repo_name
stringlengths
7
81
path
stringlengths
6
242
copies
stringclasses
53 values
size
stringlengths
2
6
content
stringlengths
73
737k
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
5.44
99.8
line_max
int64
15
977
alpha_frac
float64
0.3
0.91
ratio
float64
2
9.93
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
abigpotostew/easypolitics
db/src/main/kotlin/bz/stewart/bracken/db/bill/data/Bill.kt
1
5497
package bz.stewart.bracken.db.bill.data import bz.stewart.bracken.db.bill.data.parse.DbDateSerializer import bz.stewart.bracken.db.bill.data.parse.FlexibleDateParser import bz.stewart.bracken.db.database.DbItem import bz.stewart.bracken.shared.DateUtils import bz.stewart.bracken.shared.data.BillType import bz.stewart.bracken.shared.data.EnactedAs import com.fasterxml.jackson.annotation.JsonIgnore import com.fasterxml.jackson.annotation.JsonInclude import com.fasterxml.jackson.annotation.JsonProperty import com.fasterxml.jackson.databind.annotation.JsonDeserialize import com.fasterxml.jackson.databind.annotation.JsonSerialize import org.bson.types.ObjectId import java.util.Arrays import java.util.Date /** * Bill that is read from congress data and stored in database * Created by stew on 3/6/17. */ @JsonInclude(JsonInclude.Include.NON_NULL) data class Bill( val _id: org.bson.types.ObjectId? = null, val bill_id: String = "", //[bill_type][number]-[congress] @JsonProperty("actions") val actionsArr: Array<Action> = emptyArray(), @JsonDeserialize(using = BillTypeDeserializer::class) @JsonSerialize(using = BillTypeSerializer::class) val bill_type: BillType = BillType.NONE, val by_request: String = "", val committee_reports: Array<String>? = null, //ignore, this is not documented @JsonProperty("congress") val congressNum: Int = -1, @JsonProperty("cosponsors") val cosponsorsArr: Array<Sponsor> = emptyArray(), val enacted_as: EnactedAs? = null, @JsonProperty("history") val billHistory: BillHistory = BillHistory(), @JsonDeserialize(using = FlexibleDateParser::class) @JsonSerialize(using = DbDateSerializer::class) val introduced_at: Date = DateUtils.defaultDate(), @JsonProperty("number") val billNumber: String = "", @JsonProperty("committees") @JsonIgnore val committeesArr: Array<Any> = emptyArray(), val official_title: String = "", val popular_title: String? = null, val related_bills: Array<RelatedBill> = emptyArray(), val short_title: String? = null, @JsonProperty("sponsor") val billSponsor: Sponsor = Sponsor(), @JsonProperty("status") val currentStatus: String = "", @JsonDeserialize(using = FlexibleDateParser::class) @JsonSerialize(using = DbDateSerializer::class) val status_at: Date = DateUtils.defaultDate(), @JsonProperty("subjects") val subjectsArr: Array<String> = emptyArray(), val subjects_top_term: String? = null, //top descriptor tag for this bill @JsonProperty("summary") val billSummary: Summary? = null, @JsonProperty("titles") val titlesArr: Array<Title> = emptyArray(), @JsonDeserialize(using = FlexibleDateParser::class) @JsonSerialize(using = DbDateSerializer::class) val updated_at: Date = DateUtils.defaultDate(), @JsonProperty("url") val urlBill: String = "", var denormalizedAllText: Array<String> = emptyArray() ) : DbItem { @JsonDeserialize(using = FlexibleDateParser::class) @JsonSerialize(using = DbDateSerializer::class) private var lastModifiedDate: Date? = null//DateUtils.parseModifiedOrUpdatedStrings (lastModifiedString, updated_at) ?: DateUtils.defaultDate() var amendments: Any? get() = null @JsonIgnore set(value) {} override fun getDbId(): ObjectId? { return this._id } override fun setLastModified(lastMod: Date?) { lastModifiedDate = lastMod } override fun getLastModified(): Date? { return lastModifiedDate } override fun <T : DbItem> equalLessId(other: T): Boolean { if (this === other) return true if (other::class != this::class) return false if (this.getDbId() == other.getDbId()) return true other as Bill if (bill_id != other.bill_id) return false if (!Arrays.equals(actionsArr, other.actionsArr)) return false if (bill_type != other.bill_type) return false if (by_request != other.by_request) return false if (!Arrays.equals(committee_reports, other.committee_reports)) return false if (congressNum != other.congressNum) return false if (!Arrays.equals(cosponsorsArr, other.cosponsorsArr)) return false if (enacted_as != other.enacted_as) return false if (billHistory != other.billHistory) return false if (introduced_at != other.introduced_at) return false if (billNumber != other.billNumber) return false if (!Arrays.equals(committeesArr, other.committeesArr)) return false if (official_title != other.official_title) return false if (popular_title != other.popular_title) return false if (!Arrays.equals(related_bills, other.related_bills)) return false if (short_title != other.short_title) return false if (billSponsor != other.billSponsor) return false if (currentStatus != other.currentStatus) return false if (status_at != other.status_at) return false if (!Arrays.equals(subjectsArr, other.subjectsArr)) return false if (subjects_top_term != other.subjects_top_term) return false if (billSummary != other.billSummary) return false if (!Arrays.equals(titlesArr, other.titlesArr)) return false if (updated_at != other.updated_at) return false if (urlBill != other.urlBill) return false if (lastModifiedDate != other.lastModifiedDate) return false return true } }
apache-2.0
9340a1407e368f7ecd09450285b92423
34.934641
147
0.696198
4.108371
false
false
false
false
abigpotostew/easypolitics
ui-app/src/main/kotlin/bz/stew/bracken/ui/Main.kt
1
1957
package bz.stew.bracken.ui import bz.stew.bracken.ui.api.BrowseRuntime import bz.stew.bracken.ui.api.SingleBillRuntime import bz.stew.bracken.ui.context.ClientPageContext import bz.stew.bracken.ui.context.PageContext import bz.stew.bracken.ui.service.RequestCallback import bz.stew.bracken.ui.service.ServerRequestDispatcher import bz.stew.bracken.ui.util.RouteMatch import bz.stew.bracken.ui.util.RouteMatch.pathVariableMap import bz.stewart.bracken.shared.web.AppServices import kotlin.browser.window /** * Created by stew on 1/23/17. */ fun main(args: Array<String>) { console.log("Hello from easypolitics ui") ServerRequestDispatcher().sendRequest("/serviceurl", object : RequestCallback() { override fun onLoad(response: String) { routeAndExecute(response) } override fun onError() { console.log("Error retrieving the service url :(") } }) } private fun routeAndExecute(restServiceUrl:String){ try { val windowPath = window.location.pathname val service = RouteMatch.matchRoute(windowPath) if (service != null) { val pageContext = ClientPageContext(restServiceUrl, service, windowPath) executeService(pageContext) } } catch (e: Exception) { console.log(e) } } private fun executeService(pageContext: PageContext) { val pathVariables = pathVariableMap(pageContext.windowPath, pageContext.service) when (pageContext.service) { AppServices.RESPOND -> console.log("Respond: " + pathVariables["id"]) AppServices.SINGLE_BILL -> SingleBillRuntime(pathVariables["id"]!!).execute(pageContext) AppServices.BROWSE_BILL -> BrowseRuntime().execute(pageContext) AppServices.SERVICE_URL -> console.error("Error UI can't resolve the current page service from the URL.") else -> console.log("Stew needs to implement ui runtime for service ${pageContext.service}") } }
apache-2.0
8701591065fcee780666811395c83727
37.392157
113
0.711804
4.111345
false
false
false
false
Maccimo/intellij-community
platform/vcs-impl/src/com/intellij/vcs/commit/NonModalCommitWorkflow.kt
1
4897
// Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.vcs.commit import com.intellij.openapi.diagnostic.logger import com.intellij.openapi.progress.ProcessCanceledException import com.intellij.openapi.progress.ProgressIndicator import com.intellij.openapi.project.DumbService.isDumb import com.intellij.openapi.project.DumbService.isDumbAware import com.intellij.openapi.project.Project import com.intellij.openapi.vcs.VcsBundle import com.intellij.openapi.vcs.changes.CommitExecutor import com.intellij.openapi.vcs.checkin.CheckinHandler import com.intellij.openapi.vcs.checkin.CheckinMetaHandler import com.intellij.openapi.vcs.checkin.CommitCheck import com.intellij.openapi.vcs.checkin.CommitProblem import kotlinx.coroutines.suspendCancellableCoroutine import kotlin.coroutines.resume private val LOG = logger<NonModalCommitWorkflow>() abstract class NonModalCommitWorkflow(project: Project) : AbstractCommitWorkflow(project) { override fun runBeforeCommitHandler(handler: CheckinHandler, executor: CommitExecutor?): CheckinHandler.ReturnResult { if (!handler.acceptExecutor(executor)) return CheckinHandler.ReturnResult.COMMIT LOG.debug("CheckinHandler.beforeCheckin: $handler") if (handler is CommitCheck<*>) { if (!handler.isEnabled()) return CheckinHandler.ReturnResult.COMMIT.also { LOG.debug("Commit check disabled $handler") } if (isDumb(project) && !isDumbAware(handler)) return CheckinHandler.ReturnResult.COMMIT.also { LOG.debug("Skipped commit check in dumb mode $handler") } } return handler.beforeCheckin(executor, commitContext.additionalDataConsumer) } suspend fun executeDefault(checker: suspend () -> CheckinHandler.ReturnResult) { var result = CheckinHandler.ReturnResult.CANCEL try { result = checkCommit(checker) processExecuteDefaultChecksResult(result) } finally { if (result != CheckinHandler.ReturnResult.COMMIT) endExecution() } } private suspend fun checkCommit(checker: suspend () -> CheckinHandler.ReturnResult): CheckinHandler.ReturnResult { var result = CheckinHandler.ReturnResult.CANCEL fireBeforeCommitChecksStarted() try { result = checker() } finally { fireBeforeCommitChecksEnded(true, result) } return result } suspend fun runMetaHandlers(metaHandlers: List<CheckinMetaHandler>, commitProgressUi: CommitProgressUi, indicator: ProgressIndicator) { // reversed to have the same order as when wrapping meta handlers into each other for (metaHandler in metaHandlers.reversed()) { if (metaHandler is CommitCheck<*>) { runCommitCheck(metaHandler, commitProgressUi, indicator) } else { suspendCancellableCoroutine<Unit> { continuation -> val handlerCall = wrapWithCommitMetaHandler(metaHandler) { continuation.resume(Unit) } handlerCall.run() } } } } suspend fun runCommitChecks(commitChecks: List<CommitCheck<*>>, commitProgressUi: CommitProgressUi, indicator: ProgressIndicator): Boolean { for (commitCheck in commitChecks) { val success = runCommitCheck(commitCheck, commitProgressUi, indicator) if (!success) return false } return true } /** * @return true if there are no errors and commit shall proceed */ private suspend fun <P : CommitProblem> runCommitCheck(commitCheck: CommitCheck<P>, commitProgressUi: CommitProgressUi, indicator: ProgressIndicator): Boolean { if (!commitCheck.isEnabled()) return true.also { LOG.debug("Commit check disabled $commitCheck") } if (isDumb(project) && !isDumbAware(commitCheck)) return true.also { LOG.debug("Skipped commit check in dumb mode $commitCheck") } LOG.debug("Running commit check $commitCheck") indicator.checkCanceled() indicator.text = "" indicator.text2 = "" try { val problem = commitCheck.runCheck(indicator) problem?.let { commitProgressUi.addCommitCheckFailure(it.text) { commitCheck.showDetails(it) } } return problem == null } catch (e: Throwable) { // Do not report error on cancellation // DO report error if someone threw PCE for no reason, ex: IDEA-234006 if (e is ProcessCanceledException && indicator.isCanceled) throw e LOG.warn(Throwable(e)) val err = e.message val message = when { err.isNullOrBlank() -> VcsBundle.message("before.checkin.error.unknown") else -> VcsBundle.message("before.checkin.error.unknown.details", err) } commitProgressUi.addCommitCheckFailure(message, null) return false } } }
apache-2.0
bbc7f082c298f3641f09a2908ba958bf
39.147541
140
0.710435
4.901902
false
false
false
false
duncte123/SkyBot
src/main/kotlin/ml/duncte123/skybot/commands/mod/WarningsCommand.kt
1
2475
/* * Skybot, a multipurpose discord bot * Copyright (C) 2017 Duncan "duncte123" Sterken & Ramid "ramidzkh" Khan & Maurice R S "Sanduhr32" * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package ml.duncte123.skybot.commands.mod import me.duncte123.botcommons.messaging.EmbedUtils import me.duncte123.botcommons.messaging.MessageUtils.sendEmbed import me.duncte123.botcommons.messaging.MessageUtils.sendMsg import ml.duncte123.skybot.commands.guild.mod.ModBaseCommand import ml.duncte123.skybot.objects.command.CommandContext import net.dv8tion.jda.api.Permission class WarningsCommand : ModBaseCommand() { init { this.requiresArgs = true this.name = "warnings" this.help = "Shows the active warnings that a member has" this.usage = "<@user>" this.userPermissions = arrayOf(Permission.KICK_MEMBERS) } override fun execute(ctx: CommandContext) { val mentioned = ctx.getMentionedArg(0) val db = ctx.databaseAdapter if (mentioned.isEmpty()) { this.sendUsageInstructions(ctx) return } val member = mentioned[0] db.getWarningsForUser(member.idLong, ctx.guild.idLong) { warnings -> if (warnings.isEmpty()) { sendMsg(ctx, "This member has no active warnings") return@getWarningsForUser } val out = buildString { warnings.forEach { val mod = ctx.jda.getUserById(it.modId) val modName = mod?.asTag ?: "Unknown#0000" val reason = if (it.reason.isNotBlank()) it.reason else "None" appendLine("`[${it.rawDate}]` Reason: _${reason}_ by $modName") } } sendEmbed(ctx, EmbedUtils.embedMessage(out)) } } }
agpl-3.0
48a9a214c848407e277617b60cd11e5f
34.357143
104
0.654141
4.326923
false
false
false
false
mdaniel/intellij-community
plugins/gradle/testSources/org/jetbrains/plugins/gradle/testFramework/fixtures/impl/FileTestFixtureImpl.kt
1
8557
// 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.plugins.gradle.testFramework.fixtures.impl import com.intellij.openapi.Disposable import com.intellij.openapi.application.PathManager import com.intellij.openapi.externalSystem.autoimport.changes.vfs.VirtualFileChangesListener import com.intellij.openapi.externalSystem.autoimport.changes.vfs.VirtualFileChangesListener.Companion.installBulkVirtualFileListener import com.intellij.openapi.externalSystem.util.* import com.intellij.openapi.util.Disposer import com.intellij.openapi.util.JDOMUtil import com.intellij.openapi.vfs.LocalFileSystem import com.intellij.openapi.vfs.VfsUtil import com.intellij.openapi.vfs.VirtualFile import com.intellij.openapi.vfs.newvfs.events.VFileEvent import com.intellij.openapi.vfs.newvfs.impl.VfsRootAccess import com.intellij.testFramework.common.runAll import com.intellij.util.throwIfNotEmpty import com.intellij.util.xmlb.XmlSerializer import org.jetbrains.plugins.gradle.testFramework.fixtures.FileTestFixture import org.jetbrains.plugins.gradle.testFramework.util.onFailureCatching import org.jetbrains.plugins.gradle.testFramework.util.withSuppressedErrors import java.nio.file.Path import java.util.* internal class FileTestFixtureImpl( private val relativePath: String, private val configure: FileTestFixture.Builder.() -> Unit ) : FileTestFixture { private var isInitialized: Boolean = false private var isSuppressedErrors: Boolean = false private lateinit var errors: MutableList<Throwable> private lateinit var snapshots: MutableMap<Path, Optional<String>> private lateinit var testRootDisposable: Disposable private lateinit var fixtureRoot: VirtualFile private lateinit var fixtureStateFile: VirtualFile override val root: VirtualFile get() = fixtureRoot override fun setUp() { isInitialized = false isSuppressedErrors = false errors = ArrayList() snapshots = HashMap() testRootDisposable = Disposer.newDisposable() fixtureRoot = createFixtureRoot(relativePath) fixtureStateFile = createFixtureStateFile() installFixtureFilesWatcher() withSuppressedErrors { repairFixtureCaches() dumpFixtureState() } withSuppressedErrors { runCatching { configureFixtureCaches() } .onFailureCatching { invalidateFixtureCaches() } .getOrThrow() root.refreshAndWait() } isInitialized = true dumpFixtureState() } override fun tearDown() { runAll( { rollbackAll() }, { throwIfNotEmpty(getErrors()) }, { Disposer.dispose(testRootDisposable) } ) } private fun createFixtureRoot(relativePath: String): VirtualFile { val fileSystem = LocalFileSystem.getInstance() val systemPath = Path.of(PathManager.getSystemPath()) val systemDirectory = fileSystem.findOrCreateDirectory(systemPath) val fixtureRoot = "FileTestFixture/$relativePath" VfsRootAccess.allowRootAccess(testRootDisposable, systemDirectory.path + "/$fixtureRoot") return runWriteActionAndGet { systemDirectory.findOrCreateDirectory(fixtureRoot) } } private fun createFixtureStateFile(): VirtualFile { return runWriteActionAndGet { root.findOrCreateFile("_FileTestFixture.xml") } } private fun repairFixtureCaches() { val state = readFixtureState() val isInitialized = state.isInitialized ?: false val isSuppressedErrors = state.isSuppressedErrors ?: false val errors = state.errors ?: emptyList() val snapshots = state.snapshots ?: emptyMap() if (!isInitialized || isSuppressedErrors || errors.isNotEmpty()) { invalidateFixtureCaches() } else { for ((path, text) in snapshots) { revertFile(path, text) } } } private fun invalidateFixtureCaches() { runWriteActionAndWait { root.deleteChildren { it != fixtureStateFile } } } private fun dumpFixtureState() { val errors = errors.map { it.message ?: it.toString() } val snapshots = snapshots.entries.associate { (k, v) -> root.getRelativePath(k) to v.orElse(null) } writeFixtureState(State(isInitialized, isSuppressedErrors, errors, snapshots)) } private fun readFixtureState(): State { return runCatching { runReadAction { val element = JDOMUtil.load(fixtureStateFile.toNioPath()) XmlSerializer.deserialize(element, State::class.java) } }.getOrElse { State() } } private fun writeFixtureState(state: State) { runWriteActionAndWait { val element = XmlSerializer.serialize(state) JDOMUtil.write(element, fixtureStateFile.toNioPath()) } } private fun configureFixtureCaches() { val builder = Builder() builder.configure() if (!areContentsEqual(builder.files)) { invalidateFixtureCaches() createFiles(builder.files) builder.builders.forEach { it(root) } } } private fun areContentsEqual(files: Map<String, String>): Boolean { for ((path, expectedContent) in files) { val content = loadText(path) if (expectedContent != content) { return false } } return true } private fun createFiles(files: Map<String, String>) { runWriteActionAndWait { for ((path, content) in files) { val file = root.createFile(path) file.text = content } } } override fun isModified(): Boolean { return snapshots.isNotEmpty() } override fun hasErrors(): Boolean { return getErrors().isNotEmpty() } private fun getErrors(): List<Throwable> { root.refreshAndWait() return errors } override fun snapshot(relativePath: String) { snapshot(root.getAbsoluteNioPath(relativePath)) } private fun snapshot(path: Path) { if (path in snapshots) return val text = loadText(path) snapshots[path] = Optional.ofNullable(text) dumpFixtureState() } override fun rollbackAll() { for (path in snapshots.keys.toSet()) { rollback(path) } } override fun rollback(relativePath: String) { rollback(root.getAbsoluteNioPath(relativePath)) } private fun rollback(path: Path) { val text = requireNotNull(snapshots[path]) { "Cannot find snapshot for $path" } revertFile(path, text.orElse(null)) snapshots.remove(path) dumpFixtureState() } private fun revertFile(relativePath: String, text: String?) { revertFile(root.getAbsoluteNioPath(relativePath), text) } private fun revertFile(path: Path, text: String?) { runWriteActionAndWait { if (text != null) { root.fileSystem.findOrCreateFile(path) .also { it.text = text } } else { root.fileSystem.deleteFileOrDirectory(path) } } } private fun loadText(relativePath: String): String? { return loadText(root.getAbsoluteNioPath(relativePath)) } private fun loadText(path: Path): String? { return runReadAction { root.fileSystem.findFile(path)?.text } } override fun suppressErrors(isSuppressedErrors: Boolean) { this.isSuppressedErrors = isSuppressedErrors dumpFixtureState() } override fun addIllegalOperationError(message: String) { if (!isSuppressedErrors) { errors.add(Exception(message)) dumpFixtureState() } } private fun installFixtureFilesWatcher() { val listener = object : VirtualFileChangesListener { override fun isProcessRecursively(): Boolean = true override fun isRelevant(file: VirtualFile, event: VFileEvent): Boolean { return !file.isDirectory && file != fixtureStateFile && VfsUtil.isAncestor(root, file, false) && file.toNioPath() !in snapshots } override fun updateFile(file: VirtualFile, event: VFileEvent) { addIllegalOperationError("Unexpected project modification $event") } } installBulkVirtualFileListener(listener, testRootDisposable) } private class Builder : FileTestFixture.Builder { val files = HashMap<String, String>() val builders = ArrayList<(VirtualFile) -> Unit>() override fun withFile(relativePath: String, content: String) { files[relativePath] = content } override fun withFiles(action: (VirtualFile) -> Unit) { builders.add(action) } } private data class State( var isInitialized: Boolean? = null, var isSuppressedErrors: Boolean? = null, var errors: List<String>? = null, var snapshots: Map<String, String?>? = null ) }
apache-2.0
96bbece211d06a3bdb3b66653cda7d19
29.02807
133
0.709478
4.823563
false
true
false
false
ingokegel/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/editor/wordSelection/KotlinClassMemberSelectioner.kt
4
1507
// 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.editor.wordSelection import com.intellij.codeInsight.editorActions.ExtendWordSelectionHandlerBase import com.intellij.openapi.editor.Editor import com.intellij.openapi.util.TextRange import com.intellij.psi.PsiElement import org.jetbrains.kotlin.psi.KtClassBody import org.jetbrains.kotlin.psi.psiUtil.getNextSiblingIgnoringWhitespace import org.jetbrains.kotlin.psi.psiUtil.getPrevSiblingIgnoringWhitespace class KotlinClassMemberSelectioner : ExtendWordSelectionHandlerBase() { override fun canSelect(e: PsiElement): Boolean { return e.parent is KtClassBody } override fun select(e: PsiElement, editorText: CharSequence, cursorOffset: Int, editor: Editor): List<TextRange>? { val parent = e.parent val firstChild = parent.firstChild ?: return null val lastChild = parent.lastChild ?: return null val startElement = firstChild.getNextSiblingIgnoringWhitespace() ?: firstChild val endElement = lastChild.getPrevSiblingIgnoringWhitespace() ?: lastChild val startOffset = startElement.textRange.startOffset val endOffset = endElement.textRange.endOffset if (startOffset >= endOffset) return null val textRange = TextRange(startOffset, endOffset) return expandToWholeLinesWithBlanks(editorText, textRange) } }
apache-2.0
f2a92652d5a63db10b0ab22ff67c612e
49.266667
158
0.773723
5.143345
false
false
false
false
WhisperSystems/Signal-Android
app/src/main/java/org/thoughtcrime/securesms/components/settings/app/privacy/expire/ExpireTimerSettingsRepository.kt
1
2368
package org.thoughtcrime.securesms.components.settings.app.privacy.expire import android.content.Context import androidx.annotation.WorkerThread import org.signal.core.util.concurrent.SignalExecutors import org.signal.core.util.logging.Log import org.thoughtcrime.securesms.database.DatabaseFactory import org.thoughtcrime.securesms.database.ThreadDatabase import org.thoughtcrime.securesms.groups.GroupChangeException import org.thoughtcrime.securesms.groups.GroupManager import org.thoughtcrime.securesms.mms.OutgoingExpirationUpdateMessage import org.thoughtcrime.securesms.recipients.Recipient import org.thoughtcrime.securesms.recipients.RecipientId import org.thoughtcrime.securesms.sms.MessageSender import java.io.IOException private val TAG: String = Log.tag(ExpireTimerSettingsRepository::class.java) /** * Provide operations to set expire timer for individuals and groups. */ class ExpireTimerSettingsRepository(val context: Context) { fun setExpiration(recipientId: RecipientId, newExpirationTime: Int, consumer: (Result<Int>) -> Unit) { SignalExecutors.BOUNDED.execute { val recipient = Recipient.resolved(recipientId) if (recipient.groupId.isPresent && recipient.groupId.get().isPush) { try { GroupManager.updateGroupTimer(context, recipient.groupId.get().requirePush(), newExpirationTime) consumer.invoke(Result.success(newExpirationTime)) } catch (e: GroupChangeException) { Log.w(TAG, e) consumer.invoke(Result.failure(e)) } catch (e: IOException) { Log.w(TAG, e) consumer.invoke(Result.failure(e)) } } else { DatabaseFactory.getRecipientDatabase(context).setExpireMessages(recipientId, newExpirationTime) val outgoingMessage = OutgoingExpirationUpdateMessage(Recipient.resolved(recipientId), System.currentTimeMillis(), newExpirationTime * 1000L) MessageSender.send(context, outgoingMessage, getThreadId(recipientId), false, null, null) consumer.invoke(Result.success(newExpirationTime)) } } } @WorkerThread private fun getThreadId(recipientId: RecipientId): Long { val threadDatabase: ThreadDatabase = DatabaseFactory.getThreadDatabase(context) val recipient: Recipient = Recipient.resolved(recipientId) return threadDatabase.getOrCreateThreadIdFor(recipient) } }
gpl-3.0
317553ef66ca09d1a4fc5a0d34da22a7
43.679245
149
0.770693
4.679842
false
false
false
false
Mystery00/JanYoShare
app/src/main/java/com/janyo/janyoshare/service/ReceiveFileService.kt
1
5331
package com.janyo.janyoshare.service import android.app.Service import android.content.Intent import android.os.IBinder import android.os.Message import com.janyo.janyoshare.R import com.janyo.janyoshare.classes.TransferHeader import com.janyo.janyoshare.handler.ErrorHandler import com.janyo.janyoshare.handler.TransferHelperHandler import com.janyo.janyoshare.util.FileTransferHelper import com.janyo.janyoshare.util.JYFileUtil import com.janyo.janyoshare.util.SocketUtil import com.janyo.janyoshare.util.TransferFileNotification import vip.mystery0.tools.logs.Logs import java.util.concurrent.Executors class ReceiveFileService : Service() { private val TAG = "ReceiveFileService" private lateinit var errorHandler: ErrorHandler private var transferHelperHandler: TransferHelperHandler? = null private val socketUtil = SocketUtil() private val singleHeaderThreadPool = Executors.newSingleThreadExecutor() private val singleFileThreadPool = Executors.newSingleThreadExecutor() private val singleThreadPool = Executors.newSingleThreadExecutor() override fun onCreate() { Logs.i(TAG, "onCreate: 创建接收文件服务") errorHandler = ErrorHandler(this) singleThreadPool.execute { while (true) { if (FileTransferHelper.getInstance().transferHelperHandler != null) { transferHelperHandler = FileTransferHelper.getInstance().transferHelperHandler break } Thread.sleep(200) } } } override fun onBind(intent: Intent): IBinder? { return null } override fun onStartCommand(intent: Intent, flags: Int, startId: Int): Int { singleHeaderThreadPool.execute { socketUtil.createSocketConnection(FileTransferHelper.getInstance().ip, FileTransferHelper.getInstance().transferPort) //获取请求头 val obj = socketUtil.receiveObject() if (obj != null) { val transferHeader = obj as TransferHeader FileTransferHelper.getInstance().fileList.clear() FileTransferHelper.getInstance().fileList.addAll(transferHeader.list) FileTransferHelper.getInstance().transferHelperHandler!!.list.clear() FileTransferHelper.getInstance().transferHelperHandler!!.list.addAll(transferHeader.list) Logs.i(TAG, "onCreate: 获取请求头成功") Logs.i(TAG, "onStartCommand: " + transferHeader.list.size) val updateListMessage = Message() updateListMessage.what = TransferHelperHandler.UPDATE_UI transferHelperHandler!!.sendMessage(updateListMessage) FileTransferHelper.getInstance().fileList.forEachIndexed { index, transferFile -> singleFileThreadPool.execute { Logs.i(TAG, "onStartCommand: " + transferFile.fileName) val path = JYFileUtil.getSaveFilePath(transferFile.fileName!!, getString(R.string.app_name)) socketUtil.receiveFile(transferFile.fileSize, path, object : SocketUtil.FileTransferListener { override fun onStart() { Logs.i(TAG, "onStart: ") FileTransferHelper.getInstance().currentFileIndex = index transferFile.transferProgress = 0 TransferFileNotification.notify(this@ReceiveFileService, index) val message = Message() message.what = TransferHelperHandler.UPDATE_UI transferHelperHandler!!.sendMessage(message) } override fun onProgress(progress: Int) { Logs.i(TAG, "onProgress: " + progress) transferFile.transferProgress = progress TransferFileNotification.notify(this@ReceiveFileService, index) val message = Message() message.what = TransferHelperHandler.UPDATE_UI transferHelperHandler!!.sendMessage(message) } override fun onFinish() { Logs.i(TAG, "onFinish: " + transferFile.fileName) transferFile.transferProgress = 100 TransferFileNotification.done(this@ReceiveFileService, index, transferFile) val map = HashMap<String, Any>() map.put("context", this@ReceiveFileService) map.put("fileName", transferFile.fileName!!) val message = Message() message.obj = map message.what = TransferHelperHandler.UPDATE_TOAST transferHelperHandler!!.sendMessage(message) } override fun onError(code: Int, e: Exception) { Logs.e(TAG, "onError: code: " + code) e.printStackTrace() val message = Message() when (code) { 1 -> message.what = ErrorHandler.FILE_EXISTS else -> message.what = ErrorHandler.UNKNOWN_ERROR } errorHandler.sendMessage(message) } }) } Thread.sleep(1000) } singleFileThreadPool.shutdown() while (true) { if (singleFileThreadPool.isTerminated) { Logs.i(TAG, "onStartCommand: 传输完成") FileTransferHelper.getInstance().fileList .filter { it.transferProgress == 100 } .forEachIndexed { index, transferFile -> TransferFileNotification.done(this@ReceiveFileService, index, transferFile) } FileTransferHelper.getInstance().clear() stopSelf() break } Thread.sleep(500) } } else { Logs.e(TAG, "onCreate: 获取请求头失败") stopSelf() } } return super.onStartCommand(intent, flags, startId) } override fun onDestroy() { socketUtil.clientDisconnect() Logs.i(TAG, "onDestroy: ") } }
gpl-3.0
82d256df466146ee44937e7c28120a88
32.56051
120
0.709243
4.28026
false
false
false
false
GunoH/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/ReplaceArrayOfWithLiteralInspection.kt
4
3188
// 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.inspections import com.intellij.codeInspection.LocalQuickFix import com.intellij.codeInspection.ProblemDescriptor import com.intellij.codeInspection.ProblemHighlightType import com.intellij.codeInspection.ProblemsHolder import com.intellij.openapi.project.Project import com.intellij.psi.PsiElementVisitor import org.jetbrains.kotlin.idea.base.resources.KotlinBundle import org.jetbrains.kotlin.idea.intentions.isArrayOfFunction import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.getParentOfType import org.jetbrains.kotlin.idea.codeinsight.api.classic.inspections.AbstractKotlinInspection class ReplaceArrayOfWithLiteralInspection : AbstractKotlinInspection() { override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean): PsiElementVisitor = callExpressionVisitor(fun(expression) { val calleeExpression = expression.calleeExpression as? KtNameReferenceExpression ?: return when (val parent = expression.parent) { is KtValueArgument -> { if (parent.parent?.parent !is KtAnnotationEntry) return if (parent.getSpreadElement() != null && !parent.isNamed()) return } is KtParameter -> { val constructor = parent.parent?.parent as? KtPrimaryConstructor ?: return val containingClass = constructor.getContainingClassOrObject() if (!containingClass.isAnnotation()) return } else -> return } if (!expression.isArrayOfFunction()) return val calleeName = calleeExpression.getReferencedName() holder.registerProblem( calleeExpression, KotlinBundle.message("0.call.should.be.replaced.with.array.literal", calleeName), ProblemHighlightType.GENERIC_ERROR_OR_WARNING, ReplaceWithArrayLiteralFix() ) }) private class ReplaceWithArrayLiteralFix : LocalQuickFix { override fun getFamilyName() = KotlinBundle.message("replace.with.array.literal.fix.family.name") override fun applyFix(project: Project, descriptor: ProblemDescriptor) { val calleeExpression = descriptor.psiElement as KtExpression val callExpression = calleeExpression.parent as KtCallExpression val valueArgument = callExpression.getParentOfType<KtValueArgument>(false) valueArgument?.getSpreadElement()?.delete() val arguments = callExpression.valueArguments val arrayLiteral = KtPsiFactory(callExpression).buildExpression { appendFixedText("[") for ((index, argument) in arguments.withIndex()) { appendExpression(argument.getArgumentExpression()) if (index != arguments.size - 1) { appendFixedText(", ") } } appendFixedText("]") } as KtCollectionLiteralExpression callExpression.replace(arrayLiteral) } } }
apache-2.0
5d1a6d813f2362632bbb4541c99d9aff
43.277778
135
0.685696
5.881919
false
false
false
false
GunoH/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/codeInsight/surroundWith/expression/KotlinWhenSurrounder.kt
3
2245
// 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.codeInsight.surroundWith.expression import org.jetbrains.kotlin.psi.KtPsiFactory import org.jetbrains.kotlin.idea.core.surroundWith.KotlinExpressionSurrounder import org.jetbrains.kotlin.psi.KtExpression import org.jetbrains.kotlin.psi.KtWhenExpression import com.intellij.codeInsight.CodeInsightUtilBase import com.intellij.openapi.editor.Editor import com.intellij.openapi.project.Project import com.intellij.openapi.util.NlsSafe import com.intellij.openapi.util.TextRange import com.intellij.refactoring.suggested.startOffset import org.jetbrains.kotlin.idea.base.psi.replaced import org.jetbrains.kotlin.idea.quickfix.AddWhenRemainingBranchesFix class KotlinWhenSurrounder : KotlinExpressionSurrounder() { @NlsSafe override fun getTemplateDescription() = "when (expr) {}" override fun surroundExpression(project: Project, editor: Editor, expression: KtExpression): TextRange { val template = "when(a) { \nb -> {}\n else -> {}\n}" val whenExpression = (KtPsiFactory(expression).createExpression(template) as KtWhenExpression).let { it.subjectExpression?.replace(expression) expression.replaced(it) } val hasRemainingBranches = AddWhenRemainingBranchesFix.isAvailable(whenExpression) if (hasRemainingBranches) { AddWhenRemainingBranchesFix.addRemainingBranches(whenExpression) whenExpression.entries.also { it.first().delete() it.last().delete() } } CodeInsightUtilBase.forcePsiPostprocessAndRestoreElement(whenExpression) val firstEntry = whenExpression.entries.first() val offset = if (hasRemainingBranches) { firstEntry.expression?.startOffset ?: firstEntry.startOffset } else { val conditionRange = firstEntry.conditions.first().textRange editor.document.deleteString(conditionRange.startOffset, conditionRange.endOffset) conditionRange.startOffset } return TextRange(offset, offset) } }
apache-2.0
e9296a30c31ebf41b3c0f51b23f49fca
44.816327
158
0.735857
5.102273
false
false
false
false
GunoH/intellij-community
platform/wsl-impl/src/com/intellij/execution/wsl/sync/LinuxFileStorage.kt
2
7225
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.execution.wsl.sync import com.intellij.execution.configurations.GeneralCommandLine import com.intellij.execution.processTools.getBareExecutionResult import com.intellij.execution.processTools.getResultStdoutStr import com.intellij.execution.wsl.* import com.intellij.openapi.diagnostic.Logger import com.intellij.util.TimeoutUtil import com.intellij.util.io.delete import kotlinx.coroutines.runBlocking import java.io.InputStream import java.nio.ByteBuffer import java.nio.ByteOrder import java.util.concurrent.TimeUnit import kotlin.io.path.writeText private val LOGGER = Logger.getInstance(LinuxFileStorage::class.java) class LinuxFileStorage(dir: LinuxFilePath, distro: AbstractWslDistribution, onlyExtensions: Array<String>) : FileStorage<LinuxFilePath, WindowsFilePath>(dir.trimEnd('/') + '/', distro, onlyExtensions) { // Linux side only works with UTF of 7-bit ASCII which is also supported by UTF and WSL doesn't support other charsets private val CHARSET = Charsets.UTF_8 private val FILE_SEPARATOR = CHARSET.encode(":").get() private val LINK_SEPARATOR = CHARSET.encode(";").get() override fun createSymLinks(links: Map<FilePathRelativeToDir, FilePathRelativeToDir>) { val script = createTmpWinFile(distro) script.first.writeText(links .map { it.key.escapedWithDir to it.value.escapedWithDir } .joinToString("\n") // No need to create link if parent dir doesn't exist { "[ -e $(dirname ${it.first}) ] && ln -s ${it.second} ${it.first}" }) runBlocking { distro.createProcess("sh", script.second).getBareExecutionResult() } script.first.delete() } override fun getHashesAndLinks(skipHashCalculation: Boolean): Pair<List<WslHashRecord>, Map<FilePathRelativeToDir, FilePathRelativeToDir>> { val hashes = ArrayList<WslHashRecord>(AVG_NUM_FILES) val links = HashMap<FilePathRelativeToDir, FilePathRelativeToDir>(AVG_NUM_FILES) val time = TimeoutUtil.measureExecutionTime<Throwable> { val tool = distro.getTool("wslhash", dir, if (skipHashCalculation) "no_hash" else "hash", *onlyExtensions) val process = tool.createProcess() process.inputStream.use { val hashesAndLinks = getHashesInternal(it) hashes += hashesAndLinks.first links += hashesAndLinks.second } runBlocking { process.getResultStdoutStr() } } LOGGER.info("Linux files calculated in $time") return Pair(hashes, links) } override fun createTempFile(): String = distro.runCommand("mktemp", "-u").getOrThrow() override fun removeLinks(vararg linksToRemove: FilePathRelativeToDir) { this.removeFiles(linksToRemove.asList()) } override fun isEmpty(): Boolean { val options = WSLCommandLineOptions().apply { addInitCommand("[ -e ${escapePath(dir)} ]") } val process = distro.patchCommandLine(GeneralCommandLine("ls", "-A", dir), null, options).createProcess() if (!process.waitFor(5, TimeUnit.SECONDS)) throw Exception("Process didn't finish: WSL frozen?") if (process.exitValue() == 0) { // Folder exists, lets check if empty return process.inputStream.read() == -1 } else { // Folder doesn't exist val error = process.errorStream.readAllBytes().decodeToString() if (error.isEmpty()) return true // Doesn't exist, but still empty throw Exception("Error checking folder: $error") } } override fun removeFiles(filesToRemove: Collection<FilePathRelativeToDir>) { LOGGER.info("Removing files") runCommands(*filesToRemove.map { arrayOf("rm", it.escapedWithDir) }.toTypedArray()) } override fun removeTempFile(file: LinuxFilePath) { distro.runCommand("rm", file) } override fun tarAndCopyTo(files: Collection<FilePathRelativeToDir>, destTar: WindowsFilePath) { val linuxTarFile = createTempFile() val listFile = createTmpWinFile(distro) listFile.first.writeText(files.joinToString("\n")) LOGGER.info("Creating tar") // See tar(1) distro.runCommand("tar", "cf", linuxTarFile, "-m", "-h", "-O", "-C", dir, "-T", listFile.second) listFile.first.delete() LOGGER.info("Copying tar") distro.runCommand("cp", linuxTarFile, distro.getWslPath(destTar)) distro.runCommand("rm", linuxTarFile) } override fun unTar(tarFile: LinuxFilePath) { LOGGER.info("Unpacking") distro.runCommand("mkdir", "-p", dir) distro.runCommand("tar", "xf", tarFile, "-C", dir) } /** * Read `wslhash` stdout and return map of [file->hash] */ private fun getHashesInternal(toolStdout: InputStream): Pair<List<WslHashRecord>, Map<FilePathRelativeToDir, FilePathRelativeToDir>> { val hashes = ArrayList<WslHashRecord>(AVG_NUM_FILES) val links = HashMap<FilePathRelativeToDir, FilePathRelativeToDir>(AVG_NUM_FILES) val fileOutput = ByteBuffer.wrap(toolStdout.readAllBytes()).order(ByteOrder.LITTLE_ENDIAN) // See wslhash.c: format is the following: [file_path]:[hash]. // Hash is little-endian 8 byte (64 bit) integer // or [file_path];[link_len][link] where link_len is 4 byte signed int var fileStarted = 0 val outputLimit = fileOutput.limit() while (fileOutput.position() < outputLimit) { when (fileOutput.get()) { FILE_SEPARATOR -> { val hash = fileOutput.long val prevPos = fileOutput.position() // 9 = 8 bytes long + separator val name = CHARSET.decode(fileOutput.limit(prevPos - 9).position(fileStarted)).toString() fileOutput.limit(outputLimit).position(prevPos) hashes += WslHashRecord(FilePathRelativeToDir(name), hash) fileStarted = prevPos } LINK_SEPARATOR -> { val length = fileOutput.int val prevPos = fileOutput.position() // 5 = 4 bytes int + separator val file = CHARSET.decode(fileOutput.limit(prevPos - 5).position(fileStarted)).toString() val link = CHARSET.decode(fileOutput.limit(prevPos + length).position(prevPos)).toString() fileOutput.limit(outputLimit).position(prevPos + length) if (link.startsWith(dir)) { links[FilePathRelativeToDir((file))] = FilePathRelativeToDir(link.substring(dir.length)) } fileStarted = prevPos + length } } } return Pair(hashes, links) } private val FilePathRelativeToDir.escapedWithDir: String get() = escapePath(dir + asUnixPath) private fun escapePath(path: LinuxFilePath) = GeneralCommandLine(path).commandLineString // it is cheaper to run 1-2 commands directly, but long list of command should run as script private fun runCommands(vararg commands: Array<String>) { if (commands.count() < 3) { for (command in commands) { distro.runCommand(*command) } } else { val script = createTmpWinFile(distro) script.first.writeText(commands.joinToString("\n") { it.joinToString(" ") }) distro.runCommand("sh", script.second) script.first.delete() } } }
apache-2.0
a5d017fe7ae6bacc449509d36e83a9f9
40.522989
142
0.689827
4.339339
false
false
false
false
GunoH/intellij-community
plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/resolve/CategoryMemberContributor.kt
7
3248
// Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.plugins.groovy.lang.resolve import com.intellij.openapi.util.NlsSafe import com.intellij.psi.* import com.intellij.psi.scope.ElementClassHint import com.intellij.psi.scope.PsiScopeProcessor import com.intellij.psi.util.PsiTypesUtil.getPsiClass import com.intellij.psi.util.PsiUtil.substituteTypeParameter import com.intellij.psi.util.parents import org.jetbrains.plugins.groovy.dgm.GdkMethodHolder.getHolderForClass import org.jetbrains.plugins.groovy.lang.psi.api.GrFunctionalExpression import org.jetbrains.plugins.groovy.lang.psi.api.statements.arguments.GrArgumentList import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrMethodCall import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrReferenceExpression import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.members.GrGdkMethod import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.members.GrMember import org.jetbrains.plugins.groovy.lang.psi.impl.GrTupleType import org.jetbrains.plugins.groovy.lang.resolve.ResolveUtil.shouldProcessMethods import org.jetbrains.plugins.groovy.lang.resolve.processors.ClassHint fun processCategoriesInScope(qualifierType: PsiType, processor: PsiScopeProcessor, place: PsiElement, state: ResolveState): Boolean { if (!shouldProcessMethods(processor.getHint(ElementClassHint.KEY))) return true for (parent in place.parents(true)) { if (parent is GrMember) break if (parent !is GrFunctionalExpression) continue val call = checkMethodCall(parent) ?: continue val categories = getCategoryClasses(call, parent) ?: continue val holders = categories.map { getHolderForClass(it, false) } val stateWithContext = state.put(ClassHint.RESOLVE_CONTEXT, call) for (category in holders) { if (!category.processMethods(processor, stateWithContext, qualifierType, place.project)) return false } } return true } private fun getCategoryClasses(call: GrMethodCall, closure: GrFunctionalExpression): List<PsiClass>? { val closures = call.closureArguments val args = call.expressionArguments if (args.isEmpty()) return null val lastArg = closure == args.last() if (!lastArg && closure != closures.singleOrNull()) return null if (call.resolveMethod() !is GrGdkMethod) return null if (args.size == 1 || args.size == 2 && lastArg) { val tupleType = args.first().type as? GrTupleType tupleType?.let { return it.componentTypes.mapNotNull { getPsiClass(substituteTypeParameter(it, CommonClassNames.JAVA_LANG_CLASS, 0, false)) } } } return args.mapNotNull { (it as? GrReferenceExpression)?.resolve() as? PsiClass } } @NlsSafe private const val USE = "use" private fun checkMethodCall(place: PsiElement): GrMethodCall? { val call = when (val context = place.context) { is GrMethodCall -> context is GrArgumentList -> context.context as? GrMethodCall else -> null } if (call == null) return null val invoked = call.invokedExpression as? GrReferenceExpression if (invoked?.referenceName != USE) return null return call }
apache-2.0
e4bf26ef12b5c1f125d1b7ffb49bd1c4
41.75
140
0.774631
4.273684
false
false
false
false
GunoH/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/AssignOperatorAmbiguityFactory.kt
1
3662
// 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.quickfix import com.intellij.codeInsight.intention.IntentionAction import com.intellij.openapi.editor.Editor import com.intellij.openapi.project.Project import org.jetbrains.kotlin.builtins.jvm.JavaToKotlinClassMapper import org.jetbrains.kotlin.diagnostics.Diagnostic import org.jetbrains.kotlin.idea.base.resources.KotlinBundle import org.jetbrains.kotlin.idea.caches.resolve.analyze import org.jetbrains.kotlin.idea.codeinsight.api.classic.quickfixes.KotlinQuickFixAction import org.jetbrains.kotlin.idea.codeinsights.impl.base.quickFix.ChangeVariableMutabilityFix import org.jetbrains.kotlin.idea.references.mainReference import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.endOffset import org.jetbrains.kotlin.resolve.calls.util.getType import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode import org.jetbrains.kotlin.types.KotlinType object AssignOperatorAmbiguityFactory : KotlinIntentionActionsFactory() { override fun doCreateActions(diagnostic: Diagnostic): List<IntentionAction> { val fixes = mutableListOf<IntentionAction>() val element = diagnostic.psiElement.parent if (element is KtBinaryExpression) { val left = element.left val right = element.right val operationText = when (element.operationToken) { KtTokens.PLUSEQ -> "plus" KtTokens.MINUSEQ -> "minus" else -> null } if (left != null && right != null && operationText != null) { val context = element.analyze(BodyResolveMode.PARTIAL) if (left.getType(context).isMutableCollection()) { val property = left.mainReference?.resolve() as? KtProperty val propertyName = property?.name if (property != null && propertyName != null && property.isLocal) { val fix = ChangeVariableMutabilityFix( property, false, KotlinBundle.message("fix.change.mutability.change.to.val", propertyName) ) fixes.add(fix) } fixes.add(ReplaceWithAssignFunctionCallFix(element, operationText)) } } } return fixes } } private fun KotlinType?.isMutableCollection(): Boolean { if (this == null) return false return JavaToKotlinClassMapper.isMutable(this) || constructor.supertypes.reversed().any { JavaToKotlinClassMapper.isMutable(it) } } private class ReplaceWithAssignFunctionCallFix( element: KtBinaryExpression, private val operationText: String ) : KotlinQuickFixAction<KtBinaryExpression>(element) { override fun getText(): String { val call = operationText + "Assign()" return KotlinBundle.message("fix.replace.with.assign.function.call", call) } override fun getFamilyName() = text override fun invoke(project: Project, editor: Editor?, file: KtFile) { val binaryExpression = element ?: return val left = binaryExpression.left ?: return val right = binaryExpression.right ?: return val replaced = binaryExpression.replace( KtPsiFactory(binaryExpression).createExpressionByPattern("$0.${operationText}Assign($1)", left, right) ) editor?.caretModel?.moveToOffset(replaced.endOffset) } }
apache-2.0
b4531e384a079f0f745258b1fc41bd6b
43.120482
158
0.683506
5.051034
false
false
false
false
marius-m/wt4
app/src/main/java/lt/markmerkk/widgets/tickets/TicketJQLGenerator.kt
1
933
package lt.markmerkk.widgets.tickets import lt.markmerkk.Const /** * Generates JQL based on provided setting details */ object TicketJQLGenerator { fun generateJQL( enabledStatuses: List<String>, onlyCurrentUser: Boolean ): String { val statusQueryPart = if (enabledStatuses.isNotEmpty()) { val statusesAsString = enabledStatuses .map { "'$it'" } .joinToString(separator = ",") "(status in ($statusesAsString))" } else { "" } val currentUserPart = if (onlyCurrentUser) { "(assignee = currentUser() OR reporter = currentUser() OR watcher = currentUser())" } else { "" } val queryParts = listOf(statusQueryPart, currentUserPart) .filter { it.isNotEmpty() } return queryParts.joinToString(separator = " AND ") } }
apache-2.0
3a61a46042f8a0d622b6ad533f1c7dbf
28.1875
95
0.562701
5.043243
false
false
false
false
cmzy/okhttp
okhttp/src/main/kotlin/okhttp3/internal/ws/MessageDeflater.kt
4
2141
/* * Copyright (C) 2020 Square, 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 okhttp3.internal.ws import java.io.Closeable import java.io.IOException import java.util.zip.Deflater import okio.Buffer import okio.ByteString import okio.ByteString.Companion.decodeHex import okio.DeflaterSink private val EMPTY_DEFLATE_BLOCK = "000000ffff".decodeHex() private const val LAST_OCTETS_COUNT_TO_REMOVE_AFTER_DEFLATION = 4 class MessageDeflater( private val noContextTakeover: Boolean ) : Closeable { private val deflatedBytes = Buffer() private val deflater = Deflater(Deflater.DEFAULT_COMPRESSION, true /* omit zlib header */) private val deflaterSink = DeflaterSink(deflatedBytes, deflater) /** Deflates [buffer] in place as described in RFC 7692 section 7.2.1. */ @Throws(IOException::class) fun deflate(buffer: Buffer) { require(deflatedBytes.size == 0L) if (noContextTakeover) { deflater.reset() } deflaterSink.write(buffer, buffer.size) deflaterSink.flush() if (deflatedBytes.endsWith(EMPTY_DEFLATE_BLOCK)) { val newSize = deflatedBytes.size - LAST_OCTETS_COUNT_TO_REMOVE_AFTER_DEFLATION deflatedBytes.readAndWriteUnsafe().use { cursor -> cursor.resizeBuffer(newSize) } } else { // Same as adding EMPTY_DEFLATE_BLOCK and then removing 4 bytes. deflatedBytes.writeByte(0x00) } buffer.write(deflatedBytes, deflatedBytes.size) } @Throws(IOException::class) override fun close() = deflaterSink.close() private fun Buffer.endsWith(suffix: ByteString): Boolean = rangeEquals(size - suffix.size, suffix) }
apache-2.0
b60cefada577bcf7119e25d6cdb7e64f
31.938462
100
0.733302
4.009363
false
false
false
false
dhis2/dhis2-android-sdk
core/src/test/java/org/hisp/dhis/android/core/event/internal/EventHandlerShould.kt
1
7723
/* * 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.event.internal import com.nhaarman.mockitokotlin2.* import org.hisp.dhis.android.core.arch.cleaners.internal.OrphanCleaner import org.hisp.dhis.android.core.arch.handlers.internal.HandleAction import org.hisp.dhis.android.core.arch.handlers.internal.Handler import org.hisp.dhis.android.core.arch.handlers.internal.IdentifiableDataHandlerParams import org.hisp.dhis.android.core.common.State import org.hisp.dhis.android.core.event.Event import org.hisp.dhis.android.core.event.EventStatus import org.hisp.dhis.android.core.note.Note import org.hisp.dhis.android.core.note.internal.NoteDHISVersionManager import org.hisp.dhis.android.core.note.internal.NoteUniquenessManager import org.hisp.dhis.android.core.relationship.Relationship import org.hisp.dhis.android.core.relationship.internal.RelationshipDHISVersionManager import org.hisp.dhis.android.core.relationship.internal.RelationshipHandler import org.hisp.dhis.android.core.relationship.internal.RelationshipItemRelatives import org.hisp.dhis.android.core.trackedentity.TrackedEntityDataValue import org.hisp.dhis.android.core.trackedentity.internal.TrackedEntityDataValueHandler import org.junit.Before import org.junit.Test import org.junit.runner.RunWith import org.junit.runners.JUnit4 @RunWith(JUnit4::class) class EventHandlerShould { private val eventStore: EventStore = mock() private val trackedEntityDataValueHandler: TrackedEntityDataValueHandler = mock() private val trackedEntityDataValue: TrackedEntityDataValue = mock() private val noteHandler: Handler<Note> = mock() private val noteUniquenessManager: NoteUniquenessManager = mock() private val note: Note = mock() private val noteVersionManager: NoteDHISVersionManager = mock() private val relationshipVersionManager: RelationshipDHISVersionManager = mock() private val relationshipItemRelatives: RelationshipItemRelatives = mock() private val relationshipHandler: RelationshipHandler = mock() private val eventBuilder: Event.Builder = mock() private val relationshipOrphanCleaner: OrphanCleaner<Event, Relationship> = mock() private val event: Event = mock() // object to test private lateinit var eventHandler: EventHandler @Before fun setUp() { whenever(event.uid()).doReturn("test_event_uid") whenever(event.notes()).doReturn(listOf(note)) whenever(event.organisationUnit()).doReturn("org_unit_uid") whenever(event.status()).doReturn(EventStatus.SCHEDULE) whenever(event.trackedEntityDataValues()).doReturn(listOf(trackedEntityDataValue)) whenever(eventStore.updateOrInsert(any())).doReturn(HandleAction.Insert) whenever(event.toBuilder()).doReturn(eventBuilder) whenever(eventBuilder.syncState(State.SYNCED)).doReturn(eventBuilder) whenever(eventBuilder.aggregatedSyncState(State.SYNCED)).doReturn(eventBuilder) whenever(eventBuilder.build()).doReturn(event) eventHandler = EventHandler( relationshipVersionManager, relationshipHandler, eventStore, trackedEntityDataValueHandler, noteHandler, noteVersionManager, noteUniquenessManager, relationshipOrphanCleaner ) } @Test fun do_nothing_when_passing_empty_list_argument() { val params = IdentifiableDataHandlerParams(hasAllAttributes = false, overwrite = false, asRelationship = false) eventHandler.handleMany(listOf(), params, relationshipItemRelatives) // verify that store is never invoked verify(eventStore, never()).deleteIfExists(any()) verify(eventStore, never()).update(any()) verify(eventStore, never()).insert(any<Event>()) verify(noteHandler, never()).handleMany(any()) } @Test fun invoke_only_delete_when_a_event_is_set_as_deleted() { whenever(event.deleted()).doReturn(true) val params = IdentifiableDataHandlerParams(hasAllAttributes = false, overwrite = false, asRelationship = false) eventHandler.handleMany(listOf(event), params, relationshipItemRelatives) // verify that delete is invoked once verify(eventStore, times(1)).deleteIfExists(event.uid()) verify(relationshipHandler, times(1)).deleteLinkedRelationships(any()) // verify that update and insert is never invoked verify(eventStore, never()).update(any()) verify(eventStore, never()).insert(any<Event>()) verify(noteHandler, never()).handleMany(any()) // verify that data value handler is never invoked verify(trackedEntityDataValueHandler, never()).handleMany(any(), any()) } @Test fun invoke_update_and_insert_when_handle_event_not_inserted() { whenever(eventStore.updateOrInsert(any())).doReturn(HandleAction.Insert) whenever(event.organisationUnit()).doReturn("org_unit_uid") whenever(event.status()).doReturn(EventStatus.SCHEDULE) val params = IdentifiableDataHandlerParams(hasAllAttributes = false, overwrite = false, asRelationship = false) eventHandler.handleMany(listOf(event), params, relationshipItemRelatives) // verify that update and insert is invoked, since we're updating before inserting verify(eventStore, times(1)).updateOrInsert(any()) verify(trackedEntityDataValueHandler, times(1)).handleMany(any(), any()) verify(noteHandler, times(1)).handleMany(any()) // verify that delete is never invoked verify(eventStore, never()).deleteIfExists(any()) verify(relationshipHandler, never()).deleteLinkedRelationships(any()) } @Test fun delete_event_data_values_if_empty_list() { whenever(event.trackedEntityDataValues()).doReturn(emptyList()) val params = IdentifiableDataHandlerParams(hasAllAttributes = false, overwrite = false, asRelationship = false) eventHandler.handleMany(listOf(event), params, relationshipItemRelatives) verify(trackedEntityDataValueHandler, times(1)).removeEventDataValues(any()) verify(trackedEntityDataValueHandler, never()).handleMany(any(), any()) } }
bsd-3-clause
7a14dd4ed27a04da261ef3480ade07d2
49.809211
119
0.749968
4.767284
false
false
false
false
android/project-replicator
code/codegen/src/main/kotlin/com/android/gradle/replicator/resgen/GeneratorDriver.kt
1
2353
package com.android.gradle.replicator.resgen import com.android.gradle.replicator.model.internal.filedata.AbstractAndroidResourceProperties import com.android.gradle.replicator.resgen.resourceModel.ResourceModel import com.android.gradle.replicator.resgen.util.ResgenConstants import com.android.gradle.replicator.resgen.util.UniqueIdGenerator import java.io.File import kotlin.random.Random class GeneratorDriver (val random: Random, private val uniqueIdGenerator: UniqueIdGenerator) { // TODO: implement other generators private fun getGenerator(random: Random, resourceType: String, constants: ResgenConstants, resourceModel: ResourceModel): ResourceGenerator? { val params = ResourceGenerationParams(random, constants, uniqueIdGenerator, resourceModel) return when(resourceType) { //"animator" -> //"anim" -> //"color" -> "drawable" -> DrawableResourceGenerator(params) "font" -> FontResourceGenerator(params) //"layout" -> //"menu" -> "mipmap" -> DrawableResourceGenerator(params) "raw" -> RawResourceGenerator(params) //"transition" -> "values" -> ValueResourceGenerator(params) //"xml" -> else -> null } } fun generateResources( outputFolder: File, resourceType: String, resourceProperties: AbstractAndroidResourceProperties, resgenConstants: ResgenConstants, resourceModel: ResourceModel) { // TODO: Generate resources based on property type (size matters, values, etc.) val generator = getGenerator(random, resourceType, resgenConstants, resourceModel) // empty qualifiers means the folder is unqualified, as in "mipmap" instead of "mipmap-hidpi" val qualifiedFolder = if (resourceProperties.qualifiers.isEmpty()) { File(outputFolder, resourceType) } else { File(outputFolder, "${resourceType}-${resourceProperties.qualifiers}") } qualifiedFolder.mkdirs() generator?.generateResource( properties = resourceProperties, outputFolder = qualifiedFolder ) ?: println("w: unsupported resource type $resourceType. Skipping.") } }
apache-2.0
86c9058399d4ca2ec9482217ac047eb5
41.8
146
0.657459
5.263982
false
false
false
false
dahlstrom-g/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/conventionNameCalls/ReplaceGetOrSetInspection.kt
1
5783
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.inspections.conventionNameCalls import com.intellij.codeInspection.CleanupLocalInspectionTool import com.intellij.codeInspection.ProblemHighlightType import com.intellij.openapi.editor.Editor import com.intellij.openapi.project.Project import com.intellij.psi.PsiElement import org.jetbrains.kotlin.descriptors.FunctionDescriptor import org.jetbrains.kotlin.idea.KotlinBundle import org.jetbrains.kotlin.idea.caches.resolve.analyze import org.jetbrains.kotlin.idea.caches.resolve.resolveToCall import org.jetbrains.kotlin.idea.inspections.AbstractApplicabilityBasedInspection import org.jetbrains.kotlin.idea.intentions.callExpression import org.jetbrains.kotlin.idea.intentions.calleeName import org.jetbrains.kotlin.idea.intentions.isReceiverExpressionWithValue import org.jetbrains.kotlin.idea.intentions.toResolvedCall import org.jetbrains.kotlin.idea.util.calleeTextRangeInThis import org.jetbrains.kotlin.load.java.descriptors.JavaClassDescriptor import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.getChildOfType import org.jetbrains.kotlin.psi.psiUtil.startOffset import org.jetbrains.kotlin.resolve.bindingContextUtil.isUsedAsExpression import org.jetbrains.kotlin.resolve.calls.util.getResolvedCall import org.jetbrains.kotlin.resolve.calls.model.isReallySuccess import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode import org.jetbrains.kotlin.util.OperatorNameConventions import org.jetbrains.kotlin.util.isValidOperator class ReplaceGetOrSetInspection : AbstractApplicabilityBasedInspection<KtDotQualifiedExpression>( KtDotQualifiedExpression::class.java ), CleanupLocalInspectionTool { private fun FunctionDescriptor.isExplicitOperator(): Boolean { return if (overriddenDescriptors.isEmpty()) containingDeclaration !is JavaClassDescriptor && isOperator else overriddenDescriptors.any { it.isExplicitOperator() } } private val operatorNames = setOf(OperatorNameConventions.GET, OperatorNameConventions.SET) override fun isApplicable(element: KtDotQualifiedExpression): Boolean { val callExpression = element.callExpression ?: return false val calleeName = (callExpression.calleeExpression as? KtSimpleNameExpression)?.getReferencedNameAsName() if (calleeName !in operatorNames) return false if (callExpression.typeArgumentList != null) return false val arguments = callExpression.valueArguments if (arguments.isEmpty()) return false if (arguments.any { it.isNamed() || it.isSpread }) return false val bindingContext = callExpression.analyze(BodyResolveMode.PARTIAL_WITH_CFA) val resolvedCall = callExpression.getResolvedCall(bindingContext) ?: return false if (!resolvedCall.isReallySuccess()) return false val target = resolvedCall.resultingDescriptor as? FunctionDescriptor ?: return false if (!target.isValidOperator() || target.name !in operatorNames) return false if (!element.isReceiverExpressionWithValue()) return false return target.name != OperatorNameConventions.SET || !element.isUsedAsExpression(bindingContext) } override fun inspectionText(element: KtDotQualifiedExpression) = KotlinBundle.message("should.be.replaced.with.indexing") override fun inspectionHighlightType(element: KtDotQualifiedExpression): ProblemHighlightType = if ((element.toResolvedCall(BodyResolveMode.PARTIAL)?.resultingDescriptor as? FunctionDescriptor)?.isExplicitOperator() == true) { ProblemHighlightType.GENERIC_ERROR_OR_WARNING } else { ProblemHighlightType.INFORMATION } override val defaultFixText: String get() = KotlinBundle.message("replace.get.or.set.call.with.indexing.operator") override fun fixText(element: KtDotQualifiedExpression): String { val callExpression = element.callExpression ?: return defaultFixText val resolvedCall = callExpression.resolveToCall() ?: return defaultFixText return KotlinBundle.message("replace.0.call.with.indexing.operator", resolvedCall.resultingDescriptor.name.asString()) } override fun inspectionHighlightRangeInElement(element: KtDotQualifiedExpression) = element.calleeTextRangeInThis() override fun applyTo(element: KtDotQualifiedExpression, project: Project, editor: Editor?) { val allArguments = element.callExpression?.valueArguments ?: return assert(allArguments.isNotEmpty()) val isSet = element.calleeName == OperatorNameConventions.SET.identifier val newExpression = KtPsiFactory(element).buildExpression { appendExpression(element.receiverExpression) appendFixedText("[") val arguments = if (isSet) allArguments.dropLast(1) else allArguments appendExpressions(arguments.map { it.getArgumentExpression() }) appendFixedText("]") if (isSet) { appendFixedText("=") appendExpression(allArguments.last().getArgumentExpression()) } } val newElement = element.replace(newExpression) if (editor != null) { moveCaret(editor, isSet, newElement) } } private fun moveCaret(editor: Editor, isSet: Boolean, newElement: PsiElement) { val arrayAccessExpression = if (isSet) { newElement.getChildOfType() } else { newElement as? KtArrayAccessExpression } ?: return arrayAccessExpression.leftBracket?.startOffset?.let { editor.caretModel.moveToOffset(it) } } }
apache-2.0
2884906dee8f47d39fa67fbb8db7d68c
47.191667
158
0.756874
5.576663
false
false
false
false
hkokocin/androidKit
library/src/main/java/com/github/hkokocin/androidkit/app/BaseKit.kt
1
4416
package com.github.hkokocin.androidkit.app import android.content.Intent import android.content.res.Resources import android.graphics.drawable.Drawable import android.os.Bundle import com.github.hkokocin.androidkit.AndroidKit import java.io.Serializable import kotlin.reflect.KClass fun <T : Any> getExtra(intent: Intent, name: String, type: KClass<T>): T? = AndroidKit.instance.getExtra(intent, name, type) fun <T : Any> getResource(resources: Resources, resourceId: Int, type: KClass<T>) = AndroidKit.instance.getResource(resources, resourceId, type) fun dimensionInPixels(resources: Resources, resourcesId: Int) = lazy { AndroidKit.instance.dimensionInPixels(resources, resourcesId) } interface BaseKit { @Suppress("UNCHECKED_CAST") fun <T : Any> getExtra(intent: Intent, name: String, type: KClass<T>): T? = when (type) { Char::class -> intent.getCharExtra(name, ' ') as T? Array<Char>::class -> intent.getCharArrayExtra(name).toTypedArray() as T? CharArray::class -> intent.getCharArrayExtra(name) as T? String::class -> intent.getStringExtra(name) as T? Array<String>::class -> intent.getStringArrayExtra(name) as T? CharSequence::class -> intent.getCharSequenceExtra(name) as T? Array<CharSequence>::class -> intent.getCharSequenceArrayExtra(name) as T? Short::class -> intent.getShortExtra(name, 0) as T? Array<Short>::class -> intent.getShortArrayExtra(name).toTypedArray() as T? ShortArray::class -> intent.getShortArrayExtra(name) as T? Int::class -> intent.getIntExtra(name, 0) as T? Array<Int>::class -> intent.getIntArrayExtra(name).toTypedArray() as T? IntArray::class -> intent.getIntArrayExtra(name) as T? Long::class -> intent.getLongExtra(name, 0) as T? Array<Long>::class -> intent.getLongArrayExtra(name).toTypedArray() as T? LongArray::class -> intent.getLongArrayExtra(name) as T? Double::class -> intent.getDoubleExtra(name, 0.0) as T? Array<Double>::class -> intent.getDoubleArrayExtra(name).toTypedArray() as T? DoubleArray::class -> intent.getDoubleArrayExtra(name) as T? Float::class -> intent.getFloatExtra(name, 0f) as T? Array<Float>::class -> intent.getFloatArrayExtra(name).toTypedArray() as T? FloatArray::class -> intent.getFloatArrayExtra(name) as T? Boolean::class -> intent.getBooleanExtra(name, false) as T? Array<Boolean>::class -> intent.getBooleanArrayExtra(name).toTypedArray() as T? BooleanArray::class -> intent.getBooleanArrayExtra(name) as T? Byte::class -> intent.getByteExtra(name, 0) as T? Array<Byte>::class -> intent.getByteArrayExtra(name).toTypedArray() as T? ByteArray::class -> intent.getByteArrayExtra(name) as T? Serializable::class -> intent.getSerializableExtra(name) as T? Bundle::class -> intent.getBundleExtra(name) as T? else -> throw IllegalArgumentException("cannot get extra of unknown type ${type.java.name}") } @Suppress("UNCHECKED_CAST", "DEPRECATION") fun <T : Any> getResource(resources: Resources, resourceId: Int, type: KClass<T>) = when (type) { String::class -> resources.getString(resourceId) as T Array<String>::class -> resources.getStringArray(resourceId) as T CharSequence::class -> resources.getText(resourceId) as T Array<CharSequence>::class -> resources.getTextArray(resourceId) as T Int::class -> resources.getInteger(resourceId) as T Array<Int>::class -> resources.getIntArray(resourceId).toTypedArray() as T Boolean::class -> resources.getBoolean(resourceId) as T Drawable::class -> resources.getDrawable(resourceId) as T else -> throw IllegalArgumentException("cannot get resource of unknown type ${type.java.name}") } fun dimensionInPixels(resources: Resources, resourcesId: Int) = resources.getDimensionPixelSize(resourcesId) }
mit
4480cc8b9df016ded7ce22afd27fb2b3
60.347222
125
0.629529
4.487805
false
false
false
false
dahlstrom-g/intellij-community
platform/workspaceModel/storage/testEntities/gen/com/intellij/workspaceModel/storage/entities/test/api/ChildSecondEntityImpl.kt
3
10030
package com.intellij.workspaceModel.storage.entities.test.api import com.intellij.workspaceModel.storage.EntityInformation import com.intellij.workspaceModel.storage.EntitySource import com.intellij.workspaceModel.storage.EntityStorage import com.intellij.workspaceModel.storage.GeneratedCodeApiVersion import com.intellij.workspaceModel.storage.GeneratedCodeImplVersion import com.intellij.workspaceModel.storage.ModifiableWorkspaceEntity import com.intellij.workspaceModel.storage.MutableEntityStorage import com.intellij.workspaceModel.storage.WorkspaceEntity import com.intellij.workspaceModel.storage.impl.ConnectionId import com.intellij.workspaceModel.storage.impl.EntityLink import com.intellij.workspaceModel.storage.impl.ModifiableWorkspaceEntityBase import com.intellij.workspaceModel.storage.impl.WorkspaceEntityBase import com.intellij.workspaceModel.storage.impl.WorkspaceEntityData import com.intellij.workspaceModel.storage.impl.extractOneToAbstractManyParent import com.intellij.workspaceModel.storage.impl.updateOneToAbstractManyParentOfChild import org.jetbrains.deft.ObjBuilder import org.jetbrains.deft.Type import org.jetbrains.deft.annotations.Abstract import org.jetbrains.deft.annotations.Child @GeneratedCodeApiVersion(1) @GeneratedCodeImplVersion(1) open class ChildSecondEntityImpl: ChildSecondEntity, WorkspaceEntityBase() { companion object { internal val PARENTENTITY_CONNECTION_ID: ConnectionId = ConnectionId.create(ParentAbEntity::class.java, ChildAbstractBaseEntity::class.java, ConnectionId.ConnectionType.ONE_TO_ABSTRACT_MANY, false) val connections = listOf<ConnectionId>( PARENTENTITY_CONNECTION_ID, ) } @JvmField var _commonData: String? = null override val commonData: String get() = _commonData!! override val parentEntity: ParentAbEntity get() = snapshot.extractOneToAbstractManyParent(PARENTENTITY_CONNECTION_ID, this)!! @JvmField var _secondData: String? = null override val secondData: String get() = _secondData!! override fun connectionIdList(): List<ConnectionId> { return connections } class Builder(val result: ChildSecondEntityData?): ModifiableWorkspaceEntityBase<ChildSecondEntity>(), ChildSecondEntity.Builder { constructor(): this(ChildSecondEntityData()) override fun applyToBuilder(builder: MutableEntityStorage) { if (this.diff != null) { if (existsInBuilder(builder)) { this.diff = builder return } else { error("Entity ChildSecondEntity is already created in a different builder") } } this.diff = builder this.snapshot = builder addToBuilder() this.id = getEntityData().createEntityId() // Process linked entities that are connected without a builder processLinkedEntities(builder) checkInitialization() // TODO uncomment and check failed tests } fun checkInitialization() { val _diff = diff if (!getEntityData().isCommonDataInitialized()) { error("Field ChildAbstractBaseEntity#commonData should be initialized") } if (_diff != null) { if (_diff.extractOneToAbstractManyParent<WorkspaceEntityBase>(PARENTENTITY_CONNECTION_ID, this) == null) { error("Field ChildAbstractBaseEntity#parentEntity should be initialized") } } else { if (this.entityLinks[EntityLink(false, PARENTENTITY_CONNECTION_ID)] == null) { error("Field ChildAbstractBaseEntity#parentEntity should be initialized") } } if (!getEntityData().isSecondDataInitialized()) { error("Field ChildSecondEntity#secondData should be initialized") } if (!getEntityData().isEntitySourceInitialized()) { error("Field ChildSecondEntity#entitySource should be initialized") } } override fun connectionIdList(): List<ConnectionId> { return connections } override var commonData: String get() = getEntityData().commonData set(value) { checkModificationAllowed() getEntityData().commonData = value changedProperty.add("commonData") } override var parentEntity: ParentAbEntity get() { val _diff = diff return if (_diff != null) { _diff.extractOneToAbstractManyParent(PARENTENTITY_CONNECTION_ID, this) ?: this.entityLinks[EntityLink(false, PARENTENTITY_CONNECTION_ID)]!! as ParentAbEntity } else { this.entityLinks[EntityLink(false, PARENTENTITY_CONNECTION_ID)]!! as ParentAbEntity } } set(value) { checkModificationAllowed() val _diff = diff if (_diff != null && value is ModifiableWorkspaceEntityBase<*> && value.diff == null) { // Setting backref of the list if (value is ModifiableWorkspaceEntityBase<*>) { val data = (value.entityLinks[EntityLink(true, PARENTENTITY_CONNECTION_ID)] as? List<Any> ?: emptyList()) + this value.entityLinks[EntityLink(true, PARENTENTITY_CONNECTION_ID)] = data } // else you're attaching a new entity to an existing entity that is not modifiable _diff.addEntity(value) } if (_diff != null && (value !is ModifiableWorkspaceEntityBase<*> || value.diff != null)) { _diff.updateOneToAbstractManyParentOfChild(PARENTENTITY_CONNECTION_ID, this, value) } else { // Setting backref of the list if (value is ModifiableWorkspaceEntityBase<*>) { val data = (value.entityLinks[EntityLink(true, PARENTENTITY_CONNECTION_ID)] as? List<Any> ?: emptyList()) + this value.entityLinks[EntityLink(true, PARENTENTITY_CONNECTION_ID)] = data } // else you're attaching a new entity to an existing entity that is not modifiable this.entityLinks[EntityLink(false, PARENTENTITY_CONNECTION_ID)] = value } changedProperty.add("parentEntity") } override var secondData: String get() = getEntityData().secondData set(value) { checkModificationAllowed() getEntityData().secondData = value changedProperty.add("secondData") } override var entitySource: EntitySource get() = getEntityData().entitySource set(value) { checkModificationAllowed() getEntityData().entitySource = value changedProperty.add("entitySource") } override fun getEntityData(): ChildSecondEntityData = result ?: super.getEntityData() as ChildSecondEntityData override fun getEntityClass(): Class<ChildSecondEntity> = ChildSecondEntity::class.java } } class ChildSecondEntityData : WorkspaceEntityData<ChildSecondEntity>() { lateinit var commonData: String lateinit var secondData: String fun isCommonDataInitialized(): Boolean = ::commonData.isInitialized fun isSecondDataInitialized(): Boolean = ::secondData.isInitialized override fun wrapAsModifiable(diff: MutableEntityStorage): ModifiableWorkspaceEntity<ChildSecondEntity> { val modifiable = ChildSecondEntityImpl.Builder(null) modifiable.allowModifications { modifiable.diff = diff modifiable.snapshot = diff modifiable.id = createEntityId() modifiable.entitySource = this.entitySource } modifiable.changedProperty.clear() return modifiable } override fun createEntity(snapshot: EntityStorage): ChildSecondEntity { val entity = ChildSecondEntityImpl() entity._commonData = commonData entity._secondData = secondData entity.entitySource = entitySource entity.snapshot = snapshot entity.id = createEntityId() return entity } override fun getEntityInterface(): Class<out WorkspaceEntity> { return ChildSecondEntity::class.java } override fun serialize(ser: EntityInformation.Serializer) { } override fun deserialize(de: EntityInformation.Deserializer) { } override fun equals(other: Any?): Boolean { if (other == null) return false if (this::class != other::class) return false other as ChildSecondEntityData if (this.commonData != other.commonData) return false if (this.secondData != other.secondData) return false if (this.entitySource != other.entitySource) return false return true } override fun equalsIgnoringEntitySource(other: Any?): Boolean { if (other == null) return false if (this::class != other::class) return false other as ChildSecondEntityData if (this.commonData != other.commonData) return false if (this.secondData != other.secondData) return false return true } override fun hashCode(): Int { var result = entitySource.hashCode() result = 31 * result + commonData.hashCode() result = 31 * result + secondData.hashCode() return result } }
apache-2.0
0070ac8d7d19a7039b5d7bf53217e931
41.147059
205
0.626919
6.130807
false
false
false
false
awsdocs/aws-doc-sdk-examples
kotlin/services/xray/src/main/kotlin/com/kotlin/xray/CreateSamplingRule.kt
1
2153
// snippet-sourcedescription:[CreateSamplingRule.kt demonstrates how to create a rule to control sampling behavior for instrumented applications.] // snippet-keyword:[SDK for Kotlin] // snippet-service:[AWS X-Ray Service] /* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. SPDX-License-Identifier: Apache-2.0 */ package com.kotlin.xray // snippet-start:[xray.kotlin_create_rule.import] import aws.sdk.kotlin.services.xray.XRayClient import aws.sdk.kotlin.services.xray.model.CreateSamplingRuleRequest import aws.sdk.kotlin.services.xray.model.CreateSamplingRuleResponse import aws.sdk.kotlin.services.xray.model.SamplingRule import kotlin.system.exitProcess // snippet-end:[xray.kotlin_create_rule.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: <ruleName> Where: ruleName - The name of the rule. """ if (args.size != 1) { println(usage) exitProcess(0) } val ruleName = args[0] createRule(ruleName) } // snippet-start:[xray.kotlin_create_rule.main] suspend fun createRule(ruleNameVal: String?) { val rule = SamplingRule { ruleName = ruleNameVal priority = 1 httpMethod = "*" serviceType = "*" serviceName = "*" urlPath = "*" version = 1 host = "*" resourceArn = "*" } val ruleRequest = CreateSamplingRuleRequest { samplingRule = rule } XRayClient { region = "us-east-1" }.use { xRayClient -> val ruleResponse: CreateSamplingRuleResponse = xRayClient.createSamplingRule(ruleRequest) println("The ARN of the new rule is ${ruleResponse.samplingRuleRecord?.samplingRule?.ruleArn}") } } // snippet-end:[xray.kotlin_create_rule.main]
apache-2.0
ebf595f208b0ba35562595a6cb94955c
27.902778
146
0.652113
4.093156
false
false
false
false
tateisu/SubwayTooter
app/src/main/java/jp/juggler/subwaytooter/action/Action_Server.kt
1
6253
package jp.juggler.subwaytooter.action import androidx.appcompat.app.AlertDialog import jp.juggler.subwaytooter.* import jp.juggler.subwaytooter.actmain.addColumn import jp.juggler.subwaytooter.actmain.defaultInsertPosition import jp.juggler.subwaytooter.actmain.nextPosition import jp.juggler.subwaytooter.api.entity.* import jp.juggler.subwaytooter.api.runApiTask import jp.juggler.subwaytooter.column.Column import jp.juggler.subwaytooter.column.ColumnType import jp.juggler.subwaytooter.column.onDomainBlockChanged import jp.juggler.subwaytooter.dialog.pickAccount import jp.juggler.subwaytooter.table.SavedAccount import jp.juggler.subwaytooter.util.matchHost import jp.juggler.subwaytooter.util.openBrowser import jp.juggler.util.* // profile directory を開く private fun ActMain.serverProfileDirectory( accessInfo: SavedAccount, host: Host, instance: TootInstance? = null, pos: Int = defaultInsertPosition, ) { when { // インスタンスのバージョン情報がなければ取得してやり直し instance == null -> launchMain { var targetInstance: TootInstance? = null runApiTask(host) { client -> val (ti, ri) = TootInstance.getEx(client, host, allowPixelfed = true) targetInstance = ti ri }?.let { result -> when (val ti = targetInstance) { null -> showToast(true, result.error) else -> serverProfileDirectory(accessInfo, host, ti, pos) } } } // Misskey非対応 instance.instanceType == InstanceType.Misskey -> showToast(false, R.string.profile_directory_not_supported_on_misskey) // バージョンが足りないならWebページを開く !instance.versionGE(TootInstance.VERSION_3_0_0_rc1) -> openBrowser("https://${host.ascii}/explore") // ホスト名部分が一致するならそのアカウントで開く accessInfo.matchHost(host) -> addColumn( false, pos, accessInfo, ColumnType.PROFILE_DIRECTORY, host ) // 疑似アカウントで開く else -> launchMain { addPseudoAccount(host, instance)?.let { ai -> addColumn( false, pos, ai, ColumnType.PROFILE_DIRECTORY, host ) } } } } // サイドメニューからprofile directory を開く fun ActMain.serverProfileDirectoryFromSideMenu() { launchMain { pickAccount( bAllowPseudo = true, bAllowMisskey = false, bAllowMastodon = true, bAuto = true, message = getString( R.string.account_picker_add_timeline_of, ColumnType.PROFILE_DIRECTORY.name1(applicationContext) ) )?.let { ai -> serverProfileDirectory(ai, ai.apiHost) } } } // インスタンス情報カラムやコンテキストメニューからprofile directoryを開く fun ActMain.serverProfileDirectoryFromInstanceInformation( currentColumn: Column, host: Host, instance: TootInstance? = null, ) = serverProfileDirectory( currentColumn.accessInfo, host, instance = instance, pos = nextPosition(currentColumn) ) // インスタンス情報カラムを開く fun ActMain.serverInformation( pos: Int, host: Host, ) = addColumn( false, pos, SavedAccount.na, ColumnType.INSTANCE_INFORMATION, host ) // ドメインブロック一覧から解除 fun ActMain.clickDomainBlock(accessInfo: SavedAccount, item: TootDomainBlock) { AlertDialog.Builder(this) .setMessage(getString(R.string.confirm_unblock_domain, item.domain.pretty)) .setNegativeButton(R.string.cancel, null) .setPositiveButton(R.string.ok) { _, _ -> domainBlock(accessInfo, item.domain, bBlock = false) } .show() } // ContextMenuからドメインブロックを追加 fun ActMain.clickDomainBlock( accessInfo: SavedAccount, who: TootAccount, ) { // 疑似アカウントではドメインブロックできない if (accessInfo.isPseudo) { showToast(false, R.string.domain_block_from_pseudo) return } val whoApDomain = who.apDomain // 自分のドメインではブロックできない if (accessInfo.matchHost(whoApDomain)) { showToast(false, R.string.domain_block_from_local) return } AlertDialog.Builder(this) .setMessage(getString(R.string.confirm_block_domain, whoApDomain)) .setNegativeButton(R.string.cancel, null) .setPositiveButton(R.string.ok) { _, _ -> domainBlock(accessInfo, whoApDomain, true) } .show() } // ドメインブロック fun ActMain.domainBlock( accessInfo: SavedAccount, domain: Host, bBlock: Boolean, ) { if (accessInfo.matchHost(domain)) { showToast(false, R.string.it_is_you) return } launchMain { runApiTask(accessInfo) { client -> client.request( "/api/v1/domain_blocks", "domain=${domain.ascii.encodePercent()}" .toFormRequestBody() .toRequest(if (bBlock) "POST" else "DELETE") ) }?.let { result -> when (result.jsonObject) { null -> showToast(false, result.error) else -> { for (column in appState.columnList) { column.onDomainBlockChanged(accessInfo, domain, bBlock) } showToast( false, if (bBlock) R.string.block_succeeded else R.string.unblock_succeeded ) } } } } }
apache-2.0
ecfe32e53c3705fc434ee11dd2413a39
28.539267
92
0.575176
4.320741
false
false
false
false
pr0stik/AndroidDev
Anko/KotlinWebView/app/src/main/java/com/example/foxy/kotlinwebview/Asconjs.kt
1
402
package com.example.foxy.kotlinwebview /** * Created by foxy on 29.12.2017. */ class Asconjs { public class jSkin(){ val a: Int = 0 val a2: Int = 0 val a3: Int = 0 val a4: Int = 0 val a5: Int = 0 val a6: Int = 0 val a7: Int = 0 val a8: Int = 0 val a9: Int = 0 val a10: Int = 0 val a11: Int = 0 } }
gpl-3.0
9450d3eef4ea9166354018d2e261672e
14.5
38
0.460199
3.045455
false
false
false
false
cbeust/klaxon
klaxon/src/test/kotlin/com/beust/klaxon/JsonAnnotationTest.kt
1
4185
package com.beust.klaxon import org.assertj.core.api.Assertions import org.testng.Assert import org.testng.annotations.Test @Test class JsonAnnotationTest { private val jsonString: String = json { obj( "name" to "John", "change" to 1 ) }.toJsonString() fun ignoredWithAnnotation() { class IgnoredWithAnnotation( val name: String, @Json(ignored = true) val change: Int = 0) val result = Klaxon().parse<IgnoredWithAnnotation>(jsonString) Assert.assertEquals(result?.name, "John") Assert.assertEquals(result?.change, 0) } fun ignoredWithPrivate() { class IgnoredWithPrivate( val name: String, private val change: Int = 0){ fun changed(): Boolean = change != 0 } val result = Klaxon().parse<IgnoredWithPrivate>(jsonString) Assert.assertEquals(result?.name, "John") Assert.assertEquals(result?.changed(), false) } @Test fun privateNotIgnored() { data class Config( val version: String, @Json(ignored = false) private val projects: Set<String>) { fun contains(name: String) = projects.contains(name) } val jsonString = """{"version": "v1", "projects": ["abc"]}""" val r = Klaxon().parse<Config>(jsonString) Assertions.assertThat(r).isEqualTo(Config("v1", setOf("abc"))) } @Test fun serializeNullFalseRoundtripWithoutDefault() { // when serializeNull == false, null is the default value during parsing data class ObjWithSerializeNullFalse( @Json(serializeNull = false) val value: Int? ) val originalObj = ObjWithSerializeNullFalse(null) val serialized = Klaxon().toJsonString(originalObj) Assert.assertEquals("{}", serialized) // with serializeNull = false, the null property is not serialized val parsed = Klaxon().parse<ObjWithSerializeNullFalse>(serialized) val expected = ObjWithSerializeNullFalse(null) Assert.assertEquals(expected, parsed) } @Test fun serializeNullFalseRoundtripWithDefault() { // Kotlin defaults are ignored when serializeNull == false and replaced with null during parsing data class ObjWithSerializeNullFalseAndDefault( @Json(serializeNull = false) val value: Int? = 1 ) val originalObj = ObjWithSerializeNullFalseAndDefault(null) val serialized = Klaxon().toJsonString(originalObj) Assert.assertEquals("{}", serialized) val parsed = Klaxon().parse<ObjWithSerializeNullFalseAndDefault>(serialized) val expected = ObjWithSerializeNullFalseAndDefault(null) Assert.assertEquals(expected, parsed) } @Test fun serializeNullFalseValueSet() { data class ObjWithSerializeNullFalse( @Json(serializeNull = false) val value: Int? ) Assertions .assertThat( Klaxon().toJsonString( ObjWithSerializeNullFalse(1) ) ) .isEqualTo("""{"value" : 1}""") } @Test fun serializeNullTrue() { data class ObjWithSerializeNullTrue( @Json(serializeNull = true) val value: Int? ) Assertions .assertThat( Klaxon().toJsonString( ObjWithSerializeNullTrue(null) ) ) .isEqualTo("""{"value" : null}""") Assertions .assertThat( Klaxon().toJsonString( ObjWithSerializeNullTrue(1))) .isEqualTo("""{"value" : 1}""") } @Test fun serializeNullWithoutNullableProperty() { data class ObjWithSerializeNullFalse( @Json(serializeNull = false) val value: Int = 1 ) val parsed = Klaxon().parse<ObjWithSerializeNullFalse>("{}") val expected = ObjWithSerializeNullFalse(1) Assert.assertEquals(expected, parsed) } }
apache-2.0
c5ad7f710f87ad22f04d32b34152b42f
29.779412
112
0.586858
5.372272
false
true
false
false
skydoves/ElasticViews
elasticviews/src/main/java/com/skydoves/elasticviews/ElasticExtensions.kt
1
3308
/* * The MIT License (MIT) * * Copyright (c) 2017 skydoves * * 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. */ @file:Suppress("unused") @file:JvmName("ElasticExtensions") @file:JvmMultifileClass package com.skydoves.elasticviews import android.view.View @DslMarker internal annotation class ElasticDsl /** * An extension for operating elastic animation to the target view with custom attributes. * * @param scaleX The target elastic scale-x size of the animation. * @param scaleY The target elastic scale-y size of the animation. * @param duration The duration of the animation. * @param listener The [ElasticFinishListener] for being notified when the animation is finished. */ @ElasticDsl @JvmOverloads @JvmSynthetic fun View.elasticAnimation( scaleX: Float = Definitions.DEFAULT_SCALE_X, scaleY: Float = Definitions.DEFAULT_SCALE_Y, duration: Int = Definitions.DEFAULT_DURATION, listener: ElasticFinishListener? = null ): ElasticAnimation { return ElasticAnimation(this) .setScaleX(scaleX) .setScaleY(scaleY) .setDuration(duration) .setOnFinishListener(listener) } /** * An extension for operating elastic animation to the target view with custom attributes. * * @param scaleX The target elastic scale-x size of the animation. * @param scaleY The target elastic scale-y size of the animation. * @param duration The duration of the animation. * @param block The lambda for being notified when the animation is finished. */ @ElasticDsl @JvmOverloads @JvmSynthetic inline fun View.elasticAnimation( scaleX: Float = Definitions.DEFAULT_SCALE_X, scaleY: Float = Definitions.DEFAULT_SCALE_Y, duration: Int = Definitions.DEFAULT_DURATION, crossinline block: () -> Unit ): ElasticAnimation { return ElasticAnimation(this) .setScaleX(scaleX) .setScaleY(scaleY) .setDuration(duration) .setOnFinishListener(ElasticFinishListener { block() }) } /** * An extension for creating elastic animation with kotlin dsl style. * * @param block The dsl block of the [ElasticAnimation]. * * @return A new instance of the [ElasticAnimation]. */ @ElasticDsl @JvmSynthetic inline fun elasticAnimation( view: View, crossinline block: ElasticAnimation.() -> Unit ): ElasticAnimation = ElasticAnimation(view).apply(block)
mit
44994bc287099e420b4944d7ea6cb381
33.821053
97
0.75786
4.364116
false
false
false
false
DemonWav/MinecraftDevIntelliJ
src/main/kotlin/com/demonwav/mcdev/platform/forge/inspections/sideonly/NestedClassSideOnlyInspection.kt
1
3417
/* * Minecraft Dev for IntelliJ * * https://minecraftdev.org * * Copyright (c) 2020 minecraft-dev * * MIT License */ package com.demonwav.mcdev.platform.forge.inspections.sideonly import com.intellij.psi.PsiClass import com.siyeh.ig.BaseInspection import com.siyeh.ig.BaseInspectionVisitor import com.siyeh.ig.InspectionGadgetsFix import org.jetbrains.annotations.Nls class NestedClassSideOnlyInspection : BaseInspection() { @Nls override fun getDisplayName() = "Invalid usage of @SideOnly in nested class declaration" override fun buildErrorString(vararg infos: Any) = "A nested class cannot declare a side that is different from the parent class." + "\nEither remove the nested class's @SideOnly annotation, or change it to match it's parent's side." override fun getStaticDescription(): String? { return "Classes which are annotated with @SideOnly cannot contain any nested classes which are " + "annotated with a different @SideOnly annotation. Since a class that is annotated with @SideOnly " + "brings everything with it, @SideOnly annotated nested classes are usually useless." } override fun buildFix(vararg infos: Any): InspectionGadgetsFix? { val psiClass = infos[0] as PsiClass return if (psiClass.isWritable) { RemoveAnnotationInspectionGadgetsFix(psiClass, "Remove @SideOnly annotation from nested class") } else { null } } override fun buildVisitor(): BaseInspectionVisitor { return object : BaseInspectionVisitor() { override fun visitClass(aClass: PsiClass) { if (aClass.parent == null) { return } aClass.nameIdentifier ?: return if (!SideOnlyUtil.beginningCheck(aClass)) { return } val classHierarchyList = SideOnlyUtil.checkClassHierarchy(aClass) // The class lists are ordered from lowest to highest in the hierarchy - that is the first element in the list // is the most nested class, and the last element in the list is the top level class // // In this case, the higher-level classes take precedence, so if a class is annotated as @SideOnly.CLIENT and a nested class is // annotated as @SideOnly.SERVER, the nested class is the class that is in error, not the top level class var currentSide = Side.NONE for (pair in classHierarchyList) { if (currentSide === Side.NONE) { // If currentSide is NONE, then a class hasn't declared yet what it is if (pair.first !== Side.NONE && pair.first !== Side.INVALID) { currentSide = pair.first } else { // We are only worried about this class return } } else if (pair.first !== Side.NONE && pair.first !== Side.INVALID) { if (pair.first !== currentSide) { registerClassError(aClass, aClass) } else { return } } } } } } }
mit
aed386ae72d26febf041ba472ff9c840
39.2
143
0.57887
5.372642
false
false
false
false
lisuperhong/ModularityApp
KaiyanModule/src/main/java/com/lisuperhong/openeye/ui/fragment/home/CategoryFragment.kt
1
2589
package com.lisuperhong.openeye.ui.fragment.home import android.support.v7.widget.GridLayoutManager import android.widget.Toast import com.company.commonbusiness.base.fragment.BaseMvpFragment import com.lisuperhong.openeye.R import com.lisuperhong.openeye.mvp.contract.CategoryContract import com.lisuperhong.openeye.mvp.model.bean.BaseBean import com.lisuperhong.openeye.mvp.presenter.CategoryPresenter import com.lisuperhong.openeye.ui.adapter.CategoryAdapter import com.scwang.smartrefresh.layout.header.ClassicsHeader import kotlinx.android.synthetic.main.fragment_category.* /** * Author: lisuperhong * Time: Create on 2018/9/16 13:40 * Github: https://github.com/lisuperhong * Desc: 全部分类 */ class CategoryFragment : BaseMvpFragment<CategoryPresenter>(), CategoryContract.View { private var categoryAdapter: CategoryAdapter? = null private var dataList: ArrayList<BaseBean.Item>? = null override val layoutId: Int get() = R.layout.fragment_category override fun setPresenter() { presenter = CategoryPresenter(this) } override fun initView() { refreshLayout.setEnableLoadMore(false) refreshLayout.setRefreshHeader(ClassicsHeader(activity)) refreshLayout.setOnClickListener { initData() } categoryAdapter = CategoryAdapter(getContext()!!, ArrayList<BaseBean.Item>()) val layoutManager = GridLayoutManager(activity, 2) categoryRecyclerView.layoutManager = layoutManager layoutManager.spanSizeLookup = object : GridLayoutManager.SpanSizeLookup() { override fun getSpanSize(position: Int): Int { val item = dataList!![position] if (item.type == "rectangleCard") { return 2 } else { return 1 } } } categoryRecyclerView.adapter = categoryAdapter showLoading() } override fun initData() { presenter?.getAllCategory() } override fun showContent(baseBean: BaseBean) { refreshLayout.finishRefresh() if (baseBean.itemList.isEmpty()) return dataList = baseBean.itemList categoryAdapter?.setRefreshData(baseBean.itemList) } override fun showLoading() { loadingProgressBar.show() } override fun hideLoading() { loadingProgressBar.hide() } override fun showMessage(message: String) { refreshLayout.finishRefresh() Toast.makeText(activity, message, Toast.LENGTH_LONG).show() } }
apache-2.0
b4d7ec030a215af3c793b3416a3501cd
30.864198
86
0.681131
4.944444
false
false
false
false
apoi/quickbeer-next
app/src/main/java/quickbeer/android/ui/transformations/ContainerLabelExtractor.kt
2
4892
/* * This file is part of QuickBeer. * Copyright (C) 2017 Antti Poikela <[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 quickbeer.android.ui.transformations import android.graphics.Bitmap import android.graphics.Canvas import android.graphics.Color import android.graphics.Rect import coil.bitmap.BitmapPool import coil.size.Size import coil.transform.Transformation import kotlin.math.abs class ContainerLabelExtractor( private val width: Int, private val height: Int ) : Transformation { override fun key(): String { return "label-%d-%d".format(width, height) } override suspend fun transform(pool: BitmapPool, input: Bitmap, size: Size): Bitmap { val result = getLabel(input, width, height) input.recycle() return result } private fun getLabel(source: Bitmap, width: Int, height: Int): Bitmap { val destination = Bitmap.createBitmap(width, height, source.config) val destinationRect = Rect(0, 0, destination.width, destination.height) val canvas = Canvas(destination) val sourceRect = cutToFit(getCentralRect(source), width, height) canvas.drawBitmap(source, sourceRect, destinationRect, null) return destination } private fun cutToFit(source: Rect, width: Int, height: Int): Rect { val sourceRatio = source.width().toFloat() / source.height() val targetRatio = width.toFloat() / height return if (sourceRatio > targetRatio) { // Keep max height of source, cut sides to fit target size val diff = (source.width() - source.height() * targetRatio).toInt() / 2 Rect(source.left + diff, source.top, source.right - diff, source.bottom) } else { // Keep max width of source, cut top and bottom to fit val diff = (source.height() - source.width() / targetRatio).toInt() / 2 Rect(source.left, source.top + diff, source.right, source.bottom - diff) } } private fun getCentralRect(source: Bitmap): Rect { // Reference point at 2/3 of the height where we expect the container to be thickest val referenceY = (source.height * LABEL_REFERENCE_Y).toInt() val minX = scanFromLeft(source, referenceY) val maxX = scanFromRight(source, referenceY) // Maximum difference we allow from the reference point width scan is 7% // Success function: scan doesn't overshoot more than max difference. val diff = (source.width * ALLOWED_REFERENCE_VARIANCE).toInt() val func: (y: Int) -> Boolean = { y -> scanFromLeft(source, y) < minX + diff } // Do a binary search for the cut points above and below the reference point val minY = binarySearch(referenceY, 0, func) val maxY = binarySearch(referenceY, source.height, func) // Do a fixed cut from all sides to remove any blending with the background return Rect(minX + diff, minY + diff, maxX - diff, maxY - diff) } private fun binarySearch(from: Int, to: Int, func: (Int) -> Boolean): Int { val middle = to.coerceAtLeast(from) - (to.coerceAtLeast(from) - to.coerceAtMost(from)) / 2 return when { abs(from - to) == 1 -> from func(middle) -> binarySearch(middle, to, func) else -> binarySearch(from, middle, func) } } private fun scanFromLeft(source: Bitmap, y: Int): Int { return (0 until source.width / 2) .firstOrNull { !isWhitePixel(source, it, y) } ?: 0 } private fun scanFromRight(source: Bitmap, y: Int): Int { return (source.width - 1 downTo source.width / 2 + 1) .firstOrNull { !isWhitePixel(source, it, y) } ?: source.width - 1 } private fun isWhitePixel(source: Bitmap, x: Int, y: Int): Boolean { val color = source.getPixel(x, y) val r = Color.red(color) val g = Color.green(color) val b = Color.blue(color) return r > WHITE_POINT && g > WHITE_POINT && b > WHITE_POINT } companion object { private const val LABEL_REFERENCE_Y = 2F / 3F private const val ALLOWED_REFERENCE_VARIANCE = 0.07F private const val WHITE_POINT = 190 } }
gpl-3.0
4f3aa9f4fa89c7dd93efd8b9a0dfc70b
37.825397
98
0.65045
4.12827
false
false
false
false
google/intellij-community
plugins/package-search/src/com/jetbrains/packagesearch/intellij/plugin/ui/toolwindow/models/operations/PackageSearchOperationFactory.kt
1
9965
/******************************************************************************* * Copyright 2000-2022 JetBrains s.r.o. and contributors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.operations import com.intellij.buildsystem.model.unified.UnifiedDependency import com.intellij.openapi.project.Project import com.jetbrains.packagesearch.intellij.plugin.extensibility.ProjectModule import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.KnownRepositories import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.ModuleModel import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.PackageModel import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.PackageScope import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.PackageVersion import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.RepositoryModel import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.TargetModules import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.versions.NormalizedPackageVersion import com.jetbrains.packagesearch.intellij.plugin.util.toUnifiedDependency import com.jetbrains.packagesearch.intellij.plugin.util.toUnifiedRepository internal class PackageSearchOperationFactory { inline fun <reified T : PackageModel, V : PackageVersion> computeInstallActionsFor( project: Project, packageModel: T, moduleModel: ModuleModel, defaultScope: PackageScope, knownRepositories: KnownRepositories.InTargetModules, targetVersion: NormalizedPackageVersion<V> ): List<PackageSearchOperation<*>> { if (packageModel !is PackageModel.SearchResult) return emptyList() val versionToInstall = targetVersion.originalVersion return createAddPackageOperations( packageModel = packageModel, version = versionToInstall, scope = defaultScope, targetModules = TargetModules.from(moduleModel), repoToInstall = knownRepositories.repositoryToAddWhenInstallingOrUpgrading(project, packageModel, versionToInstall) ) } inline fun <reified T : PackageModel, V : PackageVersion> computeUpgradeActionsFor( project: Project, packageModel: T, moduleModel: ModuleModel, knownRepositories: KnownRepositories.InTargetModules, targetVersion: NormalizedPackageVersion<V> ): List<PackageSearchOperation<*>> { if (packageModel !is PackageModel.Installed) return emptyList() return packageModel.usageInfo.asSequence() .filter { it.projectModule == moduleModel.projectModule } .flatMap { usageInfo -> createChangePackageVersionOperations( packageModel = packageModel, newVersion = targetVersion.originalVersion, targetModules = TargetModules.from(moduleModel), repoToInstall = knownRepositories.repositoryToAddWhenInstallingOrUpgrading(project, packageModel, targetVersion.originalVersion) ) } .toList() } inline fun <reified T : PackageModel> computeRemoveActionsFor( packageModel: T, moduleModel: ModuleModel ): List<PackageSearchOperation<*>> { if (packageModel !is PackageModel.Installed) return emptyList() return packageModel.usageInfo.asSequence() .filter { it.projectModule == moduleModel.projectModule } .flatMap { usageInfo -> createRemovePackageOperations( packageModel = packageModel, version = usageInfo.declaredVersion, scope = usageInfo.scope, targetModules = TargetModules.from(moduleModel) ) } .toList() } fun createChangePackageVersionOperations( packageModel: PackageModel.Installed, newVersion: PackageVersion, targetModules: TargetModules, repoToInstall: RepositoryModel? ) = createChangePackageOperations( packageModel = packageModel, newVersion = newVersion, targetModules = targetModules, repoToInstall = repoToInstall ) fun createChangePackageScopeOperations( packageModel: PackageModel.Installed, newScope: PackageScope, targetModules: TargetModules, repoToInstall: RepositoryModel? ) = createChangePackageOperations( packageModel = packageModel, newVersion = PackageVersion.Missing, newScope = newScope, targetModules = targetModules, repoToInstall = repoToInstall ) fun createChangePackageVersionOperations( projectModule: ProjectModule, dependency: UnifiedDependency, newVersion: PackageVersion, repoToInstall: RepositoryModel? ): List<PackageSearchOperation<*>> { val currentScope = PackageScope.from(dependency.scope) val currentVersion = PackageVersion.from(dependency.coordinates.version) val packageOperation = PackageSearchOperation.Package.ChangeInstalled( model = dependency, projectModule = projectModule, currentVersion = currentVersion, currentScope = currentScope, newVersion = newVersion, newScope = currentScope ) return if (repoToInstall != null) { val repoToInstallOperation = createAddRepositoryOperation(repoToInstall, projectModule) listOf(packageOperation, repoToInstallOperation) } else { listOf(packageOperation) } } fun createChangePackageOperations( packageModel: PackageModel.Installed, newVersion: PackageVersion, newScope: PackageScope? = null, targetModules: TargetModules, repoToInstall: RepositoryModel? ): List<PackageSearchOperation<*>> { if (targetModules is TargetModules.None) return emptyList() return usagesByModule(targetModules, packageModel) .flatMap { (module, usageInfo) -> val packageOperation = PackageSearchOperation.Package.ChangeInstalled( model = packageModel.toUnifiedDependency(usageInfo.declaredVersion, usageInfo.scope), projectModule = module.projectModule, currentVersion = usageInfo.declaredVersion, currentScope = usageInfo.scope, newVersion = newVersion, newScope = newScope ?: usageInfo.scope ) if (repoToInstall != null) { val repoToInstallOperation = createAddRepositoryOperation(repoToInstall, module.projectModule) listOf(packageOperation, repoToInstallOperation) } else { listOf(packageOperation) } } } fun createAddPackageOperations( packageModel: PackageModel.SearchResult, version: PackageVersion, scope: PackageScope, targetModules: TargetModules, repoToInstall: RepositoryModel? ): List<PackageSearchOperation<*>> { if (targetModules is TargetModules.None) return emptyList() return targetModules.flatMap { module -> val packageOperation = PackageSearchOperation.Package.Install( model = packageModel.toUnifiedDependency(version, scope), projectModule = module.projectModule, newVersion = version, newScope = scope ) if (repoToInstall != null) { val repoToInstallOperation = createAddRepositoryOperation(repoToInstall, module.projectModule) listOf(packageOperation, repoToInstallOperation) } else { listOf(packageOperation) } } } fun createRemovePackageOperations( packageModel: PackageModel.Installed, version: PackageVersion, scope: PackageScope, targetModules: TargetModules ): List<PackageSearchOperation<*>> { if (targetModules is TargetModules.None) return emptyList() return usagesByModule(targetModules, packageModel) .map { (module, usageInfo) -> PackageSearchOperation.Package.Remove( model = packageModel.toUnifiedDependency(usageInfo.declaredVersion, usageInfo.scope), projectModule = module.projectModule, currentVersion = version, currentScope = scope ) } } private fun usagesByModule(targetModules: TargetModules, packageModel: PackageModel.Installed) = targetModules.flatMap { module -> packageModel.usageInfo.filter { usageInfo -> usageInfo.projectModule == module.projectModule } .map { usageInfo -> module to usageInfo } } private fun createAddRepositoryOperation( repoToInstall: RepositoryModel, projectModule: ProjectModule ) = PackageSearchOperation.Repository.Install( model = repoToInstall.toUnifiedRepository(), projectModule = projectModule ) }
apache-2.0
d63523f4d302c9be3eb701713ae9e91b
41.58547
148
0.66292
6.302973
false
false
false
false
JetBrains/intellij-community
platform/diagnostic/src/startUpPerformanceReporter/IdeThreadNameManager.kt
1
1833
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. @file:Suppress("ConstPropertyName") package com.intellij.diagnostic.startUpPerformanceReporter import com.intellij.diagnostic.ActivityImpl import com.intellij.diagnostic.ThreadNameManager import it.unimi.dsi.fastutil.longs.Long2ObjectOpenHashMap private const val pooledPrefix = "ApplicationImpl pooled thread " private val regex = Regex(" *@[a-z ]+#\\d+$") internal class IdeThreadNameManager : ThreadNameManager { // ConcurrencyUtil.runUnderThreadName is used in our code (to make thread dumps more clear) and changes thread name, // so, use first thread name that associated with thread and not subsequent one private val idToName = Long2ObjectOpenHashMap<String>() override fun getThreadName(event: ActivityImpl): String { var result = idToName.get(event.threadId) if (result != null) { return result } var name = event.threadName if (name.endsWith(']') && name.contains(pooledPrefix)) { val lastOpen = name.lastIndexOf('[') if (lastOpen > 0) { name = name.substring(lastOpen + 1, name.length - 1) } } result = when { name.startsWith("JobScheduler FJ pool ") -> name.replace("JobScheduler FJ pool ", "fj ") name.startsWith("DefaultDispatcher-worker-") -> name.replace("DefaultDispatcher-worker-", "d ") name.startsWith("AWT-EventQueue-") -> "edt" name.startsWith("Idea Main Thread") -> "idea main" name.startsWith(pooledPrefix) -> name.replace(pooledPrefix, "pooled ") name.startsWith("StatisticsFileEventLogger: ") -> "StatFileEventLogger" else -> name } //main @coroutine#4946 result = result.replace(regex, "") idToName.put(event.threadId, result) return result } }
apache-2.0
9e9ae88009b009e0582d9a1f31d1543e
38.021277
120
0.705401
4.233256
false
false
false
false
vhromada/Catalog
core/src/main/kotlin/com/github/vhromada/catalog/controller/MusicController.kt
1
3725
package com.github.vhromada.catalog.controller import com.github.vhromada.catalog.common.entity.Page import com.github.vhromada.catalog.entity.ChangeMusicRequest import com.github.vhromada.catalog.entity.Music import com.github.vhromada.catalog.entity.MusicStatistics import com.github.vhromada.catalog.facade.MusicFacade import com.github.vhromada.catalog.filter.NameFilter import org.springframework.http.HttpStatus import org.springframework.web.bind.annotation.DeleteMapping import org.springframework.web.bind.annotation.GetMapping import org.springframework.web.bind.annotation.PathVariable import org.springframework.web.bind.annotation.PostMapping import org.springframework.web.bind.annotation.PutMapping import org.springframework.web.bind.annotation.RequestBody import org.springframework.web.bind.annotation.RequestMapping import org.springframework.web.bind.annotation.ResponseStatus import org.springframework.web.bind.annotation.RestController /** * A class represents controller for music. * * @author Vladimir Hromada */ @RestController("musicController") @RequestMapping("rest/music") class MusicController( /** * Facade for music */ private val facade: MusicFacade ) { /** * Returns list of music for filter. * * @param filter filter * @return list of music for filter */ @GetMapping fun search(filter: NameFilter): Page<Music> { return facade.search(filter = filter) } /** * Returns music. * <br></br> * Validation errors: * * * Music doesn't exist in data storage * * @param id ID * @return music */ @GetMapping("{id}") fun get(@PathVariable("id") id: String): Music { return facade.get(uuid = id) } /** * Adds music. * <br></br> * Validation errors: * * * Name is null * * Name is empty string * * Count of media is null * * Count of media isn't positive number * * @param request request for changing music * @return added music */ @PutMapping @ResponseStatus(HttpStatus.CREATED) fun add(@RequestBody request: ChangeMusicRequest): Music { return facade.add(request = request) } /** * Updates music. * <br></br> * Validation errors: * * * Name is null * * Name is empty string * * Count of media is null * * Count of media isn't positive number * * Music doesn't exist in data storage * * @param id ID * @param request request for changing music * @return updated music */ @PostMapping("{id}") fun update( @PathVariable("id") id: String, @RequestBody request: ChangeMusicRequest ): Music { return facade.update(uuid = id, request = request) } /** * Removes music. * <br></br> * Validation errors: * * * Music doesn't exist in data storage * * @param id ID */ @DeleteMapping("{id}") @ResponseStatus(HttpStatus.NO_CONTENT) fun remove(@PathVariable("id") id: String) { facade.remove(uuid = id) } /** * Duplicates music. * <br></br> * Validation errors: * * * Music doesn't exist in data storage * * @param id ID * @return duplicated music */ @PostMapping("{id}/duplicate") @ResponseStatus(HttpStatus.CREATED) fun duplicate(@PathVariable("id") id: String): Music { return facade.duplicate(uuid = id) } /** * Returns statistics. * * @return statistics */ @GetMapping("statistics") fun getStatistics(): MusicStatistics { return facade.getStatistics() } }
mit
3454e836bf608611f5773ad626c3ff4f
25.048951
62
0.639732
4.247434
false
false
false
false
Atsky/haskell-idea-plugin
plugin/src/org/jetbrains/yesod/julius/completion/JuliusCompletionContributor.kt
1
7977
package org.jetbrains.yesod.julius.completion /** * @author Leyla H */ import com.intellij.codeInsight.completion.CompletionContributor import com.intellij.codeInsight.completion.CompletionParameters import com.intellij.codeInsight.completion.CompletionResultSet import com.intellij.codeInsight.completion.CompletionType import com.intellij.codeInsight.lookup.LookupElementBuilder import java.util.Arrays class JuliusCompletionContributor : CompletionContributor() { override fun fillCompletionVariants(parameters: CompletionParameters, result: CompletionResultSet) { if (parameters.completionType === CompletionType.BASIC) { for (tagName in KEYWORDS) { result.addElement(LookupElementBuilder.create(tagName)) } for (tagName in AJAX_FUNCTIONS) { result.addElement(LookupElementBuilder.create(tagName)) } for (tagName in AJAX_SETTINGS) { result.addElement(LookupElementBuilder.create(tagName)) } for (tagName in JS_FUNCTIONS) { result.addElement(LookupElementBuilder.create(tagName)) } } } companion object { var KEYWORDS: List<String> = Arrays.asList( "abstract", "arguments", "boolean", "break", "byte", "case", "catch", "char", "class", "const", "continue", "debugger", "default", "delete", "do", "double", "else", "enum", "eval", "export", "extends", "false", "final", "finally", "float", "for", "function", "goto", "if", "implements", "import", "in", "instanceof", "int", "interface", "let", "long", "native", "new", "null", "package", "private", "protected", "public", "return", "short", "static", "super", "switch", "synchronized", "this", "throw", "throws", "transient", "true", "try", "typeof", "var", "void", "volatile", "while", "with", "yield" ) var AJAX_SETTINGS: List<String> = Arrays.asList( "ajax", "accepts", "async", "beforeSend", "cache", "complete", "contents", "contentType", "context", "converters", "crossDomain", "data", "dataFilter", "dataType", "error", "global", "headers", "ifModified", "isLocal", "jsonp", "jsonpCallback", "mimeType", "password", "processData", "scriptCharset", "statusCode", "success", "timeout", "traditional", "type", "url", "username", "xhr", "xhrFields", "xml", "html", "script", "json", "text" ) var AJAX_FUNCTIONS: List<String> = Arrays.asList( "jQuery.ajax", "ajaxComplete", "ajaxError", "ajaxSend", "jQuery.ajaxSetup", "ajaxStart", "ajaxStop", "ajaxSuccess", "jQuery.get", "jQuery.getJSON", "jQuery.getScript" ) var JS_FUNCTIONS: List<String> = Arrays.asList( "anchor", "apply", "alert", "atEnd", "big", "bind", "blink", "bold", "call", "charAt", "charCodeAt", "compile", "concat", "dimensions", "every", "exec", "filter", "fixed", "fontcolor", "fontsize", "forEach", "getDate", "getDay", "getFullYear", "getHours", "getItem", "getMilliseconds", "getMinutes", "getMonth", "getSeconds", "getTime", "getTimezoneOffset", "getUTCDate", "getUTCDay", "getUTCFullYear", "getUTCHours", "getUTCMilliseconds", "getUTCMinutes", "getUTCMonth", "getUTCSeconds", "getVarDate", "getYear", "hasOwnProperty", "indexOf", "isPrototypeOf", "italics", "item", "join", "lastIndexOf", "lbound", "link", "localeCompare", "map", "match", "moveFirst", "moveNext", "pop", "propertyIsEnumerable", "push", "reduce", "reduceRight", "replace", "reverse", "search", "setDate", "setFullYear", "setHours", "setMilliseconds", "setMinutes", "setMonth", "setSeconds", "setTime", "setUTCDate", "setUTCFullYear", "setUTCHours", "setUTCMilliseconds", "setUTCMinutes", "setUTCMonth", "setUTCSeconds", "setYear", "shift", "slice", "small", "some", "sort", "splice", "split", "strike", "sub", "substr", "substring", "sup", "test", "toArray", "toDateString", "toExponential", "toFixed", "toGMTString", "toISOString", "toJSON", "toLocaleDateString", "toLocaleLowerCase", "toLocaleString", "toLocaleTimeString", "toLocaleUpperCase", "toLowerCase", "toPrecision", "toString", "toTimeString", "toUpperCase", "toUTCString", "trim", "ubound", "unshift", "valueOf", "abs", "acos", "asin", "atan", "atan2", "ceil", "cos", "create", "decodeURI", "decodeURIComponent", "defineProperties", "defineProperty", "encodeURI", "encodeURIComponent", "escape", "eval", "exp", "floor", "freeze", "fromCharCode", "GetObject", "getOwnPropertyDescriptor", "getOwnPropertyNames", "getPrototypeOf", "isArray", "isExtensible", "isFinite", "isFrozen", "isNaN", "isSealed", "keys", "log", "max", "min", "now", "parse", "parseFloat", "parseInt", "pow", "preventExtensions", "random", "round", "ScriptEngine", "ScriptEngineBuildVersion", "ScriptEngineMajorVersion", "ScriptEngineMinorVersion", "seal", "sin", "sqrt", "stringify", "tan", "unescape", "UTC", "write", "writeln" ) } }
apache-2.0
4a5ff1d5a4d968a772cfc7fa5203f22a
58.088889
105
0.401404
5.213725
false
false
false
false
JetBrains/intellij-community
platform/workspaceModel/storage/src/com/intellij/workspaceModel/storage/impl/external/ExternalEntityMappingImpl.kt
1
8425
// 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.workspaceModel.storage.impl.external import com.google.common.collect.HashBiMap import com.intellij.openapi.diagnostic.logger import com.intellij.openapi.diagnostic.trace import com.intellij.workspaceModel.storage.* import com.intellij.workspaceModel.storage.impl.* import com.intellij.workspaceModel.storage.impl.containers.BidirectionalMap import java.util.* internal open class ExternalEntityMappingImpl<T> internal constructor(internal open val index: BidirectionalMap<EntityId, T>) : ExternalEntityMapping<T> { protected lateinit var entityStorage: AbstractEntityStorage override fun getEntities(data: T): List<WorkspaceEntity> { return index.getKeysByValue(data)?.mapNotNull { entityStorage.entityDataById(it)?.createEntity(entityStorage) } ?: emptyList() } override fun getFirstEntity(data: T): WorkspaceEntity? { return index.getKeysByValue(data)?.firstOrNull()?.let { entityStorage.entityDataById(it)?.createEntity(entityStorage) } } override fun getDataByEntity(entity: WorkspaceEntity): T? { entity as WorkspaceEntityBase return getDataByEntityId(entity.id) } internal fun getDataByEntityId(entityId: EntityId): T? { return index[entityId] } override fun size(): Int = index.size internal fun setTypedEntityStorage(storage: AbstractEntityStorage) { entityStorage = storage } override fun forEach(action: (key: WorkspaceEntity, value: T) -> Unit) { index.forEach { (key, value) -> action(entityStorage.entityDataByIdOrDie(key).createEntity(entityStorage), value) } } } internal class MutableExternalEntityMappingImpl<T> private constructor( // Do not write to [index] directly! Create a method in this index and call [startWrite] before write. override var index: BidirectionalMap<EntityId, T>, internal var indexLogBunches: IndexLog, private var freezed: Boolean ) : ExternalEntityMappingImpl<T>(index), MutableExternalEntityMapping<T> { constructor() : this(BidirectionalMap<EntityId, T>(), IndexLog(mutableListOf()), false) override fun addMapping(entity: WorkspaceEntity, data: T) { startWrite() add((entity as WorkspaceEntityBase).id, data) (entityStorage as MutableEntityStorageImpl).incModificationCount() } internal fun add(id: EntityId, data: T) { startWrite() index[id] = data indexLogBunches.add(id, IndexLogRecord.Add(id, data)) LOG.trace { try { "Adding to external index: ${id.asString()} -> $data. Data hash: ${data.hashCode()}" } catch (e: Throwable) { "Adding to external index. ${id.asString()}, cannot get data info. ${e.message}" } } } override fun addIfAbsent(entity: WorkspaceEntity, data: T): Boolean { startWrite() entity as WorkspaceEntityBase return if (entity.id !in index) { add(entity.id, data) true } else false } override fun getOrPutDataByEntity(entity: WorkspaceEntity, defaultValue: () -> T): T { return getDataByEntity(entity) ?: run { startWrite() val defaultVal = defaultValue() add((entity as WorkspaceEntityBase).id, defaultVal) defaultVal } } override fun removeMapping(entity: WorkspaceEntity): T? { startWrite() entity as WorkspaceEntityBase val removed = remove(entity.id) (entityStorage as MutableEntityStorageImpl).incModificationCount() return removed } internal fun clearMapping() { startWrite() index.clear() indexLogBunches.clear() } internal fun remove(id: EntityId): T? { startWrite() LOG.trace { "Remove $id from external index" } val removed = index.remove(id) indexLogBunches.add(id, IndexLogRecord.Remove(id)) return removed } fun applyChanges(other: MutableExternalEntityMappingImpl<*>, replaceMap: HashBiMap<NotThisEntityId, ThisEntityId>, target: MutableEntityStorageImpl) { other.indexLogBunches.chain.forEach { operation -> when (operation) { is IndexLogOperation.Changes -> { operation.changes.values.forEach { record -> when (record) { is IndexLogRecord.Add<*> -> { getTargetId(replaceMap, target, record.id)?.let { entityId -> @Suppress("UNCHECKED_CAST") add(entityId, record.data as T) } } is IndexLogRecord.Remove -> { remove(record.id) } } } } IndexLogOperation.Clear -> { clearMapping() } } } } private fun getTargetId(replaceMap: HashBiMap<NotThisEntityId, ThisEntityId>, target: MutableEntityStorageImpl, id: EntityId): EntityId? { val possibleTargetId = replaceMap[id.notThis()] if (possibleTargetId != null) return possibleTargetId.id if (target.entityDataById(id) == null) return null // It's possible that before addDiff there was a gup in this particular id. If it's so, replaceMap should not have a mapping to it val sourceId = replaceMap.inverse()[id.asThis()] return if (sourceId != null) null else id } private fun startWrite() { if (!freezed) return this.index = this.index.copy() this.indexLogBunches = IndexLog(this.indexLogBunches.chain.mapTo(ArrayList()) { if (it is IndexLogOperation.Changes) IndexLogOperation.Changes(LinkedHashMap(it.changes)) else it }) this.freezed = false } private fun toImmutable(): ExternalEntityMappingImpl<T> { this.freezed = true return ExternalEntityMappingImpl(this.index) } internal sealed class IndexLogRecord { data class Add<T>(val id: EntityId, val data: T) : IndexLogRecord() data class Remove(val id: EntityId) : IndexLogRecord() } internal sealed interface IndexLogOperation { data class Changes(val changes: LinkedHashMap<EntityId, IndexLogRecord>) : IndexLogOperation object Clear : IndexLogOperation } internal class IndexLog( val chain: MutableList<IndexLogOperation>, ) { fun add(id: EntityId, operation: IndexLogRecord) { var lastBunch = chain.lastOrNull() if (lastBunch !is IndexLogOperation.Changes) { chain.add(IndexLogOperation.Changes(LinkedHashMap())) lastBunch = chain.last() } lastBunch as IndexLogOperation.Changes val existing = lastBunch.changes[id] if (existing != null) { when (operation) { is IndexLogRecord.Add<*> -> { lastBunch.changes.remove(id) lastBunch.changes[id] = operation } is IndexLogRecord.Remove -> { if (existing is IndexLogRecord.Add<*>) { lastBunch.changes.remove(id) } else { lastBunch.changes[id] = operation } } } } else { lastBunch.changes[id] = operation } } fun clear() { chain.add(IndexLogOperation.Clear) } } companion object { fun fromMap(other: Map<String, ExternalEntityMappingImpl<*>>): MutableMap<String, MutableExternalEntityMappingImpl<*>> { val result = mutableMapOf<String, MutableExternalEntityMappingImpl<*>>() other.forEach { (identifier, index) -> if (index is MutableExternalEntityMappingImpl) index.freezed = true result[identifier] = MutableExternalEntityMappingImpl(index.index, IndexLog(mutableListOf()), true) } return result } fun toImmutable(other: MutableMap<String, MutableExternalEntityMappingImpl<*>>): Map<String, ExternalEntityMappingImpl<*>> { val result = mutableMapOf<String, ExternalEntityMappingImpl<*>>() other.forEach { (identifier, index) -> result[identifier] = index.toImmutable() } return Collections.unmodifiableMap(result) } private val LOG = logger<MutableExternalEntityMappingImpl<*>>() } } internal object EmptyExternalEntityMapping : ExternalEntityMapping<Any> { override fun getEntities(data: Any): List<WorkspaceEntity> = emptyList() override fun getFirstEntity(data: Any): WorkspaceEntity? = null override fun getDataByEntity(entity: WorkspaceEntity): Any? = null override fun forEach(action: (key: WorkspaceEntity, value: Any) -> Unit) {} override fun size(): Int = 0 }
apache-2.0
427d13dd4fd0b7f74c29c18dfd39d1b9
33.81405
140
0.680237
4.792378
false
false
false
false
spacecowboy/Feeder
app/src/main/java/com/nononsenseapps/feeder/util/LinkUtils.kt
1
1751
package com.nononsenseapps.feeder.util import java.net.MalformedURLException import java.net.URL /** * Ensures a url is valid, having a scheme and everything. It turns 'google.com' into 'http://google.com' for example. */ fun sloppyLinkToStrictURL(url: String): URL = try { // If no exception, it's valid URL(url) } catch (_: MalformedURLException) { URL("http://$url") } /** * Returns a URL but does not guarantee that it accurately represents the input string if the input string is an invalid URL. * This is used to ensure that migrations to versions where Feeds have URL and not strings don't crash. */ fun sloppyLinkToStrictURLNoThrows(url: String): URL = try { sloppyLinkToStrictURL(url) } catch (_: MalformedURLException) { sloppyLinkToStrictURL("") } /** * On error, this method simply returns the original link. It does *not* throw exceptions. */ fun relativeLinkIntoAbsolute(base: URL, link: String): String = try { // If no exception, it's valid relativeLinkIntoAbsoluteOrThrow(base, link).toString() } catch (_: MalformedURLException) { link } /** * On error, this method simply returns the original link. It does *not* throw exceptions. */ fun relativeLinkIntoAbsoluteOrNull(base: URL, link: String?): String? = try { // If no exception, it's valid if (link != null) { relativeLinkIntoAbsoluteOrThrow(base, link).toString() } else { null } } catch (_: MalformedURLException) { link } /** * On error, throws MalformedURLException. */ @Throws(MalformedURLException::class) fun relativeLinkIntoAbsoluteOrThrow(base: URL, link: String): URL = try { // If no exception, it's valid URL(link) } catch (_: MalformedURLException) { URL(base, link) }
gpl-3.0
7b31f9e4326fb0b693b68c88380c875d
28.677966
125
0.699029
4.169048
false
false
false
false
StepicOrg/stepik-android
app/src/main/java/org/stepik/android/cache/lesson/structure/DbStructureLesson.kt
2
2454
package org.stepik.android.cache.lesson.structure import androidx.sqlite.db.SupportSQLiteDatabase object DbStructureLesson { const val TABLE_NAME = "lesson" object Columns { const val ID = "id" const val TITLE = "title" const val SLUG = "slug" const val COVER_URL = "cover_url" const val COURSES = "courses" const val STEPS = "steps" const val ACTIONS = "actions" const val IS_FEATURED = "is_featured" const val PROGRESS = "progress" const val OWNER = "owner" const val SUBSCRIPTIONS = "subscriptions" const val VIEWED_BY = "viewed_by" const val PASSED_BY = "passed_by" const val VOTE_DELTA = "vote_delta" const val LANGUAGE = "language" const val IS_PUBLIC = "is_public" const val CREATE_DATE = "create_date" const val UPDATE_DATE = "update_date" const val LEARNERS_GROUP = "learners_group" const val TEACHERS_GROUP = "teachers_group" const val TIME_TO_COMPLETE = "time_to_complete" const val UNITS = "units" } fun createTable(db: SupportSQLiteDatabase) { db.execSQL(""" CREATE TABLE IF NOT EXISTS $TABLE_NAME ( ${DbStructureLesson.Columns.ID} LONG PRIMARY KEY, ${DbStructureLesson.Columns.TITLE} TEXT, ${DbStructureLesson.Columns.SLUG} TEXT, ${DbStructureLesson.Columns.COVER_URL} TEXT, ${DbStructureLesson.Columns.STEPS} TEXT, ${DbStructureLesson.Columns.IS_FEATURED} INTEGER, ${DbStructureLesson.Columns.PROGRESS} TEXT, ${DbStructureLesson.Columns.OWNER} LONG, ${DbStructureLesson.Columns.SUBSCRIPTIONS} TEXT, ${DbStructureLesson.Columns.VIEWED_BY} LONG, ${DbStructureLesson.Columns.PASSED_BY} LONG, ${DbStructureLesson.Columns.VOTE_DELTA} LONG, ${DbStructureLesson.Columns.LANGUAGE} TEXT, ${DbStructureLesson.Columns.IS_PUBLIC} INTEGER, ${DbStructureLesson.Columns.CREATE_DATE} LONG, ${DbStructureLesson.Columns.UPDATE_DATE} LONG, ${DbStructureLesson.Columns.LEARNERS_GROUP} TEXT, ${DbStructureLesson.Columns.TEACHERS_GROUP} TEXT, ${DbStructureLesson.Columns.TIME_TO_COMPLETE} LONG ) """.trimIndent()) } }
apache-2.0
363e3c0c49f2befff93a6d181e22cd7d
41.327586
66
0.601874
4.604128
false
false
false
false
envoyproxy/envoy-mobile
test/kotlin/integration/SendHeadersTest.kt
2
3118
package test.kotlin.integration import io.envoyproxy.envoymobile.Custom import io.envoyproxy.envoymobile.EngineBuilder import io.envoyproxy.envoymobile.RequestHeadersBuilder import io.envoyproxy.envoymobile.RequestMethod import io.envoyproxy.envoymobile.ResponseHeaders import io.envoyproxy.envoymobile.UpstreamHttpProtocol import io.envoyproxy.envoymobile.engine.JniLibrary import java.util.concurrent.CountDownLatch import java.util.concurrent.TimeUnit import org.assertj.core.api.Assertions.assertThat import org.assertj.core.api.Assertions.fail import org.junit.Test private val apiListenerType = "type.googleapis.com/envoy.extensions.filters.network.http_connection_manager.v3.EnvoyMobileHttpConnectionManager" private val assertionFilterType = "type.googleapis.com/envoymobile.extensions.filters.http.assertion.Assertion" private val config = """ static_resources: listeners: - name: base_api_listener address: socket_address: protocol: TCP address: 0.0.0.0 port_value: 10000 api_listener: api_listener: "@type": $apiListenerType config: stat_prefix: hcm route_config: name: api_router virtual_hosts: - name: api domains: - "*" routes: - match: prefix: "/" direct_response: status: 200 http_filters: - name: envoy.filters.http.assertion typed_config: "@type": $assertionFilterType match_config: http_request_headers_match: headers: - name: ":authority" exact_match: example.com - name: envoy.router typed_config: "@type": type.googleapis.com/envoy.extensions.filters.http.router.v3.Router """ class SendHeadersTest { init { JniLibrary.loadTestLibrary() } @Test fun `successful sending of request headers`() { val headersExpectation = CountDownLatch(1) val engine = EngineBuilder(Custom(config)).build() val client = engine.streamClient() val requestHeaders = RequestHeadersBuilder( method = RequestMethod.GET, scheme = "https", authority = "example.com", path = "/test" ) .addUpstreamHttpProtocol(UpstreamHttpProtocol.HTTP2) .build() var resultHeaders: ResponseHeaders? = null var resultEndStream: Boolean? = null client.newStreamPrototype() .setOnResponseHeaders { responseHeaders, endStream, _ -> resultHeaders = responseHeaders resultEndStream = endStream headersExpectation.countDown() } .setOnError { _, _ -> fail("Unexpected error") } .start() .sendHeaders(requestHeaders, true) headersExpectation.await(10, TimeUnit.SECONDS) engine.terminate() assertThat(headersExpectation.count).isEqualTo(0) assertThat(resultHeaders!!.httpStatus).isEqualTo(200) assertThat(resultEndStream).isTrue() } }
apache-2.0
b13be197942b0b1a3db8331b15ccb344
29.871287
144
0.646248
4.717095
false
true
false
false
allotria/intellij-community
platform/lang-impl/src/com/intellij/codeInsight/hints/presentation/InlayTextMetrics.kt
2
3608
// 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.codeInsight.hints.presentation import com.intellij.ide.ui.AntialiasingType import com.intellij.openapi.editor.Editor import com.intellij.openapi.editor.impl.EditorImpl import com.intellij.openapi.editor.impl.FontInfo import com.intellij.util.concurrency.annotations.RequiresEdt import com.intellij.util.ui.UIUtil import java.awt.Font import java.awt.FontMetrics import java.awt.RenderingHints import java.awt.font.FontRenderContext import kotlin.math.ceil import kotlin.math.max internal class InlayTextMetricsStorage(val editor: EditorImpl) { private var smallTextMetrics : InlayTextMetrics? = null private var normalTextMetrics : InlayTextMetrics? = null val smallTextSize: Int @RequiresEdt get() = max(1, editor.colorsScheme.editorFontSize - 1) val normalTextSize: Int @RequiresEdt get() = editor.colorsScheme.editorFontSize @RequiresEdt fun getFontMetrics(small: Boolean): InlayTextMetrics { var metrics: InlayTextMetrics? if (small) { metrics = smallTextMetrics val fontSize = smallTextSize if (metrics == null || !metrics.isActual(smallTextSize)) { metrics = InlayTextMetrics.create(editor, fontSize) smallTextMetrics = metrics } } else { metrics = normalTextMetrics val fontSize = normalTextSize if (metrics == null || !metrics.isActual(normalTextSize)) { metrics = InlayTextMetrics.create(editor, fontSize) normalTextMetrics = metrics } } return metrics } } internal class InlayTextMetrics( private val editor: EditorImpl, val fontHeight: Int, val fontBaseline: Int, private val fontMetrics: FontMetrics ) { companion object { fun create(editor: EditorImpl, size: Int) : InlayTextMetrics { val familyName = UIUtil.getLabelFont().family val font = UIUtil.getFontWithFallback(familyName, Font.PLAIN, size) val context = getCurrentContext(editor) val metrics = FontInfo.getFontMetrics(font, context) // We assume this will be a better approximation to a real line height for a given font val fontHeight = ceil(font.createGlyphVector(context, "Albpq@").visualBounds.height).toInt() val fontBaseline = ceil(font.createGlyphVector(context, "Alb").visualBounds.height).toInt() return InlayTextMetrics(editor, fontHeight, fontBaseline, metrics) } private fun getCurrentContext(editor: Editor): FontRenderContext { val editorContext = FontInfo.getFontRenderContext(editor.contentComponent) return FontRenderContext(editorContext.transform, AntialiasingType.getKeyForCurrentScope(false), if (editor is EditorImpl) editor.myFractionalMetricsHintValue else RenderingHints.VALUE_FRACTIONALMETRICS_OFF) } } val font: Font get() = fontMetrics.font // Editor metrics: val ascent: Int get() = editor.ascent val descent: Int get() = editor.descent fun isActual(size: Int) : Boolean { if (size != font.size) return false return getCurrentContext(editor).equals(fontMetrics.fontRenderContext) } /** * Offset from the top edge of drawing rectangle to rectangle with text. */ fun offsetFromTop(): Int = (editor.lineHeight - fontHeight) / 2 fun getStringWidth(text: String): Int { return fontMetrics.stringWidth(text) } }
apache-2.0
f4a1f534d87e620c8375e3a312d392af
34.038835
140
0.705377
4.697917
false
false
false
false
code-helix/slatekit
src/lib/kotlin/slatekit-common/src/main/kotlin/slatekit/common/data/Connections.kt
1
2063
/** * <slate_header> * url: www.slatekit.com * git: www.github.com/code-helix/slatekit * org: www.codehelix.co * author: Kishore Reddy * copyright: 2016 CodeHelix Solutions Inc. * license: refer to website and/or github * about: A tool-kit, utility library and server-backend * mantra: Simplicity above all else * </slate_header> */ package slatekit.common.data import slatekit.common.conf.Conf /** * Lookup for database connections. Supports a default connection * 1. default connection: { connectionString } * 2. named connection : "qa1" -> {connectionString} * 3. grouped shard : ( group="usa", shard="01" ) -> { connectionString } */ class Connections( private val defaultCon: DbCon? = null, private val names: Map<String, DbCon>? = null, private val groups: Map<String, Map<String, DbCon>>? = null ) { /** * Gets the default database connection * * @return */ fun default(): DbCon? = defaultCon /** * Gets a named database connection * * @param key * @return */ fun named(key: String): DbCon? = names?.let { map -> map[key] } /** * Gets a named database connection * * @param key * @return */ fun group(groupName: String, key: String): DbCon? = groups?.let { gs -> gs[groupName]?.let { g -> g[key] } } companion object { /** * Creates a database lookup with just the default connection * * @param con * @return */ @JvmStatic fun of(con: DbCon): Connections { val db = Connections(defaultCon = con) return db } @JvmStatic fun from(cls:Class<*>, conf: Conf):Connections { return of(conf.dbCon("db")) } /** * Creates a database lookup with just named databases * * @param items * @return */ @JvmStatic fun named(items: List<Pair<String, DbCon>>): Connections { val named = items.map { item -> item.first to item.second }.toMap() val db = Connections(names = named) return db } } }
apache-2.0
bfdb259638835ab1b22cfb560979d715
21.423913
78
0.601066
3.848881
false
false
false
false
HTWDD/HTWDresden
app/src/main/java/de/htwdd/htwdresden/utils/holders/StringHolder.kt
1
759
package de.htwdd.htwdresden.utils.holders import android.content.Context import androidx.annotation.ArrayRes import androidx.annotation.StringRes import kotlin.properties.Delegates class StringHolder private constructor() { private var ctx: Context by Delegates.notNull() private object Holder { val INSTANCE = StringHolder() } companion object { val instance: StringHolder by lazy { Holder.INSTANCE } fun init(context: Context) { instance.ctx = context.applicationContext } } fun getString(@StringRes id: Int) = ctx.getString(id) fun getString(@StringRes id: Int, vararg params: Any) = ctx.getString(id, *params) fun getStringArray(@ArrayRes id: Int) = ctx.resources.getStringArray(id) }
mit
726090f6d3a2208c5b329bc9f600fdc9
29.4
86
0.722003
4.54491
false
false
false
false
smmribeiro/intellij-community
plugins/kotlin/idea/tests/testData/formatter/EmptyLineBetweeMultilineDeclarationTwo.after.kt
5
3508
interface Some { fun f1() fun f2() fun f3() /* test */ fun f4() /* test */ fun f5() /** * test * 2 */ fun f6() fun f7() @NotNull fun f8() fun f9() } interface Some2 { fun f1() fun f2() fun f3() @Ann fun f4() @Ann fun f5() @Ann( 42 ) fun f6() fun f7() @NotNull fun f8() fun f9() } abstract class Abstract() { abstract fun f1() abstract fun f2() // test abstract fun f3() // test /* test */ abstract fun f4() abstract fun f5() abstract fun f6() /* test */ abstract fun f7() } abstract class Abstract() { abstract fun f1() abstract fun f2() @Ann abstract fun f3() @Ann @Ann abstract fun f4() abstract fun f5() abstract fun f6() @Ann abstract fun f7() } fun f1() {} class C1 {} // ----- fun f2() {} class C2 // ----- // test fun f3 = 1 class C3 {} // ----- /*test*/ fun f4 = 2 class C4 // ----- @Ann fun f3 = 1 class C3 {} // ----- @Ann fun f4 = 2 class C4 // ----- class C5 {} fun f5() {} // ----- class C6 fun f6() {} // ----- class C7 {} fun f7 = 1 // ----- class D { } class E : Some class F @Ann fun some() = 1 class G fun some() = 1 val a = 1 class H val b = 1 // No lines fun f1() {} val p1 = 1 fun f2() {} @Ann fun f3() = 1 val p2 = 1 fun f4() = 1 fun f4() {} val p3: Int get() = 1 fun f5() = 1 class OneLine { fun f1() {} val p1 = 1 fun f2() {} fun f3() = 1 val p2 = 1 fun f4() = 1 fun f4() {} val p3: Int get() = 1 fun f5() = 1 } class TwoLines { fun f1() {} val p1 = 1 fun f2() {} fun f3() = 1 val p2 = 1 fun f4() = 1 fun f4() {} val p3: Int get() = 1 fun f5() = 1 } // No lines between fun f2() {} fun f1() {} fun f3() = 1 fun f4() {} fun f5() { } fun f6() = 1 fun f7() = 8 // One line fun f2() {} fun f1() {} fun f3() = 1 fun f4() {} fun f5() { } fun f6() = 1 fun f7() = 8 // test fun f8() = 42 // Two lines between fun l1() {} fun l2() {} fun l3() = 1 fun l4() {} fun l5() { } fun l6() = 1 fun l7() = 8 // test val p1 by Some val p2 = 1 val p3: Int get() = 3 val p4: Int get() { return 1 } val p5: Int class OneLine { val p1 by Some val p2 = 1 val p3: Int get() = 3 val p4: Int get() { return 1 } val p5: Int } class TwoLines { val p1 by Some val p2 = 1 val p3: Int get() = 3 val p4: Int get() { return 1 } val p5: Int } class Some(b: Boolean) { // Comment. constructor(b: Int) : this(b == 0) /** * test * 2 */ constructor(b: String) : this(b.isEmpty()) constructor(b: Long) : this(b == 0L) @Ann constructor(b: Int) : this(b == 0) @Ann( 42 ) constructor(b: String) : this(b.isEmpty()) constructor(b: Long) : this(b == 0L) } enum class TestEnum { /** A comment for the item #1. */ ITEM1, /** A comment for the item #2. */ ITEM2, /** A comment for the item #3. */ ITEM3 } class Foo { @Inject lateinit var logger: Logger @Inject lateinit var userService: UserService @Inject override lateinit var configBridge: ConfigBridge } // SET_INT: BLANK_LINES_BEFORE_DECLARATION_WITH_COMMENT_OR_ANNOTATION_ON_SEPARATE_LINE = 2
apache-2.0
19beb377a11c6d70e5ea4744813fd073
8.332447
90
0.464082
2.775316
false
false
false
false
smmribeiro/intellij-community
plugins/kotlin/idea/tests/testData/unifier/equivalence/controlStructures/whileRuntime.kt
13
336
fun foo(a: Int, b: Int) { var t = a <selection>while (t != (a + b)) { println(t) t++ }</selection> var u = a while (u != a + b) { println(t) t++ } do { println(t) t++ } while (t != a + b) while (t != a + b) { println((t)) t++ } }
apache-2.0
1b8c9f6d992bbfc742ee5a0ca93c0df2
13.652174
37
0.333333
3.027027
false
false
false
false
smmribeiro/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/refactoring/pullUp/KotlinPullUpHelper.kt
2
32469
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.refactoring.pullUp import com.intellij.psi.* import com.intellij.psi.codeStyle.JavaCodeStyleManager import com.intellij.psi.impl.light.LightField import com.intellij.psi.search.GlobalSearchScope import com.intellij.refactoring.classMembers.MemberInfoBase import com.intellij.refactoring.memberPullUp.PullUpData import com.intellij.refactoring.memberPullUp.PullUpHelper import com.intellij.refactoring.util.RefactoringUtil import org.jetbrains.kotlin.asJava.getRepresentativeLightMethod import org.jetbrains.kotlin.asJava.namedUnwrappedElement import org.jetbrains.kotlin.asJava.toLightClass import org.jetbrains.kotlin.asJava.unwrapped import org.jetbrains.kotlin.descriptors.* import org.jetbrains.kotlin.idea.KotlinLanguage import org.jetbrains.kotlin.idea.codeInsight.shorten.addToShorteningWaitSet import org.jetbrains.kotlin.idea.core.dropDefaultValue import org.jetbrains.kotlin.idea.core.getOrCreateCompanionObject import org.jetbrains.kotlin.idea.core.replaced import org.jetbrains.kotlin.idea.core.setType import org.jetbrains.kotlin.idea.inspections.CONSTRUCTOR_VAL_VAR_MODIFIERS import org.jetbrains.kotlin.idea.refactoring.createJavaField import org.jetbrains.kotlin.idea.refactoring.dropOverrideKeywordIfNecessary import org.jetbrains.kotlin.idea.refactoring.isAbstract import org.jetbrains.kotlin.idea.refactoring.isCompanionMemberOf import org.jetbrains.kotlin.idea.refactoring.memberInfo.KtPsiClassWrapper import org.jetbrains.kotlin.idea.refactoring.memberInfo.toKtDeclarationWrapperAware import org.jetbrains.kotlin.idea.refactoring.safeDelete.removeOverrideModifier import org.jetbrains.kotlin.idea.util.anonymousObjectSuperTypeOrNull import org.jetbrains.kotlin.idea.util.hasComments import org.jetbrains.kotlin.idea.util.psi.patternMatching.KotlinPsiUnifier import org.jetbrains.kotlin.idea.util.reformatted import org.jetbrains.kotlin.lexer.KtModifierKeywordToken import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.name.Name import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.* import org.jetbrains.kotlin.resolve.BindingContext import org.jetbrains.kotlin.resolve.DescriptorUtils import org.jetbrains.kotlin.resolve.calls.callUtil.getResolvedCall import org.jetbrains.kotlin.resolve.calls.resolvedCallUtil.getExplicitReceiverValue import org.jetbrains.kotlin.resolve.scopes.receivers.ExpressionReceiver import org.jetbrains.kotlin.resolve.source.getPsi import org.jetbrains.kotlin.types.Variance class KotlinPullUpHelper( private val javaData: PullUpData, private val data: KotlinPullUpData ) : PullUpHelper<MemberInfoBase<PsiMember>> { companion object { private val MODIFIERS_TO_LIFT_IN_SUPERCLASS = listOf(KtTokens.PRIVATE_KEYWORD) private val MODIFIERS_TO_LIFT_IN_INTERFACE = listOf(KtTokens.PRIVATE_KEYWORD, KtTokens.PROTECTED_KEYWORD, KtTokens.INTERNAL_KEYWORD) } private fun KtExpression.isMovable(): Boolean { return accept( object : KtVisitor<Boolean, Nothing?>() { override fun visitKtElement(element: KtElement, arg: Nothing?): Boolean { return element.allChildren.all { (it as? KtElement)?.accept(this, arg) ?: true } } override fun visitKtFile(file: KtFile, data: Nothing?) = false override fun visitSimpleNameExpression(expression: KtSimpleNameExpression, arg: Nothing?): Boolean { val resolvedCall = expression.getResolvedCall(data.resolutionFacade.analyze(expression)) ?: return true val receiver = (resolvedCall.getExplicitReceiverValue() as? ExpressionReceiver)?.expression if (receiver != null && receiver !is KtThisExpression && receiver !is KtSuperExpression) return true var descriptor: DeclarationDescriptor = resolvedCall.resultingDescriptor if (descriptor is ConstructorDescriptor) { descriptor = descriptor.containingDeclaration } // todo: local functions if (descriptor is ValueParameterDescriptor) return true if (descriptor is ClassDescriptor && !descriptor.isInner) return true if (descriptor is MemberDescriptor) { if (descriptor.source.getPsi() in propertiesToMoveInitializers) return true descriptor = descriptor.containingDeclaration } return descriptor is PackageFragmentDescriptor || (descriptor is ClassDescriptor && DescriptorUtils.isSubclass(data.targetClassDescriptor, descriptor)) } }, null ) } private fun getCommonInitializer( currentInitializer: KtExpression?, scope: KtBlockExpression?, propertyDescriptor: PropertyDescriptor, elementsToRemove: MutableSet<KtElement> ): KtExpression? { if (scope == null) return currentInitializer var initializerCandidate: KtExpression? = null for (statement in scope.statements) { statement.asAssignment()?.let body@{ val lhs = KtPsiUtil.safeDeparenthesize(it.left ?: return@body) val receiver = (lhs as? KtQualifiedExpression)?.receiverExpression if (receiver != null && receiver !is KtThisExpression) return@body val resolvedCall = lhs.getResolvedCall(data.resolutionFacade.analyze(it)) ?: return@body if (resolvedCall.resultingDescriptor != propertyDescriptor) return@body if (initializerCandidate == null) { if (currentInitializer == null) { if (!statement.isMovable()) return null initializerCandidate = statement elementsToRemove.add(statement) } else { if (!KotlinPsiUnifier.DEFAULT.unify(statement, currentInitializer).matched) return null initializerCandidate = currentInitializer elementsToRemove.add(statement) } } else if (!KotlinPsiUnifier.DEFAULT.unify(statement, initializerCandidate).matched) return null } } return initializerCandidate } private data class InitializerInfo( val initializer: KtExpression?, val usedProperties: Set<KtProperty>, val usedParameters: Set<KtParameter>, val elementsToRemove: Set<KtElement> ) private fun getInitializerInfo( property: KtProperty, propertyDescriptor: PropertyDescriptor, targetConstructor: KtElement ): InitializerInfo? { val sourceConstructors = targetToSourceConstructors[targetConstructor] ?: return null val elementsToRemove = LinkedHashSet<KtElement>() val commonInitializer = sourceConstructors.fold(null as KtExpression?) { commonInitializer, constructor -> val body = (constructor as? KtSecondaryConstructor)?.bodyExpression getCommonInitializer(commonInitializer, body, propertyDescriptor, elementsToRemove) } if (commonInitializer == null) { elementsToRemove.clear() } val usedProperties = LinkedHashSet<KtProperty>() val usedParameters = LinkedHashSet<KtParameter>() val visitor = object : KtTreeVisitorVoid() { override fun visitSimpleNameExpression(expression: KtSimpleNameExpression) { val context = data.resolutionFacade.analyze(expression) val resolvedCall = expression.getResolvedCall(context) ?: return val receiver = (resolvedCall.getExplicitReceiverValue() as? ExpressionReceiver)?.expression if (receiver != null && receiver !is KtThisExpression) return val target = (resolvedCall.resultingDescriptor as? DeclarationDescriptorWithSource)?.source?.getPsi() when (target) { is KtParameter -> usedParameters.add(target) is KtProperty -> usedProperties.add(target) } } } commonInitializer?.accept(visitor) if (targetConstructor == ((data.targetClass as? KtClass)?.primaryConstructor ?: data.targetClass)) { property.initializer?.accept(visitor) } return InitializerInfo(commonInitializer, usedProperties, usedParameters, elementsToRemove) } private val propertiesToMoveInitializers = with(data) { membersToMove .filterIsInstance<KtProperty>() .filter { val descriptor = memberDescriptors[it] as? PropertyDescriptor descriptor != null && data.sourceClassContext[BindingContext.BACKING_FIELD_REQUIRED, descriptor] ?: false } } private val targetToSourceConstructors = LinkedHashMap<KtElement, MutableList<KtElement>>().let { result -> if (!data.isInterfaceTarget && data.targetClass is KtClass) { result[data.targetClass.primaryConstructor ?: data.targetClass] = ArrayList() data.sourceClass.accept( object : KtTreeVisitorVoid() { private fun processConstructorReference(expression: KtReferenceExpression, callingConstructorElement: KtElement) { val descriptor = data.resolutionFacade.analyze(expression)[BindingContext.REFERENCE_TARGET, expression] val constructorElement = (descriptor as? DeclarationDescriptorWithSource)?.source?.getPsi() ?: return if (constructorElement == data.targetClass || (constructorElement as? KtConstructor<*>)?.getContainingClassOrObject() == data.targetClass) { result.getOrPut(constructorElement as KtElement) { ArrayList() }.add(callingConstructorElement) } } override fun visitSuperTypeCallEntry(specifier: KtSuperTypeCallEntry) { val constructorRef = specifier.calleeExpression.constructorReferenceExpression ?: return val containingClass = specifier.getStrictParentOfType<KtClassOrObject>() ?: return val callingConstructorElement = containingClass.primaryConstructor ?: containingClass processConstructorReference(constructorRef, callingConstructorElement) } override fun visitSecondaryConstructor(constructor: KtSecondaryConstructor) { val constructorRef = constructor.getDelegationCall().calleeExpression ?: return processConstructorReference(constructorRef, constructor) } } ) } result } private val targetConstructorToPropertyInitializerInfoMap = LinkedHashMap<KtElement, Map<KtProperty, InitializerInfo>>().let { result -> for (targetConstructor in targetToSourceConstructors.keys) { val propertyToInitializerInfo = LinkedHashMap<KtProperty, InitializerInfo>() for (property in propertiesToMoveInitializers) { val propertyDescriptor = data.memberDescriptors[property] as? PropertyDescriptor ?: continue propertyToInitializerInfo[property] = getInitializerInfo(property, propertyDescriptor, targetConstructor) ?: continue } val unmovableProperties = RefactoringUtil.transitiveClosure( object : RefactoringUtil.Graph<KtProperty> { override fun getVertices() = propertyToInitializerInfo.keys override fun getTargets(source: KtProperty) = propertyToInitializerInfo[source]?.usedProperties } ) { !propertyToInitializerInfo.containsKey(it) } propertyToInitializerInfo.keys.removeAll(unmovableProperties) result[targetConstructor] = propertyToInitializerInfo } result } private var dummyField: PsiField? = null private fun addMovedMember(newMember: KtNamedDeclaration) { if (newMember is KtProperty) { // Add dummy light field since PullUpProcessor won't invoke moveFieldInitializations() if no PsiFields are present if (dummyField == null) { val factory = JavaPsiFacade.getElementFactory(newMember.project) val dummyField = object : LightField( newMember.manager, factory.createField("dummy", PsiType.BOOLEAN), factory.createClass("Dummy") ) { // Prevent processing by JavaPullUpHelper override fun getLanguage() = KotlinLanguage.INSTANCE } javaData.movedMembers.add(dummyField) } } when (newMember) { is KtProperty, is KtNamedFunction -> { newMember.getRepresentativeLightMethod()?.let { javaData.movedMembers.add(it) } } is KtClassOrObject -> { newMember.toLightClass()?.let { javaData.movedMembers.add(it) } } } } private fun liftVisibility(declaration: KtNamedDeclaration, ignoreUsages: Boolean = false) { val newModifier = if (data.isInterfaceTarget) KtTokens.PUBLIC_KEYWORD else KtTokens.PROTECTED_KEYWORD val modifiersToLift = if (data.isInterfaceTarget) MODIFIERS_TO_LIFT_IN_INTERFACE else MODIFIERS_TO_LIFT_IN_SUPERCLASS val currentModifier = declaration.visibilityModifierTypeOrDefault() if (currentModifier !in modifiersToLift) return if (ignoreUsages || willBeUsedInSourceClass(declaration, data.sourceClass, data.membersToMove)) { if (newModifier != KtTokens.DEFAULT_VISIBILITY_KEYWORD) { declaration.addModifier(newModifier) } else { declaration.removeModifier(currentModifier) } } } override fun setCorrectVisibility(info: MemberInfoBase<PsiMember>) { val member = info.member.namedUnwrappedElement as? KtNamedDeclaration ?: return if (data.isInterfaceTarget) { member.removeModifier(KtTokens.PUBLIC_KEYWORD) } val modifiersToLift = if (data.isInterfaceTarget) MODIFIERS_TO_LIFT_IN_INTERFACE else MODIFIERS_TO_LIFT_IN_SUPERCLASS if (member.visibilityModifierTypeOrDefault() in modifiersToLift) { member.accept( object : KtVisitorVoid() { override fun visitNamedDeclaration(declaration: KtNamedDeclaration) { when (declaration) { is KtClass -> { liftVisibility(declaration) declaration.declarations.forEach { it.accept(this) } } is KtNamedFunction, is KtProperty -> { liftVisibility(declaration, declaration == member && info.isToAbstract) } } } } ) } } override fun encodeContextInfo(info: MemberInfoBase<PsiMember>) { } private fun fixOverrideAndGetClashingSuper( sourceMember: KtCallableDeclaration, targetMember: KtCallableDeclaration ): KtCallableDeclaration? { val memberDescriptor = data.memberDescriptors[sourceMember] as CallableMemberDescriptor if (memberDescriptor.overriddenDescriptors.isEmpty()) { targetMember.removeOverrideModifier() return null } val clashingSuperDescriptor = data.getClashingMemberInTargetClass(memberDescriptor) ?: return null if (clashingSuperDescriptor.overriddenDescriptors.isEmpty()) { targetMember.removeOverrideModifier() } return clashingSuperDescriptor.source.getPsi() as? KtCallableDeclaration } private fun moveSuperInterface(member: PsiNamedElement, substitutor: PsiSubstitutor) { val realMemberPsi = (member as? KtPsiClassWrapper)?.psiClass ?: member val classDescriptor = data.memberDescriptors[member] as? ClassDescriptor ?: return val currentSpecifier = data.sourceClass.getSuperTypeEntryByDescriptor(classDescriptor, data.sourceClassContext) ?: return when (data.targetClass) { is KtClass -> { data.sourceClass.removeSuperTypeListEntry(currentSpecifier) addSuperTypeEntry( currentSpecifier, data.targetClass, data.targetClassDescriptor, data.sourceClassContext, data.sourceToTargetClassSubstitutor ) } is PsiClass -> { val elementFactory = JavaPsiFacade.getElementFactory(member.project) val sourcePsiClass = data.sourceClass.toLightClass() ?: return val superRef = sourcePsiClass.implementsList ?.referenceElements ?.firstOrNull { it.resolve()?.unwrapped == realMemberPsi } ?: return val superTypeForTarget = substitutor.substitute(elementFactory.createType(superRef)) data.sourceClass.removeSuperTypeListEntry(currentSpecifier) if (DescriptorUtils.isSubclass(data.targetClassDescriptor, classDescriptor)) return val refList = if (data.isInterfaceTarget) data.targetClass.extendsList else data.targetClass.implementsList refList?.add(elementFactory.createReferenceFromText(superTypeForTarget.canonicalText, null)) } } return } private fun removeOriginalMemberOrAddOverride(member: KtCallableDeclaration) { if (member.isAbstract()) { member.deleteWithCompanion() } else { member.addModifier(KtTokens.OVERRIDE_KEYWORD) KtTokens.VISIBILITY_MODIFIERS.types.forEach { member.removeModifier(it as KtModifierKeywordToken) } (member as? KtNamedFunction)?.valueParameters?.forEach { it.dropDefaultValue() } } } private fun moveToJavaClass(member: KtNamedDeclaration, substitutor: PsiSubstitutor) { if (!(data.targetClass is PsiClass && member.canMoveMemberToJavaClass(data.targetClass))) return // TODO: Drop after PsiTypes in light elements are properly generated if (member is KtCallableDeclaration && member.typeReference == null) { val returnType = (data.memberDescriptors[member] as CallableDescriptor).returnType returnType?.anonymousObjectSuperTypeOrNull()?.let { member.setType(it, false) } } val project = member.project val elementFactory = JavaPsiFacade.getElementFactory(project) val lightMethod = member.getRepresentativeLightMethod()!! val movedMember: PsiMember = when (member) { is KtProperty, is KtParameter -> { val newType = substitutor.substitute(lightMethod.returnType) val newField = createJavaField(member, data.targetClass) newField.typeElement?.replace(elementFactory.createTypeElement(newType)) if (member.isCompanionMemberOf(data.sourceClass)) { newField.modifierList?.setModifierProperty(PsiModifier.STATIC, true) } if (member is KtParameter) { (member.parent as? KtParameterList)?.removeParameter(member) } else { member.deleteWithCompanion() } newField } is KtNamedFunction -> { val newReturnType = substitutor.substitute(lightMethod.returnType) val newParameterTypes = lightMethod.parameterList.parameters.map { substitutor.substitute(it.type) } val objectType = PsiType.getJavaLangObject(PsiManager.getInstance(project), GlobalSearchScope.allScope(project)) val newTypeParameterBounds = lightMethod.typeParameters.map { it.superTypes.map { type -> substitutor.substitute(type) as? PsiClassType ?: objectType } } val newMethod = org.jetbrains.kotlin.idea.refactoring.createJavaMethod(member, data.targetClass) RefactoringUtil.makeMethodAbstract(data.targetClass, newMethod) newMethod.returnTypeElement?.replace(elementFactory.createTypeElement(newReturnType)) newMethod.parameterList.parameters.forEachIndexed { i, parameter -> parameter.typeElement?.replace(elementFactory.createTypeElement(newParameterTypes[i])) } newMethod.typeParameters.forEachIndexed { i, typeParameter -> typeParameter.extendsList.referenceElements.forEachIndexed { j, referenceElement -> referenceElement.replace(elementFactory.createReferenceElementByType(newTypeParameterBounds[i][j])) } } removeOriginalMemberOrAddOverride(member) if (!data.isInterfaceTarget && !data.targetClass.hasModifierProperty(PsiModifier.ABSTRACT)) { data.targetClass.modifierList?.setModifierProperty(PsiModifier.ABSTRACT, true) } newMethod } else -> return } JavaCodeStyleManager.getInstance(project).shortenClassReferences(movedMember) } override fun move(info: MemberInfoBase<PsiMember>, substitutor: PsiSubstitutor) { val member = info.member.toKtDeclarationWrapperAware() ?: return if ((member is KtClass || member is KtPsiClassWrapper) && info.overrides != null) { moveSuperInterface(member, substitutor) return } if (data.targetClass is PsiClass) { moveToJavaClass(member, substitutor) return } val markedElements = markElements(member, data.sourceClassContext, data.sourceClassDescriptor, data.targetClassDescriptor) val memberCopy = member.copy() as KtNamedDeclaration fun moveClassOrObject(member: KtClassOrObject, memberCopy: KtClassOrObject): KtClassOrObject { if (data.isInterfaceTarget) { memberCopy.removeModifier(KtTokens.INNER_KEYWORD) } val movedMember = addMemberToTarget(memberCopy, data.targetClass as KtClass) as KtClassOrObject member.deleteWithCompanion() return movedMember } fun moveCallableMember(member: KtCallableDeclaration, memberCopy: KtCallableDeclaration): KtCallableDeclaration { data.targetClass as KtClass val movedMember: KtCallableDeclaration val clashingSuper = fixOverrideAndGetClashingSuper(member, memberCopy) val psiFactory = KtPsiFactory(member) val originalIsAbstract = member.hasModifier(KtTokens.ABSTRACT_KEYWORD) val toAbstract = when { info.isToAbstract -> true !data.isInterfaceTarget -> false member is KtProperty -> member.mustBeAbstractInInterface() else -> false } val classToAddTo = if (member.isCompanionMemberOf(data.sourceClass)) data.targetClass.getOrCreateCompanionObject() else data.targetClass if (toAbstract) { if (!originalIsAbstract) { makeAbstract( memberCopy, data.memberDescriptors[member] as CallableMemberDescriptor, data.sourceToTargetClassSubstitutor, data.targetClass ) } movedMember = doAddCallableMember(memberCopy, clashingSuper, classToAddTo) if (member.typeReference == null) { movedMember.typeReference?.addToShorteningWaitSet() } if (movedMember.nextSibling.hasComments()) { movedMember.parent.addAfter(psiFactory.createNewLine(), movedMember) } removeOriginalMemberOrAddOverride(member) } else { movedMember = doAddCallableMember(memberCopy, clashingSuper, classToAddTo) if (member is KtParameter && movedMember is KtParameter) { member.valOrVarKeyword?.delete() CONSTRUCTOR_VAL_VAR_MODIFIERS.forEach { member.removeModifier(it) } val superEntry = data.superEntryForTargetClass val superResolvedCall = data.targetClassSuperResolvedCall if (superResolvedCall != null) { val superCall = if (superEntry !is KtSuperTypeCallEntry || superEntry.valueArgumentList == null) { superEntry!!.replaced(psiFactory.createSuperTypeCallEntry("${superEntry.text}()")) } else superEntry val argumentList = superCall.valueArgumentList!! val parameterIndex = movedMember.parameterIndex() val prevParameterDescriptor = superResolvedCall.resultingDescriptor.valueParameters.getOrNull(parameterIndex - 1) val prevArgument = superResolvedCall.valueArguments[prevParameterDescriptor]?.arguments?.singleOrNull() as? KtValueArgument val newArgumentName = if (prevArgument != null && prevArgument.isNamed()) Name.identifier(member.name!!) else null val newArgument = psiFactory.createArgument(psiFactory.createExpression(member.name!!), newArgumentName) if (prevArgument == null) { argumentList.addArgument(newArgument) } else { argumentList.addArgumentAfter(newArgument, prevArgument) } } } else { member.deleteWithCompanion() } } if (originalIsAbstract && data.isInterfaceTarget) { movedMember.removeModifier(KtTokens.ABSTRACT_KEYWORD) } if (movedMember.hasModifier(KtTokens.ABSTRACT_KEYWORD)) { data.targetClass.makeAbstract() } return movedMember } try { val movedMember = when (member) { is KtCallableDeclaration -> moveCallableMember(member, memberCopy as KtCallableDeclaration) is KtClassOrObject -> moveClassOrObject(member, memberCopy as KtClassOrObject) else -> return } movedMember.modifierList?.reformatted() applyMarking(movedMember, data.sourceToTargetClassSubstitutor, data.targetClassDescriptor) addMovedMember(movedMember) } finally { clearMarking(markedElements) } } override fun postProcessMember(member: PsiMember) { val declaration = member.unwrapped as? KtNamedDeclaration ?: return dropOverrideKeywordIfNecessary(declaration) } override fun moveFieldInitializations(movedFields: LinkedHashSet<PsiField>) { val psiFactory = KtPsiFactory(data.sourceClass) fun KtClassOrObject.getOrCreateClassInitializer(): KtAnonymousInitializer { getOrCreateBody().declarations.lastOrNull { it is KtAnonymousInitializer }?.let { return it as KtAnonymousInitializer } return addDeclaration(psiFactory.createAnonymousInitializer()) } fun KtElement.getConstructorBodyBlock(): KtBlockExpression? { return when (this) { is KtClassOrObject -> { getOrCreateClassInitializer().body } is KtPrimaryConstructor -> { getContainingClassOrObject().getOrCreateClassInitializer().body } is KtSecondaryConstructor -> { bodyExpression ?: add(psiFactory.createEmptyBody()) } else -> null } as? KtBlockExpression } fun KtClassOrObject.getDelegatorToSuperCall(): KtSuperTypeCallEntry? { return superTypeListEntries.singleOrNull { it is KtSuperTypeCallEntry } as? KtSuperTypeCallEntry } fun addUsedParameters(constructorElement: KtElement, info: InitializerInfo) { if (info.usedParameters.isEmpty()) return val constructor: KtConstructor<*> = when (constructorElement) { is KtConstructor<*> -> constructorElement is KtClass -> constructorElement.createPrimaryConstructorIfAbsent() else -> return } with(constructor.getValueParameterList()!!) { info.usedParameters.forEach { val newParameter = addParameter(it) val originalType = data.sourceClassContext[BindingContext.VALUE_PARAMETER, it]!!.type newParameter.setType( data.sourceToTargetClassSubstitutor.substitute(originalType, Variance.INVARIANT) ?: originalType, false ) newParameter.typeReference!!.addToShorteningWaitSet() } } targetToSourceConstructors[constructorElement]!!.forEach { val superCall: KtCallElement? = when (it) { is KtClassOrObject -> it.getDelegatorToSuperCall() is KtPrimaryConstructor -> it.getContainingClassOrObject().getDelegatorToSuperCall() is KtSecondaryConstructor -> { if (it.hasImplicitDelegationCall()) { it.replaceImplicitDelegationCallWithExplicit(false) } else { it.getDelegationCall() } } else -> null } superCall?.valueArgumentList?.let { args -> info.usedParameters.forEach { parameter -> args.addArgument(psiFactory.createArgument(psiFactory.createExpression(parameter.name ?: "_"))) } } } } for ((constructorElement, propertyToInitializerInfo) in targetConstructorToPropertyInitializerInfoMap.entries) { val properties = propertyToInitializerInfo.keys.sortedWith( Comparator { property1, property2 -> val info1 = propertyToInitializerInfo[property1]!! val info2 = propertyToInitializerInfo[property2]!! when { property2 in info1.usedProperties -> -1 property1 in info2.usedProperties -> 1 else -> 0 } } ) for (oldProperty in properties) { val info = propertyToInitializerInfo.getValue(oldProperty) addUsedParameters(constructorElement, info) info.initializer?.let { val body = constructorElement.getConstructorBodyBlock() body?.addAfter(it, body.statements.lastOrNull() ?: body.lBrace!!) } info.elementsToRemove.forEach { it.delete() } } } } override fun updateUsage(element: PsiElement) { } } internal fun KtNamedDeclaration.deleteWithCompanion() { val containingClass = this.containingClassOrObject if (containingClass is KtObjectDeclaration && containingClass.isCompanion() && containingClass.declarations.size == 1 && containingClass.getSuperTypeList() == null ) { containingClass.delete() } else { this.delete() } }
apache-2.0
58f3e3606ce90a6c0089b9426aefe4e4
47.606287
164
0.633774
6.590014
false
false
false
false
RuneSuite/client
updater-mapper/src/main/java/org/runestar/client/updater/mapper/std/classes/PacketBitNode.kt
1
788
package org.runestar.client.updater.mapper.std.classes import org.runestar.client.updater.mapper.IdentityMapper import org.runestar.client.updater.mapper.DependsOn import org.runestar.client.updater.mapper.and import org.runestar.client.updater.mapper.predicateOf import org.runestar.client.updater.mapper.Class2 import org.runestar.client.updater.mapper.Field2 @DependsOn(Node::class, PacketBit::class) class PacketBitNode : IdentityMapper.Class() { override val predicate = predicateOf<Class2> { it.superType == type<Node>() } .and { it.instanceFields.any { it.type == type<PacketBit>() } } @DependsOn(PacketBit::class) class bit : IdentityMapper.InstanceField() { override val predicate = predicateOf<Field2> { it.type == type<PacketBit>() } } }
mit
6855264a378ff4b6b842efab615d26c7
38.45
85
0.751269
3.862745
false
false
false
false
benjamin-bader/thrifty
thrifty-runtime/src/commonMain/kotlin/com/microsoft/thrifty/protocol/BinaryProtocol.kt
1
10978
/* * Thrifty * * Copyright (c) Microsoft Corporation * * All rights reserved. * * Licensed under the Apache License, Version 2.0 (the License); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING * WITHOUT LIMITATION ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, * FITNESS FOR A PARTICULAR PURPOSE, MERCHANTABLITY OR NON-INFRINGEMENT. * * See the Apache Version 2.0 License for specific language governing permissions and limitations under the License. */ package com.microsoft.thrifty.protocol import com.microsoft.thrifty.TType import com.microsoft.thrifty.internal.ProtocolException import com.microsoft.thrifty.transport.Transport import okio.ByteString import okio.ByteString.Companion.toByteString import okio.EOFException import okio.IOException import kotlin.jvm.JvmOverloads /** * An implementation of the simple Thrift binary protocol. * * Instances of this class are *not* threadsafe. * * @param transport * @param stringLengthLimit * The maximum number of bytes to read from the transport for * variable-length fields (strings or binary), or -1 for unlimited. * @param containerLengthLimit * The maximum number of elements to read from the network for containers * (maps, lists, sets). */ class BinaryProtocol @JvmOverloads constructor( transport: Transport, private val stringLengthLimit: Long = -1, private val containerLengthLimit: Long = -1 ) : BaseProtocol(transport) { /** * A shared buffer for writing. */ private val buffer = ByteArray(8) private val strictRead = false private val strictWrite = false @Throws(IOException::class) override fun writeMessageBegin(name: String, typeId: Byte, seqId: Int) { if (strictWrite) { val version = VERSION_1 or (typeId.toInt() and 0xFF) writeI32(version) writeString(name) writeI32(seqId) } else { writeString(name) writeByte(typeId) writeI32(seqId) } } @Throws(IOException::class) override fun writeMessageEnd() { } @Throws(IOException::class) override fun writeStructBegin(structName: String) { } @Throws(IOException::class) override fun writeStructEnd() { } @Throws(IOException::class) override fun writeFieldBegin(fieldName: String, fieldId: Int, typeId: Byte) { writeByte(typeId) writeI16(fieldId.toShort()) } @Throws(IOException::class) override fun writeFieldEnd() { } @Throws(IOException::class) override fun writeFieldStop() { writeByte(TType.STOP) } @Throws(IOException::class) override fun writeMapBegin(keyTypeId: Byte, valueTypeId: Byte, mapSize: Int) { writeByte(keyTypeId) writeByte(valueTypeId) writeI32(mapSize) } @Throws(IOException::class) override fun writeMapEnd() { } @Throws(IOException::class) override fun writeListBegin(elementTypeId: Byte, listSize: Int) { writeByte(elementTypeId) writeI32(listSize) } @Throws(IOException::class) override fun writeListEnd() { } @Throws(IOException::class) override fun writeSetBegin(elementTypeId: Byte, setSize: Int) { writeByte(elementTypeId) writeI32(setSize) } @Throws(IOException::class) override fun writeSetEnd() { } @Throws(IOException::class) override fun writeBool(b: Boolean) { writeByte(if (b) 1.toByte() else 0.toByte()) } @Throws(IOException::class) override fun writeByte(b: Byte) { buffer[0] = b transport.write(buffer, 0, 1) } @Throws(IOException::class) override fun writeI16(i16: Short) { buffer[0] = ((i16.toInt() shr 8) and 0xFF).toByte() buffer[1] = (i16.toInt() and 0xFF).toByte() transport.write(buffer, 0, 2) } @Throws(IOException::class) override fun writeI32(i32: Int) { buffer[0] = ((i32 shr 24) and 0xFF).toByte() buffer[1] = ((i32 shr 16) and 0xFF).toByte() buffer[2] = ((i32 shr 8) and 0xFF).toByte() buffer[3] = (i32 and 0xFF).toByte() transport.write(buffer, 0, 4) } @Throws(IOException::class) override fun writeI64(i64: Long) { buffer[0] = ((i64 shr 56) and 0xFF).toByte() buffer[1] = ((i64 shr 48) and 0xFF).toByte() buffer[2] = ((i64 shr 40) and 0xFF).toByte() buffer[3] = ((i64 shr 32) and 0xFF).toByte() buffer[4] = ((i64 shr 24) and 0xFF).toByte() buffer[5] = ((i64 shr 16) and 0xFF).toByte() buffer[6] = ((i64 shr 8) and 0xFF).toByte() buffer[7] = (i64 and 0xFF).toByte() transport.write(buffer, 0, 8) } @Throws(IOException::class) override fun writeDouble(dub: Double) { writeI64(dub.toRawBits()) } @Throws(IOException::class) override fun writeString(str: String) { val bs = str.encodeToByteArray() writeI32(bs.size) transport.write(bs) } @Throws(IOException::class) override fun writeBinary(buf: ByteString) { writeI32(buf.size) transport.write(buf.toByteArray()) } ////////////////////// @Throws(IOException::class) override fun readMessageBegin(): MessageMetadata { val size = readI32() return if (size < 0) { val version = size and VERSION_MASK if (version != VERSION_1) { throw ProtocolException("Bad version in readMessageBegin") } MessageMetadata(readString(), (size and 0xff).toByte(), readI32()) } else { if (strictRead) { throw ProtocolException("Missing version in readMessageBegin") } MessageMetadata(readStringWithSize(size), readByte(), readI32()) } } @Throws(IOException::class) override fun readMessageEnd() { } @Throws(IOException::class) override fun readStructBegin(): StructMetadata { return NO_STRUCT } @Throws(IOException::class) override fun readStructEnd() { } @Throws(IOException::class) override fun readFieldBegin(): FieldMetadata { val typeId = readByte() val fieldId = if (typeId == TType.STOP) 0 else readI16() return FieldMetadata("", typeId, fieldId) } @Throws(IOException::class) override fun readFieldEnd() { } @Throws(IOException::class) override fun readMapBegin(): MapMetadata { val keyTypeId = readByte() val valueTypeId = readByte() val size = readI32() if (containerLengthLimit != -1L && size > containerLengthLimit) { throw ProtocolException("Container size limit exceeded") } return MapMetadata(keyTypeId, valueTypeId, size) } @Throws(IOException::class) override fun readMapEnd() { } @Throws(IOException::class) override fun readListBegin(): ListMetadata { val elementTypeId = readByte() val size = readI32() if (containerLengthLimit != -1L && size > containerLengthLimit) { throw ProtocolException("Container size limit exceeded") } return ListMetadata(elementTypeId, size) } @Throws(IOException::class) override fun readListEnd() { } @Throws(IOException::class) override fun readSetBegin(): SetMetadata { val elementTypeId = readByte() val size = readI32() if (containerLengthLimit != -1L && size > containerLengthLimit) { throw ProtocolException("Container size limit exceeded") } return SetMetadata(elementTypeId, size) } @Throws(IOException::class) override fun readSetEnd() { } @Throws(IOException::class) override fun readBool(): Boolean { return readByte().toInt() == 1 } @Throws(IOException::class) override fun readByte(): Byte { readFully(buffer, 1) return buffer[0] } @Throws(IOException::class) override fun readI16(): Short { readFully(buffer, 2) return (((buffer[0].toInt() and 0xFF) shl 8) or (buffer[1].toInt() and 0xFF)).toShort() } @Throws(IOException::class) override fun readI32(): Int { readFully(buffer, 4) return (((buffer[0].toInt() and 0xFF) shl 24) or ((buffer[1].toInt() and 0xFF) shl 16) or ((buffer[2].toInt() and 0xFF) shl 8) or (buffer[3].toInt() and 0xFF)) } @Throws(IOException::class) override fun readI64(): Long { readFully(buffer, 8) return (((buffer[0].toLong() and 0xFFL) shl 56) or ((buffer[1].toLong() and 0xFFL) shl 48) or ((buffer[2].toLong() and 0xFFL) shl 40) or ((buffer[3].toLong() and 0xFFL) shl 32) or ((buffer[4].toLong() and 0xFFL) shl 24) or ((buffer[5].toLong() and 0xFFL) shl 16) or ((buffer[6].toLong() and 0xFFL) shl 8) or ((buffer[7].toLong() and 0xFFL))) } @Throws(IOException::class) override fun readDouble(): Double { return Double.fromBits(readI64()) } @Throws(IOException::class) override fun readString(): String { val sizeInBytes = readI32() if (stringLengthLimit != -1L && sizeInBytes > stringLengthLimit) { throw ProtocolException("String size limit exceeded") } return readStringWithSize(sizeInBytes) } @Throws(IOException::class) override fun readBinary(): ByteString { val sizeInBytes = readI32() if (stringLengthLimit != -1L && sizeInBytes > stringLengthLimit) { throw ProtocolException("Binary size limit exceeded") } val data = ByteArray(sizeInBytes) readFully(data, data.size) return data.toByteString() } @Throws(IOException::class) private fun readStringWithSize(size: Int): String { val encoded = ByteArray(size) readFully(encoded, size) return encoded.decodeToString() } @Throws(IOException::class) private fun readFully(buffer: ByteArray, count: Int) { var toRead = count var offset = 0 while (toRead > 0) { val read = transport.read(buffer, offset, toRead) if (read == -1) { throw EOFException("Expected $count bytes; got $offset") } toRead -= read offset += read } } companion object { private const val VERSION_MASK = -0x10000 private const val VERSION_1 = -0x7fff0000 private val NO_STRUCT = StructMetadata("") } }
apache-2.0
0ef1b66f9d4a15627bc4ab38f45092b7
29.242424
116
0.613409
4.25834
false
false
false
false
ncoe/rosetta
Intersecting_Number_Wheels/Kotlin/src/WheelController.kt
1
1906
import java.util.Collections import java.util.stream.IntStream object WheelController { private val IS_NUMBER = "[0-9]".toRegex() private const val TWENTY = 20 private var wheelMap = mutableMapOf<String, WheelModel>() private fun advance(wheel: String) { val w = wheelMap[wheel] if (w!!.list[w.position].matches(IS_NUMBER)) { w.printThePosition() } else { val wheelName = w.list[w.position] advance(wheelName) } w.advanceThePosition() } private fun run() { println(wheelMap) IntStream.rangeClosed(1, TWENTY) .forEach { advance("A") } println() wheelMap.clear() } @JvmStatic fun main(args: Array<String>) { wheelMap["A"] = WheelModel("1", "2", "3") run() wheelMap["A"] = WheelModel("1", "B", "2") wheelMap["B"] = WheelModel("3", "4") run() wheelMap["A"] = WheelModel("1", "D", "D") wheelMap["D"] = WheelModel("6", "7", "8") run() wheelMap["A"] = WheelModel("1", "B", "C") wheelMap["B"] = WheelModel("3", "4") wheelMap["C"] = WheelModel("5", "B") run() } } internal class WheelModel(vararg values: String?) { var list = mutableListOf<String>() var position: Int private var endPosition: Int override fun toString(): String { return list.toString() } fun advanceThePosition() { if (position == endPosition) { position = INITIAL // new beginning } else { position++ // advance position } } fun printThePosition() { print(" ${list[position]}") } companion object { private const val INITIAL = 0 } init { Collections.addAll<String>(list, *values) position = INITIAL endPosition = list.size - 1 } }
mit
d67a345392bda6492fdd779725cd2ef1
24.413333
61
0.537775
4.125541
false
false
false
false
siosio/intellij-community
java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/JdkComboBox.kt
1
5169
// Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.openapi.roots.ui.configuration import com.intellij.CommonBundle import com.intellij.ide.JavaUiBundle import com.intellij.ide.starters.JavaStartersBundle import com.intellij.ide.util.PropertiesComponent import com.intellij.ide.util.projectWizard.ModuleBuilder import com.intellij.ide.util.projectWizard.ProjectWizardUtil import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.module.ModuleType import com.intellij.openapi.module.StdModuleTypes import com.intellij.openapi.observable.properties.GraphProperty import com.intellij.openapi.options.ConfigurationException import com.intellij.openapi.project.Project import com.intellij.openapi.projectRoots.JavaSdk import com.intellij.openapi.projectRoots.JavaSdkVersion import com.intellij.openapi.projectRoots.Sdk import com.intellij.openapi.roots.ModifiableRootModel import com.intellij.openapi.roots.ProjectRootManager import com.intellij.openapi.roots.ui.configuration.projectRoot.ProjectSdksModel import com.intellij.openapi.ui.Messages import com.intellij.ui.layout.* fun Row.sdkComboBox(sdkModel: ProjectSdksModel, sdkProperty: GraphProperty<Sdk?>, project: Project?, moduleBuilder: ModuleBuilder): CellBuilder<JdkComboBox> { sdkModel.reset(project) val sdkFilter = moduleBuilder::isSuitableSdkType val sdkComboBox = JdkComboBox(project, sdkModel, sdkFilter, JdkComboBox.getSdkFilter(sdkFilter), sdkFilter, null) val moduleType: ModuleType<*> = StdModuleTypes.JAVA val selectedJdkProperty = "jdk.selected." + moduleType.id val stateComponent = if (project == null) PropertiesComponent.getInstance() else PropertiesComponent.getInstance(project) sdkComboBox.addActionListener { val jdk: Sdk? = getTargetJdk(sdkComboBox, project) if (jdk != null) { stateComponent.setValue(selectedJdkProperty, jdk.name) } sdkProperty.set(jdk) } val lastUsedSdk = stateComponent.getValue(selectedJdkProperty) ProjectWizardUtil.preselectJdkForNewModule(project, lastUsedSdk, sdkComboBox, moduleBuilder, sdkFilter) return this.component(sdkComboBox) } private fun getTargetJdk(sdkComboBox: JdkComboBox, project: Project?): Sdk? { val selectedJdk = sdkComboBox.selectedJdk if (selectedJdk != null) return selectedJdk if (project != null && sdkComboBox.isProjectJdkSelected) { return ProjectRootManager.getInstance(project).projectSdk } return null } fun validateSdk(sdkProperty: GraphProperty<Sdk?>, sdkModel: ProjectSdksModel): Boolean { if (sdkProperty.get() == null) { if (Messages.showDialog(JavaUiBundle.message("prompt.confirm.project.no.jdk"), JavaUiBundle.message("title.no.jdk.specified"), arrayOf(CommonBundle.getYesButtonText(), CommonBundle.getNoButtonText()), 1, Messages.getWarningIcon()) != Messages.YES) { return false } } try { sdkModel.apply(null, true) } catch (e: ConfigurationException) { //IDEA-98382 We should allow Next step if user has wrong SDK if (Messages.showDialog(JavaUiBundle.message("dialog.message.0.do.you.want.to.proceed", e.message), e.title, arrayOf(CommonBundle.getYesButtonText(), CommonBundle.getNoButtonText()), 1, Messages.getWarningIcon()) != Messages.YES) { return false } } return true } fun validateJavaVersion(sdkProperty: GraphProperty<Sdk?>, javaVersion: String?): Boolean { val sdk = sdkProperty.get() if (sdk != null) { val wizardVersion = JavaSdk.getInstance().getVersion(sdk) if (wizardVersion != null && javaVersion != null) { val selectedVersion = JavaSdkVersion.fromVersionString(javaVersion) if (selectedVersion != null && !wizardVersion.isAtLeast(selectedVersion)) { Messages.showErrorDialog(JavaStartersBundle.message("message.java.version.not.supported.by.sdk", selectedVersion.description, sdk.name, wizardVersion.description), JavaStartersBundle.message("message.title.error")) return false } } } return true } fun setupNewModuleJdk(modifiableRootModel: ModifiableRootModel, selectedJdk: Sdk?, isCreatingNewProject: Boolean): Sdk? { if (ApplicationManager.getApplication().isUnitTestMode && selectedJdk == modifiableRootModel.sdk) { // do not change SDK in tests return selectedJdk } val sdk = selectedJdk ?: getProjectJdk(modifiableRootModel.project) if (sdk != null) { if (isCreatingNewProject || (!isCreatingNewProject && sdk == getProjectJdk(modifiableRootModel.project))) { modifiableRootModel.inheritSdk() } else { modifiableRootModel.sdk = sdk } } return sdk } private fun getProjectJdk(project: Project): Sdk? { return ProjectRootManager.getInstance(project).projectSdk }
apache-2.0
7e9bb59c13e0396ec9002d196284f48e
40.031746
140
0.718127
4.904175
false
false
false
false
siosio/intellij-community
plugins/kotlin/performance-tests/test/org/jetbrains/kotlin/idea/perf/profilers/async/AsyncProfilerHandler.kt
2
7690
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.perf.profilers.async import com.intellij.openapi.util.SystemInfo import com.intellij.openapi.util.io.FileUtil import com.intellij.util.containers.ContainerUtil import org.jetbrains.kotlin.idea.perf.profilers.ProfilerConfig import org.jetbrains.kotlin.idea.perf.profilers.ProfilerHandler import org.jetbrains.kotlin.idea.perf.profilers.doOrThrow import org.jetbrains.kotlin.idea.perf.util.logMessage import java.io.File import java.lang.reflect.Method import java.nio.file.Files import java.nio.file.StandardCopyOption import java.util.* /** * To use AsyncProfilerHandler: * - it has to be running on GNU/Linux or MacOSX (as async-profiler does NOT work on Windows) * - env variable ASYNC_PROFILER_HOME has to be specified and points to async-profiler installation * - ${ASYNC_PROFILER_HOME}/build/async-profiler.jar has to be in a classpath (done by gradle task) * * AsyncProfiler could be downloaded from https://github.com/jvm-profiling-tools/async-profiler/releases/ */ internal class AsyncProfilerHandler(val profilerConfig: ProfilerConfig) : ProfilerHandler { private val asyncProfiler: Any private var profilingStarted = false private var profilingOptions: List<String>? = null init { val asyncLibPath = asyncLib().absolutePath val getInstanceMethod = asyncLibClass.getMethod("getInstance", String::class.java) // use reflection to exclude compile time dependency on async profiler that has not been published to maven yet asyncProfiler = getInstanceMethod.invoke(null, asyncLibPath) as Any logMessage { "asyncProfiler successfully loaded" } } private fun execute(command: String) { logMessage { "asyncProfiler command: '$command'" } executeMethod.invoke(asyncProfiler, command) } override fun startProfiling() { try { profilingOptions = profilerConfig.options execute(AsyncProfilerCommandBuilder.buildStartCommand(profilerConfig.options)) profilingStarted = true } catch (e: Exception) { throw RuntimeException(e) } } override fun stopProfiling(attempt: Int) { val combinedOptions = ArrayList(profilerConfig.options) val commandBuilder = AsyncProfilerCommandBuilder(profilerConfig.path) val name = "${profilerConfig.name}-$attempt".replace(' ', '_').replace('/', '_') val stopAndDumpCommands = commandBuilder.buildStopAndDumpCommands(name, combinedOptions) for (stopCommand in stopAndDumpCommands) { execute(stopCommand) } profilingStarted = false } companion object { private val asyncLibClass: Class<*> = doOrThrow("async-profiler.jar is not in a classpath") { Class.forName("one.profiler.AsyncProfiler") } private val executeMethod: Method = doOrThrow("one.profiler.AsyncProfiler#execute(String) not found") { asyncLibClass.getMethod("execute", String::class.java) } private const val AGENT_FILE_NAME = "libasyncProfiler.so" private var extractedFile: File? = null private fun asyncLib(): File { val osName = when { SystemInfo.isLinux -> "linux" SystemInfo.isMac -> "macos" else -> error("AsyncProfiler does not support OS ${SystemInfo.OS_NAME}") } extractedFile = extractedFile ?: File("${System.getenv("ASYNC_PROFILER_HOME")}/build/$AGENT_FILE_NAME") if (extractedFile == null || !extractedFile!!.exists()) { val extracted = FileUtil.createTempFile("extracted_$AGENT_FILE_NAME", null, true) val inputStream = asyncLibClass.getResourceAsStream("/binaries/$osName/$AGENT_FILE_NAME") Files.copy(inputStream, extracted.toPath(), StandardCopyOption.REPLACE_EXISTING) extractedFile = extracted } return extractedFile ?: error("Unable to lookup $AGENT_FILE_NAME") } } } class AsyncProfilerCommandBuilder(private val snapshotsPath: String) { fun buildStopAndDumpCommands(activityName: String, options: List<String>): List<String> { if (options.isEmpty()) { val dumpFileName = getDumpFileName(activityName, "svg") return listOf(buildCommand("stop", listOf("svg", "file=$dumpFileName"))) } else { val dumpOptions = ArrayList<String>() val profilingOptions = ArrayList<String>() for (option in options) { val myDumpOptions = listOf("summary", "traces", "flat", "jfr", "collapsed", "svg", "tree") val trimmedOption = option.split("=".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()[0].trim { it <= ' ' } if (myDumpOptions.contains(trimmedOption)) { dumpOptions.add(option + ",file=" + getDumpFileName(activityName, trimmedOption)) } else { profilingOptions.add(option) } } val stopCommands = ArrayList<String>() for (option in dumpOptions) { stopCommands.add( buildCommand( "stop", mergeParameters( profilingOptions, listOf(*option.split(",".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()) ) ) ) } return stopCommands } } private fun getDumpFileName(activityName: String, profilingType: String): String { return "$snapshotsPath${File.separator}$activityName" + when (profilingType) { "jfr" -> ".jfr" "svg" -> ".svg" "tree" -> ".html" else -> ".txt" } } companion object { private val DEFAULT_PROFILING_OPTIONS: List<String> = listOf("event=cpu", "framebuf=10000000", "interval=1000000") fun buildStartCommand(options: List<String>): String { return if (options.isEmpty()) { buildCommand("start", DEFAULT_PROFILING_OPTIONS) } else { buildCommand("start", mergeParameters(options, DEFAULT_PROFILING_OPTIONS)) } } private fun buildCommand(initialCommand: String, options: List<String>): String { val builder = StringBuilder(initialCommand) for (option in options) { builder.append(",").append(option) } return builder.toString() } private fun parseParametersList(options: List<String>): Map<String, String> { return options.map { option -> option.split("=".toRegex()).dropLastWhile { it.isEmpty() } .toTypedArray() }.flatMap { it.toList() }.map { it to it }.toMap() } private fun mergeParameters(options: List<String>, defaultOptions: List<String>): List<String> { val userOptions = parseParametersList(options) val defOptions = parseParametersList(defaultOptions) val mergedOptions = HashMap(defOptions) mergedOptions.putAll(userOptions) return ContainerUtil.map(mergedOptions.keys) { key -> if (mergedOptions[key]?.isEmpty() == true) key else key + "=" + mergedOptions[key] } } } }
apache-2.0
f2fd3d411f7110ba83a58e83a094c9dc
41.252747
158
0.620806
4.867089
false
false
false
false
androidx/androidx
health/connect/connect-client/src/test/java/androidx/health/connect/client/records/ExerciseEventRepetitionsTest.kt
3
3078
/* * Copyright 2022 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.health.connect.client.records import androidx.test.ext.junit.runners.AndroidJUnit4 import com.google.common.truth.Truth.assertThat import java.time.Instant import kotlin.reflect.typeOf import kotlin.test.assertFailsWith import org.junit.Test import org.junit.runner.RunWith @RunWith(AndroidJUnit4::class) class ExerciseEventRepetitionsTest { @Test fun validRecord_equals() { assertThat( ExerciseRepetitionsRecord( startTime = Instant.ofEpochMilli(1234L), startZoneOffset = null, endTime = Instant.ofEpochMilli(1236L), endZoneOffset = null, count = 10, type = ExerciseRepetitionsRecord.REPETITION_TYPE_ARM_CURL, ) ) .isEqualTo( ExerciseRepetitionsRecord( startTime = Instant.ofEpochMilli(1234L), startZoneOffset = null, endTime = Instant.ofEpochMilli(1236L), endZoneOffset = null, count = 10, type = ExerciseRepetitionsRecord.REPETITION_TYPE_ARM_CURL, ) ) } @Test fun invalidTimes_throws() { assertFailsWith<IllegalArgumentException> { ExerciseRepetitionsRecord( startTime = Instant.ofEpochMilli(1234L), startZoneOffset = null, endTime = Instant.ofEpochMilli(1234L), endZoneOffset = null, count = 10, type = ExerciseRepetitionsRecord.REPETITION_TYPE_ARM_CURL, ) } } @Test fun allRepetitions_hasMapping() { val allEnums = ExerciseRepetitionsRecord.Companion::class .members .asSequence() .filter { it -> it.name.startsWith("REPETITION_TYPE") && !it.name.endsWith("UNKNOWN") } .filter { it -> it.returnType == typeOf<Int>() } .map { it -> it.call(ExerciseSessionRecord.Companion) } .toHashSet() assertThat(ExerciseRepetitionsRecord.REPETITION_TYPE_STRING_TO_INT_MAP.values) .containsExactlyElementsIn(allEnums) assertThat(ExerciseRepetitionsRecord.REPETITION_TYPE_INT_TO_STRING_MAP.keys) .containsExactlyElementsIn(allEnums) } }
apache-2.0
690bc134362a22e19572d0f5755a3fcc
34.790698
89
0.602664
5.190556
false
true
false
false
nrizzio/Signal-Android
app/src/main/java/org/thoughtcrime/securesms/mediapreview/MediaPreviewRepository.kt
1
2488
package org.thoughtcrime.securesms.mediapreview import io.reactivex.rxjava3.core.Flowable import io.reactivex.rxjava3.core.Single import io.reactivex.rxjava3.schedulers.Schedulers import org.signal.core.util.logging.Log import org.signal.core.util.requireLong import org.thoughtcrime.securesms.attachments.AttachmentId import org.thoughtcrime.securesms.database.AttachmentDatabase import org.thoughtcrime.securesms.database.MediaDatabase import org.thoughtcrime.securesms.database.MediaDatabase.Sorting import org.thoughtcrime.securesms.database.SignalDatabase.Companion.media /** * Repository for accessing the attachments in the encrypted database. */ class MediaPreviewRepository { companion object { private val TAG: String = Log.tag(MediaPreviewRepository::class.java) } /** * Accessor for database attachments. * @param startingUri the initial position to select from * @param threadId the thread to select from * @param sorting the ordering of the results * @param limit the maximum quantity of the results */ fun getAttachments(startingAttachmentId: AttachmentId, threadId: Long, sorting: Sorting, limit: Int = 500): Flowable<Result> { return Single.fromCallable { media.getGalleryMediaForThread(threadId, sorting).use { cursor -> val mediaRecords = mutableListOf<MediaDatabase.MediaRecord>() var startingRow = -1 while (cursor.moveToNext()) { if (startingAttachmentId.rowId == cursor.requireLong(AttachmentDatabase.ROW_ID) && startingAttachmentId.uniqueId == cursor.requireLong(AttachmentDatabase.UNIQUE_ID) ) { startingRow = cursor.position break } } var itemPosition = -1 if (startingRow >= 0) { val frontLimit: Int = limit / 2 val windowStart = if (startingRow >= frontLimit) startingRow - frontLimit else 0 itemPosition = startingRow - windowStart cursor.moveToPosition(windowStart) for (i in 0..limit) { val element = MediaDatabase.MediaRecord.from(cursor) if (element != null) { mediaRecords.add(element) } if (!cursor.moveToNext()) { break } } } Result(itemPosition, mediaRecords.toList()) } }.subscribeOn(Schedulers.io()).toFlowable() } data class Result(val initialPosition: Int, val records: List<MediaDatabase.MediaRecord>) }
gpl-3.0
d0a7043599c8b1ae10e8247bf55b5479
35.588235
128
0.690916
4.659176
false
false
false
false
GunoH/intellij-community
plugins/kotlin/idea/tests/testData/formatter/PropertyAccessors.kt
13
808
class Hi { val simple: Int get() = 1 val newline: String get() = "" var getterAndSetter: Int = 0 get() = 1 set(some) { field = some } var badNoType get() = 1 } class EmptyProperties { var newline: String get() { return "" } set(value) {} } class EmptyProperties { /** * */ var newline: String /** * */ get() { return "" } /** * */ set(value) {} } var prop: Int // Int get() = 1 // this is getter set(value) {} // this is setter val prop2: Int get = 1 // prop2 var prop3: Int // Int // this comment is for getter get() = 1 // this comment is for setter set(value) {} val prop4: Int get () = 42 set (value) {}
apache-2.0
63210262443e90a5a4af2788c6f174d7
12.711864
38
0.456683
3.591111
false
false
false
false
GunoH/intellij-community
platform/lang-api/src/com/intellij/codeInsight/hints/InlayParameterHintsProvider.kt
4
5883
// 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 com.intellij.codeInsight.hints import com.intellij.codeInsight.CodeInsightBundle import com.intellij.codeInsight.hints.settings.ParameterNameHintsSettings import com.intellij.lang.Language import com.intellij.lang.LanguageExtension import com.intellij.lang.LanguageExtensionPoint import com.intellij.openapi.editor.Editor import com.intellij.openapi.extensions.ExtensionPointName import com.intellij.openapi.util.NlsActions import com.intellij.openapi.util.NlsContexts import com.intellij.psi.PsiElement import org.jetbrains.annotations.Nls import org.jetbrains.annotations.NonNls import java.util.function.Supplier val PARAMETER_NAME_HINTS_EP: ExtensionPointName<LanguageExtensionPoint<InlayParameterHintsProvider>> = ExtensionPointName.create<LanguageExtensionPoint<InlayParameterHintsProvider>>("com.intellij.codeInsight.parameterNameHints") object InlayParameterHintsExtension : LanguageExtension<InlayParameterHintsProvider>(PARAMETER_NAME_HINTS_EP) /** * If you are just implementing parameter hints, only three options are relevant to you: text, offset, isShowOnlyIfExistedBefore. The rest * can be used in completion hints. * * @property text hints text to show * @property offset offset in document where hint should be shown * @property isShowOnlyIfExistedBefore defines if hint should be shown only if it was present in editor before update * * @property isFilterByExcludeList allows to prevent hints from filtering by blacklist matcher (possible use in completion hints) * @property relatesToPrecedingText whether hint is associated with previous or following text * @property widthAdjustment allows resulting hint's width to match certain editor text's width, see [HintWidthAdjustment] */ class InlayInfo(val text: String, val offset: Int, val isShowOnlyIfExistedBefore: Boolean, val isFilterByExcludeList: Boolean, val relatesToPrecedingText: Boolean, val widthAdjustment: HintWidthAdjustment?) { constructor(text: String, offset: Int, isShowOnlyIfExistedBefore: Boolean, isFilterByBlacklist: Boolean, relatesToPrecedingText: Boolean) : this(text, offset, isShowOnlyIfExistedBefore, isFilterByBlacklist, relatesToPrecedingText, null) constructor(text: String, offset: Int, isShowOnlyIfExistedBefore: Boolean) : this(text, offset, isShowOnlyIfExistedBefore, true, false) constructor(text: String, offset: Int) : this(text, offset, false, true, false) override fun equals(other: Any?): Boolean { if (this === other) return true if (other?.javaClass != javaClass) return false other as InlayInfo if (text != other.text) return false if (offset != other.offset) return false return true } override fun hashCode(): Int { var result = text.hashCode() result = 31 * result + offset return result } } sealed class HintInfo { /** * Provides fully qualified method name (e.g. "java.util.Map.put") and list of its parameter names. * Used to match method with exclude list, and to add method into exclude list. * @language in case you want to put this method into blacklist of another language. */ open class MethodInfo(val fullyQualifiedName: String, val paramNames: List<String>, val language: Language?) : HintInfo() { constructor(fullyQualifiedName: String, paramNames: List<String>) : this(fullyQualifiedName, paramNames, null) /** * Presentable method name which will be shown to the user when adding it to exclude list. */ open fun getMethodName(): String { val start = fullyQualifiedName.lastIndexOf('.') + 1 return fullyQualifiedName.substring(start) } /** * Presentable text which will be shown in the inlay hints popup menu. */ @NlsActions.ActionText open fun getDisableHintText(): String { return CodeInsightBundle.message("inlay.hints.show.settings", getMethodName()) } } /** * Provides option to disable/enable by alt-enter. */ open class OptionInfo(protected val option: Option) : HintInfo() { open fun disable(): Unit = alternate() open fun enable(): Unit = alternate() private fun alternate() { val current = option.get() option.set(!current) } open val optionName: String = option.name fun isOptionEnabled(): Boolean = option.isEnabled() } open fun isOwnedByPsiElement(elem: PsiElement, editor: Editor): Boolean { val textRange = elem.textRange if (textRange == null) return false val start = if (textRange.isEmpty) textRange.startOffset else textRange.startOffset + 1 return editor.inlayModel.hasInlineElementsInRange(start, textRange.endOffset) } } /** * @param id global unique identifier of this option * @param nameSupplier user visible name supplier */ data class Option(@NonNls val id: String, private val nameSupplier: Supplier<@NlsContexts.DetailedDescription String>, val defaultValue: Boolean) { @Deprecated("Use default constructor") constructor(@NonNls id: String, @Nls name: String, defaultValue: Boolean) : this(id, Supplier { name }, defaultValue) @get:NlsContexts.DetailedDescription val name: String get() = nameSupplier.get() var extendedDescriptionSupplier: Supplier<@NlsContexts.DetailedDescription String>? = null fun isEnabled(): Boolean = get() fun get(): Boolean { return ParameterNameHintsSettings.getInstance().getOption(id) ?: defaultValue } fun set(newValue: Boolean) { val settings = ParameterNameHintsSettings.getInstance() if (newValue == defaultValue) { settings.setOption(id, null) } else { settings.setOption(id, newValue) } } }
apache-2.0
bdd4b218246e52f28b169af7131008f3
36.954839
228
0.737889
4.834018
false
false
false
false
jwren/intellij-community
plugins/package-search/gradle/src/com/jetbrains/packagesearch/intellij/plugin/gradle/GradleProjectModuleOperationProvider.kt
1
3118
package com.jetbrains.packagesearch.intellij.plugin.gradle import com.intellij.buildsystem.model.OperationFailure import com.intellij.buildsystem.model.OperationItem import com.intellij.openapi.project.Project import com.intellij.psi.PsiFile import com.jetbrains.packagesearch.intellij.plugin.PackageSearchBundle import com.jetbrains.packagesearch.intellij.plugin.extensibility.AbstractProjectModuleOperationProvider import com.jetbrains.packagesearch.intellij.plugin.extensibility.DependencyOperationMetadata import com.jetbrains.packagesearch.intellij.plugin.extensibility.ProjectModule import com.jetbrains.packagesearch.intellij.plugin.extensibility.ProjectModuleType import com.jetbrains.packagesearch.intellij.plugin.gradle.configuration.PackageSearchGradleConfiguration private const val FILE_TYPE_GROOVY = "groovy" private const val FILE_TYPE_KOTLIN = "kotlin" private const val EXTENSION_GRADLE = "gradle" private const val EXTENSION_GRADLE_KTS = "gradle.kts" internal open class GradleProjectModuleOperationProvider : AbstractProjectModuleOperationProvider() { override fun usesSharedPackageUpdateInspection() = true override fun hasSupportFor(project: Project, psiFile: PsiFile?): Boolean { // Logic based on com.android.tools.idea.gradle.project.sync.GradleFiles.isGradleFile() val file = psiFile?.virtualFile ?: return false val isGroovyFile = FILE_TYPE_GROOVY.equals(psiFile.fileType.name, ignoreCase = true) val isKotlinFile = FILE_TYPE_KOTLIN.equals(psiFile.fileType.name, ignoreCase = true) if (!isGroovyFile && !isKotlinFile) return false return file.name.endsWith(EXTENSION_GRADLE, ignoreCase = true) || file.name.endsWith(EXTENSION_GRADLE_KTS, ignoreCase = true) } override fun hasSupportFor(projectModuleType: ProjectModuleType): Boolean = projectModuleType is GradleProjectModuleType override fun addDependencyToModule( operationMetadata: DependencyOperationMetadata, module: ProjectModule ): List<OperationFailure<out OperationItem>> { saveAdditionalScopeToConfigurationIfNeeded(module.nativeModule.project, requireNotNull(operationMetadata.newScope) { PackageSearchBundle.getMessage("packagesearch.operation.error.gradle.missing.configuration") }) return super.addDependencyToModule(operationMetadata, module) } override fun removeDependencyFromModule( operationMetadata: DependencyOperationMetadata, module: ProjectModule ): List<OperationFailure<out OperationItem>> { requireNotNull(operationMetadata.currentScope) { PackageSearchBundle.getMessage("packagesearch.operation.error.gradle.missing.configuration") } return super.removeDependencyFromModule(operationMetadata, module) } private fun saveAdditionalScopeToConfigurationIfNeeded(project: Project, scopeName: String) { val configuration = PackageSearchGradleConfiguration.getInstance(project) if (configuration.updateScopesOnUsage) { configuration.addGradleScope(scopeName) } } }
apache-2.0
53415c0c88f17b4f8d75ac2b27a51430
47.71875
133
0.783515
5.489437
false
true
false
false
junerver/CloudNote
app/src/main/java/com/junerver/cloudnote/ui/activity/MainActivity.kt
1
2422
package com.junerver.cloudnote.ui.activity import android.view.View import androidx.fragment.app.Fragment import androidx.fragment.app.FragmentManager import androidx.fragment.app.FragmentPagerAdapter import androidx.viewpager.widget.ViewPager import com.junerver.cloudnote.R import com.junerver.cloudnote.databinding.ActivityMainBinding import com.junerver.cloudnote.ui.fragment.ConfigFragment import com.junerver.cloudnote.ui.fragment.NoteFragment import com.junerver.cloudnote.ui.widget.TabView import java.util.HashMap class MainActivity : BaseActivity<ActivityMainBinding>() { private val mTitle = arrayOf("笔记", "设置") private val mIconSelect = intArrayOf(R.drawable.docker_tab_doc_selected, R.drawable.docker_tab_setting_selected) private val mIconNormal = intArrayOf(R.drawable.docker_tab_doc_normal, R.drawable.docker_tab_setting_normal) private lateinit var mViewPager: ViewPager private lateinit var mTabView: TabView private lateinit var mFragmentMap: MutableMap<Int, Fragment> override fun initView() { mFragmentMap = HashMap<Int, Fragment>() mViewPager = viewBinding.idViewPager mViewPager.offscreenPageLimit = 2 mViewPager.adapter = PageAdapter(supportFragmentManager) mTabView = viewBinding.idTab mTabView.setViewPager(mViewPager) } override fun initData() {} override fun setListeners() {} private fun getFragment(position: Int): Fragment { var fragment = mFragmentMap[position] if (fragment == null) { when (position) { 0 -> fragment = NoteFragment() 1 -> fragment = ConfigFragment() } mFragmentMap[position] = fragment!! } return fragment!! } internal inner class PageAdapter(fm: FragmentManager) : FragmentPagerAdapter(fm), TabView.OnItemIconTextSelectListener { override fun getItem(position: Int): Fragment { return getFragment(position) } override fun onIconSelect(position: Int): IntArray { val icon = IntArray(2) icon[0] = mIconSelect[position] icon[1] = mIconNormal[position] return icon } override fun onTextSelect(position: Int): String { return mTitle[position] } override fun getCount(): Int { return mTitle.size } } }
apache-2.0
785f0dc1fd1d96fa00c25dfdc36916e5
35.044776
116
0.684756
4.808765
false
false
false
false
smmribeiro/intellij-community
plugins/github/src/org/jetbrains/plugins/github/pullrequest/comment/ui/GHPRReviewThreadModelImpl.kt
1
3155
// 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 org.jetbrains.plugins.github.pullrequest.comment.ui import com.intellij.collaboration.ui.SimpleEventListener import com.intellij.ui.CollectionListModel import com.intellij.util.EventDispatcher import org.jetbrains.plugins.github.api.data.pullrequest.GHPullRequestReviewThread class GHPRReviewThreadModelImpl(thread: GHPullRequestReviewThread) : CollectionListModel<GHPRReviewCommentModel>(thread.comments.map { GHPRReviewCommentModel.convert(it, thread.startLine) }), GHPRReviewThreadModel { override val id: String = thread.id override val createdAt = thread.createdAt override var state = thread.state private set override var isResolved: Boolean = thread.isResolved private set override var isOutdated: Boolean = thread.isOutdated private set override val commit = thread.originalCommit override val filePath = thread.path override val diffHunk = thread.diffHunk override val line = thread.line override val startLine = thread.startLine private val stateEventDispatcher = EventDispatcher.create(SimpleEventListener::class.java) init { maybeMarkFirstCommentResolved() } override fun update(thread: GHPullRequestReviewThread) { var dataChanged = false if (state != thread.state) { state = thread.state dataChanged = true } if (isResolved != thread.isResolved) { isResolved = thread.isResolved dataChanged = true } if (isOutdated != thread.isOutdated) { isOutdated = thread.isOutdated dataChanged = true } if (dataChanged) stateEventDispatcher.multicaster.eventOccurred() var removed = 0 for (i in 0 until items.size) { val idx = i - removed val newComment = thread.comments.getOrNull(idx) if (newComment == null) { removeRange(idx, items.size - 1) break } val comment = items.getOrNull(idx) ?: break if (comment.id == newComment.id) { if (comment.update(newComment)) fireContentsChanged(this, idx, idx) } else { remove(idx) removed++ } } val newComments = thread.comments.subList(size, thread.comments.size) add(newComments.map { GHPRReviewCommentModel.convert(it, thread.startLine) }) maybeMarkFirstCommentResolved() } private fun maybeMarkFirstCommentResolved() { if (size > 0) { getElementAt(0).isFirstInResolvedThread = isResolved for (i in 1 until size) { getElementAt(i).isFirstInResolvedThread = false } } } override fun addComment(comment: GHPRReviewCommentModel) { add(comment) } override fun addAndInvokeStateChangeListener(listener: () -> Unit) = SimpleEventListener.addAndInvokeListener(stateEventDispatcher, listener) override fun equals(other: Any?): Boolean { if (this === other) return true if (other !is GHPRReviewThreadModelImpl) return false if (id != other.id) return false return true } override fun hashCode(): Int { return id.hashCode() } }
apache-2.0
eb8bcba537d66230816841fd04cf01e6
29.640777
140
0.709984
4.592431
false
false
false
false
hazuki0x0/YuzuBrowser
legacy/src/main/java/jp/hazuki/yuzubrowser/legacy/settings/preference/ProxySettingDialog.kt
1
4417
/* * Copyright (C) 2017-2019 Hazuki * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package jp.hazuki.yuzubrowser.legacy.settings.preference import android.app.AlertDialog import android.app.Dialog import android.content.Context import android.os.Bundle import android.util.AttributeSet import android.view.LayoutInflater import android.widget.CheckBox import android.widget.EditText import jp.hazuki.yuzubrowser.legacy.R import jp.hazuki.yuzubrowser.legacy.webkit.WebViewProxy import jp.hazuki.yuzubrowser.ui.preference.CustomDialogPreference import jp.hazuki.yuzubrowser.ui.settings.AppPrefs class ProxySettingDialog @JvmOverloads constructor( context: Context, attrs: AttributeSet? = null ) : CustomDialogPreference(context, attrs) { private var mSaveSettings = true fun setSaveSettings(save: Boolean): ProxySettingDialog { mSaveSettings = save return this } override fun crateCustomDialog(): CustomDialogFragment { return SettingDialog.newInstance(mSaveSettings) } class SettingDialog : CustomDialogPreference.CustomDialogFragment() { override fun onCreateDialog(savedInstanceState: Bundle?): Dialog { val view = LayoutInflater.from(context).inflate(R.layout.proxy_dialog, null) val checkBox = view.findViewById<CheckBox>(R.id.checkBox) val editText = view.findViewById<EditText>(R.id.editText) val httpsCheckBox = view.findViewById<CheckBox>(R.id.httpsCheckBox) val httpsText = view.findViewById<EditText>(R.id.httpsEditText) httpsCheckBox.setOnCheckedChangeListener { _, isChecked -> httpsText.isEnabled = isChecked } checkBox.isChecked = AppPrefs.proxy_set.get() editText.setText(AppPrefs.proxy_address.get()) httpsCheckBox.isChecked = AppPrefs.proxy_https_set.get() httpsText.setText(AppPrefs.proxy_https_address.get()) httpsText.isEnabled = httpsCheckBox.isChecked val builder = AlertDialog.Builder(activity) builder .setView(view) .setTitle(R.string.pref_proxy_settings) .setPositiveButton(android.R.string.ok) { _, _ -> val context = context val enable = checkBox.isChecked val proxyAddress = editText.text.toString() val enableHttps = httpsCheckBox.isChecked val httpsProxyAddress = httpsText.text.toString() if (enable) { val https = if (enableHttps) httpsProxyAddress else null WebViewProxy.setProxy(proxyAddress, https) } else { WebViewProxy.clearProxy() } if (requireArguments().getBoolean(SAVE)) { AppPrefs.proxy_set.set(enable) AppPrefs.proxy_address.set(proxyAddress) AppPrefs.proxy_https_set.set(enableHttps) AppPrefs.proxy_https_address.set(httpsProxyAddress) AppPrefs.commit(context, AppPrefs.proxy_set, AppPrefs.proxy_address, AppPrefs.proxy_https_set, AppPrefs.proxy_https_address) } } .setNegativeButton(android.R.string.cancel, null) return builder.create() } companion object { private const val SAVE = "save" fun newInstance(save: Boolean): SettingDialog { val dialog = SettingDialog() val bundle = Bundle() bundle.putBoolean(SAVE, save) dialog.arguments = bundle return dialog } } } }
apache-2.0
3cd9bb337f76cb44100e1f356fa18529
39.522936
104
0.620783
5.136047
false
false
false
false
Magneticraft-Team/ModelLoader
src/main/kotlin/com/cout970/modelloader/gltf/UnbakedGltfModel.kt
1
2770
package com.cout970.modelloader.gltf import com.cout970.modelloader.animation.AnimatedModel import com.cout970.modelloader.api.AnimatableModel import com.cout970.modelloader.api.FilterableModel import com.cout970.modelloader.api.MutableModelConversion import com.cout970.modelloader.mutable.MutableModel import net.minecraft.client.renderer.model.IBakedModel import net.minecraft.client.renderer.model.IUnbakedModel import net.minecraft.client.renderer.model.ModelBakery import net.minecraft.client.renderer.model.ModelRotation import net.minecraft.client.renderer.texture.ISprite import net.minecraft.client.renderer.texture.TextureAtlasSprite import net.minecraft.client.renderer.vertex.VertexFormat import net.minecraft.util.ResourceLocation import java.util.function.Function class UnbakedGltfModel(val tree: GltfTree.DefinitionTree) : IUnbakedModel, FilterableModel, AnimatableModel, MutableModelConversion { override fun getDependencies(): MutableCollection<ResourceLocation> = mutableListOf() override fun bake(bakery: ModelBakery, spriteGetter: Function<ResourceLocation, TextureAtlasSprite>, sprite: ISprite, format: VertexFormat): IBakedModel? { return GltfBaker(format, spriteGetter, sprite as? ModelRotation ?: ModelRotation.X0_Y0).bake(this) } override fun getTextures(modelGetter: Function<ResourceLocation, IUnbakedModel>, missingTextureErrors: MutableSet<String>): MutableCollection<ResourceLocation> { return tree.textures.toMutableList() } override fun filterParts(filter: (String) -> Boolean): UnbakedGltfModel { // Filter nodes from scenes val newScenes = tree.scenes.map { GltfTree.Scene(filterNodes(it.nodes, filter)) } // Keep all the tree except the scenes val newTree = tree.copy(scenes = newScenes) return UnbakedGltfModel(newTree) } private fun filterNodes(nodes: List<GltfTree.Node>, filter: (String) -> Boolean): List<GltfTree.Node> { return nodes.mapNotNull { node -> if (node.name == null || filter(node.name)) { // Create a new node with filtered children node.copy(children = filterNodes(node.children, filter)) } else { // Discard the node null } } } override fun toMutable(sprites: Function<ResourceLocation, TextureAtlasSprite>, format: VertexFormat): MutableModel { return GltfBaker(format, sprites, ModelRotation.X0_Y0).bakeMutableModel(this) } override fun getAnimations(): Map<String, AnimatedModel> { var count = 0 return tree.animations.map { val name = it.name ?: "Animation${count++}" name to GltfAnimator(tree).animate(it) }.toMap() } }
gpl-2.0
8e7db5a90cd02a8a18580446290c2c89
44.42623
165
0.728159
4.460548
false
false
false
false
fod-dev/bsi-token-parser
src/main/kotlin/com/fortify/fod/parser/BsiToken.kt
1
1889
/* * (c) Copyright 2017 EntIT Software LLC * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.fortify.fod.parser /** * A Build Server (Continuous) Integration Token for integrating with Fortify on Demand */ class BsiToken { var tenantId: Int = 0 var tenantCode: String = "" var projectVersionId: Int = 0 var assessmentTypeId: Int = 0 var payloadType: String = "ANALYSIS_PAYLOAD" var scanPreferenceId: Int = 1 var scanPreference: String = "Standard" var auditPreferenceId: Int = 1 var auditPreference: String = "Manual" var includeThirdParty: Boolean = false var includeOpenSourceAnalysis: Boolean = false var portalUri: String = "https://ams.fortify.com" var apiUri: String = "https://api.ams.fortify.com" var technologyTypeId: Int = 0 var technologyType: String? = null var technologyVersion: String? = null var technologyVersionId: Int? = null /** * Legacy alias for Technology Type */ var technologyStack: String? get() { return technologyType } set(value) { this.technologyType = value } /** * Legacy alias for Technology Version */ var languageLevel: String? get() { return technologyVersion } set(value) { this.technologyVersion = value } }
apache-2.0
0bf0eb6dc06b748658e7337ec4c5ac7b
26.779412
87
0.662255
4.293182
false
false
false
false
AlmasB/FXGL
fxgl/src/main/kotlin/com/almasb/fxgl/app/scene/FXGLMenu.kt
1
5037
/* * FXGL - JavaFX Game Library. The MIT License (MIT). * Copyright (c) AlmasB ([email protected]). * See LICENSE for details. */ package com.almasb.fxgl.app.scene import com.almasb.fxgl.core.util.InputPredicates import com.almasb.fxgl.dsl.FXGL import com.almasb.fxgl.dsl.getDialogService import com.almasb.fxgl.dsl.getSettings import com.almasb.fxgl.dsl.localize import com.almasb.fxgl.logging.Logger import com.almasb.fxgl.profile.SaveFile import com.almasb.fxgl.profile.SaveLoadService import com.almasb.fxgl.scene.SubScene import java.util.function.Consumer /** * This is a base class for main/game menus. * Custom menus can interact with FXGL by calling fireXXXX methods. * * @author Almas Baimagambetov (AlmasB) ([email protected]) */ abstract class FXGLMenu(protected val type: MenuType) : SubScene() { companion object { private val log = Logger.get("Menu") } protected val saveLoadService: SaveLoadService = FXGL.getSaveLoadService() protected val controller by lazy { FXGL.getGameController() } protected val appWidth by lazy { FXGL.getAppWidth() } protected val appHeight by lazy { FXGL.getAppHeight() } /** * Starts new game. */ protected fun fireNewGame() { log.debug("fireNewGame()") controller.startNewGame() } /** * Loads the game state from last modified save file. */ protected fun fireContinue() { log.debug("fireContinue()") val task = saveLoadService .readLastModifiedSaveFileTask("./", getSettings().saveFileExt) .onSuccess { it.ifPresent { fireLoad(it) } } FXGL.getTaskService().runAsyncFXWithDialog(task, localize("menu.loading") + "...") } /** * Loads the game state from a [saveFile]. */ protected fun fireLoad(saveFile: SaveFile) { log.debug("fireLoad()") val text = localize("menu.loadSave") + " [${saveFile.name}]?\n" + localize("menu.unsavedProgress") getDialogService().showConfirmationBox(text) { yes -> if (yes) { // we don't need to run this with "runAsyncFXWithDialog" since loadGame triggers LoadingScene controller.loadGame(saveFile.data) } } } /** * Can only be fired from game menu. * Saves current state of the game to a file whose name is provided by user. */ protected fun fireSave() { log.debug("fireSave()") getDialogService().showInputBoxWithCancel(localize("menu.enterSaveName"), InputPredicates.ALPHANUM, Consumer { saveFileName -> if (saveFileName.isEmpty()) return@Consumer val saveFile = SaveFile(saveFileName + "." + getSettings().saveFileExt) if (saveLoadService.saveFileExists(saveFile.name)) { getDialogService().showConfirmationBox(localize("menu.overwrite") +" [$saveFileName]?") { yes -> if (yes) doSave(saveFile) } } else { doSave(saveFile) } }) } private fun doSave(saveFile: SaveFile) { controller.saveGame(saveFile.data) FXGL.getTaskService().runAsyncFXWithDialog( saveLoadService.writeTask(saveFile.name, saveFile.data), localize("menu.savingData") + ": ${saveFile.name}" ) } /** * Deletes a given [saveFile]. */ protected fun fireDelete(saveFile: SaveFile) { log.debug("fireDelete()") getDialogService().showConfirmationBox(localize("menu.deleteSave") + "[${saveFile.name}]?") { yes -> if (yes) { val task = saveLoadService.deleteSaveFileTask(saveFile.name) FXGL.getTaskService().runAsyncFXWithDialog(task, localize("menu.deleting") + ": ${saveFile.name}") } } } /** * Can only be fired from game menu. * Will close the menu and unpause the game. */ protected fun fireResume() { log.debug("fireResume()") FXGL.getSceneService().popSubScene() } /** * Shows an exit dialog. * If the user selects "yes", the game will exit. */ protected fun fireExit() { log.debug("fireExit()") val text = localize("dialog.exitGame") getDialogService().showConfirmationBox(text) { yes -> if (yes) controller.exit() } } /** * Shows an "exit to main menu" dialog. * If the user selects "yes", the game will exit to main menu. */ protected fun fireExitToMainMenu() { log.debug("fireExitToMainMenu()") val text = localize("menu.exitMainMenu") + "\n" + localize("menu.unsavedProgress") getDialogService().showConfirmationBox(text) { yes -> if (yes) controller.gotoMainMenu() } } protected fun restoreDefaultSettings() { log.debug("restoreDefaultSettings()") } }
mit
550eed9bdd30afdeebf2fe96b0380917
28.629412
134
0.606909
4.50134
false
false
false
false
googlecodelabs/android-compose-codelabs
AdaptiveUICodelab/app/src/main/java/com/example/reply/ui/MainActivity.kt
1
2097
/* * Copyright 2022 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.reply.ui import android.os.Bundle import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.activity.viewModels import androidx.compose.runtime.Composable import androidx.compose.runtime.collectAsState import androidx.compose.ui.tooling.preview.Preview import com.example.reply.data.local.LocalEmailsDataProvider import com.example.reply.ui.theme.ReplyTheme class MainActivity : ComponentActivity() { private val viewModel: ReplyHomeViewModel by viewModels() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { ReplyTheme { val uiState = viewModel.uiState.collectAsState().value ReplyApp(uiState) } } } } @Preview(showBackground = true) @Composable fun ReplyAppPreview() { ReplyTheme { ReplyApp(replyHomeUIState = ReplyHomeUIState( emails = LocalEmailsDataProvider.allEmails )) } } @Preview(showBackground = true, widthDp = 700) @Composable fun ReplyAppPreviewTablet() { ReplyTheme { ReplyApp(replyHomeUIState = ReplyHomeUIState( emails = LocalEmailsDataProvider.allEmails )) } } @Preview(showBackground = true, widthDp = 1000) @Composable fun ReplyAppPreviewDesktop() { ReplyTheme { ReplyApp(replyHomeUIState = ReplyHomeUIState( emails = LocalEmailsDataProvider.allEmails )) } }
apache-2.0
e0abecee6711436881d1b6cb16de49c8
27.739726
75
0.716738
4.722973
false
false
false
false
RP-Kit/RPKit
bukkit/rpk-skills-bukkit/src/main/kotlin/com/rpkit/skills/bukkit/command/BindSkillCommand.kt
1
3796
/* * Copyright 2021 Ren Binden * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.rpkit.skills.bukkit.command import com.rpkit.characters.bukkit.character.RPKCharacterService import com.rpkit.core.service.Services import com.rpkit.players.bukkit.profile.minecraft.RPKMinecraftProfileService import com.rpkit.skills.bukkit.RPKSkillsBukkit import com.rpkit.skills.bukkit.skills.RPKSkillName import com.rpkit.skills.bukkit.skills.RPKSkillService import org.bukkit.command.Command import org.bukkit.command.CommandExecutor import org.bukkit.command.CommandSender import org.bukkit.entity.Player class BindSkillCommand(private val plugin: RPKSkillsBukkit) : CommandExecutor { override fun onCommand(sender: CommandSender, command: Command, label: String, args: Array<out String>): Boolean { if (!sender.hasPermission("rpkit.skills.command.bindskill")) { sender.sendMessage(plugin.messages["no-permission-bind-skill"]) return true } if (args.isEmpty()) { sender.sendMessage(plugin.messages["bind-skill-usage"]) return true } val skillService = Services[RPKSkillService::class.java] if (skillService == null) { sender.sendMessage(plugin.messages["no-skill-service"]) return true } val skillName = args[0] val skill = skillService.getSkill(RPKSkillName(skillName)) if (skill == null) { sender.sendMessage(plugin.messages["bind-skill-invalid-skill"]) return true } if (sender !is Player) { sender.sendMessage(plugin.messages["not-from-console"]) return true } val minecraftProfileService = Services[RPKMinecraftProfileService::class.java] if (minecraftProfileService == null) { sender.sendMessage(plugin.messages["no-minecraft-profile-service"]) return true } val minecraftProfile = minecraftProfileService.getPreloadedMinecraftProfile(sender) if (minecraftProfile == null) { sender.sendMessage(plugin.messages["no-minecraft-profile"]) return true } val characterService = Services[RPKCharacterService::class.java] if (characterService == null) { sender.sendMessage(plugin.messages["no-character-service"]) return true } val character = characterService.getPreloadedActiveCharacter(minecraftProfile) if (character == null) { sender.sendMessage(plugin.messages["no-character"]) return true } val item = sender.inventory.itemInMainHand if (skillService.getPreloadedSkillBinding(character, item) != null) { sender.sendMessage(plugin.messages["bind-skill-invalid-binding-already-exists"]) return true } skillService.setSkillBinding(character, item, skill).thenRun { sender.sendMessage( plugin.messages["bind-skill-valid", mapOf( "character" to character.name, "item" to item.type.toString().lowercase().replace('_', ' '), "skill" to skill.name.value )] ) } return true } }
apache-2.0
bf42b8f8d6c00682111f77a83a026c8a
40.725275
118
0.662276
4.733167
false
false
false
false
luxons/seven-wonders
sw-engine/src/main/kotlin/org/luxons/sevenwonders/engine/data/GameDefinition.kt
1
4597
package org.luxons.sevenwonders.engine.data import com.github.salomonbrys.kotson.typeToken import com.google.gson.Gson import com.google.gson.GsonBuilder import org.luxons.sevenwonders.engine.Game import org.luxons.sevenwonders.engine.boards.Board import org.luxons.sevenwonders.engine.data.definitions.DecksDefinition import org.luxons.sevenwonders.engine.data.definitions.WonderDefinition import org.luxons.sevenwonders.engine.data.serializers.NumericEffectSerializer import org.luxons.sevenwonders.engine.data.serializers.ProductionIncreaseSerializer import org.luxons.sevenwonders.engine.data.serializers.ProductionSerializer import org.luxons.sevenwonders.engine.data.serializers.ResourceTypeSerializer import org.luxons.sevenwonders.engine.data.serializers.ResourceTypesSerializer import org.luxons.sevenwonders.engine.data.serializers.ResourcesSerializer import org.luxons.sevenwonders.engine.data.serializers.ScienceProgressSerializer import org.luxons.sevenwonders.engine.effects.GoldIncrease import org.luxons.sevenwonders.engine.effects.MilitaryReinforcements import org.luxons.sevenwonders.engine.effects.ProductionIncrease import org.luxons.sevenwonders.engine.effects.RawPointsIncrease import org.luxons.sevenwonders.engine.effects.ScienceProgress import org.luxons.sevenwonders.engine.resources.Production import org.luxons.sevenwonders.engine.resources.Resources import org.luxons.sevenwonders.model.Age import org.luxons.sevenwonders.model.Settings import org.luxons.sevenwonders.model.resources.ResourceType import org.luxons.sevenwonders.model.wonders.AssignedWonder import org.luxons.sevenwonders.model.wonders.PreGameWonder internal const val LAST_AGE: Age = 3 internal data class GlobalRules( val minPlayers: Int, val maxPlayers: Int, ) class GameDefinition internal constructor( rules: GlobalRules, wonderDefinitions: List<WonderDefinition>, private val decksDefinition: DecksDefinition, ) { val minPlayers: Int = rules.minPlayers val maxPlayers: Int = rules.maxPlayers val allWonders: List<PreGameWonder> = wonderDefinitions.map { w -> PreGameWonder(w.name, w.sides.mapValues { (_, def) -> def.image }) } private val wondersByName = wonderDefinitions.associateBy { it.name } fun createGame(id: Long, wonders: Collection<AssignedWonder>, settings: Settings): Game { val nbPlayers = wonders.size val boards = wonders.mapIndexed { index, wonder -> wonder.createBoard(index, settings) } val decks = decksDefinition.prepareDecks(nbPlayers, settings.random) return Game(id, settings, boards, decks) } private fun AssignedWonder.createBoard(playerIndex: Int, settings: Settings): Board { val wonder = wondersByName[name] ?: error("Unknown wonder '$name'") return Board(wonder.create(side), playerIndex, settings) } companion object { fun load(): GameDefinition { val gson: Gson = createGson() val rules = loadJson("global_rules.json", GlobalRules::class.java, gson) val wonders = loadJson("wonders.json", Array<WonderDefinition>::class.java, gson) val decksDefinition = loadJson("cards.json", DecksDefinition::class.java, gson) return GameDefinition(rules, wonders.toList(), decksDefinition) } } } private fun <T> loadJson(filename: String, clazz: Class<T>, gson: Gson): T { val packageAsPath = GameDefinition::class.java.`package`.name.replace('.', '/') val resourcePath = "/$packageAsPath/$filename" val resource = GameDefinition::class.java.getResource(resourcePath) val json = resource.readText() return gson.fromJson(json, clazz) } private fun createGson(): Gson { return GsonBuilder().disableHtmlEscaping() .registerTypeAdapter<Resources>(ResourcesSerializer()) .registerTypeAdapter<ResourceType>(ResourceTypeSerializer()) .registerTypeAdapter<List<ResourceType>>(ResourceTypesSerializer()) .registerTypeAdapter<Production>(ProductionSerializer()) .registerTypeAdapter<ProductionIncrease>(ProductionIncreaseSerializer()) .registerTypeAdapter<MilitaryReinforcements>(NumericEffectSerializer()) .registerTypeAdapter<RawPointsIncrease>(NumericEffectSerializer()) .registerTypeAdapter<GoldIncrease>(NumericEffectSerializer()) .registerTypeAdapter<ScienceProgress>(ScienceProgressSerializer()) .create() } private inline fun <reified T : Any> GsonBuilder.registerTypeAdapter(typeAdapter: Any): GsonBuilder = this.registerTypeAdapter(typeToken<T>(), typeAdapter)
mit
a44243db14fb2da484b40b8d2d73dcb3
45.908163
101
0.771155
4.610832
false
false
false
false
ujpv/intellij-rust
src/main/kotlin/org/rust/ide/surroundWith/statement/RustWithIfSurrounder.kt
1
816
package org.rust.ide.surroundWith.statement import com.intellij.openapi.project.Project import com.intellij.psi.PsiElement import org.rust.lang.core.psi.RustBlockElement import org.rust.lang.core.psi.RustIfExprElement import org.rust.lang.core.psi.RustPsiFactory class RustWithIfSurrounder : RustStatementsSurrounderBase() { override fun getTemplateDescription(): String = "if { }" override fun createTemplate(project: Project): PsiElement = RustPsiFactory(project).createExpression("if a {\n}") override fun getCodeBlock(expression: PsiElement): RustBlockElement = checkNotNull((expression as RustIfExprElement).block) override val shouldRemoveExpr = true override fun getExprForRemove(expression: PsiElement): PsiElement = (expression as RustIfExprElement).expr }
mit
f6796749590d9dc7c3bef954a7173865
36.090909
73
0.778186
4.558659
false
false
false
false
JakeWharton/RxBinding
rxbinding/src/main/java/com/jakewharton/rxbinding4/widget/SeekBarChangeObservable.kt
1
2705
@file:JvmName("RxSeekBar") @file:JvmMultifileClass package com.jakewharton.rxbinding4.widget import android.widget.SeekBar import android.widget.SeekBar.OnSeekBarChangeListener import androidx.annotation.CheckResult import com.jakewharton.rxbinding4.InitialValueObservable import io.reactivex.rxjava3.core.Observer import io.reactivex.rxjava3.android.MainThreadDisposable import com.jakewharton.rxbinding4.internal.checkMainThread /** * Create an observable of progress value changes on `view`. * * *Warning:* The created observable keeps a strong reference to `view`. Unsubscribe * to free this reference. * * *Note:* A value will be emitted immediately on subscribe. */ @CheckResult fun SeekBar.changes(): InitialValueObservable<Int> { return SeekBarChangeObservable(this, null) } /** * Create an observable of progress value changes on `view` that were made only from the * user. * * *Warning:* The created observable keeps a strong reference to `view`. Unsubscribe * to free this reference. * * *Note:* A value will be emitted immediately on subscribe. */ @CheckResult fun SeekBar.userChanges(): InitialValueObservable<Int> { return SeekBarChangeObservable(this, true) } /** * Create an observable of progress value changes on `view` that were made only from the * system. * * *Warning:* The created observable keeps a strong reference to `view`. Unsubscribe * to free this reference. * * *Note:* A value will be emitted immediately on subscribe. */ @CheckResult fun SeekBar.systemChanges(): InitialValueObservable<Int> { return SeekBarChangeObservable(this, false) } private class SeekBarChangeObservable( private val view: SeekBar, private val shouldBeFromUser: Boolean? ) : InitialValueObservable<Int>() { override fun subscribeListener(observer: Observer<in Int>) { if (!checkMainThread(observer)) { return } val listener = Listener(view, shouldBeFromUser, observer) view.setOnSeekBarChangeListener(listener) observer.onSubscribe(listener) } override val initialValue get() = view.progress private class Listener( private val view: SeekBar, private val shouldBeFromUser: Boolean?, private val observer: Observer<in Int> ) : MainThreadDisposable(), OnSeekBarChangeListener { override fun onProgressChanged(seekBar: SeekBar, progress: Int, fromUser: Boolean) { if (!isDisposed && (shouldBeFromUser == null || shouldBeFromUser == fromUser)) { observer.onNext(progress) } } override fun onStartTrackingTouch(seekBar: SeekBar) {} override fun onStopTrackingTouch(seekBar: SeekBar) {} override fun onDispose() { view.setOnSeekBarChangeListener(null) } } }
apache-2.0
d068f424d8ca1c280d41012db4c73c0f
28.402174
88
0.747874
4.584746
false
false
false
false
sungmin-park/validator.kt
src/main/kotlin/com/github/sungminpark/validator/SizeGe.kt
1
1132
package com.github.sungminpark.validator import javax.validation.Constraint import javax.validation.ConstraintValidator import javax.validation.ConstraintValidatorContext import javax.validation.Payload import kotlin.reflect.KClass @Target(AnnotationTarget.FIELD) @Retention @Constraint(validatedBy = arrayOf(SizeGeValidator::class)) annotation class SizeGe(val value: Int, val message: String = "{com.github.sungminpark.validator.SizeGe}", @Suppress("unused") val groups: Array<KClass<*>> = arrayOf(), @Suppress("unused") val payload: Array<KClass<out Payload>> = arrayOf()) class SizeGeValidator : ConstraintValidator<SizeGe, Any> { private var size: Int = 0 private lateinit var message: String override fun initialize(constraintAnnotation: SizeGe) { size = constraintAnnotation.value message = constraintAnnotation.message } override fun isValid(value: Any?, context: ConstraintValidatorContext): Boolean { if (value == null) { return true } return sizeOf(value) >= size } }
mit
cfaa9a77437d1149a2b9ce5aaa485824
33.333333
96
0.690813
4.697095
false
false
false
false
LorittaBot/Loritta
discord/loritta-bot-common/src/main/kotlin/net/perfectdreams/loritta/cinnamon/discord/interactions/commands/customoptions/ImageReferenceCommandOption.kt
1
4119
package net.perfectdreams.loritta.cinnamon.discord.interactions.commands.customoptions import dev.kord.common.Locale import dev.kord.common.entity.CommandArgument import dev.kord.common.entity.DiscordInteraction import dev.kord.common.entity.Snowflake import dev.kord.core.Kord import dev.kord.rest.Image import dev.kord.rest.builder.interaction.BaseInputChatBuilder import dev.kord.rest.builder.interaction.string import net.perfectdreams.discordinteraktions.common.commands.options.CommandOptionBuilder import net.perfectdreams.discordinteraktions.common.commands.options.NameableCommandOption import net.perfectdreams.loritta.cinnamon.discord.interactions.commands.ApplicationCommandContext import net.perfectdreams.loritta.cinnamon.discord.utils.ContextStringToUserInfoConverter import net.perfectdreams.loritta.cinnamon.discord.utils.UserUtils import net.perfectdreams.loritta.common.images.URLImageReference import net.perfectdreams.loritta.common.locale.LanguageManager import kotlin.streams.toList // ===[ OPTION ]=== @JvmInline value class ImageReferenceIntermediaryData(val value: String) { suspend fun get(context: ApplicationCommandContext): URLImageReference { // Now check if it is a valid thing! // First, we will try matching via user mentions or user IDs val cachedUserInfo = ContextStringToUserInfoConverter.convert( context, value ) if (cachedUserInfo != null) { val icon = UserUtils.createUserAvatarOrDefaultUserAvatar( context.loritta.interaKTions.kord, Snowflake(cachedUserInfo.id.value), cachedUserInfo.avatarId, cachedUserInfo.discriminator ) return URLImageReference(icon.cdnUrl.toUrl { this.format = Image.Format.PNG this.size = Image.Size.Size128 }) } if (value.startsWith("http")) { // It is a URL! // TODO: Use a RegEx to check if it is a valid URL return URLImageReference(value) } // It is a emote! // Discord emotes always starts with "<" and ends with ">" return if (value.startsWith("<") && value.endsWith(">")) { val emoteId = value.substringAfterLast(":").substringBefore(">") URLImageReference("https://cdn.discordapp.com/emojis/${emoteId}.png?v=1") } else { // If not, we are going to handle it as if it were a Unicode emoji val emoteId = value.codePoints().toList() .joinToString(separator = "-") { String.format("\\u%04x", it).substring(2) } URLImageReference("https://twemoji.maxcdn.com/2/72x72/$emoteId.png") } } } class ImageReferenceCommandOption( val languageManager: LanguageManager, override val name: String, val required: Boolean, ) : NameableCommandOption<ImageReferenceIntermediaryData> { override val description = "User, URL or Emoji" override val nameLocalizations: Map<Locale, String> = emptyMap() override val descriptionLocalizations: Map<Locale, String> = emptyMap() override fun register(builder: BaseInputChatBuilder) { builder.string(name, description) { this.nameLocalizations = [email protected]() this.required = [email protected] } } override fun parse( kord: Kord, args: List<CommandArgument<*>>, interaction: DiscordInteraction ): ImageReferenceIntermediaryData { val value = args.first { it.name == name }.value as String return ImageReferenceIntermediaryData(value) } } // ===[ BUILDER ]=== class ImageReferenceCommandOptionBuilder( val languageManager: LanguageManager, override val name: String, override val required: Boolean ) : CommandOptionBuilder<ImageReferenceIntermediaryData, ImageReferenceIntermediaryData>() { override fun build() = ImageReferenceCommandOption( languageManager, name, required ) }
agpl-3.0
ce4c201f220d52ab3a36d5e8faf5d45f
39.392157
102
0.695314
4.868794
false
false
false
false
edsilfer/presence-control
app/src/main/java/br/com/edsilfer/android/presence_control/main/presentation/view/MainActivity.kt
1
4589
package br.com.edsilfer.android.presence_control.main.presentation.view import android.Manifest.permission.ACCESS_COARSE_LOCATION import android.Manifest.permission.ACCESS_FINE_LOCATION import android.content.Intent import android.support.design.widget.NavigationView import android.support.v4.content.PermissionChecker.PERMISSION_GRANTED import android.support.v4.view.GravityCompat.START import br.com.edsilfer.android.presence_control.R import br.com.edsilfer.android.presence_control.core.di.Injector import br.com.edsilfer.android.presence_control.core.presentation.BaseActivity import br.com.edsilfer.android.presence_control.main.presentation.presenter.IMainPresenter import br.com.edsilfer.android.presence_control.user.domain.entity.User import com.squareup.picasso.Picasso import kotlinx.android.synthetic.main.main_content.* import kotlinx.android.synthetic.main.main_drawer_menu_header.* import kotlinx.android.synthetic.main.main_view.* import javax.inject.Inject class MainActivity : BaseActivity(), IMainView, NavigationView.OnNavigationItemSelectedListener { companion object { private val ARG_REQUEST_GEOLOCATION_PERMISSION_FOR_OPENING_MAPS_ACTIVITY = 98 fun getIntent(context: android.content.Context): Intent { return Intent(context, MainActivity::class.java) } } @Inject lateinit var mController: IMainPresenter override fun getPresenter() = mController override fun getViewContext() = this override fun onCreate(savedInstanceState: android.os.Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.main_view) Injector.getInstance().inject(this) checkRequiredPermissions() setSupportActionBar(toolbar) assembleDrawerMenu() viewpager.adapter = ViewPagerAdapter(supportFragmentManager) tabs.setViewPager(viewpager) } private fun checkRequiredPermissions() { if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) { if (checkSelfPermission(ACCESS_COARSE_LOCATION) + checkSelfPermission(ACCESS_FINE_LOCATION) != PERMISSION_GRANTED) { requestPermissions( arrayOf(ACCESS_COARSE_LOCATION, ACCESS_FINE_LOCATION), ARG_REQUEST_GEOLOCATION_PERMISSION_FOR_OPENING_MAPS_ACTIVITY ) } } } override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) { when (requestCode) { ARG_REQUEST_GEOLOCATION_PERMISSION_FOR_OPENING_MAPS_ACTIVITY -> { if (grantResults.filter { result -> result != PERMISSION_GRANTED }.isNotEmpty()) { mController.onLogoutClick() } } } super.onRequestPermissionsResult(requestCode, permissions, grantResults) } override fun onBackPressed() { if (drawer_layout.isDrawerOpen(START)) { drawer_layout.closeDrawer(START) } else { super.onBackPressed() } } /* DRAWER MENU */ private fun assembleDrawerMenu() { val toggle = android.support.v7.app.ActionBarDrawerToggle( this, drawer_layout, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close ) drawer_layout.setDrawerListener(toggle) toggle.syncState() nav_view.setNavigationItemSelectedListener(this) } override fun onCreateOptionsMenu(menu: android.view.Menu): Boolean { menuInflater.inflate(R.menu.main_activity, menu) return true } override fun onOptionsItemSelected(item: android.view.MenuItem): Boolean { val id = item.itemId when (id) { R.id.action_logout -> mController.onLogoutClick() } return super.onOptionsItemSelected(item) } override fun onNavigationItemSelected(item: android.view.MenuItem): Boolean { val id = item.itemId when (id) { R.id.nav_fork_me -> mController.onForkMeClick() R.id.nav_meet_author -> mController.onMeetTheAuthorClick() } drawer_layout.closeDrawer(android.support.v4.view.GravityCompat.START) return true } override fun updateDrawerMenu(user: User) { Picasso.with(this).load(user.thumbnail).fit().centerCrop().into(circularImageView_thumbnail) textView_name.text = user.name textView_email.text = user.email } }
apache-2.0
84c04969f83599852ef834bd3df856e5
36.614754
128
0.680758
4.701844
false
false
false
false
TheFallOfRapture/First-Game-Engine
src/main/kotlin/com/morph/engine/core/gui/ConsoleGUI.kt
2
2408
package com.morph.engine.core.gui import com.morph.engine.core.Game import com.morph.engine.graphics.Color import com.morph.engine.graphics.Texture import com.morph.engine.input.KeyPress import com.morph.engine.input.Keyboard import com.morph.engine.input.StdKeyEvent import com.morph.engine.math.Vector2f import com.morph.engine.newgui.ConsoleTextField import com.morph.engine.newgui.GUI import com.morph.engine.newgui.Panel import com.morph.engine.newgui.TextField import com.morph.engine.script.debug.Console import org.lwjgl.glfw.GLFW import java.util.* /** * Created on 11/24/2017. */ class ConsoleGUI(game: Game, private val console: Console, private val width: Int, private val height: Int) : GUI(game) { private lateinit var consoleInput: ConsoleTextField private lateinit var consoleOutput: TextField override fun init() { val fontSize = 16 val font = "fonts/FiraCode-Regular.ttf" val consoleBG = Panel("consoleBackground", Vector2f(0f, (height - 500).toFloat()), Vector2f(width.toFloat(), 500f), Color(0f, 1f, 0f, 0.3f), Texture("textures/solid.png")) val consoleInputBG = Panel("consoleInput", Vector2f(0f, (height - 520).toFloat()), Vector2f(width.toFloat(), 20f), Color(0f, 0f, 1f, 0.3f), Texture("textures/solid.png")) consoleInput = ConsoleTextField("consoleInput", console, "", font, fontSize, Color(1f, 1f, 1f), Vector2f(0f, (height - 515).toFloat()), -1200) consoleOutput = TextField("consoleOutput", "Morph " + Game.VERSION_STRING + " - Console Output\n", font, fontSize, Color(1f, 1f, 1f, 0.7f), Vector2f(10f, (height - 20).toFloat()), -1200) consoleBG.depth = -1000 consoleInputBG.depth = -1000 addElement(consoleBG) addElement(consoleInputBG) addElement(consoleInput) addElement(consoleOutput) } override fun load() {} private fun onKeyEvent(e: StdKeyEvent) { consoleInput.handleGUIKeyEvent(e) } override fun update() { Keyboard.standardKeyEvents.forEach { this.onKeyEvent(it) } } private fun onConsoleUpdate() { println("Updating the console...") consoleOutput.addString(console.lastLine) } private fun onConsoleClear() { println("Clearing the console...") consoleOutput.clearText() Console.out.println("Cleared console text.") } override fun unload() { } }
mit
62becf1f54dc308d7211a382d0aa2330
34.940299
194
0.693522
3.716049
false
false
false
false
danielrs/botellier
src/test/kotlin/org/botellier/command/commands.kt
1
13597
package org.botellier.command import org.botellier.store.* import org.botellier.value.* import org.junit.Assert import org.junit.Test class CommandsTest { // Keys. @Test fun delCommand() { val store = Store() val del = DelCommand() store.transaction().begin { set("one", IntValue(1)) set("two", IntValue(2)) set("three", IntValue(3)) set("four", IntValue(4)) } del.key = CValue.Primitive.String("one") del.rest = CValue.Array.String(listOf( CValue.Primitive.String("two"), CValue.Primitive.String("three") )) Assert.assertEquals(StringValue("OK"), del.execute(store)) Assert.assertEquals(1, store.size) } @Test fun existsCommand() { val store = Store() val exists = ExistsCommand() store.transaction().begin { set("one", IntValue(1)) set("two", IntValue(2)) set("three", IntValue(3)) } exists.key = CValue.Primitive.String("one") exists.rest = CValue.Array.String(listOf( CValue.Primitive.String("two"), CValue.Primitive.String("three"), CValue.Primitive.String("not key"), CValue.Primitive.String("not there neither") )) Assert.assertEquals(IntValue(3), exists.execute(store)) } @Test fun keysCommand() { val store = Store() val keys = KeysCommand() store.transaction().begin { set("one", IntValue(1)) set("prone", StringValue("yes")) set("two", IntValue(2)) } keys.pattern = CValue.Primitive.String(".*ne") Assert.assertEquals(IntValue(2), (keys.execute(store) as ListValue).size) } @Test fun renameCommand() { val store = Store() val rename = RenameCommand() store.transaction().begin { set("one", IntValue(1)) } rename.key = CValue.Primitive.String("one") rename.newkey = CValue.Primitive.String("uno") Assert.assertEquals(StringValue("OK"), rename.execute(store)) Assert.assertEquals(NilValue(), store.get("one")) Assert.assertEquals(IntValue(1), store.get("uno")) rename.key = rename.newkey Assert.assertEquals(StringValue("OK"), rename.execute(store)) Assert.assertEquals(IntValue(1), store.get("uno")) } @Test fun typeCommand() { val store = Store() val type = TypeCommand() store.transaction().begin { set("one", IntValue(1)) } type.key = CValue.Primitive.String("one") Assert.assertEquals(StringValue("IntValue"), type.execute(store)) type.key = CValue.Primitive.String("not key") Assert.assertEquals(StringValue("NilValue"), type.execute(store)) } // Lists. @Test fun lindexCommand() { val store = Store() val lindex = LIndexCommand() store.transaction().begin { set("list", listOf(1, 2, 3).map { it.toValue() }.toValue()) } lindex.key = CValue.Primitive.String("list") lindex.index = CValue.Primitive.Int(2) Assert.assertEquals(IntValue(3), lindex.execute(store)) } @Test fun linsertCommand() { val store = Store() val linsert = LInsertCommand() store.transaction().begin { set("list", listOf(1, 2, 3).map { it.toValue() }.toValue()) } linsert.key = CValue.Primitive.String("list") linsert.position = CValue.Primitive.String("BEFORE") linsert.pivot = CValue.Primitive.Int(1) linsert.value = CValue.Primitive.Int(0) Assert.assertEquals(IntValue(4), linsert.execute(store)) Assert.assertEquals(IntValue(0), (store.get("list") as ListValue).unwrap().get(0)) linsert.position = CValue.Primitive.String("AFTER") linsert.value = CValue.Primitive.Float(1.5) Assert.assertEquals(IntValue(5), linsert.execute(store)) Assert.assertEquals(FloatValue(1.5), (store.get("list") as ListValue).unwrap().get(2)) } @Test fun llenCommand() { val store = Store() val llen = LLenCommand() store.transaction().begin { set("list", listOf(1, 2, 3).map { it.toValue() }.toValue()) } llen.key = CValue.Primitive.String("list") Assert.assertEquals(IntValue(3), llen.execute(store)) llen.key = CValue.Primitive.String("not key") Assert.assertEquals(IntValue(0), llen.execute(store)) } @Test fun lpopCommand() { val store = Store() val lpop = LPopCommand() store.transaction().begin { set("list", listOf(1, 2, 3).map { it.toValue() }.toValue()) } lpop.key = CValue.Primitive.String("list") Assert.assertEquals(IntValue(1), lpop.execute(store)) Assert.assertEquals(IntValue(2), lpop.execute(store)) Assert.assertEquals(IntValue(3), lpop.execute(store)) Assert.assertEquals(NilValue(), lpop.execute(store)) } @Test fun lpushCommand() { val store = Store() val lpush = LPushCommand() lpush.key = CValue.Primitive.String("new-list") lpush.value = CValue.Primitive.Int(1) lpush.rest = CValue.Array.Any(listOf(CValue.Primitive.Float(2.0), CValue.Primitive.String("three"))) Assert.assertEquals(IntValue(3), lpush.execute(store)) Assert.assertEquals(IntValue(1), (store.get("new-list") as ListValue).unwrap().last()) } @Test fun lrangeCommand() { val store = Store() val lrange = LRangeCommand() store.transaction().begin { set("list", listOf(1, 2, 3).map { it.toValue() }.toValue()) } lrange.key = CValue.Primitive.String("list") lrange.start = CValue.Primitive.Int(-2) lrange.stop = CValue.Primitive.Int(2) Assert.assertEquals(listOf(2, 3), (lrange.execute(store) as ListValue).toList().map { (it as IntValue).unwrap() }) } @Test fun lremCommand() { val store = Store() val lrem = LRemCommand() lrem.key = CValue.Primitive.String("list") store.transaction().begin { set("list", listOf(1, 1, 2, 2).map { it.toValue() }.toValue()) } lrem.count = CValue.Primitive.Int(-2) lrem.value = CValue.Primitive.Int(1) Assert.assertEquals(IntValue(2), lrem.execute(store)) Assert.assertEquals(listOf(2, 2), (store.get("list") as ListValue).toList().map { (it as IntValue).unwrap() }) store.transaction().begin { set("list", listOf(1, 1, 2, 2).map { it.toValue() }.toValue()) } lrem.count = CValue.Primitive.Int(2) lrem.value = CValue.Primitive.Int(2) Assert.assertEquals(IntValue(2), lrem.execute(store)) Assert.assertEquals(listOf(1, 1), (store.get("list") as ListValue).toList().map { (it as IntValue).unwrap() }) } @Test fun lsetCommand() { val store = Store() val lset = LSetCommand() store.transaction().begin { set("list", listOf(1, 2, 3).map { it.toValue() }.toValue()) } lset.key = CValue.Primitive.String("list") lset.index = CValue.Primitive.Int(2) lset.value = CValue.Primitive.Int(3) Assert.assertEquals(StringValue("OK"), lset.execute(store)) Assert.assertEquals(IntValue(3), (store.get("list") as ListValue).unwrap().get(2)) } @Test fun ltrimCommand() { val store = Store() val ltrim = LTrimCommand() store.transaction().begin { set("list", listOf(1, 2, 3).map { it.toValue() }.toValue()) } ltrim.key = CValue.Primitive.String("list") ltrim.start = CValue.Primitive.Int(0) ltrim.stop = CValue.Primitive.Int(1) Assert.assertEquals(StringValue("OK"), ltrim.execute(store)) Assert.assertEquals(1, store.size) ltrim.start = CValue.Primitive.Int(1) ltrim.stop = CValue.Primitive.Int(0) Assert.assertEquals(StringValue("OK"), ltrim.execute(store)) Assert.assertEquals(0, store.size) } @Test fun rpopCommand() { val store = Store() val rpop = RPopCommand() store.transaction().begin { set("list", listOf(1, 2, 3).map { it.toValue() }.toValue()) } rpop.key = CValue.Primitive.String("list") Assert.assertEquals(IntValue(3), rpop.execute(store)) Assert.assertEquals(IntValue(2), rpop.execute(store)) Assert.assertEquals(IntValue(1), rpop.execute(store)) Assert.assertEquals(NilValue(), rpop.execute(store)) } @Test fun rpushCommand() { val store = Store() val rpush = RPushCommand() rpush.key = CValue.Primitive.String("list") rpush.value = CValue.Primitive.Int(1) rpush.rest = CValue.Array.Any(listOf(CValue.Primitive.Float(2.0), CValue.Primitive.String("three"))) Assert.assertEquals(IntValue(3), rpush.execute(store)) Assert.assertEquals(IntValue(1), (store.get("list") as ListValue).unwrap().first()) } // Strings. @Test fun appendCommand() { val store = Store() val append = AppendCommand() append.key = CValue.Primitive.String("key") append.value = CValue.Primitive.Int(1) append.execute(store) append.value = CValue.Primitive.Float(2.0) append.execute(store) append.value = CValue.Primitive.String("three") Assert.assertEquals(IntValue(9), append.execute(store)) Assert.assertEquals(StringValue("12.0three"), store.get("key")) } @Test fun decrCommand() { val store = Store() val decr = DecrCommand() decr.key = CValue.Primitive.String("key") Assert.assertEquals(IntValue(-1), decr.execute(store)) Assert.assertEquals(IntValue(-1), store.get("key")) } @Test fun decrbyCommand() { val store = Store() val decrby = DecrbyCommand() decrby.key = CValue.Primitive.String("key") decrby.decrement = CValue.Primitive.Int(10) Assert.assertEquals(IntValue(-10), decrby.execute(store)) Assert.assertEquals(IntValue(-10), store.get("key")) } @Test fun getCommand() { val store = Store() val get = GetCommand() store.transaction().begin { set("key", StringValue("Hello, world!")) } get.key = CValue.Primitive.String("key") Assert.assertEquals(StringValue("Hello, world!"), get.execute(store)) } @Test fun incrCommand() { val store = Store() val incr = IncrCommand() incr.key = CValue.Primitive.String("key") Assert.assertEquals(IntValue(1), incr.execute(store)) Assert.assertEquals(IntValue(1), store.get("key")) } @Test fun incrbyCommand() { val store = Store() val incrby = IncrbyCommand() incrby.key = CValue.Primitive.String("key") incrby.increment = CValue.Primitive.Int(10) Assert.assertEquals(IntValue(10), incrby.execute(store)) Assert.assertEquals(IntValue(10), store.get("key")) } @Test fun incrbyfloatCommand() { val store = Store() val incrby = IncrbyfloatCommand() incrby.key = CValue.Primitive.String("key") incrby.increment = CValue.Primitive.Float(10.0) Assert.assertEquals(FloatValue(10.0), incrby.execute(store)) Assert.assertEquals(FloatValue(10.0), store.get("key")) } @Test fun mgetCommand() { val store = Store() val mget = MGetCommand() store.transaction().begin { set("one", IntValue(1)) } mget.key = CValue.Primitive.String("zero") mget.rest = CValue.Array.String(listOf("one", "two").map(CValue.Primitive::String)) val list = (mget.execute(store) as ListValue).unwrap() Assert.assertEquals(NilValue(), list.get(0)) Assert.assertEquals(IntValue(1), list.get(1)) Assert.assertEquals(NilValue(), list.get(2)) } @Test fun msetCommand() { val store = Store() val mset = MSetCommand() mset.key = CValue.Primitive.String("key0") mset.value = CValue.Primitive.Int(0) mset.rest = CValue.Array.Pair(listOf( CValue.Pair("key1", CValue.Primitive.Float(1.0)), CValue.Pair("key2", CValue.Primitive.String("two")) )) Assert.assertEquals(StringValue("OK"), mset.execute(store)) Assert.assertEquals(IntValue(0), store.get("key0")) Assert.assertEquals(FloatValue(1.0), store.get("key1")) Assert.assertEquals(StringValue("two"), store.get("key2")) } @Test fun setCommand() { val store = Store() val set = SetCommand() set.key = CValue.Primitive.String("key") set.value = CValue.Primitive.String("Hello, world!") Assert.assertEquals(StringValue("OK"), set.execute(store)) Assert.assertEquals(StringValue("Hello, world!"), store.get("key")) } @Test fun strlenCommand() { val store = Store() val strlen = StrlenCommand() store.transaction().begin { set("message", StringValue("Hello, world!")) } strlen.key = CValue.Primitive.String("message") Assert.assertEquals(IntValue(13), strlen.execute(store)) } }
mit
df568d9cf2f955bb17af2de053b21fc6
32.163415
122
0.588586
4.056384
false
true
false
false
Ph1b/MaterialAudiobookPlayer
app/src/main/kotlin/de/ph1b/audiobook/features/bookPlaying/selectchapter/SelectChapterDialog.kt
1
2583
package de.ph1b.audiobook.features.bookPlaying.selectchapter import android.app.Dialog import android.os.Bundle import android.view.View import com.afollestad.materialdialogs.MaterialDialog import com.afollestad.materialdialogs.list.customListAdapter import com.afollestad.materialdialogs.list.getRecyclerView import com.xwray.groupie.GroupAdapter import com.xwray.groupie.GroupieViewHolder import de.ph1b.audiobook.R import de.ph1b.audiobook.common.conductor.DialogController import de.ph1b.audiobook.data.Book2 import de.ph1b.audiobook.data.ChapterMark import de.ph1b.audiobook.data.getBookId import de.ph1b.audiobook.data.putBookId import de.ph1b.audiobook.databinding.SelectChapterRowBinding import de.ph1b.audiobook.injection.appComponent import de.ph1b.audiobook.misc.groupie.BindingItem import kotlinx.coroutines.launch import javax.inject.Inject private const val NI_BOOK_ID = "ni#bookId" class SelectChapterDialog(bundle: Bundle) : DialogController(bundle) { @Inject lateinit var viewModel: SelectChapterViewModel constructor(bookId: Book2.Id) : this( Bundle().apply { putBookId(NI_BOOK_ID, bookId) } ) init { appComponent.inject(this) viewModel.bookId = args.getBookId(NI_BOOK_ID)!! } override fun onCreateDialog(savedViewState: Bundle?): Dialog { val viewState = viewModel.viewState() val items = viewState.chapters.mapIndexed { index, mark -> val listener = View.OnClickListener { viewModel.chapterClicked(index) } BindingItem<SelectChapterRowBinding, ChapterMark>( mark, R.layout.select_chapter_row, SelectChapterRowBinding::bind ) { data, position -> root.setOnClickListener(listener) @Suppress("SetTextI18n") textView.text = "${position + 1} - ${data.name}" textView.setCompoundDrawablesWithIntrinsicBounds( 0, 0, if (position == viewState.selectedIndex) R.drawable.ic_equalizer else 0, 0 ) } } val adapter = GroupAdapter<GroupieViewHolder>() adapter.addAll(items) return MaterialDialog(activity!!).apply { customListAdapter(adapter) if (viewState.selectedIndex != null) { getRecyclerView().layoutManager!!.scrollToPosition(viewState.selectedIndex) } } } override fun onAttach(view: View) { super.onAttach(view) lifecycleScope.launch { viewModel.viewEffects.collect { when (it) { SelectChapterViewEffect.CloseScreen -> { dismissDialog() } } } } } }
lgpl-3.0
cef2e18a664430f5b134c88e854a9d66
29.034884
83
0.711189
4.234426
false
false
false
false
google-developer-training/android-demos
DonutTracker/NavigationUI/app/src/main/java/com/android/samples/donuttracker/coffee/CoffeeListAdapter.kt
2
2999
/* * Copyright (C) 2021 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.samples.donuttracker.coffee import android.view.LayoutInflater import android.view.ViewGroup import androidx.recyclerview.widget.DiffUtil import androidx.recyclerview.widget.ListAdapter import androidx.recyclerview.widget.RecyclerView import com.android.samples.donuttracker.R import com.android.samples.donuttracker.databinding.CoffeeItemBinding import com.android.samples.donuttracker.model.Coffee /** * The adapter used by the RecyclerView to display the current list of Coffees */ class CoffeeListAdapter( private var onEdit: (Coffee) -> Unit, private var onDelete: (Coffee) -> Unit ) : ListAdapter<Coffee, CoffeeListAdapter.CoffeeListViewHolder>(CoffeeDiffCallback()) { class CoffeeListViewHolder( private val binding: CoffeeItemBinding, private var onEdit: (Coffee) -> Unit, private var onDelete: (Coffee) -> Unit ) : RecyclerView.ViewHolder(binding.root) { private var coffeeId: Long = -1 private var nameView = binding.name private var description = binding.description private var thumbnail = binding.thumbnail private var rating = binding.rating private var coffee: Coffee? = null fun bind(coffee: Coffee) { coffeeId = coffee.id nameView.text = coffee.name description.text = coffee.description rating.text = coffee.rating.toString() thumbnail.setImageResource(R.drawable.coffee_cup) this.coffee = coffee binding.deleteButton.setOnClickListener { onDelete(coffee) } binding.root.setOnClickListener { onEdit(coffee) } } } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int) = CoffeeListViewHolder( CoffeeItemBinding.inflate(LayoutInflater.from(parent.context), parent, false), onEdit, onDelete ) override fun onBindViewHolder(holder: CoffeeListViewHolder, position: Int) { holder.bind(getItem(position)) } } class CoffeeDiffCallback : DiffUtil.ItemCallback<Coffee>() { override fun areItemsTheSame(oldItem: Coffee, newItem: Coffee): Boolean { return oldItem.id == newItem.id } override fun areContentsTheSame(oldItem: Coffee, newItem: Coffee): Boolean { return oldItem == newItem } }
apache-2.0
e56c884af692de7aab6ccf95eeb13fe4
35.13253
94
0.698233
4.783094
false
false
false
false
actions-on-google/appactions-fitness-kotlin
app/src/main/java/com/devrel/android/fitactions/home/FitStatsAdapter.kt
1
3522
/* * Copyright 2019 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.devrel.android.fitactions.home import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.recyclerview.widget.DiffUtil import androidx.recyclerview.widget.ListAdapter import androidx.recyclerview.widget.RecyclerView import com.devrel.android.fitactions.R import com.devrel.android.fitactions.model.FitActivity import kotlinx.android.synthetic.main.fit_stats_row.view.* import java.text.SimpleDateFormat import java.util.* import java.util.concurrent.TimeUnit class FitStatsAdapter : ListAdapter<FitActivity, FitStatsAdapter.ViewHolder>(DIFF) { private var maxDuration = 0.0 override fun submitList(list: List<FitActivity>?) { list?.forEach { maxDuration = Math.max(maxDuration, it.distanceMeters) } super.submitList(list) } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { return ViewHolder(LayoutInflater.from(parent.context).inflate(R.layout.fit_stats_row, parent, false)) } override fun onBindViewHolder(holder: ViewHolder, position: Int) { holder.bind(getItem(position), maxDuration.toInt()) } companion object { val DIFF = object : DiffUtil.ItemCallback<FitActivity>() { override fun areItemsTheSame(oldItem: FitActivity, newItem: FitActivity): Boolean { return oldItem.id == newItem.id } override fun areContentsTheSame(oldItem: FitActivity, newItem: FitActivity): Boolean { return oldItem == newItem } } } class ViewHolder(view: View) : RecyclerView.ViewHolder(view) { fun bind(activity: FitActivity, max: Int) { val context = itemView.context val calendar = Calendar.getInstance().apply { timeInMillis = activity.date } val day = calendar.getDisplayName( Calendar.DAY_OF_WEEK, Calendar.LONG, Locale.getDefault() ) val monthFormatter = SimpleDateFormat("MM") itemView.statsRowTitle.text = context.getString( R.string.stat_date, day, calendar.get(Calendar.DAY_OF_MONTH), monthFormatter.format(calendar.time).toInt() ) val minutes = TimeUnit.MILLISECONDS.toMinutes(activity.durationMs) val km = String.format("%.2f", activity.distanceMeters / 1000) val duration = context.getString(R.string.stat_duration, minutes) val distance = context.getString(R.string.stat_distance, km) itemView.statsRowContent.apply { text = duration append("\n") append(distance) } itemView.statsRowProgress.max = max itemView.statsRowProgress.progress = activity.distanceMeters.toInt() } } }
apache-2.0
099383ae7c44c1ad93f48beefc12944f
35.319588
109
0.662408
4.696
false
false
false
false
shaeberling/euler
kotlin/src/com/s13g/aoc/aoc2021/Day14.kt
1
1934
package com.s13g.aoc.aoc2021 import com.s13g.aoc.Result import com.s13g.aoc.Solver /** * --- Day 14: Extended Polymerization --- * https://adventofcode.com/2021/day/14 */ private typealias PairCounts = MutableMap<String, Long> class Day14 : Solver { override fun solve(lines: List<String>): Result { val polymer = lines[0] val rules = lines.filter { it.contains("->") }.map { it.split(" -> ") }.associate { it[0] to it[1][0] } return Result("${calcRounds(polymer, rules, 10)}", "${calcRounds(polymer, rules, 40)}") } private fun calcRounds(polymer: String, rules: Map<String, Char>, numRounds: Int): Long { var pairCounts: PairCounts = polymer.windowed(2) .map { "${it[0]}${it[1]}" } .groupingBy { it } .eachCount() .map { it.key to it.value.toLong() } .toMap() .toMutableMap() for (r in 1..numRounds) { val pc2 = pairCounts.toMutableMap() for (p in pairCounts.keys) { if (rules.containsKey(p)) { pc2.increment("${p[0]}${rules[p]}", pairCounts[p]!!) pc2.increment("${rules[p]}${p[1]}", pairCounts[p]!!) pc2[p] = pc2[p]!! - pairCounts[p]!! } } pairCounts = pc2 } // Count all individual characters. val counts = mutableMapOf<Char, Long>() for (pc in pairCounts) { for (ch in pc.key) { if (!counts.containsKey(ch)) counts[ch] = 0 counts[ch] = counts[ch]!! + pc.value } } // First and last never get doubled, so add one of each for divide by two to work. counts[polymer.first()] = counts[polymer.first()]!! + 1 counts[polymer.last()] = counts[polymer.last()]!! + 1 val max = counts.map { it.value / 2 }.max()!! val min = counts.map { it.value / 2 }.min()!! return max - min } private fun PairCounts.increment(v: String, l: Long) { this.compute(v) { _, ll -> if (ll == null) l else ll + l } } }
apache-2.0
191124f3906de37cb73496df8b482066
30.209677
107
0.577042
3.441281
false
false
false
false
yyued/CodeX-UIKit-Android
library/src/main/java/com/yy/codex/uikit/UIResponder.kt
1
1855
package com.yy.codex.uikit /** * Created by it on 17/1/6. */ interface UIResponder { val nextResponder: UIResponder? fun canBecomeFirstResponder(): Boolean fun becomeFirstResponder() fun canResignFirstResponder(): Boolean fun resignFirstResponder() fun isFirstResponder(): Boolean fun touchesBegan(touches: List<UITouch>, event: UIEvent) fun touchesMoved(touches: List<UITouch>, event: UIEvent) fun touchesEnded(touches: List<UITouch>, event: UIEvent) fun touchesCancelled(touches: List<UITouch>, event: UIEvent) fun keyboardPressDown(event: UIKeyEvent) fun keyboardPressUp(event: UIKeyEvent) companion object { var firstResponder: UIResponder? = null set(value) { field?.let { field = null it.resignFirstResponder() } field = value } fun findFirstResponder(currentResponder: UIResponder): UIResponder? { if (currentResponder.canBecomeFirstResponder()) { return currentResponder } if (currentResponder is UIViewController) { if (currentResponder.view?.canBecomeFirstResponder() ?: false) { return currentResponder.view } for (childResponder in currentResponder.childViewControllers) { val firstResponder = findFirstResponder(childResponder) ?: continue return firstResponder } } else if (currentResponder is UIView) { for (childResponder in currentResponder.subviews) { val firstResponder = findFirstResponder(childResponder) ?: continue return firstResponder } } return null } } }
gpl-3.0
50ed5d3bcf08ad4194b1a8ffca22d6ec
29.916667
87
0.596226
5.570571
false
false
false
false
BaReinhard/Hacktoberfest-Data-Structure-and-Algorithms
data_structures/queue/kotlin/IterableQueue.kt
1
3170
import java.util.NoSuchElementException class IterableQueue<E> : Iterable<E> { private var first: Node<E>? = null // beginning of queue private var last: Node<E>? = null // end of queue private var n: Int = 0 // number of elements on queue // helper linked list class private class Node<E> { internal var element: E? = null internal var next: Node<E>? = null } /** * Initializes an empty queue. */ init { first = null last = null n = 0 } /** * Returns true if this queue is empty. * @return `true` if this queue is empty; `false` otherwise */ val isEmpty: Boolean get() = first == null /** * Returns the number of items in this queue. * @return the number of items in this queue */ fun size(): Int { return n } /** * Returns the element least recently added to this queue. * @return the element least recently added to this queue * * * @throws NoSuchElementException if this queue is empty */ fun peek(): E { if (isEmpty) throw NoSuchElementException("Queue underflow") return first!!.element!! } /** * Adds the element to this queue. * @param element the element to add */ fun enqueue(element: E) { val oldLast = last last = Node<E>() last!!.element = element last!!.next = null if (isEmpty) first = last else oldLast!!.next = last n++ } /** * Removes and returns the element on this queue that was least recently added. * @return the element on this queue that was least recently added * * * @throws NoSuchElementException if this queue is empty */ fun dequeue(): E { if (isEmpty) throw NoSuchElementException("Queue underflow") val element = first!!.element first = first!!.next n-- if (isEmpty) last = null // to avoid loitering return element!! } /** * Returns a string representation of this queue. * @return the sequence of items in FIFO order, separated by spaces */ override fun toString(): String { val s = StringBuilder() for (element in this) { s.append(element) s.append(' ') } return s.toString() } /** * Returns an iterator that iterates over the items in this queue in FIFO order. * @return an iterator that iterates over the items in this queue in FIFO order */ override fun iterator(): Iterator<E> { return ListIterator(first) } // an iterator, doesn't implement remove() since it's optional private inner class ListIterator<Item>(private var current: Node<Item>?) : Iterator<Item> { override fun hasNext(): Boolean { return current != null } override fun next(): Item { if (!hasNext()) throw NoSuchElementException() val item = current!!.element current = current!!.next return item!! } } }
gpl-3.0
9ef74e2fd03ca09c223d51b857ec66a0
24.983607
95
0.565615
4.696296
false
false
false
false
vsch/idea-multimarkdown
src/main/java/com/vladsch/md/nav/parser/LexParserState.kt
1
23722
// Copyright (c) 2015-2020 Vladimir Schneider <[email protected]> Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.vladsch.md.nav.parser import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.components.ServiceManager import com.intellij.openapi.diagnostic.Logger import com.intellij.psi.tree.IElementType import com.intellij.psi.tree.TokenSet import com.vladsch.md.nav.highlighter.MdHighlighterColors import com.vladsch.md.nav.highlighter.MdSyntaxHighlighter import com.vladsch.md.nav.psi.util.MdTokenSets import com.vladsch.md.nav.psi.util.MdTokenType import com.vladsch.md.nav.psi.util.MdTypes.* import com.vladsch.md.nav.settings.MdApplicationSettings import com.vladsch.plugin.util.max import java.util.* @Suppress("UNUSED_VARIABLE") class LexParserState { companion object { private val DEFAULT: LexParserState by lazy { LexParserState() } private val LOG: Logger = Logger.getInstance("com.vladsch.md.nav.parser") @JvmStatic fun getInstance(): LexParserState { return if (ApplicationManager.getApplication() == null) DEFAULT else ServiceManager.getService(LexParserState::class.java) } } private val childrenNotExcludingParentsMap = HashMap<IElementType, HashSet<IElementType>>() private val parentsNotExcludingChildrenMap = HashMap<IElementType, HashSet<IElementType>>() fun isExcludedByChild(parent: IElementType, child: IElementType): Boolean { val childNotExcludingParents = childrenNotExcludingParentsMap[child] ?: return true return !childNotExcludingParents.contains(parent) } fun isExcludedByParent(parent: IElementType, child: IElementType): Boolean { val parentNotExcludingChildren = parentsNotExcludingChildrenMap[parent] ?: return true return !parentNotExcludingChildren.contains(child) } private val COMBINATION_TYPES = HashMap<String, IElementType>() val state: State by lazy { initialize() } data class State( @JvmField val TYPOGRAPHIC_MARKER_SET: TokenSet, @JvmField val TEXT_SET: TokenSet, @JvmField val TEXT_TOKEN_TYPE_MAP: Map<IElementType, IElementType>, @JvmField val NON_MERGE_TOKEN_SET: TokenSet, @JvmField val COMBINATION_SPLITS: Map<IElementType, Map<IElementType, IElementType>>, @JvmField val INLINE_NON_PLAIN_TEXT: List<IElementType>, @JvmField val INLINE_SPECIAL_TEXT: List<IElementType>, @JvmField val INLINE_PLAIN_TEXT: List<IElementType> ) // @formatter:off private var TYPOGRAPHIC_MARKER_SET: TokenSet = TokenSet.create() private var TEXT_SET: TokenSet = TokenSet.create() private val TEXT_TOKEN_TYPE_MAP = HashMap<IElementType, IElementType>() /* NOTE: must add all markers that can be consecutive, otherwise they are combined into a single leaf and it is hell to debug why formatting, wrap on typing and other features fail. */ // these will not be combined into a single lexer token even if adjacent, others will combine consecutive tokens private val NON_MERGE_TOKEN_SET = TokenSet.create( IMAGE_LINK_REF_TITLE_MARKER, LINK_REF_TITLE_MARKER, REFERENCE_TITLE_MARKER, ASIDE_BLOCK_MARKER, BLOCK_QUOTE_MARKER, BULLET_LIST_ITEM_MARKER, ORDERED_LIST_ITEM_MARKER, DEFINITION_TERM, FLEXMARK_EXAMPLE_SEPARATOR, EOL, BLANK_LINE ) private val COMBINATION_SPLITS: MutableMap<IElementType, HashMap<IElementType, IElementType>> = HashMap() private val INLINE_NON_PLAIN_TEXT: ArrayList<IElementType> = arrayListOf( COMMENT_OPEN, COMMENT_CLOSE, BLOCK_COMMENT_OPEN, BLOCK_COMMENT_CLOSE, HTML_ENTITY, EMOJI_MARKER, EMOJI_ID ) private val INLINE_SPECIAL_TEXT: ArrayList<IElementType> = arrayListOf( SPECIAL_TEXT ) private val INLINE_PLAIN_TEXT = arrayListOf<IElementType>( // COMMENT_TEXT, // BLOCK_COMMENT_TEXT, ) internal fun addChildDoesNotExcludeParent(parent: IElementType, child: IElementType, addParentDoesNotExcludesChild: Boolean = false) { val childExclusions = childrenNotExcludingParentsMap.computeIfAbsent(child ){ HashSet() } childExclusions.add(parent) if (addParentDoesNotExcludesChild) { addParentDoesNotExcludesChild(parent, child) } } private fun addParentDoesNotExcludesChild(parent: IElementType, child: IElementType) { val parentExclusions = parentsNotExcludingChildrenMap.computeIfAbsent(parent ){ HashSet() } parentExclusions.add(child) } private fun addInlineExclusions(parent: IElementType, addNonPlainText: Boolean = true) { addChildDoesNotExcludeParent(parent, TEXT) if (addNonPlainText) { for (inline in INLINE_NON_PLAIN_TEXT) { addChildDoesNotExcludeParent(parent, inline) } } } // @formatter:on private fun <T : Any> List<T>.union(other: Collection<T>): List<T> { val setList = this.toSet() val list = ArrayList<T>() list.addAll(this) for (item in other) { if (!setList.contains(item)) list.add(item) } return list } private fun initialize(): State { // create combination types so that overlay highlighting cab be done in lexer // do it first so that the non-text inline set is updated val inlineEmphasis: List<IElementType> val inlineEmphasisMarkers: List<IElementType> val tableCellsInline: List<IElementType> val fullHighlightCombinations = MdApplicationSettings.instance.documentSettings.fullHighlightCombinations LOG.info("Initializing LexParserState: fullHighlights = $fullHighlightCombinations") inlineEmphasis = if (fullHighlightCombinations) listOf( STRIKETHROUGH_TEXT, BOLD_TEXT, UNDERLINE_TEXT, SUPERSCRIPT_TEXT, SUBSCRIPT_TEXT, ITALIC_TEXT ) else listOf( STRIKETHROUGH_TEXT, BOLD_TEXT, ITALIC_TEXT ) inlineEmphasisMarkers = if (fullHighlightCombinations) listOf( BOLD_MARKER, UNDERLINE_MARKER, SUPERSCRIPT_MARKER, SUBSCRIPT_MARKER, ITALIC_MARKER, STRIKETHROUGH_MARKER ) else listOf( BOLD_MARKER, ITALIC_MARKER, STRIKETHROUGH_MARKER ) tableCellsInline = listOf( TABLE_CELL_REVEN_CEVEN, TABLE_CELL_REVEN_CODD, TABLE_CELL_RODD_CEVEN, TABLE_CELL_RODD_CODD, TABLE_HDR_CELL_REVEN_CEVEN, TABLE_HDR_CELL_REVEN_CODD, TABLE_HDR_CELL_RODD_CEVEN, TABLE_HDR_CELL_RODD_CODD ) INLINE_PLAIN_TEXT.add(TEXT) INLINE_PLAIN_TEXT.addAll(inlineEmphasis) INLINE_NON_PLAIN_TEXT.addAll(inlineEmphasisMarkers) if (fullHighlightCombinations) { INLINE_PLAIN_TEXT.addAll(listOf(CODE_TEXT, GITLAB_MATH_TEXT, QUOTED_TEXT, ABBREVIATED_TEXT)) } else { INLINE_PLAIN_TEXT.addAll(listOf(CODE_TEXT, ABBREVIATED_TEXT)) } val combinator = Combinator(this) val combinationInlineEmphasis = combinator.combinationSplits(inlineEmphasis, inlineEmphasis) val combinationInlineEmphasisQuotes = if (!fullHighlightCombinations) listOf() else combinator.combinationSplits(inlineEmphasis.union(setOf(QUOTED_TEXT)), inlineEmphasis.union(setOf(QUOTED_TEXT))) // val combinationInlineEmphasisAbbrQuotes = combinator.crossSplits(combinationInlineEmphasisQuotes, listOf(ABBREVIATED_TEXT)) // val combinationInlineEmphasisAbbrQuotes = combinationInlineEmphasisQuotes val combinationInlineEmphasisCode = combinator.combinationSplits(inlineEmphasis, listOf(CODE_TEXT)) // val combinationInlineEmphasisEntity = combinator.combinationSplits(inlineEmphasis.union(setOf(QUOTED_TEXT)), listOf(HTML_ENTITY)) // val combinationInlineEmphasisSpecial = combinator.combinationSplits(inlineEmphasis.union(setOf(QUOTED_TEXT)), listOf(SPECIAL_TEXT)).union(combinator.combinationSplits(listOf(QUOTED_TEXT), listOf(SPECIAL_TEXT_MARKER))) // val combinationInlineEmphasisSmarts = inlineEmphasis.union(setOf(QUOTED_TEXT, SMARTS)) if (fullHighlightCombinations) { val combinationInlineEmphasisSmarts = combinator.combinationSplits(inlineEmphasis.union(setOf(QUOTED_TEXT)), listOf(SMARTS)) val tableCellInlineCombo = combinator.crossSplits(tableCellsInline, INLINE_PLAIN_TEXT.union(INLINE_NON_PLAIN_TEXT).union(INLINE_SPECIAL_TEXT)) } val tableCellInlineComboEmphasis = combinator.crossSplits(tableCellsInline, combinationInlineEmphasis) // val tableCellInlineComboAbbr = combinator.crossSplits(tableCellsInline, combinationInlineEmphasisAbbrQuotes) // val tableCellInlineComboEmphasisMarkers = combinator.crossSplits(tableCellsInline, inlineEmphasisMarkers.union(setOf(QUOTE_MARKER, CODE_MARKER, SPECIAL_TEXT_MARKER))) // val tableCellInlineComboEmphasisMarkers = combinator.crossSplits(tableCellsInline, inlineEmphasisMarkers.union(setOf(CODE_MARKER))) if (fullHighlightCombinations) { val tableCellInlineComboNotIssueMarkers = combinator.crossSplits(tableCellsInline, MdTokenSets.NON_TEXT_INLINE_ELEMENTS.types.toList()) } // add combinations for emphasis, quotes and code to header text overlays val overlays = listOf<IElementType>() .union(combinationInlineEmphasisQuotes) // .union(combinationInlineEmphasisAbbrQuotes) .union(combinationInlineEmphasisCode) // .union(combinationInlineEmphasisEntity) // .union(combinationInlineEmphasisSpecial) // .union(combinationInlineEmphasisSmarts) // .union(combinationInlineEmphasis) // .union(inlineEmphasisMarkers) .union(setOf(QUOTE_MARKER, CODE_MARKER, SPECIAL_TEXT_MARKER)) // .union(setOf(CODE_MARKER, SPECIAL_TEXT_MARKER)) // .union(INLINE_NON_PLAIN_TEXT.filter { !it.toString().startsWith("TABLE_") && !it.toString().startsWith("DEFINITION_") }) // .union(issueMarkerEmphasis).union(setOf(ISSUE_MARKER)) if (fullHighlightCombinations) { val headerCombos = combinator.crossSplits(listOf(HEADER_TEXT), overlays) val headerEmphasis = combinator.crossSplits(listOf(HEADER_TEXT), combinationInlineEmphasis) // val headerEmphasisIssueMarker = combinator.crossSplits(headerEmphasis, setOf(ISSUE_MARKER)) val headerEmphasisMarkers = combinator.crossSplits(listOf(HEADER_TEXT), inlineEmphasisMarkers .union(setOf(QUOTE_MARKER, CODE_MARKER, SPECIAL_TEXT_MARKER)) .union(INLINE_NON_PLAIN_TEXT.filter { !it.toString().startsWith("TABLE_") && !it.toString().startsWith("DEFINITION_") }) ) } // construct TEXT to ABBREVIATED_TEXT map // val combinationInlineAbbrText = combinator.crossSplits(tableCellInlineComboAbbr.union(headerCombos).union(headerEmphasis), listOf(ABBREVIATED_TEXT)) val abbrMap = COMBINATION_SPLITS[ABBREVIATED_TEXT] if (abbrMap != null) TEXT_TOKEN_TYPE_MAP.putAll(abbrMap) // now add these so the rest of the code knows what an issue marker is val issueMarkers = mutableListOf<IElementType>() val invalidIssueMarkers = mutableListOf<IElementType>() val textSet = mutableListOf<IElementType>() val invalidTextSet = mutableListOf<IElementType>() val typographicMarkers = mutableListOf<IElementType>() for (entry in COMBINATION_SPLITS.entries) { issueMarkers.addAll(entry.value.values.filter { it.toString().endsWith("_ISSUE_MARKER") }) invalidIssueMarkers.addAll(entry.value.values.filter { it.toString().contains("_ISSUE_MARKER_") }) textSet.addAll(entry.value.values.filter { it.toString().endsWith("_CODE_TEXT") }) invalidIssueMarkers.addAll(entry.value.values.filter { it.toString().contains("_CODE_TEXT_") }) typographicMarkers.addAll(entry.value.values.filter { it.toString().endsWith("_SMARTS") || it.toString().endsWith("_QUOTE_MARKER") }) } TYPOGRAPHIC_MARKER_SET = TokenSet.create(QUOTE_MARKER, SMARTS, *typographicMarkers.toTypedArray()) TEXT_SET = TokenSet.create(TEXT, CODE_TEXT, *textSet.toTypedArray(), *combinationInlineEmphasisCode.toTypedArray()) INLINE_PLAIN_TEXT.addAll(tableCellsInline) // Text does not punch through other inline elements for (inline in INLINE_PLAIN_TEXT.union(INLINE_NON_PLAIN_TEXT)) { addChildDoesNotExcludeParent(inline, TEXT) } // nodes not to be punched out by text or emphasis // addInlineExclusions(ABBREVIATION) addInlineExclusions(ANCHOR_LINK) // addInlineExclusions(AUTO_LINK) addInlineExclusions(DEFINITION_TERM) // addInlineExclusions(HEADER_ATX_MARKER) // addInlineExclusions(HEADER_SETEXT_MARKER) // addInlineExclusions(IMAGE_LINK_REF_TEXT) // addInlineExclusions(IMAGE_LINK_REF_TITLE) // addInlineExclusions(LINK_REF_TITLE) // addInlineExclusions(QUOTE) // addInlineExclusions(REFERENCE) // addInlineExclusions(REFERENCE_IMAGE_REFERENCE) // addInlineExclusions(REFERENCE_IMAGE_TEXT) // addInlineExclusions(REFERENCE_LINK_REFERENCE) // addInlineExclusions(REFERENCE_LINK_TEXT) // addInlineExclusions(REFERENCE_TEXT) // addInlineExclusions(REFERENCE_TITLE) // addInlineExclusions(TASK_DONE_ITEM_MARKER) // addInlineExclusions(TASK_ITEM_MARKER) // addInlineExclusions(WIKI_LINK_REF) // addInlineExclusions(WIKI_LINK_TEXT) // after all are updated, fire off the merger just in case val combinedTypes = COMBINATION_TYPES.size val splitCombos = MdSyntaxHighlighter.getMergedKeys().size val s = "Combined highlighters: $splitCombos, $combinedTypes" LOG.info(s) System.out.println(s) MdSyntaxHighlighter.computeMergedAttributes(false) return State( TYPOGRAPHIC_MARKER_SET, TEXT_SET, TEXT_TOKEN_TYPE_MAP.toMap(), NON_MERGE_TOKEN_SET, COMBINATION_SPLITS.toMap(), INLINE_NON_PLAIN_TEXT.toList(), INLINE_SPECIAL_TEXT.toList(), INLINE_PLAIN_TEXT.toList() ) } private class Combinator(val state: LexParserState) { private val highlighterColors = MdHighlighterColors.getInstance() /** * Create all combinations of elements in both the bases and overlays lists * overlays list gives elements that are always contained by base elements or their combinations * * eg. bases(a,b) overlays (c,e) will produce the following calls to combinationSplit(): * ; 1x1 => 2 * c(a,b) => ab 0001 0010 0011 * c(a,c) => ac 0001 0100 0101 * c(a,e) => ae 0001 1000 1001 * c(b,a) => ab 0010 0001 0011 * c(b,c) => bc 0010 0100 0110 * c(b,e) => be 0010 1000 1010 * c(c,a) => * * c(c,b) => * * c(c,e) => ce 0100 1000 1100 * c(e,a) => * * c(e,b) => * * c(e,c) => ce 1000 0100 1100 * * ; 1x2 => 3 * c(a,bc) => abc 0001 0110 0111 * c(a,be) => abe 0001 1010 1011 * c(b,ce) => bce 0010 1100 1110 * * ; 2x1 => 3 * c(ab,c) => abc 0011 0100 0111 * c(ae,c) => ace 1001 0100 1101 * c(ab,e) => abe 0011 1000 1011 * c(ac,e) => ace 0101 1000 1101 * c(bc,e) => bce 0110 1000 1110 * * ; 1x3 => 4 * c(a,bce) => abce 0001 1110 1111 * c(b,ace) => abce 0010 1101 1111 * c(abe,c) => abce 1011 0100 1111 * c(abc,e) => abce 0111 1000 1111 * * ; 2x2 => 4 * c(ab,ce) => abce 0011 1100 1111 * c(ac,be) => abce 0101 1010 1111 * c(ae,bc) => abce 1001 0110 1111 */ fun combinationSplits(bases: List<IElementType>, overlays: List<IElementType>): List<IElementType> { val bitMap = HashMap<IElementType, Int>() val bitMaskNameMap = HashMap<Int, String>() val bitList = ArrayList<IElementType>(bases.size.max(overlays.size)) var bitMask = 1 for (item in bases) { if (bitMap[item] == null) { bitMap.put(item, bitMask) bitMaskNameMap.put(bitMask, item.toString()) bitList.add(item) bitMask = bitMask.shl(1) state.addChildDoesNotExcludeParent(item, TEXT, false) } } val maxBaseMask = bitMask val basesBitMask = maxBaseMask - 1 for (item in overlays) { if (bitMap[item] == null) { bitMap.put(item, bitMask) bitMaskNameMap.put(bitMask, item.toString()) bitList.add(item) bitMask = bitMask.shl(1) state.addChildDoesNotExcludeParent(item, TEXT, false) } } // start with all singles var combinationCount: Int val combinationList = ArrayList<IElementType>(bases.size * overlays.size) combinationList.addAll(bitList) val bitItems = bitList.toSet() do { combinationCount = combinationList.size val newCombinations = ArrayList<IElementType>() for (item in combinationList) { val itemBitMask = bitMap[item]!! for (combo in combinationList) { val comboBitMask = bitMap[combo]!! if (comboBitMask and itemBitMask == 0) { // this combination can be a new one val base: IElementType val overlay: IElementType if (itemBitMask < maxBaseMask) { base = item overlay = combo } else { // only allow overlay items with combinations or other overlay items if (bitItems.contains(combo) && comboBitMask < maxBaseMask) { continue } base = combo overlay = item } val comboName = bitMaskNameMap.computeIfAbsent(itemBitMask or comboBitMask) { base.toString() + "_" + overlay.toString() } val element = createSplitCombo(comboName, base, overlay) if (!bitMap.contains(element)) { bitMap.put(element, itemBitMask or comboBitMask) newCombinations.add(element) } } } } combinationList.addAll(newCombinations) } while (combinationCount < combinationList.size) return combinationList } fun crossSplits(bases: Collection<IElementType>, overlays: Collection<IElementType>): Set<IElementType> { val listSet = HashSet<IElementType>(bases.size * overlays.size) for (base in bases) { if (!listSet.contains(base)) { listSet.add(base) for (overlay in overlays) { if (!listSet.contains(overlay)) { listSet.add(overlay) } val element = createSplitCombo(base.toString() + "_" + overlay.toString(), base, overlay) if (!listSet.contains(element)) { listSet.add(element) } } state.addChildDoesNotExcludeParent(base, TEXT, false) } } return listSet } fun createSplitCombo(comboName: String, base: IElementType, overlay: IElementType): IElementType { var tableCellType = state.COMBINATION_TYPES[comboName] if (tableCellType != null) { state.addCombinationSplit(tableCellType, base, overlay) return tableCellType } tableCellType = MdTokenType(comboName) state.COMBINATION_TYPES[comboName] = tableCellType state.addCombinationSplit(tableCellType, base, overlay) // TEXT does not exclude the combination state.addChildDoesNotExcludeParent(tableCellType, TEXT, false) val tableCellSet = TokenSet.create(tableCellType) val tableCellKey = highlighterColors.createKey(comboName) MdSyntaxHighlighter.fillMap(tableCellSet, tableCellKey) val baseKey = MdSyntaxHighlighter.getAttributes()[base] val overlayKey = MdSyntaxHighlighter.getAttributes()[overlay] if (baseKey != null && overlayKey != null) MdSyntaxHighlighter.addMergedKey(tableCellKey, baseKey, overlayKey) // if base and overlay are inline then the combination is an inline if (state.INLINE_NON_PLAIN_TEXT.contains(base) || state.INLINE_NON_PLAIN_TEXT.contains(overlay)) { state.INLINE_NON_PLAIN_TEXT.add(tableCellType) } else if (state.INLINE_SPECIAL_TEXT.contains(base) || state.INLINE_SPECIAL_TEXT.contains(overlay)) { state.INLINE_SPECIAL_TEXT.add(tableCellType) } else if (state.INLINE_PLAIN_TEXT.contains(base) || state.INLINE_PLAIN_TEXT.contains(overlay)) { state.INLINE_PLAIN_TEXT.add(tableCellType) } return tableCellType } } internal fun addCombinationSplit(resultingType: IElementType, parentType: IElementType, childType: IElementType) { COMBINATION_SPLITS.computeIfAbsent(childType) { HashMap(2) }.computeIfAbsent(parentType) { resultingType } } }
apache-2.0
4636f356172cd4c95074a81fc2656d94
45.241715
239
0.599823
5.015222
false
false
false
false
sepatel/tekniq
tekniq-jdbc/src/main/kotlin/io/tekniq/jdbc/TqSingleConnectionDataSource.kt
1
2028
package io.tekniq.jdbc import java.io.PrintWriter import java.sql.Connection import java.sql.DriverManager import java.sql.SQLException import java.util.logging.Logger import javax.sql.DataSource /** * Used mostly for testing purposes. Cannot imagine a real use case for a single connection data source otherwise. * True datasource libraries like vibur-dbcp should be used instead in most cases. * @author Sejal Patel */ @Suppress("unused") open class TqSingleConnectionDataSource( url: String, username: String? = null, password: String? = null, autoCommit: Boolean = true ) : DataSource { private val connection: Connection = DriverManager.getConnection(url, username, password) .apply { setAutoCommit(autoCommit) } fun close() { connection.close() } override fun setLogWriter(out: PrintWriter?) { throw UnsupportedOperationException("setLogWriter(PrintWriter)") } override fun setLoginTimeout(seconds: Int) { throw UnsupportedOperationException("setLoginTimeout(Int)") } override fun getParentLogger(): Logger { throw UnsupportedOperationException("getParentLogger()") } override fun getLogWriter(): PrintWriter { throw UnsupportedOperationException("getLogWriter()") } override fun getLoginTimeout(): Int = 0 override fun isWrapperFor(iface: Class<*>?): Boolean = iface!!.isInstance(this) override fun <T : Any?> unwrap(iface: Class<T>?): T { if (iface!!.isInstance(this)) { @Suppress("UNCHECKED_CAST") return this as T } throw SQLException("Connection cannot be unwrapped to ${iface.name}") } override fun getConnection(): Connection = UncloseableConnection(connection) override fun getConnection(username: String?, password: String?): Connection = UncloseableConnection(connection) private class UncloseableConnection(connection: Connection) : Connection by connection { override fun close() { } } }
mit
826ab87d87f0ff6186693494529012e6
29.727273
116
0.699211
4.771765
false
false
false
false
charlesmadere/smash-ranks-android
smash-ranks-android/app/src/main/java/com/garpr/android/sync/roster/SmashRosterSyncWorker.kt
1
1442
package com.garpr.android.sync.roster import android.content.Context import androidx.work.Worker import androidx.work.WorkerParameters import com.garpr.android.data.models.SmashRosterSyncResult import com.garpr.android.misc.Timber import org.koin.core.KoinComponent import org.koin.core.inject class SmashRosterSyncWorker( context: Context, workerParams: WorkerParameters ) : Worker(context, workerParams), KoinComponent { protected val smashRosterSyncManager: SmashRosterSyncManager by inject() protected val timber: Timber by inject() companion object { private const val TAG = "SmashRosterSyncWorker" } override fun doWork(): Result { timber.d(TAG, "work starting...") var syncResult: SmashRosterSyncResult? = null try { smashRosterSyncManager.sync() .blockingAwait() timber.d(TAG, "successfully synced smash roster") syncResult = smashRosterSyncManager.syncResult } catch (e: RuntimeException) { timber.e(TAG, "Exception when syncing smash roster", e) } timber.d(TAG, "work complete") return if (syncResult?.success == true) { timber.d(TAG, "work was successful ($syncResult)") Result.success() } else { timber.w(TAG, "work wasn't successful, will retry ($syncResult)") Result.retry() } } }
unlicense
7859e1c840e3fdeb53da2944107bdb27
28.428571
77
0.653953
4.790698
false
false
false
false
android/architecture-samples
app/src/main/java/com/example/android/architecture/blueprints/todoapp/statistics/StatisticsViewModel.kt
1
3354
/* * Copyright (C) 2019 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.android.architecture.blueprints.todoapp.statistics import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.example.android.architecture.blueprints.todoapp.data.Result import com.example.android.architecture.blueprints.todoapp.data.Result.Success import com.example.android.architecture.blueprints.todoapp.data.Task import com.example.android.architecture.blueprints.todoapp.data.source.TasksRepository import com.example.android.architecture.blueprints.todoapp.util.Async import com.example.android.architecture.blueprints.todoapp.util.WhileUiSubscribed import dagger.hilt.android.lifecycle.HiltViewModel import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.map import kotlinx.coroutines.flow.onStart import kotlinx.coroutines.flow.stateIn import kotlinx.coroutines.launch import javax.inject.Inject /** * UiState for the statistics screen. */ data class StatisticsUiState( val isEmpty: Boolean = false, val isLoading: Boolean = false, val activeTasksPercent: Float = 0f, val completedTasksPercent: Float = 0f ) /** * ViewModel for the statistics screen. */ @HiltViewModel class StatisticsViewModel @Inject constructor( private val tasksRepository: TasksRepository ) : ViewModel() { val uiState: StateFlow<StatisticsUiState> = tasksRepository.getTasksStream() .map { Async.Success(it) } .onStart<Async<Result<List<Task>>>> { emit(Async.Loading) } .map { taskAsync -> produceStatisticsUiState(taskAsync) } .stateIn( scope = viewModelScope, started = WhileUiSubscribed, initialValue = StatisticsUiState(isLoading = true) ) fun refresh() { viewModelScope.launch { tasksRepository.refreshTasks() } } private fun produceStatisticsUiState(taskLoad: Async<Result<List<Task>>>) = when (taskLoad) { Async.Loading -> { StatisticsUiState(isLoading = true, isEmpty = true) } is Async.Success -> { when (val result = taskLoad.data) { is Success -> { val stats = getActiveAndCompletedStats(result.data) StatisticsUiState( isEmpty = result.data.isEmpty(), activeTasksPercent = stats.activeTasksPercent, completedTasksPercent = stats.completedTasksPercent, isLoading = false ) } else -> StatisticsUiState(isLoading = false) } } } }
apache-2.0
e723db2e2c8a26f52aeddb4ace5e4dca
36.266667
86
0.664878
4.882096
false
false
false
false
http4k/http4k
http4k-serverless/gcf/src/test/kotlin/org/http4k/serverless/helpers.kt
1
1868
package org.http4k.serverless import com.google.cloud.functions.HttpRequest import com.google.cloud.functions.HttpResponse import org.http4k.core.Request import java.io.ByteArrayOutputStream import java.util.Optional class FakeGCFRequest(private val http4k: Request) : HttpRequest { override fun getReader() = TODO() override fun getMethod() = http4k.method.name override fun getHeaders(): Map<String, List<String>> = http4k.headers .groupBy { it.first } .mapValues { it.value.map { it.second ?: "" } } .toMutableMap() override fun getUri() = http4k.uri.toString() override fun getCharacterEncoding() = TODO() override fun getQuery() = TODO() override fun getContentLength() = http4k.body.length ?: -1 override fun getContentType() = TODO() override fun getPath() = http4k.uri.path override fun getParts() = TODO() override fun getQueryParameters() = TODO() override fun getInputStream() = http4k.body.stream } class FakeGCFResponse : HttpResponse { var status: Int? = null private var _contentType: Optional<String> = Optional.empty() private val headers = mutableMapOf<String, MutableList<String>>() private val outStream = ByteArrayOutputStream() override fun getOutputStream() = outStream override fun getHeaders() = headers override fun getContentType() = _contentType override fun getWriter() = TODO() override fun setStatusCode(code: Int) = TODO() val body: String get() = String(outStream.toByteArray()) override fun setContentType(contentType: String) { _contentType = Optional.of(contentType) } override fun appendHeader(header: String, value: String) { headers.getOrPut(header, { mutableListOf() }).add(value) } override fun setStatusCode(code: Int, message: String?) { status = code } }
apache-2.0
0f0c4b96d64dac1dfe8aeb9a97093aae
34.245283
73
0.698073
4.294253
false
false
false
false
mbuhot/eskotlin
src/main/kotlin/mbuhot/eskotlin/query/compound/Bool.kt
1
1220
/* * Copyright (c) 2016. Michael Buhot [email protected] */ package mbuhot.eskotlin.query.compound import org.elasticsearch.index.query.BoolQueryBuilder import org.elasticsearch.index.query.QueryBuilder data class BoolData( var must: List<QueryBuilder>? = null, var filter: List<QueryBuilder>? = null, var must_not: List<QueryBuilder>? = null, var should: List<QueryBuilder>? = null, var minimum_should_match: Int? = null, var boost: Float? = null) { fun must(f: () -> QueryBuilder) { must = listOf(f()) } fun must_not(f: () -> QueryBuilder) { must_not = listOf(f()) } fun filter(f: () -> QueryBuilder) { filter = listOf(f()) } fun should(f: () -> QueryBuilder) { should = listOf(f()) } } fun bool(init: BoolData.() -> Unit): BoolQueryBuilder { val params = BoolData().apply(init) return BoolQueryBuilder().apply { params.must?.forEach { must(it) } params.filter?.forEach { filter(it) } params.must_not?.forEach { mustNot(it) } params.should?.forEach { should(it) } params.minimum_should_match?.let { minimumShouldMatch(it) } params.boost?.let { boost(it) } } }
mit
f72f97ce7e45dde0bafe5c0c7dc69429
25.543478
67
0.612295
3.620178
false
false
false
false
msebire/intellij-community
plugins/svn4idea/src/org/jetbrains/idea/svn/integrate/AlienCommitWorkflow.kt
1
2223
// 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.idea.svn.integrate import com.intellij.openapi.vcs.AbstractVcs import com.intellij.openapi.vcs.changes.Change import com.intellij.openapi.vcs.changes.CommitExecutor import com.intellij.openapi.vcs.changes.LocalChangeList import com.intellij.openapi.vcs.changes.ui.CommitChangeListDialog import com.intellij.openapi.vcs.changes.ui.CommitChangeListDialog.DIALOG_TITLE import com.intellij.openapi.vcs.changes.ui.CommitDialogChangesBrowser import com.intellij.openapi.vcs.changes.ui.DefaultCommitResultHandler import com.intellij.openapi.vcs.changes.ui.DialogCommitWorkflow import com.intellij.openapi.vcs.checkin.CheckinHandler import com.intellij.openapi.vfs.VirtualFile import com.intellij.util.NullableFunction class AlienCommitWorkflow(val vcs: AbstractVcs<*>, changeListName: String, changes: List<Change>, commitMessage: String?) : DialogCommitWorkflow(vcs.project, changes, vcsToCommit = vcs, initialCommitMessage = commitMessage) { val changeList = AlienLocalChangeList(changes, changeListName) override fun prepareCommit(unversionedFiles: List<VirtualFile>, browser: CommitDialogChangesBrowser) = true override fun doRunBeforeCommitChecks(changeList: LocalChangeList, checks: Runnable) = checks.run() override fun canExecute(executor: CommitExecutor, changes: Collection<Change>) = true override fun doCommit(changeList: LocalChangeList, changes: List<Change>, commitMessage: String, handlers: List<CheckinHandler>, additionalData: NullableFunction<Any, Any>) { val committer = AlienCommitter(vcs, changes, commitMessage, handlers, additionalData) committer.addResultHandler(DefaultCommitResultHandler(committer)) committer.runCommit(DIALOG_TITLE, false) } override fun createBrowser() = AlienChangeListBrowser(project, changeList) override fun initDialog(dialog: CommitChangeListDialog) { val browser = dialog.browser browser.viewer.setIncludedChanges(initiallyIncluded) browser.viewer.rebuildTree() } }
apache-2.0
32b1c52bd4cb1d8b5cd56f4279aedc26
47.347826
140
0.783176
4.790948
false
false
false
false
xiaopansky/Sketch
sample/src/main/java/me/panpf/sketch/sample/ui/ImageDetailActivity.kt
1
3750
/* * Copyright 2013 Peng fei Pan * * 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 me.panpf.sketch.sample.ui import android.app.Activity import android.content.Intent import android.os.Build import android.os.Bundle import android.view.MotionEvent import androidx.core.view.updatePadding import kotlinx.android.synthetic.main.at_image_detail.* import me.panpf.androidxkt.view.isOrientationPortrait import me.panpf.sketch.sample.ImageOptions import me.panpf.sketch.sample.R import me.panpf.sketch.sample.base.BaseActivity import me.panpf.sketch.sample.base.BindContentView import me.panpf.sketch.sample.util.DeviceUtils @BindContentView(R.layout.at_image_detail) class ImageDetailActivity : BaseActivity(), PageBackgApplyCallback { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { imageDetailAt_contentFrame.updatePadding(top = imageDetailAt_contentFrame.paddingTop + DeviceUtils.getStatusBarHeight(resources)) } // + DeviceUtils.getNavigationBarHeightByUiVisibility(this) 是为了兼容 MIX 2 imageDetailAt_bgImage.layoutParams?.let { it.width = resources.displayMetrics.widthPixels it.height = resources.displayMetrics.heightPixels if (isOrientationPortrait()) { it.height += DeviceUtils.getWindowHeightSupplement(this) } else { it.width += DeviceUtils.getWindowHeightSupplement(this) } imageDetailAt_bgImage.layoutParams = it } imageDetailAt_bgImage.setOptions(ImageOptions.WINDOW_BACKGROUND) val imageDetailFragment = ImageDetailFragment() imageDetailFragment.arguments = intent.extras supportFragmentManager .beginTransaction() .replace(R.id.imageDetailAt_contentFrame, imageDetailFragment) .commit() } override fun dispatchTouchEvent(ev: MotionEvent): Boolean { var result = true try { result = super.dispatchTouchEvent(ev) } catch (e: RuntimeException) { e.printStackTrace() } return result } override fun onBackPressed() { super.onBackPressed() overridePendingTransition(R.anim.window_pop_enter, R.anim.window_pop_exit) } override fun onApplyBackground(imageUri: String?) { imageUri?.let { imageDetailAt_bgImage.displayImage(it) } } companion object { fun launch(activity: Activity, dataTransferKey: String, loadingImageOptionsInfo: String?, defaultPosition: Int) { val intent = Intent(activity, ImageDetailActivity::class.java) intent.putExtra(ImageDetailFragment.PARAM_REQUIRED_STRING_DATA_TRANSFER_KEY, dataTransferKey) intent.putExtra(ImageDetailFragment.PARAM_REQUIRED_STRING_LOADING_IMAGE_OPTIONS_KEY, loadingImageOptionsInfo) intent.putExtra(ImageDetailFragment.PARAM_OPTIONAL_INT_DEFAULT_POSITION, defaultPosition) activity.startActivity(intent) activity.overridePendingTransition(R.anim.window_push_enter, R.anim.window_push_exit) } } }
apache-2.0
d2eb1252a043e139de5c5a6e2ed49f18
37.556701
141
0.709091
4.663342
false
false
false
false
ankidroid/Anki-Android
AnkiDroid/src/main/java/com/ichi2/anki/cardviewer/ViewerCommand.kt
1
9919
/* Copyright (c) 2020 David Allison <[email protected]> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.ichi2.anki.cardviewer import android.content.SharedPreferences import android.view.KeyEvent import androidx.core.content.edit import com.ichi2.anki.R import com.ichi2.anki.reviewer.Binding.Companion.keyCode import com.ichi2.anki.reviewer.Binding.Companion.unicode import com.ichi2.anki.reviewer.Binding.ModifierKeys import com.ichi2.anki.reviewer.Binding.ModifierKeys.Companion.ctrl import com.ichi2.anki.reviewer.Binding.ModifierKeys.Companion.shift import com.ichi2.anki.reviewer.CardSide import com.ichi2.anki.reviewer.MappableBinding import com.ichi2.anki.reviewer.MappableBinding.Companion.fromPreference import com.ichi2.anki.reviewer.MappableBinding.Companion.toPreferenceString import java.util.* import java.util.function.BiFunction import java.util.stream.Collectors /** Abstraction: Discuss moving many of these to 'Reviewer' */ enum class ViewerCommand(val resourceId: Int) { SHOW_ANSWER(R.string.show_answer), FLIP_OR_ANSWER_EASE1(R.string.gesture_answer_1), FLIP_OR_ANSWER_EASE2(R.string.gesture_answer_2), FLIP_OR_ANSWER_EASE3(R.string.gesture_answer_3), FLIP_OR_ANSWER_EASE4(R.string.gesture_answer_4), FLIP_OR_ANSWER_RECOMMENDED(R.string.gesture_answer_green), FLIP_OR_ANSWER_BETTER_THAN_RECOMMENDED(R.string.gesture_answer_better_recommended), UNDO(R.string.undo), EDIT(R.string.cardeditor_title_edit_card), MARK(R.string.menu_mark_note), BURY_CARD(R.string.menu_bury), SUSPEND_CARD(R.string.menu_suspend_card), DELETE(R.string.menu_delete_note), PLAY_MEDIA(R.string.gesture_play), EXIT(R.string.gesture_abort_learning), BURY_NOTE(R.string.menu_bury_note), SUSPEND_NOTE(R.string.menu_suspend_note), TOGGLE_FLAG_RED(R.string.gesture_flag_red), TOGGLE_FLAG_ORANGE(R.string.gesture_flag_orange), TOGGLE_FLAG_GREEN(R.string.gesture_flag_green), TOGGLE_FLAG_BLUE(R.string.gesture_flag_blue), TOGGLE_FLAG_PINK(R.string.gesture_flag_pink), TOGGLE_FLAG_TURQUOISE(R.string.gesture_flag_turquoise), TOGGLE_FLAG_PURPLE(R.string.gesture_flag_purple), UNSET_FLAG(R.string.gesture_flag_remove), PAGE_UP(R.string.gesture_page_up), PAGE_DOWN(R.string.gesture_page_down), TAG(R.string.add_tag), CARD_INFO(R.string.card_info_title), ABORT_AND_SYNC(R.string.gesture_abort_sync), RECORD_VOICE(R.string.record_voice), REPLAY_VOICE(R.string.replay_voice), TOGGLE_WHITEBOARD(R.string.gesture_toggle_whiteboard), SHOW_HINT(R.string.gesture_show_hint), SHOW_ALL_HINTS(R.string.gesture_show_all_hints), ADD_NOTE(R.string.menu_add_note); companion object { val allDefaultBindings: List<MappableBinding> get() = Arrays.stream(values()) .flatMap { x: ViewerCommand -> x.defaultValue.stream() } .collect(Collectors.toList()) } val preferenceKey: String get() = "binding_$name" fun addBinding(preferences: SharedPreferences, binding: MappableBinding) { val addAtStart = BiFunction { collection: MutableList<MappableBinding>, element: MappableBinding -> // reorder the elements, moving the added binding to the first position collection.remove(element) collection.add(0, element) true } addBindingInternal(preferences, binding, addAtStart) } fun addBindingAtEnd(preferences: SharedPreferences, binding: MappableBinding) { val addAtEnd = BiFunction { collection: MutableList<MappableBinding>, element: MappableBinding -> // do not reorder the elements if (collection.contains(element)) { return@BiFunction false } collection.add(element) return@BiFunction true } addBindingInternal(preferences, binding, addAtEnd) } private fun addBindingInternal(preferences: SharedPreferences, binding: MappableBinding, performAdd: BiFunction<MutableList<MappableBinding>, MappableBinding, Boolean>) { val bindings: MutableList<MappableBinding> = fromPreference(preferences, this) performAdd.apply(bindings, binding) val newValue: String = bindings.toPreferenceString() preferences.edit { putString(preferenceKey, newValue) } } fun removeBinding(prefs: SharedPreferences, binding: MappableBinding) { val bindings: MutableList<MappableBinding> = MappableBinding.fromPreferenceString(preferenceKey) bindings.remove(binding) prefs.edit { putString(preferenceKey, bindings.toPreferenceString()) } } // If we use the serialised format, then this adds additional coupling to the properties. val defaultValue: List<MappableBinding> get() = // If we use the serialised format, then this adds additional coupling to the properties. when (this) { FLIP_OR_ANSWER_EASE1 -> from( keyCode(KeyEvent.KEYCODE_BUTTON_Y, CardSide.BOTH), keyCode(KeyEvent.KEYCODE_1, CardSide.ANSWER), keyCode(KeyEvent.KEYCODE_NUMPAD_1, CardSide.ANSWER) ) FLIP_OR_ANSWER_EASE2 -> from( keyCode(KeyEvent.KEYCODE_BUTTON_X, CardSide.BOTH), keyCode(KeyEvent.KEYCODE_2, CardSide.ANSWER), keyCode(KeyEvent.KEYCODE_NUMPAD_2, CardSide.ANSWER) ) FLIP_OR_ANSWER_EASE3 -> from( keyCode(KeyEvent.KEYCODE_BUTTON_B, CardSide.BOTH), keyCode(KeyEvent.KEYCODE_3, CardSide.ANSWER), keyCode(KeyEvent.KEYCODE_NUMPAD_3, CardSide.ANSWER) ) FLIP_OR_ANSWER_EASE4 -> from( keyCode(KeyEvent.KEYCODE_BUTTON_A, CardSide.BOTH), keyCode(KeyEvent.KEYCODE_4, CardSide.ANSWER), keyCode(KeyEvent.KEYCODE_NUMPAD_4, CardSide.ANSWER) ) FLIP_OR_ANSWER_RECOMMENDED -> from( keyCode(KeyEvent.KEYCODE_DPAD_CENTER, CardSide.BOTH), keyCode(KeyEvent.KEYCODE_SPACE, CardSide.ANSWER), keyCode(KeyEvent.KEYCODE_ENTER, CardSide.ANSWER), keyCode(KeyEvent.KEYCODE_NUMPAD_ENTER, CardSide.ANSWER) ) EDIT -> from(keyCode(KeyEvent.KEYCODE_E, CardSide.BOTH)) MARK -> from(unicode('*', CardSide.BOTH)) BURY_CARD -> from(unicode('-', CardSide.BOTH)) BURY_NOTE -> from(unicode('=', CardSide.BOTH)) SUSPEND_CARD -> from(unicode('@', CardSide.BOTH)) SUSPEND_NOTE -> from(unicode('!', CardSide.BOTH)) PLAY_MEDIA -> from(keyCode(KeyEvent.KEYCODE_R, CardSide.BOTH), keyCode(KeyEvent.KEYCODE_F5, CardSide.BOTH)) REPLAY_VOICE -> from(keyCode(KeyEvent.KEYCODE_V, CardSide.BOTH)) RECORD_VOICE -> from(keyCode(KeyEvent.KEYCODE_V, CardSide.BOTH, shift())) UNDO -> from(keyCode(KeyEvent.KEYCODE_Z, CardSide.BOTH)) TOGGLE_FLAG_RED -> from(keyCode(KeyEvent.KEYCODE_1, CardSide.BOTH, ctrl()), keyCode(KeyEvent.KEYCODE_NUMPAD_1, CardSide.BOTH, ctrl())) TOGGLE_FLAG_ORANGE -> from(keyCode(KeyEvent.KEYCODE_2, CardSide.BOTH, ctrl()), keyCode(KeyEvent.KEYCODE_NUMPAD_2, CardSide.BOTH, ctrl())) TOGGLE_FLAG_GREEN -> from(keyCode(KeyEvent.KEYCODE_3, CardSide.BOTH, ctrl()), keyCode(KeyEvent.KEYCODE_NUMPAD_3, CardSide.BOTH, ctrl())) TOGGLE_FLAG_BLUE -> from(keyCode(KeyEvent.KEYCODE_4, CardSide.BOTH, ctrl()), keyCode(KeyEvent.KEYCODE_NUMPAD_4, CardSide.BOTH, ctrl())) TOGGLE_FLAG_PINK -> from(keyCode(KeyEvent.KEYCODE_5, CardSide.BOTH, ctrl()), keyCode(KeyEvent.KEYCODE_NUMPAD_5, CardSide.BOTH, ctrl())) TOGGLE_FLAG_TURQUOISE -> from(keyCode(KeyEvent.KEYCODE_6, CardSide.BOTH, ctrl()), keyCode(KeyEvent.KEYCODE_NUMPAD_6, CardSide.BOTH, ctrl())) TOGGLE_FLAG_PURPLE -> from(keyCode(KeyEvent.KEYCODE_7, CardSide.BOTH, ctrl()), keyCode(KeyEvent.KEYCODE_NUMPAD_7, CardSide.BOTH, ctrl())) SHOW_HINT -> from(keyCode(KeyEvent.KEYCODE_H, CardSide.BOTH)) SHOW_ALL_HINTS -> from(keyCode(KeyEvent.KEYCODE_G, CardSide.BOTH)) ADD_NOTE -> from(keyCode(KeyEvent.KEYCODE_A, CardSide.BOTH)) else -> ArrayList() } private fun keyCode(keycode: Int, side: CardSide, keys: ModifierKeys): MappableBinding { return MappableBinding(keyCode(keys, keycode), MappableBinding.Screen.Reviewer(side)) } private fun unicode(c: Char, side: CardSide): MappableBinding { return MappableBinding(unicode(c), MappableBinding.Screen.Reviewer(side)) } private fun from(vararg bindings: MappableBinding): List<MappableBinding> { return ArrayList(listOf(*bindings)) } private fun keyCode(keyCode: Int, side: CardSide): MappableBinding { return MappableBinding(keyCode(keyCode), MappableBinding.Screen.Reviewer(side)) } fun interface CommandProcessor { /** * * example failure: answering an ease on the front of the card */ fun executeCommand(which: ViewerCommand, fromGesture: Gesture?): Boolean } }
gpl-3.0
44e8c4056ab5d949f8320cd904f04544
50.393782
174
0.675673
4.21547
false
false
false
false
ccomeaux/boardgamegeek4android
app/src/main/java/com/boardgamegeek/ui/dialog/SuggestedAgeFilterDialog.kt
1
1853
package com.boardgamegeek.ui.dialog import android.content.Context import com.boardgamegeek.R import com.boardgamegeek.extensions.andMore import com.boardgamegeek.filterer.CollectionFilterer import com.boardgamegeek.filterer.SuggestedAgeFilterer import kotlin.math.roundToInt class SuggestedAgeFilterDialog : SliderFilterDialog() { override fun getType(context: Context) = SuggestedAgeFilterer(context).type override val titleResId = R.string.menu_suggested_age override val descriptionResId = R.string.filter_description_include_missing_suggested_age override val valueFrom = SuggestedAgeFilterer.lowerBound.toFloat() override val valueTo = SuggestedAgeFilterer.upperBound.toFloat() override fun initValues(filter: CollectionFilterer?): InitialValues { val f = filter as? SuggestedAgeFilterer return InitialValues( (f?.min ?: SuggestedAgeFilterer.lowerBound).toFloat(), (f?.max ?: SuggestedAgeFilterer.upperBound).toFloat(), f?.includeUndefined ?: false, f?.ignoreRange ?: false, ) } override fun createFilterer(context: Context): CollectionFilterer { return SuggestedAgeFilterer(context).apply { min = low.roundToInt() max = high.roundToInt() includeUndefined = checkboxIsChecked ignoreRange = rangeIsIgnored } } override fun describeRange(context: Context): String { return (createFilterer(context) as? SuggestedAgeFilterer)?.describeRange(rangeSeparator = " - ") ?: context.getString(R.string.all) } override fun formatSliderLabel(context: Context, value: Float): String { return when (val age = value.roundToInt()) { SuggestedAgeFilterer.upperBound -> age.toString().andMore() else -> age.toString() } } }
gpl-3.0
e74d70b46f144295114742ed3ce7bfd5
39.282609
139
0.702105
5.02168
false
false
false
false
songzhw/Hello-kotlin
AdvancedJ/src/main/kotlin/aop/proxy/retrofit/Retrofit.kt
1
2308
package aop.proxy.retrofit import sun.reflect.generics.reflectiveObjects.ParameterizedTypeImpl import java.lang.reflect.* class Retrofit(val baseUrl: String) { fun <T> create(targetClass: Class<T>): T { val wrapped = Proxy.newProxyInstance( targetClass.classLoader, arrayOf<Class<*>>(targetClass), object : InvocationHandler { override fun invoke(proxy: Any?, method: Method, args: Array<out Any>?): Any { val getAnnotation = method.getAnnotation(GET::class.java) val subUrl = getAnnotation.value val url = "${baseUrl}/${subUrl}" println("http url = ${url}") // 若返回Call<User>, 那这没问题 // 若返回User, 那method.genericReturnType就是Class, 而不是ParametrizedType val returnType = method.genericReturnType //=> Call<List<User>>; 有泛型时是Call<List<T>> if (returnType is ParameterizedType) { val actualType = returnType.actualTypeArguments[0] if (actualType is ParameterizedTypeImpl) { // 有泛型时, 如Call<List<User> val returnedType = actualType as ParameterizedTypeImpl //=> List<User>; 有泛型时是List<T> val clz = returnedType.rawType return clz.newInstance() } else { // 无泛型时, 如Call<User>. clz就是User val clz = actualType as Class<*> val obj = clz.newInstance() return obj // TODO 返回List<User>时, 这里clz是User类, 但要如何转成List<User>? } } else { // 返回的不是Call<User>, 而就是无泛型的, 如User val clz = returnType as Class<*> return clz.newInstance() } } } ) as T return wrapped } }
apache-2.0
f406f8eac775f9a58ee2f65ba019ff88
43.44898
120
0.461433
5.445
false
false
false
false
ratabb/Hishoot2i
app/src/main/java/org/illegaller/ratabb/hishoot2i/ui/setting/SettingFragment.kt
1
6714
package org.illegaller.ratabb.hishoot2i.ui.setting import android.graphics.Bitmap.CompressFormat import android.net.Uri import android.os.Build.VERSION.SDK_INT import android.os.Bundle import android.text.format.Formatter.formatShortFileSize import android.view.View import androidx.annotation.RequiresApi import androidx.appcompat.app.AppCompatDelegate import androidx.documentfile.provider.DocumentFile import androidx.fragment.app.Fragment import androidx.fragment.app.clearFragmentResult import androidx.fragment.app.setFragmentResultListener import androidx.fragment.app.viewModels import androidx.navigation.fragment.findNavController import common.ext.preventMultipleClick import common.ext.setOnItemSelected import common.ext.toFile import dagger.hilt.android.AndroidEntryPoint import entity.DayNightMode import entity.DayNightMode.DARK import entity.DayNightMode.LIGHT import entity.DayNightMode.SYSTEM import entity.mode import org.illegaller.ratabb.hishoot2i.R import org.illegaller.ratabb.hishoot2i.data.pref.SettingPref import org.illegaller.ratabb.hishoot2i.databinding.FragmentSettingBinding import org.illegaller.ratabb.hishoot2i.ui.ARG_THEME import org.illegaller.ratabb.hishoot2i.ui.KEY_REQ_THEME import org.illegaller.ratabb.hishoot2i.ui.common.registerOpenDocumentTree import org.illegaller.ratabb.hishoot2i.ui.common.viewObserve import org.illegaller.ratabb.hishoot2i.ui.setting.SettingFragmentDirections.Companion.actionSettingToThemeChooser import javax.inject.Inject @AndroidEntryPoint class SettingFragment : Fragment(R.layout.fragment_setting) { @Inject lateinit var settingPref: SettingPref private val viewModel: SettingViewModel by viewModels() @RequiresApi(21) private val customDir = registerOpenDocumentTree { uri -> val file = DocumentFile.fromTreeUri(requireContext(), uri)?.uri?.toFile(requireContext()) settingPref.customFontPath = file?.absolutePath } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) FragmentSettingBinding.bind(view).apply { setViewListener() setFragmentResultListener(KEY_REQ_THEME) { _, result -> val ordinal = result.getInt(ARG_THEME) val dayNightMode = DayNightMode.values()[ordinal] settingPref.dayNightMode = dayNightMode AppCompatDelegate.setDefaultNightMode(dayNightMode.mode) updateDayNightUi() } } } override fun onDestroyView() { clearFragmentResult(KEY_REQ_THEME) super.onDestroyView() } private fun FragmentSettingBinding.setViewListener() { settingBottomAppBar.setNavigationOnClickListener { it.preventMultipleClick { findNavController().popBackStack() } } // region Theme itemSettingAppThemes.settingDayNight.setOnClickListener { it.preventMultipleClick { findNavController().navigate(actionSettingToThemeChooser(settingPref.dayNightMode)) } } updateDayNightUi() // endregion // region Badge itemSettingBadgeFontPath.settingBadgeSystemFont.apply { isChecked = settingPref.systemFontEnable setOnCheckedChangeListener { cb, checked -> cb.preventMultipleClick { if (settingPref.systemFontEnable != checked) { settingPref.systemFontEnable = checked } } } } itemSettingBadgeFontPath.settingBadgeCustomFontDir.apply { isEnabled = SDK_INT >= 21 setOnClickListener { it.preventMultipleClick { if (SDK_INT >= 21) customDir.launch(Uri.EMPTY) } } } // endregion // region Save itemSettingSaveOption.settingSaveQuality.apply { value = settingPref.saveQuality.toFloat() addOnChangeListener { _, value, _ -> settingPref.saveQuality = value.toInt() } } handleEnableQuality() itemSettingSaveOption.settingSaveFormat.apply { setSelection(settingPref.compressFormat.ordinal, false) setOnItemSelected { _, v, position, _ -> v?.preventMultipleClick { if (position != settingPref.compressFormat.ordinal) { settingPref.compressFormat = CompressFormat.values()[position] handleEnableQuality() } } } } itemSettingSaveOption.settingSaveNotification.apply { isChecked = settingPref.saveNotificationEnable setOnCheckedChangeListener { cb, checked -> cb.preventMultipleClick { if (settingPref.saveNotificationEnable != checked) { settingPref.saveNotificationEnable = checked } } } } itemSettingSaveOption.settingSaveConfirmation.apply { isChecked = settingPref.saveConfirmEnable setOnCheckedChangeListener { cb, checked -> cb.preventMultipleClick { if (settingPref.saveConfirmEnable != checked) { settingPref.saveConfirmEnable = checked } } } } // endregion // region Cache viewObserve(viewModel.diskCacheSize) { updateCacheCount(it) } itemSettingCache.settingCacheClear.setOnClickListener { it.preventMultipleClick { viewModel.clearDiskCache() } } // endregion } private fun FragmentSettingBinding.handleEnableQuality() { itemSettingSaveOption.settingSaveQuality.isEnabled = settingPref.compressFormat != CompressFormat.PNG } private fun FragmentSettingBinding.updateCacheCount(diskCacheSize: Long) { itemSettingCache.settingCacheCount.apply { text = formatShortFileSize(context, diskCacheSize) } } private fun FragmentSettingBinding.updateDayNightUi() { val (textId, iconId) = when (settingPref.dayNightMode) { LIGHT -> R.string.light to R.drawable.ic_brightness_day DARK -> R.string.dark to R.drawable.ic_brightness_night SYSTEM -> R.string.follow_system to R.drawable.ic_brightness_auto // } with(itemSettingAppThemes.settingDayNight) { setText(textId) setCompoundDrawablesWithIntrinsicBounds(0, 0, iconId, 0) } } }
apache-2.0
6b244e8cb26626926ec72f410323a17d
37.809249
113
0.659666
5.449675
false
false
false
false
Geobert/radis
app/src/main/kotlin/fr/geobert/radis/tools/ProjectionDateController.kt
1
5973
package fr.geobert.radis.tools import android.app.Activity import android.os.Bundle import android.view.View import android.widget.AdapterView import android.widget.ArrayAdapter import android.widget.EditText import android.widget.Spinner import fr.geobert.radis.R import fr.geobert.radis.data.Account import kotlin.properties.Delegates public class ProjectionDateController(private val mActivity: Activity) { private val mProjectionMode: Spinner by lazy(LazyThreadSafetyMode.NONE) { mActivity.findViewById(R.id.projection_date_spinner) as Spinner } public val mProjectionDate: EditText by lazy(LazyThreadSafetyMode.NONE) { mActivity.findViewById(R.id.projection_date_value) as EditText } private var mAccountId: Long = 0 private var mOrigProjMode: Int = 0 private var mOrigProjDate: String? = null private var mCurPos: Int = 0 init { initViews() } public fun initViews() { val adapter = ArrayAdapter.createFromResource(mActivity, R.array.projection_modes, android.R.layout.simple_spinner_item) adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item) mProjectionMode.adapter = adapter mProjectionMode.onItemSelectedListener = object : AdapterView.OnItemSelectedListener { override fun onItemSelected(arg0: AdapterView<*>?, arg1: View?, pos: Int, id: Long) { mProjectionDate.visibility = if (pos > 0) View.VISIBLE else View.GONE if (pos != mCurPos) { mProjectionDate.setText("") } [email protected](pos) } override fun onNothingSelected(arg0: AdapterView<*>?) { } } } protected fun setHint(pos: Int) { var hint: CharSequence = "" when (pos) { 0 -> hint = "" 1 -> hint = mActivity.getString(R.string.projection_day_of_month) 2 -> hint = mActivity.getString(R.string.projection_full_date) } mProjectionDate.hint = hint } public fun populateFields(account: Account) { mAccountId = account.id mCurPos = account.projMode mOrigProjDate = account.projDate setHint(mCurPos) mOrigProjMode = mCurPos mProjectionMode.setSelection(mCurPos) mProjectionDate.visibility = if (mCurPos > 0) View.VISIBLE else View.GONE mProjectionDate.setText(mOrigProjDate) } public fun getMode(): Int { return mProjectionMode.selectedItemPosition } public fun getDate(): String { return mProjectionDate.text.toString() } public fun hasChanged(): Boolean { return mOrigProjMode != mProjectionMode.selectedItemPosition || (mOrigProjMode != 0 && mOrigProjDate != mProjectionDate.text.toString()) } public fun onSaveInstanceState(outState: Bundle) { outState.putInt("projectionMode", mProjectionMode.selectedItemPosition) outState.putString("projectionDate", mProjectionDate.text.toString()) outState.putInt("origProjMode", mOrigProjMode) outState.putString("origProjDate", mOrigProjDate) outState.putInt("pos", mCurPos) outState.putLong("accountId", mAccountId) } public fun onRestoreInstanceState(state: Bundle) { mProjectionMode.setSelection(state.getInt("projectionMode")) mProjectionDate.setText(state.getString("projectionDate")) mOrigProjDate = state.getString("origProjDate") mOrigProjMode = state.getInt("origProjMode") mCurPos = state.getInt("pos") mAccountId = state.getLong("accountId") setHint(mCurPos) mProjectionMode.setSelection(mCurPos) mProjectionDate.visibility = if (mCurPos > 0) View.VISIBLE else View.GONE mProjectionDate.setText(mOrigProjDate) } // protected fun saveProjectionDate() { // try { // AccountTable.updateAccountProjectionDate(mActivity, mAccountId, mInstance) // if (mActivity is UpdateDisplayInterface) { // (mActivity as UpdateDisplayInterface).updateDisplay(null) // } // } catch (e: ParseException) { // Tools.popError(mActivity, mActivity.getString(R.string.bad_format_for_date), null) // e.printStackTrace() // } catch (e: NumberFormatException) { // Tools.popError(mActivity, mActivity.getString(R.string.bad_format_for_date), null) // e.printStackTrace() // } // // } // companion object { // // protected var mInstance: ProjectionDateController by Delegates.notNull() // // platformStatic public fun getDialog(activity: Activity): AlertDialog { // val builder = AlertDialog.Builder(activity) // val inflater = activity.getLayoutInflater() // val layout = inflater.inflate(R.layout.projection_date_dialog, null) // builder.setPositiveButton(activity.getString(R.string.ok), object : DialogInterface.OnClickListener { // override fun onClick(dialog: DialogInterface, id: Int) { // mInstance.saveProjectionDate() // } // }).setNegativeButton(activity.getString(R.string.cancel), object : DialogInterface.OnClickListener { // override fun onClick(dialog: DialogInterface, id: Int) { // dialog.cancel() // } // }).setTitle(R.string.projection_date) // builder.setView(layout) // val dialog = builder.create() // mInstance = ProjectionDateController(activity) // return dialog // } // // platformStatic public fun onPrepareDialog(account: Cursor) { // mInstance.populateFields(account) // } // } }
gpl-2.0
94f3b84997a4e6e9d1533fc62a3d3208
40.479167
144
0.635024
4.936364
false
false
false
false
FHannes/intellij-community
platform/configuration-store-impl/testSrc/MockStreamProvider.kt
17
1633
package com.intellij.configurationStore import com.intellij.openapi.components.RoamingType import com.intellij.util.io.* import java.io.InputStream import java.nio.file.NoSuchFileException import java.nio.file.Path class MockStreamProvider(private val dir: Path) : StreamProvider { override fun write(fileSpec: String, content: ByteArray, size: Int, roamingType: RoamingType) { dir.resolve(fileSpec).write(content, 0, size) } override fun read(fileSpec: String, roamingType: RoamingType, consumer: (InputStream?) -> Unit): Boolean { val file = dir.resolve(fileSpec) try { file.inputStream().use(consumer) } catch (e: NoSuchFileException) { consumer(null) } return true } override fun processChildren(path: String, roamingType: RoamingType, filter: (name: String) -> Boolean, processor: (name: String, input: InputStream, readOnly: Boolean) -> Boolean): Boolean { dir.resolve(path).directoryStreamIfExists({ filter(it.fileName.toString()) }) { for (file in it) { val attributes = file.basicAttributesIfExists() if (attributes == null || attributes.isDirectory || file.isHidden()) { continue } // we ignore empty files as well - delete if corrupted if (attributes.size() == 0L) { file.delete() continue } if (!file.inputStream().use { processor(file.fileName.toString(), it, false) }) { break } } } return true } override fun delete(fileSpec: String, roamingType: RoamingType): Boolean { dir.resolve(fileSpec).delete() return true } }
apache-2.0
a2a798a879757a34b921238644a7a3a4
30.403846
193
0.665034
4.389785
false
false
false
false
NextFaze/dev-fun
test/src/testData/kotlin/tested/categories/CategoryOrdering.kt
1
2207
@file:Suppress("unused", "ClassName") package tested.categories import com.nextfaze.devfun.category.DeveloperCategory import com.nextfaze.devfun.function.DeveloperFunction import com.nextfaze.devfun.internal.splitSimpleName annotation class CategoryOrdering object co_ExpectedCategoryOrdering { val order = listOf( // MIN_VALUE co_ClassThatShouldBeFirst::class.splitSimpleName, // default=0 co_ClassWithoutCategoryAAAAA::class.splitSimpleName, co_ClassWithoutCategoryBBBBB::class.splitSimpleName, // 9,10 co_ClassWithOrderShouldBeBefore_AAAA::class.splitSimpleName, co_ClassWithOrderAAAA::class.splitSimpleName, // 50 co_ClassWithFunctionCategory::class.splitSimpleName, // 100 "My Named Category (order=100 set at fun)", // MAX_VALUE co_ClassThatShouldBeLast::class.splitSimpleName ) } @DeveloperCategory class co_ClassWithNoFunctions @DeveloperCategory("Custom Name") class co_ClassWithNoFunctionsAndCustomName class co_ClassWithoutCategoryBBBBB { @DeveloperFunction fun someFun() = Unit } class co_ClassWithoutCategoryAAAAA { @DeveloperFunction fun someFun() = Unit } @DeveloperCategory(order = Int.MIN_VALUE) class co_ClassThatShouldBeFirst { @DeveloperFunction fun someFun() = Unit } @DeveloperCategory(order = Int.MAX_VALUE) class co_ClassThatShouldBeLast { @DeveloperFunction fun someFun() = Unit } @DeveloperCategory(order = 10) class co_ClassWithOrderAAAA { @DeveloperFunction fun someFun() = Unit } @DeveloperCategory(order = 9) class co_ClassWithOrderShouldBeBefore_AAAA { @DeveloperFunction fun someFun() = Unit } class co_ClassWithFunctionCategory { @DeveloperFunction(category = DeveloperCategory(order = 50)) fun someFun() = Unit } @DeveloperCategory("My Named Category (order=100 set at fun)") class co_ClassWithNamedCategory { @DeveloperFunction(category = DeveloperCategory(order = 100)) fun someFun() = Unit } class co_ClassAddingSomeComplexity { @DeveloperFunction(category = DeveloperCategory("My Named Category (order=100 set at fun)")) fun funRedeclareCategory() = Unit }
apache-2.0
dfa1250dd5d0cfaf7bf8a503667f53f4
23.797753
96
0.732669
4.353057
false
false
false
false
cwoolner/flex-poker
src/main/kotlin/com/flexpoker/table/query/handlers/PlayerForceFoldedEventHandler.kt
1
2446
package com.flexpoker.table.query.handlers import com.flexpoker.chat.service.ChatService import com.flexpoker.framework.event.EventHandler import com.flexpoker.framework.pushnotifier.PushNotificationPublisher import com.flexpoker.login.repository.LoginRepository import com.flexpoker.pushnotifications.TableUpdatedPushNotification import com.flexpoker.table.command.events.PlayerForceFoldedEvent import com.flexpoker.table.query.repository.TableRepository import org.springframework.stereotype.Component import javax.inject.Inject @Component class PlayerForceFoldedEventHandler @Inject constructor( private val loginRepository: LoginRepository, private val tableRepository: TableRepository, private val pushNotificationPublisher: PushNotificationPublisher, private val chatService: ChatService ) : EventHandler<PlayerForceFoldedEvent> { override fun handle(event: PlayerForceFoldedEvent) { handleUpdatingTable(event) handlePushNotifications(event) handleChat(event) } private fun handleUpdatingTable(event: PlayerForceFoldedEvent) { val tableDTO = tableRepository.fetchById(event.aggregateId) val username = loginRepository.fetchUsernameByAggregateId(event.playerId) val updatedSeats = tableDTO.seats!! .map { if (it.name == username) { it.copy(isStillInHand = false, raiseTo = 0, callAmount = 0, isActionOn = false) } else { it } } val updatePots = tableDTO.pots!! .map { val updatedPotSeats = it.seats.filter { seatName -> seatName != username }.toSet() it.copy(seats = updatedPotSeats) }.toSet() val updatedTable = tableDTO.copy(version = event.version, seats = updatedSeats, pots = updatePots) tableRepository.save(updatedTable) } private fun handlePushNotifications(event: PlayerForceFoldedEvent) { val pushNotification = TableUpdatedPushNotification(event.gameId, event.aggregateId) pushNotificationPublisher.publish(pushNotification) } private fun handleChat(event: PlayerForceFoldedEvent) { val username = loginRepository.fetchUsernameByAggregateId(event.playerId) val message = "Time expired - $username folds" chatService.saveAndPushSystemTableChatMessage(event.gameId, event.aggregateId, message) } }
gpl-2.0
5d6db8645b852124f732c53e6e9a7c2d
41.189655
106
0.721995
5.328976
false
false
false
false
d9n/intellij-rust
src/main/kotlin/org/rust/lang/utils/RsBooleanExpUtils.kt
1
1150
package org.rust.lang.utils import com.intellij.psi.PsiElement import org.rust.lang.core.psi.* import org.rust.lang.core.psi.ext.ComparisonOp.* import org.rust.lang.core.psi.ext.operatorType fun RsBinaryExpr.negateToString(): String { val lhs = left.text val rhs = right?.text ?: "" val op = when (operatorType) { EQ -> "!=" EXCLEQ -> "==" GT -> "<=" LT -> ">=" GTEQ -> "<" LTEQ -> ">" else -> null } return if (op != null) "$lhs $op $rhs" else "!($text)" } fun PsiElement.isNegation(): Boolean = this is RsUnaryExpr && excl != null fun PsiElement.negate(): PsiElement { val psiFactory = RsPsiFactory(project) return when { isNegation() -> { val inner = (this as RsUnaryExpr).expr!! (inner as? RsParenExpr)?.expr ?: inner } this is RsBinaryExpr -> psiFactory.createExpression(negateToString()) this is RsParenExpr || this is RsPathExpr || this is RsCallExpr -> psiFactory.createExpression("!$text") else -> psiFactory.createExpression("!($text)") } }
mit
095c0673ac3b15f7aa2b92e2d5b0e0cd
25.744186
74
0.574783
4.291045
false
false
false
false
DankBots/Mega-Gnar
src/main/kotlin/gg/octave/bot/commands/music/dj/Stop.kt
1
1056
package gg.octave.bot.commands.music.dj import gg.octave.bot.Launcher import gg.octave.bot.entities.framework.CheckVoiceState import gg.octave.bot.entities.framework.DJ import gg.octave.bot.entities.framework.MusicCog import gg.octave.bot.utils.extensions.manager import me.devoxin.flight.api.Context import me.devoxin.flight.api.annotations.Command class Stop : MusicCog { @DJ @CheckVoiceState @Command(aliases = ["leave", "end", "st", "fuckoff"], description = "Stop and clear the music player.") fun stop(ctx: Context, clear: Boolean = false) { val karen = ctx.manager if (clear) { karen.scheduler.queue.clear() } karen.discordFMTrack = null ctx.guild!!.audioManager.closeAudioConnection() Launcher.players.destroy(ctx.guild!!.idLong) val extra = if (clear) ", and the queue has been cleared." else ". If you want to clear the queue run `${ctx.trigger}clearqueue` or `${ctx.trigger}stop yes`" ctx.send("Playback has been completely stopped$extra") } }
mit
d6ccbcfce20f24ba353b9071178abda1
35.413793
165
0.696023
3.798561
false
false
false
false
nextcloud/android
app/src/androidTest/java/com/owncloud/android/datamodel/OCCapabilityIT.kt
1
1851
/* * * Nextcloud Android client application * * @author Tobias Kaminsky * Copyright (C) 2020 Tobias Kaminsky * Copyright (C) 2020 Nextcloud GmbH * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package com.owncloud.android.datamodel import com.owncloud.android.AbstractIT import com.owncloud.android.lib.resources.status.CapabilityBooleanType import com.owncloud.android.lib.resources.status.OCCapability import org.junit.Assert.assertEquals import org.junit.Test class OCCapabilityIT : AbstractIT() { @Test fun saveCapability() { val fileDataStorageManager = FileDataStorageManager(user, targetContext.contentResolver) val capability = OCCapability() capability.etag = "123" capability.userStatus = CapabilityBooleanType.TRUE capability.userStatusSupportsEmoji = CapabilityBooleanType.TRUE fileDataStorageManager.saveCapabilities(capability) val newCapability = fileDataStorageManager.getCapability(user.accountName) assertEquals(capability.etag, newCapability.etag) assertEquals(capability.userStatus, newCapability.userStatus) assertEquals(capability.userStatusSupportsEmoji, newCapability.userStatusSupportsEmoji) } }
gpl-2.0
32685a701de54147f0ecbc2f4970c6d2
36.77551
96
0.764452
4.69797
false
false
false
false
openHPI/android-app
app/src/main/java/de/xikolo/utils/extensions/ShareExtensions.kt
1
1371
package de.xikolo.utils.extensions import android.app.Activity import android.app.PendingIntent import android.content.Intent import android.os.Build import androidx.core.app.ShareCompat import de.xikolo.R import de.xikolo.config.Config import de.xikolo.models.dao.CourseDao import de.xikolo.receivers.ShareBroadcastReceiver import de.xikolo.utils.LanalyticsUtil fun <T : Activity> T.shareCourseLink(courseId: String) { val intent = ShareCompat.IntentBuilder.from(this) .setType("text/plain") .setText("${Config.HOST_URL}courses/${CourseDao.Unmanaged.find(courseId)?.slug}") .intent val chooserIntent = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP_MR1) { val receiverIntent = Intent(this, ShareBroadcastReceiver::class.java) receiverIntent.putExtra("course_id", courseId) val pendingIntent = PendingIntent.getBroadcast( this, 0, receiverIntent, PendingIntent.FLAG_UPDATE_CURRENT ) Intent.createChooser( intent, getString(R.string.action_share), pendingIntent.intentSender ) } else { LanalyticsUtil.trackShareCourseLink(courseId) Intent.createChooser( intent, getString(R.string.action_share) ) } startActivity(chooserIntent) }
bsd-3-clause
f76e9ec85b19c2d8c02f94e49b9cf61d
28.804348
89
0.677608
4.436893
false
true
false
false
REBOOTERS/AndroidAnimationExercise
app/src/main/java/home/smart/fly/animations/recyclerview/DataFactory.kt
1
1118
package home.smart.fly.animations.recyclerview import android.content.Context import com.google.gson.Gson import com.google.gson.reflect.TypeToken import home.smart.fly.animations.recyclerview.bean.StickBean import home.smart.fly.animations.utils.Tools /** * @author rookie * @since 07-23-2019 */ object DataFactory { fun initDefaultData(context: Context?): ArrayList<String> { val josn = Tools.readStrFromAssets("pics.json", context) val gson = Gson() return gson.fromJson(josn, object : TypeToken<ArrayList<String>>() {}.type) } fun initStringData(): ArrayList<String> { val datas = ArrayList<String>() for (i in 0..100) { datas.add("This is $i") } return datas } fun initStickData():ArrayList<StickBean> { val datas = ArrayList<StickBean>() for (i in 0..100) { val value = "item $i" val stickBean = StickBean(value,false) if (i % 6 == 0) { stickBean.isStick = true } datas.add(stickBean) } return datas } }
apache-2.0
62385f9ed8b558d642622069965a1345
25.642857
83
0.603757
3.909091
false
false
false
false
REBOOTERS/AndroidAnimationExercise
app/src/main/java/home/smart/fly/animations/recyclerview/fragments/BaseListFragment.kt
1
2168
package home.smart.fly.animations.recyclerview.fragments import android.content.Context import android.os.Bundle import android.util.Log import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.fragment.app.Fragment import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import home.smart.fly.animations.R /** * @author rookie * @since 07-23-2019 */ abstract class BaseListFragment<T> : Fragment() { var mContext: Context? = null protected lateinit var datas: ArrayList<T> protected lateinit var adapter: RecyclerView.Adapter<RecyclerView.ViewHolder> private lateinit var mRecyclerView: RecyclerView override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) mContext = context datas = loadDatas() } abstract fun loadDatas(): ArrayList<T> abstract fun getLayoutResId(): Int abstract fun getCustomAdapter(): RecyclerView.Adapter<*> open fun getCustomLayoutManager(): RecyclerView.LayoutManager { return LinearLayoutManager(mContext) } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { return inflater.inflate(getLayoutResId(), container, false) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) mRecyclerView = view.findViewById(R.id.recyclerview) mRecyclerView.layoutManager = getCustomLayoutManager() mRecyclerView.adapter = getCustomAdapter() mRecyclerView.addRecyclerListener { holder -> Log.e("recyclerview", "itemViewType " + holder.itemViewType.toString()) Log.e("recyclerview", "itemId " + holder.itemId.toString()) Log.e("recyclerview", "adapterPosition " + holder.adapterPosition.toString()) Log.e("recyclerview", "oldPosition " + holder.oldPosition.toString()) } } fun getRecyclerView(): RecyclerView { return mRecyclerView } }
apache-2.0
813bb6867c8bf624fef8a844c899ec0d
32.369231
89
0.708948
5.113208
false
false
false
false
synyx/calenope
modules/core.google/src/main/kotlin/de/synyx/calenope/core/google/service/GoogleQuery.kt
1
3160
package de.synyx.calenope.core.google.service import com.google.api.client.util.DateTime import com.google.api.services.calendar.Calendar.Events.List import com.google.api.services.calendar.model.Event.Creator import com.google.api.services.calendar.model.EventAttendee import com.google.api.services.calendar.model.EventDateTime import com.google.api.services.calendar.model.Events import de.synyx.calenope.core.api.model.Attendee import de.synyx.calenope.core.api.model.Event import de.synyx.calenope.core.api.service.Query import de.synyx.calenope.core.std.model.MemoryAttendee import de.synyx.calenope.core.std.model.MemoryEvent import org.joda.time.DateTimeZone import org.joda.time.Instant import java.util.* import java.util.concurrent.TimeUnit /** * @author clausen - [email protected] */ class GoogleQuery(private val events: () -> List) : Query { override fun between (start: Instant, end: Instant, zone : TimeZone): Collection<Event> { return process ( events ().setTimeMin (datetime (start, zone)) .setTimeMax (datetime (end, zone)) .setSingleEvents (true) .execute () ) } override fun starting (start: Instant, zone : TimeZone): Collection<Event> { return process ( events ().setTimeMin (datetime (start, zone)) .setSingleEvents (true) .execute () ) } private fun process (events : Events) : Collection<Event> = events.items.filterNot { it.start == null }.map { convert (it) } private fun convert (e: com.google.api.services.calendar.model.Event): Event { return MemoryEvent ( id = e.id, title = e.summary ?: "", location = e.location, description = e.description, start = instant (e.start), end = instant (e.end), creator = attendee (e.creator), attendees = attendees (e.attendees) ) } private fun datetime (instant: Instant, zone : TimeZone): DateTime { return DateTime (instant.toDate (), zone) } private fun instant (time: EventDateTime): Instant { val start: DateTime = time.dateTime ?: time.date val value = start.value val offset = TimeUnit.MINUTES.toMillis (start.timeZoneShift.toLong ()).toInt () return org.joda.time.DateTime (value, DateTimeZone.forOffsetMillis (offset)).toInstant () } private fun attendees (attendees : Collection<EventAttendee>) : Collection<Attendee> { return attendees.map { attendee (it) } } private fun attendee (attendee : Any) = when (attendee) { is EventAttendee -> MemoryAttendee (name = attendee.displayName ?: attendee.email, email = attendee.email) is Creator -> MemoryAttendee (name = attendee.displayName ?: attendee.email, email = attendee.email) else -> throw UnsupportedOperationException ("$attendee unsupported") } }
apache-2.0
455d286c356c96a9c5c88b436a98d4bc
38.5
128
0.623418
4.31694
false
false
false
false
Jire/Abendigo
src/main/kotlin/org/abendigo/plugin/csgo/FakeLagPlugin.kt
1
686
package org.abendigo.plugin.csgo import org.abendigo.DEBUG import org.abendigo.csgo.engineDLL import org.abendigo.csgo.offsets.m_bSendPacket import org.abendigo.plugin.sleep import org.abendigo.util.random import org.jire.arrowhead.get object FakeLagPlugin : InGamePlugin("Fake Lag", duration = 1) { private const val MIN_DURATION = 80 private const val MAX_DURATION = 310 override fun cycle() { try { val sendPacket: Boolean = engineDLL[m_bSendPacket] engineDLL[m_bSendPacket] = !sendPacket sleep(random(MIN_DURATION, MAX_DURATION)) } catch (t: Throwable) { if (DEBUG) t.printStackTrace() } } override fun disable() { engineDLL[m_bSendPacket] = true } }
gpl-3.0
71d55f06298c23a0c455926200bf7764
22.689655
63
0.741983
3.362745
false
false
false
false
edvin/tornadofx
src/test/kotlin/tornadofx/tests/MultipleLifecycleAsyncAppTest.kt
2
1465
package tornadofx.tests import org.junit.After import org.junit.Before import org.junit.Test import org.junit.runner.RunWith import org.junit.runners.Parameterized import org.testfx.api.FxRobot import org.testfx.api.FxToolkit import tornadofx.* import tornadofx.testapps.MultipleLifecycleAsyncView import java.util.concurrent.CountDownLatch import kotlin.test.assertEquals //@RunWith(Parameterized::class) class MultipleLifecycleAsyncAppTest(val round: Int) { // // companion object { // @JvmStatic // @Parameterized.Parameters // fun data(): Collection<Array<Int>> { // return listOf(arrayOf(1), arrayOf(2)) // } // } // // lateinit var robot: FxRobot // lateinit var app: App // // @Before // fun before() { // FxToolkit.registerPrimaryStage() // app = App(MultipleLifecycleAsyncView::class) // FxToolkit.setupApplication { app } // robot = FxRobot() // // println("round: $round") // } // // @After // fun after() { // FxToolkit.cleanupStages() // FxToolkit.cleanupApplication(app) // } // // @Test(timeout = 20000) // fun itShouldSurviveRunAsyncMultipleTimes() { // val latch = CountDownLatch(2) // val view: MultipleLifecycleAsyncView = find() // view.counterProperty.onChange { latch.countDown() } // // robot.clickOn(".button") // // latch.await() // assertEquals(2, view.counter) // } }
apache-2.0
d7eb9eb35d52939fbf339b99166dacf8
25.178571
61
0.643003
3.680905
false
true
false
false
openstreetview/android
app/src/main/java/com/telenav/osv/data/collector/obddata/ClientDataTransmissionBle.kt
1
9898
package com.telenav.osv.data.collector.obddata import android.annotation.TargetApi import android.bluetooth.BluetoothGatt import android.bluetooth.BluetoothGattCharacteristic import android.content.Context import android.os.Build import com.telenav.osv.data.collector.datatype.util.LibraryUtil import com.telenav.osv.data.collector.obddata.connection.BleObdDataListener import com.telenav.osv.data.collector.obddata.connection.OBDCommunication import com.telenav.osv.data.collector.obddata.manager.OBDServiceManager import com.telenav.osv.data.collector.obddata.manager.ObdDataListener import com.telenav.osv.data.collector.obddata.obdinitializer.ATConstants import com.telenav.osv.data.collector.obddata.obdinitializer.AbstractOBDInitializer import com.telenav.osv.data.collector.obddata.obdinitializer.BleObdInitializer import com.telenav.osv.utils.StringUtils import timber.log.Timber /** * Created by adrianbostan on 11/10/16. */ @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2) class ClientDataTransmissionBle(obdDataListener: ObdDataListener) : AbstractClientDataTransmission(obdDataListener), BleObdDataListener { /** * ble connection thread instance */ private val bleCommunicationThread: ObdCollectionThread? /** * result from the written characteristic */ private var characteristicResult = "" /** * result from the written characteristic and used in entire module */ private var characteristicResultBle: String? = null /** * Sensors availabilities */ private var availabilities: Map<String, Boolean>? = null private var atThread: Thread? = null private var isInitializing = false override fun onCharacteristicChangedBle(gatt: BluetoothGatt?, characteristic: BluetoothGattCharacteristic) { formCharacteristicResult(characteristic) Timber.tag(TAG).d("Ble status: onCharacteristicChangedBle: %s", characteristic) } override fun onConnectionStateChanged(context: Context?, @LibraryUtil.HardwareSource source: String?, @LibraryUtil.ObdStatusCode statusCode: Int) { if (source == LibraryUtil.OBD_BLE_SOURCE) { Timber.tag(TAG).d("Ble status: onBleErrorOccurred: %s", statusCode) } } override fun onConnectionStopped(@LibraryUtil.HardwareSource source: String?) { if (source == LibraryUtil.OBD_BLE_SOURCE) { Timber.tag(TAG).d("Ble status: onBleConnectionStopped") OBDServiceManager.instance.unbindService() stopSendingSensorCommands() resetBleFields() //clear obd listeners obdDataListener.onConnectionStopped(LibraryUtil.OBD_BLE_SOURCE) } } private fun resetBleFields() { characteristicResult = "" characteristicResultBle = "" } override fun onDeviceConnected(context: Context?, source: String?) { throw UnsupportedOperationException("The onDeviceConnected method should not be called from ClientDataTransmissionBle") } /** * initialize and start the communication thread */ override fun startSendingSensorCommands() { receiveObdVersion() startToWriteCommands() } /** * stop the communication thread */ override fun stopSendingSensorCommands() { Timber.tag(TAG).d("OVI: threads state: isInitializing=" + isInitializing + ", isRetrievingVin=" + isRetrievingVin + ", thread id=" + Thread.currentThread().id) if (isInitializing && atThread != null) { atThread!!.interrupt() } if (isRetrievingVin && vinThread != null) { vinThread!!.interrupt() } if (bleCommunicationThread != null) { bleCommunicationThread.setWasCollectionStopped(true) bleCommunicationThread.cancel() } } override fun initializationFailed() { ObdHelper.notifyInitializationFailed(obdDataListener) } override fun onCollectionThreadRestartRequired() { bleCommunicationThread?.onFrequencyChanged() } override fun closeCollectionThread() { bleCommunicationThread!!.cancel() } override fun writeCommand(sendingCommand: String) { sendCommandToBle(sendingCommand) delay(getDelayForCommand(sendingCommand)) } /** * Formats the response that comes on characteristic * @param characteristic - Characteristic that is received */ private fun formCharacteristicResult(characteristic: BluetoothGattCharacteristic) { characteristicResult += characteristic.getStringValue(0) Timber.tag(TAG).d("onCharacteristicChangedBle characteristicResult: %s", characteristicResult) if (characteristicResult.trim { it <= ' ' }.endsWith(">")) { Timber.tag(TAG).d("onCharacteristicChangedBle characteristicResult >: %s", characteristicResult) characteristicResult = formatCharacteristicResult(characteristicResult) characteristicResultForAbstract = characteristicResult characteristicResultBle = characteristicResult //notify listeners of the baseObject read val baseObject = ObdHelper.convertResult(characteristicResult) if (baseObject != null) { obdDataListener.onSensorChanged(baseObject) } characteristicResult = StringUtils.EMPTY_STRING } } /** * Remove unused strings from the characteristic * @param characteristicResult - Characteristic that is received * @return - formatted characteristic */ fun formatCharacteristicResult(characteristicResult: String): String { var result = characteristicResult if (result.contains(">")) { result = result.replace(">".toRegex(), "") } if (result.contains("\r")) { result = result.replace("\r".toRegex(), "") } if (result.contains(" ")) { result = result.replace(" ".toRegex(), "") } return result } /** * Sends a command to ble obd * @param sendingCommand Command to be sent */ private fun sendCommandToBle(sendingCommand: String): Boolean { Timber.tag(TAG).d("Ble status: sendCommandToBle %s", sendingCommand) val isWritten: Boolean val gatt: BluetoothGatt? = OBDCommunication.instance.bluetoothGatt isWritten = if (gatt != null) { Timber.tag(TAG).d("Ble status: sendCommandToBle gatt != null") val bluetoothGattService = gatt.getService(OBDCommunication.serviceUUID) if (bluetoothGattService == null) { obdDataListener.onConnectionStateChanged(LibraryUtil.OBD_BLE_SOURCE, LibraryUtil.BLUETOOTH_ADAPTER_OFF) Timber.tag(TAG).d("Ble stop start") false } else { val writeChar = bluetoothGattService.getCharacteristic(OBDCommunication.characteristicUUID) if (writeChar == null) { obdDataListener.onConnectionStateChanged(LibraryUtil.OBD_BLE_SOURCE, LibraryUtil.BLUETOOTH_ADAPTER_OFF) Timber.tag(TAG).d("Ble stop start") false } else { writeChar.setValue(sendingCommand + '\r') gatt.writeCharacteristic(writeChar) } } } else { false } return isWritten } /** * Starts the thread that sends command */ private fun startToWriteCommands() { //the vehicle id is only collected once, before the other sensors delay(500) collectVehicleId() if (availabilities != null) { bleCommunicationThread?.setAvailabilities(availabilities!!) bleCommunicationThread?.start() } } /** * Takes the current version of the interface and add the availability of the sensors */ private fun receiveObdVersion() { //this thread will run the AT Z command, and will receive the OBD device version val initial = System.currentTimeMillis() isInitializing = true atThread = Thread { val obdVersion: String = getObdDeviceVersion(ATConstants.CONNECTION_BLE) val abstractOBDInitializer: AbstractOBDInitializer = BleObdInitializer(obdVersion, this@ClientDataTransmissionBle, obdDataListener) initializeObd(obdVersion, abstractOBDInitializer) } atThread!!.start() isInitializing = false try { atThread!!.join() } catch (e: InterruptedException) { Timber.tag(TAG).e(e, "Exception while receiving OBD version %s", e.message) Thread.currentThread().interrupt() } atThread!!.interrupt() //find out which sensors are available //availabilities = AvailabilityRetriever.retrieveAvailabilityMap(new SensorAvailabilityBle(this)); availabilities = defaultMap if (availabilities == null) { obdDataListener.onConnectionStopped(LibraryUtil.OBD_BLE_SOURCE) return } //notify unavailable sensors for ((key, value) in availabilities!!) { if (!value) { ObdHelper.notifySensorNotAvailable(key, obdDataListener) } } Timber.tag(TAG).d("Init time %s", System.currentTimeMillis() - initial) } /** * Returns the characteristic result * @return Resulted characteristic */ fun getCharacteristicResult(): String? { return characteristicResultBle } companion object { /** * Tag used for logging */ private val TAG = ClientDataTransmissionBle::class.java.simpleName } /** * Private constructor */ init { bleCommunicationThread = ObdCollectionThread() } }
lgpl-3.0
4a6be95b848c45704d06cc3b2c658d69
36.354717
167
0.65983
5.184914
false
false
false
false