repo_name
stringlengths
7
79
path
stringlengths
8
206
copies
stringclasses
36 values
size
stringlengths
2
6
content
stringlengths
55
523k
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
7.18
99.5
line_max
int64
16
979
alpha_frac
float64
0.3
0.87
ratio
float64
2.01
8.07
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
inorichi/mangafeed
app/src/main/java/eu/kanade/tachiyomi/widget/preference/LoginDialogPreference.kt
2
2257
package eu.kanade.tachiyomi.widget.preference import android.app.Dialog import android.os.Bundle import android.view.LayoutInflater import android.view.View import androidx.annotation.StringRes import com.bluelinelabs.conductor.ControllerChangeHandler import com.bluelinelabs.conductor.ControllerChangeType import com.dd.processbutton.iml.ActionProcessButton import com.google.android.material.dialog.MaterialAlertDialogBuilder import eu.kanade.tachiyomi.R import eu.kanade.tachiyomi.data.preference.PreferencesHelper import eu.kanade.tachiyomi.databinding.PrefAccountLoginBinding import eu.kanade.tachiyomi.ui.base.controller.DialogController import uy.kohesive.injekt.injectLazy abstract class LoginDialogPreference( @StringRes private val usernameLabelRes: Int? = null, bundle: Bundle? = null ) : DialogController(bundle) { var binding: PrefAccountLoginBinding? = null private set val preferences: PreferencesHelper by injectLazy() override fun onCreateDialog(savedViewState: Bundle?): Dialog { binding = PrefAccountLoginBinding.inflate(LayoutInflater.from(activity!!)) onViewCreated(binding!!.root) val titleName = activity!!.getString(getTitleName()) return MaterialAlertDialogBuilder(activity!!) .setTitle(activity!!.getString(R.string.login_title, titleName)) .setView(binding!!.root) .setNegativeButton(android.R.string.cancel, null) .create() } fun onViewCreated(view: View) { if (usernameLabelRes != null) { binding!!.usernameLabel.hint = view.context.getString(usernameLabelRes) } binding!!.login.setMode(ActionProcessButton.Mode.ENDLESS) binding!!.login.setOnClickListener { checkLogin() } setCredentialsOnView(view) } override fun onChangeStarted(handler: ControllerChangeHandler, type: ControllerChangeType) { super.onChangeStarted(handler, type) if (!type.isEnter) { onDialogClosed() } } open fun onDialogClosed() { binding = null } @StringRes protected abstract fun getTitleName(): Int protected abstract fun checkLogin() protected abstract fun setCredentialsOnView(view: View) }
apache-2.0
856aff0fc3dc39f1630243eaa23c337c
32.686567
96
0.731502
4.843348
false
false
false
false
Novatec-Consulting-GmbH/testit-testutils
logrecorder/logrecorder-assertions/src/main/kotlin/info/novatec/testit/logrecorder/assertion/blocks/Contains.kt
1
2847
/* * Copyright 2017-2021 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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 info.novatec.testit.logrecorder.assertion.blocks import info.novatec.testit.logrecorder.api.LogEntry import info.novatec.testit.logrecorder.assertion.LogRecordAssertion /** * Custom assertion block for the [LogRecordAssertion] DSL. * * This assertion block requires each specified expected message to be found, * but allows other messages between those expectations and does not care about * the order the messages are in. * * **Example:** * ``` * assertThat(log) { * contains { * info("hello world") * // there might be other between these two * debug(startsWith("foo") * // the debug message might even come before the info * } * } * ``` * * @since 1.5.0 */ internal class Contains : AbstractMessagesAssertionBlock() { override fun check(entries: List<LogEntry>, expectations: List<ExpectedLogEntry>): List<MatchingResult> { val remainingEntries = entries.toMutableList() return expectations .map { expectation -> val matchedIndex = remainingEntries.indexOfFirst { matches(expectation, it) } if (matchedIndex != -1) { val entry = remainingEntries.removeAt(matchedIndex) ContainsMatchingResult(entry, expectation) } else { ContainsMatchingResult(null, expectation) } } } private fun matches(expected: ExpectedLogEntry, actual: LogEntry): Boolean { val levelMatches = expected.logLevelMatcher.matches(actual.level) val messageMatches = expected.messageMatchers.all { it.matches(actual.message) } return levelMatches && messageMatches } private class ContainsMatchingResult( private val actual: LogEntry?, private val expected: ExpectedLogEntry ) : MatchingResult { override val matches: Boolean get() = actual != null override fun describe() = if (actual != null) { """[${'\u2713'}] ${actual.level} | ${actual.message}""" } else { """[${'\u2717'}] did not find entry matching: ${expected.logLevelMatcher} | ${expected.messageMatchers}""" } } }
apache-2.0
c85fb5037cc98896f288358d14b588a3
34.5875
118
0.653671
4.606796
false
false
false
false
FountainMC/FountainAPI
src/main/kotlin/org/fountainmc/api/Fountain.kt
1
1341
package org.fountainmc.api /** * The singleton [Server] implementation, * which delegates all calls to [Fountain.server]. */ @Suppress("DEPRECATION") // We're the one actually doing the delegation object Fountain: Server by Fountain.server { @Volatile private var _server: Server? = null @Deprecated( message = "Server should be accessed through the 'Fountain' singleton", replaceWith = ReplaceWith("Fountain", "org.fountainmc.api.Fountain"), level = DeprecationLevel.WARNING ) val server: Server get() = checkNotNull(_server) { "No server implementation currently present!" } /** * Set the specified server implementation as the delegate for this singleton. * * @throws IllegalStateException if the fountain implementation has already been set */ fun setImplementation(implementation: Server) { synchronized(this) { val previousServer = this._server if (previousServer != null) { throw IllegalStateException( "Can't set server implementation to ${implementation.javaClass.typeName}" + " since it's already set to ${previousServer.javaClass.typeName}" ) } _server = implementation } } }
mit
e1c16fbfb4660bf6e77b2eaa3effde01
35.243243
99
0.62267
5.022472
false
false
false
false
Tickaroo/tikxml
processor/src/test/java/com/tickaroo/tikxml/processor/xml/XmlElementTest.kt
1
9266
/* * Copyright (C) 2015 Hannes Dorfmann * Copyright (C) 2015 Tickaroo, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.tickaroo.tikxml.processor.xml import com.tickaroo.tikxml.annotation.Element import com.tickaroo.tikxml.annotation.Path import com.tickaroo.tikxml.processor.expectException import com.tickaroo.tikxml.processor.field.AttributeField import com.tickaroo.tikxml.processor.field.ElementField import com.tickaroo.tikxml.processor.field.PropertyField import com.tickaroo.tikxml.processor.mock.MockVariableElement import com.tickaroo.tikxml.processor.mock.MockXmlElement import org.junit.Test import kotlin.test.assertEquals import kotlin.test.assertTrue /** * * @author Hannes Dorfmann */ class XmlElementTest { @Test fun addAttribute() { val xmlElement = MockXmlElement() val attribute1 = AttributeField(MockVariableElement("foo"), "foo") val attribute2 = AttributeField(MockVariableElement("other"), "other") val path = emptyList<String>() xmlElement.addAttribute(attribute1, path) assertEquals(xmlElement.attributes["foo"], attribute1) xmlElement.addAttribute(attribute2, path) assertEquals(xmlElement.attributes["other"], attribute2) } @Test fun addAttributeInConflict() { val xmlElement = MockXmlElement() val attribute1 = AttributeField(MockVariableElement("foo"), "foo") val attribute2 = AttributeField(MockVariableElement("other"), "foo") val path = emptyList<String>() xmlElement.addAttribute(attribute1, path) assertEquals(xmlElement.attributes["foo"], attribute1) expectException( "Conflict: field 'other' in class mocked.MockedClass has the same xml attribute name 'foo' as the field 'foo' in class mocked.MockedClass. You can specify another name via annotations.") { xmlElement.addAttribute(attribute2, path) } } @Test fun noAttributeConflictBecauseDifferentPath() { val xmlElement = MockXmlElement() val attribute1 = AttributeField(MockVariableElement("foo"), "foo") val attribute2 = AttributeField(MockVariableElement("other"), "foo") val path1 = emptyList<String>() val path2 = arrayListOf("some") xmlElement.addAttribute(attribute1, path1) assertEquals(xmlElement.attributes["foo"], attribute1) xmlElement.addAttribute(attribute2, path2) assertEquals(xmlElement.getXmlElementForPath(path2).attributes["foo"], attribute2) } @Test fun noConflictPropertyElements() { val rootElement = MockXmlElement() val childElement1 = PropertyField(MockVariableElement("foo"), "foo") val childElement2 = PropertyField(MockVariableElement("other"), "other") val path = emptyList<String>() rootElement.addChildElement(childElement1, path) assertEquals(childElement1, rootElement.childElements["foo"]) rootElement.addChildElement(childElement2, path) assertEquals(childElement2, rootElement.childElements["other"]) } @Test fun noConflictPropertyElementsDifferentPath() { val rootElement = MockXmlElement() val childElement1 = PropertyField(MockVariableElement("foo"), "foo") val childElement2 = PropertyField(MockVariableElement("foo"), "foo") val path1 = listOf("a") val path2 = listOf("a", "b") rootElement.addChildElement(childElement1, path1) assertEquals(childElement1, rootElement.getXmlElementForPath(path1).childElements["foo"]) rootElement.addChildElement(childElement2, path2) assertEquals(childElement2, rootElement.getXmlElementForPath(path2).childElements["foo"]) } @Test fun conflictingProperties() { val rootElement = MockXmlElement() val childElement1 = PropertyField(MockVariableElement("foo"), "foo") val childElement2 = PropertyField(MockVariableElement("foo"), "foo") val path1 = listOf("a") val path2 = listOf("a") rootElement.addChildElement(childElement1, path1) assertEquals(childElement1, rootElement.getXmlElementForPath(path1).childElements["foo"]) expectException( "Conflict: field 'foo' in class mocked.MockedClass is in conflict with field 'foo' in class mocked.MockedClass. Maybe both have the same xml name 'foo' (you can change that via annotations) or @${Path::class.simpleName} is causing this conflict.") { rootElement.addChildElement(childElement2, path2) } } @Test fun addingAttributeToExistingNode() { val rootElement = MockXmlElement() val attribute1 = AttributeField(MockVariableElement("attribute1"), "attribute1") val childElement1 = PropertyField(MockVariableElement("foo"), "foo") val path1 = listOf("a") rootElement.addAttribute(attribute1, path1) assertTrue(rootElement.getXmlElementForPath(path1) is PlaceholderXmlElement) assertEquals(rootElement.getXmlElementForPath(path1).attributes["attribute1"], attribute1) rootElement.addChildElement(childElement1, path1) assertTrue(rootElement.getXmlElementForPath(path1) is PlaceholderXmlElement) assertEquals(rootElement.getXmlElementForPath(path1.plus("foo")), childElement1) assertEquals(rootElement.getXmlElementForPath(path1).attributes["attribute1"], attribute1) // Add an attribute on existing PropertyField val attribute2 = AttributeField(MockVariableElement("attribute2"), "attribute2") val path2 = listOf("a", "foo") // Add child on childElement1 rootElement.addAttribute(attribute2, path2) assertEquals(rootElement.getXmlElementForPath(path2), childElement1) assertEquals(rootElement.getXmlElementForPath(path2).attributes["attribute2"], attribute2) assertEquals(childElement1.attributes["attribute2"], attribute2) } @Test fun mergePlaceholderFromAttributeWithPropertyNode() { val rootElement = MockXmlElement() val attribute = AttributeField(MockVariableElement("attribute1"), "attribute1") val childElement = PropertyField(MockVariableElement("foo"), "foo") val attributePath = listOf("foo") rootElement.addAttribute(attribute, attributePath) assertTrue(rootElement.getXmlElementForPath(attributePath) is PlaceholderXmlElement) rootElement.addChildElement(childElement, emptyList()) // Add foo node assertEquals(rootElement.getXmlElementForPath(attributePath), childElement) assertEquals(rootElement.getXmlElementForPath(attributePath).attributes["attribute1"], attribute) assertEquals(childElement.attributes["attribute1"], attribute) } @Test fun mergingPlaceholderFromAttributeWithElementFieldNotPossible() { val rootElement = MockXmlElement() val attribute = AttributeField(MockVariableElement("attribute1"), "attribute1") val childElement = ElementField(MockVariableElement("foo"), "foo") val attributePath = listOf("foo") rootElement.addAttribute(attribute, attributePath) assertTrue(rootElement.getXmlElementForPath(attributePath) is PlaceholderXmlElement) expectException( "Conflict: field 'foo' in class mocked.MockedClass is in conflict with mocked.MockedClass. Maybe both have the same xml name 'foo' (you can change that via annotations) or @${Path::class.simpleName} is causing this conflict.") { rootElement.addChildElement(childElement, emptyList()) // Add foo node } } @Test fun addingAttributeToElementFieldNotPossible() { val rootElement = MockXmlElement() val attribute = AttributeField(MockVariableElement("attribute1"), "attribute1") val childElement = ElementField(MockVariableElement("foo"), "foo") val attributePath = listOf("foo") rootElement.addChildElement(childElement, emptyList()) // Add foo node // Add attribute to foo node should fail expectException( "Element field 'foo' in class mocked.MockedClass can't have attributes that are accessed from outside of the TypeAdapter that is generated from @${Element::class.simpleName} annotated class! Therefore attribute field 'attribute1' in class mocked.MockedClass can't be added. Most likely the @${Path::class.simpleName} is in conflict with an @${Element::class.simpleName} annotation.") { rootElement.addAttribute(attribute, attributePath) } } @Test fun attributeInSamePath() { val rootElement = MockXmlElement() val attribute1 = AttributeField(MockVariableElement("attribute1"), "foo") val attribute2 = AttributeField(MockVariableElement("attribute2"), "foo") val path = listOf("a", "b") rootElement.addAttribute(attribute1, path) // Add attribute to foo node should fail expectException( "Conflict: field 'attribute2' in class mocked.MockedClass has the same xml attribute name 'foo' as the field 'attribute1' in class mocked.MockedClass. You can specify another name via annotations.") { rootElement.addAttribute(attribute2, path) } } }
apache-2.0
7c33cce84b7bcbd920fc4ec960367a05
39.112554
391
0.753507
4.566782
false
true
false
false
songful/PocketHub
app/src/main/java/com/github/pockethub/android/ui/item/news/TeamAddEventItem.kt
1
1523
package com.github.pockethub.android.ui.item.news import android.view.View import androidx.text.bold import androidx.text.buildSpannedString import com.github.pockethub.android.ui.view.OcticonTextView import com.github.pockethub.android.util.AvatarLoader import com.meisolsson.githubsdk.model.GitHubEvent import com.meisolsson.githubsdk.model.payload.TeamAddPayload import com.xwray.groupie.kotlinandroidextensions.ViewHolder import kotlinx.android.synthetic.main.news_item.* class TeamAddEventItem( avatarLoader: AvatarLoader, gitHubEvent: GitHubEvent ) : NewsItem(avatarLoader, gitHubEvent) { override fun bind(holder: ViewHolder, position: Int) { super.bind(holder, position) holder.tv_event_icon.text = OcticonTextView.ICON_ADD_MEMBER holder.tv_event.text = buildSpannedString { boldActor(this, gitHubEvent) append(" added ") val payload = gitHubEvent.payload() as TeamAddPayload? val repo = payload?.repository() val repoName = repo?.name() if (repoName != null) { bold { append(repoName) } } append(" to team") val team = payload?.team() val teamName = team?.name() if (teamName != null) { append(' ') bold { append(teamName) } } } holder.tv_event_details.visibility = View.GONE } }
apache-2.0
afcb7a2969bf45f7825f2babc3dab149
31.404255
67
0.616546
4.700617
false
false
false
false
dahlstrom-g/intellij-community
plugins/settings-repository/src/IcsManager.kt
7
9077
// 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.settingsRepository import com.intellij.configurationStore.StreamProvider import com.intellij.configurationStore.schemeManager.SchemeManagerFactoryBase import com.intellij.ide.AppLifecycleListener import com.intellij.ide.ApplicationLoadListener import com.intellij.openapi.Disposable import com.intellij.openapi.application.Application import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.application.ex.ApplicationManagerEx import com.intellij.openapi.components.RoamingType import com.intellij.openapi.components.stateStore import com.intellij.openapi.diagnostic.logger import com.intellij.openapi.diagnostic.runAndLogException import com.intellij.openapi.options.SchemeManagerFactory import com.intellij.openapi.progress.runBackgroundableTask import com.intellij.openapi.project.Project import com.intellij.openapi.project.ProjectManager import com.intellij.openapi.project.ProjectManagerListener import com.intellij.openapi.util.Disposer import com.intellij.openapi.util.io.FileUtil import com.intellij.util.SingleAlarm import kotlinx.coroutines.runBlocking import org.jetbrains.settingsRepository.git.GitRepositoryManager import org.jetbrains.settingsRepository.git.GitRepositoryService import org.jetbrains.settingsRepository.git.processChildren import java.io.InputStream import java.nio.file.Path internal val LOG = logger<IcsManager>() internal val icsManager by lazy(LazyThreadSafetyMode.NONE) { ApplicationLoadListener.EP_NAME.findExtensionOrFail(IcsApplicationLoadListener::class.java).icsManager!! } class IcsManager @JvmOverloads constructor(dir: Path, parentDisposable: Disposable, val schemeManagerFactory: Lazy<SchemeManagerFactoryBase> = lazy { (SchemeManagerFactory.getInstance() as SchemeManagerFactoryBase) }) : Disposable { val credentialsStore = lazy { IcsCredentialsStore() } val settingsFile: Path = dir.resolve("config.json") val settings: IcsSettings val repositoryManager: RepositoryManager = GitRepositoryManager(credentialsStore, dir.resolve("repository"), this) val readOnlySourcesManager = ReadOnlySourceManager(this, dir) init { Disposer.register(parentDisposable, this) settings = try { loadSettings(settingsFile) } catch (e: Exception) { LOG.error(e) IcsSettings() } } override fun dispose() { } val repositoryService: RepositoryService = GitRepositoryService() private val commitAlarm = SingleAlarm(Runnable { runBackgroundableTask(icsMessage("task.commit.title")) { indicator -> LOG.runAndLogException { runBlocking { repositoryManager.commit(indicator, fixStateIfCannotCommit = false) } } } }, settings.commitDelay) @Volatile private var autoCommitEnabled = true @Volatile var isRepositoryActive = false val isActive: Boolean get() = isRepositoryActive || readOnlySourcesManager.repositories.isNotEmpty() internal val autoSyncManager = AutoSyncManager(this) internal val syncManager = SyncManager(this, autoSyncManager) private fun scheduleCommit() { if (autoCommitEnabled && !ApplicationManager.getApplication()!!.isUnitTestMode) { commitAlarm.cancelAndRequest() } } suspend fun sync(syncType: SyncType, project: Project? = null, localRepositoryInitializer: (() -> Unit)? = null): Boolean { return syncManager.sync(syncType, project, localRepositoryInitializer) } private fun cancelAndDisableAutoCommit() { if (autoCommitEnabled) { autoCommitEnabled = false commitAlarm.cancel() } } suspend fun runInAutoCommitDisabledMode(task: suspend () -> Unit) { cancelAndDisableAutoCommit() try { task() } finally { autoCommitEnabled = true isRepositoryActive = repositoryManager.isRepositoryExists() } } fun setApplicationLevelStreamProvider() { val storageManager = ApplicationManager.getApplication().stateStore.storageManager // just to be sure storageManager.removeStreamProvider(IcsStreamProvider::class.java) storageManager.addStreamProvider(IcsStreamProvider(), first = true) } fun beforeApplicationLoaded(app: Application) { isRepositoryActive = repositoryManager.isRepositoryExists() app.stateStore.storageManager.addStreamProvider(IcsStreamProvider()) val messageBusConnection = app.messageBus.simpleConnect() messageBusConnection.subscribe(AppLifecycleListener.TOPIC, object : AppLifecycleListener { override fun appWillBeClosed(isRestart: Boolean) { autoSyncManager.autoSync(true) } }) messageBusConnection.subscribe(ProjectManager.TOPIC, object : ProjectManagerListener { override fun projectClosed(project: Project) { if (!ApplicationManagerEx.getApplicationEx().isExitInProgress) { autoSyncManager.autoSync() } } }) } inner class IcsStreamProvider : StreamProvider { override val enabled: Boolean get() = [email protected] override val isExclusive: Boolean get() = isRepositoryActive override fun isApplicable(fileSpec: String, roamingType: RoamingType): Boolean = isRepositoryActive override fun processChildren(path: String, roamingType: RoamingType, filter: (name: String) -> Boolean, processor: (name: String, input: InputStream, readOnly: Boolean) -> Boolean): Boolean { val fullPath = toRepositoryPath(path, roamingType) // first we must load read-only schemes - scheme could be overridden if bundled or read-only, so, such schemes must be loaded first for (repository in readOnlySourcesManager.repositories) { repository.processChildren(fullPath, filter) { name, input -> processor(name, input, true) } } if (!isRepositoryActive) { return false } repositoryManager.processChildren(fullPath, filter) { name, input -> processor(name, input, false) } return true } override fun write(fileSpec: String, content: ByteArray, size: Int, roamingType: RoamingType) { if (syncManager.writeAndDeleteProhibited) { throw IllegalStateException("Save is prohibited now") } if (doSave(fileSpec, content, size, roamingType)) { scheduleCommit() } } fun doSave(fileSpec: String, content: ByteArray, size: Int, roamingType: RoamingType): Boolean = repositoryManager.write(toRepositoryPath(fileSpec, roamingType), content, size) override fun read(fileSpec: String, roamingType: RoamingType, consumer: (InputStream?) -> Unit): Boolean { if (!isRepositoryActive) { return false } repositoryManager.read(toRepositoryPath(fileSpec, roamingType), consumer) return true } override fun delete(fileSpec: String, roamingType: RoamingType): Boolean { if (!isRepositoryActive) { return false } if (syncManager.writeAndDeleteProhibited) { throw IllegalStateException("Delete is prohibited now") } if (repositoryManager.delete(toRepositoryPath(fileSpec, roamingType))) { scheduleCommit() } return true } } } internal class IcsApplicationLoadListener : ApplicationLoadListener { var icsManager: IcsManager? = null private set override fun beforeApplicationLoaded(application: Application, configPath: Path) { if (application.isUnitTestMode) { return } val customPath = System.getProperty("ics.settingsRepository") val pluginSystemDir = if (customPath == null) configPath.resolve("settingsRepository") else Path.of(FileUtil.expandUserHome(customPath)) @Suppress("IncorrectParentDisposable") // this plugin is special and can't be dynamic anyway val icsManager = IcsManager(pluginSystemDir, application) this.icsManager = icsManager val repositoryManager = icsManager.repositoryManager if (repositoryManager.isRepositoryExists() && repositoryManager is GitRepositoryManager) { val osFolderName = getOsFolderName() val migrateSchemes = repositoryManager.renameDirectory(linkedMapOf( Pair("\$ROOT_CONFIG$", null), Pair("$osFolderName/\$ROOT_CONFIG$", osFolderName), Pair("\$APP_CONFIG$", null), Pair("$osFolderName/\$APP_CONFIG$", osFolderName) ), "Get rid of \$ROOT_CONFIG$ and \$APP_CONFIG") val migrateKeyMaps = repositoryManager.renameDirectory(linkedMapOf( Pair("$osFolderName/keymaps", "keymaps") ), "Move keymaps to root") val removeOtherXml = repositoryManager.delete("other.xml") if (migrateSchemes || migrateKeyMaps || removeOtherXml) { // schedule push to avoid merge conflicts application.invokeLater { icsManager.autoSyncManager.autoSync(force = true) } } } icsManager.beforeApplicationLoaded(application) } }
apache-2.0
92821bcc2e925fba0c5474f1dab66a30
35.604839
195
0.733172
5.139864
false
false
false
false
cdietze/klay
src/main/kotlin/klay/core/Touch.kt
1
1722
package klay.core /** * Defines and dispatches touch events. */ open class Touch { /** Contains information on a touch event. */ class Event constructor(flags: Int, time: Double, x: Float, y: Float, /** Whether this event represents a start, move, etc. */ val kind: Event.Kind, /** The id of the touch associated with this event. */ val id: Int, /** The pressure of the touch. */ val pressure: Float = -1f, // TODO(mdb): provide guidance as to range in the docs? 0 to 1? /** The size of the touch. */ val size: Float = -1f) : klay.core.Event.XY(flags, time, x, y) { /** Enumerates the different kinds of touch event. */ enum class Kind constructor( // NOTE: this enum order must match Pointer.Event.Kind exactly /** Whether this touch kind starts or ends an interaction. */ val isStart: Boolean, val isEnd: Boolean) { START(true, false), MOVE(false, false), END(false, true), CANCEL(false, true) } override fun name(): String { return "Touch" } override fun addFields(builder: StringBuilder) { super.addFields(builder) builder.append(", kind=").append(kind).append(", id=").append(id).append(", pressure=").append(pressure).append(", size=").append(size) } }// TODO(mdb): provide more details in the docs? size in pixels? // TODO: Implement pressure and size across all platforms that support touch. }
apache-2.0
c4c814be971f2f243cbdd9b44e230dc2
42.05
147
0.534262
4.692098
false
false
false
false
dahlstrom-g/intellij-community
platform/core-impl/src/com/intellij/ide/plugins/PluginDescriptorLoader.kt
1
30490
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. @file:Suppress("ReplaceNegatedIsEmptyWithIsNotEmpty", "ReplacePutWithAssignment") @file:JvmName("PluginDescriptorLoader") @file:ApiStatus.Internal package com.intellij.ide.plugins import com.intellij.diagnostic.ActivityCategory import com.intellij.diagnostic.StartUpMeasurer import com.intellij.openapi.application.PathManager import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.extensions.PluginId import com.intellij.openapi.util.BuildNumber import com.intellij.openapi.util.io.NioFiles import com.intellij.util.PlatformUtils import com.intellij.util.io.Decompressor import com.intellij.util.io.URLUtil import com.intellij.util.lang.UrlClassLoader import com.intellij.util.lang.ZipFilePool import com.intellij.util.xml.dom.createNonCoalescingXmlStreamReader import org.codehaus.stax2.XMLStreamReader2 import org.jetbrains.annotations.ApiStatus import org.jetbrains.annotations.ApiStatus.Internal import org.jetbrains.annotations.TestOnly import java.io.Closeable import java.io.File import java.io.IOException import java.io.InputStream import java.net.URL import java.nio.charset.StandardCharsets import java.nio.file.Files import java.nio.file.NoSuchFileException import java.nio.file.Path import java.nio.file.Paths import java.util.* import java.util.concurrent.* import java.util.function.BiConsumer import java.util.function.Supplier import java.util.zip.ZipFile import javax.xml.stream.XMLStreamException import kotlin.io.path.name private val LOG: Logger get() = PluginManagerCore.getLogger() internal fun createPluginLoadingResult(buildNumber: BuildNumber?): PluginLoadingResult { return PluginLoadingResult(brokenPluginVersions = PluginManagerCore.getBrokenPluginVersions(), productBuildNumber = { buildNumber ?: PluginManagerCore.getBuildNumber() }) } @TestOnly fun loadDescriptor(file: Path, parentContext: DescriptorListLoadingContext): IdeaPluginDescriptorImpl? { return loadDescriptorFromFileOrDir(file = file, context = parentContext, pathResolver = PluginXmlPathResolver.DEFAULT_PATH_RESOLVER, isBundled = false, isEssential = false, isDirectory = Files.isDirectory(file), useCoreClassLoader = false) } internal fun loadForCoreEnv(pluginRoot: Path, fileName: String): IdeaPluginDescriptorImpl? { val pathResolver = PluginXmlPathResolver.DEFAULT_PATH_RESOLVER val parentContext = DescriptorListLoadingContext(disabledPlugins = DisabledPluginsState.disabledPlugins()) if (Files.isDirectory(pluginRoot)) { return loadDescriptorFromDir(file = pluginRoot, descriptorRelativePath = "${PluginManagerCore.META_INF}$fileName", pluginPath = null, context = parentContext, isBundled = true, isEssential = true, pathResolver = pathResolver, useCoreClassLoader = false) } else { return loadDescriptorFromJar(file = pluginRoot, fileName = fileName, pathResolver = pathResolver, parentContext = parentContext, isBundled = true, isEssential = true, pluginPath = null, useCoreClassLoader = false) } } private fun loadDescriptorFromDir(file: Path, descriptorRelativePath: String, pluginPath: Path?, context: DescriptorListLoadingContext, isBundled: Boolean, isEssential: Boolean, useCoreClassLoader: Boolean, pathResolver: PathResolver): IdeaPluginDescriptorImpl? { try { val input = Files.readAllBytes(file.resolve(descriptorRelativePath)) val dataLoader = LocalFsDataLoader(file) val raw = readModuleDescriptor(input = input, readContext = context, pathResolver = pathResolver, dataLoader = dataLoader, includeBase = null, readInto = null, locationSource = file.toString()) val descriptor = IdeaPluginDescriptorImpl(raw = raw, path = pluginPath ?: file, isBundled = isBundled, id = null, moduleName = null, useCoreClassLoader = useCoreClassLoader) descriptor.readExternal(raw = raw, pathResolver = pathResolver, context = context, isSub = false, dataLoader = dataLoader) descriptor.jarFiles = Collections.singletonList(file) return descriptor } catch (e: NoSuchFileException) { return null } catch (e: Throwable) { if (isEssential) { throw e } LOG.warn("Cannot load ${file.resolve(descriptorRelativePath)}", e) return null } } private fun loadDescriptorFromJar(file: Path, fileName: String, pathResolver: PathResolver, parentContext: DescriptorListLoadingContext, isBundled: Boolean, isEssential: Boolean, useCoreClassLoader: Boolean, pluginPath: Path?): IdeaPluginDescriptorImpl? { var closeable: Closeable? = null try { val dataLoader: DataLoader val pool = ZipFilePool.POOL if (pool == null || parentContext.transient) { val zipFile = ZipFile(file.toFile(), StandardCharsets.UTF_8) closeable = zipFile dataLoader = JavaZipFileDataLoader(zipFile) } else { dataLoader = ImmutableZipFileDataLoader(pool.load(file), file, pool) } val raw = readModuleDescriptor(input = dataLoader.load("META-INF/$fileName") ?: return null, readContext = parentContext, pathResolver = pathResolver, dataLoader = dataLoader, includeBase = null, readInto = null, locationSource = file.toString()) val descriptor = IdeaPluginDescriptorImpl(raw = raw, path = pluginPath ?: file, isBundled = isBundled, id = null, moduleName = null, useCoreClassLoader = useCoreClassLoader) descriptor.readExternal(raw = raw, pathResolver = pathResolver, context = parentContext, isSub = false, dataLoader = dataLoader) descriptor.jarFiles = Collections.singletonList(descriptor.pluginPath) return descriptor } catch (e: Throwable) { if (isEssential) { throw if (e is XMLStreamException) RuntimeException("Cannot read $file", e) else e } parentContext.result.reportCannotLoad(file, e) } finally { closeable?.close() } return null } private class JavaZipFileDataLoader(private val file: ZipFile) : DataLoader { override val pool: ZipFilePool? get() = null override fun load(path: String): InputStream? { val entry = file.getEntry(if (path[0] == '/') path.substring(1) else path) ?: return null return file.getInputStream(entry) } override fun toString() = file.toString() } fun loadDescriptorFromFileOrDir( file: Path, context: DescriptorListLoadingContext, pathResolver: PathResolver, isBundled: Boolean, isEssential: Boolean, isDirectory: Boolean, useCoreClassLoader: Boolean, isUnitTestMode: Boolean = false ): IdeaPluginDescriptorImpl? { return when { isDirectory -> { loadFromPluginDir( file = file, parentContext = context, isBundled = isBundled, isEssential = isEssential, useCoreClassLoader = useCoreClassLoader, pathResolver = pathResolver, isUnitTestMode = isUnitTestMode, ) } file.fileName.toString().endsWith(".jar", ignoreCase = true) -> { loadDescriptorFromJar(file = file, fileName = PluginManagerCore.PLUGIN_XML, pathResolver = pathResolver, parentContext = context, isBundled = isBundled, isEssential = isEssential, pluginPath = null, useCoreClassLoader = useCoreClassLoader) } else -> null } } // [META-INF] [classes] lib/*.jar private fun loadFromPluginDir( file: Path, parentContext: DescriptorListLoadingContext, isBundled: Boolean, isEssential: Boolean, useCoreClassLoader: Boolean, pathResolver: PathResolver, isUnitTestMode: Boolean = false, ): IdeaPluginDescriptorImpl? { val pluginJarFiles = ArrayList(resolveArchives(file)) if (!pluginJarFiles.isEmpty()) { putMoreLikelyPluginJarsFirst(file, pluginJarFiles) val pluginPathResolver = PluginXmlPathResolver(pluginJarFiles) for (jarFile in pluginJarFiles) { loadDescriptorFromJar(file = jarFile, fileName = PluginManagerCore.PLUGIN_XML, pathResolver = pluginPathResolver, parentContext = parentContext, isBundled = isBundled, isEssential = isEssential, pluginPath = file, useCoreClassLoader = useCoreClassLoader)?.let { it.jarFiles = pluginJarFiles return it } } } // not found, ok, let's check classes (but only for unbundled plugins) if (!isBundled || isUnitTestMode) { val classesDir = file.resolve("classes") sequenceOf( classesDir, file, ).firstNotNullOfOrNull { loadDescriptorFromDir( file = it, descriptorRelativePath = PluginManagerCore.PLUGIN_XML_PATH, pluginPath = file, context = parentContext, isBundled = isBundled, isEssential = isEssential, pathResolver = pathResolver, useCoreClassLoader = useCoreClassLoader, ) }?.let { val classPath = ArrayList<Path>(pluginJarFiles.size + 1) classPath.add(classesDir) classPath.addAll(pluginJarFiles) it.jarFiles = classPath return it } } return null } private fun resolveArchives(path: Path): List<Path> { return try { Files.newDirectoryStream(path.resolve("lib")).use { stream -> stream.filter { val childPath = it.toString() childPath.endsWith(".jar", ignoreCase = true) || childPath.endsWith(".zip", ignoreCase = true) } } } catch (e: NoSuchFileException) { emptyList() } } /* * Sort the files heuristically to load the plugin jar containing plugin descriptors without extra ZipFile accesses. * File name preference: * a) last order for files with resources in name, like resources_en.jar * b) last order for files that have `-digit` suffix is the name e.g., completion-ranking.jar is before `gson-2.8.0.jar` or `junit-m5.jar` * c) jar with name close to plugin's directory name, e.g., kotlin-XXX.jar is before all-open-XXX.jar * d) shorter name, e.g., android.jar is before android-base-common.jar */ private fun putMoreLikelyPluginJarsFirst(pluginDir: Path, filesInLibUnderPluginDir: MutableList<Path>) { val pluginDirName = pluginDir.fileName.toString() // don't use kotlin sortWith to avoid loading of CollectionsKt Collections.sort(filesInLibUnderPluginDir, Comparator { o1: Path, o2: Path -> val o2Name = o2.fileName.toString() val o1Name = o1.fileName.toString() val o2StartsWithResources = o2Name.startsWith("resources") val o1StartsWithResources = o1Name.startsWith("resources") if (o2StartsWithResources != o1StartsWithResources) { return@Comparator if (o2StartsWithResources) -1 else 1 } val o2IsVersioned = fileNameIsLikeVersionedLibraryName(o2Name) val o1IsVersioned = fileNameIsLikeVersionedLibraryName(o1Name) if (o2IsVersioned != o1IsVersioned) { return@Comparator if (o2IsVersioned) -1 else 1 } val o2StartsWithNeededName = o2Name.startsWith(pluginDirName, ignoreCase = true) val o1StartsWithNeededName = o1Name.startsWith(pluginDirName, ignoreCase = true) if (o2StartsWithNeededName != o1StartsWithNeededName) { return@Comparator if (o2StartsWithNeededName) 1 else -1 } val o2EndsWithIdea = o2Name.endsWith("-idea.jar") val o1EndsWithIdea = o1Name.endsWith("-idea.jar") if (o2EndsWithIdea != o1EndsWithIdea) { return@Comparator if (o2EndsWithIdea) 1 else -1 } o1Name.length - o2Name.length }) } private fun fileNameIsLikeVersionedLibraryName(name: String): Boolean { val i = name.lastIndexOf('-') if (i == -1) { return false } if (i + 1 < name.length) { val c = name[i + 1] return Character.isDigit(c) || ((c == 'm' || c == 'M') && i + 2 < name.length && Character.isDigit(name[i + 2])) } return false } private fun loadDescriptorsFromProperty(result: PluginLoadingResult, context: DescriptorListLoadingContext) { val pathProperty = System.getProperty(PluginManagerCore.PROPERTY_PLUGIN_PATH) ?: return // gradle-intellij-plugin heavily depends on this property in order to have core class loader plugins during tests val useCoreClassLoaderForPluginsFromProperty = java.lang.Boolean.getBoolean("idea.use.core.classloader.for.plugin.path") val t = StringTokenizer(pathProperty, File.pathSeparatorChar + ",") while (t.hasMoreTokens()) { val file = Paths.get(t.nextToken()) loadDescriptorFromFileOrDir( file = file, context = context, pathResolver = PluginXmlPathResolver.DEFAULT_PATH_RESOLVER, isBundled = false, isEssential = false, isDirectory = Files.isDirectory(file), useCoreClassLoader = useCoreClassLoaderForPluginsFromProperty, )?.let { // plugins added via property shouldn't be overridden to avoid plugin root detection issues when running external plugin tests result.add(it, overrideUseIfCompatible = true) } } } /** * Think twice before use and get approve from core team. * * Returns enabled plugins only. */ @Internal @JvmOverloads fun loadDescriptors( isUnitTestMode: Boolean = PluginManagerCore.isUnitTestMode, isRunningFromSources: Boolean = PluginManagerCore.isRunningFromSources(), ): DescriptorListLoadingContext { val result = createPluginLoadingResult(null) val context = DescriptorListLoadingContext( isMissingSubDescriptorIgnored = true, isMissingIncludeIgnored = isUnitTestMode, checkOptionalConfigFileUniqueness = isUnitTestMode || isRunningFromSources, disabledPlugins = DisabledPluginsState.disabledPlugins(), result = result, ) context.use { loadDescriptorsFromDirs( context = context, customPluginDir = Paths.get(PathManager.getPluginsPath()), isUnitTestMode = isUnitTestMode, isRunningFromSources = isRunningFromSources, ) loadDescriptorsFromProperty(result, context) if (isUnitTestMode && result.enabledPluginsById.size <= 1) { // we're running in unit test mode, but the classpath doesn't contain any plugins; try to load bundled plugins anyway ForkJoinPool.commonPool().invoke(LoadDescriptorsFromDirAction(Paths.get(PathManager.getPreInstalledPluginsPath()), context, isBundled = true)) } } return context } private fun loadDescriptorsFromDirs( context: DescriptorListLoadingContext, customPluginDir: Path, bundledPluginDir: Path? = null, isUnitTestMode: Boolean = PluginManagerCore.isUnitTestMode, isRunningFromSources: Boolean = PluginManagerCore.isRunningFromSources(), ) { val classLoader = DescriptorListLoadingContext::class.java.classLoader val pool = ForkJoinPool.commonPool() var activity = StartUpMeasurer.startActivity("platform plugin collecting", ActivityCategory.DEFAULT) val platformPrefix = PlatformUtils.getPlatformPrefix() val isInDevServerMode = java.lang.Boolean.getBoolean("idea.use.dev.build.server") val pathResolver = ClassPathXmlPathResolver( classLoader = classLoader, isRunningFromSources = isRunningFromSources && !isInDevServerMode, ) val useCoreClassLoader = pathResolver.isRunningFromSources || platformPrefix.startsWith("CodeServer") || java.lang.Boolean.getBoolean("idea.force.use.core.classloader") // should be the only plugin in lib (only for Ultimate and WebStorm for now) if ((platformPrefix == PlatformUtils.IDEA_PREFIX || platformPrefix == PlatformUtils.WEB_PREFIX) && (isInDevServerMode || (!isUnitTestMode && !isRunningFromSources))) { loadCoreProductPlugin(getResourceReader(PluginManagerCore.PLUGIN_XML_PATH, classLoader)!!, context = context, pathResolver = pathResolver, useCoreClassLoader = useCoreClassLoader) } else { val fileName = "${platformPrefix}Plugin.xml" getResourceReader("${PluginManagerCore.META_INF}$fileName", classLoader)?.let { loadCoreProductPlugin(it, context, pathResolver, useCoreClassLoader) } val urlToFilename = collectPluginFilesInClassPath(classLoader) if (!urlToFilename.isEmpty()) { activity = activity.endAndStart("plugin from classpath loading") pool.invoke(LoadDescriptorsFromClassPathAction(urlToFilename = urlToFilename, context = context, pathResolver = pathResolver, useCoreClassLoader = useCoreClassLoader)) } } activity = activity.endAndStart("plugin from user dir loading") pool.invoke(LoadDescriptorsFromDirAction(customPluginDir, context, isBundled = false)) val bundledPluginDirOrDefault = bundledPluginDir ?: if (isUnitTestMode) { null } else if (isInDevServerMode) { Paths.get(PathManager.getHomePath(), "out/dev-run", platformPrefix, "plugins") } else { Paths.get(PathManager.getPreInstalledPluginsPath()) } if (bundledPluginDirOrDefault != null) { activity = activity.endAndStart("plugin from bundled dir loading") pool.invoke(LoadDescriptorsFromDirAction(bundledPluginDirOrDefault, context, isBundled = true)) } activity.end() } private fun getResourceReader(path: String, classLoader: ClassLoader): XMLStreamReader2? { if (classLoader is UrlClassLoader) { return createNonCoalescingXmlStreamReader(classLoader.getResourceAsBytes(path, false) ?: return null, path) } else { return createNonCoalescingXmlStreamReader(classLoader.getResourceAsStream(path) ?: return null, path) } } private fun loadCoreProductPlugin(reader: XMLStreamReader2, context: DescriptorListLoadingContext, pathResolver: ClassPathXmlPathResolver, useCoreClassLoader: Boolean) { val dataLoader = object : DataLoader { override val pool: ZipFilePool get() = throw IllegalStateException("must be not called") override val emptyDescriptorIfCannotResolve: Boolean get() = true override fun load(path: String) = throw IllegalStateException("must be not called") override fun toString() = "product classpath" } val raw = readModuleDescriptor(reader, readContext = context, pathResolver = pathResolver, dataLoader = dataLoader, includeBase = null, readInto = null) val descriptor = IdeaPluginDescriptorImpl(raw = raw, path = Paths.get(PathManager.getLibPath()), isBundled = true, id = null, moduleName = null, useCoreClassLoader = useCoreClassLoader) descriptor.readExternal(raw = raw, pathResolver = pathResolver, context = context, isSub = false, dataLoader = dataLoader) context.result.add(descriptor, overrideUseIfCompatible = false) } private fun collectPluginFilesInClassPath(loader: ClassLoader): Map<URL, String> { val urlToFilename = LinkedHashMap<URL, String>() try { val enumeration = loader.getResources(PluginManagerCore.PLUGIN_XML_PATH) while (enumeration.hasMoreElements()) { urlToFilename.put(enumeration.nextElement(), PluginManagerCore.PLUGIN_XML) } } catch (e: IOException) { LOG.warn(e) } return urlToFilename } @Throws(IOException::class) fun loadDescriptorFromArtifact(file: Path, buildNumber: BuildNumber?): IdeaPluginDescriptorImpl? { val context = DescriptorListLoadingContext(isMissingSubDescriptorIgnored = true, disabledPlugins = DisabledPluginsState.disabledPlugins(), result = createPluginLoadingResult(buildNumber), transient = true) val descriptor = loadDescriptorFromFileOrDir(file = file, context = context, pathResolver = PluginXmlPathResolver.DEFAULT_PATH_RESOLVER, isBundled = false, isEssential = false, isDirectory = false, useCoreClassLoader = false) if (descriptor != null || !file.toString().endsWith(".zip")) { return descriptor } val outputDir = Files.createTempDirectory("plugin")!! try { Decompressor.Zip(file).extract(outputDir) try { //org.jetbrains.intellij.build.io.ZipArchiveOutputStream may add __index__ entry to the plugin zip, we need to ignore it here val rootDir = NioFiles.list(outputDir).firstOrNull { it.name != "__index__" } if (rootDir != null) { return loadDescriptorFromFileOrDir(file = rootDir, context = context, pathResolver = PluginXmlPathResolver.DEFAULT_PATH_RESOLVER, isBundled = false, isEssential = false, isDirectory = true, useCoreClassLoader = false) } } catch (ignore: NoSuchFileException) { } } finally { NioFiles.deleteRecursively(outputDir) } return null } fun loadDescriptor(file: Path, disabledPlugins: Set<PluginId>, isBundled: Boolean, pathResolver: PathResolver): IdeaPluginDescriptorImpl? { DescriptorListLoadingContext(disabledPlugins = disabledPlugins).use { context -> return loadDescriptorFromFileOrDir(file = file, context = context, pathResolver = pathResolver, isBundled = isBundled, isEssential = false, isDirectory = Files.isDirectory(file), useCoreClassLoader = false) } } @Throws(ExecutionException::class, InterruptedException::class) fun loadDescriptors( customPluginDir: Path, bundledPluginDir: Path?, brokenPluginVersions: Map<PluginId, Set<String?>>?, productBuildNumber: BuildNumber?, ): PluginLoadingResult { val result = PluginLoadingResult( brokenPluginVersions = brokenPluginVersions ?: PluginManagerCore.getBrokenPluginVersions(), productBuildNumber = Supplier { productBuildNumber ?: PluginManagerCore.getBuildNumber() }, ) DescriptorListLoadingContext( disabledPlugins = emptySet(), result = result, isMissingIncludeIgnored = true, isMissingSubDescriptorIgnored = true, ).use { loadDescriptorsFromDirs(it, customPluginDir, bundledPluginDir) } return result } @TestOnly fun testLoadDescriptorsFromClassPath(loader: ClassLoader): List<IdeaPluginDescriptor> { val urlToFilename = collectPluginFilesInClassPath(loader) val buildNumber = BuildNumber.fromString("2042.42")!! val context = DescriptorListLoadingContext(disabledPlugins = Collections.emptySet(), result = PluginLoadingResult(brokenPluginVersions = emptyMap(), productBuildNumber = Supplier { buildNumber }, checkModuleDependencies = false)) LoadDescriptorsFromClassPathAction( urlToFilename = urlToFilename, context = context, pathResolver = ClassPathXmlPathResolver(loader, isRunningFromSources = false), useCoreClassLoader = true, ).compute() return context.result.enabledPlugins } private class LoadDescriptorsFromDirAction( private val dir: Path, private val context: DescriptorListLoadingContext, private val isBundled: Boolean, ) : RecursiveAction() { override fun compute() { try { val tasks: List<RecursiveTask<IdeaPluginDescriptorImpl?>> = Files.newDirectoryStream(dir).use { dirStream -> dirStream.map { file -> object : RecursiveTask<IdeaPluginDescriptorImpl?>() { override fun compute(): IdeaPluginDescriptorImpl? { return loadDescriptorFromFileOrDir( file = file, context = context, pathResolver = PluginXmlPathResolver.DEFAULT_PATH_RESOLVER, isBundled = isBundled, isDirectory = Files.isDirectory(file), isEssential = false, useCoreClassLoader = false, ) } } } } ForkJoinTask.invokeAll(tasks) for (task in tasks) { task.rawResult?.let { context.result.add(it, overrideUseIfCompatible = false) } } } catch (ignore: IOException) { } } } // urls here expected to be a file urls to plugin.xml private class LoadDescriptorsFromClassPathAction( private val urlToFilename: Map<URL, String>, private val context: DescriptorListLoadingContext, private val pathResolver: ClassPathXmlPathResolver, private val useCoreClassLoader: Boolean, ) : RecursiveAction() { public override fun compute() { val tasks = ArrayList<ForkJoinTask<IdeaPluginDescriptorImpl?>>(urlToFilename.size) urlToFilename.forEach(BiConsumer { url, filename -> tasks.add(object : RecursiveTask<IdeaPluginDescriptorImpl?>() { override fun compute(): IdeaPluginDescriptorImpl? { return try { loadDescriptorFromResource(resource = url, filename = filename) } catch (e: Throwable) { LOG.info("Cannot load $url", e) null } } }) }) val result = context.result ForkJoinTask.invokeAll(tasks) for (task in tasks) { task.rawResult?.let { result.add(it, overrideUseIfCompatible = false) } } } // filename - plugin.xml or ${platformPrefix}Plugin.xml private fun loadDescriptorFromResource(resource: URL, filename: String): IdeaPluginDescriptorImpl? { val file = Paths.get(UrlClassLoader.urlToFilePath(resource.path)) var closeable: Closeable? = null val dataLoader: DataLoader val basePath: Path try { val input: InputStream when { URLUtil.FILE_PROTOCOL == resource.protocol -> { basePath = file.parent.parent dataLoader = LocalFsDataLoader(basePath) input = Files.newInputStream(file) } URLUtil.JAR_PROTOCOL == resource.protocol -> { // support for unpacked plugins in classpath, e.g. .../community/build/dependencies/build/kotlin/Kotlin/lib/kotlin-plugin.jar basePath = file.parent?.takeIf { !it.endsWith("lib") }?.parent ?: file val pool = if (context.transient) null else ZipFilePool.POOL if (pool == null) { val zipFile = ZipFile(file.toFile(), StandardCharsets.UTF_8) closeable = zipFile dataLoader = JavaZipFileDataLoader(zipFile) } else { dataLoader = ImmutableZipFileDataLoader(pool.load(file), file, pool) } input = dataLoader.load("META-INF/$filename") ?: return null } else -> return null } val raw = readModuleDescriptor(input = input, readContext = context, pathResolver = pathResolver, dataLoader = dataLoader, includeBase = null, readInto = null, locationSource = file.toString()) // it is very important to not set useCoreClassLoader = true blindly // - product modules must uses own class loader if not running from sources val descriptor = IdeaPluginDescriptorImpl(raw = raw, path = basePath, isBundled = true, id = null, moduleName = null, useCoreClassLoader = useCoreClassLoader) descriptor.readExternal(raw = raw, pathResolver = pathResolver, context = context, isSub = false, dataLoader = dataLoader) // do not set jarFiles by intention - doesn't make sense return descriptor } finally { closeable?.close() } } }
apache-2.0
8015f731b036cc05589322ab9b62291d
39.872654
138
0.628501
5.366068
false
false
false
false
dkandalov/katas
kotlin/src/katas/kotlin/graph/Traversal3.kt
1
2481
package katas.kotlin.graph import katas.kotlin.graph.Graph.Node import nonstdlib.join import datsok.shouldEqual import org.junit.Test import java.util.* class Traversal3 { @Test fun `depth-first traversal`() { "[a]".toGraph().dft("a").join("-") shouldEqual "a" "[a-b]".toGraph().dft("a").join("-") shouldEqual "a-b" "[a-b, b-c]".toGraph().let { it.dft("a").join("-") shouldEqual "a-b-c" it.dft("b").join("-") shouldEqual "b-a-c" it.dft("c").join("-") shouldEqual "c-b-a" } // a──b1──c // └──b2──┘ "[a-b1, a-b2, b1-c, b2-c]".toGraph().let { it.dft("a").join("-") shouldEqual "a-b1-c-b2" it.dft("b1").join("-") shouldEqual "b1-a-b2-c" it.dft("b2").join("-") shouldEqual "b2-a-b1-c" it.dft("c").join("-") shouldEqual "c-b1-a-b2" } } @Test fun `breadth-first traversal`() { "[a]".toGraph().bft("a").join("-") shouldEqual "a" "[a-b]".toGraph().bft("a").join("-") shouldEqual "a-b" "[a-b, b-c]".toGraph().let { it.bft("a").join("-") shouldEqual "a-b-c" it.bft("b").join("-") shouldEqual "b-a-c" it.bft("c").join("-") shouldEqual "c-b-a" } // a──b1──c // └──b2──┘ "[a-b1, a-b2, b1-c, b2-c]".toGraph().let { it.bft("a").join("-") shouldEqual "a-b1-b2-c" it.bft("b1").join("-") shouldEqual "b1-a-c-b2" it.bft("b2").join("-") shouldEqual "b2-a-c-b1" it.bft("c").join("-") shouldEqual "c-b1-b2-a" } } private fun <T, U> Graph<T, U>.bft(value: T) = node(value).bft() private fun <T, U> Node<T, U>.bft(): List<T> { val result = LinkedHashSet<T>() val queue = LinkedList<Node<T, U>>() queue.add(this) while (queue.isNotEmpty()) { val node = queue.removeFirst() if (!result.contains(node.value)) { result.add(node.value) queue.addAll(node.neighbors()) } } return result.toList() } private fun <T, U> Graph<T, U>.dft(value: T) = node(value).dft() private fun <T, U> Node<T, U>.dft(visited: HashSet<Node<T, U>> = HashSet()): List<T> { val added = visited.add(this) return if (!added) emptyList() else listOf(this.value) + this.neighbors().flatMap { it.dft(visited) } } }
unlicense
67b6e7d6362a9aa345c18f72c59cdd46
32.438356
90
0.492421
3.00246
false
false
false
false
DreierF/MyTargets
shared/src/main/java/de/dreier/mytargets/shared/targets/drawable/TargetImpactAggregationDrawable.kt
1
2742
/* * Copyright (C) 2018 Florian Dreier * * This file is part of MyTargets. * * MyTargets is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 * as published by the Free Software Foundation. * * MyTargets 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. */ package de.dreier.mytargets.shared.targets.drawable import androidx.annotation.ColorInt import de.dreier.mytargets.shared.analysis.aggregation.EAggregationStrategy import de.dreier.mytargets.shared.analysis.aggregation.EAggregationStrategy.NONE import de.dreier.mytargets.shared.analysis.aggregation.IAggregationStrategy import de.dreier.mytargets.shared.models.Target import de.dreier.mytargets.shared.models.db.Shot import java.util.* class TargetImpactAggregationDrawable(target: Target) : TargetImpactDrawable(target), IAggregationStrategy.OnAggregationResult { private val faceAggregations = ArrayList<IAggregationStrategy>() private var resultsMissing = 0 init { setAggregationStrategy(NONE) } fun setAggregationStrategy(aggregation: EAggregationStrategy) { faceAggregations.clear() for (i in 0 until model.faceCount) { val strategy = aggregation.create() strategy.setOnAggregationResultListener(this) faceAggregations.add(strategy) } setColor(-0x55555556) recalculateAggregation() } private fun setColor(@ColorInt color: Int) { for (faceAggregation in faceAggregations) { faceAggregation.color = color } } override fun onResult() { resultsMissing-- if (resultsMissing == 0) { invalidateSelf() } } override fun onPostDraw(canvas: CanvasWrapper, faceIndex: Int) { super.onPostDraw(canvas, faceIndex) val result = faceAggregations[faceIndex].result result.onDraw(canvas) } override fun cleanup() { for (cluster in faceAggregations) { cluster.cleanup() } } override fun notifyArrowSetChanged() { super.notifyArrowSetChanged() recalculateAggregation() } private fun recalculateAggregation() { resultsMissing = model.faceCount for (faceIndex in 0 until model.faceCount) { val combinedList = ArrayList<Shot>() combinedList.addAll(transparentShots[faceIndex]) combinedList.addAll(shots[faceIndex]) faceAggregations[faceIndex].calculate(combinedList) } } }
gpl-2.0
e1fb6fbb55c9128929fddf7f7027b986
31.258824
128
0.696572
4.623946
false
false
false
false
kindraywind/Recorda
app/src/main/kotlin/com/octtoplus/proj/recorda/SecondActivity.kt
1
919
package com.octtoplus.proj.recorda import android.content.Intent import android.support.v7.app.AppCompatActivity import android.os.Bundle import android.view.View import android.widget.Button import android.widget.TextView import kotlinx.android.synthetic.main.activity_second.* class SecondActivity : AppCompatActivity() { internal var res = 0 override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_second) val intent = intent res = intent.getIntExtra("result", 0) initInstances() } private fun initInstances() { resLabel.text = "Res: " + res goto3Button.setOnClickListener { val intent = Intent(this@SecondActivity, ThirdActivity::class.java) intent.putExtra("result", 500) startActivity(intent) } } }
mit
2a6c6245cb1183cdbf32ff65db8cfc86
24.527778
56
0.675734
4.527094
false
false
false
false
chrislo27/Tickompiler
src/main/kotlin/rhmodding/tickompiler/cli/UpdatesCheckCommand.kt
2
2728
package rhmodding.tickompiler.cli import com.github.salomonbrys.kotson.fromJson import com.google.gson.Gson import picocli.CommandLine import rhmodding.tickompiler.Tickompiler import rhmodding.tickompiler.Tickompiler.GITHUB import rhmodding.tickompiler.util.Version import java.net.HttpURLConnection import java.net.URL import java.time.LocalDateTime import java.time.ZoneId import java.time.ZonedDateTime import java.time.format.DateTimeFormatter @CommandLine.Command(name = "updates", description = ["Check GitHub for an update to Tickompiler."], mixinStandardHelpOptions = true) class UpdatesCheckCommand : Runnable { override fun run() { println("Checking for updates...") val path = URL("https://api.github.com/repos/${GITHUB.replace("https://github.com/", "")}/releases/latest") val con = path.openConnection() as HttpURLConnection con.requestMethod = "GET" con.setRequestProperty("Accept", "application/vnd.github.v3+json") if (con.responseCode != 200) { println("Failed to get version info: got non-200 response code (${con.responseCode} ${con.responseMessage})") } else { val inputStream = con.inputStream val bufferedReader = inputStream.bufferedReader() val content = bufferedReader.readText() bufferedReader.close() con.disconnect() val release = Gson().fromJson<Release>(content) val releaseVersion: Version? = Version.fromStringOrNull(release.tag_name ?: "") if (releaseVersion == null) { println("Failed to get version info: release version is null? (${release.tag_name})") } else { if (releaseVersion > Tickompiler.VERSION) { println("A new ${if (release.prerelease) "PRE-RELEASE " else ""}version is available: $releaseVersion") val publishDate: LocalDateTime? = try { ZonedDateTime.parse(release.published_at, DateTimeFormatter.ISO_DATE_TIME)?.withZoneSameInstant(ZoneId.systemDefault())?.toLocalDateTime() } catch (ignored: Exception) { null } println("Published on ${publishDate?.format(DateTimeFormatter.ofPattern("dd MMMM yyyy, HH:mm:ss")) ?: release.published_at}") println(release.html_url) } else { println("No new version found.") } } } } @Suppress("PropertyName") class Release { var html_url: String? = "" var tag_name: String? = "" var name: String? = "" var published_at: String? = "" var prerelease: Boolean = false } }
mit
5a6506dedf9ca3481c086a08f2ee46ac
42.31746
162
0.632698
4.785965
false
false
false
false
outbrain/ob1k
ob1k-crud/src/main/java/com/outbrain/ob1k/crud/dao/AsyncDaoBridge.kt
1
958
package com.outbrain.ob1k.crud.dao import com.outbrain.ob1k.concurrent.ComposableFutures import java.util.concurrent.Callable import java.util.concurrent.ExecutorService class AsyncDaoBridge<T>(val dao: ICrudDao<T>, val executor: ExecutorService) : ICrudAsyncDao<T> { override fun list(pagination: IntRange, sort: Pair<String, String>, filter: T?) = toAsync { dao.list(pagination, sort, filter) } override fun list(ids: List<String>) = toAsync { dao.list(ids) } override fun read(id: String) = toAsync { dao.read(id) } override fun create(entity: T) = toAsync { dao.create(entity) } override fun update(id: String, entity: T) = toAsync { dao.update(id, entity) } override fun delete(id: String) = toAsync { dao.delete(id) } override fun resourceName() = dao.resourceName() override fun type() = dao.type() private fun <T> toAsync(func: () -> T) = ComposableFutures.submit(executor, Callable { func.invoke() }) }
apache-2.0
778aab157ed98a582080f3d7b29750a8
35.884615
132
0.707724
3.535055
false
false
false
false
deso88/TinyGit
src/main/kotlin/hamburg/remme/tinygit/gui/dialog/AboutDialog.kt
1
1420
package hamburg.remme.tinygit.gui.dialog import hamburg.remme.tinygit.I18N import hamburg.remme.tinygit.TinyGit import hamburg.remme.tinygit.asResource import hamburg.remme.tinygit.gui.builder.addClass import hamburg.remme.tinygit.gui.builder.grid import hamburg.remme.tinygit.gui.builder.label import hamburg.remme.tinygit.gui.builder.link import hamburg.remme.tinygit.gui.component.Icons import javafx.scene.control.Label import javafx.scene.image.Image import javafx.stage.Window private const val DEFAULT_STYLE_CLASS = "about-dialog" private const val AUTHOR_STYLE_CLASS = "${DEFAULT_STYLE_CLASS}__author" class AboutDialog(window: Window) : Dialog<Unit>(window, I18N["dialog.about.title"]) { init { +DialogButton(DialogButton.CLOSE) header = "TinyGit ${javaClass.`package`.implementationVersion ?: ""}" image = Image("icon.png".asResource()) content = grid(2) { addClass(DEFAULT_STYLE_CLASS) val author = label { addClass(AUTHOR_STYLE_CLASS) text = "Dennis Remme" } val link = link { text = "www.remme.hamburg" setOnAction { TinyGit.showDocument("https://remme.hamburg") } } +listOf(Icons.coffee(), author, Icons.envelope(), Label("[email protected]"), Icons.globe(), link) } } }
bsd-3-clause
633f56be561a64391daada0ea302c7a3
32.023256
86
0.650704
4.011299
false
false
false
false
apoi/quickbeer-next
app/src/main/java/quickbeer/android/feature/styledetails/StyleDetailsViewModel.kt
2
3372
/** * 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.feature.styledetails import androidx.lifecycle.SavedStateHandle import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import dagger.hilt.android.lifecycle.HiltViewModel import javax.inject.Inject import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.collect import kotlinx.coroutines.flow.collectLatest import kotlinx.coroutines.flow.map import kotlinx.coroutines.launch import quickbeer.android.data.repository.Accept import quickbeer.android.data.state.State import quickbeer.android.domain.beer.repository.BeerRepository import quickbeer.android.domain.beerlist.repository.BeersInStyleRepository import quickbeer.android.domain.style.Style import quickbeer.android.domain.style.repository.StyleRepository import quickbeer.android.ui.adapter.beer.BeerListModel import quickbeer.android.ui.adapter.beer.BeerListModelRatingMapper import quickbeer.android.util.ktx.navId @HiltViewModel class StyleDetailsViewModel @Inject constructor( savedStateHandle: SavedStateHandle, private val styleRepository: StyleRepository, private val beersInStyleRepository: BeersInStyleRepository, private val beerRepository: BeerRepository ) : ViewModel() { private val styleId = savedStateHandle.navId() private val _styleState = MutableStateFlow<State<Style>>(State.Initial) val styleState: Flow<State<Style>> = _styleState private val _beersState = MutableStateFlow<State<List<BeerListModel>>>(State.Initial) val beersState: Flow<State<List<BeerListModel>>> = _beersState private val _parentStyleState = MutableStateFlow<State<Style>>(State.Initial) val parentStyleState: Flow<State<Style>> = _parentStyleState init { viewModelScope.launch(Dispatchers.IO) { styleRepository.getStream(styleId, Accept()) .collect { if (it is State.Success) getParentStyle(it.value.parent) _styleState.emit(it) } } viewModelScope.launch(Dispatchers.IO) { beersInStyleRepository.getStream(styleId.toString(), Accept()) .map(BeerListModelRatingMapper(beerRepository)::map) .collectLatest(_beersState::emit) } } private fun getParentStyle(parentStyleId: Int?) { if (parentStyleId == null) return viewModelScope.launch(Dispatchers.IO) { styleRepository.getStream(parentStyleId, Accept()) .collectLatest(_parentStyleState::emit) } } }
gpl-3.0
c336ecd065aaf7eb9bcb81d6510a54c8
38.670588
89
0.747331
4.484043
false
false
false
false
RuneSuite/client
updater-mapper/src/main/java/org/runestar/client/updater/mapper/std/classes/SeqType.kt
1
4854
package org.runestar.client.updater.mapper.std.classes import org.runestar.client.common.startsWith import org.objectweb.asm.Opcodes.* import org.objectweb.asm.Type.INT_TYPE import org.objectweb.asm.Type.VOID_TYPE import org.runestar.client.updater.mapper.IdentityMapper import org.runestar.client.updater.mapper.OrderMapper import org.runestar.client.updater.mapper.UniqueMapper import org.runestar.client.updater.mapper.DependsOn import org.runestar.client.updater.mapper.MethodParameters import org.runestar.client.updater.mapper.and import org.runestar.client.updater.mapper.predicateOf import org.runestar.client.updater.mapper.type import org.runestar.client.updater.mapper.std.ConstructorPutField import org.runestar.client.updater.mapper.Class2 import org.runestar.client.updater.mapper.Instruction2 import org.runestar.client.updater.mapper.Method2 @DependsOn(DualNode::class) class SeqType : IdentityMapper.Class() { override val predicate = predicateOf<Class2> { it.superType == type<DualNode>() } .and { it.instanceFields.count { it.type == IntArray::class.type } == 5 } @DependsOn(Packet::class) class decode : IdentityMapper.InstanceMethod() { override val predicate = predicateOf<Method2> { it.returnType == VOID_TYPE } .and { it.instructions.any { it.opcode == GOTO } } .and { it.instructions.none { it.opcode == BIPUSH && it.intOperand == 13 } } .and { it.arguments.startsWith(type<Packet>()) } } class decode0 : IdentityMapper.InstanceMethod() { override val predicate = predicateOf<Method2> { it.returnType == VOID_TYPE } .and { it.instructions.any { it.opcode == GOTO } } .and { it.instructions.any { it.opcode == BIPUSH && it.intOperand == 13 } } } class lefthand : OrderMapper.InConstructor.Field(SeqType::class, 2) { override val predicate = predicateOf<Instruction2> { it.opcode == PUTFIELD && it.fieldType == INT_TYPE } } class righthand : OrderMapper.InConstructor.Field(SeqType::class, 3) { override val predicate = predicateOf<Instruction2> { it.opcode == PUTFIELD && it.fieldType == INT_TYPE } } @MethodParameters() class postDecode : IdentityMapper.InstanceMethod() { override val predicate = predicateOf<Method2> { it.returnType == VOID_TYPE } .and { it.arguments.size in 0..1 } .and { it.instructions.none { it.isMethod } } } @DependsOn(decode0::class) class frameLengths : OrderMapper.InMethod.Field(decode0::class, 0) { override val predicate = predicateOf<Instruction2> { it.opcode == PUTFIELD && it.fieldType == IntArray::class.type } } @DependsOn(decode0::class) class frameIds : OrderMapper.InMethod.Field(decode0::class, 1) { override val predicate = predicateOf<Instruction2> { it.opcode == PUTFIELD && it.fieldType == IntArray::class.type } } @MethodParameters("model", "frame") @DependsOn(SpotType.getModel::class) class animateSpotAnimation : UniqueMapper.InMethod.Method(SpotType.getModel::class) { override val predicate = predicateOf<Instruction2> { it.isMethod && it.methodOwner == type<SeqType>() } } @MethodParameters("model", "frame", "orientation") @DependsOn(LocType.getModelDynamic::class) class animateObject : UniqueMapper.InMethod.Method(LocType.getModelDynamic::class) { override val predicate = predicateOf<Instruction2> { it.isMethod && it.methodOwner == type<SeqType>() } } @MethodParameters("model", "frame", "sequence", "sequenceFrame") @DependsOn(Model::class) class animateSequence2 : IdentityMapper.InstanceMethod() { override val predicate = predicateOf<Method2> { it.returnType == type<Model>() } .and { it.arguments.size in 4..5 } .and { it.arguments.startsWith(type<Model>(), INT_TYPE, type<SeqType>(), INT_TYPE) } } @MethodParameters("model", "frame") @DependsOn(animateSequence2::class) class animateSequence : UniqueMapper.InMethod.Method(animateSequence2::class) { override val predicate = predicateOf<Instruction2> { it.isMethod && it.methodOwner == type<SeqType>() } } @MethodParameters("model", "frame") @DependsOn(Component.getModel::class) class animateComponent : UniqueMapper.InMethod.Method(Component.getModel::class) { override val predicate = predicateOf<Instruction2> { it.isMethod && it.methodOwner == type<SeqType>() } } @DependsOn(animateComponent::class) class frameIds2 : OrderMapper.InMethod.Field(animateComponent::class, 1) { override val predicate = predicateOf<Instruction2> { it.opcode == GETFIELD && it.fieldType == IntArray::class.type } } class frameCount : ConstructorPutField(SeqType::class, 0, INT_TYPE) }
mit
773d9bba809d3b97fd90c506b7eb1671
46.598039
124
0.695921
4.145175
false
false
false
false
RuneSuite/client
plugins-dev/src/main/java/org/runestar/client/plugins/dev/ModelDrawTest.kt
1
2217
package org.runestar.client.plugins.dev import org.runestar.client.api.plugins.DisposablePlugin import org.runestar.client.api.game.Model import org.runestar.client.api.game.SceneElement import org.runestar.client.api.game.SceneElementKind import org.runestar.client.api.game.live.Canvas import org.runestar.client.api.game.live.Scene import org.runestar.client.api.game.live.Viewport import org.runestar.client.api.game.live.SceneElements import org.runestar.client.api.game.live.VisibilityMap import org.runestar.client.api.plugins.PluginSettings import java.awt.Color import java.awt.Graphics2D class ModelDrawTest : DisposablePlugin<PluginSettings>() { override val defaultSettings = PluginSettings() private val objs: MutableSet<SceneElement> = LinkedHashSet() override fun onStart() { add(SceneElements.cleared.subscribe { objs.clear() }) add(SceneElements.removed.subscribe { objs.remove(it) }) add(SceneElements.added.subscribe { objs.add(it) }) Scene.reload() add(Canvas.repaints.subscribe { g -> objs.forEach { g.color = colorFor(it) it.models.forEach { drawModel(g, it) } } }) } override fun onStop() { objs.clear() } private fun colorFor(obj: SceneElement): Color { return when (obj.tag.kind) { SceneElementKind.OBJ -> Color.RED SceneElementKind.NPC -> Color.YELLOW SceneElementKind.PLAYER -> Color.WHITE SceneElementKind.LOC -> when (obj) { is SceneElement.Wall -> Color.MAGENTA is SceneElement.Scenery -> Color.BLUE is SceneElement.FloorDecoration -> Color.CYAN is SceneElement.WallDecoration -> Color.ORANGE else -> throw IllegalStateException() } else -> error(obj) } } private fun drawModel(g: Graphics2D, model: Model) { val pos = model.base val tile = pos.sceneTile if (!tile.isLoaded || !VisibilityMap.isVisible(tile)) return val pt = pos.toScreen() ?: return if (pt !in Viewport) return model.drawWireFrame(g.color) } }
mit
95657f387a20256c0c667de805480860
33.65625
68
0.651331
4.175141
false
false
false
false
JetBrains/intellij-community
plugins/kotlin/gradle/gradle/src/org/jetbrains/kotlin/idea/gradle/configuration/kotlinResolverUtil.kt
1
3402
// 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.gradle.configuration import com.intellij.ide.plugins.PluginManagerCore import com.intellij.notification.Notification import com.intellij.notification.NotificationAction import com.intellij.notification.NotificationType import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.extensions.PluginId import com.intellij.openapi.project.ProjectManager import com.intellij.openapi.updateSettings.impl.pluginsAdvertisement.installAndEnable import com.intellij.openapi.updateSettings.impl.pluginsAdvertisement.notificationGroup import com.intellij.openapi.util.NlsContexts import com.intellij.util.PlatformUtils import org.jetbrains.annotations.NotNull import org.jetbrains.kotlin.idea.gradle.KotlinIdeaGradleBundle import org.jetbrains.kotlin.idea.gradle.configuration.state.DontShowAgainKotlinAdditionPluginSuggestionService private var isNativeDebugSuggestionEnabled: Boolean get() { val service = DontShowAgainKotlinAdditionPluginSuggestionService.getInstance() return !service.state.dontShowAgainKotlinNativeDebuggerPluginSuggestion } set(value) { val service = DontShowAgainKotlinAdditionPluginSuggestionService.getInstance() service.state.dontShowAgainKotlinNativeDebuggerPluginSuggestion = !value } fun suggestNativeDebug(projectPath: String) { if (!isNativeDebugSuggestionEnabled) return suggestPluginInstall( projectPath = projectPath, notificationContent = KotlinIdeaGradleBundle.message("notification.text.native.debug.provides.debugger.for.kotlin.native"), displayId = "kotlin.native.debug", pluginId = PluginId.getId("com.intellij.nativeDebug"), onDontShowAgainActionPerformed = { isNativeDebugSuggestionEnabled = false }, onlyForUltimate = true, ) } private fun suggestPluginInstall( projectPath: String, @NlsContexts.NotificationContent notificationContent: String, pluginId: PluginId, displayId: String, onDontShowAgainActionPerformed: () -> Unit = { }, onlyForUltimate: Boolean = false, ) { if (onlyForUltimate && !PlatformUtils.isIdeaUltimate()) return if (PluginManagerCore.isPluginInstalled(pluginId)) return val projectManager = ProjectManager.getInstance() val project = projectManager.openProjects.firstOrNull { it.basePath == projectPath } ?: return notificationGroup .createNotification(KotlinIdeaGradleBundle.message("notification.title.plugin.suggestion"), notificationContent, NotificationType.INFORMATION) .setDisplayId(displayId) .setSuggestionType(true) .addAction(object : NotificationAction(KotlinIdeaGradleBundle.message("action.text.install")) { override fun actionPerformed(e: AnActionEvent, notification: Notification) { installAndEnable(project, setOf<@NotNull PluginId>(pluginId)) { notification.expire() } } }) .addAction(object : NotificationAction(KotlinIdeaGradleBundle.message("action.text.dontShowAgain")) { override fun actionPerformed(e: AnActionEvent, notification: Notification) { onDontShowAgainActionPerformed() notification.expire() } }) .notify(project) }
apache-2.0
1ca7ae03efbd4145c227d47eaa4ae7ea
46.25
150
0.765726
5.201835
false
false
false
false
NeatoRobotics/neato-sdk-android
Neato-SDK/neato-sdk-android/src/main/java/com/neatorobotics/sdk/android/dsl/RobotStateDSL.kt
1
4598
/* * Copyright (c) 2019. * Neato Robotics Inc. */ package com.neatorobotics.sdk.android.dsl import android.graphics.PointF import com.neatorobotics.sdk.android.models.* import java.util.ArrayList import java.util.HashMap class RobotStateBuilder { var state: State = State.INVALID var action: Action = Action.INVALID var cleaningCategory: CleaningCategory = CleaningCategory.HOUSE var cleaningModifier: CleaningModifier = CleaningModifier.NORMAL var cleaningMode: CleaningMode = CleaningMode.TURBO var navigationMode: NavigationMode = NavigationMode.NORMAL var isCharging: Boolean = false var isDocked: Boolean = false var isDockHasBeenSeen: Boolean = false var isScheduleEnabled: Boolean = false var isStartAvailable: Boolean = false var isStopAvailable: Boolean = false var isPauseAvailable: Boolean = false var isResumeAvailable: Boolean = false var isGoToBaseAvailable: Boolean = false var spotSize: Int = 0 var mapId: String? = null var boundary: Boundary? = null var boundaries: MutableList<Boundary> = mutableListOf() var scheduleEvents: ArrayList<ScheduleEvent> = ArrayList() var availableServices: HashMap<String, String> = HashMap() var message: String? = null var error: String? = null var alert: String? = null var charge: Double = 0.toDouble() var serial: String? = null var result: String? = null var robotRemoteProtocolVersion: Int = 0 var robotModelName: String? = null var firmware: String? = null fun build(): RobotState { return RobotState(state = state, action = action, cleaningCategory = cleaningCategory, cleaningModifier = cleaningModifier, cleaningMode = cleaningMode, navigationMode = navigationMode, isCharging = isCharging, isDocked = isDocked, isDockHasBeenSeen = isDockHasBeenSeen, isScheduleEnabled = isScheduleEnabled, isStartAvailable = isStartAvailable, isStopAvailable = isStopAvailable, isPauseAvailable = isPauseAvailable, isResumeAvailable = isResumeAvailable, isGoToBaseAvailable = isGoToBaseAvailable, cleaningSpotHeight = spotSize, cleaningSpotWidth = spotSize, mapId = mapId, boundary = boundary, boundaries = boundaries, scheduleEvents = scheduleEvents, availableServices = availableServices, message = message, error = error, alert = alert, charge = charge, serial = serial, result = result,robotRemoteProtocolVersion = robotRemoteProtocolVersion, robotModelName = robotModelName, firmware = firmware) } } fun RobotStateBuilder.boundary(block: BoundaryBuilder.() -> Unit) { val bb = BoundaryBuilder() block(bb) this.boundary = bb.build() } class BoundaryBuilder { var id: String? = null var type: String = "polyline" //polyline or polygon var name: String = "" var color: String = "#000000" var isEnabled: Boolean = true var isSelected: Boolean = false var isValid: Boolean = true var vertices: MutableList<PointF>? = null var relevancy: PointF? = null //interest point inside a zone var state: BoundaryStatus = BoundaryStatus.NONE fun build(): Boundary { return Boundary(id = id, type = type, name = name, color = color, isEnabled = isEnabled, isSelected = isSelected, isValid = isValid, vertices = vertices, relevancy = relevancy, state = state) } } fun RobotStateBuilder.boundaries(block: BoundariesBuilder.() -> Unit) { val bb = BoundariesBuilder() block(bb) this.boundaries = bb.build() } class BoundariesBuilder { var boundaries = mutableListOf<Boundary>() fun boundary(block: BoundaryBuilder.() -> Unit) { val tb = BoundaryBuilder() block(tb) boundaries.add(tb.build()) } fun build(): MutableList<Boundary> { return boundaries } } fun RobotStateBuilder.services(block: ServicesBuilder.() -> Unit) { val bb = ServicesBuilder() block(bb) this.availableServices = bb.build() } class ServicesBuilder { var services = hashMapOf<String, String>() fun service(block: ServiceBuilder.() -> Unit) { val tb = ServiceBuilder() block(tb) services[tb.buildName()]= tb.buildVersion() } fun build(): HashMap<String, String> { return services } } class ServiceBuilder { var name: String = "" var version: String = "" fun buildName(): String { return name } fun buildVersion(): String { return version } }
mit
e834d2b6ebf1023f95d4ce1ffbbb369b
31.387324
152
0.679643
4.477118
false
false
false
false
chrislo27/RhythmHeavenRemixEditor2
core/src/main/kotlin/io/github/chrislo27/rhre3/git/GitHelper.kt
2
4424
package io.github.chrislo27.rhre3.git import com.badlogic.gdx.files.FileHandle import io.github.chrislo27.rhre3.RHRE3 import io.github.chrislo27.rhre3.screen.GitUpdateScreen import io.github.chrislo27.toolboks.Toolboks import org.eclipse.jgit.api.Git import org.eclipse.jgit.api.ResetCommand import org.eclipse.jgit.lib.NullProgressMonitor import org.eclipse.jgit.lib.ProgressMonitor import org.eclipse.jgit.lib.Repository import org.eclipse.jgit.lib.RepositoryBuilder import org.eclipse.jgit.transport.RefSpec import org.eclipse.jgit.transport.URIish import java.net.URL object GitHelper { val SOUNDS_DIR: FileHandle by lazy { RHRE3.RHRE3_FOLDER.child("sfx/${RHRE3.DATABASE_BRANCH}/").apply { mkdirs() } } fun makeRepositoryBuilder(mustExist: Boolean = false): RepositoryBuilder = RepositoryBuilder().setWorkTree(SOUNDS_DIR.file()).setMustExist(mustExist) fun <T> temporarilyUseRepo(mustExist: Boolean = false, action: Repository.() -> T): T { val repo = makeRepositoryBuilder(mustExist = mustExist).build() val result: T = repo.action() repo.close() return result } fun doesGitFolderExist(): Boolean { return temporarilyUseRepo { this.objectDatabase.exists() } } fun initGitRepo() { val git = Git.init().setDirectory(SOUNDS_DIR.file()).call() git.remoteAdd().apply { setName("origin") setUri(URIish(RHRE3.DATABASE_URL)) call() } git.close() } fun initGitRepoIfGitRepoDoesNotExist(): Boolean { if (!doesGitFolderExist()) { initGitRepo() return true } return false } fun reset() { Toolboks.LOGGER.info("Resetting...") temporarilyUseRepo(true) { val git = Git(this) val result = git.reset() .setMode(ResetCommand.ResetType.HARD) .setRef("origin/${RHRE3.DATABASE_BRANCH}") .call() } } fun fetchOrClone(progressMonitor: ProgressMonitor = NullProgressMonitor.INSTANCE) { if (doesGitFolderExist()) { Toolboks.LOGGER.info("Fetching...") if (progressMonitor is GitUpdateScreen.GitScreenProgressMonitor) progressMonitor.currentSpecialState = GitUpdateScreen.GitScreenProgressMonitor.SpecialState.FETCHING ensureRemoteExists() temporarilyUseRepo(true) { val git = Git(this) this.directory.resolve("index.lock").delete() // mega naughty val result = git.fetch() .setRemote("origin") .setProgressMonitor(progressMonitor) .setRefSpecs( RefSpec("refs/heads/${RHRE3.DATABASE_BRANCH}:refs/remotes/origin/${RHRE3.DATABASE_BRANCH}")) .setCheckFetchedObjects(true) .call() if (!result.messages.isNullOrEmpty()) { Toolboks.LOGGER.info("Fetch result has messages: ${result.messages}") } } if (progressMonitor is GitUpdateScreen.GitScreenProgressMonitor) progressMonitor.currentSpecialState = GitUpdateScreen.GitScreenProgressMonitor.SpecialState.RESETTING reset() } else { Toolboks.LOGGER.info("Cloning...") if (progressMonitor is GitUpdateScreen.GitScreenProgressMonitor) progressMonitor.currentSpecialState = GitUpdateScreen.GitScreenProgressMonitor.SpecialState.CLONING val file = SOUNDS_DIR.file() file.deleteRecursively() Git.cloneRepository() .setBranch(RHRE3.DATABASE_BRANCH) .setProgressMonitor(progressMonitor) .setRemote("origin") .setURI(RHRE3.DATABASE_URL) .setDirectory(file) .call() } } fun ensureRemoteExists() { temporarilyUseRepo { val git = Git(this) if ("origin" !in git.repository.remoteNames) { val remoteAdd = git.remoteAdd() remoteAdd.setName("origin") remoteAdd.setUri(URIish(URL(RHRE3.DATABASE_URL))) remoteAdd.call() } } } }
gpl-3.0
c58606654c7a7a8183741027f1b9f591
34.4
124
0.596519
4.642183
false
false
false
false
matrix-org/matrix-android-sdk
matrix-sdk-crypto/src/main/java/org/matrix/androidsdk/crypto/api/RoomKeysApi.kt
1
6083
/* * Copyright 2018 New Vector Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.matrix.androidsdk.crypto.api import org.matrix.androidsdk.crypto.model.keys.* import org.matrix.androidsdk.crypto.model.rest.keys.BackupKeysResult import org.matrix.androidsdk.crypto.model.rest.keys.UpdateKeysBackupVersionBody import retrofit2.Call import retrofit2.http.* /** * Ref: https://github.com/uhoreg/matrix-doc/blob/e2e_backup/proposals/1219-storing-megolm-keys-serverside.md */ interface RoomKeysApi { /* ========================================================================================== * Backup versions management * ========================================================================================== */ /** * Create a new keys backup version. */ @POST("room_keys/version") fun createKeysBackupVersion(@Body createKeysBackupVersionBody: CreateKeysBackupVersionBody): Call<KeysVersion> /** * Get information about the last version. */ @GET("room_keys/version") fun getKeysBackupLastVersion(): Call<KeysVersionResult> /** * Get information about the given version. */ @GET("room_keys/version/{version}") fun getKeysBackupVersion(@Path("version") version: String): Call<KeysVersionResult> /** * Update information about the given version. */ @PUT("room_keys/version/{version}") fun updateKeysBackupVersion(@Path("version") version: String, @Body keysBackupVersionBody: UpdateKeysBackupVersionBody): Call<Void> /* ========================================================================================== * Storing keys * ========================================================================================== */ /** * Store the key for the given session in the given room, using the given backup version. * * * If the server already has a backup in the backup version for the given session and room, then it will * keep the "better" one. To determine which one is "better", key backups are compared first by the is_verified * flag (true is better than false), then by the first_message_index (a lower number is better), and finally by * forwarded_count (a lower number is better). */ @PUT("room_keys/keys/{roomId}/{sessionId}") fun storeRoomSessionData(@Path("roomId") roomId: String, @Path("sessionId") sessionId: String, @Query("version") version: String, @Body keyBackupData: KeyBackupData): Call<BackupKeysResult> /** * Store several keys for the given room, using the given backup version. */ @PUT("room_keys/keys/{roomId}") fun storeRoomSessionsData(@Path("roomId") roomId: String, @Query("version") version: String, @Body roomKeysBackupData: RoomKeysBackupData): Call<BackupKeysResult> /** * Store several keys, using the given backup version. */ @PUT("room_keys/keys") fun storeSessionsData(@Query("version") version: String, @Body keysBackupData: KeysBackupData): Call<BackupKeysResult> /* ========================================================================================== * Retrieving keys * ========================================================================================== */ /** * Retrieve the key for the given session in the given room from the backup. */ @GET("room_keys/keys/{roomId}/{sessionId}") fun getRoomSessionData(@Path("roomId") roomId: String, @Path("sessionId") sessionId: String, @Query("version") version: String): Call<KeyBackupData> /** * Retrieve all the keys for the given room from the backup. */ @GET("room_keys/keys/{roomId}") fun getRoomSessionsData(@Path("roomId") roomId: String, @Query("version") version: String): Call<RoomKeysBackupData> /** * Retrieve all the keys from the backup. */ @GET("room_keys/keys") fun getSessionsData(@Query("version") version: String): Call<KeysBackupData> /* ========================================================================================== * Deleting keys * ========================================================================================== */ /** * Deletes keys from the backup. */ @DELETE("room_keys/keys/{roomId}/{sessionId}") fun deleteRoomSessionData(@Path("roomId") roomId: String, @Path("sessionId") sessionId: String, @Query("version") version: String): Call<Void> /** * Deletes keys from the backup. */ @DELETE("room_keys/keys/{roomId}") fun deleteRoomSessionsData(@Path("roomId") roomId: String, @Query("version") version: String): Call<Void> /** * Deletes keys from the backup. */ @DELETE("room_keys/keys") fun deleteSessionsData(@Query("version") version: String): Call<Void> /* ========================================================================================== * Deleting backup * ========================================================================================== */ /** * Deletes a backup. */ @DELETE("room_keys/version/{version}") fun deleteBackup(@Path("version") version: String): Call<Void> }
apache-2.0
d10c2cb1cb4d663e01f0a245f4eb70bb
38.5
115
0.533618
4.994253
false
false
false
false
leafclick/intellij-community
plugins/filePrediction/src/com/intellij/filePrediction/history/FilePredictionHistory.kt
1
1461
// 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.filePrediction.history import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.components.ServiceManager import com.intellij.openapi.project.Project import com.intellij.openapi.project.ProjectManager import com.intellij.openapi.project.ProjectManagerListener class FilePredictionHistory(val project: Project) { companion object { private const val RECENT_FILES_LIMIT = 50 fun getInstance(project: Project): FilePredictionHistory { return ServiceManager.getService(project, FilePredictionHistory::class.java) } } private var manager: FileHistoryManager init { manager = FileHistoryManager(FileHistoryPersistence.loadFileHistory(project), RECENT_FILES_LIMIT) project.messageBus.connect().subscribe(ProjectManager.TOPIC, object : ProjectManagerListener { override fun projectClosing(project: Project) { ApplicationManager.getApplication().executeOnPooledThread { FileHistoryPersistence.saveFileHistory(project, manager.getState()) } } }) } fun onFileOpened(fileUrl: String) = manager.onFileOpened(fileUrl) fun calcHistoryFeatures(fileUrl: String): FileHistoryFeatures = manager.calcHistoryFeatures(fileUrl) fun size(): Int = manager.size() fun cleanup() = manager.cleanup() }
apache-2.0
da3d96b8bd15e3c82cc2d1815d0d48dd
35.55
140
0.774812
4.853821
false
false
false
false
leafclick/intellij-community
python/src/com/jetbrains/python/sdk/add/PyAddNewCondaEnvPanel.kt
1
6566
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.jetbrains.python.sdk.add import com.intellij.execution.ExecutionException import com.intellij.openapi.fileChooser.FileChooserDescriptorFactory import com.intellij.openapi.module.Module import com.intellij.openapi.progress.ProgressIndicator import com.intellij.openapi.progress.Task import com.intellij.openapi.project.Project import com.intellij.openapi.projectRoots.Sdk import com.intellij.openapi.ui.ComboBox import com.intellij.openapi.ui.TextFieldWithBrowseButton import com.intellij.openapi.ui.ValidationInfo import com.intellij.openapi.util.UserDataHolder import com.intellij.openapi.util.io.FileUtil import com.intellij.openapi.util.text.StringUtil import com.intellij.openapi.vfs.LocalFileSystem import com.intellij.ui.DocumentAdapter import com.intellij.ui.components.JBCheckBox import com.intellij.util.PathUtil import com.intellij.util.SystemProperties import com.intellij.util.ui.FormBuilder import com.jetbrains.python.PyBundle import com.jetbrains.python.packaging.PyCondaPackageManagerImpl import com.jetbrains.python.packaging.PyCondaPackageService import com.jetbrains.python.psi.LanguageLevel import com.jetbrains.python.sdk.associateWithModule import com.jetbrains.python.sdk.basePath import com.jetbrains.python.sdk.createSdkByGenerateTask import icons.PythonIcons import org.jetbrains.annotations.SystemIndependent import java.awt.BorderLayout import java.io.File import javax.swing.Icon import javax.swing.JComboBox import javax.swing.event.DocumentEvent /** * @author vlan */ class PyAddNewCondaEnvPanel(private val project: Project?, private val module: Module?, private val existingSdks: List<Sdk>, newProjectPath: String?, context: UserDataHolder) : PyAddNewEnvPanel() { override val envName: String = "Conda" override val panelName: String = "New environment" override val icon: Icon = PythonIcons.Python.Anaconda private val languageLevelsField: JComboBox<String> private val condaPathField = TextFieldWithBrowseButton().apply { val path = PyCondaPackageService.getInstance().PREFERRED_CONDA_PATH ?: PyCondaPackageService.getSystemCondaExecutable() path?.let { text = it } addBrowseFolderListener(PyBundle.message("python.sdk.select.conda.path.title"), null, project, FileChooserDescriptorFactory.createSingleFileOrExecutableAppDescriptor()) textField.document.addDocumentListener(object : DocumentAdapter() { override fun textChanged(e: DocumentEvent) { updatePathField() } }) } private val pathField = TextFieldWithBrowseButton().apply { addBrowseFolderListener(PyBundle.message("python.sdk.select.location.for.conda.title"), null, project, FileChooserDescriptorFactory.createSingleFolderDescriptor()) } private val makeSharedField = JBCheckBox(PyBundle.message("available.to.all.projects")) override var newProjectPath: String? = newProjectPath set(value) { field = value updatePathField() } init { layout = BorderLayout() // https://conda.io/docs/user-guide/install/index.html#system-requirements val supportedLanguageLevels = LanguageLevel.SUPPORTED_LEVELS.asReversed().filter { it != LanguageLevel.PYTHON38 }.map { it.toString() } languageLevelsField = ComboBox(supportedLanguageLevels.toTypedArray()).apply { selectedItem = if (itemCount > 0) getItemAt(0) else null } updatePathField() val formPanel = FormBuilder.createFormBuilder() .addLabeledComponent("Location:", pathField) .addLabeledComponent("Python version:", languageLevelsField) .addLabeledComponent(PyBundle.message("python.sdk.conda.path"), condaPathField) .addComponent(makeSharedField) .panel add(formPanel, BorderLayout.NORTH) } override fun validateAll(): List<ValidationInfo> = listOfNotNull(validateAnacondaPath(), validateEnvironmentDirectoryLocation(pathField)) override fun getOrCreateSdk(): Sdk? { val condaPath = condaPathField.text val task = object : Task.WithResult<String, ExecutionException>(project, PyBundle.message("python.sdk.creating.conda.environment.title"), false) { override fun compute(indicator: ProgressIndicator): String { indicator.isIndeterminate = true return PyCondaPackageManagerImpl.createVirtualEnv(condaPath, pathField.text, selectedLanguageLevel) } } val shared = makeSharedField.isSelected val associatedPath = if (!shared) projectBasePath else null val sdk = createSdkByGenerateTask(task, existingSdks, null, associatedPath, null) ?: return null if (!shared) { sdk.associateWithModule(module, newProjectPath) } PyCondaPackageService.getInstance().PREFERRED_CONDA_PATH = condaPath return sdk } override fun addChangeListener(listener: Runnable) { val documentListener = object : DocumentAdapter() { override fun textChanged(e: DocumentEvent) { listener.run() } } pathField.textField.document.addDocumentListener(documentListener) condaPathField.textField.document.addDocumentListener(documentListener) } private fun updatePathField() { val baseDir = defaultBaseDir ?: "${SystemProperties.getUserHome()}/.conda/envs" val dirName = PathUtil.getFileName(projectBasePath ?: "untitled") pathField.text = FileUtil.toSystemDependentName("$baseDir/$dirName") } private fun validateAnacondaPath(): ValidationInfo? { val text = condaPathField.text val file = File(text) val message = when { StringUtil.isEmptyOrSpaces(text) -> "Conda executable path is empty" !file.exists() -> "Conda executable not found" !file.isFile || !file.canExecute() -> "Conda executable path is not an executable file" else -> return null } return ValidationInfo(message) } private val defaultBaseDir: String? get() { val conda = condaPathField.text val condaFile = LocalFileSystem.getInstance().findFileByPath(conda) ?: return null return condaFile.parent?.parent?.findChild("envs")?.path } private val projectBasePath: @SystemIndependent String? get() = newProjectPath ?: module?.basePath ?: project?.basePath private val selectedLanguageLevel: String get() = languageLevelsField.getItemAt(languageLevelsField.selectedIndex) }
apache-2.0
b1b892e0f8e6bfa0fa73262575205102
40.556962
150
0.747182
4.768337
false
false
false
false
anthonycr/Lightning-Browser
app/src/main/java/acr/browser/lightning/database/bookmark/BookmarkDatabase.kt
1
11002
package acr.browser.lightning.database.bookmark import acr.browser.lightning.R import acr.browser.lightning.database.Bookmark import acr.browser.lightning.database.asFolder import acr.browser.lightning.database.databaseDelegate import acr.browser.lightning.extensions.firstOrNullMap import acr.browser.lightning.extensions.useMap import android.app.Application import android.content.ContentValues import android.database.Cursor import android.database.DatabaseUtils import android.database.sqlite.SQLiteDatabase import android.database.sqlite.SQLiteOpenHelper import androidx.core.database.getStringOrNull import io.reactivex.Completable import io.reactivex.Maybe import io.reactivex.Single import javax.inject.Inject import javax.inject.Singleton /** * The disk backed bookmark database. See [BookmarkRepository] for function documentation. * * Created by anthonycr on 5/6/17. */ @Singleton class BookmarkDatabase @Inject constructor( application: Application ) : SQLiteOpenHelper(application, DATABASE_NAME, null, DATABASE_VERSION), BookmarkRepository { private val defaultBookmarkTitle: String = application.getString(R.string.untitled) private val database: SQLiteDatabase by databaseDelegate() // Creating Tables override fun onCreate(db: SQLiteDatabase) { val createBookmarkTable = "CREATE TABLE ${DatabaseUtils.sqlEscapeString(TABLE_BOOKMARK)}(" + "${DatabaseUtils.sqlEscapeString(KEY_ID)} INTEGER PRIMARY KEY," + "${DatabaseUtils.sqlEscapeString(KEY_URL)} TEXT," + "${DatabaseUtils.sqlEscapeString(KEY_TITLE)} TEXT," + "${DatabaseUtils.sqlEscapeString(KEY_FOLDER)} TEXT," + "${DatabaseUtils.sqlEscapeString(KEY_POSITION)} INTEGER" + ')' db.execSQL(createBookmarkTable) } // Upgrading database override fun onUpgrade(db: SQLiteDatabase, oldVersion: Int, newVersion: Int) { // Drop older table if it exists db.execSQL("DROP TABLE IF EXISTS ${DatabaseUtils.sqlEscapeString(TABLE_BOOKMARK)}") // Create tables again onCreate(db) } /** * Queries the database for bookmarks with the provided URL. If it * cannot find any bookmarks with the given URL, it will try to query * for bookmarks with the [.alternateSlashUrl] as its URL. * * @param url the URL to query for. * @return a cursor with bookmarks matching the URL. */ private fun queryWithOptionalEndSlash(url: String): Cursor { val alternateUrl = alternateSlashUrl(url) return database.query( TABLE_BOOKMARK, null, "$KEY_URL=? OR $KEY_URL=?", arrayOf(url, alternateUrl), null, null, null, "1" ) } /** * Deletes a bookmark from the database with the provided URL. If it * cannot find any bookmark with the given URL, it will try to delete * a bookmark with the [.alternateSlashUrl] as its URL. * * @param url the URL to delete. * @return the number of deleted rows. */ private fun deleteWithOptionalEndSlash(url: String): Int { return database.delete( TABLE_BOOKMARK, "$KEY_URL=? OR $KEY_URL=?", arrayOf(url, alternateSlashUrl(url)) ) } /** * Updates a bookmark in the database with the provided URL. If it * cannot find any bookmark with the given URL, it will try to update * a bookmark with the [.alternateSlashUrl] as its URL. * * @param url the URL to update. * @param contentValues the new values to update to. * @return the number of rows updated. */ private fun updateWithOptionalEndSlash(url: String, contentValues: ContentValues): Int { var updatedRows = database.update( TABLE_BOOKMARK, contentValues, "$KEY_URL=?", arrayOf(url) ) if (updatedRows == 0) { val alternateUrl = alternateSlashUrl(url) updatedRows = database.update( TABLE_BOOKMARK, contentValues, "$KEY_URL=?", arrayOf(alternateUrl) ) } return updatedRows } override fun findBookmarkForUrl(url: String): Maybe<Bookmark.Entry> = Maybe.fromCallable { return@fromCallable queryWithOptionalEndSlash(url).firstOrNullMap { it.bindToBookmarkEntry() } } override fun isBookmark(url: String): Single<Boolean> = Single.fromCallable { queryWithOptionalEndSlash(url).use { return@fromCallable it.moveToFirst() } } override fun addBookmarkIfNotExists(entry: Bookmark.Entry): Single<Boolean> = Single.fromCallable { queryWithOptionalEndSlash(entry.url).use { if (it.moveToFirst()) { return@fromCallable false } } val id = database.insert( TABLE_BOOKMARK, null, entry.bindBookmarkToContentValues() ) return@fromCallable id != -1L } override fun addBookmarkList(bookmarkItems: List<Bookmark.Entry>): Completable = Completable.fromAction { database.apply { beginTransaction() for (item in bookmarkItems) { addBookmarkIfNotExists(item).subscribe() } setTransactionSuccessful() endTransaction() } } override fun deleteBookmark(entry: Bookmark.Entry): Single<Boolean> = Single.fromCallable { return@fromCallable deleteWithOptionalEndSlash(entry.url) > 0 } override fun renameFolder(oldName: String, newName: String): Completable = Completable.fromAction { val contentValues = ContentValues(1).apply { put(KEY_FOLDER, newName) } database.update(TABLE_BOOKMARK, contentValues, "$KEY_FOLDER=?", arrayOf(oldName)) } override fun deleteFolder(folderToDelete: String): Completable = Completable.fromAction(renameFolder(folderToDelete, "")::subscribe) override fun deleteAllBookmarks(): Completable = Completable.fromAction { database.run { delete(TABLE_BOOKMARK, null, null) close() } } override fun editBookmark( oldBookmark: Bookmark.Entry, newBookmark: Bookmark.Entry ): Completable = Completable.fromAction { val contentValues = newBookmark.bindBookmarkToContentValues() updateWithOptionalEndSlash(oldBookmark.url, contentValues) } override fun getAllBookmarksSorted(): Single<List<Bookmark.Entry>> = Single.fromCallable { return@fromCallable database.query( TABLE_BOOKMARK, null, null, null, null, null, "$KEY_FOLDER, $KEY_POSITION ASC, $KEY_TITLE COLLATE NOCASE ASC, $KEY_URL ASC" ).useMap { it.bindToBookmarkEntry() } } override fun getBookmarksFromFolderSorted(folder: String?): Single<List<Bookmark>> = Single.fromCallable { val finalFolder = folder ?: "" return@fromCallable database.query( TABLE_BOOKMARK, null, "$KEY_FOLDER=?", arrayOf(finalFolder), null, null, "$KEY_POSITION ASC, $KEY_TITLE COLLATE NOCASE ASC, $KEY_URL ASC" ).useMap { it.bindToBookmarkEntry() } } override fun getFoldersSorted(): Single<List<Bookmark.Folder>> = Single.fromCallable { return@fromCallable database .query( true, TABLE_BOOKMARK, arrayOf(KEY_FOLDER), null, null, null, null, "$KEY_FOLDER ASC", null ) .useMap { it.getString(it.getColumnIndex(KEY_FOLDER)) } .filter { !it.isNullOrEmpty() } .map(String::asFolder) } override fun getFolderNames(): Single<List<String>> = Single.fromCallable { return@fromCallable database.query( true, TABLE_BOOKMARK, arrayOf(KEY_FOLDER), null, null, null, null, "$KEY_FOLDER ASC", null ).useMap { it.getString(it.getColumnIndex(KEY_FOLDER)) } .filter { !it.isNullOrEmpty() } } override fun count(): Long = DatabaseUtils.queryNumEntries(database, TABLE_BOOKMARK) /** * Binds a [Bookmark.Entry] to [ContentValues]. * * @return a valid values object that can be inserted into the database. */ private fun Bookmark.Entry.bindBookmarkToContentValues() = ContentValues(4).apply { put(KEY_TITLE, title.takeIf(String::isNotBlank) ?: defaultBookmarkTitle) put(KEY_URL, url) put(KEY_FOLDER, folder.title) put(KEY_POSITION, position) } /** * Binds a cursor to a [Bookmark.Entry]. This is * a non consuming operation on the cursor. Note that * this operation is not safe to perform on a cursor * unless you know that the cursor is of history items. * * @return a valid item containing all the pertinent information. */ private fun Cursor.bindToBookmarkEntry() = Bookmark.Entry( url = getString(getColumnIndex(KEY_URL)), title = getString(getColumnIndex(KEY_TITLE)), folder = getStringOrNull(getColumnIndex(KEY_FOLDER)).asFolder(), position = getInt(getColumnIndex(KEY_POSITION)) ) /** * URLs can represent the same thing with or without a trailing slash, * for instance, google.com/ is the same page as google.com. Since these * can be represented as different bookmarks within the bookmark database, * it is important to be able to get the alternate version of a URL. * * @param url the string that might have a trailing slash. * @return a string without a trailing slash if the original had one, * or a string with a trailing slash if the original did not. */ private fun alternateSlashUrl(url: String): String = if (url.endsWith("/")) { url.substring(0, url.length - 1) } else { "$url/" } companion object { // Database version private const val DATABASE_VERSION = 1 // Database name private const val DATABASE_NAME = "bookmarkManager" // Bookmark table name private const val TABLE_BOOKMARK = "bookmark" // Bookmark table columns names private const val KEY_ID = "id" private const val KEY_URL = "url" private const val KEY_TITLE = "title" private const val KEY_FOLDER = "folder" private const val KEY_POSITION = "position" } }
mpl-2.0
fcadf905fc193a4c770bcc0157284d3e
33.38125
102
0.616252
4.785559
false
false
false
false
code-helix/slatekit
src/lib/kotlin/slatekit/src/main/kotlin/slatekit/docs/Doc.kt
1
1562
package slatekit.docs data class Doc( val name: String, val proj: String, val namespace: String, val source: String, val version: String, val example: String, val available: Boolean, val multi: Boolean, val readme: Boolean, val group: String, val jar: String, val depends: String, val desc: String ) { fun sourceFolder(files: DocFiles): String { //"slate.common.args.Args" val path = namespace.replace(".", "/") // Adjust for file in root namespace ( e.g. slatekit.common.Result.kt ) val sourceFolderPath = "src/lib/${files.lang}/${proj}/src/main/kotlin/${path}" return sourceFolderPath } fun artifact(): String { return "com.slatekit:$proj" } fun dependsOn(): String { var items = "" val tokens = depends.split(',') tokens.forEach { token -> when (token) { "res" -> items += " slatekit-results" "com" -> items += " slatekit-common" "ent" -> items += " slatekit-entities" "core" -> items += " slatekit-core" "cloud" -> items += " slatekit-providers-aws" else -> { } } } return items } fun layout(): String { return when (group) { "infra" -> "_mods_infra" "feat" -> "_mods_fea" "utils" -> "_mods_utils" else -> "_mods_utils" } } }
apache-2.0
41471699bd52d86162ca73f6f5c06d3b
25.05
86
0.487196
4.412429
false
false
false
false
JuliusKunze/kotlin-native
backend.native/tests/external/codegen/box/enum/innerClassMethodInEnumEntryClass.kt
1
258
// LANGUAGE_VERSION: 1.2 enum class A { X { val x = "OK" inner class Inner { fun foo() = x } val z = Inner() override val test = z.foo() }; abstract val test: String } fun box() = A.X.test
apache-2.0
6ce6606d8fea84d61c4d879931c67fa9
12.631579
35
0.453488
3.534247
false
true
false
false
smmribeiro/intellij-community
plugins/kotlin/test-framework/test/org/jetbrains/kotlin/idea/test/KotlinLightCodeInsightFixtureTestCase.kt
1
21884
// 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.test import com.intellij.application.options.CodeStyle import com.intellij.codeInsight.daemon.impl.EditorTracker import com.intellij.ide.highlighter.JavaFileType import com.intellij.openapi.actionSystem.* import com.intellij.openapi.actionSystem.ex.ActionManagerEx import com.intellij.openapi.actionSystem.ex.ActionUtil import com.intellij.openapi.actionSystem.impl.SimpleDataContext import com.intellij.openapi.application.WriteAction import com.intellij.openapi.editor.Caret import com.intellij.openapi.editor.Editor import com.intellij.openapi.editor.ex.EditorEx import com.intellij.openapi.externalSystem.service.project.ProjectDataManager import com.intellij.openapi.fileEditor.impl.text.TextEditorPsiDataProvider import com.intellij.openapi.module.Module import com.intellij.openapi.project.Project import com.intellij.openapi.projectRoots.Sdk import com.intellij.openapi.util.SystemInfo import com.intellij.openapi.util.io.FileUtil import com.intellij.openapi.util.registry.Registry import com.intellij.openapi.util.text.StringUtil import com.intellij.openapi.vfs.VfsUtilCore import com.intellij.openapi.vfs.newvfs.impl.VfsRootAccess import com.intellij.pom.java.LanguageLevel import com.intellij.psi.PsiClassOwner import com.intellij.psi.PsiFile import com.intellij.psi.PsiJavaFile import com.intellij.psi.PsiManager import com.intellij.psi.codeStyle.CodeStyleSettings import com.intellij.psi.codeStyle.CodeStyleSettingsManager import com.intellij.psi.search.FileTypeIndex import com.intellij.psi.search.ProjectScope import com.intellij.testFramework.IdeaTestUtil import com.intellij.testFramework.LightProjectDescriptor import com.intellij.testFramework.LoggedErrorProcessor import com.intellij.testFramework.RunAll import com.intellij.testFramework.fixtures.JavaCodeInsightTestFixture import com.intellij.util.ThrowableRunnable import org.jetbrains.kotlin.cli.common.arguments.K2JVMCompilerArguments import org.jetbrains.kotlin.config.ApiVersion import org.jetbrains.kotlin.config.CompilerSettings import org.jetbrains.kotlin.config.CompilerSettings.Companion.DEFAULT_ADDITIONAL_ARGUMENTS import org.jetbrains.kotlin.config.JvmTarget import org.jetbrains.kotlin.config.LanguageVersion import org.jetbrains.kotlin.idea.KotlinFileType import org.jetbrains.kotlin.idea.compiler.configuration.KotlinCommonCompilerArgumentsHolder import org.jetbrains.kotlin.idea.compiler.configuration.KotlinCompilerSettings import org.jetbrains.kotlin.idea.facet.* import org.jetbrains.kotlin.idea.formatter.KotlinLanguageCodeStyleSettingsProvider import org.jetbrains.kotlin.idea.formatter.KotlinStyleGuideCodeStyle import org.jetbrains.kotlin.idea.inspections.UnusedSymbolInspection import org.jetbrains.kotlin.idea.test.CompilerTestDirectives.API_VERSION_DIRECTIVE import org.jetbrains.kotlin.idea.test.CompilerTestDirectives.COMPILER_ARGUMENTS_DIRECTIVE import org.jetbrains.kotlin.idea.test.CompilerTestDirectives.JVM_TARGET_DIRECTIVE import org.jetbrains.kotlin.idea.test.CompilerTestDirectives.LANGUAGE_VERSION_DIRECTIVE import org.jetbrains.kotlin.psi.KtFile import org.jetbrains.kotlin.test.InTextDirectivesUtils import org.jetbrains.kotlin.test.KotlinRoot import org.jetbrains.kotlin.test.KotlinTestUtils import org.jetbrains.kotlin.test.TestMetadataUtil import org.jetbrains.kotlin.test.util.slashedPath import org.jetbrains.kotlin.utils.addIfNotNull import org.jetbrains.kotlin.utils.rethrow import java.io.File import java.io.IOException import java.nio.file.Path abstract class KotlinLightCodeInsightFixtureTestCase : KotlinLightCodeInsightFixtureTestCaseBase() { private val exceptions = ArrayList<Throwable>() protected open val captureExceptions = false protected fun testDataFile(fileName: String): File = File(testDataDirectory, fileName) protected fun testDataFile(): File = testDataFile(fileName()) protected fun testDataFilePath(): Path = testDataFile().toPath() protected fun testPath(fileName: String = fileName()): String = testDataFile(fileName).toString() protected fun testPath(): String = testPath(fileName()) protected open fun fileName(): String = KotlinTestUtils.getTestDataFileName(this::class.java, this.name) ?: (getTestName(false) + ".kt") @Deprecated("Migrate to 'testDataDirectory'.", ReplaceWith("testDataDirectory")) final override fun getTestDataPath(): String = testDataDirectory.slashedPath open val testDataDirectory: File by lazy { File(TestMetadataUtil.getTestDataPath(javaClass)) } override fun setUp() { super.setUp() enableKotlinOfficialCodeStyle(project) if (!isFirPlugin) { // We do it here to avoid possible initialization problems // UnusedSymbolInspection() calls IDEA UnusedDeclarationInspection() in static initializer, // which in turn registers some extensions provoking "modifications aren't allowed during highlighting" // when done lazily UnusedSymbolInspection() } VfsRootAccess.allowRootAccess(myFixture.testRootDisposable, KotlinRoot.DIR.path) EditorTracker.getInstance(project) if (!isFirPlugin) { invalidateLibraryCache(project) } } override fun runBare(testRunnable: ThrowableRunnable<Throwable>) { if (captureExceptions) { LoggedErrorProcessor.executeWith<RuntimeException>(object : LoggedErrorProcessor() { override fun processError(category: String, message: String?, t: Throwable?, details: Array<out String>): Boolean { exceptions.addIfNotNull(t) return super.processError(category, message, t, details) } }) { super.runBare(testRunnable) } } else { super.runBare(testRunnable) } } override fun tearDown() { runAll( ThrowableRunnable { disableKotlinOfficialCodeStyle(project) }, ThrowableRunnable { super.tearDown() }, ) if (exceptions.isNotEmpty()) { exceptions.forEach { it.printStackTrace() } throw AssertionError("Exceptions in other threads happened") } } override fun getProjectDescriptor(): LightProjectDescriptor = getProjectDescriptorFromFileDirective() protected fun getProjectDescriptorFromAnnotation(): LightProjectDescriptor { val testMethod = this::class.java.getDeclaredMethod(name) return when (testMethod.getAnnotation(ProjectDescriptorKind::class.java)?.value) { JDK_AND_MULTIPLATFORM_STDLIB_WITH_SOURCES -> KotlinJdkAndMultiplatformStdlibDescriptor.JDK_AND_MULTIPLATFORM_STDLIB_WITH_SOURCES KOTLIN_JVM_WITH_STDLIB_SOURCES -> ProjectDescriptorWithStdlibSources.INSTANCE KOTLIN_JAVASCRIPT -> KotlinStdJSProjectDescriptor KOTLIN_JVM_WITH_STDLIB_SOURCES_WITH_ADDITIONAL_JS -> { KotlinMultiModuleProjectDescriptor( KOTLIN_JVM_WITH_STDLIB_SOURCES_WITH_ADDITIONAL_JS, mainModuleDescriptor = ProjectDescriptorWithStdlibSources.INSTANCE, additionalModuleDescriptor = KotlinStdJSProjectDescriptor ) } KOTLIN_JAVASCRIPT_WITH_ADDITIONAL_JVM_WITH_STDLIB -> { KotlinMultiModuleProjectDescriptor( KOTLIN_JAVASCRIPT_WITH_ADDITIONAL_JVM_WITH_STDLIB, mainModuleDescriptor = KotlinStdJSProjectDescriptor, additionalModuleDescriptor = ProjectDescriptorWithStdlibSources.INSTANCE ) } else -> throw IllegalStateException("Unknown value for project descriptor kind") } } protected fun getProjectDescriptorFromTestName(): LightProjectDescriptor { val testName = StringUtil.toLowerCase(getTestName(false)) return when { testName.endsWith("runtime") -> KotlinWithJdkAndRuntimeLightProjectDescriptor.INSTANCE testName.endsWith("stdlib") -> ProjectDescriptorWithStdlibSources.INSTANCE else -> KotlinLightProjectDescriptor.INSTANCE } } protected fun getProjectDescriptorFromFileDirective(): LightProjectDescriptor { val file = mainFile() if (!file.exists()) { return KotlinLightProjectDescriptor.INSTANCE } try { val fileText = FileUtil.loadFile(file, true) val withLibraryDirective = InTextDirectivesUtils.findLinesWithPrefixesRemoved(fileText, "WITH_LIBRARY:") val minJavaVersion = InTextDirectivesUtils.findStringWithPrefixes(fileText, "MIN_JAVA_VERSION:")?.toInt() if (minJavaVersion != null && !(InTextDirectivesUtils.isDirectiveDefined(fileText, "RUNTIME") || InTextDirectivesUtils.isDirectiveDefined(fileText, "WITH_STDLIB")) ) { error("MIN_JAVA_VERSION so far is supported for RUNTIME/WITH_STDLIB only") } return when { withLibraryDirective.isNotEmpty() -> SdkAndMockLibraryProjectDescriptor(IDEA_TEST_DATA_DIR.resolve(withLibraryDirective[0]).path, true) InTextDirectivesUtils.isDirectiveDefined(fileText, "RUNTIME_WITH_SOURCES") -> ProjectDescriptorWithStdlibSources.INSTANCE InTextDirectivesUtils.isDirectiveDefined(fileText, "RUNTIME_WITHOUT_SOURCES") -> ProjectDescriptorWithStdlibSources.INSTANCE_NO_SOURCES InTextDirectivesUtils.isDirectiveDefined(fileText, "RUNTIME_WITH_KOTLIN_TEST") -> KotlinWithJdkAndRuntimeLightProjectDescriptor.INSTANCE_WITH_KOTLIN_TEST InTextDirectivesUtils.isDirectiveDefined(fileText, "RUNTIME_WITH_FULL_JDK") -> KotlinWithJdkAndRuntimeLightProjectDescriptor.INSTANCE_FULL_JDK InTextDirectivesUtils.isDirectiveDefined(fileText, "RUNTIME_WITH_JDK_10") -> KotlinWithJdkAndRuntimeLightProjectDescriptor.getInstance(LanguageLevel.JDK_10) InTextDirectivesUtils.isDirectiveDefined(fileText, "RUNTIME_WITH_REFLECT") -> KotlinWithJdkAndRuntimeLightProjectDescriptor.INSTANCE_WITH_REFLECT InTextDirectivesUtils.isDirectiveDefined(fileText, "RUNTIME_WITH_SCRIPT_RUNTIME") -> KotlinWithJdkAndRuntimeLightProjectDescriptor.INSTANCE_WITH_SCRIPT_RUNTIME InTextDirectivesUtils.isDirectiveDefined(fileText, "RUNTIME") || InTextDirectivesUtils.isDirectiveDefined(fileText, "WITH_STDLIB") -> if (minJavaVersion != null) { object : KotlinWithJdkAndRuntimeLightProjectDescriptor(INSTANCE.libraryFiles, INSTANCE.librarySourceFiles) { val sdkValue by lazy { sdk(minJavaVersion) } override fun getSdk(): Sdk = sdkValue } } else { KotlinWithJdkAndRuntimeLightProjectDescriptor.INSTANCE } InTextDirectivesUtils.isDirectiveDefined(fileText, "JS") -> KotlinStdJSProjectDescriptor InTextDirectivesUtils.isDirectiveDefined(fileText, "ENABLE_MULTIPLATFORM") -> KotlinProjectDescriptorWithFacet.KOTLIN_STABLE_WITH_MULTIPLATFORM else -> getDefaultProjectDescriptor() } } catch (e: IOException) { throw rethrow(e) } } protected open fun mainFile() = File(testDataDirectory, fileName()) private fun sdk(javaVersion: Int): Sdk = when (javaVersion) { 6 -> IdeaTestUtil.getMockJdk16() 8 -> IdeaTestUtil.getMockJdk18() 9 -> IdeaTestUtil.getMockJdk9() 11 -> { if (SystemInfo.isJavaVersionAtLeast(javaVersion, 0, 0)) { PluginTestCaseBase.fullJdk() } else { error("JAVA_HOME have to point at least to JDK 11") } } else -> error("Unsupported JDK version $javaVersion") } protected open fun getDefaultProjectDescriptor(): KotlinLightProjectDescriptor = KotlinLightProjectDescriptor.INSTANCE protected fun performNotWriteEditorAction(actionId: String): Boolean { val dataContext = (myFixture.editor as EditorEx).dataContext val managerEx = ActionManagerEx.getInstanceEx() val action = managerEx.getAction(actionId) val event = AnActionEvent(null, dataContext, ActionPlaces.UNKNOWN, Presentation(), managerEx, 0) if (ActionUtil.lastUpdateAndCheckDumb(action, event, false)) { ActionUtil.performActionDumbAwareWithCallbacks(action, event) return true } return false } fun JavaCodeInsightTestFixture.configureByFile(file: File): PsiFile { val relativePath = file.toRelativeString(testDataDirectory) return configureByFile(relativePath) } fun JavaCodeInsightTestFixture.checkResultByFile(file: File) { val relativePath = file.toRelativeString(testDataDirectory) checkResultByFile(relativePath) } } object CompilerTestDirectives { const val LANGUAGE_VERSION_DIRECTIVE = "LANGUAGE_VERSION:" const val API_VERSION_DIRECTIVE = "API_VERSION:" const val JVM_TARGET_DIRECTIVE = "JVM_TARGET:" const val COMPILER_ARGUMENTS_DIRECTIVE = "COMPILER_ARGUMENTS:" val ALL_COMPILER_TEST_DIRECTIVES = listOf(LANGUAGE_VERSION_DIRECTIVE, JVM_TARGET_DIRECTIVE, COMPILER_ARGUMENTS_DIRECTIVE) } fun <T> withCustomCompilerOptions(fileText: String, project: Project, module: Module, body: () -> T): T { val removeFacet = !module.hasKotlinFacet() val configured = configureCompilerOptions(fileText, project, module) try { return body() } finally { if (configured) { rollbackCompilerOptions(project, module, removeFacet) } } } private fun configureCompilerOptions(fileText: String, project: Project, module: Module): Boolean { val version = InTextDirectivesUtils.findStringWithPrefixes(fileText, "// $LANGUAGE_VERSION_DIRECTIVE ") val apiVersion = InTextDirectivesUtils.findStringWithPrefixes(fileText, "// $API_VERSION_DIRECTIVE ") val jvmTarget = InTextDirectivesUtils.findStringWithPrefixes(fileText, "// $JVM_TARGET_DIRECTIVE ") // We can have several such directives in quickFixMultiFile tests // TODO: refactor such tests or add sophisticated check for the directive val options = InTextDirectivesUtils.findListWithPrefixes(fileText, "// $COMPILER_ARGUMENTS_DIRECTIVE ").firstOrNull() if (version != null || apiVersion != null || jvmTarget != null || options != null) { configureLanguageAndApiVersion( project, module, version ?: LanguageVersion.LATEST_STABLE.versionString, apiVersion ) val facetSettings = KotlinFacet.get(module)!!.configuration.settings if (jvmTarget != null) { val compilerArguments = facetSettings.compilerArguments require(compilerArguments is K2JVMCompilerArguments) { "Attempt to specify `$JVM_TARGET_DIRECTIVE` for non-JVM test" } compilerArguments.jvmTarget = jvmTarget } if (options != null) { val compilerSettings = facetSettings.compilerSettings ?: CompilerSettings().also { facetSettings.compilerSettings = it } compilerSettings.additionalArguments = options facetSettings.updateMergedArguments() KotlinCompilerSettings.getInstance(project).update { this.additionalArguments = options } } return true } return false } fun configureRegistryAndRun(fileText: String, body: () -> Unit) { val registers = InTextDirectivesUtils.findListWithPrefixes(fileText, "// REGISTRY:") .map { it.split(' ') } .map { Registry.get(it.first()) to it.last() } try { for ((register, value) in registers) { register.setValue(value) } body() } finally { for ((register, _) in registers) { register.resetToDefault() } } } fun configureCodeStyleAndRun( project: Project, configurator: (CodeStyleSettings) -> Unit = { }, body: () -> Unit ) { val testSettings = CodeStyle.createTestSettings(CodeStyle.getSettings(project)) CodeStyle.doWithTemporarySettings(project, testSettings, Runnable { configurator(testSettings) body() }) } fun enableKotlinOfficialCodeStyle(project: Project) { val settings = CodeStyleSettingsManager.getInstance(project).createTemporarySettings() KotlinStyleGuideCodeStyle.apply(settings) CodeStyle.setTemporarySettings(project, settings) } fun disableKotlinOfficialCodeStyle(project: Project) { CodeStyle.dropTemporarySettings(project) } fun resetCodeStyle(project: Project) { val provider = KotlinLanguageCodeStyleSettingsProvider() CodeStyle.getSettings(project).apply { removeCommonSettings(provider) removeCustomSettings(provider) clearCodeStyleSettings() } } fun runAll( vararg actions: ThrowableRunnable<Throwable>, suppressedExceptions: List<Throwable> = emptyList() ) = RunAll(actions.toList()).run(suppressedExceptions) private fun rollbackCompilerOptions(project: Project, module: Module, removeFacet: Boolean) { KotlinCompilerSettings.getInstance(project).update { this.additionalArguments = DEFAULT_ADDITIONAL_ARGUMENTS } KotlinCommonCompilerArgumentsHolder.getInstance(project).update { this.languageVersion = LanguageVersion.LATEST_STABLE.versionString } if (removeFacet) { module.removeKotlinFacet(ProjectDataManager.getInstance().createModifiableModelsProvider(project), commitModel = true) return } configureLanguageAndApiVersion(project, module, LanguageVersion.LATEST_STABLE.versionString, ApiVersion.LATEST_STABLE.versionString) val facetSettings = KotlinFacet.get(module)!!.configuration.settings (facetSettings.compilerArguments as? K2JVMCompilerArguments)?.jvmTarget = JvmTarget.DEFAULT.description val compilerSettings = facetSettings.compilerSettings ?: CompilerSettings().also { facetSettings.compilerSettings = it } compilerSettings.additionalArguments = DEFAULT_ADDITIONAL_ARGUMENTS facetSettings.updateMergedArguments() } fun withCustomLanguageAndApiVersion( project: Project, module: Module, languageVersion: String, apiVersion: String?, body: () -> Unit ) { val removeFacet = !module.hasKotlinFacet() configureLanguageAndApiVersion(project, module, languageVersion, apiVersion) try { body() } finally { if (removeFacet) { KotlinCommonCompilerArgumentsHolder.getInstance(project) .update { this.languageVersion = LanguageVersion.LATEST_STABLE.versionString } module.removeKotlinFacet(ProjectDataManager.getInstance().createModifiableModelsProvider(project), commitModel = true) } else { configureLanguageAndApiVersion( project, module, LanguageVersion.LATEST_STABLE.versionString, ApiVersion.LATEST_STABLE.versionString ) } } } private fun configureLanguageAndApiVersion( project: Project, module: Module, languageVersion: String, apiVersion: String? ) { WriteAction.run<Throwable> { val modelsProvider = ProjectDataManager.getInstance().createModifiableModelsProvider(project) val facet = module.getOrCreateFacet(modelsProvider, useProjectSettings = false) val compilerArguments = facet.configuration.settings.compilerArguments if (compilerArguments != null) { compilerArguments.apiVersion = null } facet.configureFacet(languageVersion, null, modelsProvider, emptySet()) if (apiVersion != null) { facet.configuration.settings.apiLevel = LanguageVersion.fromVersionString(apiVersion) } KotlinCommonCompilerArgumentsHolder.getInstance(project).update { this.languageVersion = languageVersion } modelsProvider.commit() } } fun Project.allKotlinFiles(): List<KtFile> { val virtualFiles = FileTypeIndex.getFiles(KotlinFileType.INSTANCE, ProjectScope.getProjectScope(this)) return virtualFiles .map { PsiManager.getInstance(this).findFile(it) } .filterIsInstance<KtFile>() } fun Project.allJavaFiles(): List<PsiJavaFile> { val virtualFiles = FileTypeIndex.getFiles(JavaFileType.INSTANCE, ProjectScope.getProjectScope(this)) return virtualFiles .map { PsiManager.getInstance(this).findFile(it) } .filterIsInstance<PsiJavaFile>() } fun Project.findFileWithCaret(): PsiClassOwner { return (allKotlinFiles() + allJavaFiles()).single { "<caret>" in VfsUtilCore.loadText(it.virtualFile) && !it.virtualFile.name.endsWith(".after") } } fun createTextEditorBasedDataContext( project: Project, editor: Editor, caret: Caret, additionalSteps: SimpleDataContext.Builder.() -> SimpleDataContext.Builder = { this }, ): DataContext { val textEditorPsiDataProvider = TextEditorPsiDataProvider() val parentContext = DataContext { dataId -> textEditorPsiDataProvider.getData(dataId, editor, caret) } return SimpleDataContext.builder() .add(CommonDataKeys.PROJECT, project) .add(CommonDataKeys.EDITOR, editor) .additionalSteps() .setParent(parentContext) .build() }
apache-2.0
4b500d1066d4996f3cf4babfacf2fe5b
41.658869
158
0.711799
5.527658
false
true
false
false
smmribeiro/intellij-community
platform/lang-impl/src/com/intellij/navigation/NavigatorWithinProject.kt
4
10319
// 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.navigation import com.intellij.ide.IdeBundle import com.intellij.ide.RecentProjectListActionProvider import com.intellij.ide.RecentProjectsManagerBase import com.intellij.ide.ReopenProjectAction import com.intellij.ide.actions.searcheverywhere.SymbolSearchEverywhereContributor import com.intellij.ide.impl.OpenProjectTask import com.intellij.ide.impl.ProjectUtil import com.intellij.ide.impl.getProjectOriginUrl import com.intellij.openapi.actionSystem.ActionPlaces import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.actionSystem.impl.SimpleDataContext import com.intellij.openapi.application.* import com.intellij.openapi.editor.Editor import com.intellij.openapi.editor.ScrollType import com.intellij.openapi.fileEditor.FileEditorManager import com.intellij.openapi.fileEditor.TextEditor import com.intellij.openapi.progress.EmptyProgressIndicator import com.intellij.openapi.progress.ProgressIndicator import com.intellij.openapi.progress.ProgressManager import com.intellij.openapi.progress.Task import com.intellij.openapi.project.Project import com.intellij.openapi.project.guessProjectDir import com.intellij.openapi.roots.ProjectRootManager import com.intellij.openapi.startup.StartupManager import com.intellij.openapi.util.Disposer import com.intellij.openapi.util.io.FileUtil import com.intellij.openapi.vfs.VirtualFile import com.intellij.openapi.vfs.VirtualFileManager import com.intellij.openapi.wm.IdeFocusManager import com.intellij.psi.PsiElement import com.intellij.util.PsiNavigateUtil import com.intellij.util.containers.ComparatorUtil.max import com.intellij.util.text.nullize import java.io.File import java.nio.file.Path import java.util.concurrent.CompletableFuture import java.util.regex.Pattern const val NAVIGATE_COMMAND = "navigate" const val REFERENCE_TARGET = "reference" const val PROJECT_NAME_KEY = "project" const val ORIGIN_URL_KEY = "origin" const val SELECTION = "selection" fun openProject(parameters: Map<String, String>): CompletableFuture<Project?> { val projectName = parameters[PROJECT_NAME_KEY]?.nullize(nullizeSpaces = true) val originUrl = parameters[ORIGIN_URL_KEY]?.nullize(nullizeSpaces = true) if (projectName == null && originUrl == null) { return CompletableFuture.failedFuture(IllegalArgumentException(IdeBundle.message("jb.protocol.navigate.missing.parameters"))) } val openProject = ProjectUtil.getOpenProjects().find { projectName != null && it.name == projectName || originUrl != null && areOriginsEqual(originUrl, getProjectOriginUrl(it.guessProjectDir()?.toNioPath())) } if (openProject != null) { return CompletableFuture.completedFuture(openProject) } val recentProjectAction = RecentProjectListActionProvider.getInstance().getActions().asSequence() .filterIsInstance(ReopenProjectAction::class.java) .find { projectName != null && it.projectName == projectName || originUrl != null && areOriginsEqual(originUrl, getProjectOriginUrl(Path.of(it.projectPath))) } if (recentProjectAction == null) { return CompletableFuture.completedFuture(null) } val result = CompletableFuture<Project?>() RecentProjectsManagerBase.instanceEx .openProject(Path.of(recentProjectAction.projectPath), OpenProjectTask()) .thenAccept { project -> when (project) { null -> result.complete(null) else -> { ApplicationManager.getApplication().invokeLater({ if (project.isDisposed) result.complete(null) else { StartupManager.getInstance(project).runAfterOpened { result.complete(project) } } }, ModalityState.NON_MODAL) } } } return result } data class LocationInFile(val line: Int, val column: Int) typealias LocationToOffsetConverter = (LocationInFile, Editor) -> Int class NavigatorWithinProject(val project: Project, val parameters: Map<String, String>, locationToOffset_: LocationToOffsetConverter) { companion object { private const val FILE_PROTOCOL = "file://" private const val PATH_GROUP = "path" private const val LINE_GROUP = "line" private const val COLUMN_GROUP = "column" private const val REVISION = "revision" private val PATH_WITH_LOCATION = Pattern.compile("(?<${PATH_GROUP}>[^:]+)(:(?<${LINE_GROUP}>[\\d]+))?(:(?<${COLUMN_GROUP}>[\\d]+))?") fun parseNavigationPath(pathText: String): Triple<String?, String?, String?> { val matcher = PATH_WITH_LOCATION.matcher(pathText) return if (!matcher.matches()) Triple(null, null, null) else Triple(matcher.group(PATH_GROUP), matcher.group(LINE_GROUP), matcher.group(COLUMN_GROUP)) } private fun parseLocationInFile(range: String): LocationInFile? { val position = range.split(':') return if (position.size != 2) null else try { LocationInFile(position[0].toInt(), position[1].toInt()) } catch (e: Exception) { null } } } val locationToOffset: LocationToOffsetConverter = { locationInFile, editor -> max(locationToOffset_(locationInFile, editor), 0) } enum class NavigationKeyPrefix(val prefix: String) { FQN("fqn"), PATH("path"); override fun toString() = prefix } private val navigatorByKeyPrefix = mapOf( (NavigationKeyPrefix.FQN to this::navigateByFqn), (NavigationKeyPrefix.PATH to this::navigateByPath) ) private val selections by lazy { parseSelections() } fun navigate(keysPrefixesToNavigate: List<NavigationKeyPrefix>) { keysPrefixesToNavigate.forEach { keyPrefix -> parameters.filterKeys { it.startsWith(keyPrefix.prefix) }.values.forEach { navigatorByKeyPrefix[keyPrefix]?.invoke(it) } } } private fun navigateByFqn(reference: String) { // handle single reference to method: com.intellij.navigation.JBProtocolNavigateCommand#perform // multiple references are encoded and decoded properly val fqn = parameters[JBProtocolCommand.FRAGMENT_PARAM_NAME]?.let { "$reference#$it" } ?: reference runNavigateTask(reference) { val dataContext = SimpleDataContext.getProjectContext(project) val searcher = invokeAndWaitIfNeeded { SymbolSearchEverywhereContributor(AnActionEvent.createFromDataContext(ActionPlaces.UNKNOWN, null, dataContext)) } Disposer.register(project, searcher) try { searcher.search(fqn, EmptyProgressIndicator()) .filterIsInstance<PsiElement>() .forEach { invokeLater { PsiNavigateUtil.navigate(it) makeSelectionsVisible() } } } finally { Disposer.dispose(searcher) } } } private fun navigateByPath(pathText: String) { var (path, line, column) = parseNavigationPath(pathText) if (path == null) { return } val locationInFile = LocationInFile(line?.toInt() ?: 0, column?.toInt() ?: 0) path = FileUtil.expandUserHome(path) runNavigateTask(pathText) { val virtualFile: VirtualFile if (FileUtil.isAbsolute(path)) virtualFile = findFile(path, parameters[REVISION]) ?: return@runNavigateTask else virtualFile = (sequenceOf(project.guessProjectDir()?.path, project.basePath) + ProjectRootManager.getInstance(project).contentRoots.map { it.path }) .filterNotNull() .mapNotNull { projectPath -> findFile(File(projectPath, path).absolutePath, parameters[REVISION]) } .firstOrNull() ?: return@runNavigateTask ApplicationManager.getApplication().invokeLater { FileEditorManager.getInstance(project).openFile(virtualFile, true) .filterIsInstance<TextEditor>().first().let { textEditor -> performEditorAction(textEditor, locationInFile) } } } } private fun runNavigateTask(reference: String, task: (indicator: ProgressIndicator) -> Unit) { ProgressManager.getInstance().run( object : Task.Backgroundable(project, IdeBundle.message("navigate.command.search.reference.progress.title", reference), true) { override fun run(indicator: ProgressIndicator) { task.invoke(indicator) } override fun shouldStartInBackground(): Boolean = !ApplicationManager.getApplication().isUnitTestMode override fun isConditionalModal(): Boolean = !ApplicationManager.getApplication().isUnitTestMode } ) } private fun performEditorAction(textEditor: TextEditor, locationInFile: LocationInFile) { val editor = textEditor.editor editor.caretModel.removeSecondaryCarets() editor.caretModel.moveToOffset(locationToOffset(locationInFile, editor)) editor.scrollingModel.scrollToCaret(ScrollType.CENTER) editor.selectionModel.removeSelection() IdeFocusManager.getGlobalInstance().requestFocus(editor.contentComponent, true) makeSelectionsVisible() } private fun makeSelectionsVisible() { val editor = FileEditorManager.getInstance(project).selectedTextEditor selections.forEach { editor?.selectionModel?.setSelection( locationToOffset(it.first, editor), locationToOffset(it.second, editor) ) } } private fun findFile(absolutePath: String?, revision: String?): VirtualFile? { absolutePath ?: return null if (revision != null) { val virtualFile = JBProtocolRevisionResolver.processResolvers(project, absolutePath, revision) if (virtualFile != null) return virtualFile } return VirtualFileManager.getInstance().findFileByUrl(FILE_PROTOCOL + absolutePath) } private fun parseSelections(): List<Pair<LocationInFile, LocationInFile>> = parameters.filterKeys { it.startsWith(SELECTION) }.values.mapNotNull { val split = it.split('-') if (split.size != 2) return@mapNotNull null val startLocation = parseLocationInFile(split[0]) val endLocation = parseLocationInFile(split[1]) if (startLocation != null && endLocation != null) { return@mapNotNull Pair(startLocation, startLocation) } return@mapNotNull null } }
apache-2.0
fc3516202aad54a7f85f7ffbbe71b0a6
39.151751
158
0.722841
4.740009
false
false
false
false
Flank/flank
test_runner/src/main/kotlin/ftl/presentation/cli/firebase/test/android/orientations/AndroidOrientationsListCommand.kt
1
1272
package ftl.presentation.cli.firebase.test.android.orientations import ftl.api.Orientation import ftl.config.FtlConstants import ftl.domain.ListAndroidOrientations import ftl.domain.invoke import ftl.presentation.outputLogger import ftl.presentation.throwUnknownType import ftl.util.PrintHelpCommand import ftl.util.asListOrNull import picocli.CommandLine @CommandLine.Command( name = "list", headerHeading = "", synopsisHeading = "%n", descriptionHeading = "%n@|bold,underline Description:|@%n%n", parameterListHeading = "%n@|bold,underline Parameters:|@%n", optionListHeading = "%n@|bold,underline Options:|@%n", header = ["List of device orientations available to test against"], description = ["Print current list of Android orientations available to test against"], usageHelpAutoWidth = true ) class AndroidOrientationsListCommand : PrintHelpCommand(), ListAndroidOrientations { @CommandLine.Option( names = ["-c", "--config"], description = ["YAML config file path"] ) override var configPath: String = FtlConstants.defaultAndroidConfig override fun run() = invoke() override val out = outputLogger { asListOrNull<Orientation>()?.toCliTable() ?: throwUnknownType() } }
apache-2.0
c1ef72dacaa3a7731cc1888a545cd698
31.615385
91
0.728774
4.386207
false
true
false
false
jotomo/AndroidAPS
app/src/main/java/info/nightscout/androidaps/plugins/general/openhumans/OpenHumansAPI.kt
1
6908
package info.nightscout.androidaps.plugins.general.openhumans import android.annotation.SuppressLint import android.util.Base64 import io.reactivex.Completable import io.reactivex.Single import io.reactivex.disposables.Disposables import okhttp3.* import okio.BufferedSink import org.json.JSONArray import org.json.JSONObject import java.io.IOException import java.text.SimpleDateFormat import java.util.* class OpenHumansAPI( private val baseUrl: String, clientId: String, clientSecret: String, private val redirectUri: String ) { private val authHeader = "Basic " + Base64.encodeToString("$clientId:$clientSecret".toByteArray(), Base64.NO_WRAP) private val client = OkHttpClient() fun exchangeAuthToken(code: String): Single<OAuthTokens> = sendTokenRequest(FormBody.Builder() .add("grant_type", "authorization_code") .add("redirect_uri", redirectUri) .add("code", code) .build()) fun refreshAccessToken(refreshToken: String): Single<OAuthTokens> = sendTokenRequest(FormBody.Builder() .add("grant_type", "refresh_token") .add("redirect_uri", redirectUri) .add("refresh_token", refreshToken) .build()) private fun sendTokenRequest(body: FormBody) = Request.Builder() .url("$baseUrl/oauth2/token/") .addHeader("Authorization", authHeader) .post(body) .build() .toSingle() .map { response -> response.use { _ -> val responseBody = response.body val jsonObject = responseBody?.let { JSONObject(it.string()) } if (!response.isSuccessful) throw OHHttpException(response.code, response.message, jsonObject?.getString("error")) if (jsonObject == null) throw OHHttpException(response.code, response.message, "No body") if (!jsonObject.has("expires_in")) throw OHMissingFieldException("expires_in") OAuthTokens( accessToken = jsonObject.getString("access_token") ?: throw OHMissingFieldException("access_token"), refreshToken = jsonObject.getString("refresh_token") ?: throw OHMissingFieldException("refresh_token"), expiresAt = response.sentRequestAtMillis + jsonObject.getInt("expires_in") * 1000L ) } } fun getProjectMemberId(accessToken: String): Single<String> = Request.Builder() .url("$baseUrl/api/direct-sharing/project/exchange-member/?access_token=$accessToken") .get() .build() .toSingle() .map { it.jsonBody.getString("project_member_id") ?: throw OHMissingFieldException("project_member_id") } fun prepareFileUpload(accessToken: String, fileName: String, metadata: FileMetadata): Single<PreparedUpload> = Request.Builder() .url("$baseUrl/api/direct-sharing/project/files/upload/direct/?access_token=$accessToken") .post(FormBody.Builder() .add("filename", fileName) .add("metadata", metadata.toJSON().toString()) .build()) .build() .toSingle() .map { val json = it.jsonBody PreparedUpload( fileId = json.getString("id") ?: throw OHMissingFieldException("id"), uploadURL = json.getString("url") ?: throw OHMissingFieldException("url") ) } fun uploadFile(url: String, content: ByteArray): Completable = Request.Builder() .url(url) .put(object : RequestBody() { override fun contentType(): MediaType? = null override fun contentLength() = content.size.toLong() override fun writeTo(sink: BufferedSink) { sink.write(content) } }) .build() .toSingle() .doOnSuccess { response -> response.use { _ -> if (!response.isSuccessful) throw OHHttpException(response.code, response.message, null) } } .ignoreElement() fun completeFileUpload(accessToken: String, fileId: String): Completable = Request.Builder() .url("$baseUrl/api/direct-sharing/project/files/upload/complete/?access_token=$accessToken") .post(FormBody.Builder() .add("file_id", fileId) .build()) .build() .toSingle() .doOnSuccess { it.jsonBody } .ignoreElement() private fun Request.toSingle() = Single.create<Response> { val call = client.newCall(this) call.enqueue(object : Callback { override fun onFailure(call: Call, e: IOException) { it.tryOnError(e) } override fun onResponse(call: Call, response: Response) { it.onSuccess(response) } }) it.setDisposable(Disposables.fromRunnable { call.cancel() }) } private val Response.jsonBody get() = use { _ -> val jsonObject = body?.let { JSONObject(it.string()) } ?: throw OHHttpException(code, message, null) if (!isSuccessful) throw OHHttpException(code, message, jsonObject.getString("detail")) jsonObject } data class OAuthTokens( val accessToken: String, val refreshToken: String, val expiresAt: Long ) data class FileMetadata( val tags: List<String>, val description: String, val md5: String? = null, val creationDate: Long? = null, val startDate: Long? = null, val endDate: Long? = null ) { fun toJSON(): JSONObject { val jsonObject = JSONObject() jsonObject.put("tags", JSONArray().apply { tags.forEach { put(it) } }) jsonObject.put("description", description) jsonObject.put("md5", md5) creationDate?.let { jsonObject.put("creation_date", iso8601DateFormatter.format(Date(it))) } startDate?.let { jsonObject.put("start_date", iso8601DateFormatter.format(Date(it))) } endDate?.let { jsonObject.put("end_date", iso8601DateFormatter.format(Date(it))) } return jsonObject } } data class PreparedUpload( val fileId: String, val uploadURL: String ) data class OHHttpException( val code: Int, val meaning: String, val detail: String? ) : RuntimeException() { override val message: String get() = toString() } data class OHMissingFieldException( val name: String ) : RuntimeException() { override val message: String get() = toString() } companion object { @SuppressLint("SimpleDateFormat") private val iso8601DateFormatter = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX") } }
agpl-3.0
d74761f3652d93f02d2e1b444670e074
35.172775
132
0.604227
4.70893
false
false
false
false
siosio/intellij-community
plugins/kotlin/fir-low-level-api/src/org/jetbrains/kotlin/idea/fir/low/level/api/trackers/KotlinFirOutOfBlockModificationTrackerFactory.kt
1
1844
/* * Copyright 2010-2020 JetBrains s.r.o. and Kotlin Programming Language contributors. * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.fir.low.level.api.trackers import com.intellij.openapi.components.service import com.intellij.openapi.module.Module import com.intellij.openapi.project.Project import com.intellij.openapi.util.ModificationTracker import org.jetbrains.annotations.TestOnly import org.jetbrains.kotlin.trackers.KotlinOutOfBlockModificationTrackerFactory class KotlinFirOutOfBlockModificationTrackerFactory(private val project: Project) : KotlinOutOfBlockModificationTrackerFactory() { override fun createProjectWideOutOfBlockModificationTracker(): ModificationTracker = KotlinFirOutOfBlockModificationTracker(project) override fun createModuleWithoutDependenciesOutOfBlockModificationTracker(module: Module): ModificationTracker = KotlinFirOutOfBlockModuleModificationTracker(module) @TestOnly fun incrementModificationsCount() { project.service<KotlinFirModificationTrackerService>().increaseModificationCountForAllModules() } } private class KotlinFirOutOfBlockModificationTracker(project: Project) : ModificationTracker { private val trackerService = project.service<KotlinFirModificationTrackerService>() override fun getModificationCount(): Long = trackerService.projectGlobalOutOfBlockInKotlinFilesModificationCount } private class KotlinFirOutOfBlockModuleModificationTracker(private val module: Module) : ModificationTracker { private val trackerService = module.project.service<KotlinFirModificationTrackerService>() override fun getModificationCount(): Long = trackerService.getOutOfBlockModificationCountForModules(module) }
apache-2.0
9bc0483b94209d77825fa77207df15ea
45.125
130
0.827007
5.891374
false
true
false
false
siosio/intellij-community
plugins/kotlin/gradle/gradle-tooling/src/KotlinCommonizerModelBuilder.kt
1
2507
// 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.gradle import org.gradle.api.Project import org.gradle.api.logging.Logging import org.jetbrains.plugins.gradle.tooling.AbstractModelBuilderService import org.jetbrains.plugins.gradle.tooling.ErrorMessageBuilder import org.jetbrains.plugins.gradle.tooling.ModelBuilderContext interface EnableCommonizerTask class KotlinCommonizerModelBuilder : AbstractModelBuilderService() { companion object { private const val COMMONIZER_TASK_NAME = "runCommonizer" private const val COMMONIZER_SETUP_CLASS = "org.jetbrains.kotlin.gradle.targets.native.internal.KotlinNativePlatformDependenciesKt" } override fun canBuild(modelName: String?): Boolean { return EnableCommonizerTask::class.java.name == modelName } override fun buildAll(modelName: String, project: Project, context: ModelBuilderContext): Any? { val kotlinExt = project.extensions.findByName("kotlin") ?: return null try { val classLoader = kotlinExt.javaClass.classLoader val clazz = try { Class.forName(COMMONIZER_SETUP_CLASS, false, classLoader) } catch (e: ClassNotFoundException) { //It can be old version mpp gradle plugin. Supported only 1.4+ return null } val isAllowCommonizerFun = clazz.getMethodOrNull("isAllowCommonizer", Project::class.java) ?: return null val isAllowCommonizer = isAllowCommonizerFun.invoke(Boolean::class.java, project) as Boolean if (isAllowCommonizer) { val startParameter = project.gradle.startParameter val tasks = HashSet(startParameter.taskNames) if (!tasks.contains(COMMONIZER_TASK_NAME)) { tasks.add(COMMONIZER_TASK_NAME) startParameter.setTaskNames(tasks) } } } catch (e: Exception) { project.logger.error( getErrorMessageBuilder(project, e).build() ) } return null } override fun getErrorMessageBuilder(project: Project, e: Exception): ErrorMessageBuilder { return ErrorMessageBuilder.create( project, e, "EnableCommonizerTask error" ).withDescription("Unable to create $COMMONIZER_TASK_NAME task.") } }
apache-2.0
15977f5bb178bb52cb08d68c2ea57576
40.098361
158
0.673714
4.867961
false
false
false
false
siosio/intellij-community
platform/build-scripts/icons/src/org/jetbrains/intellij/build/images/ImageSvgPreCompiler.kt
1
10224
// 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.intellij.build.images import com.intellij.openapi.util.text.Formats import com.intellij.ui.svg.ImageValue import com.intellij.ui.svg.SvgCacheManager import com.intellij.ui.svg.SvgTranscoder import com.intellij.ui.svg.createSvgDocument import com.intellij.util.ImageLoader import com.intellij.util.io.DigestUtil import org.apache.batik.transcoder.TranscoderException import org.jetbrains.jps.model.java.JpsJavaExtensionService import org.jetbrains.jps.model.module.JpsModule import org.jetbrains.mvstore.MVMap import org.jetbrains.mvstore.MVStore import org.jetbrains.mvstore.type.LongDataType import java.awt.image.BufferedImage import java.nio.file.* import java.util.concurrent.ConcurrentHashMap import java.util.concurrent.ConcurrentLinkedQueue import java.util.concurrent.atomic.AtomicLong import kotlin.system.exitProcess private class FileInfo(val file: Path) { companion object { fun digest(file: Path) = digest(loadAndNormalizeSvgFile(file).toByteArray()) fun digest(fileNormalizedData: ByteArray): ByteArray = DigestUtil.sha256().digest(fileNormalizedData) } val checksum: ByteArray by lazy { digest(file) } } /** * Works together with [SvgCacheManager] to generate pre-cached icons */ internal class ImageSvgPreCompiler { /// the expected scales of images that we have /// the macOS touch bar uses 2.5x scale /// the application icon (which one?) is 4x on macOS private val scales = floatArrayOf(1f, 1.25f, /*Windows*/ 1.5f, /*Windows*/ 2.0f, 2.5f /*macOS touchBar*/ ) /// the 4.0 scale is used on retina macOS for product icon, adds few more scales for few icons //private val productIconScales = (scales + scales.map { it * 2 }).toSortedSet().toFloatArray() //private val productIconPrefixes = mutableListOf<String>() private val totalFiles = AtomicLong(0) private val collisionGuard = ConcurrentHashMap<Long, FileInfo>() // System.out is blocking and can lead to deadlock private val errorMessages = ConcurrentLinkedQueue<String>() companion object { @JvmStatic fun main(args: Array<String>) { try { mainImpl(args) } catch (e: Throwable) { System.err.println("Unexpected crash: ${e.message}") e.printStackTrace(System.err) exitProcess(1) } exitProcess(0) } private fun mainImpl(args: Array<String>) { println("Pre-building SVG images...") if (args.isEmpty()) { println("Usage: <tool> dbFile tasks_file product_icons*") println("") println("tasks_file: list of paths, every path on a new line: {<input dir>\\n}+") println("") exitProcess(1) } System.setProperty("java.awt.headless", "true") val dbFile = args.getOrNull(0) ?: error("only one parameter is supported") val argsFile = args.getOrNull(1) ?: error("only one parameter is supported") val dirs = Files.readAllLines(Paths.get(argsFile)).map { Paths.get(it) } val productIcons = args.drop(2).toSortedSet() println("Expecting product icons: $productIcons") val compiler = ImageSvgPreCompiler() // todo //productIcons.forEach(compiler::addProductIconPrefix) compiler.compileIcons(Paths.get(dbFile), dirs) } } fun preCompileIcons(modules: List<JpsModule>, dbFile: Path) { val javaExtensionService = JpsJavaExtensionService.getInstance() compileIcons(dbFile, modules.mapNotNull { javaExtensionService.getOutputDirectory(it, false)?.toPath() }) } fun compileIcons(dbFile: Path, dirs: List<Path>) { val storeBuilder = MVStore.Builder() .autoCommitBufferSize(128_1024) .backgroundExceptionHandler { e, _ -> throw e } .compressionLevel(2) val store = storeBuilder.truncateAndOpen(dbFile) try { val scaleToMap = ConcurrentHashMap<Float, MVMap<Long, ImageValue>>(scales.size * 2, 0.75f, 2) val mapBuilder = MVMap.Builder<Long, ImageValue>() mapBuilder.keyType(LongDataType.INSTANCE) mapBuilder.valueType(ImageValue.ImageValueSerializer()) val getMapByScale: (scale: Float, isDark: Boolean) -> MutableMap<Long, ImageValue> = { k, isDark -> SvgCacheManager.getMap(k, isDark, scaleToMap, store, mapBuilder) } val rootRobotData = IconRobotsData(parent = null, ignoreSkipTag = false, usedIconsRobots = null) dirs.parallelStream().forEach { dir -> processDir(dir, dir, 1, rootRobotData, getMapByScale) } System.err.println(errorMessages.joinToString(separator = "\n")) } finally { println("Saving rasterized SVG database (${totalFiles.get()} icons)...") store.close() println("Saved rasterized SVG database (size=${Formats.formatFileSize(Files.size(dbFile))}, path=$dbFile)") } } private fun processDir(dir: Path, rootDir: Path, level: Int, rootRobotData: IconRobotsData, getMapByScale: (scale: Float, isDark: Boolean) -> MutableMap<Long, ImageValue>) { val stream = try { Files.newDirectoryStream(dir) } catch (e: NotDirectoryException) { return } catch (e: NoSuchFileException) { return } var idToVariants: MutableMap<String, MutableList<Path>>? = null stream.use { val robotData = rootRobotData.fork(dir, dir) for (file in stream) { val fileName = file.fileName.toString() if (level == 1) { if (isBlacklistedTopDirectory(fileName)) { continue } } if (robotData.isSkipped(file)) { continue } if (fileName.endsWith(".svg")) { if (idToVariants == null) { idToVariants = HashMap() } idToVariants!!.computeIfAbsent(getImageCommonName(fileName)) { mutableListOf() }.add(file) } else if (!fileName.endsWith(".class")) { processDir(file, rootDir, level + 1, rootRobotData.fork(file, rootDir), getMapByScale) } } } val idToVariants1 = idToVariants ?: return val keys = idToVariants1.keys.toTypedArray() keys.sort() val dimension = ImageLoader.Dimension2DDouble(0.0, 0.0) for (commonName in keys) { val variants = idToVariants1.getValue(commonName) variants.sort() try { processImage(variants, getMapByScale, dimension) } catch (e: TranscoderException) { throw RuntimeException("Cannot process $commonName (variants=$variants)", e) } } } private fun processImage(variants: List<Path>, getMapByScale: (scale: Float, isDark: Boolean) -> MutableMap<Long, ImageValue>, // just to reuse dimension: ImageLoader.Dimension2DDouble) { //println("$id: ${variants.joinToString { rootDir.relativize(it).toString() }}") val light1x = variants[0] val light1xPath = light1x.toString() if (light1xPath.endsWith("@2x.svg") || light1xPath.endsWith("_dark.svg")) { throw IllegalStateException("$light1x doesn't have 1x light icon") } val light1xData = loadAndNormalizeSvgFile(light1x) if (light1xData.contains("data:image")) { println("WARN: image $light1x uses data urls and will be skipped") return } totalFiles.addAndGet(variants.size.toLong()) // key is the same for all variants val light1xBytes = light1xData.toByteArray() val imageKey = getImageKey(light1xBytes, light1x.fileName.toString()) if (checkCollision(imageKey, light1x, light1xBytes)) { return } val light2x = variants.find { it.toString().endsWith("@2x.svg") } for (scale in scales) { val document = createSvgDocument(null, if (scale >= 2 && light2x != null) Files.newInputStream(light2x) else light1xData.byteInputStream()) addEntry(getMapByScale(scale, false), SvgTranscoder.createImage(scale, document, dimension), dimension, light1x, imageKey) } val dark2x = variants.find { it.toString().endsWith("@2x_dark.svg") } val dark1x = variants.find { it !== dark2x && it.toString().endsWith("_dark.svg") } ?: return for (scale in scales) { val document = createSvgDocument(null, Files.newInputStream(if (scale >= 2 && dark2x != null) dark2x else dark1x)) val image = SvgTranscoder.createImage(scale, document, dimension) addEntry(getMapByScale(scale, true), image, dimension, dark1x, imageKey) } } private fun checkCollision(imageKey: Long, file: Path, fileNormalizedData: ByteArray): Boolean { val duplicate = collisionGuard.putIfAbsent(imageKey, FileInfo(file)) if (duplicate == null) { return false } if (duplicate.checksum.contentEquals(FileInfo.digest(fileNormalizedData))) { errorMessages.add("${duplicate.file} duplicates $file") // skip - do not add return true } throw IllegalStateException("Hash collision:\n file1=${duplicate.file},\n file2=${file},\n imageKey=$imageKey") } } private fun addEntry(map: MutableMap<Long, ImageValue>, image: BufferedImage, dimension: ImageLoader.Dimension2DDouble, file: Path, imageKey: Long) { val newValue = SvgCacheManager.writeImage(image, dimension) //println("put ${(map as MVMap).id} $file : $imageKey") val oldValue = map.putIfAbsent(imageKey, newValue) // duplicated images - not yet clear should be forbid it or not if (oldValue != null && oldValue != newValue) { throw IllegalStateException("Hash collision for key $file (imageKey=$imageKey)") } } private fun getImageCommonName(fileName: String): String { for (p in listOf("@2x.svg", "@2x_dark.svg", "_dark.svg", ".svg")) { if (fileName.endsWith(p)) { return fileName.substring(0, fileName.length - p.length) } } throw IllegalStateException("Not a SVG: $fileName") }
apache-2.0
738a3c2c183faf213dbbdcb00cf78269
36.047101
145
0.658842
4.152721
false
false
false
false
jwren/intellij-community
plugins/ide-features-trainer/src/training/learn/lesson/general/assistance/LocalHistoryLesson.kt
4
15171
// 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 training.learn.lesson.general.assistance import com.intellij.CommonBundle import com.intellij.history.integration.ui.actions.LocalHistoryGroup import com.intellij.history.integration.ui.actions.ShowHistoryAction import com.intellij.icons.AllIcons import com.intellij.idea.ActionsBundle import com.intellij.openapi.actionSystem.CommonDataKeys import com.intellij.openapi.actionSystem.DataProvider import com.intellij.openapi.actionSystem.IdeActions import com.intellij.openapi.actionSystem.impl.ActionMenu import com.intellij.openapi.actionSystem.impl.ActionMenuItem import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.application.ModalityState import com.intellij.openapi.application.invokeAndWaitIfNeeded import com.intellij.openapi.application.invokeLater import com.intellij.openapi.editor.Editor import com.intellij.openapi.editor.EditorModificationUtil import com.intellij.openapi.editor.LogicalPosition import com.intellij.openapi.editor.ex.EditorEx import com.intellij.openapi.editor.ex.EditorGutterComponentEx import com.intellij.openapi.editor.impl.EditorComponentImpl import com.intellij.openapi.fileEditor.FileDocumentManager import com.intellij.openapi.progress.runBackgroundableTask import com.intellij.openapi.project.Project import com.intellij.openapi.ui.Messages import com.intellij.openapi.ui.popup.Balloon import com.intellij.openapi.util.io.FileUtil import com.intellij.ui.components.JBLoadingPanel import com.intellij.ui.components.JBLoadingPanelListener import com.intellij.ui.table.JBTable import com.intellij.ui.tabs.impl.SingleHeightTabs import com.intellij.util.DocumentUtil import com.intellij.util.concurrency.annotations.RequiresBackgroundThread import com.intellij.util.ui.UIUtil import org.assertj.swing.core.MouseButton import org.assertj.swing.data.TableCell import org.assertj.swing.fixture.JTableFixture import org.jetbrains.annotations.Nls import training.FeaturesTrainerIcons import training.dsl.* import training.dsl.LessonUtil.restoreIfModifiedOrMoved import training.learn.LearnBundle import training.learn.LessonsBundle import training.learn.course.KLesson import training.learn.course.LessonProperties import training.learn.course.LessonType import training.learn.lesson.LessonManager import training.ui.LearningUiHighlightingManager import training.ui.LearningUiHighlightingManager.HighlightingOptions import training.ui.LearningUiUtil import training.util.LessonEndInfo import java.awt.Component import java.awt.Point import java.awt.Rectangle import java.util.concurrent.CompletableFuture import javax.swing.JFrame class LocalHistoryLesson : KLesson("CodeAssistance.LocalHistory", LessonsBundle.message("local.history.lesson.name")) { override val languageId = "yaml" override val lessonType = LessonType.SCRATCH override val properties = LessonProperties(availableSince = "212.5284") private val lineToDelete = 14 private val revisionInd = 2 private val sample = parseLessonSample(""" cat: name: Pelmen gender: male breed: sphinx fur_type: hairless fur_pattern: solid fur_colors: [ white ] tail_length: long eyes_colors: [ green ] favourite_things: - three plaids - pile of clothes - castle of boxes - toys scattered all over the place behavior: - play: condition: boring actions: - bring one of the favourite toys to the human - run all over the house - eat: condition: want to eat actions: - shout to the whole house - sharpen claws by the sofa - wake up a human in the middle of the night""".trimIndent()) private val textToDelete = """ | - play: | condition: boring | actions: | - bring one of the favourite toys to the human | - run all over the house """.trimMargin() private val textAfterDelete = """ | behavior: | | - eat: """.trimMargin() private val textToAppend = """ | - sleep: | condition: want to sleep | action: | - bury himself in a human's blanket | - bury himself in a favourite plaid """.trimMargin() override val lessonContent: LessonContext.() -> Unit = { prepareSample(sample) caret(textToDelete, select = true) prepareRuntimeTask(ModalityState.NON_MODAL) { FileDocumentManager.getInstance().saveDocument(editor.document) } val localHistoryActionText = ActionsBundle.groupText("LocalHistory").dropMnemonic() task { text(LessonsBundle.message("local.history.remove.code", strong(localHistoryActionText), action(IdeActions.ACTION_EDITOR_BACKSPACE))) stateCheck { editor.document.charsSequence.contains(textAfterDelete) } restoreIfModifiedOrMoved() test { invokeActionViaShortcut("DELETE") } } setEditorHint(LessonsBundle.message("local.history.editor.hint")) waitBeforeContinue(500) prepareRuntimeTask { if (!TaskTestContext.inTestMode) { val userDecision = Messages.showOkCancelDialog( LessonsBundle.message("local.history.dialog.message"), LessonsBundle.message("recent.files.dialog.title"), CommonBundle.message("button.ok"), LearnBundle.message("learn.stop.lesson"), FeaturesTrainerIcons.Img.PluginIcon ) if (userDecision != Messages.OK) { LessonManager.instance.stopLesson() } } } modifyFile() lateinit var invokeMenuTaskId: TaskContext.TaskId task { invokeMenuTaskId = taskId text(LessonsBundle.message("local.history.imagine.restore", strong(ActionsBundle.message("action.\$Undo.text")))) text(LessonsBundle.message("local.history.invoke.context.menu", strong(localHistoryActionText))) triggerAndBorderHighlight().component { ui: EditorComponentImpl -> ui.editor == editor } triggerAndFullHighlight().component { ui: ActionMenu -> isClassEqual(ui.anAction, LocalHistoryGroup::class.java) } test { ideFrame { robot().rightClick(editor.component) } } } task("LocalHistory.ShowHistory") { val showHistoryActionText = ActionsBundle.actionText(it).dropMnemonic() text(LessonsBundle.message("local.history.show.history", strong(localHistoryActionText), strong(showHistoryActionText))) triggerAndFullHighlight { clearPreviousHighlights = false }.component { ui: ActionMenuItem -> isClassEqual(ui.anAction, ShowHistoryAction::class.java) } trigger(it) restoreByUi() test { ideFrame { jMenuItem { item: ActionMenu -> isClassEqual(item.anAction, LocalHistoryGroup::class.java) }.click() jMenuItem { item: ActionMenuItem -> isClassEqual(item.anAction, ShowHistoryAction::class.java) }.click() } } } var revisionsTable: JBTable? = null task { triggerAndBorderHighlight().componentPart { ui: JBTable -> if (checkInsideLocalHistoryFrame(ui)) { revisionsTable = ui ui.getCellRect(revisionInd, 0, false) } else null } } lateinit var selectRevisionTaskId: TaskContext.TaskId task { selectRevisionTaskId = taskId text(LessonsBundle.message("local.history.select.revision", strong(localHistoryActionText), strong(localHistoryActionText))) val step = CompletableFuture<Boolean>() addStep(step) triggerUI { clearPreviousHighlights = false }.component l@{ ui: JBLoadingPanel -> if (!checkInsideLocalHistoryFrame(ui)) return@l false ui.addListener(object : JBLoadingPanelListener { override fun onLoadingStart() { // do nothing } override fun onLoadingFinish() { val revisions = revisionsTable ?: return if (revisions.selectionModel.selectedIndices.let { it.size == 1 && it[0] == revisionInd }) { ui.removeListener(this) step.complete(true) } } }) true } restoreByUi(invokeMenuTaskId, delayMillis = defaultRestoreDelay) test { ideFrame { Thread.sleep(1000) val table = revisionsTable ?: error("revisionsTable is not initialized") JTableFixture(robot(), table).click(TableCell.row(revisionInd).column(0), MouseButton.LEFT_BUTTON) } } } task { triggerAndBorderHighlight().componentPart { ui: EditorGutterComponentEx -> findDiffGutterRect(ui) } } task { text(LessonsBundle.message("local.history.restore.code", icon(AllIcons.Diff.ArrowRight))) text(LessonsBundle.message("local.history.restore.code.balloon"), LearningBalloonConfig(Balloon.Position.below, 0, cornerToPointerDistance = 50)) stateCheck { editor.document.charsSequence.contains(textToDelete) } restoreByUi(invokeMenuTaskId) restoreState(selectRevisionTaskId) l@{ val revisions = revisionsTable ?: return@l false revisions.selectionModel.selectedIndices.let { it.size != 1 || it[0] != revisionInd } } test { ideFrame { val gutterComponent = previous.ui as? EditorGutterComponentEx ?: error("Failed to find gutter component") val gutterRect = findDiffGutterRect(gutterComponent) ?: error("Failed to find required gutter") robot().click(gutterComponent, Point(gutterRect.x + gutterRect.width / 2, gutterRect.y + gutterRect.height / 2)) } } } task { before { LearningUiHighlightingManager.clearHighlights() } text(LessonsBundle.message("local.history.close.window", action("EditorEscape"))) stateCheck { val focusedEditor = focusOwner as? EditorComponentImpl // check that it is editor from main IDE frame focusedEditor != null && UIUtil.getParentOfType(SingleHeightTabs::class.java, focusedEditor) != null } test { invokeActionViaShortcut("ESCAPE") // sometimes some small popup appears at mouse position so the first Escape may close just that popup invokeActionViaShortcut("ESCAPE") } } setEditorHint(null) text(LessonsBundle.message("local.history.congratulations")) } override fun onLessonEnd(project: Project, lessonEndInfo: LessonEndInfo) { if (!lessonEndInfo.lessonPassed) return ApplicationManager.getApplication().executeOnPooledThread { val editorComponent = LearningUiUtil.findComponentOrNull(project, EditorComponentImpl::class.java) { editor -> UIUtil.getParentOfType(SingleHeightTabs::class.java, editor) != null } ?: error("Failed to find editor component") invokeLater { val lines = textToDelete.lines() val rightColumn = lines.maxOf { it.length } LearningUiHighlightingManager.highlightPartOfComponent(editorComponent, HighlightingOptions(highlightInside = false)) { val editor = editorComponent.editor val textToFind = lines[0].trim() val offset = editor.document.charsSequence.indexOf(textToFind) if (offset == -1) error("Failed to find '$textToFind' in the editor") val leftPosition = editor.offsetToLogicalPosition(offset) val leftPoint = editor.logicalPositionToXY(leftPosition) val rightPoint = editor.logicalPositionToXY(LogicalPosition(leftPosition.line, rightColumn)) Rectangle(leftPoint.x - 3, leftPoint.y, rightPoint.x - leftPoint.x + 6, editor.lineHeight * lines.size) } } } } private fun isClassEqual(value: Any, expectedClass: Class<*>): Boolean { return value.javaClass.name == expectedClass.name } private fun findDiffGutterRect(ui: EditorGutterComponentEx): Rectangle? { val editor = CommonDataKeys.EDITOR.getData(ui as DataProvider) ?: return null val offset = editor.document.charsSequence.indexOf(textToDelete) return if (offset != -1) { val lineIndex = editor.document.getLineNumber(offset) invokeAndWaitIfNeeded { val y = editor.visualLineToY(lineIndex) Rectangle(ui.width - ui.whitespaceSeparatorOffset, y, ui.width - 26, editor.lineHeight) } } else null } private fun TaskRuntimeContext.checkInsideLocalHistoryFrame(component: Component): Boolean { val frame = UIUtil.getParentOfType(JFrame::class.java, component) return frame?.title == FileUtil.toSystemDependentName(virtualFile.path) } // If message is null it will remove the existing hint and allow file modification private fun LessonContext.setEditorHint(@Nls message: String?) { prepareRuntimeTask { EditorModificationUtil.setReadOnlyHint(editor, message) (editor as EditorEx).isViewer = message != null } } private fun LessonContext.modifyFile() { task { addFutureStep { val editor = this.editor runBackgroundableTask(LessonsBundle.message("local.history.file.modification.progress"), project, cancellable = false) { val document = editor.document invokeAndWaitIfNeeded { FileDocumentManager.getInstance().saveDocument(document) } removeLineWithAnimation(editor) invokeAndWaitIfNeeded { FileDocumentManager.getInstance().saveDocument(document) } Thread.sleep(50) insertStringWithAnimation(editor, textToAppend, editor.document.textLength) taskInvokeLater { editor.caretModel.moveToOffset(document.textLength) FileDocumentManager.getInstance().saveDocument(document) completeStep() } } } } } @RequiresBackgroundThread private fun removeLineWithAnimation(editor: Editor) { val document = editor.document val startOffset = document.getLineStartOffset(lineToDelete) val endOffset = document.getLineEndOffset(lineToDelete) for (ind in endOffset downTo startOffset) { invokeAndWaitIfNeeded { DocumentUtil.writeInRunUndoTransparentAction { editor.caretModel.moveToOffset(ind) document.deleteString(ind - 1, ind) } } Thread.sleep(10) } } @RequiresBackgroundThread private fun insertStringWithAnimation(editor: Editor, text: String, offset: Int) { val document = editor.document for (ind in text.indices) { invokeAndWaitIfNeeded { DocumentUtil.writeInRunUndoTransparentAction { document.insertString(offset + ind, text[ind].toString()) editor.caretModel.moveToOffset(offset + ind) } } Thread.sleep(10) } } override val suitableTips = listOf("local_history") override val helpLinks: Map<String, String> get() = mapOf( Pair(LessonsBundle.message("local.history.help.link"), LessonUtil.getHelpLink("local-history.html")), ) }
apache-2.0
cbce75bbd4461ab01c9c1cace9e30b1c
37.803069
158
0.699624
4.89545
false
false
false
false
JetBrains/kotlin-native
backend.native/compiler/ir/backend.native/src/org/jetbrains/kotlin/backend/konan/llvm/StaticObjects.kt
1
4965
/* * Copyright 2010-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.kotlin.backend.konan.llvm import kotlinx.cinterop.cValuesOf import llvm.* import org.jetbrains.kotlin.backend.konan.ir.llvmSymbolOrigin import org.jetbrains.kotlin.ir.declarations.IrClass private fun ConstPointer.add(index: Int): ConstPointer { return constPointer(LLVMConstGEP(llvm, cValuesOf(Int32(index).llvm), 1)!!) } // Must match OBJECT_TAG_PERMANENT_CONTAINER in C++. private fun StaticData.permanentTag(typeInfo: ConstPointer): ConstPointer { // Only pointer arithmetic via GEP works on constant pointers in LLVM. return typeInfo.bitcast(int8TypePtr).add(1).bitcast(kTypeInfoPtr) } private fun StaticData.objHeader(typeInfo: ConstPointer): Struct { return Struct(runtime.objHeaderType, permanentTag(typeInfo)) } private fun StaticData.arrayHeader(typeInfo: ConstPointer, length: Int): Struct { assert (length >= 0) return Struct(runtime.arrayHeaderType, permanentTag(typeInfo), Int32(length)) } internal fun StaticData.createKotlinStringLiteral(value: String): ConstPointer { val elements = value.toCharArray().map(::Char16) val objRef = createConstKotlinArray(context.ir.symbols.string.owner, elements) return objRef } private fun StaticData.createRef(objHeaderPtr: ConstPointer) = objHeaderPtr.bitcast(kObjHeaderPtr) internal fun StaticData.createConstKotlinArray(arrayClass: IrClass, elements: List<LLVMValueRef>) = createConstKotlinArray(arrayClass, elements.map { constValue(it) }).llvm internal fun StaticData.createConstKotlinArray(arrayClass: IrClass, elements: List<ConstValue>): ConstPointer { val typeInfo = arrayClass.typeInfoPtr val bodyElementType: LLVMTypeRef = elements.firstOrNull()?.llvmType ?: int8Type // (use [0 x i8] as body if there are no elements) val arrayBody = ConstArray(bodyElementType, elements) val compositeType = structType(runtime.arrayHeaderType, arrayBody.llvmType) val global = this.createGlobal(compositeType, "") val objHeaderPtr = global.pointer.getElementPtr(0) val arrayHeader = arrayHeader(typeInfo, elements.size) global.setInitializer(Struct(compositeType, arrayHeader, arrayBody)) global.setConstant(true) return createRef(objHeaderPtr) } internal fun StaticData.createConstKotlinObject(type: IrClass, vararg fields: ConstValue): ConstPointer { val typeInfo = type.typeInfoPtr val objHeader = objHeader(typeInfo) val global = this.placeGlobal("", Struct(objHeader, *fields)) global.setConstant(true) val objHeaderPtr = global.pointer.getElementPtr(0) return createRef(objHeaderPtr) } internal fun StaticData.createInitializer(type: IrClass, vararg fields: ConstValue): ConstValue = Struct(objHeader(type.typeInfoPtr), *fields) /** * Creates static instance of `kotlin.collections.ArrayList<elementType>` with given values of fields. * * @param array value for `array: Array<E>` field. * @param length value for `length: Int` field. */ internal fun StaticData.createConstArrayList(array: ConstPointer, length: Int): ConstPointer { val arrayListClass = context.ir.symbols.arrayList.owner val arrayListFields = mapOf( "array" to array, "offset" to Int32(0), "length" to Int32(length), "backing" to NullPointer(kObjHeader)) // Now sort these values according to the order of fields returned by getFields() // to match the sorting order of the real ArrayList(). val sorted = mutableListOf<ConstValue>() context.getLayoutBuilder(arrayListClass).fields.forEach { require (it.parent == arrayListClass) sorted.add(arrayListFields[it.name.asString()]!!) } return createConstKotlinObject(arrayListClass, *sorted.toTypedArray()) } internal fun StaticData.createUniqueInstance( kind: UniqueKind, bodyType: LLVMTypeRef, typeInfo: ConstPointer): ConstPointer { assert (getStructElements(bodyType).size == 1) // ObjHeader only. val objHeader = when (kind) { UniqueKind.UNIT -> objHeader(typeInfo) UniqueKind.EMPTY_ARRAY -> arrayHeader(typeInfo, 0) } val global = this.placeGlobal(kind.llvmName, objHeader, isExported = true) global.setConstant(true) return global.pointer } internal fun ContextUtils.unique(kind: UniqueKind): ConstPointer { val descriptor = when (kind) { UniqueKind.UNIT -> context.ir.symbols.unit.owner UniqueKind.EMPTY_ARRAY -> context.ir.symbols.array.owner } return if (isExternal(descriptor)) { constPointer(importGlobal( kind.llvmName, context.llvm.runtime.objHeaderType, origin = descriptor.llvmSymbolOrigin )) } else { context.llvmDeclarations.forUnique(kind).pointer } } internal val ContextUtils.theUnitInstanceRef: ConstPointer get() = this.unique(UniqueKind.UNIT)
apache-2.0
238b74f933ad5a5582d9a0fbc5e35db7
36.908397
111
0.740383
4.123754
false
false
false
false
jwren/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/intentions/RemoveEmptyParenthesesFromLambdaCallIntention.kt
2
2762
// 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.intentions import com.intellij.codeInspection.CleanupLocalInspectionTool import com.intellij.codeInspection.ProblemHighlightType import com.intellij.openapi.editor.Editor import com.intellij.openapi.util.TextRange import org.jetbrains.kotlin.idea.KotlinBundle import org.jetbrains.kotlin.idea.inspections.IntentionBasedInspection import org.jetbrains.kotlin.idea.refactoring.getLineNumber import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.psi.KtCallExpression import org.jetbrains.kotlin.psi.KtQualifiedExpression import org.jetbrains.kotlin.psi.KtValueArgumentList import org.jetbrains.kotlin.psi.psiUtil.getPrevSiblingIgnoringWhitespaceAndComments @Suppress("DEPRECATION") class RemoveEmptyParenthesesFromLambdaCallInspection : IntentionBasedInspection<KtValueArgumentList>( RemoveEmptyParenthesesFromLambdaCallIntention::class ), CleanupLocalInspectionTool { override fun problemHighlightType(element: KtValueArgumentList): ProblemHighlightType = ProblemHighlightType.LIKE_UNUSED_SYMBOL } class RemoveEmptyParenthesesFromLambdaCallIntention : SelfTargetingRangeIntention<KtValueArgumentList>( KtValueArgumentList::class.java, KotlinBundle.lazyMessage("remove.unnecessary.parentheses.from.function.call.with.lambda") ) { override fun applicabilityRange(element: KtValueArgumentList): TextRange? = Companion.applicabilityRange(element) override fun applyTo(element: KtValueArgumentList, editor: Editor?) = Companion.applyTo(element) companion object { fun isApplicable(list: KtValueArgumentList): Boolean = applicabilityRange(list) != null fun applyTo(list: KtValueArgumentList) = list.delete() fun applyToIfApplicable(list: KtValueArgumentList) { if (isApplicable(list)) { applyTo(list) } } private fun applicabilityRange(list: KtValueArgumentList): TextRange? { if (list.arguments.isNotEmpty()) return null val parent = list.parent as? KtCallExpression ?: return null if (parent.calleeExpression?.text == KtTokens.SUSPEND_KEYWORD.value) return null val singleLambdaArgument = parent.lambdaArguments.singleOrNull() ?: return null if (list.getLineNumber(start = false) != singleLambdaArgument.getLineNumber(start = true)) return null val prev = list.getPrevSiblingIgnoringWhitespaceAndComments() if (prev is KtCallExpression || (prev as? KtQualifiedExpression)?.callExpression != null) return null return list.textRange } } }
apache-2.0
9db7c4def9fa2c9442178f993d104cba
50.148148
158
0.774077
5.491054
false
false
false
false
google/playhvz
Android/ghvzApp/app/src/main/java/com/app/playhvz/firebase/constants/MissionPath.kt
1
3810
/* * Copyright 2020 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.app.playhvz.firebase.constants import com.google.firebase.firestore.Query class MissionPath { companion object { /** * Top level collection name for Missions. */ const val MISSION_COLLECTION_PATH = "missions" /******************************************************************************************* * Begin string definitions for field names in Firebase documents. Alphabetize. ******************************************************************************************/ /** * Field inside Mission document that contains the mission details. */ const val MISSION_FIELD__DETAILS = "details" /** * Field inside Mission document that contains the mission ending time. */ const val MISSION_FIELD__END_TIME = "endTime" /** * Field inside Mission document that contains the group id associated with the mission. */ const val MISSION_FIELD__GROUP_ID = "associatedGroupId" /** * Field inside Mission document that contains the mission name. */ const val MISSION_FIELD__NAME = "name" /** * Field inside Mission document that contains the mission starting time. */ const val MISSION_FIELD__START_TIME = "startTime" /******************************************************************************************* * End string definitions for field names in Firebase documents. ******************************************************************************************/ /******************************************************************************************* * Begin path definitions to documents. Alphabetize. ******************************************************************************************/ /** * DocRef that navigates to Mission documents. */ val MISSION_COLLECTION = { gameId: String -> GamePath.GAMES_COLLECTION.document(gameId).collection(MISSION_COLLECTION_PATH) } val MISSION_DOCUMENT_REFERENCE = { gameId: String, missionId: String -> MISSION_COLLECTION(gameId).document(missionId) } val MISSION_BY_GROUP_QUERY = { gameId: String, groupIdList: List<String> -> GamePath.GAMES_COLLECTION.document(gameId).collection(MISSION_COLLECTION_PATH) .whereIn(MISSION_FIELD__GROUP_ID, groupIdList) .orderBy(MISSION_FIELD__END_TIME, Query.Direction.DESCENDING) } val LATEST_MISSION_QUERY = { gameId: String, groupIdList: List<String> -> GamePath.GAMES_COLLECTION.document(gameId).collection(MISSION_COLLECTION_PATH) .whereIn(MISSION_FIELD__GROUP_ID, groupIdList) .orderBy(MISSION_FIELD__END_TIME, Query.Direction.DESCENDING) .limit(1) } /******************************************************************************************* * End path definitions to documents ******************************************************************************************/ } }
apache-2.0
554a7c3b2999ccd17a552f4fcd71f9ad
39.978495
100
0.507087
5.611193
false
false
false
false
androidx/androidx
compose/ui/ui-text/src/androidMain/kotlin/androidx/compose/ui/text/style/LineBreak.android.kt
3
10248
/* * 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.compose.ui.text.style import androidx.compose.runtime.Immutable import androidx.compose.ui.text.ExperimentalTextApi // TODO(b/246340708): Remove @sample LineBreakSample from the actual class /** * When soft wrap is enabled and the width of the text exceeds the width of its container, * line breaks are inserted in the text to split it over multiple lines. * * There are a number of parameters that affect how the line breaks are inserted. * For example, the breaking algorithm can be changed to one with improved readability * at the cost of speed. * Another example is the strictness, which in some languages determines which symbols can appear * at the start of a line. * * This represents a configuration for line breaking on Android, describing [Strategy], [Strictness], * and [WordBreak]. * * @sample androidx.compose.ui.text.samples.LineBreakSample * @sample androidx.compose.ui.text.samples.AndroidLineBreakSample * * @param strategy defines the algorithm that inserts line breaks * @param strictness defines the line breaking rules * @param wordBreak defines how words are broken */ @ExperimentalTextApi @Immutable actual class LineBreak( val strategy: Strategy, val strictness: Strictness, val wordBreak: WordBreak ) { actual companion object { /** * The greedy, fast line breaking algorithm. Ideal for text that updates often, * such as a text editor, as the text will reflow minimally. * * <pre> * +---------+ * | This is | * | an | * | example | * | text. | * | 今日は自 | * | 由が丘で | * | 焼き鳥を | * | 食べま | * | す。 | * +---------+ * </pre> */ actual val Simple: LineBreak = LineBreak( strategy = Strategy.Simple, strictness = Strictness.Normal, wordBreak = WordBreak.Default ) /** * Balanced line lengths, hyphenation, and phrase-based breaking. * Suitable for short text such as titles or narrow newspaper columns. * * <pre> * +---------+ * | This | * | is an | * | example | * | text. | * | 今日は | * | 自由が丘 | * | で焼き鳥 | * | を食べ | * | ます。 | * +---------+ * </pre> */ actual val Heading: LineBreak = LineBreak( strategy = Strategy.Balanced, strictness = Strictness.Loose, wordBreak = WordBreak.Phrase ) /** * Slower, higher quality line breaking for improved readability. * Suitable for larger amounts of text. * * <pre> * +---------+ * | This | * | is an | * | example | * | text. | * | 今日は自 | * | 由が丘で | * | 焼き鳥を | * | 食べま | * | す。 | * +---------+ * </pre> */ actual val Paragraph: LineBreak = LineBreak( strategy = Strategy.HighQuality, strictness = Strictness.Strict, wordBreak = WordBreak.Default ) } fun copy( strategy: Strategy = this.strategy, strictness: Strictness = this.strictness, wordBreak: WordBreak = this.wordBreak ): LineBreak = LineBreak( strategy = strategy, strictness = strictness, wordBreak = wordBreak ) override fun equals(other: Any?): Boolean { if (this === other) return true if (other !is LineBreak) return false if (strategy != other.strategy) return false if (strictness != other.strictness) return false if (wordBreak != other.wordBreak) return false return true } override fun hashCode(): Int { var result = strategy.hashCode() result = 31 * result + strictness.hashCode() result = 31 * result + wordBreak.hashCode() return result } override fun toString(): String = "LineBreak(strategy=$strategy, strictness=$strictness, wordBreak=$wordBreak)" /** * The strategy used for line breaking. */ @JvmInline value class Strategy private constructor(private val value: Int) { companion object { /** * Basic, fast break strategy. Hyphenation, if enabled, is done only for words * that don't fit on an entire line by themselves. * * <pre> * +---------+ * | This is | * | an | * | example | * | text. | * +---------+ * </pre> */ val Simple: Strategy = Strategy(1) /** * Does whole paragraph optimization for more readable text, * including hyphenation if enabled. * * <pre> * +---------+ * | This | * | is an | * | example | * | text. | * +---------+ * </pre> */ val HighQuality: Strategy = Strategy(2) /** * Attempts to balance the line lengths of the text, also applying automatic * hyphenation if enabled. Suitable for small screens. * * <pre> * +-----------------------+ * | This is an | * | example text. | * +-----------------------+ * </pre> */ val Balanced: Strategy = Strategy(3) } override fun toString(): String = when (this) { Simple -> "Strategy.Simple" HighQuality -> "Strategy.HighQuality" Balanced -> "Strategy.Balanced" else -> "Invalid" } } /** * Describes the strictness of line breaking, determining before which characters * line breaks can be inserted. It is useful when working with CJK scripts. */ @JvmInline value class Strictness private constructor(private val value: Int) { companion object { /** * Default breaking rules for the locale, which may correspond to [Normal] or [Strict]. */ val Default: Strictness = Strictness(1) /** * The least restrictive rules, suitable for short lines. * * For example, in Japanese it allows breaking before iteration marks, such as 々, 〻. */ val Loose: Strictness = Strictness(2) /** * The most common rules for line breaking. * * For example, in Japanese it allows breaking before characters like * small hiragana (ぁ), small katakana (ァ), halfwidth variants (ァ). */ val Normal: Strictness = Strictness(3) /** * The most stringent rules for line breaking. * * For example, in Japanese it does not allow breaking before characters like * small hiragana (ぁ), small katakana (ァ), halfwidth variants (ァ). */ val Strict: Strictness = Strictness(4) } override fun toString(): String = when (this) { Default -> "Strictness.None" Loose -> "Strictness.Loose" Normal -> "Strictness.Normal" Strict -> "Strictness.Strict" else -> "Invalid" } } /** * Describes how line breaks should be inserted within words. */ @JvmInline value class WordBreak private constructor(private val value: Int) { companion object { /** * Default word breaking rules for the locale. * In latin scripts this means inserting line breaks between words, * while in languages that don't use whitespace (e.g. Japanese) the line can break * between characters. * * <pre> * +---------+ * | This is | * | an | * | example | * | text. | * | 今日は自 | * | 由が丘で | * | 焼き鳥を | * | 食べま | * | す。 | * +---------+ * </pre> */ val Default: WordBreak = WordBreak(1) /** * Line breaking is based on phrases. * In languages that don't use whitespace (e.g. Japanese), line breaks are not inserted * between characters that are part of the same phrase unit. * This is ideal for short text such as titles and UI labels. * * <pre> * +---------+ * | This | * | is an | * | example | * | text. | * | 今日は | * | 自由が丘 | * | で焼き鳥 | * | を食べ | * | ます。 | * +---------+ * </pre> */ val Phrase: WordBreak = WordBreak(2) } override fun toString(): String = when (this) { Default -> "WordBreak.None" Phrase -> "WordBreak.Phrase" else -> "Invalid" } } }
apache-2.0
e92c1c599c6cfc815cd72cdb5060a567
30.946032
101
0.504671
4.534475
false
false
false
false
nrizzio/Signal-Android
app/src/androidTest/java/org/thoughtcrime/securesms/testing/ResponseMocking.kt
1
1468
package org.thoughtcrime.securesms.testing import okhttp3.mockwebserver.MockResponse import okhttp3.mockwebserver.RecordedRequest import okhttp3.mockwebserver.SocketPolicy import org.thoughtcrime.securesms.util.JsonUtils import java.util.concurrent.TimeUnit typealias ResponseFactory = (request: RecordedRequest) -> MockResponse /** * Represent an HTTP verb for mocking web requests. */ sealed class Verb(val verb: String, val path: String, val responseFactory: ResponseFactory) class Get(path: String, responseFactory: ResponseFactory) : Verb("GET", path, responseFactory) class Put(path: String, responseFactory: ResponseFactory) : Verb("PUT", path, responseFactory) fun MockResponse.success(response: Any? = null): MockResponse { return setResponseCode(200).apply { if (response != null) { setBody(JsonUtils.toJson(response)) } } } fun MockResponse.failure(code: Int, response: Any? = null): MockResponse { return setResponseCode(code).apply { if (response != null) { setBody(JsonUtils.toJson(response)) } } } fun MockResponse.connectionFailure(): MockResponse { return setSocketPolicy(SocketPolicy.DISCONNECT_AT_START) } fun MockResponse.timeout(): MockResponse { return setHeadersDelay(1, TimeUnit.DAYS) .setBodyDelay(1, TimeUnit.DAYS) } inline fun <reified T> RecordedRequest.parsedRequestBody(): T { val bodyString = String(body.readByteArray()) return JsonUtils.fromJson(bodyString, T::class.java) }
gpl-3.0
5dec1e994e5bfade65ef3c88eeed337c
29.583333
94
0.76158
4.135211
false
false
false
false
GunoH/intellij-community
python/testSrc/com/jetbrains/env/conda/LocalCondaRule.kt
2
1419
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.jetbrains.env.conda import com.jetbrains.env.conda.LocalCondaRule.Companion.CONDA_PATH import com.intellij.execution.target.FullPathOnTarget import com.jetbrains.python.sdk.add.target.conda.suggestCondaPath import com.jetbrains.python.sdk.flavors.conda.PyCondaCommand import kotlinx.coroutines.runBlocking import org.junit.AssumptionViolatedException import org.junit.rules.ExternalResource import java.nio.file.Path import kotlin.io.path.isExecutable /** * Finds conda on local system using [CONDA_PATH] env var. * * To be fixed: support targets as well */ class LocalCondaRule : ExternalResource() { private companion object { const val CONDA_PATH = "CONDA_PATH" } lateinit var condaPath: Path private set val condaPathOnTarget: FullPathOnTarget get() = condaPath.toString() val condaCommand: PyCondaCommand get() = PyCondaCommand(condaPathOnTarget, null) override fun before() { super.before() val condaPathEnv = System.getenv()[CONDA_PATH] ?: runBlocking { suggestCondaPath(null) } ?: throw AssumptionViolatedException("No $CONDA_PATH set") condaPath = Path.of(condaPathEnv) if (!condaPath.isExecutable()) { throw AssumptionViolatedException("$condaPath is not executable") } } }
apache-2.0
c82fe3e0785c4939d4b840581d278ca4
34.5
120
0.744186
4.054286
false
false
false
false
loxal/FreeEthereum
free-ethereum-core/src/test/java/org/ethereum/net/HelloMessageTest.kt
1
4890
/* * The MIT License (MIT) * * Copyright 2017 Alexander Orlov <[email protected]>. All rights reserved. * Copyright (c) [2016] [ <ether.camp> ] * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * */ package org.ethereum.net import org.ethereum.net.client.Capability import org.ethereum.net.eth.EthVersion import org.ethereum.net.p2p.HelloMessage import org.ethereum.net.p2p.P2pHandler import org.ethereum.net.p2p.P2pMessageCodes import org.ethereum.net.shh.ShhHandler import org.junit.Assert.assertEquals import org.junit.Test import org.slf4j.LoggerFactory import org.spongycastle.util.encoders.Hex import java.util.* class HelloMessageTest { //Parsing from raw bytes @Test fun test1() { val helloMessageRaw = "f87902a5457468657265756d282b2b292f76302e372e392f52656c656173652f4c696e75782f672b2bccc58365746827c583736868018203e0b8401fbf1e41f08078918c9f7b6734594ee56d7f538614f602c71194db0a1af5a77f9b86eb14669fe7a8a46a2dd1b7d070b94e463f4ecd5b337c8b4d31bbf8dd5646" val payload = Hex.decode(helloMessageRaw) val helloMessage = HelloMessage(payload) logger.info(helloMessage.toString()) assertEquals(P2pMessageCodes.HELLO, helloMessage.command) assertEquals(2, helloMessage.p2PVersion.toLong()) assertEquals("Ethereum(++)/v0.7.9/Release/Linux/g++", helloMessage.clientId) assertEquals(2, helloMessage.capabilities.size.toLong()) assertEquals(992, helloMessage.listenPort.toLong()) assertEquals( "1fbf1e41f08078918c9f7b6734594ee56d7f538614f602c71194db0a1af5a77f9b86eb14669fe7a8a46a2dd1b7d070b94e463f4ecd5b337c8b4d31bbf8dd5646", helloMessage.peerId) } //Instantiate from constructor @Test fun test2() { //Init val version: Byte = 2 val clientStr = "Ethereum(++)/v0.7.9/Release/Linux/g++" val capabilities = Arrays.asList( Capability(Capability.ETH, EthVersion.UPPER), Capability(Capability.SHH, ShhHandler.VERSION), Capability(Capability.P2P, P2pHandler.VERSION)) val listenPort = 992 val peerId = "1fbf1e41f08078918c9f7b6734594ee56d7f538614f602c71194db0a1af5a" val helloMessage = HelloMessage(version, clientStr, capabilities, listenPort, peerId) logger.info(helloMessage.toString()) assertEquals(P2pMessageCodes.HELLO, helloMessage.command) assertEquals(version.toLong(), helloMessage.p2PVersion.toLong()) assertEquals(clientStr, helloMessage.clientId) assertEquals(3, helloMessage.capabilities.size.toLong()) assertEquals(listenPort.toLong(), helloMessage.listenPort.toLong()) assertEquals(peerId, helloMessage.peerId) } //Fail test @Test fun test3() { //Init val version: Byte = -1 //invalid version val clientStr = "" //null id val capabilities = Arrays.asList<Capability>( Capability(null, 0.toByte()), Capability(null, 0.toByte()), null, //null here causes NullPointerException when using toString Capability(null, 0.toByte())) //encoding null capabilities val listenPort = 99999 //invalid port val peerId = "" //null id val helloMessage = HelloMessage(version, clientStr, capabilities, listenPort, peerId) assertEquals(P2pMessageCodes.HELLO, helloMessage.command) assertEquals(version.toLong(), helloMessage.p2PVersion.toLong()) assertEquals(clientStr, helloMessage.clientId) assertEquals(4, helloMessage.capabilities.size.toLong()) assertEquals(listenPort.toLong(), helloMessage.listenPort.toLong()) assertEquals(peerId, helloMessage.peerId) } companion object { /* HELLO_MESSAGE */ private val logger = LoggerFactory.getLogger("test") } }
mit
0ce9a048561dc5ae93b0cb19f2ea0b83
41.521739
278
0.721063
3.75
false
true
false
false
BijoySingh/Quick-Note-Android
base/src/main/java/com/maubis/scarlet/base/settings/sheet/LineCountBottomSheet.kt
1
2351
package com.maubis.scarlet.base.settings.sheet import android.app.Dialog import com.facebook.litho.Column import com.facebook.litho.Component import com.facebook.litho.ComponentContext import com.facebook.yoga.YogaEdge import com.maubis.scarlet.base.MainActivity import com.maubis.scarlet.base.R import com.maubis.scarlet.base.config.ApplicationBase.Companion.sAppPreferences import com.maubis.scarlet.base.support.sheets.LithoBottomSheet import com.maubis.scarlet.base.support.sheets.getLithoBottomSheetTitle import com.maubis.scarlet.base.support.specs.BottomSheetBar import com.maubis.scarlet.base.support.specs.CounterChooser import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.GlobalScope import kotlinx.coroutines.launch const val STORE_KEY_LINE_COUNT = "KEY_LINE_COUNT" const val LINE_COUNT_DEFAULT = 7 const val LINE_COUNT_MIN = 2 const val LINE_COUNT_MAX = 15 var sNoteItemLineCount: Int get() = sAppPreferences.get(STORE_KEY_LINE_COUNT, LINE_COUNT_DEFAULT) set(value) = sAppPreferences.put(STORE_KEY_LINE_COUNT, value) class LineCountBottomSheet : LithoBottomSheet() { override fun getComponent(componentContext: ComponentContext, dialog: Dialog): Component { val activity = context as MainActivity val component = Column.create(componentContext) .widthPercent(100f) .paddingDip(YogaEdge.VERTICAL, 8f) .paddingDip(YogaEdge.HORIZONTAL, 20f) .child( getLithoBottomSheetTitle(componentContext) .textRes(R.string.note_option_number_lines) .marginDip(YogaEdge.HORIZONTAL, 0f)) .child(CounterChooser.create(componentContext) .value(sNoteItemLineCount) .minValue(LINE_COUNT_MIN) .maxValue(LINE_COUNT_MAX) .onValueChange { value -> sNoteItemLineCount = value GlobalScope.launch(Dispatchers.Main) { reset(activity, dialog) } GlobalScope.launch(Dispatchers.Main) { activity.notifyAdapterExtraChanged() } } .paddingDip(YogaEdge.VERTICAL, 16f)) .child(BottomSheetBar.create(componentContext) .primaryActionRes(R.string.import_export_layout_exporting_done) .onPrimaryClick { dismiss() }.paddingDip(YogaEdge.VERTICAL, 8f)) return component.build() } }
gpl-3.0
fa214190922c11cf05e9e0ea048891d4
40.263158
94
0.723522
4.205725
false
false
false
false
GunoH/intellij-community
plugins/ide-features-trainer/src/training/dsl/TaskContext.kt
8
12490
// 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 training.dsl import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.project.Project import com.intellij.ui.tree.TreeVisitor import com.intellij.util.ui.tree.TreeUtil import org.intellij.lang.annotations.Language import org.jetbrains.annotations.Nls import training.learn.LearnBundle import training.statistic.LearningInternalProblems import training.ui.LearningUiHighlightingManager import training.ui.LearningUiManager import java.awt.Component import java.awt.Rectangle import java.util.concurrent.CompletableFuture import java.util.concurrent.Future import javax.swing.Icon import javax.swing.JList import javax.swing.JTree import javax.swing.tree.TreePath @LearningDsl abstract class TaskContext : LearningDslBase { abstract val project: Project open val taskId: TaskId = TaskId(0) /** * This property can be set to the true if you want that the next task restore will jump over the current task. * Default `null` value is reserved for the future automatic transparent restore calculation. */ open var transparentRestore: Boolean? = null /** * Can be set to true iff you need to rehighlight the triggered element from the previous task when it will be shown again. * Note: that the rehighlighted element can be different from `previous?.ui` (it can become `null` or `!isValid` or `!isShowing`) * */ open var rehighlightPreviousUi: Boolean? = null /** * Can be set to true iff you need to propagate found highlighting component from the previous task as found from the current task. * So it may be used as `previous.ui`. And will be rehighlighted on restore. * * The default `null` means true now, but it may be changed later. */ open var propagateHighlighting: Boolean? = null /** Put here some initialization for the task */ open fun before(preparation: TaskRuntimeContext.() -> Unit) = Unit /** * @param [restoreId] where to restore, `null` means the previous task * @param [delayMillis] the delay before restore actions can be applied. * Delay may be needed to give pass condition take place. * It is a hack solution because of possible race conditions. * @param [checkByTimer] Check by timer may be useful in UI detection tasks (in submenus for example). * @param [restoreRequired] returns true iff restore is needed */ open fun restoreState(restoreId: TaskId? = null, delayMillis: Int = 0, checkByTimer: Int? = null, restoreRequired: TaskRuntimeContext.() -> Boolean) = Unit /** Shortcut */ fun restoreByUi(restoreId: TaskId? = null, delayMillis: Int = 0, checkByTimer: Int? = null) { restoreState(restoreId, delayMillis, checkByTimer) { previous.ui?.isShowing?.not() ?: true } } /** Restore when timer is out. Is needed for chained tasks. */ open fun restoreByTimer(delayMillis: Int = 2000, restoreId: TaskId? = null) = Unit data class RestoreNotification(@Nls val message: String, @Nls val restoreLinkText: String = LearnBundle.message("learn.restore.default.link.text"), val callback: () -> Unit) open fun proposeRestore(restoreCheck: TaskRuntimeContext.() -> RestoreNotification?) = Unit open fun showWarning(@Language("HTML") @Nls text: String, restoreTaskWhenResolved: Boolean = false, problem: LearningInternalProblems? = null, warningRequired: TaskRuntimeContext.() -> Boolean) = Unit /** * Write a text to the learn panel (panel with a learning tasks). */ open fun text(@Language("HTML") @Nls text: String, useBalloon: LearningBalloonConfig? = null) = Unit /** Add an illustration */ fun illustration(icon: Icon): Unit = text("<illustration>${LearningUiManager.getIconIndex(icon)}</illustration>") /** Insert text in the current position */ open fun type(text: String) = Unit /** Write a text to the learn panel (panel with a learning tasks). */ open fun runtimeText(@Nls callback: RuntimeTextContext.() -> String?) = Unit /** Simply wait until an user perform particular action */ open fun trigger(actionId: String) = Unit /** Simply wait until an user perform actions */ open fun trigger(checkId: (String) -> Boolean) = Unit /** Trigger on actions start. Needs if you want to split long actions into several tasks. */ open fun triggerStart(actionId: String, checkState: TaskRuntimeContext.() -> Boolean = { true }) = Unit /** [actionIds] these actions required for the current task */ open fun triggers(vararg actionIds: String) = Unit /** An user need to rice an action which leads to necessary state change */ open fun <T : Any?> trigger(actionId: String, calculateState: TaskRuntimeContext.() -> T, checkState: TaskRuntimeContext.(T, T) -> Boolean) = Unit /** An user need to rice an action which leads to appropriate end state */ fun trigger(actionId: String, checkState: TaskRuntimeContext.() -> Boolean) { trigger(actionId, { }, { _, _ -> checkState() }) } /** * Check that IDE state is as expected * In some rare cases DSL could wish to complete a future by itself */ open fun stateCheck(checkState: TaskRuntimeContext.() -> Boolean): CompletableFuture<Boolean> = CompletableFuture() /** * Check that IDE state is fit * @return A feature with value associated with fit state */ open fun <T : Any> stateRequired(requiredState: TaskRuntimeContext.() -> T?): Future<T> = CompletableFuture() /** * Check that IDE state is as expected and check it by timer. * Need to consider merge this method with [stateCheck]. */ open fun timerCheck(delayMillis: Int = 200, checkState: TaskRuntimeContext.() -> Boolean): CompletableFuture<Boolean> = CompletableFuture() open fun addFutureStep(p: DoneStepContext.() -> Unit) = Unit /* The step should be used only inside one task to preserve problems on restore */ open fun addStep(step: CompletableFuture<Boolean>) = Unit /** [action] What should be done to pass the current task */ open fun test(waitEditorToBeReady: Boolean = true, action: TaskTestContext.() -> Unit) = Unit fun triggerAndFullHighlight(parameters: HighlightTriggerParametersContext.() -> Unit = {}): HighlightingTriggerMethods { return triggerUI { highlightBorder = true highlightInside = true parameters() } } fun triggerAndBorderHighlight(parameters: HighlightTriggerParametersContext.() -> Unit = {}): HighlightingTriggerMethods { return triggerUI { highlightBorder = true parameters() } } open fun triggerUI(parameters: HighlightTriggerParametersContext.() -> Unit = {}): HighlightingTriggerMethods { return object : HighlightingTriggerMethods() {} } @Deprecated("Use triggerAndBorderHighlight().treeItem") fun triggerByFoundPathAndHighlight(highlightBorder: Boolean = true, highlightInside: Boolean = false, usePulsation: Boolean = false, clearPreviousHighlights: Boolean = true, checkPath: TaskRuntimeContext.(tree: JTree, path: TreePath) -> Boolean) { val options = LearningUiHighlightingManager.HighlightingOptions(highlightBorder, highlightInside, usePulsation, clearPreviousHighlights) triggerByFoundPathAndHighlight(options) { tree -> TreeUtil.visitVisibleRows(tree, TreeVisitor { path -> if (checkPath(tree, path)) TreeVisitor.Action.INTERRUPT else TreeVisitor.Action.CONTINUE }) } } // This method later can be converted to the public (But I'm not sure it will be ever needed in a such form) protected open fun triggerByFoundPathAndHighlight(options: LearningUiHighlightingManager.HighlightingOptions, checkTree: TaskRuntimeContext.(tree: JTree) -> TreePath?) = Unit @Deprecated("Use triggerAndBorderHighlight().componentPart") inline fun <reified T : Component> triggerByPartOfComponent(highlightBorder: Boolean = true, highlightInside: Boolean = false, usePulsation: Boolean = false, clearPreviousHighlights: Boolean = true, noinline selector: ((candidates: Collection<T>) -> T?)? = null, crossinline rectangle: TaskRuntimeContext.(T) -> Rectangle?) { val options = LearningUiHighlightingManager.HighlightingOptions(highlightBorder, highlightInside, usePulsation, clearPreviousHighlights) @Suppress("DEPRECATION") triggerByPartOfComponentImpl(T::class.java, options, selector) { rectangle(it) } } @Deprecated("Use inline version") open fun <T : Component> triggerByPartOfComponentImpl(componentClass: Class<T>, options: LearningUiHighlightingManager.HighlightingOptions, selector: ((candidates: Collection<T>) -> T?)?, rectangle: TaskRuntimeContext.(T) -> Rectangle?) = Unit @Deprecated("Use triggerAndBorderHighlight().listItem") fun triggerByListItemAndHighlight(highlightBorder: Boolean = true, highlightInside: Boolean = false, usePulsation: Boolean = false, clearPreviousHighlights: Boolean = true, checkList: TaskRuntimeContext.(item: Any) -> Boolean) { val options = LearningUiHighlightingManager.HighlightingOptions(highlightBorder, highlightInside, usePulsation, clearPreviousHighlights) triggerByFoundListItemAndHighlight(options) { ui: JList<*> -> LessonUtil.findItem(ui) { checkList(it) } } } // This method later can be converted to the public (But I'm not sure it will be ever needed in a such form protected open fun triggerByFoundListItemAndHighlight(options: LearningUiHighlightingManager.HighlightingOptions, checkList: TaskRuntimeContext.(list: JList<*>) -> Int?) = Unit @Deprecated("Use triggerAndFullHighlight().component") inline fun <reified ComponentType : Component> triggerByUiComponentAndHighlight( highlightBorder: Boolean = true, highlightInside: Boolean = true, usePulsation: Boolean = false, clearPreviousHighlights: Boolean = true, noinline selector: ((candidates: Collection<ComponentType>) -> ComponentType?)? = null, crossinline finderFunction: TaskRuntimeContext.(ComponentType) -> Boolean ) { val options = LearningUiHighlightingManager.HighlightingOptions(highlightBorder, highlightInside, usePulsation, clearPreviousHighlights) @Suppress("DEPRECATION") triggerByUiComponentAndHighlightImpl(ComponentType::class.java, options, selector) { finderFunction(it) } } @Deprecated("Use inline version") open fun <ComponentType : Component> triggerByUiComponentAndHighlightImpl(componentClass: Class<ComponentType>, options: LearningUiHighlightingManager.HighlightingOptions, selector: ((candidates: Collection<ComponentType>) -> ComponentType?)?, finderFunction: TaskRuntimeContext.(ComponentType) -> Boolean) = Unit open fun caret(position: LessonSamplePosition) = before { caret(position) } /** NOTE: [line] and [column] starts from 1 not from zero. So these parameters should be same as in editors. */ open fun caret(line: Int, column: Int) = before { caret(line, column) } class DoneStepContext(private val future: CompletableFuture<Boolean>, rt: TaskRuntimeContext) : TaskRuntimeContext(rt) { fun completeStep() { ApplicationManager.getApplication().assertIsDispatchThread() if (!future.isDone && !future.isCancelled) { future.complete(true) } } } data class TaskId(val idx: Int) companion object { val CaretRestoreProposal: String get() = LearnBundle.message("learn.restore.notification.caret.message") val ModificationRestoreProposal: String get() = LearnBundle.message("learn.restore.notification.modification.message") } }
apache-2.0
e28cc0a326283f425cd74b8f551a611b
47.980392
157
0.686309
5.182573
false
false
false
false
smmribeiro/intellij-community
platform/lang-impl/src/com/intellij/codeInsight/documentation/actions/ShowQuickDocInfoAction.kt
1
4217
// 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.documentation.actions import com.intellij.codeInsight.documentation.DocumentationManager import com.intellij.codeInsight.documentation.QuickDocUtil.isDocumentationV2Enabled import com.intellij.codeInsight.hint.HintManagerImpl.ActionToIgnore import com.intellij.codeInsight.lookup.LookupManager import com.intellij.featureStatistics.FeatureUsageTracker import com.intellij.lang.documentation.ide.actions.documentationTargets import com.intellij.lang.documentation.ide.impl.DocumentationManager.Companion.instance import com.intellij.openapi.actionSystem.* import com.intellij.openapi.editor.EditorGutter import com.intellij.openapi.project.DumbAware import com.intellij.openapi.util.registry.Registry import com.intellij.psi.PsiDocumentManager import com.intellij.psi.util.PsiUtilBase open class ShowQuickDocInfoAction : AnAction(), ActionToIgnore, DumbAware, PopupAction, UpdateInBackground, PerformWithDocumentsCommitted { init { isEnabledInModalContext = true @Suppress("LeakingThis") setInjectedContext(true) } override fun update(e: AnActionEvent) { if (isDocumentationV2Enabled()) { e.presentation.isEnabled = documentationTargets(e.dataContext).isNotEmpty() return } val presentation = e.presentation val dataContext = e.dataContext presentation.isEnabled = false val project = CommonDataKeys.PROJECT.getData(dataContext) ?: return val editor = CommonDataKeys.EDITOR.getData(dataContext) val element = CommonDataKeys.PSI_ELEMENT.getData(dataContext) if (editor == null && element == null) return if (LookupManager.getInstance(project).activeLookup != null) { presentation.isEnabled = true } else { if (editor != null) { if (e.getData(EditorGutter.KEY) != null) return val file = PsiDocumentManager.getInstance(project).getPsiFile(editor.document) if (file == null && element == null) return } presentation.isEnabled = true } } override fun actionPerformed(e: AnActionEvent) { if (isDocumentationV2Enabled()) { actionPerformedV2(e.dataContext) return } val dataContext = e.dataContext val project = CommonDataKeys.PROJECT.getData(dataContext) ?: return val editor = CommonDataKeys.EDITOR.getData(dataContext) if (editor != null) { FeatureUsageTracker.getInstance().triggerFeatureUsed(CODEASSISTS_QUICKJAVADOC_FEATURE) val activeLookup = LookupManager.getActiveLookup(editor) if (activeLookup != null) { FeatureUsageTracker.getInstance().triggerFeatureUsed(CODEASSISTS_QUICKJAVADOC_LOOKUP_FEATURE) } val psiFile = PsiUtilBase.getPsiFileInEditor(editor, project) ?: return val documentationManager = DocumentationManager.getInstance(project) val hint = documentationManager.docInfoHint documentationManager.showJavaDocInfo(editor, psiFile, hint != null || activeLookup == null) return } val element = CommonDataKeys.PSI_ELEMENT.getData(dataContext) if (element != null) { FeatureUsageTracker.getInstance().triggerFeatureUsed(CODEASSISTS_QUICKJAVADOC_CTRLN_FEATURE) val documentationManager = DocumentationManager.getInstance(project) val hint = documentationManager.docInfoHint documentationManager.showJavaDocInfo(element, null, hint != null, null) } } private fun actionPerformedV2(dataContext: DataContext) { val project = dataContext.getData(CommonDataKeys.PROJECT) ?: return instance(project).actionPerformed(dataContext) } @Suppress("SpellCheckingInspection") companion object { const val CODEASSISTS_QUICKJAVADOC_FEATURE = "codeassists.quickjavadoc" const val CODEASSISTS_QUICKJAVADOC_LOOKUP_FEATURE = "codeassists.quickjavadoc.lookup" const val CODEASSISTS_QUICKJAVADOC_CTRLN_FEATURE = "codeassists.quickjavadoc.ctrln" } }
apache-2.0
aa257a385b11b9b4174444d50c200d46
42.927083
158
0.730377
4.770362
false
false
false
false
smmribeiro/intellij-community
plugins/github/src/org/jetbrains/plugins/github/pullrequest/ui/changes/GHPRChangesTreeFactory.kt
10
2825
// Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.plugins.github.pullrequest.ui.changes import com.intellij.collaboration.ui.SingleValueModel import com.intellij.openapi.actionSystem.ActionGroup import com.intellij.openapi.actionSystem.ActionManager import com.intellij.openapi.actionSystem.DefaultActionGroup import com.intellij.openapi.actionSystem.IdeActions import com.intellij.openapi.project.Project import com.intellij.openapi.vcs.changes.Change import com.intellij.openapi.vcs.changes.ui.ChangesTree import com.intellij.openapi.vcs.changes.ui.TreeActionsToolbarPanel import com.intellij.openapi.vcs.changes.ui.TreeModelBuilder import com.intellij.openapi.vcs.changes.ui.VcsTreeModelData import com.intellij.ui.ExpandableItemsHandler import com.intellij.ui.SelectionSaver import com.intellij.util.ui.UIUtil import com.intellij.util.ui.tree.TreeUtil import java.awt.event.FocusAdapter import java.awt.event.FocusEvent import javax.swing.JComponent internal class GHPRChangesTreeFactory(private val project: Project, private val changesModel: SingleValueModel<out Collection<Change>>) { fun create(emptyTextText: String): ChangesTree { val tree = object : ChangesTree(project, false, false) { override fun rebuildTree() { updateTreeModel(TreeModelBuilder(project, grouping).setChanges(changesModel.value, null).build()) if (isSelectionEmpty && !isEmpty) TreeUtil.selectFirstNode(this) } override fun getData(dataId: String) = super.getData(dataId) ?: VcsTreeModelData.getData(project, this, dataId) }.apply { emptyText.text = emptyTextText }.also { UIUtil.putClientProperty(it, ExpandableItemsHandler.IGNORE_ITEM_SELECTION, true) SelectionSaver.installOn(it) it.addFocusListener(object : FocusAdapter() { override fun focusGained(e: FocusEvent?) { if (it.isSelectionEmpty && !it.isEmpty) TreeUtil.selectFirstNode(it) } }) } changesModel.addAndInvokeListener { tree.rebuildTree() } return tree } companion object { fun createTreeToolbar(actionManager: ActionManager, treeContainer: JComponent): JComponent { val changesToolbarActionGroup = actionManager.getAction("Github.PullRequest.Changes.Toolbar") as ActionGroup val changesToolbar = actionManager.createActionToolbar("ChangesBrowser", changesToolbarActionGroup, true) val treeActionsGroup = DefaultActionGroup(actionManager.getAction(IdeActions.ACTION_EXPAND_ALL), actionManager.getAction(IdeActions.ACTION_COLLAPSE_ALL)) return TreeActionsToolbarPanel(changesToolbar, treeActionsGroup, treeContainer) } } }
apache-2.0
aea4c04a372ff04d9e438bffa3f4335d
46.898305
140
0.760708
4.677152
false
false
false
false
Waboodoo/HTTP-Shortcuts
HTTPShortcuts/app/src/main/kotlin/ch/rmy/android/http_shortcuts/plugin/SessionMonitor.kt
1
1032
package ch.rmy.android.http_shortcuts.plugin import kotlinx.coroutines.CompletableDeferred import kotlinx.coroutines.withTimeout import javax.inject.Inject import javax.inject.Singleton import kotlin.time.Duration @Singleton class SessionMonitor @Inject constructor() { private var startedDeferred: CompletableDeferred<Unit>? = null private var completedDeferred: CompletableDeferred<Unit>? = null suspend fun monitorSession(startTimeout: Duration, completionTimeout: Duration) { withTimeout(startTimeout) { startedDeferred?.await() } withTimeout(completionTimeout) { completedDeferred?.await() } } fun onSessionScheduled() { startedDeferred = CompletableDeferred() completedDeferred = CompletableDeferred() } fun onSessionStarted() { startedDeferred?.complete(Unit) startedDeferred = null } fun onSessionComplete() { completedDeferred?.complete(Unit) completedDeferred = null } }
mit
c20b13c2e07547f7cca5d29ae4377fa1
24.8
85
0.703488
5.134328
false
false
false
false
srodrigo/Kotlin-Wars
core/src/main/kotlin/me/srodrigo/kotlinwars/infrastructure/Commands.kt
1
3503
package me.srodrigo.kotlinwars.infrastructure import java.util.* import java.util.concurrent.Callable interface Command<T> : Callable<T> interface CommandResult<T> { fun onResult(result: T) } interface CommandError class GenericError(val cause: Exception? = null) : CommandError interface CommandErrorAction<T : CommandError> { fun onError(error: T) } open class CommandResponse<T>(val response: T? = null, val error: CommandError? = null) { fun hasError(): Boolean = error != null } interface ExecutionThread { fun execute(runnable: Runnable) } interface CommandExecutor { fun <T : CommandResponse<out Any>> execute(execution: CommandExecution<T>) } class CommandExecutorTask<T : CommandResponse<out Any>>(private val execution: CommandExecution<T>, private val postExecutionThread: ExecutionThread) : Runnable { override fun run() { try { val response = execution.command.call() if (response.hasError()) { postExecutionThread.execute(Runnable { onErrorAction(execution, response) }) } else { postExecutionThread.execute(Runnable { onResultAction(execution, response) }) } } catch (e: Exception) { postExecutionThread.execute(Runnable { doGenericErrorAction(execution, GenericError(e)) }) } } private fun <T : CommandResponse<out Any>> onResultAction(execution: CommandExecution<T>, response: T) { execution.commandResult.onResult(response) } private fun <T : CommandResponse<out Any>> onErrorAction(execution: CommandExecution<T>, response: T) { val error: CommandError = response.error!! val errorActions = execution.getActions(error.javaClass) if (errorActions == null) { doGenericErrorAction(execution, GenericError()) } else { for (action in errorActions) { action.onError(error) } } } private fun <T : CommandResponse<out Any>> doGenericErrorAction(execution: CommandExecution<T>, genericError: GenericError) { val genericErrorActions = execution.getGenericErrorActions() if (genericErrorActions != null) { for (action in genericErrorActions) { action.onError(genericError) } } } } class CommandExecution<T : CommandResponse<out Any>>(val command: Command<T>, val commandResult: CommandResult<T>) { private val genericErrorClass = GenericError::class.java private val errors = HashMap<Class<out CommandError>, List<CommandErrorAction<in CommandError>>> () fun <E : CommandError> error(javaClass: Class<E>, vararg errorActions: CommandErrorAction<out CommandError>): CommandExecution<T> { val mappedActions = ArrayList<CommandErrorAction<in CommandError>>() for (act in errorActions) { mappedActions.add(castErrorAction(act)) } errors[javaClass] = mappedActions return this } fun genericErrorActions(errorAction: CommandErrorAction<out CommandError>): CommandExecution<T> { errors[genericErrorClass] = listOf(castErrorAction(errorAction)) return this } private fun castErrorAction(errorAction: CommandErrorAction<out CommandError>) = errorAction as CommandErrorAction<in CommandError> fun execute(executor: CommandExecutor) { executor.execute(this) } fun getActions(javaClass: Class<CommandError>) = errors[javaClass] /** * Returns an optional, as it's not mandatory to be subscribed to generic errors from everywhere */ fun getGenericErrorActions() = errors[genericErrorClass] }
mit
a4d58e29e3740e9295c4479ddf7f83e1
31.137615
132
0.7171
3.994299
false
false
false
false
glorantq/KalanyosiRamszesz
src/glorantq/ramszesz/memes/NumberOneMeme.kt
1
2305
package glorantq.ramszesz.memes import com.cloudinary.utils.ObjectUtils import glorantq.ramszesz.cloudinary import sx.blah.discord.handle.impl.events.guild.channel.message.MessageReceivedEvent import sx.blah.discord.handle.obj.IUser import java.awt.Graphics import java.awt.image.BufferedImage import java.io.File import java.net.URL import java.net.URLConnection import javax.imageio.ImageIO /** * Created by glora on 2017. 07. 26.. */ class NumberOneMeme : IMeme { override val name: String get() = "numberone" override var parameters: ArrayList<MemeParameter> = arrayListOf( MemeParameter(MemeParameter.Companion.Type.USER), MemeParameter(MemeParameter.Companion.Type.USER), MemeParameter(MemeParameter.Companion.Type.USER), MemeParameter(MemeParameter.Companion.Type.USER) ) override fun execute(event: MessageReceivedEvent) { val pictures: ArrayList<BufferedImage> = arrayListOf() (0..3) .map { parameters[it].value as IUser } .mapTo(pictures) { downloadProfileImage(it) } val background: BufferedImage = ImageIO.read(File("./assets/numberone.jpg")) val combined: BufferedImage = BufferedImage(background.width, background.height, BufferedImage.TYPE_INT_RGB) val graphics: Graphics = combined.graphics graphics.drawImage(background, 0, 0, null) graphics.drawImage(pictures[0], 205, 445 - 260, 260, 260, null) graphics.drawImage(pictures[1], 575, 580 - 260, 260, 260, null) graphics.drawImage(pictures[2], 780, 380 - 215, 215, 215, null) graphics.drawImage(pictures[3], 555, 260 - 240, 240, 240, null) graphics.dispose() val final: BufferedImage = BufferedImage(640, 360, BufferedImage.TYPE_INT_RGB) val finalG: Graphics = final.graphics finalG.drawImage(combined, 0, 0, 640, 360, null) finalG.dispose() val imageFile: File = File.createTempFile("numberone-meme-${event.author.name}", ".png") imageFile.deleteOnExit() ImageIO.write(final, "png", imageFile) val url: String = cloudinary.uploader().upload(imageFile, ObjectUtils.emptyMap())["secure_url"].toString() deliverMeme(event, url) imageFile.delete() } }
gpl-3.0
74de214b9e66817b665fcdfb0412a6dc
36.193548
116
0.684599
4.175725
false
false
false
false
mikepenz/MaterialDrawer
materialdrawer/src/main/java/com/mikepenz/materialdrawer/model/interfaces/Badgeable.kt
1
1367
package com.mikepenz.materialdrawer.model.interfaces import com.mikepenz.materialdrawer.holder.StringHolder /** * Defines a [IDrawerItem] which allows to have a badge */ interface Badgeable { /** the badge text to show for this item */ var badge: StringHolder? } @Deprecated("Please consider to replace with the actual property setter") fun <T : Badgeable> T.withBadge(badge: String): T { this.badge = StringHolder(badge) return this } @Deprecated("Please consider to replace with the actual property setter") fun <T : Badgeable> T.withBadge(badgeRes: Int): T { this.badge = StringHolder(badgeRes) return this } @Deprecated("Please consider to replace with the actual property setter") fun <T : Badgeable> T.withBadge(badge: StringHolder?): T { this.badge = badge return this } /** Set the badge name */ var Badgeable.badgeRes: Int @Deprecated(level = DeprecationLevel.ERROR, message = "Not readable") get() = throw UnsupportedOperationException("Please use the direct property") set(value) { badge = StringHolder(value) } /** Set the badge name */ var Badgeable.badgeText: CharSequence @Deprecated(level = DeprecationLevel.ERROR, message = "Not readable") get() = throw UnsupportedOperationException("Please use the direct property") set(value) { badge = StringHolder(value) }
apache-2.0
4d310ebcfb5e05cbac1a8869aca14acb
29.377778
81
0.713241
4.180428
false
false
false
false
fgsguedes/adventofcode
2017/src/main/kotlin/day5/Maze.kt
1
893
package day5 import fromMultipleLineInput fun leaveMaze(input: List<Int>): Int { val mutable = input.toMutableList() var steps = 0 var index = 0 do { steps++ val offset = mutable[index] mutable[index] = offset + 1 index += offset } while (index < mutable.size) return steps } fun leaveMazePart2(input: List<Int>): Int { val mutable = input.toMutableList() var steps = 0 var index = 0 do { steps++ val offset = mutable[index] mutable[index] = offset + if (offset >= 3) -1 else 1 index += offset } while (index < mutable.size) return steps } fun main(args: Array<String>) { fromMultipleLineInput(2017, 5, "MazePart1Input.txt") { rawInput -> println(leaveMaze(rawInput.map { it.toInt() })) } fromMultipleLineInput(2017, 5, "MazePart2Input.txt") { rawInput -> println(leaveMazePart2(rawInput.map { it.toInt() })) } }
gpl-2.0
94ec04b8f7a00bcae5c22b9da7c01dee
19.790698
68
0.649496
3.369811
false
false
false
false
orgzly/orgzly-android
app/src/main/java/com/orgzly/android/prefs/TimePreference.kt
1
1510
package com.orgzly.android.prefs import android.content.Context import android.content.res.TypedArray import android.text.format.DateFormat import android.util.AttributeSet import androidx.preference.DialogPreference import com.orgzly.R import org.joda.time.DateTime import org.joda.time.DateTimeZone class TimePreference : DialogPreference { constructor(context: Context, attrs: AttributeSet, defStyleAttr: Int, defStyleRes: Int) : super(context, attrs, defStyleAttr, defStyleRes) { dialogLayoutResource = R.layout.pref_dialog_time } constructor(context: Context, attrs: AttributeSet, defStyleAttr: Int) : super(context, attrs, defStyleAttr) { dialogLayoutResource = R.layout.pref_dialog_time } constructor(context: Context, attrs: AttributeSet) : super(context, attrs) { dialogLayoutResource = R.layout.pref_dialog_time } override fun onGetDefaultValue(a: TypedArray, index: Int): Any? { return a.getString(index) } override fun getSummary(): CharSequence { val timeFormat = DateFormat.getTimeFormat(context) val time = DateTime.now(DateTimeZone.forTimeZone(timeFormat.timeZone)) .withTimeAtStartOfDay() .plusMinutes(getTime()) .toDate() return timeFormat.format(time) } fun getTime(): Int { return AppPreferences.reminderDailyTime(context) } fun setTime(time: Int) { AppPreferences.reminderDailyTime(context, time) } }
gpl-3.0
8bc3b92f159565038c14a2730a1875e6
29.816327
144
0.70596
4.561934
false
false
false
false
seventhroot/elysium
bukkit/rpk-chat-bukkit/src/main/kotlin/com/rpkit/chat/bukkit/chatchannel/RPKChatChannelImpl.kt
1
8837
/* * Copyright 2020 Ren Binden * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.rpkit.chat.bukkit.chatchannel import com.rpkit.chat.bukkit.RPKChatBukkit import com.rpkit.chat.bukkit.chatchannel.context.DirectedChatChannelMessageContextImpl import com.rpkit.chat.bukkit.chatchannel.context.UndirectedChatChannelMessageContextImpl import com.rpkit.chat.bukkit.chatchannel.pipeline.DirectedChatChannelPipelineComponent import com.rpkit.chat.bukkit.chatchannel.pipeline.UndirectedChatChannelPipelineComponent import com.rpkit.chat.bukkit.context.DirectedChatChannelMessageContext import com.rpkit.chat.bukkit.context.UndirectedChatChannelMessageContext import com.rpkit.chat.bukkit.event.chatchannel.RPKBukkitChatChannelMessageEvent import com.rpkit.chat.bukkit.mute.RPKChatChannelMuteProvider import com.rpkit.chat.bukkit.speaker.RPKChatChannelSpeakerProvider import com.rpkit.players.bukkit.player.RPKPlayer import com.rpkit.players.bukkit.player.RPKPlayerProvider import com.rpkit.players.bukkit.profile.RPKMinecraftProfile import com.rpkit.players.bukkit.profile.RPKMinecraftProfileProvider import com.rpkit.players.bukkit.profile.RPKThinProfile import java.awt.Color /** * Chat channel implementation. */ class RPKChatChannelImpl( private val plugin: RPKChatBukkit, override var id: Int = 0, override val name: String, override val color: Color, override val radius: Double, override val directedPipeline: List<DirectedChatChannelPipelineComponent>, override val undirectedPipeline: List<UndirectedChatChannelPipelineComponent>, override val matchPattern: String?, override var isJoinedByDefault: Boolean ) : RPKChatChannel { override val speakers: List<RPKPlayer> get() = plugin.server.onlinePlayers .map { player -> plugin.core.serviceManager.getServiceProvider(RPKPlayerProvider::class).getPlayer(player) } .filter { player -> plugin.core.serviceManager.getServiceProvider(RPKChatChannelSpeakerProvider::class).getPlayerChannel(player) == this } override val speakerMinecraftProfiles: List<RPKMinecraftProfile> get() = plugin.server.onlinePlayers .mapNotNull { player -> plugin.core.serviceManager.getServiceProvider(RPKMinecraftProfileProvider::class).getMinecraftProfile(player) } .filter { minecraftProfile -> plugin.core.serviceManager.getServiceProvider(RPKChatChannelSpeakerProvider::class).getMinecraftProfileChannel(minecraftProfile) == this } override val listeners: List<RPKPlayer> get() = plugin.server.onlinePlayers .filter { player -> player.hasPermission("rpkit.chat.listen.$name") } .map { player -> plugin.core.serviceManager.getServiceProvider(RPKPlayerProvider::class).getPlayer(player) } .filter { player -> !plugin.core.serviceManager.getServiceProvider(RPKChatChannelMuteProvider::class).hasPlayerMutedChatChannel(player, this) } override val listenerMinecraftProfiles: List<RPKMinecraftProfile> get() = plugin.server.onlinePlayers .filter { player -> player.hasPermission("rpkit.chat.listen.$name") } .mapNotNull { player -> plugin.core.serviceManager.getServiceProvider(RPKMinecraftProfileProvider::class).getMinecraftProfile(player) } .filter { minecraftProfile -> !plugin.core.serviceManager.getServiceProvider(RPKChatChannelMuteProvider::class).hasMinecraftProfileMutedChatChannel(minecraftProfile, this) } override fun addSpeaker(speaker: RPKPlayer) { plugin.core.serviceManager.getServiceProvider(RPKChatChannelSpeakerProvider::class).setPlayerChannel(speaker, this) } override fun addSpeaker(speaker: RPKMinecraftProfile) { plugin.core.serviceManager.getServiceProvider(RPKChatChannelSpeakerProvider::class).setMinecraftProfileChannel(speaker, this) } override fun removeSpeaker(speaker: RPKPlayer) { val chatChannelSpeakerProvider = plugin.core.serviceManager.getServiceProvider(RPKChatChannelSpeakerProvider::class) if (chatChannelSpeakerProvider.getPlayerChannel(speaker) == this) { chatChannelSpeakerProvider.removePlayerChannel(speaker) } } override fun removeSpeaker(speaker: RPKMinecraftProfile) { val chatChannelSpeakerProvider = plugin.core.serviceManager.getServiceProvider(RPKChatChannelSpeakerProvider::class) if (chatChannelSpeakerProvider.getMinecraftProfileChannel(speaker) == this) { chatChannelSpeakerProvider.removeMinecraftProfileChannel(speaker) } } override fun addListener(listener: RPKPlayer) { plugin.core.serviceManager.getServiceProvider(RPKChatChannelMuteProvider::class).removeChatChannelMute(listener, this) } override fun addListener(listener: RPKMinecraftProfile, isAsync: Boolean) { plugin.core.serviceManager.getServiceProvider(RPKChatChannelMuteProvider::class).removeChatChannelMute(listener, this, isAsync) } override fun removeListener(listener: RPKPlayer) { plugin.core.serviceManager.getServiceProvider(RPKChatChannelMuteProvider::class).addChatChannelMute(listener, this) } override fun removeListener(listener: RPKMinecraftProfile) { plugin.core.serviceManager.getServiceProvider(RPKChatChannelMuteProvider::class).addChatChannelMute(listener, this) } override fun sendMessage(sender: RPKPlayer, message: String, isAsync: Boolean) { val bukkitPlayer = sender.bukkitPlayer if (bukkitPlayer != null) { val minecraftProfileProvider = plugin.core.serviceManager.getServiceProvider(RPKMinecraftProfileProvider::class) val minecraftProfile = minecraftProfileProvider.getMinecraftProfile(bukkitPlayer) if (minecraftProfile != null) { val profile = minecraftProfile.profile sendMessage(profile, minecraftProfile, message, isAsync) } } } override fun sendMessage(sender: RPKThinProfile, senderMinecraftProfile: RPKMinecraftProfile?, message: String, isAsync: Boolean) { sendMessage(sender, senderMinecraftProfile, message, directedPipeline, undirectedPipeline, isAsync) } override fun sendMessage(sender: RPKPlayer, message: String, directedPipeline: List<DirectedChatChannelPipelineComponent>, undirectedPipeline: List<UndirectedChatChannelPipelineComponent>, isAsync: Boolean) { val bukkitPlayer = sender.bukkitPlayer if (bukkitPlayer != null) { val minecraftProfileProvider = plugin.core.serviceManager.getServiceProvider(RPKMinecraftProfileProvider::class) val minecraftProfile = minecraftProfileProvider.getMinecraftProfile(bukkitPlayer) if (minecraftProfile != null) { val profile = minecraftProfile.profile sendMessage(profile, minecraftProfile, message, directedPipeline, undirectedPipeline, isAsync) } } } override fun sendMessage(sender: RPKThinProfile, senderMinecraftProfile: RPKMinecraftProfile?, message: String, directedPipeline: List<DirectedChatChannelPipelineComponent>, undirectedPipeline: List<UndirectedChatChannelPipelineComponent>, isAsync: Boolean) { val event = RPKBukkitChatChannelMessageEvent(sender, senderMinecraftProfile, this, message, isAsync) plugin.server.pluginManager.callEvent(event) if (event.isCancelled) return listenerMinecraftProfiles.forEach { listener -> var context: DirectedChatChannelMessageContext = DirectedChatChannelMessageContextImpl( event.chatChannel, event.profile, event.minecraftProfile, listener, event.message ) directedPipeline.forEach { component -> context = component.process(context) } } var context: UndirectedChatChannelMessageContext = UndirectedChatChannelMessageContextImpl( event.chatChannel, event.profile, event.minecraftProfile, event.message ) undirectedPipeline.forEach { component -> context = component.process(context) } } }
apache-2.0
8faeec2c30e90bc237cc785de2dc78bc
52.890244
263
0.740636
5.614358
false
false
false
false
kangsLee/sh8email-kotlin
app/src/main/kotlin/org/triplepy/sh8email/sh8/activities/login/di/LoginModule.kt
1
914
package org.triplepy.sh8email.sh8.activities.login.di import dagger.Module import dagger.Provides import org.triplepy.sh8email.sh8.activities.login.presenter.LoginPresenter import org.triplepy.sh8email.sh8.activities.login.presenter.LoginPresenterImpl import org.triplepy.sh8email.sh8.di.module.ClientModule /** * The sh8email-android Project. * ============================== * org.triplepy.sh8email.sh8.activities.login.di * ============================== * Created by igangsan on 2016. 9. 3.. */ @Module(includes = arrayOf(ClientModule::class)) class LoginModule { val view: LoginPresenter.View constructor(view: LoginPresenter.View) { this.view = view } @Provides fun provideLoginPresenter(loginPresenter: LoginPresenterImpl): LoginPresenter { return loginPresenter } @Provides fun provideLoginView(): LoginPresenter.View { return view } }
apache-2.0
fd8f9cd7ab27eb72c59d27349ac070b7
26.727273
83
0.693654
3.991266
false
false
false
false
EMResearch/EvoMaster
core/src/main/kotlin/org/evomaster/core/search/algorithms/WtsAlgorithm.kt
1
4265
package org.evomaster.core.search.algorithms import org.evomaster.core.EMConfig import org.evomaster.core.search.Individual import org.evomaster.core.search.Solution import org.evomaster.core.search.algorithms.wts.WtsEvalIndividual import org.evomaster.core.search.service.SearchAlgorithm /** * An implementation of the Whole Test Suite (WTS) algorithm, * as used in EvoSuite. * <br> * Each individual is a set of test cases (ie a test suite), * and we use a population algorithm as Genetic Algorithm (GA). * But still use an archive to do not lose best individuals. * <br> * Note: unless some unknown side-effect, or bug, WTS would be * worse than MIO on average. * This implementation was written mainly to run experiments on comparisons * of search algorithms, and not really something to * use regularly in EvoMaster */ class WtsAlgorithm<T> : SearchAlgorithm<T>() where T : Individual { private val population: MutableList<WtsEvalIndividual<T>> = mutableListOf() override fun getType(): EMConfig.Algorithm { return EMConfig.Algorithm.WTS } override fun setupBeforeSearch() { population.clear() initPopulation() } override fun searchOnce() { val n = config.populationSize //new generation val nextPop: MutableList<WtsEvalIndividual<T>> = mutableListOf() while (nextPop.size < n) { val x = selection() val y = selection() //x and y are copied if (randomness.nextBoolean(config.xoverProbability)) { xover(x, y) } mutate(x) mutate(y) nextPop.add(x) nextPop.add(y) if (!time.shouldContinueSearch()) { break } } population.clear() population.addAll(nextPop) } private fun mutate(wts: WtsEvalIndividual<T>) { val op = randomness.choose(listOf("del", "add", "mod")) val n = wts.suite.size when (op) { "del" -> if (n > 1) { val i = randomness.nextInt(n) wts.suite.removeAt(i) } "add" -> if (n < config.maxSearchSuiteSize) { ff.calculateCoverage(sampler.sample())?.run { archive.addIfNeeded(this) wts.suite.add(this) } } "mod" -> { val i = randomness.nextInt(n) val ind = wts.suite[i] getMutatator().mutateAndSave(ind, archive) ?.let { wts.suite[i] = it } } } } private fun selection(): WtsEvalIndividual<T> { val x = randomness.choose(population) val y = randomness.choose(population) val dif = x.calculateCombinedFitness() - y.calculateCombinedFitness() val delta = 0.001 return when { dif > delta -> x.copy() dif < -delta -> y.copy() else -> when { x.size() <= y.size() -> x.copy() else -> y.copy() } } } private fun xover(x: WtsEvalIndividual<T>, y: WtsEvalIndividual<T>) { val nx = x.suite.size val ny = y.suite.size val i = randomness.nextInt(Math.min(nx, ny)) (0..i).forEach { val k = x.suite[i] x.suite[i] = y.suite[i] y.suite[i] = k } } private fun initPopulation() { val n = config.populationSize for (i in 1..n) { population.add(sampleSuite()) if (!time.shouldContinueSearch()) { break } } } private fun sampleSuite(): WtsEvalIndividual<T> { val n = 1 + randomness.nextInt(config.maxSearchSuiteSize) val wts = WtsEvalIndividual<T>(mutableListOf()) for (i in 1..n) { ff.calculateCoverage(sampler.sample())?.run { archive.addIfNeeded(this) wts.suite.add(this) } if (!time.shouldContinueSearch()) { break } } return wts } }
lgpl-3.0
2373411ff8a041696255d564b5988eb7
25.171779
79
0.534115
4.197835
false
false
false
false
bubelov/coins-android
app/src/main/java/com/bubelov/coins/map/MapFragment.kt
1
18067
package com.bubelov.coins.map import android.Manifest import android.annotation.SuppressLint import androidx.lifecycle.Observer import android.content.pm.PackageManager import android.content.res.Configuration import android.os.Bundle import android.preference.PreferenceManager import com.google.android.material.bottomsheet.BottomSheetBehavior import androidx.appcompat.app.ActionBarDrawerToggle import androidx.appcompat.widget.Toolbar import android.text.TextUtils import android.view.* import androidx.core.graphics.drawable.toDrawable import androidx.core.os.bundleOf import androidx.core.view.isVisible import androidx.fragment.app.Fragment import androidx.lifecycle.lifecycleScope import androidx.navigation.fragment.findNavController import com.bubelov.coins.R import com.bubelov.coins.auth.AuthResultViewModel import com.bubelov.coins.data.Place import com.bubelov.coins.model.Location import com.bubelov.coins.placedetails.PlaceDetailsFragment import com.bubelov.coins.search.PlacesSearchResultViewModel import com.bubelov.coins.util.* import com.squareup.picasso.Picasso import kotlinx.android.synthetic.main.fragment_map.* import kotlinx.android.synthetic.main.navigation_drawer_header.view.* import kotlinx.coroutines.* import kotlinx.coroutines.flow.* import org.koin.android.viewmodel.ext.android.sharedViewModel import org.koin.android.viewmodel.ext.android.viewModel import org.osmdroid.events.MapListener import org.osmdroid.events.ScrollEvent import org.osmdroid.events.ZoomEvent import org.osmdroid.tileprovider.tilesource.TileSourceFactory import org.osmdroid.util.GeoPoint import org.osmdroid.views.CustomZoomButtonsController import org.osmdroid.views.overlay.ItemizedIconOverlay import org.osmdroid.views.overlay.OverlayItem import org.osmdroid.views.overlay.mylocation.GpsMyLocationProvider import org.osmdroid.views.overlay.mylocation.MyLocationNewOverlay import kotlin.math.max import kotlin.math.min class MapFragment : Fragment(), Toolbar.OnMenuItemClickListener { private val model: MapViewModel by viewModel() private val log by lazy { model.log } private val placesSearchResultModel: PlacesSearchResultViewModel by sharedViewModel() private val authResultModel: AuthResultViewModel by sharedViewModel() private val placeDetailsFragment by lazy { childFragmentManager.findFragmentById(R.id.placeDetailsFragment) as PlaceDetailsFragment } private lateinit var drawerHeader: View private lateinit var drawerToggle: ActionBarDrawerToggle private lateinit var bottomSheetBehavior: BottomSheetBehavior<*> var locationOverlay: MyLocationNewOverlay? = null override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { org.osmdroid.config.Configuration.getInstance() .load(requireContext(), PreferenceManager.getDefaultSharedPreferences(requireContext())) return inflater.inflate(R.layout.fragment_map, container, false) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { drawerHeader = navigationView.getHeaderView(0) initMap() bottomSheetBehavior = BottomSheetBehavior.from(placeDetails).apply { state = BottomSheetBehavior.STATE_HIDDEN setBottomSheetCallback(object : BottomSheetBehavior.BottomSheetCallback() { override fun onStateChanged(bottomSheet: View, newState: Int) { } override fun onSlide(bottomSheet: View, slideOffset: Float) { locationFab.isVisible = slideOffset < 0.5f placeDetailsFragment.setScrollProgress(slideOffset) } }) peekHeight = resources.getDimensionPixelSize(R.dimen.map_header_height) } editPlaceFab.setOnClickListener { lifecycleScope.launchWhenResumed { model.onEditPlaceClick() } } toolbar.apply { setNavigationOnClickListener { drawerLayout.openDrawer(navigationView) } inflateMenu(R.menu.map) setOnMenuItemClickListener(this@MapFragment) } navigationView.setNavigationItemSelectedListener { item -> drawerLayout.closeDrawer(navigationView, false) when (item.itemId) { R.id.action_exchange_rates -> { findNavController().navigate(R.id.action_mapFragment_to_exchangeRatesFragment) } R.id.action_notification_area -> { findNavController().navigate(R.id.action_mapFragment_to_notificationAreaFragment) } R.id.action_chat -> openSupportChat() R.id.action_support_project -> { findNavController().navigate(R.id.action_mapFragment_to_supportProjectFragment) } R.id.action_settings -> { findNavController().navigate(R.id.action_mapFragment_to_settingsFragment) } } true } drawerToggle = ActionBarDrawerToggle( requireActivity(), drawerLayout, toolbar, R.string.open, R.string.close ) drawerLayout.addDrawerListener(drawerToggle) lifecycleScope.launchWhenResumed { updateDrawerHeader() } placeDetails.setOnClickListener { if (bottomSheetBehavior.state == BottomSheetBehavior.STATE_COLLAPSED) { bottomSheetBehavior.state = BottomSheetBehavior.STATE_EXPANDED } else { bottomSheetBehavior.setState(BottomSheetBehavior.STATE_COLLAPSED) } } lifecycleScope.launch { model.selectedPlaceFlow.collect { if (it != null) { placeDetailsFragment.setPlace(it) bottomSheetBehavior.state = BottomSheetBehavior.STATE_COLLAPSED } else { bottomSheetBehavior.state = BottomSheetBehavior.STATE_HIDDEN } } } locationFab.setOnClickListener { val location = model.location.value val mapController = map.controller mapController.setZoom(DEFAULT_MAP_ZOOM.toDouble()) val startPoint = GeoPoint(location.latitude, location.longitude) mapController.setCenter(startPoint) } placesSearchResultModel.pickedPlaceId.observe(viewLifecycleOwner, Observer { id -> lifecycleScope.launch { model.selectPlace(id ?: "") } }) authResultModel.authorized.observe(viewLifecycleOwner, Observer { runBlocking { updateDrawerHeader() } when (model.postAuthAction) { PostAuthAction.ADD_PLACE -> { val action = MapFragmentDirections.actionMapFragmentToEditPlaceFragment( null, Location(map.boundingBox.centerLatitude, map.boundingBox.centerLongitude) ) findNavController().navigate(action) } PostAuthAction.EDIT_SELECTED_PLACE -> { lifecycleScope.launch { val selectedPlace = model.selectedPlaceFlow.toList().lastOrNull() ?: return@launch val action = MapFragmentDirections.actionMapFragmentToEditPlaceFragment( selectedPlace.id, Location( map.boundingBox.centerLatitude, map.boundingBox.centerLongitude ) ) findNavController().navigate(action) } } } }) } override fun onResume() { super.onResume() map.onResume() drawerToggle.syncState() val placeId = arguments?.getString(PLACE_ID_ARG) if (placeId != null) { lifecycleScope.launch { model.selectPlace(placeId) } //model.moveToLocation(Location(placeArg.latitude, placeArg.longitude)) } } override fun onPause() { super.onPause() map.onPause() } @SuppressLint("MissingPermission") override fun onRequestPermissionsResult( requestCode: Int, permissions: Array<String>, grantResults: IntArray ) { when (requestCode) { REQUEST_ACCESS_LOCATION -> if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) { //model.onLocationPermissionGranted() } } } override fun onMenuItemClick(item: MenuItem): Boolean { when (item.itemId) { R.id.action_add -> { lifecycleScope.launchWhenResumed { model.onAddPlaceClick() } } R.id.action_search -> { lifecycleScope.launch { val action = MapFragmentDirections.actionMapFragmentToPlacesSearchFragment( model.location.value ) findNavController().navigate(action) } } else -> return super.onOptionsItemSelected(item) } return true } override fun onConfigurationChanged(newConfig: Configuration) { drawerToggle.onConfigurationChanged(newConfig) super.onConfigurationChanged(newConfig) } fun showUserProfile() { findNavController().navigate(R.id.action_mapFragment_to_profileFragment) } private fun requestLocationPermissions() { requestPermissions( arrayOf( Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.WRITE_EXTERNAL_STORAGE ), REQUEST_ACCESS_LOCATION ) } @SuppressLint("MissingPermission") private fun initMap() { log += "initMap()" if (view == null) { return } val appContext = requireContext().applicationContext org.osmdroid.config.Configuration.getInstance().load( appContext, PreferenceManager.getDefaultSharedPreferences(appContext) ) map.setTileSource(TileSourceFactory.MAPNIK) map.zoomController.setVisibility(CustomZoomButtonsController.Visibility.NEVER) map.setMultiTouchControls(true) //initClustering(map) // lifecycleScope.launch { //model.onMapReady() // model.selectedPlaceFlow.collect { place -> // if (place != null && model.navigateToNextSelectedPlace) { // val mapController = map.controller // mapController.setZoom(DEFAULT_MAP_ZOOM.toDouble()) // val startPoint = GeoPoint(place.latitude, place.longitude) // mapController.setCenter(startPoint) // // model.navigateToNextSelectedPlace = false // } // } // } // model.moveMapToLocation.observe(viewLifecycleOwner, Observer { // it?.let { location -> // if (locationOverlay == null) { // locationOverlay = // MyLocationNewOverlay(GpsMyLocationProvider(context), map).apply { // enableMyLocation() // map.overlays += this // } // } // // val mapController = map.controller // mapController.setZoom(DEFAULT_MAP_ZOOM.toDouble()) // val startPoint = GeoPoint(location.latitude, location.longitude) // mapController.setCenter(startPoint) // } // }) lifecycleScope.launchWhenResumed { model.location.collect { if (locationOverlay == null) { locationOverlay = MyLocationNewOverlay(GpsMyLocationProvider(context), map).apply { enableMyLocation() map.overlays += this } val mapController = map.controller mapController.setZoom(DEFAULT_MAP_ZOOM.toDouble()) val startPoint = GeoPoint(it.latitude, it.longitude) mapController.setCenter(startPoint) } } } var showPlacesJob: Job? = null map.addMapListener(object : MapListener { override fun onScroll(event: ScrollEvent?): Boolean { map.overlays.clear() showPlacesJob?.cancel() showPlacesJob = lifecycleScope.launch { delay(100) val items = mutableListOf<OverlayItem>() model.getMarkers( minLat = min(map.boundingBox.latNorth, map.boundingBox.latSouth), maxLat = max(map.boundingBox.latNorth, map.boundingBox.latSouth), minLon = min(map.boundingBox.lonEast, map.boundingBox.lonWest), maxLon = max(map.boundingBox.lonEast, map.boundingBox.lonWest) ).collect { log += "Loaded ${it.size} markers from cache" it.forEach { place -> items += OverlayItem( "Title", "Description", GeoPoint(place.latitude, place.longitude) ).apply { setMarker(place.icon.toDrawable(resources)) } } val overlay = ItemizedIconOverlay(requireContext(), items, null) if (isActive) { map.overlays.add(overlay) map.invalidate() log += "Added ${items.size} markers" } } } return false } override fun onZoom(event: ZoomEvent?) = false }) } private suspend fun updateDrawerHeader() { val user = model.userRepository.getUser() if (user != null) { if (!TextUtils.isEmpty(user.avatarUrl)) { Picasso.get() .load(user.avatarUrl) .transform(CircleTransformation()) .into(drawerHeader.avatar) } else { drawerHeader.avatar.setImageResource(R.drawable.ic_no_avatar) } if (!TextUtils.isEmpty(user.firstName)) { drawerHeader.userName.text = String.format("%s %s", user.firstName, user.lastName) } else { drawerHeader.userName.text = user.email } } else { drawerHeader.avatar.setImageResource(R.drawable.ic_no_avatar) drawerHeader.userName.setText(R.string.guest) } drawerHeader.setOnClickListener { lifecycleScope.launchWhenResumed { drawerLayout.closeDrawer(navigationView) model.onDrawerHeaderClick() } } } private fun openSupportChat() { requireContext().openUrl("https://t.me/joinchat/AAAAAAwVT4aVBdFzcKKbsw") } // private fun initClustering(map: GoogleMap) { // val placesManager = ClusterManager<PlaceMarker>(requireContext(), map) // placesManager.setAnimation(false) // map.setOnMarkerClickListener(placesManager) // // val renderer = PlacesRenderer(requireContext(), map, placesManager) // renderer.setAnimation(false) // placesManager.renderer = renderer // // renderer.setOnClusterItemClickListener(ClusterItemClickListener()) // // map.setOnCameraIdleListener { // placesManager.onCameraIdle() // model.mapBounds.value = map.projection.visibleRegion.latLngBounds // } // // map.setOnMapClickListener { // model.selectPlace("") // } // // model.placeMarkers.observe(viewLifecycleOwner, Observer { markers -> // placesManager.clearItems() // placesManager.addItems(markers) // placesManager.cluster() // }) // } // private inner class PlacesRenderer internal constructor( // context: Context, // map: GoogleMap, // clusterManager: ClusterManager<PlaceMarker> // ) : DefaultClusterRenderer<PlaceMarker>(context, map, clusterManager) { // override fun onBeforeClusterItemRendered( // placeMarker: PlaceMarker, // markerOptions: MarkerOptions // ) { // super.onBeforeClusterItemRendered(placeMarker, markerOptions) // // markerOptions // .icon(BitmapDescriptorFactory.fromBitmap(placeMarker.icon)) // .anchor(BuildConfig.MAP_MARKER_ANCHOR_U, BuildConfig.MAP_MARKER_ANCHOR_V) // } // } // private inner class ClusterItemClickListener : // ClusterManager.OnClusterItemClickListener<PlaceMarker> { // override fun onClusterItemClick(placeMarker: PlaceMarker): Boolean { // model.selectPlace(placeMarker.placeId) // return true // } // } companion object { private const val REQUEST_ACCESS_LOCATION = 10 private const val DEFAULT_MAP_ZOOM = 15f private const val PLACE_ID_ARG = "place_id" fun newOpenPlaceArguments(place: Place): Bundle { return bundleOf(Pair(PLACE_ID_ARG, place.id)) } } }
unlicense
f319abf46b314411f79bac8a78df5d2c
33.746154
127
0.589805
5.350015
false
false
false
false
Esri/arcgis-runtime-samples-android
kotlin/export-tiles/src/main/java/com/esri/arcgisruntime/sample/exporttiles/MainActivity.kt
1
12418
/* * Copyright 2020 Esri * * 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.esri.arcgisruntime.sample.exporttiles import android.graphics.Color import android.os.Bundle import android.util.Log import android.view.View import android.widget.Button import android.widget.TextView import android.widget.Toast import androidx.appcompat.app.AlertDialog import androidx.appcompat.app.AppCompatActivity import androidx.constraintlayout.widget.ConstraintLayout import com.esri.arcgisruntime.ArcGISRuntimeEnvironment import com.esri.arcgisruntime.concurrent.Job import com.esri.arcgisruntime.concurrent.ListenableFuture import com.esri.arcgisruntime.data.TileCache import com.esri.arcgisruntime.geometry.Envelope import com.esri.arcgisruntime.geometry.Point import com.esri.arcgisruntime.layers.ArcGISTiledLayer import com.esri.arcgisruntime.loadable.LoadStatus import com.esri.arcgisruntime.mapping.ArcGISMap import com.esri.arcgisruntime.mapping.Basemap import com.esri.arcgisruntime.mapping.BasemapStyle import com.esri.arcgisruntime.mapping.Viewpoint import com.esri.arcgisruntime.mapping.view.Graphic import com.esri.arcgisruntime.mapping.view.GraphicsOverlay import com.esri.arcgisruntime.mapping.view.MapView import com.esri.arcgisruntime.sample.exporttiles.databinding.ActivityMainBinding import com.esri.arcgisruntime.sample.exporttiles.databinding.ExportTilesDialogLayoutBinding import com.esri.arcgisruntime.symbology.SimpleLineSymbol import com.esri.arcgisruntime.tasks.tilecache.ExportTileCacheJob import com.esri.arcgisruntime.tasks.tilecache.ExportTileCacheParameters import com.esri.arcgisruntime.tasks.tilecache.ExportTileCacheTask import java.io.File class MainActivity : AppCompatActivity() { private val TAG: String = MainActivity::class.java.simpleName private var exportTileCacheJob: ExportTileCacheJob? = null private var downloadArea: Graphic? = null private val activityMainBinding by lazy { ActivityMainBinding.inflate(layoutInflater) } private val exportTilesButton: Button by lazy { activityMainBinding.exportTilesButton } private val mapPreviewLayout: ConstraintLayout by lazy { activityMainBinding.mapPreviewLayout } private val previewTextView: TextView by lazy { activityMainBinding.previewTextView } private val mapView: MapView by lazy { activityMainBinding.mapView } private val closeButton: Button by lazy { activityMainBinding.closeButton } private val previewMapView: MapView by lazy { activityMainBinding.previewMapView } private val dimBackground: View by lazy { activityMainBinding.dimBackground } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(activityMainBinding.root) // authentication with an API key or named user is required // to access basemaps and other location services ArcGISRuntimeEnvironment.setApiKey(BuildConfig.API_KEY) // create an ArcGISTiledLayer to use as the basemap val map = ArcGISMap().apply { basemap = Basemap(BasemapStyle.ARCGIS_IMAGERY) minScale = 10000000.0 } // create a graphic and graphics overlay to show a red box around the tiles to be downloaded downloadArea = Graphic() downloadArea?.symbol = SimpleLineSymbol(SimpleLineSymbol.Style.SOLID, Color.RED, 2f) val graphicsOverlay = GraphicsOverlay() graphicsOverlay.graphics.add(downloadArea) // set the map to the map view mapView.map = map mapView.setViewpoint(Viewpoint(35.0, -117.0, 10000000.0)) // add the graphics overlay to the map view mapView.graphicsOverlays.add(graphicsOverlay) mapView.addViewpointChangedListener { updateDownloadAreaGeometry() } map.addDoneLoadingListener { val tiledLayer: ArcGISTiledLayer = map.basemap.baseLayers[0] as ArcGISTiledLayer // when the button is clicked, export the tiles to the temporary directory exportTilesButton.setOnClickListener { updateDownloadAreaGeometry() val exportTileCacheTask = ExportTileCacheTask(tiledLayer.uri) // set up the export tile cache parameters val parametersFuture: ListenableFuture<ExportTileCacheParameters> = exportTileCacheTask.createDefaultExportTileCacheParametersAsync( downloadArea?.geometry, mapView.mapScale, mapView.mapScale * 0.1 ) parametersFuture.addDoneListener { try { val parameters: ExportTileCacheParameters = parametersFuture.get() // create a temporary directory in the app's cache for saving exported tiles val exportTilesDirectory = File(externalCacheDir, getString(R.string.tile_cache_folder)) // export tiles to temporary cache on device exportTileCacheJob = exportTileCacheTask.exportTileCache( parameters, exportTilesDirectory.path + "file.tpkx" ).apply { // start the export tile cache job start() val dialogLayoutBinding = ExportTilesDialogLayoutBinding.inflate(layoutInflater) // show progress of the export tile cache job on the progress bar val dialog = createProgressDialog(this) dialog.setView(dialogLayoutBinding.root) dialog.show() // on progress change addProgressChangedListener { dialogLayoutBinding.progressBar.progress = progress dialogLayoutBinding.progressTextView.text = "$progress%" } // when the job has completed, close the dialog and show the job result in the map preview addJobDoneListener { dialog.dismiss() if (status == Job.Status.SUCCEEDED) { showMapPreview(result) downloadArea?.isVisible = false } else { ("Job did not succeed: " + error.additionalMessage).also { Toast.makeText(this@MainActivity, it, Toast.LENGTH_LONG) .show() Log.e(TAG, error.additionalMessage) } } } } } catch (e: Exception) { val error = "Error generating tile cache parameters: ${e.message}" Toast.makeText(this, error, Toast.LENGTH_LONG).show() Log.e(TAG, error) } } } } // get correct view order set up on start clearPreview(mapView) } /** * Updates the [downloadArea]'s geometry on ViewPoint change * or when export tiles is clicked. */ private fun updateDownloadAreaGeometry() { try { mapView.apply { if (mapView.map.loadStatus == LoadStatus.LOADED) { // upper left corner of the downloaded tile cache area val minScreenPoint: android.graphics.Point = android.graphics.Point(150, 175) // lower right corner of the downloaded tile cache area val maxScreenPoint: android.graphics.Point = android.graphics.Point( mapView.width - 150, mapView.height - 250 ) // convert screen points to map points val minPoint: Point = mapView.screenToLocation(minScreenPoint) val maxPoint: Point = mapView.screenToLocation(maxScreenPoint) // use the points to define and return an envelope downloadArea?.geometry = Envelope(minPoint, maxPoint) } } } catch (e: java.lang.Exception) { // Silently fail, since mapView has not been rendered yet. } } /** * Show tile cache preview window including containing the exported tiles. * * @param result takes the TileCache from the ExportTileCacheJob */ private fun showMapPreview(result: TileCache) { // set up the preview map view previewMapView.apply { map = ArcGISMap(Basemap(ArcGISTiledLayer(result))) setViewpoint(mapView.getCurrentViewpoint(Viewpoint.Type.CENTER_AND_SCALE)) } // control UI visibility previewMapView.getChildAt(0).visibility = View.VISIBLE show(closeButton, dimBackground, previewTextView, previewMapView) exportTilesButton.visibility = View.GONE // required for some Android devices running older OS (combats Z-ordering bug in Android API) mapPreviewLayout.bringToFront() } /** * Clear the preview window. */ fun clearPreview(view: View) { previewMapView.getChildAt(0).visibility = View.INVISIBLE hide(closeButton, dimBackground, previewTextView, previewMapView) // control UI visibility show(exportTilesButton, mapView) downloadArea?.isVisible = true // required for some Android devices running older OS (combats Z-ordering bug in Android API) mapView.bringToFront() } /** * Create a progress dialog box for tracking the export tile cache job. * * @param exportTileCacheJob the export tile cache job progress to be tracked * @return an AlertDialog set with the dialog layout view */ private fun createProgressDialog(exportTileCacheJob: ExportTileCacheJob): AlertDialog { val builder = AlertDialog.Builder(this@MainActivity).apply { setTitle("Exporting tiles...") // provide a cancel button on the dialog setNeutralButton("Cancel") { _, _ -> exportTileCacheJob.cancelAsync() } setCancelable(false) val dialogLayoutBinding = ExportTilesDialogLayoutBinding.inflate(layoutInflater) setView(dialogLayoutBinding.root) } return builder.create() } /** * Makes the given views in the UI visible. * * @param views the views to be made visible */ private fun show(vararg views: View) { for (view in views) { view.visibility = View.VISIBLE } } /** * Makes the given views in the UI visible. * * @param views the views to be made visible */ private fun hide(vararg views: View) { for (view in views) { view.visibility = View.INVISIBLE } } override fun onResume() { super.onResume() mapView.resume() previewMapView.resume() } override fun onPause() { mapView.pause() previewMapView.pause() super.onPause() } override fun onDestroy() { mapView.dispose() super.onDestroy() } }
apache-2.0
b0771c93857911a1b5a1eb13d35b9a6e
38.173502
122
0.610726
5.380416
false
false
false
false
jayrave/falkon
falkon-dao/src/main/kotlin/com/jayrave/falkon/dao/update/UpdateBuilderImpl.kt
1
4061
package com.jayrave.falkon.dao.update import com.jayrave.falkon.dao.lib.LinkedHashMapBackedDataConsumer import com.jayrave.falkon.dao.where.AfterSimpleConnectorAdder import com.jayrave.falkon.dao.where.Where import com.jayrave.falkon.dao.where.WhereBuilder import com.jayrave.falkon.dao.where.WhereBuilderImpl import com.jayrave.falkon.engine.CompiledStatement import com.jayrave.falkon.engine.bindAll import com.jayrave.falkon.engine.closeIfOpThrows import com.jayrave.falkon.engine.safeCloseAfterExecution import com.jayrave.falkon.iterables.IterableBackedIterable import com.jayrave.falkon.iterables.IterablesBackedIterable import com.jayrave.falkon.mapper.Column import com.jayrave.falkon.mapper.Table import com.jayrave.falkon.sqlBuilders.UpdateSqlBuilder import com.jayrave.falkon.dao.where.AdderOrEnder as WhereAdderOrEnder internal class UpdateBuilderImpl<T : Any>( override val table: Table<T, *>, private val updateSqlBuilder: UpdateSqlBuilder) : UpdateBuilder<T> { private val dataConsumer = LinkedHashMapBackedDataConsumer() private var whereBuilder: WhereBuilderImpl<T, PredicateAdderOrEnder<T>>? = null /** * Calling this method again for columns that have been already set will overwrite the * existing values for those columns */ override fun values(setter: InnerSetter<T>.() -> Any?): AdderOrEnder<T> { InnerSetterImpl().setter() return AdderOrEnderImpl() } private fun build(): Update { val map = dataConsumer.map val where: Where? = whereBuilder?.build() val columns: Iterable<String> = IterableBackedIterable.create(map.keys) val sql = updateSqlBuilder.build(table.name, columns, where?.whereSections) val arguments = IterablesBackedIterable(listOf( IterableBackedIterable.create(map.values), where?.arguments ?: emptyList() )) return UpdateImpl(table.name, sql, arguments) } private fun compile(): CompiledStatement<Int> { val update = build() return table.configuration.engine .compileUpdate(table.name, update.sql) .closeIfOpThrows { bindAll(update.arguments) } } private fun update(): Int { return compile().safeCloseAfterExecution() } private inner class AdderOrEnderImpl : AdderOrEnder<T> { override fun where(): WhereBuilder<T, PredicateAdderOrEnder<T>> { whereBuilder = WhereBuilderImpl({ PredicateAdderOrEnderImpl(it) }) return whereBuilder!! } override fun build(): Update { return [email protected]() } override fun compile(): CompiledStatement<Int> { return [email protected]() } override fun update(): Int { return [email protected]() } } private inner class PredicateAdderOrEnderImpl( private val delegate: WhereAdderOrEnder<T, PredicateAdderOrEnder<T>>) : PredicateAdderOrEnder<T> { override fun and(): AfterSimpleConnectorAdder<T, PredicateAdderOrEnder<T>> { return delegate.and() } override fun or(): AfterSimpleConnectorAdder<T, PredicateAdderOrEnder<T>> { return delegate.or() } override fun build(): Update { return [email protected]() } override fun compile(): CompiledStatement<Int> { return [email protected]() } override fun update(): Int { return [email protected]() } } private inner class InnerSetterImpl : InnerSetter<T> { /** * Calling this method again for a column that has been already set will overwrite the * existing value for that column */ override fun <C> set(column: Column<T, C>, value: C) { dataConsumer.setColumnName(column.name) column.putStorageFormIn(value, dataConsumer) } } }
apache-2.0
3ba9ad0ec5f633d6a2fede3f193a2084
33.134454
94
0.674218
4.5578
false
false
false
false
prgpascal/android-qr-data-transfer
android-qr-data-transfer/src/main/java/com/prgpascal/qrdatatransfer/viewmodels/ClientAckSenderViewModel.kt
1
3659
/* * Copyright (C) 2016 Riccardo Leschiutta * * 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.prgpascal.qrdatatransfer.viewmodels import android.bluetooth.BluetoothAdapter import android.bluetooth.BluetoothSocket import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel import com.prgpascal.qrdatatransfer.utils.CHARACTER_SET_EXPANDED import com.prgpascal.qrdatatransfer.utils.T_UUID import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import java.io.IOException import java.nio.charset.Charset class ClientAckSenderViewModel : ViewModel() { private var isRunning = false val lastSentAckLiveData = MutableLiveData<String>() private var serverMacAddress: String? = null private var nextAckToSend: String? = null fun start(serverMacAddress: String) { this.serverMacAddress = serverMacAddress if (!isRunning) { CoroutineScope(Dispatchers.IO).launch { sendAckToServer() } } } fun stop() { isRunning = false } fun sendAck(ack: String) { this.nextAckToSend = ack } private suspend fun sendAckToServer() = withContext(Dispatchers.IO) { isRunning = true val serverDevice = BluetoothAdapter.getDefaultAdapter().getRemoteDevice(serverMacAddress) var socket: BluetoothSocket? = null while (isRunning) { try { socket = serverDevice.createRfcommSocketToServiceRecord(T_UUID) socket.connect() } catch (e: IOException) { e.printStackTrace() } if (socket != null) { while (isRunning && socket.isConnected) { if (nextAckToSend != null && nextAckToSend != lastSentAckLiveData.value) { val ack = nextAckToSend val outputStream = socket.outputStream val inputStream = socket.inputStream try { outputStream.write(ack?.toByteArray(Charset.forName(CHARACTER_SET_EXPANDED))) outputStream.flush() val bytes = ByteArray(1024) val length = inputStream.read(bytes) val returnedAck = String(bytes, 0, length, Charset.forName(CHARACTER_SET_EXPANDED)) if (returnedAck == ack) { lastSentAckLiveData.postValue(returnedAck) } } catch (e: Exception) { e.printStackTrace() } finally { outputStream.close() } } } if (socket.isConnected) { try { socket.close() } catch (ioe: IOException) { ioe.printStackTrace() } } } } } }
apache-2.0
fa536e45f92278ef7b19efd8ca6d3362
33.528302
111
0.583766
5.175389
false
false
false
false
RP-Kit/RPKit
bukkit/rpk-classes-bukkit/src/main/kotlin/com/rpkit/classes/bukkit/command/class/ClassSetCommand.kt
1
4053
/* * 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.classes.bukkit.command.`class` import com.rpkit.characters.bukkit.character.RPKCharacterService import com.rpkit.classes.bukkit.RPKClassesBukkit import com.rpkit.classes.bukkit.classes.RPKClassName import com.rpkit.classes.bukkit.classes.RPKClassService import com.rpkit.core.service.Services import com.rpkit.players.bukkit.profile.minecraft.RPKMinecraftProfileService import org.bukkit.command.Command import org.bukkit.command.CommandExecutor import org.bukkit.command.CommandSender import org.bukkit.entity.Player class ClassSetCommand(private val plugin: RPKClassesBukkit) : CommandExecutor { override fun onCommand(sender: CommandSender, command: Command, label: String, args: Array<out String>): Boolean { if (!sender.hasPermission("rpkit.classes.command.class.set")) { sender.sendMessage(plugin.messages["no-permission-class-set"]) return true } if (args.isEmpty()) { sender.sendMessage(plugin.messages["class-set-usage"]) 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 characterService = Services[RPKCharacterService::class.java] if (characterService == null) { sender.sendMessage(plugin.messages["no-character-service"]) return true } val classService = Services[RPKClassService::class.java] if (classService == null) { sender.sendMessage(plugin.messages["no-class-service"]) return true } val minecraftProfile = minecraftProfileService.getPreloadedMinecraftProfile(sender) if (minecraftProfile == null) { sender.sendMessage(plugin.messages["no-minecraft-profile"]) return true } val character = characterService.getPreloadedActiveCharacter(minecraftProfile) if (character == null) { sender.sendMessage(plugin.messages["no-character"]) return true } val className = args[0] val `class` = classService.getClass(RPKClassName(className)) if (`class` == null) { sender.sendMessage(plugin.messages["class-set-invalid-class"]) return true } `class`.hasPrerequisites(character).thenAccept { hasPrerequisites -> if (!hasPrerequisites) { sender.sendMessage(plugin.messages["class-set-invalid-prerequisites"]) return@thenAccept } val isAgeValid: Boolean = character.age < `class`.maxAge && character.age >= `class`.minAge if (isAgeValid) { classService.setClass(character, `class`).thenRun { sender.sendMessage( plugin.messages["class-set-valid", mapOf( "class" to `class`.name.value )] ) } } else { sender.sendMessage(plugin.messages.classSetInvalidAge.withParameters(`class`.maxAge, `class`.minAge)) return@thenAccept } } return true } }
apache-2.0
1005a407c4801f8858fd9d6a0e3cc046
40.357143
118
0.644708
4.807829
false
false
false
false
RP-Kit/RPKit
bukkit/rpk-professions-bukkit/src/main/kotlin/com/rpkit/professions/bukkit/listener/AsyncPlayerPreLoginListener.kt
1
1362
package com.rpkit.professions.bukkit.listener import com.rpkit.characters.bukkit.character.RPKCharacterService import com.rpkit.core.service.Services import com.rpkit.players.bukkit.profile.minecraft.RPKMinecraftProfileService import com.rpkit.professions.bukkit.profession.RPKProfessionService import org.bukkit.event.EventHandler import org.bukkit.event.Listener import org.bukkit.event.player.AsyncPlayerPreLoginEvent import java.util.concurrent.CompletableFuture class AsyncPlayerPreLoginListener : Listener { @EventHandler fun onAsyncPlayerPreLogin(event: AsyncPlayerPreLoginEvent) { val minecraftProfileService = Services[RPKMinecraftProfileService::class.java] ?: return val characterService = Services[RPKCharacterService::class.java] ?: return val professionService = Services[RPKProfessionService::class.java] ?: return val minecraftProfile = minecraftProfileService.getMinecraftProfile(event.uniqueId).join() ?: return val character = characterService.getActiveCharacter(minecraftProfile).join() ?: return professionService.loadProfessions(character).thenAccept { professions -> CompletableFuture.allOf(*professions.map { profession -> professionService.loadProfessionExperience(character, profession) }.toTypedArray()).join() }.join() } }
apache-2.0
597fc44a4792e086bb28b5b16cb8389e
47.678571
107
0.778267
5.426295
false
false
false
false
ajalt/clikt
clikt/src/commonTest/kotlin/com/github/ajalt/clikt/core/ContextTest.kt
1
3716
package com.github.ajalt.clikt.core import com.github.ajalt.clikt.parameters.arguments.argument import com.github.ajalt.clikt.parameters.arguments.multiple import com.github.ajalt.clikt.parameters.options.option import com.github.ajalt.clikt.testing.TestCommand import com.github.ajalt.clikt.testing.parse import io.kotest.assertions.throwables.shouldThrow import io.kotest.matchers.should import io.kotest.matchers.shouldBe import io.kotest.matchers.types.beInstanceOf import io.kotest.matchers.types.shouldBeSameInstanceAs import kotlin.js.JsName import kotlin.test.Test class ContextTest { class Foo @Test @JsName("find_functions_single_context") fun `find functions single context`() { class C : TestCommand() { val o1 by findObject<String>() val o2 by findOrSetObject { "foo" } val o3 by findObject<String>() val o4 by findObject<Int>() override fun run_() { currentContext.findRoot() shouldBe currentContext } } val c = C().apply { parse(emptyArray()) } c.o1 shouldBe null c.o2 shouldBe "foo" c.o3 shouldBe "foo" c.o4 shouldBe null } @Test @JsName("find_functions_parent_context") fun `find functions parent context`() { val foo = Foo() class C : TestCommand(invokeWithoutSubcommand = true) { val o1 by findObject<Foo>() val o2 by findOrSetObject { foo } val o3 by findObject<Foo>() val o4 by findObject<Int>() override fun run_() { currentContext.findRoot() shouldBe currentContext } } val child = C() val parent = C().subcommands(child).apply { parse(emptyArray()) } parent.o1 shouldBe child.o1 parent.o1 shouldBe null parent.o2 shouldBe child.o2 parent.o2 shouldBe foo parent.o3 shouldBe child.o3 parent.o3 shouldBe foo parent.o4 shouldBe child.o4 parent.o4 shouldBe null } @Test @JsName("requireObject_with_parent_context") fun `requireObject with parent context`() { class C : TestCommand(invokeWithoutSubcommand = true) { val o1 by findOrSetObject { Foo() } val o2 by requireObject<Foo>() } val child = C() val parent = C().subcommands(child).apply { parse(emptyArray()) } shouldThrow<NullPointerException> { parent.o2 } shouldThrow<NullPointerException> { child.o2 } parent.o1 should beInstanceOf(Foo::class) parent.o2 shouldBeSameInstanceAs parent.o1 child.o1 shouldBeSameInstanceAs parent.o1 child.o2 shouldBeSameInstanceAs parent.o1 } @Test @JsName("default_help_option_names") fun `default help option names`() { class C : TestCommand() shouldThrow<PrintHelpMessage> { C().parse("--help") } shouldThrow<PrintHelpMessage> { C().parse("-h") } shouldThrow<PrintHelpMessage> { C().context { helpOptionNames = setOf("-x") }.parse("-x") } shouldThrow<NoSuchOption> { C().context { helpOptionNames = setOf("--x") }.parse("--help") } } @Test fun originalArgv() { class C : TestCommand() class S: TestCommand() { val opt by option() val args by argument().multiple() override fun run_() { opt shouldBe "o" args shouldBe listOf("1", "2") currentContext.originalArgv shouldBe listOf("s", "--opt", "o", "1", "2") } } C().subcommands(S()).parse("s --opt o 1 2") } }
apache-2.0
3502d3cb1c345657951e0fb9f7eacf4b
30.226891
88
0.60226
4.331002
false
true
false
false
nickthecoder/tickle
tickle-editor/src/main/kotlin/uk/co/nickthecoder/tickle/editor/scene/SceneEditor.kt
1
20352
/* Tickle Copyright (C) 2017 Nick Robinson This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package uk.co.nickthecoder.tickle.editor.scene import javafx.event.EventHandler import javafx.scene.Node import javafx.scene.control.* import javafx.scene.input.MouseButton import javafx.scene.input.MouseEvent import javafx.scene.layout.BorderPane import javafx.scene.paint.Color import uk.co.nickthecoder.paratask.gui.ShortcutHelper import uk.co.nickthecoder.tickle.editor.EditorActions import uk.co.nickthecoder.tickle.editor.MainWindow import uk.co.nickthecoder.tickle.editor.resources.DesignActorResource import uk.co.nickthecoder.tickle.editor.resources.DesignSceneResource import uk.co.nickthecoder.tickle.editor.resources.ModificationType import uk.co.nickthecoder.tickle.editor.scene.history.* import uk.co.nickthecoder.tickle.editor.util.background class SceneEditor(val sceneResource: DesignSceneResource) { /** * Stores the changes made to the scene to allow undo/redo. */ val history = History(this) val scrollPane = ScrollPane() val borderPane = BorderPane() var mouseHandler: MouseHandler? = Select() set(v) { field?.end() field = v } val selection = Selection() val layers = Layers(this) val shortcuts = ShortcutHelper("SceneEditor", MainWindow.instance.borderPane) val costumeBox = CostumePickerBox { selectCostumeName(it) } val layersBox = LayersBox(layers) val actorsBox = ActorsBox(this) val actorAttributesBox = ActorAttributesBox(this) val costumesPane = TitledPane("Costume Picker", costumeBox.build()) val attributesPane = TitledPane("Attributes", actorAttributesBox.build()) val stagesPane = TitledPane("Actors", actorsBox.build()) val layersPane = TitledPane("Layers", layersBox.build()) // NOTE. If this order changes, also change the index for SHOW_COSTUME_PICKER in MainWindow val sidePanes = listOf(costumesPane, attributesPane, stagesPane, layersPane) val costumeHistory = mutableListOf<String>() val editSnapsButton = EditorActions.SNAPS_EDIT.createButton { onEditSnaps() } val toggleGridButton = EditorActions.SNAP_TO_GRID_TOGGLE.createToggleButton { sceneResource.snapToGrid.enabled = !sceneResource.snapToGrid.enabled } val toggleGuidesButton = EditorActions.SNAP_TO_GUIDES_TOGGLE.createToggleButton { sceneResource.snapToGuides.enabled = !sceneResource.snapToGuides.enabled } val toggleSnapToOThersButton = EditorActions.SNAP_TO_OTHERS_TOGGLE.createToggleButton { sceneResource.snapToOthers.enabled = !sceneResource.snapToOthers.enabled } val toggleSnapRotationButton = EditorActions.SNAP_ROTATION_TOGGLE.createToggleButton { sceneResource.snapRotation.enabled = !sceneResource.snapRotation.enabled } fun build(): Node { with(scrollPane) { content = layers.stack } with(borderPane) { center = scrollPane } with(layers.glass.canvas) { addEventHandler(MouseEvent.MOUSE_PRESSED) { onMousePressed(it) } addEventHandler(MouseEvent.MOUSE_MOVED) { onMouseMoved(it) } addEventHandler(MouseEvent.MOUSE_DRAGGED) { onMouseDragged(it) } addEventHandler(MouseEvent.DRAG_DETECTED) { onDragDetected(it) } addEventHandler(MouseEvent.MOUSE_RELEASED) { onMouseReleased(it) } } layers.stack.background = sceneResource.background.background() with(shortcuts) { add(EditorActions.ESCAPE) { onEscape() } add(EditorActions.DELETE) { onDelete() } add(EditorActions.UNDO) { onUndo() } add(EditorActions.REDO) { onRedo() } add(EditorActions.ZOOM_RESET) { layers.scale = 1.0 } add(EditorActions.ZOOM_IN1) { layers.scale *= 1.2 } add(EditorActions.ZOOM_IN2) { layers.scale *= 1.2 } add(EditorActions.ZOOM_OUT) { layers.scale /= 1.2 } } EditorActions.STAMPS.forEachIndexed { index, action -> shortcuts.add(action) { selectCostumeFromHistory(index) } } layers.visibleLayers().forEach { it.draw() } layers.glass.draw() return borderPane } fun cleanUp() { selection.clear() // Will clear the "Properties" box. shortcuts.clear() } fun findActorsAt(x: Double, y: Double, ignoreStageLock: Boolean = false): List<DesignActorResource> { val list = mutableListOf<DesignActorResource>() layers.visibleLayers().filter { ignoreStageLock || !it.isLocked }.forEach { stageLayer -> list.addAll(stageLayer.actorsAt(x, y).map { it as DesignActorResource }) } return list } fun buildContextMenu(): ContextMenu { val menu = ContextMenu() if (selection.isNotEmpty()) { val deleteText = "Delete " + if (selection.size > 1) { "(${selection.size} actors)" } else { selection.latest()!!.costumeName } val delete = MenuItem(deleteText) delete.onAction = EventHandler { onDelete() } val attributes = MenuItem("Attributes") attributes.onAction = EventHandler { MainWindow.instance.accordion.expandedPane = attributesPane } menu.items.addAll(delete, attributes) if (sceneResource.stageResources.size > 1) { val moveToStageMenu = Menu("Move to Stage") layers.stageLayers().forEach { stageLayer -> val stageItem = CheckMenuItem(stageLayer.stageName) stageItem.onAction = EventHandler { moveSelectTo(stageLayer) } moveToStageMenu.items.add(stageItem) // Add a tick if ALL of the selected ActorResources are on this layer. if (selection.filter { it.layer !== stageLayer }.isEmpty()) { stageItem.isSelected = true } } menu.items.add(moveToStageMenu) } menu.items.addAll(SeparatorMenuItem()) } val resetAllZOrders = EditorActions.RESET_ZORDERS.createMenuItem { onResetZOrders() } menu.items.addAll(resetAllZOrders, SeparatorMenuItem()) return menu } fun moveSelectTo(layer: StageLayer) { history.beginBatch() selection.toList().forEach { actorResource -> history.makeChange(MoveToLayer(actorResource, layer)) } history.endBatch() } fun onEditSnaps() { SnapEditor(mapOf( "Grid" to sceneResource.snapToGrid, "Guides" to sceneResource.snapToGuides, "Others" to sceneResource.snapToOthers, "Rotation" to sceneResource.snapRotation )).show() } fun onEscape() { selection.clear() mouseHandler = Select() } fun onUndo() { if (history.canUndo()) { history.undo() } } fun onRedo() { if (history.canRedo()) { history.redo() } } fun addActor(actorResource: DesignActorResource, layer: StageLayer) { layer.stageConstraint.addActorResource(actorResource) layer.stageResource.actorResources.add(actorResource) actorResource.layer = layer sceneResource.fireChange(actorResource, ModificationType.NEW) } fun delete(actorResource: DesignActorResource) { actorResource.layer?.stageResource?.actorResources?.remove(actorResource) sceneResource.fireChange(actorResource, ModificationType.DELETE) selection.remove(actorResource) } fun onDelete() { val focus = scrollPane.scene.focusOwner if (focus is TextInputControl || focus is Spinner<*>) { ShortcutHelper.ignore() } else { history.makeChange(DeleteActors(selection)) } } fun onResetZOrders() { history.beginBatch() sceneResource.stageResources.forEach { _, stageResource -> stageResource.actorResources.forEach { ar -> ar.costume()?.let { costume -> if (ar.zOrder != costume.zOrder) { history.makeChange(ChangeZOrder(ar, costume.zOrder)) } } } } history.endBatch() } fun selectCostumeName(costumeName: String) { mouseHandler = Stamp(costumeName) if (costumeHistory.isEmpty() || costumeHistory[0] != costumeName) { costumeHistory.add(0, costumeName) if (costumeHistory.size > 10) { costumeHistory.removeAt(costumeHistory.size - 1) } } } fun selectCostumeFromHistory(index: Int) { if (index >= 0 && index < costumeHistory.size) { mouseHandler = Stamp(costumeHistory[index]) } } var dragPreviousX: Double = 0.0 var dragPreviousY: Double = 0.0 fun onMousePressed(event: MouseEvent) { dragPreviousX = event.x dragPreviousY = event.y if (event.isPopupTrigger) { val menu = buildContextMenu() menu.show(MainWindow.instance.scene.window, event.screenX, event.screenY) } else { mouseHandler?.onMousePressed(event) } } fun onDragDetected(event: MouseEvent) { mouseHandler?.onDragDetected(event) } fun onMouseMoved(event: MouseEvent) { mouseHandler?.onMouseMoved(event) } var dragging = false var dragDeltaX: Double = 0.0 var dragDeltaY: Double = 0.0 // In the same coordinate system as event (i.e. y axis points down). fun onMouseDragged(event: MouseEvent) { dragDeltaX = event.x - dragPreviousX dragDeltaY = event.y - dragPreviousY // Prevent dragging unless the drag amount is more than a few pixels. This prevents accidental tiny movements if (!dragging) { if (Math.abs(dragDeltaX) > 5 || Math.abs(dragDeltaY) > 5) { dragging = true } } if (dragging) { mouseHandler?.onMouseDragged(event) dragPreviousX = event.x dragPreviousY = event.y } } fun onMouseReleased(event: MouseEvent) { mouseHandler?.onMouseReleased(event) dragging = false } private val adjustments = mutableListOf<Adjustment>() fun snapActor(actorResource: DesignActorResource, isNew: Boolean, useSnaps: Boolean) { if (actorResource.layer?.stageConstraint?.snapActor(actorResource, isNew) != true) { if (useSnaps) { adjustments.clear() sceneResource.snapToGrid.snapActor(actorResource, adjustments) sceneResource.snapToGuides.snapActor(actorResource, adjustments) sceneResource.snapToOthers.snapActor(actorResource, adjustments) if (adjustments.isNotEmpty()) { adjustments.sortBy { it.score } actorResource.x += adjustments.first().x actorResource.y += adjustments.first().y } } } } fun viewX(event: MouseEvent) = layers.viewX(event) fun viewY(event: MouseEvent) = layers.viewY(event) open inner class MouseHandler { open fun onMousePressed(event: MouseEvent) { event.consume() // If we drag an actor, put all of the MoveActor Changes into one Batch. // onMouseRelease ends the batch. history.beginBatch() } open fun onDragDetected(event: MouseEvent) { event.consume() } open fun onMouseMoved(event: MouseEvent) { event.consume() } open fun onMouseDragged(event: MouseEvent) { event.consume() } open fun onMouseReleased(event: MouseEvent) { event.consume() history.endBatch() } open fun end() {} } inner class Select : MouseHandler() { var offsetX: Double = 0.0 var offsetY: Double = 0.0 override fun onMousePressed(event: MouseEvent) { super.onMousePressed(event) val wx = viewX(event) val wy = viewY(event) if (event.button == MouseButton.PRIMARY) { selection.forEach { ar -> ar.draggedX = ar.x ar.draggedY = ar.y } val handle = layers.glass.findDragHandle(wx, wy) if (handle != null) { mouseHandler = AdjustDragHandle(handle) } else { val ignoreLock = event.isAltDown // On my system Mouse + Alt moves a window, but Mouse + Alt + Shift works fine ;-) val actors = findActorsAt(wx, wy, ignoreLock) val highestActor = actors.firstOrNull() if (highestActor == null) { mouseHandler = SelectArea(wx, wy) } else { if (event.isControlDown) { // Add or remove the top-most actor to/from the selection if (selection.contains(highestActor)) { selection.remove(highestActor) } else { selection.add(highestActor) } } else if (event.isShiftDown) { if (actors.contains(selection.latest())) { // Select the actor below the currently selected actor (i.e. with a higher index) // This is useful when there are many actors on top of each other. We can get to any of them, by repeatedly shift-clicking val i = actors.indexOf(selection.latest()) if (i == actors.size - 1) { selection.clearAndSelect(highestActor) } else { selection.clearAndSelect(actors[i + 1]) } } else { selection.clearAndSelect(highestActor) } } else { if (event.clickCount == 2) { MainWindow.instance.accordion.expandedPane = attributesPane } else { if (actors.contains(selection.latest())) { // Do nothing } else if (selection.contains(highestActor)) { // Already in the selection, but this makes it the "latest" one // So it is shown in the details dialog, and you can see/edit its direction arrow. selection.add(highestActor) } else { selection.clearAndSelect(highestActor) } } } } selection.latest()?.let { latest -> offsetX = latest.x - wx offsetY = latest.y - wy } } } else if (event.button == MouseButton.MIDDLE || event.isAltDown) { mouseHandler = Pan() } } override fun onMouseMoved(event: MouseEvent) { layers.glass.hover(viewX(event), viewY(event)) } // Move the selected actors override fun onMouseDragged(event: MouseEvent) { if (event.button == MouseButton.PRIMARY) { selection.selected().forEach { actorResource -> actorResource.draggedX += dragDeltaX actorResource.draggedY -= dragDeltaY val oldX = actorResource.x val oldY = actorResource.y snapActor(actorResource, false, !event.isControlDown) history.makeChange(MoveActor(actorResource, oldX, oldY)) } } } } inner class SelectArea(val startX: Double, val startY: Double) : MouseHandler() { override fun onMouseDragged(event: MouseEvent) { val wx = viewX(event) val wy = viewY(event) val fromX = Math.min(wx, startX) val fromY = Math.min(wy, startY) val toX = Math.max(wx, startX) val toY = Math.max(wy, startY) selection.clear() layers.currentLayer?.stageResource?.actorResources?.forEach { actorResource -> actorResource as DesignActorResource if (actorResource.x >= fromX && actorResource.y >= fromY && actorResource.x <= toX && actorResource.y <= toY) { selection.add(actorResource) } } layers.glass.draw { layers.glass.drawContent() with(layers.glass.canvas.graphicsContext2D) { stroke = Color.RED setLineDashes(3.0, 10.0) strokeRect(fromX, fromY, toX - fromX, toY - fromY) } } } override fun onMouseReleased(event: MouseEvent) { super.onMouseReleased(event) layers.glass.draw() mouseHandler = Select() } } inner class Pan : MouseHandler() { override fun onMouseDragged(event: MouseEvent) { layers.panBy(dragDeltaX, -dragDeltaY) } override fun onMouseReleased(event: MouseEvent) { super.onMouseReleased(event) mouseHandler = Select() } } inner class AdjustDragHandle(val dragHandle: GlassLayer.DragHandle) : MouseHandler() { override fun onMouseDragged(event: MouseEvent) { dragHandle.moveTo(viewX(event), viewY(event), !event.isControlDown) selection.latest()?.let { sceneResource.fireChange(it, ModificationType.CHANGE) } } override fun onMouseReleased(event: MouseEvent) { super.onMouseReleased(event) mouseHandler = Select() } } inner class Stamp(val costumeName: String) : MouseHandler() { var newActor = DesignActorResource() init { newActor.costumeName = costumeName newActor.layer = layers.currentLayer() layers.glass.newActor = newActor } override fun end() { layers.glass.newActor = null } override fun onMouseMoved(event: MouseEvent) { newActor.draggedX = viewX(event) newActor.draggedY = viewY(event) snapActor(newActor, true, !event.isControlDown) layers.glass.dirty = true } override fun onMousePressed(event: MouseEvent) { layers.currentLayer?.let { layer -> val change = AddActor(newActor, layer) if (event.isShiftDown) { newActor = DesignActorResource() newActor.costumeName = costumeName layers.glass.newActor = newActor } else { layers.glass.newActor = null selection.clearAndSelect(newActor) mouseHandler = Select() } history.makeChange(change) } } } }
gpl-3.0
8f23faa75ec57828cd80c67a8459d9d9
33.55348
166
0.574833
4.82618
false
false
false
false
Kotlin/anko
anko/library/generated/sdk28/src/main/java/Layouts.kt
2
67639
@file:JvmName("Sdk28LayoutsKt") package org.jetbrains.anko import android.content.Context import android.util.AttributeSet import android.view.ViewGroup import android.widget.FrameLayout import android.appwidget.AppWidgetHostView import android.view.View import android.widget.AbsoluteLayout import android.widget.ActionMenuView import android.widget.Gallery import android.widget.GridLayout import android.widget.GridView import android.widget.AbsListView import android.widget.HorizontalScrollView import android.widget.ImageSwitcher import android.widget.LinearLayout import android.widget.RadioGroup import android.widget.RelativeLayout import android.widget.ScrollView import android.widget.TableLayout import android.widget.TableRow import android.widget.TextSwitcher import android.widget.Toolbar import android.app.ActionBar import android.widget.ViewAnimator import android.widget.ViewSwitcher open class _AppWidgetHostView(ctx: Context): AppWidgetHostView(ctx) { inline fun <T: View> T.lparams( c: Context?, attrs: AttributeSet?, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(c!!, attrs!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( c: Context?, attrs: AttributeSet? ): T { val layoutParams = FrameLayout.LayoutParams(c!!, attrs!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(width, height) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT ): T { val layoutParams = FrameLayout.LayoutParams(width, height) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, gravity: Int, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(width, height, gravity) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, gravity: Int ): T { val layoutParams = FrameLayout.LayoutParams(width, height, gravity) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.LayoutParams?, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.LayoutParams? ): T { val layoutParams = FrameLayout.LayoutParams(source!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.MarginLayoutParams?, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.MarginLayoutParams? ): T { val layoutParams = FrameLayout.LayoutParams(source!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: FrameLayout.LayoutParams?, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: FrameLayout.LayoutParams? ): T { val layoutParams = FrameLayout.LayoutParams(source!!) [email protected] = layoutParams return this } } open class _AbsoluteLayout(ctx: Context): AbsoluteLayout(ctx) { inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, x: Int, y: Int, init: AbsoluteLayout.LayoutParams.() -> Unit ): T { val layoutParams = AbsoluteLayout.LayoutParams(width, height, x, y) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, x: Int, y: Int ): T { val layoutParams = AbsoluteLayout.LayoutParams(width, height, x, y) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( c: Context?, attrs: AttributeSet?, init: AbsoluteLayout.LayoutParams.() -> Unit ): T { val layoutParams = AbsoluteLayout.LayoutParams(c!!, attrs!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( c: Context?, attrs: AttributeSet? ): T { val layoutParams = AbsoluteLayout.LayoutParams(c!!, attrs!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.LayoutParams?, init: AbsoluteLayout.LayoutParams.() -> Unit ): T { val layoutParams = AbsoluteLayout.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.LayoutParams? ): T { val layoutParams = AbsoluteLayout.LayoutParams(source!!) [email protected] = layoutParams return this } } open class _ActionMenuView(ctx: Context): ActionMenuView(ctx) { inline fun <T: View> T.lparams( c: Context?, attrs: AttributeSet?, init: ActionMenuView.LayoutParams.() -> Unit ): T { val layoutParams = ActionMenuView.LayoutParams(c!!, attrs!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( c: Context?, attrs: AttributeSet? ): T { val layoutParams = ActionMenuView.LayoutParams(c!!, attrs!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( other: ViewGroup.LayoutParams?, init: ActionMenuView.LayoutParams.() -> Unit ): T { val layoutParams = ActionMenuView.LayoutParams(other!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( other: ViewGroup.LayoutParams? ): T { val layoutParams = ActionMenuView.LayoutParams(other!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( other: ActionMenuView.LayoutParams?, init: ActionMenuView.LayoutParams.() -> Unit ): T { val layoutParams = ActionMenuView.LayoutParams(other!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( other: ActionMenuView.LayoutParams? ): T { val layoutParams = ActionMenuView.LayoutParams(other!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, init: ActionMenuView.LayoutParams.() -> Unit ): T { val layoutParams = ActionMenuView.LayoutParams(width, height) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT ): T { val layoutParams = ActionMenuView.LayoutParams(width, height) [email protected] = layoutParams return this } } open class _FrameLayout(ctx: Context): FrameLayout(ctx) { inline fun <T: View> T.lparams( c: Context?, attrs: AttributeSet?, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(c!!, attrs!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( c: Context?, attrs: AttributeSet? ): T { val layoutParams = FrameLayout.LayoutParams(c!!, attrs!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(width, height) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT ): T { val layoutParams = FrameLayout.LayoutParams(width, height) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, gravity: Int, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(width, height, gravity) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, gravity: Int ): T { val layoutParams = FrameLayout.LayoutParams(width, height, gravity) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.LayoutParams?, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.LayoutParams? ): T { val layoutParams = FrameLayout.LayoutParams(source!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.MarginLayoutParams?, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.MarginLayoutParams? ): T { val layoutParams = FrameLayout.LayoutParams(source!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: FrameLayout.LayoutParams?, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: FrameLayout.LayoutParams? ): T { val layoutParams = FrameLayout.LayoutParams(source!!) [email protected] = layoutParams return this } } open class _Gallery(ctx: Context): Gallery(ctx) { inline fun <T: View> T.lparams( c: Context?, attrs: AttributeSet?, init: Gallery.LayoutParams.() -> Unit ): T { val layoutParams = Gallery.LayoutParams(c!!, attrs!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( c: Context?, attrs: AttributeSet? ): T { val layoutParams = Gallery.LayoutParams(c!!, attrs!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, init: Gallery.LayoutParams.() -> Unit ): T { val layoutParams = Gallery.LayoutParams(width, height) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT ): T { val layoutParams = Gallery.LayoutParams(width, height) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.LayoutParams?, init: Gallery.LayoutParams.() -> Unit ): T { val layoutParams = Gallery.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.LayoutParams? ): T { val layoutParams = Gallery.LayoutParams(source!!) [email protected] = layoutParams return this } } open class _GridLayout(ctx: Context): GridLayout(ctx) { inline fun <T: View> T.lparams( rowSpec: GridLayout.Spec?, columnSpec: GridLayout.Spec?, init: GridLayout.LayoutParams.() -> Unit ): T { val layoutParams = GridLayout.LayoutParams(rowSpec!!, columnSpec!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( rowSpec: GridLayout.Spec?, columnSpec: GridLayout.Spec? ): T { val layoutParams = GridLayout.LayoutParams(rowSpec!!, columnSpec!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( init: GridLayout.LayoutParams.() -> Unit ): T { val layoutParams = GridLayout.LayoutParams() layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( ): T { val layoutParams = GridLayout.LayoutParams() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( params: ViewGroup.LayoutParams?, init: GridLayout.LayoutParams.() -> Unit ): T { val layoutParams = GridLayout.LayoutParams(params!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( params: ViewGroup.LayoutParams? ): T { val layoutParams = GridLayout.LayoutParams(params!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( params: ViewGroup.MarginLayoutParams?, init: GridLayout.LayoutParams.() -> Unit ): T { val layoutParams = GridLayout.LayoutParams(params!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( params: ViewGroup.MarginLayoutParams? ): T { val layoutParams = GridLayout.LayoutParams(params!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: GridLayout.LayoutParams?, init: GridLayout.LayoutParams.() -> Unit ): T { val layoutParams = GridLayout.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: GridLayout.LayoutParams? ): T { val layoutParams = GridLayout.LayoutParams(source!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( context: Context?, attrs: AttributeSet?, init: GridLayout.LayoutParams.() -> Unit ): T { val layoutParams = GridLayout.LayoutParams(context!!, attrs!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( context: Context?, attrs: AttributeSet? ): T { val layoutParams = GridLayout.LayoutParams(context!!, attrs!!) [email protected] = layoutParams return this } } open class _GridView(ctx: Context): GridView(ctx) { inline fun <T: View> T.lparams( c: Context?, attrs: AttributeSet?, init: AbsListView.LayoutParams.() -> Unit ): T { val layoutParams = AbsListView.LayoutParams(c!!, attrs!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( c: Context?, attrs: AttributeSet? ): T { val layoutParams = AbsListView.LayoutParams(c!!, attrs!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, init: AbsListView.LayoutParams.() -> Unit ): T { val layoutParams = AbsListView.LayoutParams(width, height) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT ): T { val layoutParams = AbsListView.LayoutParams(width, height) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, viewType: Int, init: AbsListView.LayoutParams.() -> Unit ): T { val layoutParams = AbsListView.LayoutParams(width, height, viewType) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, viewType: Int ): T { val layoutParams = AbsListView.LayoutParams(width, height, viewType) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.LayoutParams?, init: AbsListView.LayoutParams.() -> Unit ): T { val layoutParams = AbsListView.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.LayoutParams? ): T { val layoutParams = AbsListView.LayoutParams(source!!) [email protected] = layoutParams return this } } open class _HorizontalScrollView(ctx: Context): HorizontalScrollView(ctx) { inline fun <T: View> T.lparams( c: Context?, attrs: AttributeSet?, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(c!!, attrs!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( c: Context?, attrs: AttributeSet? ): T { val layoutParams = FrameLayout.LayoutParams(c!!, attrs!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(width, height) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT ): T { val layoutParams = FrameLayout.LayoutParams(width, height) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, gravity: Int, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(width, height, gravity) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, gravity: Int ): T { val layoutParams = FrameLayout.LayoutParams(width, height, gravity) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.LayoutParams?, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.LayoutParams? ): T { val layoutParams = FrameLayout.LayoutParams(source!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.MarginLayoutParams?, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.MarginLayoutParams? ): T { val layoutParams = FrameLayout.LayoutParams(source!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: FrameLayout.LayoutParams?, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: FrameLayout.LayoutParams? ): T { val layoutParams = FrameLayout.LayoutParams(source!!) [email protected] = layoutParams return this } } open class _ImageSwitcher(ctx: Context): ImageSwitcher(ctx) { inline fun <T: View> T.lparams( c: Context?, attrs: AttributeSet?, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(c!!, attrs!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( c: Context?, attrs: AttributeSet? ): T { val layoutParams = FrameLayout.LayoutParams(c!!, attrs!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(width, height) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT ): T { val layoutParams = FrameLayout.LayoutParams(width, height) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, gravity: Int, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(width, height, gravity) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, gravity: Int ): T { val layoutParams = FrameLayout.LayoutParams(width, height, gravity) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.LayoutParams?, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.LayoutParams? ): T { val layoutParams = FrameLayout.LayoutParams(source!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.MarginLayoutParams?, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.MarginLayoutParams? ): T { val layoutParams = FrameLayout.LayoutParams(source!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: FrameLayout.LayoutParams?, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: FrameLayout.LayoutParams? ): T { val layoutParams = FrameLayout.LayoutParams(source!!) [email protected] = layoutParams return this } } open class _LinearLayout(ctx: Context): LinearLayout(ctx) { inline fun <T: View> T.lparams( c: Context?, attrs: AttributeSet?, init: LinearLayout.LayoutParams.() -> Unit ): T { val layoutParams = LinearLayout.LayoutParams(c!!, attrs!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( c: Context?, attrs: AttributeSet? ): T { val layoutParams = LinearLayout.LayoutParams(c!!, attrs!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, init: LinearLayout.LayoutParams.() -> Unit ): T { val layoutParams = LinearLayout.LayoutParams(width, height) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT ): T { val layoutParams = LinearLayout.LayoutParams(width, height) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, weight: Float, init: LinearLayout.LayoutParams.() -> Unit ): T { val layoutParams = LinearLayout.LayoutParams(width, height, weight) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, weight: Float ): T { val layoutParams = LinearLayout.LayoutParams(width, height, weight) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( p: ViewGroup.LayoutParams?, init: LinearLayout.LayoutParams.() -> Unit ): T { val layoutParams = LinearLayout.LayoutParams(p!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( p: ViewGroup.LayoutParams? ): T { val layoutParams = LinearLayout.LayoutParams(p!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.MarginLayoutParams?, init: LinearLayout.LayoutParams.() -> Unit ): T { val layoutParams = LinearLayout.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.MarginLayoutParams? ): T { val layoutParams = LinearLayout.LayoutParams(source!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: LinearLayout.LayoutParams?, init: LinearLayout.LayoutParams.() -> Unit ): T { val layoutParams = LinearLayout.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: LinearLayout.LayoutParams? ): T { val layoutParams = LinearLayout.LayoutParams(source!!) [email protected] = layoutParams return this } } open class _RadioGroup(ctx: Context): RadioGroup(ctx) { inline fun <T: View> T.lparams( c: Context?, attrs: AttributeSet?, init: RadioGroup.LayoutParams.() -> Unit ): T { val layoutParams = RadioGroup.LayoutParams(c!!, attrs!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( c: Context?, attrs: AttributeSet? ): T { val layoutParams = RadioGroup.LayoutParams(c!!, attrs!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, init: RadioGroup.LayoutParams.() -> Unit ): T { val layoutParams = RadioGroup.LayoutParams(width, height) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT ): T { val layoutParams = RadioGroup.LayoutParams(width, height) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, initWeight: Float, init: RadioGroup.LayoutParams.() -> Unit ): T { val layoutParams = RadioGroup.LayoutParams(width, height, initWeight) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, initWeight: Float ): T { val layoutParams = RadioGroup.LayoutParams(width, height, initWeight) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( p: ViewGroup.LayoutParams?, init: RadioGroup.LayoutParams.() -> Unit ): T { val layoutParams = RadioGroup.LayoutParams(p!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( p: ViewGroup.LayoutParams? ): T { val layoutParams = RadioGroup.LayoutParams(p!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.MarginLayoutParams?, init: RadioGroup.LayoutParams.() -> Unit ): T { val layoutParams = RadioGroup.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.MarginLayoutParams? ): T { val layoutParams = RadioGroup.LayoutParams(source!!) [email protected] = layoutParams return this } } open class _RelativeLayout(ctx: Context): RelativeLayout(ctx) { inline fun <T: View> T.lparams( c: Context?, attrs: AttributeSet?, init: RelativeLayout.LayoutParams.() -> Unit ): T { val layoutParams = RelativeLayout.LayoutParams(c!!, attrs!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( c: Context?, attrs: AttributeSet? ): T { val layoutParams = RelativeLayout.LayoutParams(c!!, attrs!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, init: RelativeLayout.LayoutParams.() -> Unit ): T { val layoutParams = RelativeLayout.LayoutParams(width, height) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT ): T { val layoutParams = RelativeLayout.LayoutParams(width, height) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.LayoutParams?, init: RelativeLayout.LayoutParams.() -> Unit ): T { val layoutParams = RelativeLayout.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.LayoutParams? ): T { val layoutParams = RelativeLayout.LayoutParams(source!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.MarginLayoutParams?, init: RelativeLayout.LayoutParams.() -> Unit ): T { val layoutParams = RelativeLayout.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.MarginLayoutParams? ): T { val layoutParams = RelativeLayout.LayoutParams(source!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: RelativeLayout.LayoutParams?, init: RelativeLayout.LayoutParams.() -> Unit ): T { val layoutParams = RelativeLayout.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: RelativeLayout.LayoutParams? ): T { val layoutParams = RelativeLayout.LayoutParams(source!!) [email protected] = layoutParams return this } } open class _ScrollView(ctx: Context): ScrollView(ctx) { inline fun <T: View> T.lparams( c: Context?, attrs: AttributeSet?, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(c!!, attrs!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( c: Context?, attrs: AttributeSet? ): T { val layoutParams = FrameLayout.LayoutParams(c!!, attrs!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(width, height) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT ): T { val layoutParams = FrameLayout.LayoutParams(width, height) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, gravity: Int, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(width, height, gravity) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, gravity: Int ): T { val layoutParams = FrameLayout.LayoutParams(width, height, gravity) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.LayoutParams?, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.LayoutParams? ): T { val layoutParams = FrameLayout.LayoutParams(source!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.MarginLayoutParams?, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.MarginLayoutParams? ): T { val layoutParams = FrameLayout.LayoutParams(source!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: FrameLayout.LayoutParams?, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: FrameLayout.LayoutParams? ): T { val layoutParams = FrameLayout.LayoutParams(source!!) [email protected] = layoutParams return this } } open class _TableLayout(ctx: Context): TableLayout(ctx) { inline fun <T: View> T.lparams( c: Context?, attrs: AttributeSet?, init: TableLayout.LayoutParams.() -> Unit ): T { val layoutParams = TableLayout.LayoutParams(c!!, attrs!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( c: Context?, attrs: AttributeSet? ): T { val layoutParams = TableLayout.LayoutParams(c!!, attrs!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, init: TableLayout.LayoutParams.() -> Unit ): T { val layoutParams = TableLayout.LayoutParams(width, height) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT ): T { val layoutParams = TableLayout.LayoutParams(width, height) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, initWeight: Float, init: TableLayout.LayoutParams.() -> Unit ): T { val layoutParams = TableLayout.LayoutParams(width, height, initWeight) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, initWeight: Float ): T { val layoutParams = TableLayout.LayoutParams(width, height, initWeight) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( init: TableLayout.LayoutParams.() -> Unit ): T { val layoutParams = TableLayout.LayoutParams() layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( ): T { val layoutParams = TableLayout.LayoutParams() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( p: ViewGroup.LayoutParams?, init: TableLayout.LayoutParams.() -> Unit ): T { val layoutParams = TableLayout.LayoutParams(p!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( p: ViewGroup.LayoutParams? ): T { val layoutParams = TableLayout.LayoutParams(p!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.MarginLayoutParams?, init: TableLayout.LayoutParams.() -> Unit ): T { val layoutParams = TableLayout.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.MarginLayoutParams? ): T { val layoutParams = TableLayout.LayoutParams(source!!) [email protected] = layoutParams return this } } open class _TableRow(ctx: Context): TableRow(ctx) { inline fun <T: View> T.lparams( c: Context?, attrs: AttributeSet?, init: TableRow.LayoutParams.() -> Unit ): T { val layoutParams = TableRow.LayoutParams(c!!, attrs!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( c: Context?, attrs: AttributeSet? ): T { val layoutParams = TableRow.LayoutParams(c!!, attrs!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, init: TableRow.LayoutParams.() -> Unit ): T { val layoutParams = TableRow.LayoutParams(width, height) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT ): T { val layoutParams = TableRow.LayoutParams(width, height) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, initWeight: Float, init: TableRow.LayoutParams.() -> Unit ): T { val layoutParams = TableRow.LayoutParams(width, height, initWeight) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, initWeight: Float ): T { val layoutParams = TableRow.LayoutParams(width, height, initWeight) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( init: TableRow.LayoutParams.() -> Unit ): T { val layoutParams = TableRow.LayoutParams() layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( ): T { val layoutParams = TableRow.LayoutParams() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( column: Int, init: TableRow.LayoutParams.() -> Unit ): T { val layoutParams = TableRow.LayoutParams(column) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( column: Int ): T { val layoutParams = TableRow.LayoutParams(column) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( p: ViewGroup.LayoutParams?, init: TableRow.LayoutParams.() -> Unit ): T { val layoutParams = TableRow.LayoutParams(p!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( p: ViewGroup.LayoutParams? ): T { val layoutParams = TableRow.LayoutParams(p!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.MarginLayoutParams?, init: TableRow.LayoutParams.() -> Unit ): T { val layoutParams = TableRow.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.MarginLayoutParams? ): T { val layoutParams = TableRow.LayoutParams(source!!) [email protected] = layoutParams return this } } open class _TextSwitcher(ctx: Context): TextSwitcher(ctx) { inline fun <T: View> T.lparams( c: Context?, attrs: AttributeSet?, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(c!!, attrs!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( c: Context?, attrs: AttributeSet? ): T { val layoutParams = FrameLayout.LayoutParams(c!!, attrs!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(width, height) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT ): T { val layoutParams = FrameLayout.LayoutParams(width, height) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, gravity: Int, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(width, height, gravity) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, gravity: Int ): T { val layoutParams = FrameLayout.LayoutParams(width, height, gravity) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.LayoutParams?, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.LayoutParams? ): T { val layoutParams = FrameLayout.LayoutParams(source!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.MarginLayoutParams?, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.MarginLayoutParams? ): T { val layoutParams = FrameLayout.LayoutParams(source!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: FrameLayout.LayoutParams?, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: FrameLayout.LayoutParams? ): T { val layoutParams = FrameLayout.LayoutParams(source!!) [email protected] = layoutParams return this } } open class _Toolbar(ctx: Context): Toolbar(ctx) { inline fun <T: View> T.lparams( c: Context?, attrs: AttributeSet?, init: Toolbar.LayoutParams.() -> Unit ): T { val layoutParams = Toolbar.LayoutParams(c!!, attrs!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( c: Context?, attrs: AttributeSet? ): T { val layoutParams = Toolbar.LayoutParams(c!!, attrs!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, init: Toolbar.LayoutParams.() -> Unit ): T { val layoutParams = Toolbar.LayoutParams(width, height) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT ): T { val layoutParams = Toolbar.LayoutParams(width, height) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, gravity: Int, init: Toolbar.LayoutParams.() -> Unit ): T { val layoutParams = Toolbar.LayoutParams(width, height, gravity) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, gravity: Int ): T { val layoutParams = Toolbar.LayoutParams(width, height, gravity) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( gravity: Int, init: Toolbar.LayoutParams.() -> Unit ): T { val layoutParams = Toolbar.LayoutParams(gravity) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( gravity: Int ): T { val layoutParams = Toolbar.LayoutParams(gravity) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: Toolbar.LayoutParams?, init: Toolbar.LayoutParams.() -> Unit ): T { val layoutParams = Toolbar.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: Toolbar.LayoutParams? ): T { val layoutParams = Toolbar.LayoutParams(source!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ActionBar.LayoutParams?, init: Toolbar.LayoutParams.() -> Unit ): T { val layoutParams = Toolbar.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ActionBar.LayoutParams? ): T { val layoutParams = Toolbar.LayoutParams(source!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.MarginLayoutParams?, init: Toolbar.LayoutParams.() -> Unit ): T { val layoutParams = Toolbar.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.MarginLayoutParams? ): T { val layoutParams = Toolbar.LayoutParams(source!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.LayoutParams?, init: Toolbar.LayoutParams.() -> Unit ): T { val layoutParams = Toolbar.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.LayoutParams? ): T { val layoutParams = Toolbar.LayoutParams(source!!) [email protected] = layoutParams return this } } open class _ViewAnimator(ctx: Context): ViewAnimator(ctx) { inline fun <T: View> T.lparams( c: Context?, attrs: AttributeSet?, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(c!!, attrs!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( c: Context?, attrs: AttributeSet? ): T { val layoutParams = FrameLayout.LayoutParams(c!!, attrs!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(width, height) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT ): T { val layoutParams = FrameLayout.LayoutParams(width, height) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, gravity: Int, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(width, height, gravity) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, gravity: Int ): T { val layoutParams = FrameLayout.LayoutParams(width, height, gravity) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.LayoutParams?, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.LayoutParams? ): T { val layoutParams = FrameLayout.LayoutParams(source!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.MarginLayoutParams?, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.MarginLayoutParams? ): T { val layoutParams = FrameLayout.LayoutParams(source!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: FrameLayout.LayoutParams?, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: FrameLayout.LayoutParams? ): T { val layoutParams = FrameLayout.LayoutParams(source!!) [email protected] = layoutParams return this } } open class _ViewSwitcher(ctx: Context): ViewSwitcher(ctx) { inline fun <T: View> T.lparams( c: Context?, attrs: AttributeSet?, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(c!!, attrs!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( c: Context?, attrs: AttributeSet? ): T { val layoutParams = FrameLayout.LayoutParams(c!!, attrs!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(width, height) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT ): T { val layoutParams = FrameLayout.LayoutParams(width, height) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, gravity: Int, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(width, height, gravity) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, gravity: Int ): T { val layoutParams = FrameLayout.LayoutParams(width, height, gravity) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.LayoutParams?, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.LayoutParams? ): T { val layoutParams = FrameLayout.LayoutParams(source!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.MarginLayoutParams?, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.MarginLayoutParams? ): T { val layoutParams = FrameLayout.LayoutParams(source!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: FrameLayout.LayoutParams?, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: FrameLayout.LayoutParams? ): T { val layoutParams = FrameLayout.LayoutParams(source!!) [email protected] = layoutParams return this } }
apache-2.0
4d57f418d1b18c7bf467eb63a968ee58
30.770315
78
0.61055
4.872776
false
false
false
false
zhengjiong/ZJ_KotlinStudy
src/main/kotlin/com/zj/example/kotlin/shengshiyuan/helloworld/99.HelloKotlin-Sequences.kt
1
8609
package com.zj.example.kotlin.shengshiyuan.helloworld /** * 序列 * @link https://juejin.im/post/5b28f4946fb9a00e3a5a9b8c * * 译者有话说 * 老实说这篇文章,好的地方在于原作者把Kotlin中的序列和Java 8中的流做了一个很好的对比,以及作者给出自己的使用建议以及针对性能效率都是通过实际基准测试结果进行对比的。但是唯一美中不足的是对于Kotlin中哪种场景下使用sequence更好,并没有说的很清楚。关于这点我想补充一下: * 1、数据集量级是足够大,建议使用序列(Sequences)。 * 2、对数据集进行频繁的数据操作,类似于多个操作符链式操作,建议使用序列(Sequences) * 3、对于使用first{},last{}建议使用序列(Sequences)。补充一下,细心的小伙伴会发现当你对一个集合使用first{},last{}操作符的时候,我们IDE工具会提示你建议使用序列(Sequences) 代替 集合(Lists) * 4、当仅仅只有map操作时,使用sequence * 这里只是简单总结了几点,具体详细内容可参考之前三篇有关Kotlin中序列的文章。好了第四篇完美收工。 * CreateTime: 2019/1/8 18:45 * @author 郑炯 */ fun main(args: Array<String>) { val demo = `HelloKotlin-Sequences`() //demo.test1() //demo.test2() //demo.test3() //demo.test4() //demo.test5() //demo.test6() //demo.test7() //demo.test8() //demo.test9() //demo.test10() demo.test11() } class `HelloKotlin-Sequences` { /** * 当你反编译下面代码的时候,你会发现Kotlin编译器会创建三个while循环.其实你可以使用命令式编程方式利用一个 * 循环就能实现上面相同任务的需求。不幸的是,编译器无法将代码优化到这样的程度。 * * 输出: * map * map * map * filter * filter * filter * count * count=1 */ fun test1() { val count = listOf(1, 2, 3) .map { println("map") it + 1 } .filter { println("filter") it == 3 } .count { println("count") it == 3 } println("count=$count") } /** * 序列(Sequences) 的秘诀在于它们是共享同一个迭代器(iterator) ---序列允许 map操作 转换一个元素后, * 然后立马可以将这个元素传递给 filter操作 ,而不是像集合(lists) 一样等待所有的元素都循环完成了map操作后, * 用一个新的集合存储起来,然后又遍历循环从新的集合取出元素完成filter操作。通过减少循环次数, * 该序列为我们提供了26%(List为286μs,Sequence为212μs)性能提升 * * 输出: * map * filter * map * filter * map * filter * count=0 */ fun test2() { val count = listOf(1, 2, 3) .asSequence() .map { println("map") it + 1 } .filter { println("filter") it == 5 } .count { println("count") it == 5 } println("count=$count") } /** * 输出: * 什么都不输出 */ fun test3() { /** * 这样其实不是不会执行map和filter中的println, 查看源码可以发现Sequences的map()和filter()方法并不会执行循环操作, * 只有当foreach或者count的时候才会执行 */ val count = listOf(1, 2, 3) .asSequence() .map { println("map") it + 1 } .filter { println("filter") it == 5 } } /** * 使用Sequence后可以提高性能: * 当使用接收一个预判断的条件 first or last 方法时候,使用**序列(Sequences)** * 会产生一个小的性能提升,如果将它与其他操作符结合使用,它的性能将会得到更大的提升。 */ fun test4() { listOf(1, 2, 3) .asSequence() .map { it + 1 } .first { it % 100 == 0 } } fun test5() { val list = listOf(1, 2, 3) .asSequence() .map { it + 1 println("map") } /** * * 每次forEach上面的map都会重新计算一次,都会重新计算元素。Lists(集合) 中的元素只计算一次,然后存储在内存中。 * 这就是为什么你不应该将Sequences(序列) 作为参数传递给函数: 函数可能会多次遍历它们。在传递或者在整个使用List之前建议将Sequences(序列) 转换 Lists(集合) * 如果你真的想要传递一个Sequences(序列),你可以使用constrainOnce() - 它只允许一次遍历Sequences(序列),第二次尝试遍历会抛出一个异常。 * 不过,我不会建议这种方法,因为它使代码难以维护。 */ list.forEach { println("forEach1->" + it) } println("----------------------------------") list.forEach { println("forEach2->" + it) } } fun test6() { var seq = sequenceOf(1, 2, 3) seq.filter { it % 2 == 0 }.toList() } fun test7() { /** * generateSequence的意思看源码自己理解 */ generateSequence(1, { println("----" + it) it + 1 }) .map { it * 2 }.take(3) .forEach { println(it) } } /** * 如果Sequence序列有类似sort这样的函数是有争议的,因为它只是固定空间长度上的惰性,并且不能用于不定长的序列。 * 之所以引进它是因为它是一种比较受欢迎的函数,并且以这种方式使用它更容易。 * 但是Kotlin开发人员应该要记住,它不能用于不定长的序列 * * 输出: * 0 * 1 * 2 */ fun test8() { generateSequence(0) { it + 1 }.sorted().take(3).toList() println("test8") } /** * take后,sequence变成了定长的序列 */ fun test9() { val list = generateSequence(0) { it + 1 }.take(3).sorted().toList() list.forEach(::println) } /** * 仅仅7行即7次操作。这意味着它只要找到第一个元素的那一刻,就会终止整个过程。 * * 输出: * * In Filter 2 * In Map 2 * In Filter 4 * In Map 3 * In Filter 6 * 6 */ fun test10() { val sequence = sequenceOf(1, 2, 3, 4, 5, 6) val result = sequence .map { println("In Map $it"); it * 2 } .filter { println("In Filter $it");it % 3 == 0 } println(result.first()) } /** * 一个相对令人惊讶的结果,如Map:Filter:Sum,Sequence比List快得多,而Map:Filter:Average,List比Sequence要快得多。 * * List: 在Sum操作上花费了3.605s,在Average操作上花费了3.536s * Sequence: 在Sum操作上花费了1.121s, 在Average操作上花费了1.058s * 3605 * List Map Sum= 1125788928 * 1121 * Sequence Map Sum 1125788928 * * 1083 * List Map Average 2.0000001E7 * 2222 * Sequence Map Average 2.0000001E7 */ fun test11() { val sequence = generateSequence(1) { it + 1 }.take(20000000) val list = sequence.toList() println("List Map Sum= " + measureNanoTime { list.map { it * 2 }.sum() }) println("Sequence Map Sum " + measureNanoTime { sequence.map { it * 2 }.sum() }) println("List Map Average " + measureNanoTime { list.map { it * 2 }.average() }) println("Sequence Map Average " + measureNanoTime { sequence.map { it * 2 }.average() }) } private fun measureNanoTime(map: () -> Number): Number { val start = System.currentTimeMillis() val result = map() println((System.currentTimeMillis() - start)) return result } }
mit
4cf666130ebfe226f36dbaa31d97dfab
23.874525
147
0.485858
3.053688
false
true
false
false
LorittaBot/Loritta
discord/loritta-bot-common/src/main/kotlin/net/perfectdreams/loritta/morenitta/profile/profiles/MSNProfileCreator.kt
1
6804
package net.perfectdreams.loritta.morenitta.profile.profiles import dev.kord.common.entity.Snowflake import net.perfectdreams.loritta.morenitta.LorittaBot import net.perfectdreams.loritta.morenitta.dao.Profile import net.perfectdreams.loritta.common.locale.BaseLocale import net.perfectdreams.i18nhelper.core.I18nContext import net.perfectdreams.loritta.morenitta.profile.ProfileGuildInfoData import net.perfectdreams.loritta.morenitta.profile.ProfileUserInfoData import net.perfectdreams.loritta.morenitta.profile.ProfileUtils import net.perfectdreams.loritta.morenitta.utils.* import net.perfectdreams.loritta.morenitta.utils.extensions.readImage import java.awt.Color import java.awt.Font import java.awt.image.BufferedImage import java.io.File import java.io.FileInputStream class MSNProfileCreator(loritta: LorittaBot) : StaticProfileCreator(loritta, "msn") { override suspend fun create( sender: ProfileUserInfoData, user: ProfileUserInfoData, userProfile: Profile, guild: ProfileGuildInfoData?, badges: List<BufferedImage>, locale: BaseLocale, i18nContext: I18nContext, background: BufferedImage, aboutMe: String, allowedDiscordEmojis: List<Snowflake>? ): BufferedImage { val profileWrapper = readImage(File(LorittaBot.ASSETS, "profile/msn/profile_wrapper.png")) val base = BufferedImage(800, 600, BufferedImage.TYPE_INT_ARGB) // Base val graphics = base.graphics.enableFontAntiAliasing() val avatar = LorittaUtils.downloadImage(loritta, user.avatarUrl)!!.getScaledInstance(141, 141, BufferedImage.SCALE_SMOOTH) val imageToBeDownload = sender.avatarUrl // TODO: If the user is not provided, use Loritta's avatar val senderAvatar = (LorittaUtils.downloadImage(loritta, imageToBeDownload) ?: Constants.DEFAULT_DISCORD_BLUE_AVATAR).getScaledInstance(141, 141, BufferedImage.SCALE_SMOOTH) val msnFont = FileInputStream(File(LorittaBot.ASSETS + "micross.ttf")).use { Font.createFont(Font.TRUETYPE_FONT, it) } val latoRegular = loritta.graphicsFonts.latoRegular val latoBold = loritta.graphicsFonts.latoBold val latoBlack = loritta.graphicsFonts.latoBlack val latoBold38 = latoBold.deriveFont(38f) val latoRegular32 = latoBold.deriveFont(32f) val latoBlack20 = latoBlack.deriveFont(20f) val latoBold20 = latoBold.deriveFont(20f) val msnFont20 = latoRegular.deriveFont(20f) val msnFont15 = latoBlack20.deriveFont(17f) val msnFont24 = latoBlack20.deriveFont(24f) graphics.drawImage(background.getScaledInstance(800, 600, BufferedImage.SCALE_SMOOTH), 0, 0, null) graphics.drawImage(avatar, 70, 130, null) graphics.drawImage(senderAvatar, 70, 422, null) graphics.drawImage(profileWrapper, 0, 0, null) graphics.font = msnFont15 graphics.color = Color(255, 255, 255) graphics.drawText(loritta, "${user.name}#${user.discriminator} <${user.id}>", 40, 27) graphics.font = latoRegular32 // OUTLINE graphics.color = Color(51, 51, 51) graphics.drawText(loritta, user.name, 266, 142) graphics.drawText(loritta, user.name, 272, 142) graphics.drawText(loritta, user.name, 269, 139) graphics.drawText(loritta, user.name, 269, 145) // USER NAME graphics.color = Color(255, 255, 255) graphics.drawText(loritta, user.name, 269, 142) ProfileUtils.getMarriageInfo(loritta, userProfile)?.let { (marriage, marriedWith) -> val marriedWithText = "${locale["profile.marriedWith"]} ${marriedWith.name}#${marriedWith.discriminator}" val gameIcon = readImage(File(LorittaBot.ASSETS, "profile/msn/game_icon.png")) graphics.drawImage(gameIcon, 0, 5, null) graphics.font = msnFont24 graphics.color = Color(51, 51, 51) graphics.drawText(loritta, marriedWithText, 294, 169) graphics.drawText(loritta, marriedWithText, 296, 169) graphics.drawText(loritta, marriedWithText, 295, 168) graphics.drawText(loritta, marriedWithText, 295, 170) // GAME graphics.color = Color(255, 255, 255) graphics.drawText(loritta, marriedWithText, 295, 169) } graphics.font = msnFont20 graphics.color = Color(142, 124, 125) ImageUtils.drawTextWrapSpaces(loritta, "Não inclua informações como senhas ou número de cartões de crédito em uma mensagem instantânea", 297, 224, 768, 1000, graphics.fontMetrics, graphics) ImageUtils.drawTextWrapSpaces(loritta, "${user.name} diz", 267, 302, 768, 1000, graphics.fontMetrics, graphics) ImageUtils.drawTextWrapSpaces(loritta, /* "Olá, meu nome é ${user.name}! Atualmente eu tenho ${userProfile.dreams} Sonhos, já recebi ${userProfile.receivedReputations.size} reputações, estou em #$position (${userProfile.xp} XP) no rank global e estou em #${localPosition ?: "???"} (${xpLocal?.xp} XP) no rank do ${guild.name}!\n\n${userProfile.aboutMe}" */ aboutMe, 297, 326, 768, 1000, graphics.fontMetrics, graphics) val shiftY = 291 graphics.font = latoBlack20 val globalPosition = ProfileUtils.getGlobalExperiencePosition(loritta, userProfile) graphics.drawText(loritta, "Global", 4, 21 + shiftY, 244) graphics.font = latoBold20 if (globalPosition != null) graphics.drawText(loritta, "#$globalPosition / ${userProfile.xp} XP", 4, 39 + shiftY, 244) else graphics.drawText(loritta, "${userProfile.xp} XP", 4, 39 + shiftY, 244) if (guild != null) { val localProfile = ProfileUtils.getLocalProfile(loritta, guild, user) val localPosition = ProfileUtils.getLocalExperiencePosition(loritta, localProfile) val xpLocal = localProfile?.xp graphics.font = latoBlack20 graphics.drawText(loritta, guild.name, 4, 61 + shiftY, 244) graphics.font = latoBold20 if (xpLocal != null) { if (localPosition != null) { graphics.drawText(loritta, "#$localPosition / $xpLocal XP", 4, 78 + shiftY, 244) } else { graphics.drawText(loritta, "$xpLocal XP", 4, 78 + shiftY, 244) } graphics.drawText(loritta, "#${localPosition ?: "???"} / $xpLocal XP", 4, 78 + shiftY, 244) } else { graphics.drawText(loritta, "???", 4, 78 + shiftY, 244) } } graphics.font = latoBlack20 graphics.drawText(loritta, "Sonhos", 4, 98 + shiftY, 244) graphics.font = latoBold20 graphics.drawText(loritta, userProfile.money.toString(), 4, 116 + shiftY, 244) var x = 272 var y = 518 for ((index, badge) in badges.withIndex()) { graphics.drawImage(badge.getScaledInstance(29, 29, BufferedImage.SCALE_SMOOTH), x, y, null) x += 35 if (index % 14 == 13) { // Aumentar chat box val extendedChatBox = readImage(File(LorittaBot.ASSETS, "profile/msn/extended_chat_box.png")) graphics.drawImage(extendedChatBox, 266, y - 38, null) x = 272 y -= 32 } } val reputations = ProfileUtils.getReputationCount(loritta, user) graphics.color = Color.WHITE graphics.font = latoBold20 graphics.drawText(loritta, "Reputações: $reputations reps", 11, 73) return base } }
agpl-3.0
fc54d947bff19590d9636bceaa319b16
40.157576
420
0.742563
3.405216
false
false
false
false
kotlintest/kotlintest
kotest-assertions/src/commonMain/kotlin/io/kotest/matchers/floats/FloatMatchers.kt
2
1407
package io.kotest.matchers.floats import io.kotest.matchers.Matcher import io.kotest.matchers.MatcherResult import kotlin.math.abs infix fun Float.plusOrMinus(tolerance: Float): FloatToleranceMatcher = FloatToleranceMatcher(this, tolerance) class FloatToleranceMatcher(private val expected: Float, private val tolerance: Float) : Matcher<Float> { override fun test(value: Float): MatcherResult { return if (expected.isNaN() && value.isNaN()) { println("[WARN] By design, Float.Nan != Float.Nan; see https://stackoverflow.com/questions/8819738/why-does-double-nan-double-nan-return-false/8819776#8819776") MatcherResult( false, "By design, Float.Nan != Float.Nan; see https://stackoverflow.com/questions/8819738/why-does-double-nan-double-nan-return-false/8819776#8819776", "By design, Float.Nan != Float.Nan; see https://stackoverflow.com/questions/8819738/why-does-double-nan-double-nan-return-false/8819776#8819776" ) } else { if (tolerance == 0.0F) println("[WARN] When comparing Float consider using tolerance, eg: a shouldBe b plusOrMinus c") val diff = abs(value - expected) MatcherResult(diff <= tolerance, "$value should be equal to $expected", "$value should not be equal to $expected") } } infix fun plusOrMinus(tolerance: Float): FloatToleranceMatcher = FloatToleranceMatcher(expected, tolerance) }
apache-2.0
da46caca731327efc382752a745df39b
49.25
166
0.727079
3.712401
false
true
false
false
DevCharly/kotlin-ant-dsl
src/main/kotlin/com/devcharly/kotlin/ant/types/dirset.kt
1
8456
/* * Copyright 2016 Karl Tauber * * 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.devcharly.kotlin.ant import org.apache.tools.ant.types.DirSet import org.apache.tools.ant.types.selectors.AndSelector import org.apache.tools.ant.types.selectors.ContainsRegexpSelector import org.apache.tools.ant.types.selectors.ContainsSelector import org.apache.tools.ant.types.selectors.DateSelector import org.apache.tools.ant.types.selectors.DependSelector import org.apache.tools.ant.types.selectors.DepthSelector import org.apache.tools.ant.types.selectors.DifferentSelector import org.apache.tools.ant.types.selectors.ExecutableSelector import org.apache.tools.ant.types.selectors.ExtendSelector import org.apache.tools.ant.types.selectors.FileSelector import org.apache.tools.ant.types.selectors.FilenameSelector import org.apache.tools.ant.types.selectors.MajoritySelector import org.apache.tools.ant.types.selectors.NoneSelector import org.apache.tools.ant.types.selectors.NotSelector import org.apache.tools.ant.types.selectors.OrSelector import org.apache.tools.ant.types.selectors.OwnedBySelector import org.apache.tools.ant.types.selectors.PresentSelector import org.apache.tools.ant.types.selectors.ReadableSelector import org.apache.tools.ant.types.selectors.SelectSelector import org.apache.tools.ant.types.selectors.SizeSelector import org.apache.tools.ant.types.selectors.SymlinkSelector import org.apache.tools.ant.types.selectors.TypeSelector import org.apache.tools.ant.types.selectors.WritableSelector import org.apache.tools.ant.types.selectors.modifiedselector.ModifiedSelector /****************************************************************************** DO NOT EDIT - this file was generated ******************************************************************************/ interface IDirSetNested : INestedComponent { fun dirset( dir: String? = null, file: String? = null, includes: String? = null, excludes: String? = null, includesfile: String? = null, excludesfile: String? = null, defaultexcludes: Boolean? = null, casesensitive: Boolean? = null, followsymlinks: Boolean? = null, maxlevelsofsymlinks: Int? = null, erroronmissingdir: Boolean? = null, nested: (KDirSet.() -> Unit)? = null) { _addDirSet(DirSet().apply { component.project.setProjectReference(this); _init(dir, file, includes, excludes, includesfile, excludesfile, defaultexcludes, casesensitive, followsymlinks, maxlevelsofsymlinks, erroronmissingdir, nested) }) } fun _addDirSet(value: DirSet) } fun IResourceCollectionNested.dirset( dir: String? = null, file: String? = null, includes: String? = null, excludes: String? = null, includesfile: String? = null, excludesfile: String? = null, defaultexcludes: Boolean? = null, casesensitive: Boolean? = null, followsymlinks: Boolean? = null, maxlevelsofsymlinks: Int? = null, erroronmissingdir: Boolean? = null, nested: (KDirSet.() -> Unit)? = null) { _addResourceCollection(DirSet().apply { component.project.setProjectReference(this); _init(dir, file, includes, excludes, includesfile, excludesfile, defaultexcludes, casesensitive, followsymlinks, maxlevelsofsymlinks, erroronmissingdir, nested) }) } fun DirSet._init( dir: String?, file: String?, includes: String?, excludes: String?, includesfile: String?, excludesfile: String?, defaultexcludes: Boolean?, casesensitive: Boolean?, followsymlinks: Boolean?, maxlevelsofsymlinks: Int?, erroronmissingdir: Boolean?, nested: (KDirSet.() -> Unit)?) { if (dir != null) setDir(project.resolveFile(dir)) if (file != null) setFile(project.resolveFile(file)) if (includes != null) setIncludes(includes) if (excludes != null) setExcludes(excludes) if (includesfile != null) setIncludesfile(project.resolveFile(includesfile)) if (excludesfile != null) setExcludesfile(project.resolveFile(excludesfile)) if (defaultexcludes != null) setDefaultexcludes(defaultexcludes) if (casesensitive != null) setCaseSensitive(casesensitive) if (followsymlinks != null) setFollowSymlinks(followsymlinks) if (maxlevelsofsymlinks != null) setMaxLevelsOfSymlinks(maxlevelsofsymlinks) if (erroronmissingdir != null) setErrorOnMissingDir(erroronmissingdir) if (nested != null) nested(KDirSet(this)) } class KDirSet(override val component: DirSet) : IFileSelectorNested, ISelectSelectorNested, IAndSelectorNested, IOrSelectorNested, INotSelectorNested, INoneSelectorNested, IMajoritySelectorNested, IDateSelectorNested, ISizeSelectorNested, IDifferentSelectorNested, IFilenameSelectorNested, ITypeSelectorNested, IExtendSelectorNested, IContainsSelectorNested, IPresentSelectorNested, IDepthSelectorNested, IDependSelectorNested, IContainsRegexpSelectorNested, IModifiedSelectorNested, IReadableSelectorNested, IWritableSelectorNested, IExecutableSelectorNested, ISymlinkSelectorNested, IOwnedBySelectorNested { fun patternset(includes: String? = null, excludes: String? = null, includesfile: String? = null, excludesfile: String? = null, nested: (KPatternSet.() -> Unit)? = null) { component.createPatternSet().apply { component.project.setProjectReference(this) _init(includes, excludes, includesfile, excludesfile, nested) } } fun include(name: String? = null, If: String? = null, unless: String? = null) { component.createInclude().apply { _init(name, If, unless) } } fun includesfile(name: String? = null, If: String? = null, unless: String? = null) { component.createIncludesFile().apply { _init(name, If, unless) } } fun exclude(name: String? = null, If: String? = null, unless: String? = null) { component.createExclude().apply { _init(name, If, unless) } } fun excludesfile(name: String? = null, If: String? = null, unless: String? = null) { component.createExcludesFile().apply { _init(name, If, unless) } } override fun _addFileSelector(value: FileSelector) = component.add(value) override fun _addSelectSelector(value: SelectSelector) = component.addSelector(value) override fun _addAndSelector(value: AndSelector) = component.addAnd(value) override fun _addOrSelector(value: OrSelector) = component.addOr(value) override fun _addNotSelector(value: NotSelector) = component.addNot(value) override fun _addNoneSelector(value: NoneSelector) = component.addNone(value) override fun _addMajoritySelector(value: MajoritySelector) = component.addMajority(value) override fun _addDateSelector(value: DateSelector) = component.addDate(value) override fun _addSizeSelector(value: SizeSelector) = component.addSize(value) override fun _addDifferentSelector(value: DifferentSelector) = component.addDifferent(value) override fun _addFilenameSelector(value: FilenameSelector) = component.addFilename(value) override fun _addTypeSelector(value: TypeSelector) = component.addType(value) override fun _addExtendSelector(value: ExtendSelector) = component.addCustom(value) override fun _addContainsSelector(value: ContainsSelector) = component.addContains(value) override fun _addPresentSelector(value: PresentSelector) = component.addPresent(value) override fun _addDepthSelector(value: DepthSelector) = component.addDepth(value) override fun _addDependSelector(value: DependSelector) = component.addDepend(value) override fun _addContainsRegexpSelector(value: ContainsRegexpSelector) = component.addContainsRegexp(value) override fun _addModifiedSelector(value: ModifiedSelector) = component.addModified(value) override fun _addReadableSelector(value: ReadableSelector) = component.addReadable(value) override fun _addWritableSelector(value: WritableSelector) = component.addWritable(value) override fun _addExecutableSelector(value: ExecutableSelector) = component.addExecutable(value) override fun _addSymlinkSelector(value: SymlinkSelector) = component.addSymlink(value) override fun _addOwnedBySelector(value: OwnedBySelector) = component.addOwnedBy(value) }
apache-2.0
2af2de09cfd7ad3c97c7c10288e58504
38.699531
171
0.767148
3.826244
false
false
false
false
yschimke/oksocial
src/main/kotlin/com/baulsupp/okurl/authenticator/PrintCredentials.kt
1
4809
package com.baulsupp.okurl.authenticator import com.baulsupp.oksocial.output.OutputHandler import com.baulsupp.okurl.commands.ToolSession import com.baulsupp.okurl.credentials.CredentialsStore import com.baulsupp.okurl.credentials.ServiceDefinition import com.baulsupp.okurl.credentials.TokenSet import com.baulsupp.okurl.util.ClientException import kotlinx.coroutines.Deferred import kotlinx.coroutines.async import kotlinx.coroutines.coroutineScope import kotlinx.coroutines.runBlocking import kotlinx.coroutines.withTimeout import okhttp3.Response import java.io.IOException import java.time.ZonedDateTime import java.time.temporal.ChronoUnit import java.util.concurrent.CancellationException import java.util.concurrent.TimeUnit import java.util.concurrent.TimeoutException import java.util.logging.Level import java.util.logging.Logger class PrintCredentials(private val commandLineClient: ToolSession) { private val logger = Logger.getLogger(PrintCredentials::class.java.name) val outputHandler: OutputHandler<Response> = commandLineClient.outputHandler val credentialsStore: CredentialsStore = commandLineClient.credentialsStore private val started: ZonedDateTime = ZonedDateTime.now() private fun printKnownCredentials(future: Deferred<ValidatedCredentials>, key: Key) { try { val left = 2000L - ZonedDateTime.now().until(started, ChronoUnit.MILLIS) val validated = runBlocking { withTimeout(TimeUnit.MILLISECONDS.toMillis(left)) { future.await() } } printSuccess(key, validated) } catch (e: Exception) { printFailed(key, e) } } private fun printSuccess(key: Key, validated: ValidatedCredentials?) { val sd = key.auth.serviceDefinition outputHandler.info( "%-40s\t%-20s\t%-20s\t%-20s".format( displayName(sd), key.tokenSet.name, validated?.username ?: "-", validated?.clientName ?: "-" ) ) } fun displayName(sd: ServiceDefinition<*>) = sd.serviceName() + " (" + sd.shortName() + ")" private fun printFailed(key: Key, e: Throwable) { val sd = key.auth.serviceDefinition when (e) { is CancellationException -> outputHandler.info( "%-40s\t%-20s %s".format( displayName(sd), key.tokenSet.name, "timeout" ) ) is TimeoutException -> outputHandler.info( "%-40s\t%-20s %s".format( displayName(sd), key.tokenSet.name, "timeout" ) ) is ClientException -> outputHandler.info( "%-40s\t%-20s %s".format( displayName(sd), key.tokenSet.name, key.auth.errorMessage(e) ) ) is IOException -> outputHandler.info("%-40s\t%-20s %s".format(displayName(sd), key.tokenSet.name, e.toString())) else -> outputHandler.info("%-40s\t%-20s %s".format(displayName(sd), key.tokenSet.name, e.toString())) } } suspend fun showCredentials(arguments: List<String>) { var services: Iterable<AuthInterceptor<*>> = commandLineClient.serviceLibrary.services val names = commandLineClient.defaultTokenSet?.let { listOf(it) } ?: commandLineClient.credentialsStore.names().map { TokenSet(it) } val full = arguments.isNotEmpty() if (arguments.isNotEmpty()) { services = arguments.mapNotNull { commandLineClient.serviceLibrary.findAuthInterceptor(it) } } val futures = validate(services, names) for ((key, future) in futures) { printKnownCredentials(future, key) if (full) { printCredentials(key) } } } data class Key(val auth: AuthInterceptor<*>, val tokenSet: TokenSet) private suspend fun printCredentials(key: Key) { val sd: ServiceDefinition<*> = key.auth.serviceDefinition val credentialsString = credentialsStore.get(sd, key.tokenSet)?.let { s(sd, it) } ?: "-" outputHandler.info(credentialsString) } suspend fun validate( services: Iterable<AuthInterceptor<*>>, names: List<TokenSet> ): Map<Key, Deferred<ValidatedCredentials>> = coroutineScope { services.flatMap { sv -> names.mapNotNull { name -> val credentials = try { credentialsStore.get(sv.serviceDefinition, name) } catch (e: Exception) { logger.log(Level.WARNING, "failed to read credentials for " + sv.name(), e) null } credentials?.let { val x = async { v(sv, credentials) } Pair(Key(sv, name), x) } } }.toMap() } suspend fun <T> v(sv: AuthInterceptor<T>, credentials: Any) = sv.validate(commandLineClient.client, sv.serviceDefinition.castToken(credentials)) fun <T> s(sd: ServiceDefinition<T>, credentials: Any) = sd.formatCredentialsString(sd.castToken(credentials)) }
apache-2.0
6ef35131a7b81cc1ffc63b093e94868b
31.493243
118
0.678311
4.167244
false
false
false
false
abdoyassen/OnlyU
NoteApp/StartUp/app/src/main/java/com/example/onlyu/startup/DbManger.kt
1
2371
package com.example.onlyu.startup import android.content.ContentValues import android.content.Context import android.database.Cursor import android.database.sqlite.SQLiteDatabase import android.database.sqlite.SQLiteOpenHelper import android.database.sqlite.SQLiteQueryBuilder import android.widget.Toast class DbManger { val dbName="MyNotes" val dbTable="Notes" val colID="ID" val colTitle="Title" val colDes="Description" val dbVersion=1 //CREATE TABLE IF NOT EXISTS MyNotes (ID INTEGER PRIMARY KEY,title TEXT, Description TEXT);" val sqlCreateTable="CREATE TABLE IF NOT EXISTS "+ dbTable +" ("+ colID +" INTEGER PRIMARY KEY,"+ colTitle + " TEXT, "+ colDes +" TEXT);" var sqlDB:SQLiteDatabase?=null constructor(context:Context){ var db=DatabaseHelperNotes(context) sqlDB=db.writableDatabase } inner class DatabaseHelperNotes:SQLiteOpenHelper{ var context:Context?=null constructor(context:Context):super(context,dbName,null,dbVersion){ this.context=context } override fun onCreate(p0: SQLiteDatabase?) { p0!!.execSQL(sqlCreateTable) Toast.makeText(this.context," database is created", Toast.LENGTH_LONG).show() } override fun onUpgrade(p0: SQLiteDatabase?, p1: Int, p2: Int) { p0!!.execSQL("Drop table IF EXISTS " + dbTable) } } fun Insert(values:ContentValues):Long{ val ID= sqlDB!!.insert(dbTable,"",values) return ID } fun Query(projection:Array<String>,selection:String,selectionArgs:Array<String>,sorOrder:String):Cursor{ val qb=SQLiteQueryBuilder() qb.tables=dbTable val cursor=qb.query(sqlDB,projection,selection,selectionArgs,null,null,sorOrder) return cursor } fun Delete(selection:String,selectionArgs:Array<String>):Int{ val count=sqlDB!!.delete(dbTable,selection,selectionArgs) return count } fun Update(values:ContentValues,selection:String,selectionargs:Array<String>):Int{ val count=sqlDB!!.update(dbTable,values,selection,selectionargs) return count } }
mit
043ccc36695428c7b56c1fef99bd2707
30.210526
113
0.631379
4.639922
false
false
false
false
Shynixn/PetBlocks
petblocks-core/src/test/java/unittest/LoggingUtilServiceTest.kt
1
6088
package unittest import com.github.shynixn.petblocks.api.business.service.LoggingService import com.github.shynixn.petblocks.core.logic.business.service.LoggingUtilServiceImpl import org.junit.jupiter.api.Assertions import org.junit.jupiter.api.Test import org.mockito.Mockito import java.util.logging.Level import java.util.logging.Logger /** * Created by Shynixn 2018. * <p> * Version 1.2 * <p> * MIT License * <p> * Copyright (c) 2018 by Shynixn * <p> * 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: * <p> * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * <p> * 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. */ class LoggingUtilServiceTest { /** * Given * a info log message without throwable. * When * info is called * Then * utils info should be called. */ @Test fun info_LogMessage_ShouldCallInfo() { // Arrange var infoCalled = false val logger = Mockito.mock(Logger::class.java) Mockito.`when`(logger.log(Mockito.any(Level::class.java),Mockito.anyString())).then { infoCalled = true Unit } val classUnderTest = createWithDependencies(logger) // Act classUnderTest.info("Sample log message.") // Assert Assertions.assertTrue(infoCalled) } /** * Given * a info log message with throwable. * When * info is called * Then * utils info should be called. */ @Test fun info_LogMessageWithError_ShouldCallInfo() { // Arrange var infoCalled = false val logger = Mockito.mock(Logger::class.java) Mockito.`when`(logger.log(Mockito.any(Level::class.java),Mockito.anyString(), Mockito.any(Throwable::class.java))).then { infoCalled = true Unit } val classUnderTest = createWithDependencies(logger) val exception = RuntimeException() // Act classUnderTest.info("Sample log message.", exception) // Assert Assertions.assertTrue(infoCalled) } /** * Given * a warn log message without throwable. * When * warn is called * Then * utils warn should be called. */ @Test fun warn_LogMessage_ShouldCallWarn() { // Arrange var warnCalled = false val logger = Mockito.mock(Logger::class.java) Mockito.`when`(logger.log(Mockito.any(Level::class.java),Mockito.anyString())).then { warnCalled = true Unit } val classUnderTest = createWithDependencies(logger) // Act classUnderTest.warn("Sample log message.") // Assert Assertions.assertTrue(warnCalled) } /** * Given * a warn log message with throwable. * When * warn is called * Then * utils warn should be called. */ @Test fun warn_LogMessageWithError_ShouldCallWarn() { // Arrange var warnCalled = false val logger = Mockito.mock(Logger::class.java) Mockito.`when`(logger.log(Mockito.any(Level::class.java),Mockito.anyString(), Mockito.any(Throwable::class.java))).then { warnCalled = true Unit } val classUnderTest = createWithDependencies(logger) val exception = RuntimeException() // Act classUnderTest.warn("Sample log message.", exception) // Assert Assertions.assertTrue(warnCalled) } /** * Given * a error log message without throwable. * When * error is called * Then * utils error should be called. */ @Test fun error_LogMessage_ShouldCallError() { // Arrange var errorCalled = false val logger = Mockito.mock(Logger::class.java) Mockito.`when`(logger.log(Mockito.any(Level::class.java),Mockito.anyString())).then { errorCalled = true Unit } val classUnderTest = createWithDependencies(logger) // Act classUnderTest.error("Sample log message.") // Assert Assertions.assertTrue(errorCalled) } /** * Given * a error log message with throwable. * When * error is called * Then * util error should be called. */ @Test fun error_LogMessageWithError_ShouldCallError() { // Arrange var errorCalled = false val logger = Mockito.mock(Logger::class.java) Mockito.`when`(logger.log(Mockito.any(Level::class.java),Mockito.anyString(), Mockito.any(Throwable::class.java))).then { errorCalled = true Unit } val classUnderTest = createWithDependencies(logger) val exception = RuntimeException() // Act classUnderTest.error("Sample log message.", exception) // Assert Assertions.assertTrue(errorCalled) } companion object { fun createWithDependencies(logger: Logger): LoggingService { return LoggingUtilServiceImpl(logger) } } }
apache-2.0
163b29c9e410e5b1f8fb87107e2b12be
28.133971
129
0.622208
4.647328
false
true
false
false
robinverduijn/gradle
subprojects/kotlin-dsl-test-fixtures/src/main/kotlin/org/gradle/kotlin/dsl/fixtures/AbstractDslTest.kt
1
2459
/* * Copyright 2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.gradle.kotlin.dsl.fixtures import org.gradle.api.Project import org.gradle.internal.classpath.ClassPath import java.io.File abstract class AbstractDslTest : TestWithTempFiles() { private val dslTestFixture: DslTestFixture by lazy { DslTestFixture(root) } protected val kotlinDslEvalBaseCacheDir: File get() = dslTestFixture.kotlinDslEvalBaseCacheDir /** * Evaluates the given Kotlin [script] against this [Project] writing compiled classes * to sub-directories of [baseCacheDir] using [scriptCompilationClassPath]. */ fun Project.eval( script: String, baseCacheDir: File = kotlinDslEvalBaseCacheDir, scriptCompilationClassPath: ClassPath = testRuntimeClassPath, scriptRuntimeClassPath: ClassPath = ClassPath.EMPTY ) = dslTestFixture.evalScript( script, this, baseCacheDir, scriptCompilationClassPath, scriptRuntimeClassPath ) } class DslTestFixture(private val testDirectory: File) { val kotlinDslEvalBaseCacheDir: File by lazy { testDirectory.resolve("kotlin-dsl-eval-cache").apply { mkdirs() } } /** * Evaluates the given Kotlin [script] against this [Project] writing compiled classes * to sub-directories of [baseCacheDir] using [scriptCompilationClassPath]. */ fun evalScript( script: String, target: Any, baseCacheDir: File = kotlinDslEvalBaseCacheDir, scriptCompilationClassPath: ClassPath = testRuntimeClassPath, scriptRuntimeClassPath: ClassPath = ClassPath.EMPTY ) = eval( script, target, baseCacheDir, scriptCompilationClassPath, scriptRuntimeClassPath ) }
apache-2.0
564c7918fe50212c8f2094f3a2b045db
28.626506
90
0.677105
4.793372
false
true
false
false
square/leakcanary
leakcanary-object-watcher-android-androidx/src/main/java/leakcanary/internal/ViewModelClearedWatcher.kt
2
2179
package leakcanary.internal import androidx.lifecycle.ViewModel import androidx.lifecycle.ViewModelProvider import androidx.lifecycle.ViewModelProvider.Factory import androidx.lifecycle.ViewModelStore import androidx.lifecycle.ViewModelStoreOwner import leakcanary.ReachabilityWatcher import leakcanary.internal.ViewModelClearedWatcher.Companion.install /** * [AndroidXFragmentDestroyWatcher] calls [install] to add a spy [ViewModel] in every * [ViewModelStoreOwner] instance (i.e. FragmentActivity and Fragment). [ViewModelClearedWatcher] * holds on to the map of [ViewModel]s backing its store. When [ViewModelClearedWatcher] receives * the [onCleared] callback, it adds each live [ViewModel] from the store to the [ReachabilityWatcher]. */ internal class ViewModelClearedWatcher( storeOwner: ViewModelStoreOwner, private val reachabilityWatcher: ReachabilityWatcher ) : ViewModel() { // We could call ViewModelStore#keys with a package spy in androidx.lifecycle instead, // however that was added in 2.1.0 and we support AndroidX first stable release. viewmodel-2.0.0 // does not have ViewModelStore#keys. All versions currently have the mMap field. private val viewModelMap: Map<String, ViewModel>? = try { val mMapField = ViewModelStore::class.java.getDeclaredField("mMap") mMapField.isAccessible = true @Suppress("UNCHECKED_CAST") mMapField[storeOwner.viewModelStore] as Map<String, ViewModel> } catch (ignored: Exception) { null } override fun onCleared() { viewModelMap?.values?.forEach { viewModel -> reachabilityWatcher.expectWeaklyReachable( viewModel, "${viewModel::class.java.name} received ViewModel#onCleared() callback" ) } } companion object { fun install( storeOwner: ViewModelStoreOwner, reachabilityWatcher: ReachabilityWatcher ) { val provider = ViewModelProvider(storeOwner, object : Factory { @Suppress("UNCHECKED_CAST") override fun <T : ViewModel?> create(modelClass: Class<T>): T = ViewModelClearedWatcher(storeOwner, reachabilityWatcher) as T }) provider.get(ViewModelClearedWatcher::class.java) } } }
apache-2.0
9c60fb9d688af0a6f7e30564bb77b855
38.618182
103
0.753098
4.587368
false
false
false
false
PGMacDesign/PGMacUtilities
library/src/main/java/com/pgmacdesign/pgmactips/misc/FileMover.kt
1
1994
package com.pgmacdesign.pgmactips.misc import android.Manifest import android.content.ContentValues import android.content.Context import android.net.Uri import android.os.Build import android.os.Environment import android.provider.MediaStore import androidx.core.content.FileProvider import androidx.documentfile.provider.DocumentFile import java.io.BufferedInputStream import java.io.File import java.io.FileInputStream //This will be used only on android P- private val DOWNLOAD_DIR2 = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) //Kitkat or above fun getMimeTypeForUri(context: Context, finalUri: Uri) : String = DocumentFile.fromSingleUri(context, finalUri)?.type ?: "application/octet-stream" /** * Pulled from https://stackoverflow.com/a/64357198/2480714 * This copies a file from the internal directory to the Downloads directory. * Note, requires the [Manifest.permission.WRITE_EXTERNAL_STORAGE] perm */ fun copyFileToDownloads(context: Context, downloadedFile: File): Uri? { val resolver = context.contentResolver return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) { val contentValues = ContentValues().apply { put(MediaStore.MediaColumns.DISPLAY_NAME, downloadedFile.name) put(MediaStore.MediaColumns.SIZE, downloadedFile.length()) } resolver.insert(MediaStore.Downloads.EXTERNAL_CONTENT_URI, contentValues) } else { val authority = "${context.packageName}.provider" val destinyFile = File(DOWNLOAD_DIR2, downloadedFile.name) FileProvider.getUriForFile(context, authority, destinyFile) }?.also { downloadedUri -> resolver.openOutputStream(downloadedUri).use { outputStream -> val brr = ByteArray(1024) var len: Int val bufferedInputStream = BufferedInputStream(FileInputStream(downloadedFile.absoluteFile)) while ((bufferedInputStream.read(brr, 0, brr.size).also { len = it }) != -1) { outputStream?.write(brr, 0, len) } outputStream?.flush() bufferedInputStream.close() } } }
apache-2.0
70acc8a686c99a1effe4b7fc7eaaeff4
35.944444
106
0.780843
3.909804
false
false
false
false
facebook/litho
sample/src/main/java/com/facebook/samples/litho/kotlin/bordereffects/AlternateColorCornerPathEffectBorder.kt
1
2048
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.facebook.samples.litho.kotlin.bordereffects import com.facebook.litho.Component import com.facebook.litho.ComponentScope import com.facebook.litho.KComponent import com.facebook.litho.Row import com.facebook.litho.Style import com.facebook.litho.dp import com.facebook.litho.flexbox.border import com.facebook.litho.kotlin.widget.Border import com.facebook.litho.kotlin.widget.BorderEdge import com.facebook.litho.kotlin.widget.BorderEffect import com.facebook.litho.kotlin.widget.BorderRadius import com.facebook.litho.kotlin.widget.Text // this doesn't actually have a path on it though? class AlternateColorCornerPathEffectBorder : KComponent() { override fun ComponentScope.render(): Component { return Row( style = Style.border( Border( edgeAll = BorderEdge(width = 5f.dp), edgeTop = BorderEdge(color = NiceColor.ORANGE), edgeBottom = BorderEdge(color = NiceColor.BLUE), edgeLeft = BorderEdge(color = NiceColor.RED), edgeRight = BorderEdge(color = NiceColor.GREEN), radius = BorderRadius(20f.dp), effect = BorderEffect.discrete(4f, 11f)))) { child( Text( "This component has a path effect with rounded corners + multiple colors", textSize = 20f.dp)) } } }
apache-2.0
9abd084c0eaca7f8c8a94506f99a0620
37.641509
92
0.681641
4.284519
false
false
false
false
fython/PackageTracker
mobile/src/main/kotlin/info/papdt/express/helper/ui/fragment/settings/SettingsMain.kt
1
3190
package info.papdt.express.helper.ui.fragment.settings import android.content.Intent import android.content.pm.PackageManager import android.net.Uri import android.os.Bundle import com.google.android.material.snackbar.Snackbar import android.view.Menu import android.view.MenuInflater import android.view.MenuItem import info.papdt.express.helper.R import info.papdt.express.helper.support.* import moe.feng.alipay.zerosdk.AlipayZeroSdk import moe.shizuku.preference.Preference import moe.feng.kotlinyan.common.* class SettingsMain : AbsPrefFragment(), Preference.OnPreferenceClickListener { // About private val mPrefVersion: Preference by PreferenceProperty("version") private val mPrefSina: Preference by PreferenceProperty("sina") private val mPrefGithub: Preference by PreferenceProperty("github") private var mPrefAlipay: Preference? = null private val mPrefTelegram: Preference by PreferenceProperty("telegram") override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setHasOptionsMenu(true) } override fun onCreatePreferences(bundle: Bundle?, s: String?) { addPreferencesFromResource(R.xml.settings_main) mPrefAlipay = findPreference("alipay") var versionName: String? = null var versionCode = 0 try { activity?.packageManager?.getPackageInfo(activity?.packageName, 0)?.let { versionName = it.versionName versionCode = it.versionCode } } catch (e: PackageManager.NameNotFoundException) { e.printStackTrace() } mPrefVersion.summary = String.format(getString(R.string.app_version_format), versionName, versionCode) mPrefVersion.onPreferenceClickListener = this mPrefGithub.onPreferenceClickListener = this mPrefSina.onPreferenceClickListener = this mPrefAlipay?.onPreferenceClickListener = this mPrefTelegram.onPreferenceClickListener = this } override fun onPreferenceClick(pref: Preference): Boolean { return when (pref) { // About mPrefGithub -> { openWebsite(getString(R.string.github_repo_url)) true } mPrefSina -> { openWebsite(getString(R.string.author_sina_url)) true } mPrefAlipay -> { if (AlipayZeroSdk.hasInstalledAlipayClient(activity)) { AlipayZeroSdk.startAlipayClient(activity, "aehvyvf4taua18zo6e") } else { ClipboardUtils.putString(activity, getString(R.string.alipay_support_account)) makeSnackbar(getString(R.string.toast_copied_successfully), Snackbar.LENGTH_SHORT) ?.show() } SettingsInstance.clickedDonate = true true } mPrefTelegram -> { openWebsite("https://t.me/gwo_apps") true } else -> false } } override fun onCreateOptionsMenu(menu: Menu?, inflater: MenuInflater?) { inflater?.inflate(R.menu.menu_settings_main, menu) menu?.tintItemsColor(resources.color[android.R.color.white]) super.onCreateOptionsMenu(menu, inflater) } override fun onOptionsItemSelected(item: MenuItem): Boolean = when (item.itemId) { R.id.action_play_store -> { val intent = Intent(Intent.ACTION_VIEW) intent.data = Uri.parse("market://details?id=${activity!!.packageName}") startActivity(intent) true } else -> super.onOptionsItemSelected(item) } }
gpl-3.0
fc7eba93004347582f65d2d46aeced67
29.970874
104
0.75674
3.739742
false
false
false
false
herbeth1u/VNDB-Android
app/src/main/java/com/booboot/vndbandroid/model/vndb/Trait.kt
1
443
package com.booboot.vndbandroid.model.vndb import com.squareup.moshi.JsonClass @JsonClass(generateAdapter = true) data class Trait( var id: Long = 0, var name: String = "", var description: String = "", var meta: Boolean = false, var chars: Int = 0, var aliases: List<String> = emptyList(), var parents: List<Long> = emptyList() ) { override fun toString(): String { return "Trait(name=$name)" } }
gpl-3.0
3cf126ec073af5118c650cba776fec85
23.666667
44
0.641084
3.786325
false
false
false
false
kotlin-es/kotlin-JFrame-standalone
05-start-async-inputDialog-application/src/main/kotlin/Main.kt
1
2645
package src import components.menuBar.child.MenuBarConfirm import components.menuBar.child.MenuBarFile import components.menuBar.child.MenuBarInput import components.menuBar.child.MenuBarMessage import components.progressBar.* import src.app.ApplicationImpl import src.configuration.ConfigurationImpl import src.configuration.Display import src.configuration.DisplayImpl import utils.map.mergeReduce import java.awt.FlowLayout import java.util.* import java.util.concurrent.ExecutionException import javax.swing.JFrame import javax.swing.SwingUtilities /** * Created by vicboma on 02/12/16. */ object Main { @JvmStatic fun main(args: Array<String>) { SwingUtilities.invokeLater { val frame = JFrame() val app = ApplicationImpl.create(frame) val display = DisplayImpl.create(Display.KFRAME_JAVA, Display.WIDHT, Display.HEIGTH, Display.VISIBLE) var textArea = TextAreaImpl.create(TextArea.TEXT) val progressBar = ProgressBarImpl.create(ProgressBar.MIN, ProgressBar.MAX) val panel = PanelImpl.create(FlowLayout(),progressBar,textArea) var textAreaCenter = TextAreaImpl.create(TextArea.KAFKA) val progressBarCenter = ProgressBarImpl.create(ProgressBar.MIN, ProgressBar.MAX) val panelCenter = PanelImpl.create(FlowLayout(),progressBarCenter,textAreaCenter) var textAreaBottom = TextAreaImpl.create(TextArea.LOREMIPSUM) val progressBarBottom = ProgressBarImpl.create(ProgressBar.MIN, ProgressBar.MAX) val panelBottom = PanelImpl.create(FlowLayout(),progressBarBottom,textAreaBottom) val statusBar = StatusBarImpl.create(Display.WIDHT) val menuFile = MenuBarImpl.Companion.MenuBarFile() val menuMessage = MenuBarImpl.Companion.MenuBarMessage(frame) val menuConfirm = MenuBarImpl.Companion.MenuBarConfirm(frame) val menuInput = MenuBarImpl.Companion.MenuBarInput(frame) val reduceMap = menuFile.mergeReduce(menuMessage.mergeReduce(menuConfirm.mergeReduce(menuInput))) val menuBar = MenuBarImpl.create(reduceMap) val configure = ConfigurationImpl.create(display, ArrayList<Panel>(Arrays.asList(panel, panelCenter, panelBottom)), menuBar, statusBar) try { app .startAsync(configure) .get() } catch (e: InterruptedException) { e.printStackTrace() } catch (e: ExecutionException) { e.printStackTrace() } finally { } } } }
mit
f5f6ffca03ab127b74c9fbfaca527f24
35.246575
147
0.690359
4.774368
false
true
false
false
alashow/music-android
modules/core-playback/src/main/java/tm/alashow/datmusic/playback/MediaNotifications.kt
1
7983
/* * Copyright (C) 2021, Alashov Berkeli * All rights reserved. */ package tm.alashow.datmusic.playback import android.app.Notification import android.app.NotificationChannel import android.app.NotificationManager import android.app.NotificationManager.IMPORTANCE_LOW import android.app.PendingIntent import android.app.PendingIntent.FLAG_IMMUTABLE import android.app.PendingIntent.FLAG_MUTABLE import android.app.PendingIntent.FLAG_UPDATE_CURRENT import android.content.Context import android.content.Intent import android.content.pm.PackageManager import android.graphics.Color import android.support.v4.media.session.MediaSessionCompat import android.support.v4.media.session.PlaybackStateCompat.ACTION_STOP import androidx.annotation.DrawableRes import androidx.core.app.NotificationCompat import androidx.media.app.NotificationCompat as NotificationMediaCompat import androidx.palette.graphics.Palette import dagger.hilt.android.qualifiers.ApplicationContext import javax.inject.Inject import kotlinx.coroutines.GlobalScope import kotlinx.coroutines.launch import tm.alashow.base.ui.utils.extensions.systemService import tm.alashow.base.util.extensions.isOreo import tm.alashow.datmusic.playback.receivers.MediaButtonReceiver.Companion.buildMediaButtonPendingIntent import tm.alashow.datmusic.playback.services.PlayerService const val NOTIFICATION_ID = 2000 const val CHANNEL_ID = "audio-player" const val PREVIOUS = "action_previous" const val NEXT = "action_next" const val STOP_PLAYBACK = "action_stop" const val PLAY_PAUSE = "action_play_or_pause" const val REPEAT_ONE = "action_repeat_one" const val REPEAT_ALL = "action_repeat_all" const val PLAY_ALL_SHUFFLED = "action_play_all_shuffled" const val PLAY_NEXT = "action_play_next" const val REMOVE_QUEUE_ITEM_BY_POSITION = "action_remove_queue_item_by_position" const val REMOVE_QUEUE_ITEM_BY_ID = "action_remove_queue_item_by_id" const val UPDATE_QUEUE = "action_update_queue" const val SET_MEDIA_STATE = "action_set_media_state" const val PLAY_ACTION = "action_play" const val PAUSE_ACTION = "action_pause" const val SWAP_ACTION = "swap_action" const val BY_UI_KEY = "by_ui_key" interface MediaNotifications { fun updateNotification(mediaSession: MediaSessionCompat) fun buildNotification(mediaSession: MediaSessionCompat): Notification fun clearNotifications() } class MediaNotificationsImpl @Inject constructor( @ApplicationContext private val context: Context, ) : MediaNotifications { private val notificationManager: NotificationManager = context.systemService(Context.NOTIFICATION_SERVICE) override fun updateNotification(mediaSession: MediaSessionCompat) { if (!PlayerService.IS_FOREGROUND) return GlobalScope.launch { notificationManager.notify(NOTIFICATION_ID, buildNotification(mediaSession)) } } override fun buildNotification(mediaSession: MediaSessionCompat): Notification { if (mediaSession.controller.metadata == null || mediaSession.controller.playbackState == null) { return createEmptyNotification() } val albumName = mediaSession.controller.metadata.album val artistName = mediaSession.controller.metadata.artist val trackName = mediaSession.controller.metadata.title val artwork = mediaSession.controller.metadata.artwork val isPlaying = mediaSession.isPlaying() val isBuffering = mediaSession.isBuffering() val description = mediaSession.controller.metadata.displayDescription val pm: PackageManager = context.packageManager val nowPlayingIntent = pm.getLaunchIntentForPackage(context.packageName) val clickIntent = PendingIntent.getActivity(context, 0, nowPlayingIntent, FLAG_UPDATE_CURRENT or FLAG_MUTABLE) createNotificationChannel() val style = NotificationMediaCompat.MediaStyle() .setMediaSession(mediaSession.sessionToken) .setShowCancelButton(true) .setShowActionsInCompactView(0, 1, 2) .setCancelButtonIntent(buildMediaButtonPendingIntent(context, ACTION_STOP)) val builder = NotificationCompat.Builder(context, CHANNEL_ID).apply { setStyle(style) setSmallIcon(R.drawable.ic_launcher_foreground) setLargeIcon(artwork) setContentIntent(clickIntent) setContentTitle(trackName) setContentText("$artistName - $albumName") setSubText(description) setColorized(true) setShowWhen(false) setVisibility(NotificationCompat.VISIBILITY_PUBLIC) setDeleteIntent(buildMediaButtonPendingIntent(context, ACTION_STOP)) addAction(getPreviousAction(context)) if (isBuffering) addAction(getBufferingAction(context)) else addAction(getPlayPauseAction(context, if (isPlaying) R.drawable.ic_pause else R.drawable.ic_play_arrow)) addAction(getNextAction(context)) addAction(getStopAction(context)) } if (artwork != null) { builder.color = Palette.from(artwork) .generate() .getDominantColor(Color.parseColor("#16053D")) } return builder.build() } override fun clearNotifications() { notificationManager.cancel(NOTIFICATION_ID) } private fun getBufferingAction(context: Context): NotificationCompat.Action { return NotificationCompat.Action(R.drawable.ic_hourglass_empty, "", null) } private fun getStopAction(context: Context): NotificationCompat.Action { val actionIntent = Intent(context, PlayerService::class.java).apply { action = STOP_PLAYBACK } val pendingIntent = PendingIntent.getService(context, 0, actionIntent, FLAG_IMMUTABLE) return NotificationCompat.Action(R.drawable.ic_stop, "", pendingIntent) } private fun getPreviousAction(context: Context): NotificationCompat.Action { val actionIntent = Intent(context, PlayerService::class.java).apply { action = PREVIOUS } val pendingIntent = PendingIntent.getService(context, 0, actionIntent, FLAG_IMMUTABLE) return NotificationCompat.Action(R.drawable.ic_skip_previous, "", pendingIntent) } private fun getPlayPauseAction( context: Context, @DrawableRes playButtonResId: Int ): NotificationCompat.Action { val actionIntent = Intent(context, PlayerService::class.java).apply { action = PLAY_PAUSE } val pendingIntent = PendingIntent.getService(context, 0, actionIntent, FLAG_IMMUTABLE) return NotificationCompat.Action(playButtonResId, "", pendingIntent) } private fun getNextAction(context: Context): NotificationCompat.Action { val actionIntent = Intent(context, PlayerService::class.java).apply { action = NEXT } val pendingIntent = PendingIntent.getService(context, 0, actionIntent, FLAG_IMMUTABLE) return NotificationCompat.Action(R.drawable.ic_skip_next, "", pendingIntent) } private fun createEmptyNotification(): Notification { createNotificationChannel() return NotificationCompat.Builder(context, CHANNEL_ID).apply { setSmallIcon(R.drawable.ic_launcher_foreground) setContentTitle(context.getString(R.string.app_name)) setColorized(true) setShowWhen(false) setVisibility(NotificationCompat.VISIBILITY_PUBLIC) }.build() } private fun createNotificationChannel() { if (!isOreo()) return val name = context.getString(R.string.app_name) val channel = NotificationChannel(CHANNEL_ID, name, IMPORTANCE_LOW).apply { description = context.getString(R.string.app_name) setShowBadge(false) lockscreenVisibility = Notification.VISIBILITY_PUBLIC } notificationManager.createNotificationChannel(channel) } }
apache-2.0
5e2fdc873e28c5e936f0457a67a3f54f
41.919355
120
0.727296
4.797476
false
false
false
false
alashow/music-android
modules/ui-search/src/main/java/tm/alashow/datmusic/ui/search/CaptchaErrorDialog.kt
1
6645
/* * Copyright (C) 2021, Alashov Berkeli * All rights reserved. */ package tm.alashow.datmusic.ui.search import androidx.compose.animation.core.animateFloatAsState import androidx.compose.animation.core.tween import androidx.compose.foundation.Image import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.aspectRatio import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.width import androidx.compose.material.Icon import androidx.compose.material.IconButton import androidx.compose.material.MaterialTheme import androidx.compose.material.OutlinedTextField import androidx.compose.material.Surface import androidx.compose.material.Text import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.Refresh import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.ExperimentalComposeUiApi import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.graphics.graphicsLayer import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.input.TextFieldValue import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import androidx.compose.ui.window.Dialog import androidx.compose.ui.window.DialogProperties import androidx.core.net.toUri import coil.compose.ImagePainter import coil.compose.rememberImagePainter import com.google.accompanist.placeholder.material.placeholder import com.google.accompanist.placeholder.material.shimmer import com.google.firebase.analytics.FirebaseAnalytics import kotlin.random.Random import tm.alashow.base.imageloading.ImageLoading import tm.alashow.base.util.event import tm.alashow.common.compose.LocalAnalytics import tm.alashow.domain.models.errors.ApiCaptchaError import tm.alashow.ui.components.TextRoundedButton import tm.alashow.ui.components.shimmer import tm.alashow.ui.theme.AppTheme import tm.alashow.ui.theme.outlinedTextFieldColors const val MAX_KEY_LENGTH = 20 @OptIn(ExperimentalComposeUiApi::class) @Composable internal fun CaptchaErrorDialog( captchaErrorShown: Boolean, setCaptchaErrorShown: (Boolean) -> Unit, captchaError: ApiCaptchaError, analytics: FirebaseAnalytics = LocalAnalytics.current, onCaptchaSubmit: (String) -> Unit, ) { var captchaVersion by remember(captchaError) { mutableStateOf(Random.nextInt()) } val (captchaKey, setCaptchaKey) = remember(captchaError) { mutableStateOf(TextFieldValue()) } if (captchaErrorShown) { Dialog( onDismissRequest = { setCaptchaErrorShown(false) }, properties = DialogProperties(usePlatformDefaultWidth = true), ) { val imageUri = captchaError.error.captchaImageUrl.toUri().buildUpon().appendQueryParameter("v", captchaVersion.toString()).build() val image = rememberImagePainter(imageUri, builder = ImageLoading.defaultConfig) Surface( shape = MaterialTheme.shapes.medium, elevation = 2.dp, ) { Column( verticalArrangement = Arrangement.spacedBy(AppTheme.specs.padding), horizontalAlignment = Alignment.CenterHorizontally, modifier = Modifier .fillMaxWidth() .padding(AppTheme.specs.padding), ) { Text( text = stringResource(R.string.captcha_title), style = MaterialTheme.typography.h6, modifier = Modifier.align(Alignment.Start) ) CaptchaErrorImage(image, onReload = { captchaVersion = Random.nextInt() }) OutlinedTextField( value = captchaKey, onValueChange = { if (it.text.length <= MAX_KEY_LENGTH) setCaptchaKey(it) }, singleLine = true, maxLines = 1, placeholder = { Text(stringResource(R.string.captcha_hint), style = MaterialTheme.typography.body1.copy(fontSize = 14.sp)) }, textStyle = MaterialTheme.typography.body1.copy(fontSize = 14.sp), colors = outlinedTextFieldColors(), modifier = Modifier.height(50.dp) ) TextRoundedButton( text = stringResource(R.string.captcha_submit), enabled = captchaKey.text.isNotBlank(), onClick = { setCaptchaErrorShown(false) analytics.event("captcha.submit", mapOf("key" to captchaKey)) onCaptchaSubmit(captchaKey.text) }, modifier = Modifier.align(Alignment.End) ) } } } } } @Composable private fun CaptchaErrorImage( image: ImagePainter, onReload: () -> Unit, modifier: Modifier = Modifier ) { Box(modifier.fillMaxWidth()) { Image( painter = image, contentDescription = null, modifier = Modifier .padding(vertical = AppTheme.specs.paddingLarge) .width(130.dp) .clip(MaterialTheme.shapes.small) .aspectRatio(130f / 50f) // source captcha original ratio .align(Alignment.Center) .placeholder( visible = image.state is ImagePainter.State.Loading, highlight = shimmer(), ) ) var angle by remember { mutableStateOf(0f) } val rotation = animateFloatAsState(angle, tween(500)) IconButton( onClick = { angle += 360; onReload(); }, Modifier .graphicsLayer { rotationZ = rotation.value } .align(Alignment.CenterEnd) ) { Icon( tint = MaterialTheme.colors.secondary, imageVector = Icons.Default.Refresh, contentDescription = stringResource(R.string.captcha_reload) ) } } }
apache-2.0
e90f23d56301e625e938c4ed5322a137
39.766871
149
0.652069
4.966368
false
false
false
false
rock3r/detekt
detekt-rules/src/main/kotlin/io/gitlab/arturbosch/detekt/rules/exceptions/ReturnFromFinally.kt
1
2342
package io.gitlab.arturbosch.detekt.rules.exceptions import io.gitlab.arturbosch.detekt.api.CodeSmell import io.gitlab.arturbosch.detekt.api.Config import io.gitlab.arturbosch.detekt.api.Debt import io.gitlab.arturbosch.detekt.api.Entity import io.gitlab.arturbosch.detekt.api.Issue import io.gitlab.arturbosch.detekt.api.Rule import io.gitlab.arturbosch.detekt.api.Severity import org.jetbrains.kotlin.psi.KtFinallySection import org.jetbrains.kotlin.psi.KtNamedFunction import org.jetbrains.kotlin.psi.KtReturnExpression import org.jetbrains.kotlin.psi.psiUtil.collectDescendantsOfType import org.jetbrains.kotlin.psi.psiUtil.parents /** * Reports all `return` statements in `finally` blocks. * Using `return` statements in `finally` blocks can discard and hide exceptions that are thrown in the `try` block. * * <noncompliant> * fun foo() { * try { * throw MyException() * } finally { * return // prevents MyException from being propagated * } * } * </noncompliant> * * @configuration ignoreLabeled - ignores labeled return statements (default: `false`) */ class ReturnFromFinally(config: Config = Config.empty) : Rule(config) { override val issue = Issue("ReturnFromFinally", Severity.Defect, "Do not return within a finally statement. This can discard exceptions.", Debt.TWENTY_MINS) private val ignoreLabeled = valueOrDefault(IGNORE_LABELED, false) override fun visitFinallySection(finallySection: KtFinallySection) { val innerFunctions = finallySection.finalExpression .collectDescendantsOfType<KtNamedFunction>() finallySection.finalExpression .collectDescendantsOfType<KtReturnExpression> { isNotInInnerFunction(it, innerFunctions) && canFilterLabeledExpression(it) } .forEach { report(CodeSmell(issue, Entity.from(it), issue.description)) } } private fun isNotInInnerFunction( returnStmts: KtReturnExpression, childFunctions: Collection<KtNamedFunction> ): Boolean = !returnStmts.parents.any { childFunctions.contains(it) } private fun canFilterLabeledExpression( returnStmt: KtReturnExpression ): Boolean = !ignoreLabeled || returnStmt.labeledExpression == null companion object { const val IGNORE_LABELED = "ignoreLabeled" } }
apache-2.0
405eaad4b29d402b53c5923c341d9215
38.033333
116
0.738258
4.565302
false
true
false
false
ankidroid/Anki-Android
AnkiDroid/src/main/java/com/ichi2/anki/dialogs/DeckPickerConfirmDeleteDeckDialog.kt
1
2956
/**************************************************************************************** * Copyright (c) 2015 Timothy Rae <[email protected]> * * * * This program is free software; you can redistribute it and/or modify it under * * the terms of the GNU General Public License as published by the Free Software * * Foundation; either version 3 of the License, or (at your option) any later * * version. * * * * This program is distributed in the hope that it will be useful, but WITHOUT ANY * * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A * * PARTICULAR PURPOSE. See the GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License along with * * this program. If not, see <http://www.gnu.org/licenses/>. * ****************************************************************************************/ package com.ichi2.anki.dialogs import android.app.Dialog import android.os.Bundle import com.afollestad.materialdialogs.MaterialDialog import com.ichi2.anki.DeckPicker import com.ichi2.anki.R import com.ichi2.anki.analytics.AnalyticsDialogFragment import com.ichi2.libanki.DeckId import com.ichi2.utils.BundleUtils.requireLong import com.ichi2.utils.iconAttr class DeckPickerConfirmDeleteDeckDialog : AnalyticsDialogFragment() { val deckId get() = requireArguments().requireLong("deckId") override fun onCreateDialog(savedInstanceState: Bundle?): Dialog { super.onCreate(savedInstanceState) return MaterialDialog(requireActivity()).show { title(R.string.delete_deck_title) message(text = requireArguments().getString("dialogMessage")!!) iconAttr(R.attr.dialogErrorIcon) positiveButton(R.string.dialog_positive_delete) { (activity as DeckPicker).deleteDeck(deckId) (activity as DeckPicker).dismissAllDialogFragments() } negativeButton(R.string.dialog_cancel) { (activity as DeckPicker).dismissAllDialogFragments() } cancelable(true) } } companion object { fun newInstance(dialogMessage: String?, deckId: DeckId): DeckPickerConfirmDeleteDeckDialog { val f = DeckPickerConfirmDeleteDeckDialog() val args = Bundle() args.putString("dialogMessage", dialogMessage) args.putLong("deckId", deckId) f.arguments = args return f } } }
gpl-3.0
68c34ed5142e4fc091c9e964eebf5180
49.101695
100
0.547361
5.673704
false
false
false
false
nosix/vue-kotlin
guide/events_/main/Events.kt
1
2863
import org.musyozoku.vuekt.* import org.w3c.dom.Element import org.w3c.dom.events.Event // var example1 = new Vue({ // el: '#example-1', // data: { // counter: 0 // } // }) @JsModule(vue.MODULE) @JsNonModule @JsName(vue.CLASS) external class Example1Vue(options: ComponentOptions<Example1Vue>) : Vue { var counter: Int } val example1 = Example1Vue(ComponentOptions { el = ElementConfig("#example-1") data = Data(json = json { counter = 0 }) }) // var example2 = new Vue({ // el: '#example-2', // data: { // name: 'Vue.js' // }, // // define methods under the `methods` object // // `methods` オブジェクトの下にメソッドを定義する // methods: { // greet: function (event) { // // `this` inside methods points to the Vue instance // // メソッド内の `this` は、 Vue インスタンスを参照します // alert('Hello ' + this.name + '!') // // `event` is the native DOM event // // `event` は、ネイティブ DOM イベントです // if (event) { // alert(event.target.tagName) // } // } // } // }) //// JavaScript からメソッドを呼び出すこともできます //example2.greet() // => 'Hello Vue.js!' @JsModule(vue.MODULE) @JsNonModule @JsName(vue.CLASS) external class Example2Vue(options: ComponentOptions<Example2Vue>) : Vue { var name: String } external fun alert(message: String) val example2 = Example2Vue(ComponentOptions { el = ElementConfig("#example-2") data = Data(json = json { name = "Vue.js" }) methods = json { this["greet"] = { event: Event? -> val self = thisAs<Example2Vue>() alert("Hello ${self.name}!") event?.let { alert((it.target as Element).tagName) } } } }) // new Vue({ // el: '#example-3', // methods: { // say: function (message) { // alert(message) // } // } // warn: function (message, event) { // // now we have access to the native event // // ネイティブイベントを参照しています // if (event) event.preventDefault() // alert(message) // } // }) val example3 = Vue(ComponentOptions { el = ElementConfig("#example-3") methods = json { this["say"] = { message: String -> alert(message) } this["warn"] = { message: String, event: Event? -> event?.preventDefault() alert(message) } } }) // // enable v-on:keyup.f1 // Vue.config.keyCodes.f1 = 112 val example4 = Vue(ComponentOptions { el = ElementConfig("#example-4") methods = json { this["submit"] = { alert("submit") } } }) fun main(args: Array<String>) { Vue.config.keyCodes["f1"] = 112 }
apache-2.0
3d0ebeb6043d18bb86559fa28e57bf1a
22.206897
74
0.546637
3.192171
false
true
false
false
DigitalPhantom/PhantomWeatherAndroid
app/src/main/java/net/digitalphantom/app/weatherapp/data/Item.kt
1
2344
/** * The MIT License (MIT) * * Copyright (c) 2015 - 2022 Yoel Nunez <[email protected]> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * */ package net.digitalphantom.app.weatherapp.data import org.json.JSONObject import org.json.JSONArray import org.json.JSONException class Item : JSONPopulator { var condition: Condition? = null var forecast: List<Condition>? = null override fun populate(data: JSONObject?) { condition = Condition().apply { populate(data?.optJSONObject("condition")) } forecast = mutableListOf<Condition>().apply { val forecastData = data?.optJSONArray("forecast") val forecastCount = forecastData?.length() ?: 0 for (i in 0 until forecastCount) { try { add(Condition().apply { populate(forecastData?.getJSONObject(i)) }) } catch (e: JSONException) { e.printStackTrace() } } }.toList() } override fun toJSON(): JSONObject { val data = JSONObject() try { data.put("condition", condition?.toJSON()) data.put("forecast", JSONArray(forecast)) } catch (e: JSONException) { e.printStackTrace() } return data } }
mit
e12bc7e437f69bfd6539972f1c43ee1e
35.076923
87
0.65785
4.632411
false
false
false
false
shkschneider/android_Skeleton
core/src/main/kotlin/me/shkschneider/skeleton/helper/KeyboardHelper.kt
1
3272
package me.shkschneider.skeleton.helper import android.app.Activity import android.content.res.Configuration import android.graphics.Rect import android.view.KeyEvent import android.view.ViewTreeObserver import android.view.Window import android.view.WindowManager import android.view.inputmethod.EditorInfo import android.widget.EditText import android.widget.TextView import me.shkschneider.skeleton.SkeletonReceiver import me.shkschneider.skeleton.helperx.Logger import me.shkschneider.skeleton.helperx.Metrics import me.shkschneider.skeleton.ui.ViewHelper object KeyboardHelper { fun has(): Boolean { return ApplicationHelper.resources().configuration.keyboard != Configuration.KEYBOARD_NOKEYS } fun show(window: Window) { Logger.verbose("SOFT_INPUT_STATE_ALWAYS_VISIBLE") if (has()) { window.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE) } } fun hide(window: Window) { Logger.verbose("SOFT_INPUT_STATE_ALWAYS_HIDDEN") if (has()) { window.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN) } } fun keyboardCallback(editText: EditText, skeletonReceiver: SkeletonReceiver?, all: Boolean = false): Boolean { skeletonReceiver ?: run { editText.setOnEditorActionListener(null) return false } @Suppress("UNUSED_ANONYMOUS_PARAMETER") editText.setOnEditorActionListener(TextView.OnEditorActionListener { textView, actionId, keyEvent -> if (all) { skeletonReceiver.post(KeyboardHelper::class.java.simpleName, actionId) return@OnEditorActionListener false } when (actionId) { EditorInfo.IME_NULL -> return@OnEditorActionListener false EditorInfo.IME_ACTION_DONE, EditorInfo.IME_ACTION_GO, EditorInfo.IME_ACTION_SEARCH, EditorInfo.IME_ACTION_SEND, KeyEvent.KEYCODE_DPAD_CENTER, KeyEvent.KEYCODE_ENTER -> skeletonReceiver.post((KeyboardHelper::class.java.simpleName), actionId) } false }) return true } // <https://github.com/yshrsmz/KeyboardVisibilityEvent> fun keyboardListener(activity: Activity, listener: Listener) { val root = ViewHelper.children(ViewHelper.content(activity))[0] root.viewTreeObserver.addOnGlobalLayoutListener(object: ViewTreeObserver.OnGlobalLayoutListener { private val rect = Rect() private val visibleThreshold = Math.round(Metrics.pixelsFromDp(1.toFloat()).toFloat()) private var wasOpened = false override fun onGlobalLayout() { root.getWindowVisibleDisplayFrame(rect) val heightDiff = root.rootView.height - rect.height() val isOpen = heightDiff > visibleThreshold if (isOpen == wasOpened) { return } wasOpened = isOpen listener.onKeyboardVisibilityChanged(isOpen) } }) } interface Listener { fun onKeyboardVisibilityChanged(isOpen: Boolean) } }
apache-2.0
d8c1bee4d704fda03a1e36ae7a1e1494
34.182796
114
0.656479
5.080745
false
false
false
false
cfig/Nexus_boot_image_editor
helper/src/test/kotlin/cfig/io/Struct3Test.kt
1
16854
// Copyright 2021 [email protected] // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import cfig.helper.Helper import cfig.io.Struct3 import com.fasterxml.jackson.databind.ObjectMapper import org.junit.Assert import org.junit.Test import java.io.ByteArrayInputStream class Struct3Test { private fun getConvertedFormats(inStruct: Struct3): ArrayList<Map<String, Int>> { val f = inStruct.javaClass.getDeclaredField("formats") f.isAccessible = true val formatDumps = arrayListOf<Map<String, Int>>() (f.get(inStruct) as ArrayList<*>).apply { this.forEach { @Suppress("UNCHECKED_CAST") val format = it as Array<Any> val k = if (format[0].toString().indexOf(" ") > 0) { format[0].toString().split(" ")[1] } else { format[0].toString() } formatDumps.add(mapOf(k to (format[1] as Int))) } } return formatDumps } private fun constructorTestFun1(inFormatString: String) { println(ObjectMapper().writeValueAsString(getConvertedFormats(Struct3(inFormatString)))) } @Test fun constructorTest() { constructorTestFun1("3s") constructorTestFun1("5b") constructorTestFun1("5x") constructorTestFun1("2c") } @Test fun calcSizeTest() { Assert.assertEquals(3, Struct3("3s").calcSize()) Assert.assertEquals(5, Struct3("5b").calcSize()) Assert.assertEquals(5, Struct3("5x").calcSize()) Assert.assertEquals(9, Struct3("9c").calcSize()) } @Test fun toStringTest() { println(Struct3("!4s2L2QL11QL4x47sx80x")) } //x @Test fun paddingTest() { Assert.assertEquals("0000000000", Helper.toHexString(Struct3("5x").pack(null))) Assert.assertEquals("0000000000", Helper.toHexString(Struct3("5x").pack(0))) Assert.assertEquals("0101010101", Helper.toHexString(Struct3("5x").pack(1))) Assert.assertEquals("1212121212", Helper.toHexString(Struct3("5x").pack(0x12))) //Integer高位被截掉 Assert.assertEquals("2323232323", Helper.toHexString(Struct3("5x").pack(0x123))) // minus 0001_0011 -> 补码 1110 1101,ie. 0xed Assert.assertEquals("ededededed", Helper.toHexString(Struct3("5x").pack(-0x13))) //0xff Assert.assertEquals("ffffffffff", Helper.toHexString(Struct3("5x").pack(-1))) try { Struct3("5x").pack("bad") Assert.assertTrue("should throw exception here", false) } catch (e: IllegalArgumentException) { } //unpack Struct3("3x").unpack(ByteArrayInputStream(Helper.fromHexString("000000"))).let { Assert.assertEquals(1, it.size) Assert.assertEquals(0.toByte(), it[0]) } Struct3("x2xx").unpack(ByteArrayInputStream(Helper.fromHexString("01121210"))).let { Assert.assertEquals(3, it.size) Assert.assertEquals(0x1.toByte(), it[0]) Assert.assertEquals(0x12.toByte(), it[1]) Assert.assertEquals(0x10.toByte(), it[2]) } } //c @Test fun characterTest() { //constructor Struct3("c") //calcSize Assert.assertEquals(3, Struct3("3c").calcSize()) //pack illegal try { Struct3("c").pack("a") Assert.fail("should throw exception here") } catch (e: Throwable) { Assert.assertTrue(e is AssertionError || e is IllegalArgumentException) } //pack legal Assert.assertEquals("61", Helper.toHexString(Struct3("!c").pack('a'))) Assert.assertEquals("61", Helper.toHexString(Struct3("c").pack('a'))) Assert.assertEquals("616263", Helper.toHexString(Struct3("3c").pack('a', 'b', 'c'))) //unpack Struct3("3c").unpack(ByteArrayInputStream(Helper.fromHexString("616263"))).let { Assert.assertEquals(3, it.size) Assert.assertEquals('a', it[0]) Assert.assertEquals('b', it[1]) Assert.assertEquals('c', it[2]) } } //b @Test fun bytesTest() { //constructor Struct3("b") //calcSize Assert.assertEquals(3, Struct3("3b").calcSize()) //pack Assert.assertEquals("123456", Helper.toHexString( Struct3("3b").pack(byteArrayOf(0x12, 0x34, 0x56)))) Assert.assertEquals("123456", Helper.toHexString( Struct3("!3b").pack(byteArrayOf(0x12, 0x34, 0x56)))) Assert.assertEquals("123400", Helper.toHexString( Struct3("3b").pack(byteArrayOf(0x12, 0x34)))) //unpack Struct3("3b").unpack(ByteArrayInputStream(Helper.fromHexString("123400"))).let { Assert.assertEquals(1, it.size) Assert.assertEquals("123400", Helper.toHexString(it[0] as ByteArray)) } Struct3("bbb").unpack(ByteArrayInputStream(Helper.fromHexString("123400"))).let { Assert.assertEquals(3, it.size) Assert.assertEquals("12", Helper.toHexString(it[0] as ByteArray)) Assert.assertEquals("34", Helper.toHexString(it[1] as ByteArray)) Assert.assertEquals("00", Helper.toHexString(it[2] as ByteArray)) } } //B: UByte array @Test fun uBytesTest() { //constructor Struct3("B") //calcSize Assert.assertEquals(3, Struct3("3B").calcSize()) //pack Assert.assertEquals("123456", Helper.toHexString( Struct3("3B").pack(byteArrayOf(0x12, 0x34, 0x56)))) Assert.assertEquals("123456", Helper.toHexString( Struct3("!3B").pack(byteArrayOf(0x12, 0x34, 0x56)))) Assert.assertEquals("123400", Helper.toHexString( Struct3("3B").pack(byteArrayOf(0x12, 0x34)))) //unpack Struct3("3B").unpack(ByteArrayInputStream(Helper.fromHexString("123400"))).let { Assert.assertEquals(1, it.size) Assert.assertEquals("123400", Helper.toHexString(it[0] as UByteArray)) } Struct3("BBB").unpack(ByteArrayInputStream(Helper.fromHexString("123400"))).let { Assert.assertEquals(3, it.size) Assert.assertEquals("12", Helper.toHexString(it[0] as UByteArray)) Assert.assertEquals("34", Helper.toHexString(it[1] as UByteArray)) Assert.assertEquals("00", Helper.toHexString(it[2] as UByteArray)) } } //s @Test fun stringTest() { //constructor Struct3("s") //calcSize Assert.assertEquals(3, Struct3("3s").calcSize()) //pack Struct3("3s").pack("a") Struct3("3s").pack("abc") try { Struct3("3s").pack("abcd") Assert.fail("should throw exception here") } catch (e: Throwable) { Assert.assertTrue(e.toString(), e is AssertionError || e is IllegalArgumentException) } //unpack Struct3("3s").unpack(ByteArrayInputStream(Helper.fromHexString("616263"))).let { Assert.assertEquals(1, it.size) Assert.assertEquals("abc", it[0]) } Struct3("3s").unpack(ByteArrayInputStream(Helper.fromHexString("610000"))).let { Assert.assertEquals(1, it.size) Assert.assertEquals("a", it[0]) } } //h @Test fun shortTest() { //constructor Struct3("h") //calcSize Assert.assertEquals(6, Struct3("3h").calcSize()) //pack Assert.assertEquals("ff7f", Helper.toHexString(Struct3("h").pack(0x7fff))) Assert.assertEquals("0080", Helper.toHexString(Struct3("h").pack(-0x8000))) Assert.assertEquals("7fff0000", Helper.toHexString(Struct3(">2h").pack(0x7fff, 0))) //unpack Struct3(">2h").unpack(ByteArrayInputStream(Helper.fromHexString("7fff0000"))).let { Assert.assertEquals(2, it.size) Assert.assertEquals(0x7fff.toShort(), it[0]) Assert.assertEquals(0.toShort(), it[1]) } } //H @Test fun uShortTest() { //constructor Struct3("H") //calcSize Assert.assertEquals(6, Struct3("3H").calcSize()) //pack Assert.assertEquals("0100", Helper.toHexString(Struct3("H").pack((1U).toUShort()))) Assert.assertEquals("0100", Helper.toHexString(Struct3("H").pack(1U))) Assert.assertEquals("ffff", Helper.toHexString(Struct3("H").pack(65535U))) Assert.assertEquals("ffff", Helper.toHexString(Struct3("H").pack(65535))) try { Struct3("H").pack(-1) Assert.fail("should throw exception here") } catch (e: Throwable) { Assert.assertTrue(e is AssertionError || e is IllegalArgumentException) } //unpack Struct3("H").unpack(ByteArrayInputStream(Helper.fromHexString("ffff"))).let { Assert.assertEquals(1, it.size) Assert.assertEquals(65535U.toUShort(), it[0]) } } //i, l @Test fun intTest() { //constructor Struct3("i") Struct3("l") //calcSize Assert.assertEquals(12, Struct3("3i").calcSize()) Assert.assertEquals(12, Struct3("3l").calcSize()) //pack Struct3("i").pack(65535 + 1) Struct3("i").pack(-1) //unpack Struct3("i").unpack(ByteArrayInputStream(Helper.fromHexString("00000100"))).let { Assert.assertEquals(1, it.size) Assert.assertEquals(65536, it[0]) } Struct3("i").unpack(ByteArrayInputStream(Helper.fromHexString("ffffffff"))).let { Assert.assertEquals(1, it.size) Assert.assertEquals(-1, it[0]) } } //I, L @Test fun uIntTest() { //constructor Struct3("I") Struct3("L") //calcSize Assert.assertEquals(12, Struct3("3I").calcSize()) Assert.assertEquals(12, Struct3("3L").calcSize()) //pack Assert.assertEquals("01000000", Helper.toHexString( Struct3("I").pack(1U))) Assert.assertEquals("80000000", Helper.toHexString( Struct3(">I").pack(Int.MAX_VALUE.toUInt() + 1U))) //unpack Struct3("I").unpack(ByteArrayInputStream(Helper.fromHexString("01000000"))).let { Assert.assertEquals(1, it.size) Assert.assertEquals(1U, it[0]) } Struct3(">I").unpack(ByteArrayInputStream(Helper.fromHexString("80000000"))).let { Assert.assertEquals(1, it.size) Assert.assertEquals(Int.MAX_VALUE.toUInt() + 1U, it[0]) } } //q: Long @Test fun longTest() { //constructor Struct3("q") //calcSize Assert.assertEquals(24, Struct3("3q").calcSize()) //pack Assert.assertEquals("8000000000000000", Helper.toHexString( Struct3(">q").pack(Long.MIN_VALUE))) Assert.assertEquals("7fffffffffffffff", Helper.toHexString( Struct3(">q").pack(Long.MAX_VALUE))) Assert.assertEquals("ffffffffffffffff", Helper.toHexString( Struct3(">q").pack(-1L))) //unpack Struct3(">q").unpack(ByteArrayInputStream(Helper.fromHexString("8000000000000000"))).let { Assert.assertEquals(1, it.size) Assert.assertEquals(Long.MIN_VALUE, it[0]) } Struct3(">q").unpack(ByteArrayInputStream(Helper.fromHexString("7fffffffffffffff"))).let { Assert.assertEquals(1, it.size) Assert.assertEquals(Long.MAX_VALUE, it[0]) } Struct3(">q").unpack(ByteArrayInputStream(Helper.fromHexString("ffffffffffffffff"))).let { Assert.assertEquals(1, it.size) Assert.assertEquals(-1L, it[0]) } } //Q: ULong @Test fun uLongTest() { //constructor Struct3("Q") //calcSize Assert.assertEquals(24, Struct3("3Q").calcSize()) //pack Assert.assertEquals("7fffffffffffffff", Helper.toHexString( Struct3(">Q").pack(Long.MAX_VALUE))) Assert.assertEquals("0000000000000000", Helper.toHexString( Struct3(">Q").pack(ULong.MIN_VALUE))) Assert.assertEquals("ffffffffffffffff", Helper.toHexString( Struct3(">Q").pack(ULong.MAX_VALUE))) try { Struct3(">Q").pack(-1L) } catch (e: Throwable) { Assert.assertTrue(e is AssertionError || e is IllegalArgumentException) } //unpack Struct3(">Q").unpack(ByteArrayInputStream(Helper.fromHexString("7fffffffffffffff"))).let { Assert.assertEquals(1, it.size) Assert.assertEquals(Long.MAX_VALUE.toULong(), it[0]) } Struct3(">Q").unpack(ByteArrayInputStream(Helper.fromHexString("0000000000000000"))).let { Assert.assertEquals(1, it.size) Assert.assertEquals(ULong.MIN_VALUE, it[0]) } Struct3(">Q").unpack(ByteArrayInputStream(Helper.fromHexString("ffffffffffffffff"))).let { Assert.assertEquals(1, it.size) Assert.assertEquals(ULong.MAX_VALUE, it[0]) } } @Test fun legacyTest() { Assert.assertTrue(Struct3("<2i4b4b").pack( 1, 7321, byteArrayOf(1, 2, 3, 4), byteArrayOf(200.toByte(), 201.toByte(), 202.toByte(), 203.toByte())) .contentEquals(Helper.fromHexString("01000000991c000001020304c8c9cacb"))) Assert.assertTrue(Struct3("<2i4b4B").pack( 1, 7321, byteArrayOf(1, 2, 3, 4), intArrayOf(200, 201, 202, 203)) .contentEquals(Helper.fromHexString("01000000991c000001020304c8c9cacb"))) Assert.assertTrue(Struct3("b2x").pack(byteArrayOf(0x13), null).contentEquals(Helper.fromHexString("130000"))) Assert.assertTrue(Struct3("b2xi").pack(byteArrayOf(0x13), null, 55).contentEquals(Helper.fromHexString("13000037000000"))) Struct3("5s").pack("Good").contentEquals(Helper.fromHexString("476f6f6400")) Struct3("5s1b").pack("Good", byteArrayOf(13)).contentEquals(Helper.fromHexString("476f6f64000d")) } @Test fun legacyIntegerLE() { //int (4B) Assert.assertTrue(Struct3("<2i").pack(1, 7321).contentEquals(Helper.fromHexString("01000000991c0000"))) val ret = Struct3("<2i").unpack(ByteArrayInputStream(Helper.fromHexString("01000000991c0000"))) Assert.assertEquals(2, ret.size) Assert.assertTrue(ret[0] is Int) Assert.assertTrue(ret[1] is Int) Assert.assertEquals(1, ret[0] as Int) Assert.assertEquals(7321, ret[1] as Int) //unsigned int (4B) Assert.assertTrue(Struct3("<I").pack(2L).contentEquals(Helper.fromHexString("02000000"))) Assert.assertTrue(Struct3("<I").pack(2).contentEquals(Helper.fromHexString("02000000"))) //greater than Int.MAX_VALUE Assert.assertTrue(Struct3("<I").pack(2147483748L).contentEquals(Helper.fromHexString("64000080"))) Assert.assertTrue(Struct3("<I").pack(2147483748).contentEquals(Helper.fromHexString("64000080"))) try { Struct3("<I").pack(-12) throw Exception("should not reach here") } catch (e: Throwable) { Assert.assertTrue(e is AssertionError || e is IllegalArgumentException) } //negative int Assert.assertTrue(Struct3("<i").pack(-333).contentEquals(Helper.fromHexString("b3feffff"))) } @Test fun legacyIntegerBE() { run { Assert.assertTrue(Struct3(">2i").pack(1, 7321).contentEquals(Helper.fromHexString("0000000100001c99"))) val ret = Struct3(">2i").unpack(ByteArrayInputStream(Helper.fromHexString("0000000100001c99"))) Assert.assertEquals(1, ret[0] as Int) Assert.assertEquals(7321, ret[1] as Int) } run { Assert.assertTrue(Struct3("!i").pack(-333).contentEquals(Helper.fromHexString("fffffeb3"))) val ret2 = Struct3("!i").unpack(ByteArrayInputStream(Helper.fromHexString("fffffeb3"))) Assert.assertEquals(-333, ret2[0] as Int) } } }
apache-2.0
b7dd43e995c152c1957e3d3050dc9691
36.252212
130
0.597696
4.078973
false
true
false
false
bpark/companion-classification-micro
src/main/kotlin/com/github/bpark/companion/classifier/TextClassifier.kt
1
2433
/* * Copyright 2017 bpark * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.bpark.companion.classifier import mu.KotlinLogging import weka.classifiers.meta.FilteredClassifier import weka.core.Attribute import weka.core.DenseInstance import weka.core.Instances import weka.core.SerializationHelper import java.util.* class TextClassifier(location: String, private val classes: List<String>) : PhraseClassifier() { companion object { private const val ATTR_CLASS = "class" private const val ATTR_TEXT = "text" } private val logger = KotlinLogging.logger {} private var classifier = SerializationHelper.read(this.javaClass.getResourceAsStream(location)) as FilteredClassifier override fun classify(attributes: List<String>): Map<String, Double> { val instances = buildInstances(attributes.first()) return classify(instances) } private fun buildInstances(text: String): Instances { val attributes = arrayListOf( Attribute(ATTR_CLASS, classes), Attribute(ATTR_TEXT, null as List<String>?) ) val instances = Instances("Test relation", attributes, 1) instances.setClassIndex(0) val instance = DenseInstance(2) instance.setValue(attributes.last(), text) instances.add(instance) return instances } private fun classify(instances: Instances): Map<String, Double> { val distributionMap = HashMap<String, Double>() val distributions = classifier.distributionForInstance(instances.instance(0)) for (i in distributions.indices) { val classValue = instances.classAttribute().value(i) val distribution = distributions[i] distributionMap.put(classValue, distribution) } logger.info { "distribution: $distributionMap" } return distributionMap } }
apache-2.0
364f7708b9816904d1140f0246659f75
29.810127
121
0.697493
4.564728
false
false
false
false
jensim/kotlin-koans
src/i_introduction/_4_Lambdas/Lambdas.kt
1
698
package i_introduction._4_Lambdas import util.TODO import util.doc4 fun example() { val sum = { x: Int, y: Int -> x + y } val square: (Int) -> Int = { x -> x * x } sum(1, square(2)) == 5 } fun todoTask4(collection: Collection<Int>): Nothing = TODO( """ Task 4. Rewrite 'JavaCode4.task4()' in Kotlin using lambdas. You can find the appropriate function to call on 'collection' through IntelliJ IDEA's code completion feature. (Don't use the class 'Iterables'). """, documentation = doc4(), references = { JavaCode4().task4(collection) }) fun task4(collection: Collection<Int>): Boolean = collection.find { x -> x % 42 == 0 } != null
mit
cd843349fe8e3541a3c63f46122bc0ba
28.083333
118
0.617479
3.673684
false
false
false
false
android/topeka
quiz/src/main/java/com/google/samples/apps/topeka/widget/fab/CheckableFab.kt
1
1847
/* * Copyright 2017 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.samples.apps.topeka.widget.fab import android.content.Context import com.google.android.material.floatingactionbutton.FloatingActionButton import android.util.AttributeSet import android.view.View import android.widget.Checkable import com.google.samples.apps.topeka.quiz.R /** * A [FloatingActionButton] that implements [Checkable] to allow display of different * icons in it's states. */ class CheckableFab( context: Context, attrs: AttributeSet? = null ) : FloatingActionButton(context, attrs), Checkable { private var _checked = true private val attrs = intArrayOf(android.R.attr.state_checked) init { setImageResource(R.drawable.answer_quiz_fab) } override fun onCreateDrawableState(extraSpace: Int): IntArray { val drawableState = super.onCreateDrawableState(1 + extraSpace) if (_checked) { View.mergeDrawableStates(drawableState, attrs) } return drawableState } override fun setChecked(checked: Boolean) { if (_checked == checked) return _checked = checked refreshDrawableState() } override fun isChecked() = _checked override fun toggle() { _checked = !_checked } }
apache-2.0
36a808d30aa0078f7bb3f0777b848298
27.859375
85
0.707093
4.397619
false
false
false
false
adityaDave2017/my-vocab
app/src/main/java/com/android/vocab/activity/WordDetailActivity.kt
1
6506
package com.android.vocab.activity import android.content.ContentUris import android.content.Intent import android.databinding.DataBindingUtil import android.os.Bundle import android.support.v7.app.AppCompatActivity import android.support.v7.widget.Toolbar import android.util.Log import android.view.Menu import android.view.MenuItem import com.android.vocab.R import com.android.vocab.adapter.ShowListAdapter import com.android.vocab.databinding.ActivityWordDetailBinding import com.android.vocab.fragment.dialog.InputDialog import com.android.vocab.fragment.dialog.RecyclerViewDialog import com.android.vocab.provider.* import com.android.vocab.provider.bean.* @Suppress("unused") class WordDetailActivity : AppCompatActivity(), ShowListAdapter.OnButtonClicked, InputDialog.OnInputReceived, RecyclerViewDialog.OnItemSelected { private val LOG_TAG: String = WordDetailActivity::class.java.simpleName private lateinit var binding: ActivityWordDetailBinding private val sentenceList: ArrayList<Sentence?> = arrayListOf(null) private val synonymList: ArrayList<SynonymWord?> = arrayListOf(null) private val antonymList: ArrayList<AntonymWord?> = arrayListOf(null) private val SENTENCE_ADD_DIALOG_TAG: String = "SENTENCE_ADD_DIALOG_TAG" private val SYNONYM_ADD_DIALOG_TAG: String = "SYNONYM_ADD_DIALOG_TAG" private val ANTONYM_ADD_DIALOG_TAG: String = "ANTONYM_ADD_DIALOG_TAG" companion object { val WORD_TO_SHOW: String = "WORD_TO_SHOW" val SHOW_WORD_REQUEST:Int = 0 val CHANGE_OCCURRED_RESULT: Int = 1 } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = DataBindingUtil.setContentView(this, R.layout.activity_word_detail) val toolBar: Toolbar = findViewById(R.id.appBarWordDetail) as Toolbar setSupportActionBar(toolBar) supportActionBar?.setDisplayHomeAsUpEnabled(true) binding.word = intent.getParcelableExtra(WORD_TO_SHOW) binding.detailContent.rvSentenceContainer.adapter = ShowListAdapter(this@WordDetailActivity, ShowListAdapter.SupportedTypes.SENTENCE_TYPE, sentenceList) binding.detailContent.rvSynonymContainer.adapter = ShowListAdapter(this@WordDetailActivity, ShowListAdapter.SupportedTypes.SYNONYM_TYPE, synonymList) binding.detailContent.rvAntonymContainer.adapter = ShowListAdapter(this@WordDetailActivity, ShowListAdapter.SupportedTypes.ANTONYM_TYPE, antonymList) loadSentences() loadSynonyms() loadAntonyms() } override fun onCreateOptionsMenu(menu: Menu?): Boolean { menuInflater.inflate(R.menu.menu_word_detail, menu) return true } override fun onOptionsItemSelected(item: MenuItem?): Boolean { return when(item?.itemId) { R.id.miEdit -> { val intent: Intent = Intent(this@WordDetailActivity, WordEditorActivity::class.java) intent.putExtra(WordEditorActivity.WORD_TO_EDIT, binding.word) intent.putExtra(WordEditorActivity.PARENT_ACTIVITY_CLASS, WordDetailActivity::class.java.name) startActivityForResult(intent, WordEditorActivity.EDIT_REQUEST) true } else -> false } } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { if (resultCode == WordEditorActivity.CHANGE_OCCURRED_RESULT) { val list: ArrayList<WordAndType> = getWordsWithType(baseContext, binding.word.wordId) if (list.size == 0) { setResult(CHANGE_OCCURRED_RESULT) finish() } else { binding.word = list[0] } } } override fun onButtonClicked(type: ShowListAdapter.SupportedTypes) { when(type) { ShowListAdapter.SupportedTypes.SENTENCE_TYPE -> { val inputDialog: InputDialog = InputDialog() inputDialog.show(supportFragmentManager, SENTENCE_ADD_DIALOG_TAG) } ShowListAdapter.SupportedTypes.SYNONYM_TYPE -> { val wordSelect: RecyclerViewDialog = RecyclerViewDialog() val bundle: Bundle = Bundle() bundle.putString(RecyclerViewDialog.TYPE_OF_DATA, RecyclerViewDialog.SupportedTypes.SYNONYM.toString()) wordSelect.arguments = bundle wordSelect.show(supportFragmentManager, SYNONYM_ADD_DIALOG_TAG) } ShowListAdapter.SupportedTypes.ANTONYM_TYPE -> { val wordSelect: RecyclerViewDialog = RecyclerViewDialog() val bundle: Bundle = Bundle() bundle.putString(RecyclerViewDialog.TYPE_OF_DATA, RecyclerViewDialog.SupportedTypes.ANTONYM.toString()) wordSelect.arguments = bundle wordSelect.show(supportFragmentManager, ANTONYM_ADD_DIALOG_TAG) } } } override fun useInput(text: String) { insertSentence(baseContext, Sentence(wordId = binding.word.wordId, sentence = text)) loadSentences() } override fun processSelectedItem(type: RecyclerViewDialog.SupportedTypes, id: Long) { when(type) { RecyclerViewDialog.SupportedTypes.SYNONYM -> { insertSynonym(baseContext, Synonym(mainWordId = binding.word.wordId, synonymWordId = id)) loadSynonyms() } RecyclerViewDialog.SupportedTypes.ANTONYM -> { insertAntonym(baseContext, Antonym(mainWordId = binding.word.wordId, antonymWordId = id)) loadAntonyms() } } } fun loadSentences() { sentenceList.clear() sentenceList.addAll(0, getSentences(baseContext, binding.word.wordId)) sentenceList.add(null) binding.detailContent.rvSentenceContainer.adapter.notifyDataSetChanged() } fun loadSynonyms() { synonymList.clear() synonymList.addAll(0, getSynonyms(baseContext, binding.word.wordId)) synonymList.add(null) binding.detailContent.rvSynonymContainer.adapter.notifyDataSetChanged() } fun loadAntonyms() { antonymList.clear() antonymList.addAll(0, getAntonyms(baseContext, binding.word.wordId)) antonymList.add(null) binding.detailContent.rvAntonymContainer.adapter.notifyDataSetChanged() } }
mit
ad7cdd7eb2752d30b7ed16754a9aa30f
38.920245
160
0.679219
4.610914
false
false
false
false
world-federation-of-advertisers/cross-media-measurement
src/main/kotlin/org/wfanet/measurement/kingdom/deploy/gcloud/spanner/readers/OpenIdRequestParamsReader.kt
1
2038
// Copyright 2021 The Cross-Media Measurement Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package org.wfanet.measurement.kingdom.deploy.gcloud.spanner.readers import com.google.cloud.spanner.Struct import kotlinx.coroutines.flow.singleOrNull import org.wfanet.measurement.common.identity.ExternalId import org.wfanet.measurement.gcloud.spanner.AsyncDatabaseClient import org.wfanet.measurement.gcloud.spanner.appendClause class OpenIdRequestParamsReader : SpannerReader<OpenIdRequestParamsReader.Result>() { data class Result(val state: ExternalId, val nonce: ExternalId, val isExpired: Boolean) override val baseSql: String = """ SELECT ExternalOpenIdRequestParamsId, Nonce, CURRENT_TIMESTAMP > TIMESTAMP_ADD(CreateTime, INTERVAL ValidSeconds SECOND) AS IsExpired, FROM OpenIdRequestParams """ .trimIndent() override suspend fun translate(struct: Struct) = Result( state = ExternalId(struct.getLong("ExternalOpenIdRequestParamsId")), nonce = ExternalId(struct.getLong("Nonce")), isExpired = struct.getBoolean("IsExpired") ) suspend fun readByState( readContext: AsyncDatabaseClient.ReadContext, state: ExternalId, ): Result? { return fillStatementBuilder { appendClause( """ WHERE OpenIdRequestParams.ExternalOpenIdRequestParamsId = @state """ .trimIndent() ) bind("state").to(state.value) } .execute(readContext) .singleOrNull() } }
apache-2.0
99c256d59a675906d899acdd66014f02
33.542373
95
0.724239
4.600451
false
false
false
false
crunchersaspire/worshipsongs-android
app/src/main/java/org/worshipsongs/service/DatabaseService.kt
2
2082
package org.worshipsongs.service import android.content.Context import android.database.sqlite.SQLiteDatabase import org.apache.commons.lang3.StringUtils import org.worshipsongs.helper.DatabaseHelper import org.worshipsongs.utils.RegexUtils import java.io.IOException /** * @Author : Madasamy * @Version : 1.0 */ class DatabaseService { // private var database: SQLiteDatabase? = null //var database: SQLiteDatabase? = null private var databaseHelper: DatabaseHelper? = null val isDatabaseExist: Boolean get() = databaseHelper!!.checkDataBase() constructor() { //Do nothing } constructor(context: Context) { databaseHelper = DatabaseHelper(context) } var database: SQLiteDatabase? = null get() { return databaseHelper!!.openDataBase() } @Throws(IOException::class) fun copyDatabase(databasePath: String, dropDatabase: Boolean) { databaseHelper!!.createDataBase(databasePath, dropDatabase) } fun open() { database = databaseHelper!!.openDataBase() } fun close() { databaseHelper!!.close() } fun get(): SQLiteDatabase { if (database == null) { database = databaseHelper!!.openDataBase() } return database!! } fun parseTamilName(topicName: String): String { if (StringUtils.isNotBlank(topicName)) { val tamilTopicName = RegexUtils.getMatchString(topicName, TOPIC_NAME_REGEX) val formattedTopicName = tamilTopicName.replace("\\{".toRegex(), "").replace("\\}".toRegex(), "") return if (StringUtils.isNotBlank(formattedTopicName)) formattedTopicName else topicName } return "" } fun parseEnglishName(topicName: String): String { return if (StringUtils.isNotBlank(topicName)) { topicName.replace(TOPIC_NAME_REGEX.toRegex(), "") } else "" } companion object { val TOPIC_NAME_REGEX = "\\{.*\\}" } }
gpl-3.0
2072778be50fddd4ed665784555f0c7c
21.879121
109
0.620557
4.753425
false
false
false
false
thm-projects/arsnova-backend
gateway/src/main/kotlin/de/thm/arsnova/service/httpgateway/service/UserService.kt
1
2784
package de.thm.arsnova.service.httpgateway.service import de.thm.arsnova.service.httpgateway.config.HttpGatewayProperties import de.thm.arsnova.service.httpgateway.model.RoomHistoryEntry import de.thm.arsnova.service.httpgateway.model.User import de.thm.arsnova.service.httpgateway.security.AuthProcessor import org.slf4j.LoggerFactory import org.springframework.http.ResponseEntity import org.springframework.stereotype.Service import org.springframework.web.reactive.function.client.WebClient import org.springframework.web.reactive.function.client.WebClientResponseException.NotFound import reactor.core.publisher.Flux import reactor.core.publisher.Mono import java.util.Date @Service class UserService( private val webClient: WebClient, private val httpGatewayProperties: HttpGatewayProperties, private val authProcessor: AuthProcessor ) { private val logger = LoggerFactory.getLogger(javaClass) fun get(userId: String, jwt: String): Mono<User> { val url = "${httpGatewayProperties.httpClient.core}/user/$userId?view=owner" logger.trace("Querying core for user with url: {}", url) return webClient.get() .uri(url) .header("Authorization", jwt) .retrieve().bodyToMono(User::class.java).cache() .checkpoint("Request failed in ${this::class.simpleName}::${::get.name}.") } fun exists(userId: String, jwt: String): Mono<Boolean> { val url = "${httpGatewayProperties.httpClient.core}/user/$userId" logger.trace("Querying core for user with url: {}", url) return webClient.get() .uri(url) .header("Authorization", jwt) .retrieve().bodyToMono(User::class.java).cache() .map { true } .onErrorResume { e -> if (e !is NotFound) { throw e } Mono.just(false) } } fun getRoomHistory(userId: String, jwt: String): Flux<RoomHistoryEntry> { val url = "${httpGatewayProperties.httpClient.core}/user/$userId/roomHistory" logger.trace("Querying core for room history with url: {}", url) return webClient.get() .uri(url) .header("Authorization", jwt) .retrieve().bodyToFlux(RoomHistoryEntry::class.java).cache() .checkpoint("Request failed in ${this::class.simpleName}::${::getRoomHistory.name}.") } fun updateAnnouncementReadTimestamp(userId: String, jwt: String): Mono<ResponseEntity<Void>> { val url = "${httpGatewayProperties.httpClient.core}/user/$userId/" return webClient.patch() .uri(url) .header("Authorization", jwt) .bodyValue(AnnouncementReadTimestamp(Date())) .retrieve() .toBodilessEntity() .checkpoint("Request failed in ${this::class.simpleName}::${::getRoomHistory.name}.") } data class AnnouncementReadTimestamp(val announcementReadTimestamp: Date) }
gpl-3.0
bffe39da69b270d52cdf54fcbef437cf
37.666667
96
0.720187
4.224583
false
false
false
false
stepstone-tech/android-material-stepper
sample/src/main/java/com/stepstone/stepper/sample/StepperFeedbackActivity.kt
2
4853
/* Copyright 2017 StepStone Services 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.stepstone.stepper.sample import android.os.Bundle import android.support.v7.app.AppCompatActivity import android.view.Menu import android.view.MenuItem import com.stepstone.stepper.StepperLayout import com.stepstone.stepper.internal.feedback.StepperFeedbackType import com.stepstone.stepper.sample.adapter.StepperFeedbackFragmentStepAdapter import butterknife.BindView import butterknife.ButterKnife class StepperFeedbackActivity : AppCompatActivity() { companion object { private const val CURRENT_STEP_POSITION_KEY = "position" } @BindView(R.id.stepperLayout) lateinit var stepperLayout: StepperLayout private var menu: Menu? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) title = "Stepper sample" setContentView(R.layout.activity_stepper_feedback) ButterKnife.bind(this) val startingStepPosition = savedInstanceState?.getInt(CURRENT_STEP_POSITION_KEY) ?: 0 stepperLayout.setAdapter(StepperFeedbackFragmentStepAdapter(supportFragmentManager, this), startingStepPosition) } override fun onSaveInstanceState(outState: Bundle) { outState.putInt(CURRENT_STEP_POSITION_KEY, stepperLayout.currentStepPosition) super.onSaveInstanceState(outState) } override fun onBackPressed() { val currentStepPosition = stepperLayout.currentStepPosition if (currentStepPosition > 0) { //do nothing when operation is in progress if (!stepperLayout.isInProgress) { stepperLayout.onBackClicked() } } else { finish() } } override fun onCreateOptionsMenu(menu: Menu): Boolean { menuInflater.inflate(R.menu.activity_stepper_feedback, menu) this.menu = menu return true } override fun onOptionsItemSelected(item: MenuItem): Boolean { val itemId = item.itemId if (!stepperLayout.isInProgress && (itemId == R.id.menu_feedback_content_progress || itemId == R.id.menu_feedback_content_fade || itemId == R.id.menu_feedback_content_overlay || itemId == R.id.menu_feedback_tabs || itemId == R.id.menu_feedback_nav || itemId == R.id.menu_feedback_content_interaction)) { toggleItem(item) val tabsEnabled = menu?.findItem(R.id.menu_feedback_tabs)?.isChecked val contentProgressEnabled = menu?.findItem(R.id.menu_feedback_content_progress)?.isChecked val contentFadeEnabled = menu?.findItem(R.id.menu_feedback_content_fade)?.isChecked val contentOverlayEnabled = menu?.findItem(R.id.menu_feedback_content_overlay)?.isChecked val disablingBottomNavigationEnabled = menu?.findItem(R.id.menu_feedback_nav)?.isChecked val disablingContentInteractionEnabled = menu?.findItem(R.id.menu_feedback_content_interaction)?.isChecked var feedbackMask = 0 if (tabsEnabled == true) { feedbackMask = feedbackMask or StepperFeedbackType.TABS } if (contentProgressEnabled == true) { feedbackMask = feedbackMask or StepperFeedbackType.CONTENT_PROGRESS } if (contentFadeEnabled == true) { feedbackMask = feedbackMask or StepperFeedbackType.CONTENT_FADE } if (contentOverlayEnabled == true) { feedbackMask = feedbackMask or StepperFeedbackType.CONTENT_OVERLAY } if (disablingBottomNavigationEnabled == true) { feedbackMask = feedbackMask or StepperFeedbackType.DISABLED_BOTTOM_NAVIGATION } if (disablingContentInteractionEnabled == true) { feedbackMask = feedbackMask or StepperFeedbackType.DISABLED_CONTENT_INTERACTION } if (feedbackMask == 0) { feedbackMask = StepperFeedbackType.NONE } stepperLayout.setFeedbackType(feedbackMask) return true } return super.onOptionsItemSelected(item) } private fun toggleItem(item: MenuItem) { item.isChecked = !item.isChecked } }
apache-2.0
712dafe96784833050aed6379b886f48
37.212598
120
0.674222
5.07636
false
false
false
false
programingjd/server
buildSrc/src/main/kotlin/Bintray.kt
1
503
import java.io.File import java.lang.RuntimeException object BINTRAY { val user = "programingjd" fun password(rootProjectDir: File) = File(rootProjectDir, "local.properties").let { if (!it.exists()) throw RuntimeException("${it} is missing.") val regex = Regex("^\\s*bintrayApiKey\\s*=\\s*(.*)\\s*$") val line = it.readLines().findLast { it.matches(regex) } ?: throw RuntimeException("bintrayApiKey is not defined in ${it}.") regex.find(line)!!.groupValues[1] } }
apache-2.0
a0e9a7dc6d8d728bea248d6da53c43e7
34.928571
85
0.656064
3.725926
false
false
false
false
d9n/intellij-rust
src/main/kotlin/org/rust/lang/core/psi/ext/RsDocAndAttributeOwner.kt
1
3360
package org.rust.lang.core.psi.ext import com.intellij.psi.NavigatablePsiElement import org.rust.lang.core.psi.RsAttr import org.rust.lang.core.psi.RsInnerAttr import org.rust.lang.core.psi.RsMetaItem import org.rust.lang.core.psi.RsOuterAttr interface RsDocAndAttributeOwner : RsCompositeElement, NavigatablePsiElement interface RsInnerAttributeOwner : RsDocAndAttributeOwner { /** * Outer attributes are always children of the owning node. * In contrast, inner attributes can be either direct * children or grandchildren. */ val innerAttrList: List<RsInnerAttr> } /** * An element with attached outer attributes and documentation comments. * Such elements should use left edge binder to properly wrap preceding comments. * * Fun fact: in Rust, documentation comments are a syntactic sugar for attribute syntax. * * ``` * /// docs * fn foo() {} * ``` * * is equivalent to * * ``` * #[doc="docs"] * fn foo() {} * ``` */ interface RsOuterAttributeOwner : RsDocAndAttributeOwner { val outerAttrList: List<RsOuterAttr> } /** * Find the first outer attribute with the given identifier. */ fun RsOuterAttributeOwner.findOuterAttr(name: String): RsOuterAttr? = outerAttrList.find { it.metaItem.identifier.textMatches(name) } /** * Get sequence of all item's inner and outer attributes. * Inner attributes take precedence, so they must go first. */ val RsDocAndAttributeOwner.allAttributes: Sequence<RsAttr> get() = Sequence { (this as? RsInnerAttributeOwner)?.innerAttrList.orEmpty().iterator() } + Sequence { (this as? RsOuterAttributeOwner)?.outerAttrList.orEmpty().iterator() } /** * Returns [QueryAttributes] for given PSI element. */ val RsDocAndAttributeOwner.queryAttributes: QueryAttributes get() = QueryAttributes(allAttributes) /** * Allows for easy querying [RsDocAndAttributeOwner] for specific attributes. * * **Do not instantiate directly**, use [RsDocAndAttributeOwner.queryAttributes] instead. */ class QueryAttributes(private val attributes: Sequence<RsAttr>) { fun hasCfgAttr(): Boolean = hasAttribute("cfg") fun hasAttribute(attributeName: String) = metaItems.any { it.identifier.text == attributeName } fun hasAtomAttribute(attributeName: String): Boolean { val attr = attrByName(attributeName) return attr != null && (attr.eq == null && attr.metaItemArgs == null) } fun hasAttributeWithArg(attributeName: String, arg: String): Boolean { val attr = attrByName(attributeName) ?: return false val args = attr.metaItemArgs ?: return false return args.metaItemList.any { it.identifier.text == arg } } fun lookupStringValueForKey(key: String): String? = metaItems .filter { it.identifier.text == key } .mapNotNull { it.litExpr?.stringLiteralValue } .singleOrNull() val langAttribute: String? get() = getStringAttribute("lang") fun getStringAttribute(attributeName: String): String? { val attr = attrByName(attributeName) ?: return null if (attr.eq == null) return null return attr.litExpr?.stringLiteralValue } val metaItems: Sequence<RsMetaItem> get() = attributes.mapNotNull { it.metaItem } private fun attrByName(name: String) = metaItems.find { it.identifier.text == name } }
mit
8b00ecc7aca90dcd5dfd1a5cf455bd4e
31
99
0.705655
4.102564
false
false
false
false
material-components/material-components-android-examples
Reply/app/src/main/java/com/materialstudies/reply/ui/nav/NavigationViewHolder.kt
1
2407
/* * 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.materialstudies.reply.ui.nav import android.view.View import androidx.recyclerview.widget.RecyclerView import com.materialstudies.reply.databinding.NavDividerItemLayoutBinding import com.materialstudies.reply.databinding.NavEmailFolderItemLayoutBinding import com.materialstudies.reply.databinding.NavMenuItemLayoutBinding sealed class NavigationViewHolder<T : NavigationModelItem>( view: View ) : RecyclerView.ViewHolder(view) { abstract fun bind(navItem : T) class NavMenuItemViewHolder( private val binding: NavMenuItemLayoutBinding, private val listener: NavigationAdapter.NavigationAdapterListener ) : NavigationViewHolder<NavigationModelItem.NavMenuItem>(binding.root) { override fun bind(navItem: NavigationModelItem.NavMenuItem) { binding.run { navMenuItem = navItem navListener = listener executePendingBindings() } } } class NavDividerViewHolder( private val binding: NavDividerItemLayoutBinding ) : NavigationViewHolder<NavigationModelItem.NavDivider>(binding.root) { override fun bind(navItem: NavigationModelItem.NavDivider) { binding.navDivider = navItem binding.executePendingBindings() } } class EmailFolderViewHolder( private val binding: NavEmailFolderItemLayoutBinding, private val listener: NavigationAdapter.NavigationAdapterListener ) : NavigationViewHolder<NavigationModelItem.NavEmailFolder>(binding.root) { override fun bind(navItem: NavigationModelItem.NavEmailFolder) { binding.run { navEmailFolder = navItem navListener = listener executePendingBindings() } } } }
apache-2.0
36af2b3217f7112ee96d52daad721f8b
34.940299
80
0.712921
5.209957
false
false
false
false
DemonWav/IntelliJBukkitSupport
src/main/kotlin/util/CommonColors.kt
1
1600
/* * Minecraft Dev for IntelliJ * * https://minecraftdev.org * * Copyright (c) 2021 minecraft-dev * * MIT License */ package com.demonwav.mcdev.util import java.awt.Color @Suppress("MemberVisibilityCanBePrivate") object CommonColors { val DARK_RED = Color(0xAA0000) val RED = Color(0xFF5555) val GOLD = Color(0xFFAA00) val YELLOW = Color(0xFFFF55) val DARK_GREEN = Color(0x00AA00) val GREEN = Color(0x55FF55) val AQUA = Color(0x55FFFF) val DARK_AQUA = Color(0x00AAAA) val DARK_BLUE = Color(0x0000AA) val BLUE = Color(0x5555FF) val LIGHT_PURPLE = Color(0xFF55FF) val DARK_PURPLE = Color(0xAA00AA) val WHITE = Color(0xFFFFFF) val GRAY = Color(0xAAAAAA) val DARK_GRAY = Color(0x555555) val BLACK = Color(0x000000) fun applyStandardColors(map: MutableMap<String, Color>, prefix: String) { map.apply { put("$prefix.DARK_RED", DARK_RED) put("$prefix.RED", RED) put("$prefix.GOLD", GOLD) put("$prefix.YELLOW", YELLOW) put("$prefix.DARK_GREEN", DARK_GREEN) put("$prefix.GREEN", GREEN) put("$prefix.AQUA", AQUA) put("$prefix.DARK_AQUA", DARK_AQUA) put("$prefix.DARK_BLUE", DARK_BLUE) put("$prefix.BLUE", BLUE) put("$prefix.LIGHT_PURPLE", LIGHT_PURPLE) put("$prefix.DARK_PURPLE", DARK_PURPLE) put("$prefix.WHITE", WHITE) put("$prefix.GRAY", GRAY) put("$prefix.DARK_GRAY", DARK_GRAY) put("$prefix.BLACK", BLACK) } } }
mit
ce5e84ea90145311c5b6132a1ef38257
28.090909
77
0.591875
3.501094
false
false
false
false
jaredsburrows/cs-interview-questions
kotlin/src/main/kotlin/koans/builders.kt
1
1244
package koans // Function literals with receiver // https://play.kotlinlang.org/koans/Builders/Function%20literals%20with%20receiver/Task.kt fun task(): List<Boolean> { val isEven: Int.() -> Boolean = { this % 2 == 0 } val isOdd: Int.() -> Boolean = { this % 2 != 0 } return listOf(42.isOdd(), 239.isOdd(), 294823098.isEven()) } // String and map builders // https://play.kotlinlang.org/koans/Builders/String%20and%20map%20builders/Task.kt fun <L, R> buildMap(build: HashMap<L, R>.() -> Unit): Map<L, R> { val map = hashMapOf<L, R>() map.build() return map } fun usage(): Map<Int, String> { return buildMap { put(0, "0") for (i in 1..10) { put(i, "$i") } } } // The function apply // https://play.kotlinlang.org/koans/Builders/The%20function%20apply/Task.kt fun <T> T.myApply(f: T.() -> Unit): T { f() return this } fun createString(): String { return StringBuilder().myApply { append("Numbers: ") for (i in 1..10) { append(i) } }.toString() } fun createMap(): Map<Int, String> { return hashMapOf<Int, String>().myApply { put(0, "0") for (i in 1..10) { put(i, "$i") } } }
apache-2.0
4ead5dab46fa71d6342a9fb83e3c885a
22.471698
91
0.561897
3.222798
false
false
false
false
edvin/tornadofx
src/test/kotlin/tornadofx/testapps/TodoTestApp.kt
1
2712
package tornadofx.testapps import javafx.beans.property.SimpleBooleanProperty import javafx.beans.property.SimpleObjectProperty import javafx.beans.property.SimpleStringProperty import javafx.collections.FXCollections import javafx.geometry.Pos import javafx.scene.control.CheckBox import javafx.scene.control.RadioButton import javafx.scene.control.TableColumn import javafx.scene.control.ToggleGroup import tornadofx.* class TodoItem(text: String? = null, completed: Boolean = true) { val textProperty = SimpleStringProperty(text) var text by textProperty val completedProperty = SimpleBooleanProperty(completed) var completed by completedProperty override fun toString() = "[${if (completed) "X" else " "}] $text" } enum class TodoFilter { All, Completed, Active } class TodoList : View("Todo List") { val todos = SortedFilteredList(FXCollections.observableArrayList(TodoItem("Item 1"), TodoItem("Item 2"), TodoItem("Item 3", false), TodoItem("Item 4"), TodoItem("Item 5"))) val todoFilter = SimpleObjectProperty(TodoFilter.All) override val root = borderpane { center { tableview(todos) { setPrefSize(300.0, 200.0) column("Completed", TodoItem::completedProperty) { sortType = TableColumn.SortType.DESCENDING sortOrder.add(this) cellFormat { graphic = cache { alignment = Pos.CENTER checkbox { selectedProperty().bindBidirectional(itemProperty()) action { tableView.edit(index, tableColumn) commitEdit(!isSelected) sort() } } } } } column("Text", TodoItem::textProperty).makeEditable() } } bottom { hbox { togglegroup { TodoFilter.values().forEach { radiobutton(value = it) } bind(todoFilter) } } todoFilter.onChange { todos.refilter() } } } init { todos.predicate = { when (todoFilter.value) { TodoFilter.All -> true TodoFilter.Completed -> it.completed TodoFilter.Active -> !it.completed } } } } class TodoTestApp : WorkspaceApp(TodoList::class)
apache-2.0
5c7260f559ccb009fd57a1fed2bd3169
31.674699
176
0.532448
5.685535
false
false
false
false
ArdentDiscord/ArdentKotlin
src/main/kotlin/commands/music/MusicCommands.kt
1
12147
package commands.music import events.Category import events.ExtensibleCommand import main.conn import main.hostname import main.r import main.waiter import net.dv8tion.jda.api.events.message.MessageReceivedEvent import translation.tr import utils.discord.* import utils.functionality.* import utils.music.DatabaseMusicPlaylist import utils.music.getPlaylistById import java.util.stream.Collectors class MyMusicLibrary : ExtensibleCommand(Category.MUSIC, "mylibrary", "reset, or play from your personal music library", "mymusic") { override fun executeBase(arguments: MutableList<String>, event: MessageReceivedEvent) { showHelp(event) } override fun registerSubcommands() { with("reset", null, "reset your music library from scratch", { arguments, event -> event.channel.send(Emoji.INFORMATION_SOURCE.symbol + " " + "Are you sure you want to reset your library? Type **yes** to continue".tr(event)) waiter.waitForMessage(Settings(event.author.id, event.channel.id, event.guild.id), { message -> if (message.contentRaw.startsWith("ye")) { val library = getMusicLibrary(event.author.id) library.tracks = mutableListOf() library.update("musicLibraries", event.author.id) event.channel.send(Emoji.BALLOT_BOX_WITH_CHECK.symbol + " " + "Successfully reset your music library") } else event.channel.send("**Yes** wasn't provided, so I cancelled the reset") }) }) with("play", null, "play from your personal music library", { arguments, event -> val library = getMusicLibrary(event.author.id) if (library.tracks.size == 0) event.channel.send(Emoji.HEAVY_MULTIPLICATION_X.symbol + " " + "You don't have any tracks in your music library! Add some at {0}".tr(event, "$hostname/profile/${event.author.id}")) else { event.channel.send("Started loading **{0}** tracks from your music library..".tr(event, library.tracks.size)) library.load(event.member!!, event.textChannel) } }) } } class Playlist : ExtensibleCommand(Category.MUSIC, "playlist", "create, delete, or play from your saved playlists", "playlists") { override fun executeBase(arguments: MutableList<String>, event: MessageReceivedEvent) { showHelp(event) } override fun registerSubcommands() { with("play", "play [playlist id]", "start playback of a playlist", { arguments, event -> val playlist: DatabaseMusicPlaylist? = asPojo(r.table("musicPlaylists").get(arguments.getOrElse(0, { "" })).run(conn), DatabaseMusicPlaylist::class.java) if (playlist == null) event.channel.send("You need to specify a valid playlist id!".tr(event)) else { event.channel.send("Loading tracks from playlist **{0}**..".tr(event, playlist.name)) playlist.toLocalPlaylist(event.member!!).loadTracks(event.textChannel, event.member!!) } }) with("list", "list @User", "see the mentioned user's playlists", { arguments, event -> val user = event.message.mentionedUsers.getOrElse(0, { event.author }) val embed = event.member!!.embed("{0} | Music Playlists".tr(event, user.toFancyString()), event.textChannel) val playlists = getPlaylists(user.id) if (playlists.isEmpty()) embed.appendDescription("This user doesn't have any playlists! Create one by typing */playlist create [name]*".tr(event)) else { playlists.forEachIndexed { index, playlist -> embed.appendDescription(index.getListEmoji() + " " + "[**{0}**]($hostname/music/playlist/{1}) - ID: *{2}* - Last Modified at *{3}*" .tr(event, playlist.name, playlist.id, playlist.id, playlist.lastModified.readableDate()) + "\n\n") } embed.appendDescription("You can play a playlist using */playlist play [playlist id]*") } embed.send() }) with("view", "view [playlist id]", "see an overview of the specified playlist", { arguments, event -> val playlist: DatabaseMusicPlaylist? = asPojo(r.table("musicPlaylists").get(arguments.getOrElse(0, { "" })).run(conn), DatabaseMusicPlaylist::class.java) if (playlist == null) event.channel.send("You need to specify a valid playlist id!".tr(event)) else { event.channel.send("To see track information for, or modify **{0}** *by {1}*, go to {2} - id: *{3}*".tr(event, playlist.name, getUserById(playlist.owner)?.toFancyString() ?: "Unknown", "$hostname/music/playlist/${playlist.id}", playlist.id)) } }) with("delete", "delete [playlist id]", "delete one of your playlists", { arguments, event -> val playlist: DatabaseMusicPlaylist? = asPojo(r.table("musicPlaylists").get(arguments.getOrElse(0, { "" })).run(conn), DatabaseMusicPlaylist::class.java) if (playlist == null) event.channel.send("You need to specify a valid playlist id!".tr(event)) else { if (playlist.owner != event.author.id) event.channel.send("You need to be the owner of this playlist in order to delete it!") else { event.channel.selectFromList(event.member!!, "Are you sure you want to delete the playlist **{0}** [{1} tracks]? This is **unreversable**".tr(event, playlist.name, playlist.tracks.size), mutableListOf("Yes", "No"), { selection, m -> if (selection == 0) { r.table("musicPlaylists").get(playlist.id).delete().runNoReply(conn) event.channel.send(Emoji.BALLOT_BOX_WITH_CHECK.symbol + " " + "Deleted the playlist **{0}**".tr(event, playlist.name)) } else event.channel.send(Emoji.BALLOT_BOX_WITH_CHECK.symbol + " " + "Cancelled playlist deletion..".tr(event)) m.delete() }, translatedTitle = true) } } }) with("create", null, "create a new playlist", { arguments, event -> if (arguments.isEmpty()) event.channel.send("You need to include a name for this playlist") else { val name = arguments.concat() event.channel.selectFromList(event.member!!, "What type of playlist do you want to create?", mutableListOf("Default", "Spotify Playlist or Album", "Clone someone's playlist", "YouTube Playlist"), { selection, msg -> msg.delete().queue() when (selection) { 0 -> { event.channel.send("Successfully created the playlist **{0}**!".tr(event, name)) val playlist = DatabaseMusicPlaylist(genId(6, "musicPlaylists"), event.author.id, name, System.currentTimeMillis(), null, null, null, tracks = mutableListOf()) playlist.insert("musicPlaylists") event.channel.send("View this playlist online at {0}".tr(event, "$hostname/music/playlist/${playlist.id}")) } 1 -> { event.channel.send("Please enter in a Spotify playlist or album url now") waiter.waitForMessage(Settings(event.author.id, event.channel.id, event.guild.id), { reply -> val url = reply.contentRaw val playlist: DatabaseMusicPlaylist? = when { url.startsWith("https://open.spotify.com/album/") -> { event.channel.send("Successfully created the playlist **{0}**!".tr(event, name)) DatabaseMusicPlaylist(genId(6, "musicPlaylists"), event.author.id, name, System.currentTimeMillis(), url.removePrefix("https://open.spotify.com/album/"), null, null) } url.startsWith("https://open.spotify.com/user/") -> { event.channel.send("Successfully created the playlist **{0}**!".tr(event, name)) DatabaseMusicPlaylist(genId(6, "musicPlaylists"), event.author.id, name, System.currentTimeMillis(), null, url.removePrefix("https://open.spotify.com/user/") .split("/playlist/").stream().collect(Collectors.joining("||")), null) } else -> { event.channel.send("You specified an invalid url. Cancelled playlist setup.".tr(event)) null } } if (playlist != null) { playlist.insert("musicPlaylists") event.channel.send("View this playlist online at {0}".tr(event, "$hostname/music/playlist/${playlist.id}")) } }) } 2 -> { event.channel.send("Please enter in an Ardent playlist id or url") waiter.waitForMessage(Settings(event.author.id, event.channel.id, event.guild.id), { reply -> val url = reply.contentRaw.replace("$hostname/music/playlist/", "") val playlist = getPlaylistById(url) if (playlist == null) event.channel.send("You specified an invalid playlist. Please try again") else { val newPlaylist = playlist.copy(id = genId(8, "musicPlaylists"), name = name, owner = event.author.id) newPlaylist.insert("musicPlaylists") event.channel.send("Successfully cloned **{0}**!".tr(event, playlist.name)) event.channel.send("View this playlist online at {0}".tr(event, "$hostname/music/playlist/${newPlaylist.id}")) } }) } else -> { event.channel.send("Please specify a YouTube playlist url now.") waiter.waitForMessage(Settings(event.author.id, event.channel.id, event.guild.id), { reply -> val url = reply.contentRaw if (url.startsWith("https://www.youtube.com/playlist?list=") || url.startsWith("https://youtube.com/playlist?list=")) { event.channel.send("Successfully created the playlist **{0}**!".tr(event, name)) val playlist = DatabaseMusicPlaylist(genId(6, "musicPlaylists"), event.author.id, name, System.currentTimeMillis(), null, null, url, tracks = mutableListOf()) playlist.insert("musicPlaylists") event.channel.send("View this playlist online at {0}".tr(event, "$hostname/music/playlist/${playlist.id}")) } else { event.channel.send("You specified an invalid url. Cancelled playlist setup.".tr(event)) } }) } } }, failure = { event.channel.send("Cancelled playlist creation.".tr(event)) }) } }) } }
apache-2.0
0019b0f1ecb209b376a94b04f020326d
66.865922
257
0.534782
4.907879
false
false
false
false