repo_name
stringlengths
7
81
path
stringlengths
4
242
copies
stringclasses
95 values
size
stringlengths
1
6
content
stringlengths
3
991k
license
stringclasses
15 values
spinnaker/echo
echo-plugins-test/src/test/kotlin/com/netflix/spinnaker/echo/plugins/test/EchoPluginsTest.kt
1
2023
/* * Copyright 2020 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.spinnaker.echo.plugins.test import com.netflix.spinnaker.echo.api.events.EventListener import com.netflix.spinnaker.echo.api.events.NotificationAgent import com.netflix.spinnaker.kork.plugins.tck.PluginsTck import com.netflix.spinnaker.kork.plugins.tck.serviceFixture import dev.minutest.rootContext import strikt.api.expect import strikt.assertions.isNotNull class EchoPluginsTest : PluginsTck<EchoPluginsFixture>() { fun tests() = rootContext<EchoPluginsFixture> { context("an echo integration test environment and an echo plugin") { serviceFixture { EchoPluginsFixture() } defaultPluginTests() test("Event listener extension is loaded into context") { val eventListeners = applicationContext.getBeansOfType(EventListener::class.java) val extensionBeanName = "com.netflix.echo.enabled.plugin_eventListenerExtension" val extension = eventListeners[extensionBeanName] expect { that(extension).isNotNull() } } test("Notification agent extension is loaded into context") { val eventListeners = applicationContext.getBeansOfType(NotificationAgent::class.java) val extensionBeanName = "com.netflix.echo.enabled.plugin_notificationAgentExtension" val extension = eventListeners[extensionBeanName] expect { that(extension).isNotNull() } } } } }
apache-2.0
jabbink/PokemonGoAPI
src/main/kotlin/ink/abb/pogo/api/cache/MapPokemon.kt
1
3550
package ink.abb.pogo.api.cache import POGOProtos.Enums.PokemonIdOuterClass import POGOProtos.Map.Fort.FortDataOuterClass import POGOProtos.Map.Pokemon.MapPokemonOuterClass import POGOProtos.Map.Pokemon.WildPokemonOuterClass import ink.abb.pogo.api.PoGoApi class MapPokemon { val encounterKind: EncounterKind val spawnPointId: String val encounterId: Long val pokemonId: PokemonIdOuterClass.PokemonId val pokemonIdValue: Int val expirationTimestampMs: Long val latitude: Double val longitude: Double val poGoApi: PoGoApi val valid: Boolean get() = expirationTimestampMs == -1L || poGoApi.currentTimeMillis() < expirationTimestampMs constructor(poGoApi: PoGoApi, proto: MapPokemonOuterClass.MapPokemonOrBuilder) { this.encounterKind = EncounterKind.NORMAL this.spawnPointId = proto.spawnPointId this.encounterId = proto.encounterId this.pokemonId = proto.pokemonId this.pokemonIdValue = proto.pokemonIdValue this.expirationTimestampMs = proto.expirationTimestampMs this.latitude = proto.latitude this.longitude = proto.longitude this.poGoApi = poGoApi } constructor(poGoApi: PoGoApi, proto: WildPokemonOuterClass.WildPokemonOrBuilder) { this.encounterKind = EncounterKind.NORMAL this.spawnPointId = proto.spawnPointId this.encounterId = proto.encounterId this.pokemonId = proto.pokemonData.pokemonId this.pokemonIdValue = proto.pokemonData.pokemonIdValue this.expirationTimestampMs = proto.timeTillHiddenMs.toLong() this.latitude = proto.latitude this.longitude = proto.longitude this.poGoApi = poGoApi } constructor(poGoApi: PoGoApi, proto: FortDataOuterClass.FortDataOrBuilder) { this.spawnPointId = proto.lureInfo.fortId this.encounterId = proto.lureInfo.encounterId this.pokemonId = proto.lureInfo.activePokemonId this.pokemonIdValue = proto.lureInfo.activePokemonIdValue this.expirationTimestampMs = proto.lureInfo .lureExpiresTimestampMs this.latitude = proto.latitude this.longitude = proto.longitude this.encounterKind = EncounterKind.DISK this.poGoApi = poGoApi } enum class EncounterKind { NORMAL, DISK } override fun toString(): String { return "MapPokemon(encounterKind=$encounterKind, spawnPointId='$spawnPointId', encounterId=$encounterId, pokemonId=$pokemonId, pokemonIdValue=$pokemonIdValue, expirationTimestampMs=$expirationTimestampMs, latitude=$latitude, longitude=$longitude)" } override fun equals(other: Any?): Boolean { if (this === other) return true if (other !is MapPokemon) return false if (encounterKind != other.encounterKind) return false if (spawnPointId != other.spawnPointId) return false if (encounterId != other.encounterId) return false if (pokemonIdValue != other.pokemonIdValue) return false if (latitude != other.latitude) return false if (longitude != other.longitude) return false return true } override fun hashCode(): Int { var result = encounterKind.hashCode() result = 31 * result + spawnPointId.hashCode() result = 31 * result + encounterId.hashCode() result = 31 * result + pokemonIdValue result = 31 * result + latitude.hashCode() result = 31 * result + longitude.hashCode() return result } }
gpl-3.0
trevjonez/AndroidGithubReleasePlugin
plugin/src/main/kotlin/com/trevjonez/agrp/AgrpLibraryPlugin.kt
1
954
/* * Copyright (c) 2019. Trevor Jones * * 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.trevjonez.agrp import com.android.build.gradle.LibraryExtension abstract class AgrpLibraryPlugin : AbsAgrpPlugin() { override fun registerTasks() { target.extensions.getByType(LibraryExtension::class.java) .libraryVariants .all { variant -> target.afterEvaluate { registerTasksForVariant(variant) } } } }
apache-2.0
xfournet/intellij-community
python/src/com/jetbrains/python/testing/PyNoseTest.kt
1
2683
/* * Copyright 2000-2017 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.jetbrains.python.testing import com.intellij.execution.Executor import com.intellij.execution.configurations.RunProfileState import com.intellij.execution.runners.ExecutionEnvironment import com.intellij.openapi.options.SettingsEditor import com.intellij.openapi.project.Project import com.jetbrains.python.PyNames import com.jetbrains.python.PythonHelper import com.jetbrains.python.run.targetBasedConfiguration.PyRunTargetVariant /** * Nose runner */ class PyNoseTestSettingsEditor(configuration: PyAbstractTestConfiguration) : PyAbstractTestSettingsEditor( PyTestSharedForm.create(configuration, PyTestSharedForm.CustomOption( PyNoseTestConfiguration::regexPattern.name, PyRunTargetVariant.PATH))) class PyNoseTestExecutionEnvironment(configuration: PyNoseTestConfiguration, environment: ExecutionEnvironment) : PyTestExecutionEnvironment<PyNoseTestConfiguration>(configuration, environment) { override fun getRunner() = PythonHelper.NOSE } class PyNoseTestConfiguration(project: Project, factory: PyNoseTestFactory) : PyAbstractTestConfiguration(project, factory, PyTestFrameworkService.getSdkReadableNameByFramework(PyNames.NOSE_TEST)) { @ConfigField var regexPattern = "" override fun getState(executor: Executor, environment: ExecutionEnvironment): RunProfileState? = PyNoseTestExecutionEnvironment(this, environment) override fun createConfigurationEditor(): SettingsEditor<PyAbstractTestConfiguration> = PyNoseTestSettingsEditor(this) override fun getCustomRawArgumentsString(forRerun: Boolean): String = when { regexPattern.isEmpty() -> "" else -> "-m $regexPattern" } override fun isFrameworkInstalled() = VFSTestFrameworkListener.getInstance().isTestFrameworkInstalled(sdk, PyNames.NOSE_TEST) } object PyNoseTestFactory : PyAbstractTestFactory<PyNoseTestConfiguration>() { override fun createTemplateConfiguration(project: Project) = PyNoseTestConfiguration(project, this) override fun getName(): String = PyTestFrameworkService.getSdkReadableNameByFramework(PyNames.NOSE_TEST) }
apache-2.0
yshrsmz/monotweety
app/src/main/java/net/yslibrary/monotweety/status/domain/UpdateStatus.kt
1
478
package net.yslibrary.monotweety.status.domain import io.reactivex.Completable import net.yslibrary.monotweety.appdata.status.StatusRepository import net.yslibrary.monotweety.di.UserScope import javax.inject.Inject @UserScope class UpdateStatus @Inject constructor(private val statusRepository: StatusRepository) { fun execute(status: String, inReplyToStatusId: Long? = null): Completable { return statusRepository.updateStatus(status, inReplyToStatusId) } }
apache-2.0
yyued/CodeX-UIKit-Android
library/src/main/java/com/yy/codex/uikit/CGTransformRotation.kt
1
132
package com.yy.codex.uikit /** * Created by adi on 17/1/13. */ class CGTransformRotation(val angle: Double) : CGTransform(true)
gpl-3.0
chrisbanes/tivi
api/tmdb/src/main/java/app/tivi/tmdb/TmdbImageSizes.kt
1
1110
/* * Copyright 2017 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package app.tivi.tmdb object TmdbImageSizes { const val baseImageUrl = "https://image.tmdb.org/t/p/" val posterSizes = listOf( "w92", "w154", "w185", "w342", "w500", "w780", "original" ) val backdropSizes = listOf( "w300", "w780", "w1280", "original" ) val logoSizes = listOf( "w45", "w92", "w154", "w185", "w300", "w500", "original" ) }
apache-2.0
vsch/idea-multimarkdown
src/main/java/com/vladsch/md/nav/flex/intentions/AddVisibleSpecLSIntention.kt
1
1840
// Copyright (c) 2017-2020 Vladimir Schneider <[email protected]> Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.vladsch.md.nav.flex.intentions import com.intellij.openapi.editor.Editor import com.intellij.psi.PsiElement import com.intellij.psi.PsiPlainText import com.vladsch.flexmark.test.util.TestUtils import com.vladsch.flexmark.util.sequence.SequenceUtils import com.vladsch.md.nav.flex.psi.FlexmarkExampleSection import com.vladsch.md.nav.psi.element.MdBlankLine import com.vladsch.md.nav.psi.element.MdParagraph import com.vladsch.md.nav.psi.element.MdTextBlock import com.vladsch.md.nav.util.PsiElementPredicateWithEditor class AddVisibleSpecLSIntention : InsertOrReplaceCaretTextIntention() { override fun getText(element: PsiElement, documentChars: CharSequence, selectionStart: Int, selectionEnd: Int): String { return TestUtils.toVisibleSpecText(SequenceUtils.LINE_SEP) } override fun getElementPredicate(): PsiElementPredicateWithEditor { return object : PsiElementPredicateWithEditor { override fun satisfiedBy(editor: Editor, selectionStart: Int, selectionEnd: Int): Boolean { return true } override fun satisfiedBy(element: PsiElement): Boolean { return element is PsiPlainText || element is MdParagraph || element.parent is MdTextBlock || element is MdBlankLine || element is FlexmarkExampleSection || element.containingFile.context is FlexmarkExampleSection || element.toString() == "PsiJavaToken:STRING_LITERAL" || element.toString() == "PsiJavaToken:CHARACTER_LITERAL" } } } }
apache-2.0
charlesmadere/smash-ranks-android
smash-ranks-android/app/src/main/java/com/garpr/android/features/players/PlayerItemView.kt
1
1788
package com.garpr.android.features.players import android.content.Context import android.graphics.Typeface import android.graphics.drawable.Drawable import android.util.AttributeSet import android.view.View import android.widget.FrameLayout import androidx.annotation.ColorInt import androidx.core.content.ContextCompat import androidx.core.view.ViewCompat import com.garpr.android.R import com.garpr.android.data.models.AbsPlayer import kotlinx.android.synthetic.main.item_player.view.* class PlayerItemView @JvmOverloads constructor( context: Context, attrs: AttributeSet? = null ) : FrameLayout(context, attrs), View.OnClickListener, View.OnLongClickListener { private var _player: AbsPlayer? = null val player: AbsPlayer get() = checkNotNull(_player) private val originalBackground: Drawable? = background @ColorInt private val cardBackgroundColor: Int = ContextCompat.getColor(context, R.color.card_background) var listeners: Listeners? = null interface Listeners { fun onClick(v: PlayerItemView) fun onLongClick(v: PlayerItemView) } init { setOnClickListener(this) setOnLongClickListener(this) } override fun onClick(v: View) { listeners?.onClick(this) } override fun onLongClick(v: View): Boolean { listeners?.onLongClick(this) return true } fun setContent(player: AbsPlayer, isIdentity: Boolean) { _player = player name.text = player.name if (isIdentity) { name.typeface = Typeface.DEFAULT_BOLD setBackgroundColor(cardBackgroundColor) } else { name.typeface = Typeface.DEFAULT ViewCompat.setBackground(this, originalBackground) } } }
unlicense
alygin/intellij-rust
src/main/kotlin/org/rust/cargo/project/workspace/impl/CargoProjectWorkspaceServiceImpl.kt
1
11324
/* * Use of this source code is governed by the MIT license that can be * found in the LICENSE file. */ package org.rust.cargo.project.workspace.impl import com.intellij.execution.ExecutionException import com.intellij.execution.process.ProcessAdapter import com.intellij.execution.process.ProcessEvent import com.intellij.notification.NotificationType import com.intellij.openapi.Disposable import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.application.runWriteAction import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.module.Module import com.intellij.openapi.progress.BackgroundTaskQueue import com.intellij.openapi.progress.ProgressIndicator import com.intellij.openapi.progress.Task import com.intellij.openapi.roots.ex.ProjectRootManagerEx import com.intellij.openapi.util.EmptyRunnable import com.intellij.openapi.util.Key import com.intellij.openapi.vfs.VirtualFileManager import com.intellij.util.Alarm import org.jetbrains.annotations.TestOnly import org.rust.cargo.project.settings.RustProjectSettingsService import org.rust.cargo.project.settings.rustSettings import org.rust.cargo.project.settings.toolchain import org.rust.cargo.project.workspace.* import org.rust.cargo.project.workspace.CargoProjectWorkspaceService.UpdateResult import org.rust.cargo.toolchain.RustToolchain import org.rust.cargo.util.cargoProjectRoot import org.rust.ide.notifications.showBalloon import org.rust.ide.utils.checkReadAccessAllowed import org.rust.ide.utils.checkWriteAccessAllowed import org.rust.utils.pathAsPath import java.nio.file.Path private val LOG = Logger.getInstance(CargoProjectWorkspaceServiceImpl::class.java) /** * [CargoWorkspace] of a real project consists of two pieces: * * * Project structure reported by `cargo metadata` * * Standard library, usually retrieved from rustup. * * This two piece may vary independently. [WorkspaceMerger] * merges them into a single [CargoWorkspace]. It's executed * only on EDT, so you may think of it as an actor maintaining * a two bits of state. */ private class WorkspaceMerger(private val updateCallback: () -> Unit) { private var rawWorkspace: CargoWorkspace? = null private var stdlib: StandardLibrary? = null fun setStdlib(lib: StandardLibrary) { checkWriteAccessAllowed() stdlib = lib update() } fun setRawWorkspace(workspace: CargoWorkspace) { checkWriteAccessAllowed() rawWorkspace = workspace update() } var workspace: CargoWorkspace? = null get() { checkReadAccessAllowed() return field } private set(value) { field = value } private fun update() { val raw = rawWorkspace if (raw == null) { workspace = null return } workspace = raw.withStdlib(stdlib?.crates.orEmpty()) updateCallback() } } class CargoProjectWorkspaceServiceImpl(private val module: Module) : CargoProjectWorkspaceService { // First updates go through [debouncer] to be properly throttled, // and then via [taskQueue] to be serialized (it should be safe to execute // several Cargo's concurrently, but let's avoid that) private val debouncer = Debouncer(delayMillis = 1000, parentDisposable = module) private val taskQueue = BackgroundTaskQueue(module.project, "Cargo update") private val workspaceMerger = WorkspaceMerger { ProjectRootManagerEx.getInstanceEx(module.project).makeRootsChange(EmptyRunnable.getInstance(), false, true) } init { fun refreshStdlib() { val projectDirectory = module.cargoProjectRoot?.pathAsPath ?: return val rustup = module.project.toolchain?.rustup(projectDirectory) if (rustup != null) { taskQueue.run(SetupRustStdlibTask(module, rustup, { runWriteAction { workspaceMerger.setStdlib(it) } })) } else { ApplicationManager.getApplication().invokeLater { val lib = StandardLibrary.fromPath(module.project.rustSettings.explicitPathToStdlib ?: "") if (lib != null) { runWriteAction { workspaceMerger.setStdlib(lib) } } } } } with(module.messageBus.connect()) { subscribe(VirtualFileManager.VFS_CHANGES, CargoTomlWatcher(fun() { if (!module.project.rustSettings.autoUpdateEnabled) return val toolchain = module.project.toolchain ?: return requestUpdate(toolchain) })) subscribe(RustProjectSettingsService.TOOLCHAIN_TOPIC, object : RustProjectSettingsService.ToolchainListener { override fun toolchainChanged() { val toolchain = module.project.toolchain if (toolchain != null) { requestUpdate(toolchain) { refreshStdlib() } } } }) } refreshStdlib() val toolchain = module.project.toolchain if (toolchain != null) { requestImmediateUpdate(toolchain) { result -> when (result) { is UpdateResult.Err -> module.project.showBalloon( "Project '${module.name}' failed to update.<br> ${result.error.message}", NotificationType.ERROR ) is UpdateResult.Ok -> { val outsider = result.workspace.packages .filter { it.origin == PackageOrigin.WORKSPACE } .mapNotNull { it.contentRoot } .find { it !in module.moduleContentScope } if (outsider != null) { module.project.showBalloon( "Workspace member ${outsider.presentableUrl} is outside of IDE project, " + "please open the root of the workspace.", NotificationType.WARNING ) } } } } } } /** * Requests to updates Rust libraries asynchronously. Consecutive requests are coalesced. * * Works in two phases. First `cargo metadata` is executed on the background thread. Then, * the actual Library update happens on the event dispatch thread. */ override fun requestUpdate(toolchain: RustToolchain) = requestUpdate(toolchain, null) override fun requestImmediateUpdate(toolchain: RustToolchain, afterCommit: (UpdateResult) -> Unit) = requestUpdate(toolchain, afterCommit) override fun syncUpdate(toolchain: RustToolchain) { taskQueue.run(UpdateTask(toolchain, module.cargoProjectRoot!!.pathAsPath, null)) val projectDirectory = module.cargoProjectRoot?.pathAsPath ?: return val rustup = module.project.toolchain?.rustup(projectDirectory) ?: return taskQueue.run(SetupRustStdlibTask(module, rustup, { runWriteAction { workspaceMerger.setStdlib(it) } })) } private fun requestUpdate(toolchain: RustToolchain, afterCommit: ((UpdateResult) -> Unit)?) { val contentRoot = module.cargoProjectRoot ?: return debouncer.submit({ taskQueue.run(UpdateTask(toolchain, contentRoot.pathAsPath, afterCommit)) }, immediately = afterCommit != null) } /** * Delivers latest cached project-description instance * * NOTA BENE: [CargoProjectWorkspaceService] is rather low-level abstraction around, `Cargo.toml`-backed projects * mapping underpinning state of the `Cargo.toml` workspace _transparently_, i.e. it doesn't provide * any facade atop of the latter insulating itself from inconsistencies in the underlying layer. For * example, [CargoProjectWorkspaceService] wouldn't be able to provide a valid [CargoWorkspace] instance * until the `Cargo.toml` becomes sound */ override val workspace: CargoWorkspace? get() = workspaceMerger.workspace private fun commitUpdate(r: UpdateResult) { ApplicationManager.getApplication().assertIsDispatchThread() if (module.isDisposed) return if (r is UpdateResult.Ok) { runWriteAction { workspaceMerger.setRawWorkspace(r.workspace) } } } private inner class UpdateTask( private val toolchain: RustToolchain, private val projectDirectory: Path, private val afterCommit: ((UpdateResult) -> Unit)? = null ) : Task.Backgroundable(module.project, "Updating cargo") { private var result: UpdateResult? = null override fun run(indicator: ProgressIndicator) { if (module.isDisposed) return LOG.info("Cargo project update started") indicator.isIndeterminate = true if (!toolchain.looksLikeValidToolchain()) { result = UpdateResult.Err(ExecutionException("Invalid toolchain ${toolchain.presentableLocation}")) return } val cargo = toolchain.cargo(projectDirectory) result = try { val description = cargo.fullProjectDescription(module, object : ProcessAdapter() { override fun onTextAvailable(event: ProcessEvent, outputType: Key<Any>) { val text = event.text.trim { it <= ' ' } if (text.startsWith("Updating") || text.startsWith("Downloading")) { indicator.text = text } } }) UpdateResult.Ok(description) } catch (e: ExecutionException) { UpdateResult.Err(e) } } override fun onSuccess() { val r = requireNotNull(result) commitUpdate(r) afterCommit?.invoke(r) } } @TestOnly fun setRawWorkspace(workspace: CargoWorkspace) { commitUpdate(UpdateResult.Ok(workspace)) } @TestOnly fun setStdlib(libs: StandardLibrary) { workspaceMerger.setStdlib(libs) } } /** * Executes tasks with rate of at most once every [delayMillis]. */ private class Debouncer( private val delayMillis: Int, parentDisposable: Disposable ) { private val alarm = Alarm(Alarm.ThreadToUse.POOLED_THREAD, parentDisposable) fun submit(task: () -> Unit, immediately: Boolean) { if (ApplicationManager.getApplication().isUnitTestMode) { check(ApplicationManager.getApplication().isDispatchThread) { "Background activity in unit tests can lead to deadlocks" } task() return } onAlarmThread { alarm.cancelAllRequests() if (immediately) { task() } else { alarm.addRequest(task, delayMillis) } } } private fun onAlarmThread(work: () -> Unit) = alarm.addRequest(work, 0) }
mit
quarkusio/quarkus
integration-tests/hibernate-orm-panache-kotlin/src/main/kotlin/io/quarkus/it/panache/kotlin/AccessorEntity.kt
1
1101
package io.quarkus.it.panache.kotlin import javax.persistence.Entity import javax.persistence.Transient @Entity open class AccessorEntity : GenericEntity<Int>() { var string: String? = null var c = 0.toChar() var bool = false var b: Byte = 0 get() { getBCalls++ return field } var s: Short = 0 var i: Int = 0 set(value) { setICalls++ field = value } var l: Long get() { throw UnsupportedOperationException("just checking") } set(value) { throw UnsupportedOperationException("just checking") } var f = 0f var d = 0.0 @Transient var trans: Any? = null @Transient var trans2: Any? = null // FIXME: those appear to be mapped by hibernate @Transient var getBCalls = 0 @Transient var setICalls = 0 @Transient var getTransCalls = 0 @Transient var setTransCalls = 0 fun method() { // touch some fields val b2 = b i = 2 t = 1 t2 = 2 } }
apache-2.0
paronos/tachiyomi
app/src/main/java/eu/kanade/tachiyomi/widget/SimpleAnimationListener.kt
5
323
package eu.kanade.tachiyomi.widget import android.view.animation.Animation open class SimpleAnimationListener : Animation.AnimationListener { override fun onAnimationRepeat(animation: Animation) {} override fun onAnimationEnd(animation: Animation) {} override fun onAnimationStart(animation: Animation) {} }
apache-2.0
blackbbc/Tucao
app/src/main/kotlin/me/sweetll/tucao/business/splash/SplashActivity.kt
1
1414
package me.sweetll.tucao.business.splash import android.content.Intent import android.os.Bundle import android.os.Handler import androidx.appcompat.app.AppCompatActivity import dagger.android.AndroidInjection import io.reactivex.schedulers.Schedulers import me.sweetll.tucao.AppApplication import me.sweetll.tucao.business.home.MainActivity import me.sweetll.tucao.di.service.ApiConfig import me.sweetll.tucao.di.service.RawApiService import javax.inject.Inject class SplashActivity : AppCompatActivity() { @Inject lateinit var rawApiService: RawApiService override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) AndroidInjection.inject(this) if (!isTaskRoot && intent.hasCategory(Intent.CATEGORY_LAUNCHER) && intent.action != null && intent.action == Intent.ACTION_MAIN) { finish() return } // Just to fetch cookie rawApiService.userInfo() .retryWhen(ApiConfig.RetryWithDelay()) .subscribeOn(Schedulers.io()) .subscribe({}, {}) Handler().postDelayed({ val intent = Intent(this, MainActivity::class.java) startActivity(intent) overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out) finish() }, 1500) } }
mit
valich/intellij-markdown
src/fileBasedTest/kotlin/org/intellij/markdown/HtmlGeneratorCommonTest.kt
1
6343
package org.intellij.markdown import org.intellij.markdown.ast.ASTNode import org.intellij.markdown.flavours.commonmark.CommonMarkFlavourDescriptor import org.intellij.markdown.flavours.gfm.GFMFlavourDescriptor import org.intellij.markdown.flavours.space.SFMFlavourDescriptor import org.intellij.markdown.html.* import kotlin.test.* class HtmlGeneratorCommonTest : HtmlGeneratorTestBase() { override fun getTestDataPath(): String { return getIntellijMarkdownHome() + "/${MARKDOWN_TEST_DATA_PATH}/html" } @Test fun testSimple() { defaultTest() } @Test fun testMarkers() { defaultTest() } @Test fun testTightLooseLists() { defaultTest() } @Test fun testPuppetApache() { defaultTest() } @Test fun testGoPlugin() { defaultTest() } @Test fun testHeaders() { defaultTest() } @Test fun testCodeFence() { defaultTest() } @Test fun testEscaping() { defaultTest() } @Test fun testHtmlBlocks() { defaultTest() } @Test fun testLinks() { defaultTest() } @Test fun testBlockquotes() { defaultTest() } @Test fun testExample226() { defaultTest() } @Test fun testExample2() { defaultTest() } @Test fun testEntities() { defaultTest() } @Test fun testImages() { defaultTest(tagRenderer = HtmlGenerator.DefaultTagRenderer(customizer = { node, _, attributes -> when { node.type == MarkdownElementTypes.IMAGE -> attributes + "style=\"max-width: 100%\"" else -> attributes } }, includeSrcPositions = false)) } @Test fun testRuby17052() { defaultTest() } @Test fun testRuby17351() { defaultTest(GFMFlavourDescriptor()) } @Test fun testBug28() { defaultTest(GFMFlavourDescriptor()) } @Test fun testStrikethrough() { defaultTest(GFMFlavourDescriptor()) } @Test fun testGfmAutolink() { defaultTest(GFMFlavourDescriptor()) } @Test fun testSfmAutolink() { defaultTest(SFMFlavourDescriptor(false)) } @Test fun testGfmTable() { defaultTest(GFMFlavourDescriptor()) } @Test fun testCheckedLists() { defaultTest(GFMFlavourDescriptor()) } @Test fun testGitBook() { defaultTest() } @Test fun testBaseUriHttp() { defaultTest(baseURI = URI("http://example.com/foo/bar.html")) } @Test fun testBaseUriRelativeRoot() { defaultTest(baseURI = URI("/user/repo-name/blob/master")) } @Test fun testBaseUriRelativeNoRoot() { defaultTest(baseURI = URI("user/repo-name/blob/master")) } @Test fun testBaseUriWithBadRelativeUrl() { try { generateHtmlFromFile(baseURI = URI("user/repo-name/blob/master")) } catch (t: Throwable) { fail("Expected to work without exception, got: $t") } } @Test fun testBaseUriWithAnchorLink() { defaultTest(baseURI = URI("/user/repo-name/blob/master")) } @Test fun testBaseUriWithAnchorLinkForceResolve() { defaultTest(baseURI = URI("/user/repo-name/blob/master"), flavour = CommonMarkFlavourDescriptor(absolutizeAnchorLinks = true)) } @Test fun testCustomRenderer() { defaultTest(tagRenderer = object: HtmlGenerator.TagRenderer { override fun openTag(node: ASTNode, tagName: CharSequence, vararg attributes: CharSequence?, autoClose: Boolean): CharSequence { return "OPEN TAG($tagName)\n" } override fun closeTag(tagName: CharSequence): CharSequence { return "CLOSE TAG($tagName)\n" } override fun printHtml(html: CharSequence): CharSequence { return "HTML($html)\n" } }) } @Test fun testXssProtection() { val disallowedLinkMd1 = "[Click me](javascript:alert(document.domain))" val disallowedLinkMd2 = "[Click me](file:///123)" val disallowedLinkMd3 = "[Click me]( VBSCRIPT:alert(1))" val disallowedLinkMd4 = "<VBSCRIPT:alert(1))>" val disallowedLinkHtml = """ <body><p><a href="#">Click me</a></p></body> """.trimIndent() val disallowedAutolinkHtml = """ <body><p><a href="#">VBSCRIPT:alert(1))</a></p></body> """.trimIndent() assertEqualsIgnoreLines(disallowedLinkHtml, generateHtmlFromString(disallowedLinkMd1)) assertEqualsIgnoreLines(disallowedLinkHtml, generateHtmlFromString(disallowedLinkMd2)) assertEqualsIgnoreLines(disallowedLinkHtml, generateHtmlFromString(disallowedLinkMd3)) assertEqualsIgnoreLines(disallowedAutolinkHtml, generateHtmlFromString(disallowedLinkMd4)) val disallowedImgMd = "![](javascript:alert('XSS');)" val disallowedImgHtml = """ <body><p><img src="#" alt="" /></p></body> """.trimIndent() assertEqualsIgnoreLines(disallowedImgHtml, generateHtmlFromString(disallowedImgMd)) val allowedImgMd = "![](data:image/gif;base64,R0lGODlhEAAQAMQAAORHHOVSKudfOulrSOp3WOyDZu6QdvCchPGolfO0o/XBs/fNwfjZ0frl3/zy7////wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACH5BAkAABAALAAAAAAQABAAAAVVICSOZGlCQAosJ6mu7fiyZeKqNKToQGDsM8hBADgUXoGAiqhSvp5QAnQKGIgUhwFUYLCVDFCrKUE1lBavAViFIDlTImbKC5Gm2hB0SlBCBMQiB0UjIQA7)" val allowedImgHtml = """ <body><p><img src="data:image/gif;base64,R0lGODlhEAAQAMQAAORHHOVSKudfOulrSOp3WOyDZu6QdvCchPGolfO0o/XBs/fNwfjZ0frl3/zy7////wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACH5BAkAABAALAAAAAAQABAAAAVVICSOZGlCQAosJ6mu7fiyZeKqNKToQGDsM8hBADgUXoGAiqhSvp5QAnQKGIgUhwFUYLCVDFCrKUE1lBavAViFIDlTImbKC5Gm2hB0SlBCBMQiB0UjIQA7" alt="" /></p></body> """.trimIndent() assertEqualsIgnoreLines(allowedImgHtml, generateHtmlFromString(allowedImgMd)) } } private fun assertEqualsIgnoreLines(expected: String, actual: String) { return assertEquals(expected.replace("\n", ""), actual.replace("\n", "")) }
apache-2.0
alashow/music-android
modules/data/src/main/java/tm/alashow/data/db/BaseTypeConverters.kt
1
709
/* * Copyright (C) 2019, Alashov Berkeli * All rights reserved. */ package tm.alashow.data.db import androidx.room.TypeConverter import org.threeten.bp.LocalDateTime import org.threeten.bp.format.DateTimeFormatter import tm.alashow.domain.models.Params object BaseTypeConverters { private val localDateFormat = DateTimeFormatter.ISO_LOCAL_DATE_TIME @TypeConverter @JvmStatic fun fromParams(params: Params) = params.toString() @TypeConverter @JvmStatic fun toLocalDateTime(value: String): LocalDateTime = LocalDateTime.parse(value, localDateFormat) @TypeConverter @JvmStatic fun fromLocalDateTime(value: LocalDateTime): String = localDateFormat.format(value) }
apache-2.0
GlimpseFramework/glimpse-framework
api/src/test/kotlin/glimpse/gles/DisposableSpec.kt
1
1203
package glimpse.gles import com.nhaarman.mockito_kotlin.* import glimpse.test.GlimpseSpec class DisposableSpec : GlimpseSpec() { init { "Disposable object" should { "be disposed if registered by calling `Disposables.register()`" { val disposable = disposableMock() Disposables.register(disposable) Disposables.disposeAll() verify(disposable).dispose() } "be disposed if registered by calling `registerDisposable()`" { val disposable = disposableMock() disposable.registerDisposable() Disposables.disposeAll() verify(disposable).dispose() } "not be disposed if not registered" { val disposable = disposableMock() Disposables.disposeAll() verify(disposable, never()).dispose() } "be disposed only once" { val disposable = disposableMock() disposable.registerDisposable() repeat(10) { Disposables.disposeAll() } verify(disposable, times(1)).dispose() } } } fun disposableMock(): Disposable { val disposableMock = mock<DisposableImpl>() doCallRealMethod().`when`(disposableMock).registerDisposable() return disposableMock } open class DisposableImpl : Disposable { override fun dispose() { } } }
apache-2.0
rock3r/detekt
detekt-rules/src/test/resources/cases/IteratorImplPositive.kt
2
1291
@file:Suppress("unused", "ConstantConditionIf") package cases // reports IteratorNotThrowingNoSuchElementException, IteratorHasNextCallsNextMethod class IteratorImpl2 : Iterator<String> { override fun hasNext(): Boolean { next() return true } override fun next(): String { return "" } } class IteratorImplContainer { // reports IteratorNotThrowingNoSuchElementException, IteratorHasNextCallsNextMethod object IteratorImplNegative3 : Iterator<String> { override fun hasNext(): Boolean { next() return true } override fun next(): String { throw IllegalStateException() } } } // reports IteratorNotThrowingNoSuchElementException, IteratorHasNextCallsNextMethod interface InterfaceIterator : Iterator<String> { override fun hasNext(): Boolean { next() return true } override fun next(): String { return "" } } // reports IteratorNotThrowingNoSuchElementException, IteratorHasNextCallsNextMethod abstract class AbstractIterator : Iterator<String> { override fun hasNext(): Boolean { if (true) { next() } return true } override fun next(): String { return "" } }
apache-2.0
rock3r/detekt
detekt-api/src/main/kotlin/io/gitlab/arturbosch/detekt/api/MultiRule.kt
1
1131
package io.gitlab.arturbosch.detekt.api import io.gitlab.arturbosch.detekt.api.internal.BaseRule import org.jetbrains.kotlin.psi.KtFile /** * Composite rule which delegates work to child rules. * Can be used to combine different rules which do similar work like * scanning the source code line by line to increase performance. */ abstract class MultiRule : BaseRule() { abstract val rules: List<Rule> var activeRules: Set<Rule> by SingleAssign() override fun visitCondition(root: KtFile): Boolean = true override fun preVisit(root: KtFile) { activeRules = rules.filterTo(HashSet(rules.size)) { it.visitCondition(root) } } override fun postVisit(root: KtFile) { for (activeRule in activeRules) { report(activeRule.findings, activeRule.aliases, activeRule.ruleSetId) } } /** * Preferred way to run child rules because this composite rule * takes care of evaluating if a specific child should be run at all. */ fun <T : Rule> T.runIfActive(block: T.() -> Unit) { if (this in activeRules) { block() } } }
apache-2.0
fan123199/V2ex-simple
app/src/main/java/im/fdx/v2ex/ui/main/MyViewPagerAdapter.kt
1
2204
package im.fdx.v2ex.ui.main import android.content.Context import androidx.core.os.bundleOf import androidx.fragment.app.FragmentManager import androidx.fragment.app.FragmentStatePagerAdapter import com.google.gson.Gson import com.google.gson.reflect.TypeToken import im.fdx.v2ex.R import im.fdx.v2ex.myApp import im.fdx.v2ex.pref import im.fdx.v2ex.ui.Tab import im.fdx.v2ex.utils.Keys import im.fdx.v2ex.utils.Keys.PREF_TAB import org.jetbrains.anko.collections.forEachWithIndex import java.util.* /** * Created by fdx on 2015/10/15. * 从MainActivity分离出来. 用了FragmentStatePagerAdapter 替代FragmentPagerAdapter,才可以动态切换Fragment * 弃用了Volley 和 模拟web + okhttp * * todo pageadapter有更新,明天需要完成 */ internal class MyViewPagerAdapter( fm: FragmentManager, private val mContext: Context) : FragmentStatePagerAdapter(fm, BEHAVIOR_SET_USER_VISIBLE_HINT ) { private val mFragments = ArrayList<TopicsFragment>() private val tabList = mutableListOf<Tab>() init { initFragment() } fun initFragment() { tabList.clear() mFragments.clear() var jsonData = pref.getString(PREF_TAB, null) if (jsonData == null) { val tabTitles = mContext.resources.getStringArray(R.array.v2ex_favorite_tab_titles) val tabPaths = mContext.resources.getStringArray(R.array.v2ex_favorite_tab_paths) val list = MutableList(tabTitles.size) { index: Int -> Tab(tabTitles[index], tabPaths[index]) } jsonData = Gson().toJson(list) } val turnsType = object : TypeToken<List<Tab>>() {}.type val list = Gson().fromJson<List<Tab>>(jsonData, turnsType) for (it in list) { if (!myApp.isLogin && it.path == "recent") { continue } mFragments.add(TopicsFragment().apply { arguments = bundleOf(Keys.KEY_TAB to it.path) }) tabList.add(it) } } override fun getItem(position: Int) = mFragments[position] override fun getCount() = tabList.size override fun getPageTitle(position: Int) = tabList[position].title }
apache-2.0
pdvrieze/ProcessManager
PE-common/src/commonMain/kotlin/nl/adaptivity/process/userMessageHandler/server/UserTask.kt
1
1589
/* * Copyright (c) 2018. * * This file is part of ProcessManager. * * ProcessManager is free software: you can redistribute it and/or modify it under the terms of version 3 of the * GNU Lesser General Public License as published by the Free Software Foundation. * * ProcessManager 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License along with ProcessManager. If not, * see <http://www.gnu.org/licenses/>. */ package nl.adaptivity.process.userMessageHandler.server import net.devrieze.util.Handle import net.devrieze.util.MutableHandleAware import nl.adaptivity.messaging.EndpointDescriptorImpl import nl.adaptivity.process.engine.processModel.NodeInstanceState import nl.adaptivity.util.security.Principal interface UserTask<T : UserTask<T>> : MutableHandleAware<T> { interface TaskItem { val options: List<String> val value: String? val type: String? val name: String? val params: String? val label: String? } val state: NodeInstanceState? fun setState(newState: NodeInstanceState, user: Principal) fun setEndpoint(endPoint: EndpointDescriptorImpl) val owner: Principal? val items: List<TaskItem> val remoteHandle: Handle<*> val instanceHandle: Handle<*> val handleValue: Long val summary: String? }
lgpl-3.0
pdvrieze/ProcessManager
JavaCommonApi/src/jsMain/kotlin/nl/adaptivity/util/security/Principal.kt
1
892
/* * Copyright (c) 2018. * * This file is part of ProcessManager. * * ProcessManager is free software: you can redistribute it and/or modify it under the terms of version 3 of the * GNU Lesser General Public License as published by the Free Software Foundation. * * ProcessManager 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License along with ProcessManager. If not, * see <http://www.gnu.org/licenses/>. */ package nl.adaptivity.util.security actual interface Principal { /** * Returns the name of this principal. * * @return the name of this principal. */ actual fun getName(): String }
lgpl-3.0
pdvrieze/ProcessManager
ProcessEngine/core/src/jvmTest/kotlin/nl/adaptivity/process/engine/test/loanOrigination/datatypes/LoanEvaluation.kt
1
985
/* * Copyright (c) 2019. * * This file is part of ProcessManager. * * ProcessManager is free software: you can redistribute it and/or modify it under the terms of version 3 of the * GNU Lesser General Public License as published by the Free Software Foundation. * * ProcessManager 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License along with ProcessManager. If not, * see <http://www.gnu.org/licenses/>. */ package nl.adaptivity.process.engine.test.loanOrigination.datatypes import kotlinx.serialization.Serializable @Serializable data class LoanEvaluation( val customerId: String, val application: LoanApplication, val isApproved: Boolean, val message: String ) { }
lgpl-3.0
wordpress-mobile/WordPress-Stores-Android
plugins/woocommerce/src/main/kotlin/org/wordpress/android/fluxc/network/rest/wpcom/wc/inbox/InboxRestClient.kt
2
4228
package org.wordpress.android.fluxc.network.rest.wpcom.wc.inbox import android.content.Context import com.android.volley.RequestQueue import org.wordpress.android.fluxc.Dispatcher import org.wordpress.android.fluxc.generated.endpoint.WOOCOMMERCE import org.wordpress.android.fluxc.model.SiteModel import org.wordpress.android.fluxc.network.UserAgent import org.wordpress.android.fluxc.network.rest.wpcom.BaseWPComRestClient import org.wordpress.android.fluxc.network.rest.wpcom.auth.AccessToken import org.wordpress.android.fluxc.network.rest.wpcom.jetpacktunnel.JetpackTunnelGsonRequestBuilder import org.wordpress.android.fluxc.network.rest.wpcom.jetpacktunnel.JetpackTunnelGsonRequestBuilder.JetpackResponse.JetpackError import org.wordpress.android.fluxc.network.rest.wpcom.jetpacktunnel.JetpackTunnelGsonRequestBuilder.JetpackResponse.JetpackSuccess import org.wordpress.android.fluxc.network.rest.wpcom.wc.WooPayload import org.wordpress.android.fluxc.network.rest.wpcom.wc.toWooError import javax.inject.Inject import javax.inject.Named import javax.inject.Singleton @Singleton class InboxRestClient @Inject constructor( dispatcher: Dispatcher, private val jetpackTunnelGsonRequestBuilder: JetpackTunnelGsonRequestBuilder, appContext: Context?, @Named("regular") requestQueue: RequestQueue, accessToken: AccessToken, userAgent: UserAgent ) : BaseWPComRestClient(appContext, dispatcher, requestQueue, accessToken, userAgent) { suspend fun fetchInboxNotes( site: SiteModel, page: Int, pageSize: Int, inboxNoteTypes: Array<String> ): WooPayload<Array<InboxNoteDto>> { val url = WOOCOMMERCE.admin.notes.pathV4Analytics val response = jetpackTunnelGsonRequestBuilder.syncGetRequest( this, site, url, mapOf( "page" to page.toString(), "per_page" to pageSize.toString(), "type" to inboxNoteTypes.joinToString(separator = ",") ), Array<InboxNoteDto>::class.java ) return when (response) { is JetpackSuccess -> WooPayload(response.data) is JetpackError -> WooPayload(response.error.toWooError()) } } suspend fun markInboxNoteAsActioned( site: SiteModel, inboxNoteId: Long, inboxNoteActionId: Long ): WooPayload<InboxNoteDto> { val url = WOOCOMMERCE.admin.notes.note(inboxNoteId) .action.item(inboxNoteActionId).pathV4Analytics val response = jetpackTunnelGsonRequestBuilder.syncPostRequest( this, site, url, emptyMap(), InboxNoteDto::class.java ) return when (response) { is JetpackSuccess -> WooPayload(response.data) is JetpackError -> WooPayload(response.error.toWooError()) } } suspend fun deleteNote( site: SiteModel, inboxNoteId: Long ): WooPayload<Unit> { val url = WOOCOMMERCE.admin.notes.delete.note(inboxNoteId).pathV4Analytics val response = jetpackTunnelGsonRequestBuilder.syncDeleteRequest( this, site, url, Unit::class.java ) return when (response) { is JetpackError -> WooPayload(response.error.toWooError()) is JetpackSuccess -> WooPayload(Unit) } } suspend fun deleteAllNotesForSite( site: SiteModel, page: Int, pageSize: Int, inboxNoteTypes: Array<String> ): WooPayload<Unit> { val url = WOOCOMMERCE.admin.notes.delete.all.pathV4Analytics val response = jetpackTunnelGsonRequestBuilder.syncDeleteRequest( this, site, url, Array<InboxNoteDto>::class.java, mapOf( "page" to page.toString(), "per_page" to pageSize.toString(), "type" to inboxNoteTypes.joinToString(separator = ",") ) ) return when (response) { is JetpackError -> WooPayload(response.error.toWooError()) is JetpackSuccess -> WooPayload(Unit) } } }
gpl-2.0
ccomeaux/boardgamegeek4android
app/src/main/java/com/boardgamegeek/ui/CommentsFragment.kt
1
2887
package com.boardgamegeek.ui import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.core.view.isVisible import androidx.fragment.app.Fragment import androidx.fragment.app.activityViewModels import androidx.lifecycle.lifecycleScope import androidx.paging.LoadState import androidx.paging.PagingData import androidx.recyclerview.widget.DividerItemDecoration import com.boardgamegeek.R import com.boardgamegeek.databinding.FragmentCommentsBinding import com.boardgamegeek.ui.adapter.GameCommentsPagedListAdapter import com.boardgamegeek.ui.viewmodel.GameCommentsViewModel import kotlinx.coroutines.launch class CommentsFragment : Fragment() { private var _binding: FragmentCommentsBinding? = null private val binding get() = _binding!! private val viewModel by activityViewModels<GameCommentsViewModel>() private val adapter by lazy { GameCommentsPagedListAdapter() } @Suppress("RedundantNullableReturnType") override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { _binding = FragmentCommentsBinding.inflate(inflater, container, false) return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) binding.recyclerView.setHasFixedSize(true) binding.recyclerView.addItemDecoration(DividerItemDecoration(context, DividerItemDecoration.VERTICAL)) binding.recyclerView.adapter = adapter adapter.addLoadStateListener { loadStates -> when (val state = loadStates.refresh) { is LoadState.Loading -> { binding.progressView.show() } is LoadState.NotLoading -> { binding.emptyView.setText(R.string.empty_comments) binding.emptyView.isVisible = adapter.itemCount == 0 binding.recyclerView.isVisible = adapter.itemCount > 0 binding.progressView.hide() } is LoadState.Error -> { binding.emptyView.text = state.error.localizedMessage binding.emptyView.isVisible = true binding.recyclerView.isVisible = false binding.progressView.hide() } } } viewModel.comments.observe(viewLifecycleOwner) { comments -> lifecycleScope.launch { adapter.submitData(comments) binding.recyclerView.isVisible = true } } } override fun onDestroyView() { super.onDestroyView() _binding = null } fun clear() { lifecycleScope.launch { adapter.submitData(PagingData.empty()) } } }
gpl-3.0
xafero/dynkt
dynkt/src/test/java/com/xafero/dynkt/hello1.kt
1
161
import java.io.* fun main(args: Array<String>) { val map = ctx as MutableMap<String, Any> val out = map["out"] as PrintWriter out.println("Hello, World!") }
agpl-3.0
wordpress-mobile/WordPress-Stores-Android
plugins/woocommerce/src/main/kotlin/org/wordpress/android/fluxc/network/rest/wpcom/wc/coupons/CouponRestClient.kt
2
8291
package org.wordpress.android.fluxc.network.rest.wpcom.wc.coupons import android.content.Context import com.android.volley.RequestQueue import org.wordpress.android.fluxc.Dispatcher import org.wordpress.android.fluxc.generated.endpoint.WOOCOMMERCE import org.wordpress.android.fluxc.model.SiteModel import org.wordpress.android.fluxc.model.coupon.UpdateCouponRequest import org.wordpress.android.fluxc.network.BaseRequest.GenericErrorType.UNKNOWN import org.wordpress.android.fluxc.network.UserAgent import org.wordpress.android.fluxc.network.rest.wpcom.BaseWPComRestClient import org.wordpress.android.fluxc.network.rest.wpcom.auth.AccessToken import org.wordpress.android.fluxc.network.rest.wpcom.jetpacktunnel.JetpackTunnelGsonRequestBuilder import org.wordpress.android.fluxc.network.rest.wpcom.jetpacktunnel.JetpackTunnelGsonRequestBuilder.JetpackResponse.JetpackError import org.wordpress.android.fluxc.network.rest.wpcom.jetpacktunnel.JetpackTunnelGsonRequestBuilder.JetpackResponse.JetpackSuccess import org.wordpress.android.fluxc.network.rest.wpcom.wc.WooError import org.wordpress.android.fluxc.network.rest.wpcom.wc.WooErrorType.API_ERROR import org.wordpress.android.fluxc.network.rest.wpcom.wc.WooPayload import org.wordpress.android.fluxc.network.rest.wpcom.wc.toWooError import java.text.SimpleDateFormat import java.util.Date import java.util.Locale import javax.inject.Inject import javax.inject.Named import javax.inject.Singleton @Singleton class CouponRestClient @Inject constructor( dispatcher: Dispatcher, private val jetpackTunnelGsonRequestBuilder: JetpackTunnelGsonRequestBuilder, appContext: Context?, @Named("regular") requestQueue: RequestQueue, accessToken: AccessToken, userAgent: UserAgent ) : BaseWPComRestClient(appContext, dispatcher, requestQueue, accessToken, userAgent) { suspend fun fetchCoupons( site: SiteModel, page: Int, pageSize: Int, searchQuery: String? = null ): WooPayload<Array<CouponDto>> { val url = WOOCOMMERCE.coupons.pathV3 val response = jetpackTunnelGsonRequestBuilder.syncGetRequest( restClient = this, site = site, url = url, params = mutableMapOf<String, String>().apply { put("page", page.toString()) put("per_page", pageSize.toString()) searchQuery?.let { put("search", searchQuery) } }, clazz = Array<CouponDto>::class.java ) return when (response) { is JetpackSuccess -> { WooPayload(response.data) } is JetpackError -> { WooPayload(response.error.toWooError()) } } } suspend fun fetchCoupon( site: SiteModel, couponId: Long ): WooPayload<CouponDto> { val url = WOOCOMMERCE.coupons.id(couponId).pathV3 val response = jetpackTunnelGsonRequestBuilder.syncGetRequest( this, site, url, emptyMap(), CouponDto::class.java ) return when (response) { is JetpackSuccess -> { WooPayload(response.data) } is JetpackError -> { WooPayload(response.error.toWooError()) } } } suspend fun createCoupon( site: SiteModel, request: UpdateCouponRequest ): WooPayload<CouponDto> { val url = WOOCOMMERCE.coupons.pathV3 val params = request.toNetworkRequest() val response = jetpackTunnelGsonRequestBuilder.syncPostRequest( this, site, url, params, CouponDto::class.java ) return when (response) { is JetpackSuccess -> { WooPayload(response.data) } is JetpackError -> { WooPayload(response.error.toWooError()) } } } suspend fun updateCoupon( site: SiteModel, couponId: Long, request: UpdateCouponRequest ): WooPayload<CouponDto> { val url = WOOCOMMERCE.coupons.id(couponId).pathV3 val params = request.toNetworkRequest() val response = jetpackTunnelGsonRequestBuilder.syncPutRequest( this, site, url, params, CouponDto::class.java ) return when (response) { is JetpackSuccess -> { WooPayload(response.data) } is JetpackError -> { WooPayload(response.error.toWooError()) } } } suspend fun deleteCoupon( site: SiteModel, couponId: Long, trash: Boolean ): WooPayload<Unit> { val url = WOOCOMMERCE.coupons.id(couponId).pathV3 val response = jetpackTunnelGsonRequestBuilder.syncDeleteRequest( restClient = this, site = site, url = url, clazz = Unit::class.java, params = mapOf("force" to trash.not().toString()) ) return when (response) { is JetpackError -> WooPayload(response.error.toWooError()) is JetpackSuccess -> WooPayload(Unit) } } suspend fun fetchCouponsReports( site: SiteModel, couponsIds: LongArray = longArrayOf(), after: Date ): WooPayload<List<CouponReportDto>> { val url = WOOCOMMERCE.reports.coupons.pathV4Analytics val dateFormatter = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss", Locale.ROOT) val params = mapOf( "after" to dateFormatter.format(after), "coupons" to couponsIds.joinToString(",") ) val response = jetpackTunnelGsonRequestBuilder.syncGetRequest( restClient = this, site = site, url = url, params = params, clazz = Array<CouponReportDto>::class.java ) return when (response) { is JetpackError -> WooPayload(response.error.toWooError()) is JetpackSuccess -> WooPayload(response.data?.toList()) } } suspend fun fetchCouponReport( site: SiteModel, couponId: Long, after: Date ): WooPayload<CouponReportDto> { return fetchCouponsReports( site = site, couponsIds = longArrayOf(couponId), after = after ).let { when { it.isError -> WooPayload(it.error) it.result.isNullOrEmpty() -> WooPayload( WooError(API_ERROR, UNKNOWN, "Empty coupons report response") ) else -> WooPayload(it.result.first()) } } } @Suppress("ComplexMethod") private fun UpdateCouponRequest.toNetworkRequest(): Map<String, Any> { return mutableMapOf<String, Any>().apply { code?.let { put("code", it) } amount?.let { put("amount", it) } discountType?.let { put("discount_type", it) } description?.let { put("description", it) } expiryDate?.let { put("date_expires", it) } minimumAmount?.let { put("minimum_amount", it) } maximumAmount?.let { put("maximum_amount", it) } productIds?.let { put("product_ids", it) } excludedProductIds?.let { put("excluded_product_ids", it) } isShippingFree?.let { put("free_shipping", it) } productCategoryIds?.let { put("product_categories", it) } excludedProductCategoryIds?.let { put("excluded_product_categories", it) } restrictedEmails?.let { put("email_restrictions", it) } isForIndividualUse?.let { put("individual_use", it) } areSaleItemsExcluded?.let { put("exclude_sale_items", it) } // The following fields can have empty value. When updating a Coupon, // the REST API accepts and treats `0` as empty for these fields. put("usage_limit", usageLimit ?: 0) put("usage_limit_per_user", usageLimitPerUser ?: 0) put("limit_usage_to_x_items", limitUsageToXItems ?: 0) } } }
gpl-2.0
LanternPowered/LanternServer
src/main/kotlin/org/lanternpowered/server/network/NetworkContext.kt
1
832
/* * Lantern * * Copyright (c) LanternPowered <https://www.lanternpowered.org> * Copyright (c) SpongePowered <https://www.spongepowered.org> * Copyright (c) contributors * * This work is licensed under the terms of the MIT License (MIT). For * a copy, see 'LICENSE.txt' or <https://opensource.org/licenses/MIT>. */ package org.lanternpowered.server.network import io.netty.channel.Channel import org.lanternpowered.server.LanternGame import org.lanternpowered.server.LanternServer interface NetworkContext { /** * The [NetworkSession] that is targeted. */ val session: NetworkSession /** * The [Channel] that is targeted. */ val channel: Channel val server: LanternServer get() = this.session.server val game: LanternGame get() = this.session.server.game }
mit
kantega/niagara
niagara-data/src/main/kotlin/org/kantega/niagara/data/equals.kt
1
125
package org.kantega.niagara.data typealias Equals<A> = (A, A) -> Boolean fun <A> equals(): Equals<A> = { a, b -> a == b }
apache-2.0
rarnu/deprecated_project
src/main/kotlin/com/rarnu/tophighlight/xposed/Versions.kt
1
3538
package com.rarnu.tophighlight.xposed /** * Created by rarnu on 1/26/17. */ object Versions { // global var inited = false // top highlight color var conversationAdapter = "" var userInfoMethod = "" var topInfoMethod = "" var topInfoField = "" // statusbar immersion var mmFragmentActivity = "" var chatUIActivity = "" var expectImmersionList = arrayListOf<String>() var getAppCompact = "" var getActionBar = "" var dividerId = 0 var actionBarViewId = 0 var customizeActionBar = "" var actionBarContainer = "" // tab var bottomTabView = "" // top mac or reader & etc. var topMacActivity = "" var topReaderActivity = "" var topMacMethod = "" var topMacField = "" var topReaderMethod = "" var topReaderField = "" var topReaderViewId = 0 // settings var settingActivity = "" var settingPreference = "" var settingListField = "" var settingAddMethod = "" // global resource var colorToChange = arrayListOf<Int>() fun initVersion(idx: Int) { when (idx) { 0 -> { // 654 conversationAdapter = "com.tencent.mm.ui.conversation.b" userInfoMethod = "en" topInfoMethod = "j" topInfoField = "oLH" mmFragmentActivity = "com.tencent.mm.ui.MMFragmentActivity" chatUIActivity = "com.tencent.mm.ui.chatting.ChattingUI\$a" // bottomTab bottomTabView = "com.tencent.mm.ui.LauncherUIBottomTabView" // top mac or reader topMacActivity = "com.tencent.mm.ui.d.m" topReaderActivity = "com.tencent.mm.ui.d.o" topMacMethod = "aii" topMacField = "ejD" topReaderMethod = "setVisibility" topReaderField = "view" topReaderViewId = 0x7f101472 // settings settingActivity = "com.tencent.mm.plugin.setting.ui.setting.SettingsAboutSystemUI" settingPreference = "com.tencent.mm.ui.base.preference.Preference" settingListField = "oHs" settingAddMethod = "a" expectImmersionList = arrayListOf( "com.tencent.mm.plugin.luckymoney.ui.LuckyMoneyIndexUI", "com.tencent.mm.plugin.luckymoney.ui.LuckyMoneyPrepareUI", "com.tencent.mm.plugin.luckymoney.ui.LuckyMoneyDetailUI", "com.tencent.mm.plugin.collect.ui.CollectMainUI", "com.tencent.mm.plugin.offline.ui.WalletOfflineCoinPurseUI", "com.tencent.mm.plugin.luckymoney.ui.LuckyMoneyMyRecordUI") // in mmfragmentactivity getAppCompact = "cU" getActionBar = "cV" dividerId = 2131755267 actionBarViewId = 2131755252 // in chatui customizeActionBar = "bIT" actionBarContainer = "oZl" colorToChange = arrayListOf( 2131231135, 2131231148, 2131689968, 2131689977, 2131690035, 2131690068, 2131690069, 2131690072, 2131690082) inited = true } } } }
gpl-3.0
LanternPowered/LanternServer
src/main/kotlin/org/lanternpowered/server/util/palette/GlobalRegistryPalette.kt
1
1628
/* * Lantern * * Copyright (c) LanternPowered <https://www.lanternpowered.org> * Copyright (c) SpongePowered <https://www.spongepowered.org> * Copyright (c) contributors * * This work is licensed under the terms of the MIT License (MIT). For * a copy, see 'LICENSE.txt' or <https://opensource.org/licenses/MIT>. */ package org.lanternpowered.server.util.palette import org.lanternpowered.api.catalog.CatalogType import org.lanternpowered.api.util.palette.GlobalPalette import org.lanternpowered.server.registry.InternalCatalogTypeRegistry import java.util.function.Supplier /** * Gets this internal catalog type registry as a [GlobalPalette]. */ fun <T : CatalogType> InternalCatalogTypeRegistry<T>.asPalette(default: () -> T): GlobalPalette<T> = asPalette(Supplier(default)) /** * Gets this internal catalog type registry as a [GlobalPalette]. */ fun <T : CatalogType> InternalCatalogTypeRegistry<T>.asPalette(default: Supplier<out T>): GlobalPalette<T> = GlobalRegistryPalette(this, default) private class GlobalRegistryPalette<T : CatalogType>( private val registry: InternalCatalogTypeRegistry<T>, private val defaultSupplier: Supplier<out T> ) : GlobalPalette<T> { override fun getIdOrAssign(obj: T): Int = this.registry.getId(obj) override fun getId(obj: T): Int = this.registry.getId(obj) override fun get(id: Int): T? = this.registry.get(id) override val default: T get() = this.defaultSupplier.get() override val entries: Collection<T> get() = this.registry.all override val size: Int get() = this.registry.all.size }
mit
LISTEN-moe/android-app
app/src/main/kotlin/me/echeung/moemoekyun/ui/view/SongList.kt
1
4706
package me.echeung.moemoekyun.ui.view import android.app.Activity import android.text.Editable import android.text.TextWatcher import android.view.MenuItem import android.view.View import android.widget.EditText import androidx.appcompat.widget.SearchView import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import androidx.swiperefreshlayout.widget.SwipeRefreshLayout import me.echeung.moemoekyun.R import me.echeung.moemoekyun.adapter.SongsListAdapter import me.echeung.moemoekyun.util.SongActionsUtil import me.echeung.moemoekyun.util.SongSortUtil import me.echeung.moemoekyun.viewmodel.SongListViewModel import org.koin.core.component.KoinComponent import org.koin.core.component.inject import java.lang.ref.WeakReference class SongList( activity: Activity, private val songListViewModel: SongListViewModel, private val songsList: RecyclerView, private val swipeRefreshLayout: SwipeRefreshLayout?, filterView: View, listId: String, private val loadSongs: (adapter: SongsListAdapter) -> Unit, ) : KoinComponent { private val songActionsUtil: SongActionsUtil by inject() private val songSortUtil: SongSortUtil by inject() private val activity: WeakReference<Activity> = WeakReference(activity) private val adapter: SongsListAdapter = SongsListAdapter(activity, listId) init { // List adapter songsList.layoutManager = LinearLayoutManager(activity) songsList.adapter = adapter // Pull to refresh if (swipeRefreshLayout != null) { swipeRefreshLayout.setColorSchemeResources(R.color.colorAccent) swipeRefreshLayout.setOnRefreshListener(SwipeRefreshLayout.OnRefreshListener { this.loadSongs() }) swipeRefreshLayout.isRefreshing = false // Only allow pull to refresh when user is at the top of the list songsList.addOnScrollListener( object : RecyclerView.OnScrollListener() { override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) { val topRowVerticalPosition = if (songsList.childCount != 0) { songsList.getChildAt(0).top } else { 0 } swipeRefreshLayout.isEnabled = topRowVerticalPosition >= 0 } }, ) } // Filter if (filterView is EditText) { filterView.addTextChangedListener( object : TextWatcher { override fun beforeTextChanged(charSequence: CharSequence, i: Int, i1: Int, i2: Int) {} override fun onTextChanged(charSequence: CharSequence, i: Int, i1: Int, i2: Int) {} override fun afterTextChanged(editable: Editable) { handleQuery(editable.toString()) } }, ) } if (filterView is SearchView) { filterView.setOnQueryTextListener( object : SearchView.OnQueryTextListener { override fun onQueryTextSubmit(query: String?): Boolean { handleQuery(query!!) return true } override fun onQueryTextChange(newText: String?): Boolean { handleQuery(newText!!) return true } }, ) filterView.setOnCloseListener { handleQuery("") true } } } private fun handleQuery(query: String) { val trimmedQuery = query.trim { it <= ' ' }.lowercase() adapter.filter(trimmedQuery) val hasResults = adapter.itemCount != 0 songListViewModel.hasResults = hasResults if (hasResults) { songsList.scrollToPosition(0) } } fun loadSongs() { loadSongs(adapter) } fun showLoading(loading: Boolean) { swipeRefreshLayout?.isRefreshing = loading } fun notifyDataSetChanged() { adapter.notifyDataSetChanged() } fun handleMenuItemClick(item: MenuItem): Boolean { val activityRef = activity.get() ?: return false if (songSortUtil.handleSortMenuItem(item, adapter)) { return true } if (item.itemId == R.id.action_random_request) { adapter.randomRequestSong?.let { songActionsUtil.request(activityRef, it) } return true } return false } }
mit
Luistlvr1989/authentication
app/src/main/java/com/belatrix/authentication/business/networking/NetworkManager.kt
1
930
package com.belatrix.authentication.business.networking import com.belatrix.authentication.business.injection.scope.ApplicationScope import com.belatrix.authentication.model.dtos.LoginResponse import retrofit2.Call import retrofit2.Callback import retrofit2.Response import timber.log.Timber import javax.inject.Inject /** * Created by ltalavera on 6/1/17. * Handles the basic communication */ @ApplicationScope class NetworkManager @Inject constructor(private val api: AuthenticationApi) { fun login(email: String, password: String) { val call = api.login(email, password) call.enqueue(object : Callback<LoginResponse>{ override fun onResponse(call: Call<LoginResponse>?, response: Response<LoginResponse>?) { Timber.i(response?.body().toString()) } override fun onFailure(call: Call<LoginResponse>?, t: Throwable?) { } }) } }
apache-2.0
damien5314/imgur-shenanigans
app/src/main/java/ddiehl/android/imgurtest/presenters/GalleryPresenter.kt
1
460
package ddiehl.android.imgurtest.presenters import ddiehl.android.imgurtest.model.AbsGalleryItem import ddiehl.android.imgurtest.model.GalleryAlbum import ddiehl.android.imgurtest.model.GalleryImage interface GalleryPresenter : BasePresenter { fun getNumImages(): Int fun getItemAt(position: Int): AbsGalleryItem fun onAlbumClicked(album: GalleryAlbum) fun onImageClicked(image: GalleryImage) fun onSubredditNavigationRequested(subreddit: String) }
apache-2.0
RoverPlatform/rover-android
core/src/main/kotlin/io/rover/sdk/core/routing/TransientLinkLaunchActivity.kt
1
1524
package io.rover.sdk.core.routing import android.os.Bundle import androidx.core.content.ContextCompat import androidx.appcompat.app.AppCompatActivity import io.rover.sdk.core.Rover import io.rover.sdk.core.logging.log import java.net.URI /** * The intent filter you add for your universal links and `rv-$appname://` deep links should by default * point to this activity. */ open class TransientLinkLaunchActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) val rover = Rover.shared if (rover == null) { log.e("A deep or universal link mapped to Rover was opened, but Rover is not initialized. Ignoring.") return } val linkOpen = rover.resolve(LinkOpenInterface::class.java) if (linkOpen == null) { log.e("A deep or universal link mapped to Rover was opened, but LinkOpenInterface is not registered in the Rover container. Ensure ExperiencesAssembler() is in Rover.initialize(). Ignoring.") return } val uri = URI(intent.data.toString()) log.v("Transient link launch activity running for received URI: '${intent.data}'") val intentStack = linkOpen.localIntentForReceived(uri) log.v("Launching stack ${intentStack.size} deep: ${intentStack.joinToString("\n") { it.toString() }}") if (intentStack.isNotEmpty()) ContextCompat.startActivities(this, intentStack.toTypedArray()) finish() } }
apache-2.0
pie-flavor/Pieconomy
src/main/kotlin/flavor/pie/pieconomy/PieconomyCurrencyRegistryModule.kt
1
1202
package flavor.pie.pieconomy import com.google.common.collect.HashBiMap import com.google.common.collect.ImmutableList import com.google.common.collect.ImmutableSet import flavor.pie.kludge.* import org.spongepowered.api.registry.AdditionalCatalogRegistryModule import org.spongepowered.api.registry.RegistrationPhase import org.spongepowered.api.registry.util.DelayedRegistration import org.spongepowered.api.service.economy.Currency import java.util.Optional class PieconomyCurrencyRegistryModule(defaults: Set<Currency>) : AdditionalCatalogRegistryModule<Currency> { val defaults: Set<Currency> val currencies: MutableMap<String, Currency> = HashBiMap.create() init { this.defaults = ImmutableSet.copyOf(defaults) } override fun getById(id: String): Optional<Currency> = currencies[id].optional override fun getAll(): Collection<Currency> = ImmutableList.copyOf(currencies.values) override fun registerAdditionalCatalog(extraCatalog: Currency) { currencies[extraCatalog.id] = extraCatalog } @DelayedRegistration(RegistrationPhase.POST_INIT) override fun registerDefaults() { defaults.forEach { currencies[it.id] = it } } }
mit
Mauin/detekt
detekt-core/src/main/kotlin/io/gitlab/arturbosch/detekt/core/processors/ProjectSLOCProcessor.kt
1
855
package io.gitlab.arturbosch.detekt.core.processors import io.gitlab.arturbosch.detekt.api.DetektVisitor import org.jetbrains.kotlin.com.intellij.openapi.util.Key import org.jetbrains.kotlin.psi.KtFile class ProjectSLOCProcessor : AbstractProcessor() { override val visitor: DetektVisitor = SLOCVisitor() override val key: Key<Int> = sourceLinesKey } class SLOCVisitor : DetektVisitor() { override fun visitKtFile(file: KtFile) { val lines = file.text.split('\n') val sloc = SLOC().count(lines) file.putUserData(sourceLinesKey, sloc) } private class SLOC { private val comments = arrayOf("//", "/*", "*/", "*") fun count(lines: List<String>): Int { return lines .map { it.trim() } .filter { trim -> trim.isNotEmpty() && !comments.any { trim.startsWith(it) } } .size } } } val sourceLinesKey = Key<Int>("sloc")
apache-2.0
FHannes/intellij-community
plugins/git4idea/src/git4idea/remote/GitConfigureRemotesDialog.kt
12
11183
/* * Copyright 2000-2016 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * Copyright 2000-2016 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package git4idea.remote import com.intellij.dvcs.DvcsUtil import com.intellij.dvcs.DvcsUtil.sortRepositories import com.intellij.openapi.components.service import com.intellij.openapi.diagnostic.logger import com.intellij.openapi.progress.ProgressIndicator import com.intellij.openapi.progress.ProgressManager import com.intellij.openapi.progress.Task import com.intellij.openapi.project.Project import com.intellij.openapi.ui.DialogWrapper import com.intellij.openapi.ui.DialogWrapper.IdeModalityType.IDE import com.intellij.openapi.ui.DialogWrapper.IdeModalityType.PROJECT import com.intellij.openapi.ui.Messages import com.intellij.openapi.ui.Messages.* import com.intellij.openapi.util.registry.Registry import com.intellij.ui.ColoredTableCellRenderer import com.intellij.ui.SimpleTextAttributes import com.intellij.ui.ToolbarDecorator import com.intellij.ui.table.JBTable import com.intellij.util.ui.JBUI import com.intellij.util.ui.UIUtil.DEFAULT_HGAP import git4idea.commands.Git import git4idea.commands.GitCommandResult import git4idea.repo.GitRemote import git4idea.repo.GitRemote.ORIGIN import git4idea.repo.GitRepository import java.awt.Dimension import java.awt.Font import java.util.* import javax.swing.* import javax.swing.table.AbstractTableModel class GitConfigureRemotesDialog(val project: Project, val repositories: Collection<GitRepository>) : DialogWrapper(project, true, getModalityType()) { private val git = service<Git>() private val LOG = logger<GitConfigureRemotesDialog>() private val NAME_COLUMN = 0 private val URL_COLUMN = 1 private val REMOTE_PADDING = 30 private val table = JBTable(RemotesTableModel()) private var nodes = buildNodes(repositories) init { init() title = "Git Remotes" updateTableWidth() } override fun createActions() = arrayOf(okAction) override fun getPreferredFocusedComponent() = table override fun createCenterPanel(): JComponent? { table.selectionModel = DefaultListSelectionModel() table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION) table.intercellSpacing = JBUI.emptySize() table.setDefaultRenderer(Any::class.java, MyCellRenderer()) return ToolbarDecorator.createDecorator(table). setAddAction { addRemote() }. setRemoveAction { removeRemote() }. setEditAction { editRemote() }. setEditActionUpdater { isRemoteSelected() }. setRemoveActionUpdater { isRemoteSelected() }. disableUpDownActions().createPanel() } private fun addRemote() { val repository = getSelectedRepo() val proposedName = if (repository.remotes.any { it.name == ORIGIN }) "" else ORIGIN val dialog = GitDefineRemoteDialog(repository, git, proposedName, "") if (dialog.showAndGet()) { runInModalTask("Adding Remote...", repository, "Add Remote", "Couldn't add remote ${dialog.remoteName} '${dialog.remoteUrl}'") { git.addRemote(repository, dialog.remoteName, dialog.remoteUrl) } } } private fun removeRemote() { val remoteNode = getSelectedRemote()!! val remote = remoteNode.remote if (YES == showYesNoDialog(rootPane, "Remove remote ${remote.name} '${getUrl(remote)}'?", "Remove Remote", getQuestionIcon())) { runInModalTask("Removing Remote...", remoteNode.repository, "Remove Remote", "Couldn't remove remote $remote") { git.removeRemote(remoteNode.repository, remote) } } } private fun editRemote() { val remoteNode = getSelectedRemote()!! val remote = remoteNode.remote val repository = remoteNode.repository val oldName = remote.name val oldUrl = getUrl(remote) val dialog = GitDefineRemoteDialog(repository, git, oldName, oldUrl) if (dialog.showAndGet()) { val newRemoteName = dialog.remoteName val newRemoteUrl = dialog.remoteUrl if (newRemoteName == oldName && newRemoteUrl == oldUrl) return runInModalTask("Changing Remote...", repository, "Change Remote", "Couldn't change remote $oldName to $newRemoteName '$newRemoteUrl'") { changeRemote(repository, oldName, oldUrl, newRemoteName, newRemoteUrl) } } } private fun changeRemote(repo: GitRepository, oldName: String, oldUrl: String, newName: String, newUrl: String): GitCommandResult { var result : GitCommandResult? = null if (newName != oldName) { result = git.renameRemote(repo, oldName, newName) if (!result.success()) return result } if (newUrl != oldUrl) { result = git.setRemoteUrl(repo, newName, newUrl) // NB: remote name has just been changed } return result!! // at least one of two has changed } private fun updateTableWidth() { var maxNameWidth = 30 var maxUrlWidth = 250 for (node in nodes) { val fontMetrics = table.getFontMetrics(UIManager.getFont("Table.font").deriveFont(Font.BOLD)) val nameWidth = fontMetrics.stringWidth(node.getPresentableString()) val remote = (node as? RemoteNode)?.remote val urlWidth = if (remote == null) 0 else fontMetrics.stringWidth(getUrl(remote)) if (maxNameWidth < nameWidth) maxNameWidth = nameWidth if (maxUrlWidth < urlWidth) maxUrlWidth = urlWidth } maxNameWidth += REMOTE_PADDING + DEFAULT_HGAP table.columnModel.getColumn(NAME_COLUMN).preferredWidth = maxNameWidth table.columnModel.getColumn(URL_COLUMN).preferredWidth = maxUrlWidth val defaultPreferredHeight = table.rowHeight*(table.rowCount+3) table.preferredScrollableViewportSize = Dimension(maxNameWidth + maxUrlWidth + DEFAULT_HGAP, defaultPreferredHeight) } private fun buildNodes(repositories: Collection<GitRepository>): List<Node> { val nodes = mutableListOf<Node>() for (repository in sortRepositories(repositories)) { if (repositories.size > 1) nodes.add(RepoNode(repository)) for (remote in sortedRemotes(repository)) { nodes.add(RemoteNode(remote, repository)) } } return nodes } private fun sortedRemotes(repository: GitRepository): List<GitRemote> { return repository.remotes.sortedWith(Comparator<GitRemote> { r1, r2 -> if (r1.name == ORIGIN) { if (r2.name == ORIGIN) 0 else -1 } else if (r2.name == ORIGIN) 1 else r1.name.compareTo(r2.name) }) } private fun rebuildTable() { nodes = buildNodes(repositories) (table.model as RemotesTableModel).fireTableDataChanged() } private fun runInModalTask(title: String, repository: GitRepository, errorTitle: String, errorMessage: String, operation: () -> GitCommandResult) { ProgressManager.getInstance().run(object : Task.Modal(project, title, true) { private var result: GitCommandResult? = null override fun run(indicator: ProgressIndicator) { result = operation() repository.update() } override fun onSuccess() { rebuildTable() if (result == null || !result!!.success()) { val errorDetails = if (result == null) "operation was not executed" else result!!.errorOutputAsJoinedString val message = "$errorMessage in $repository:\n$errorDetails" LOG.warn(message) Messages.showErrorDialog(myProject, message, errorTitle) } } }) } private fun getSelectedRepo(): GitRepository { val selectedRow = table.selectedRow if (selectedRow < 0) return sortRepositories(repositories).first() val value = nodes[selectedRow] if (value is RepoNode) return value.repository if (value is RemoteNode) return value.repository throw IllegalStateException("Unexpected selected value: $value") } private fun getSelectedRemote() : RemoteNode? { val selectedRow = table.selectedRow if (selectedRow < 0) return null return nodes[selectedRow] as? RemoteNode } private fun isRemoteSelected() = getSelectedRemote() != null private fun getUrl(remote: GitRemote) = remote.urls.firstOrNull() ?: "" private abstract class Node { abstract fun getPresentableString() : String } private class RepoNode(val repository: GitRepository) : Node() { override fun toString() = repository.presentableUrl override fun getPresentableString() = DvcsUtil.getShortRepositoryName(repository) } private class RemoteNode(val remote: GitRemote, val repository: GitRepository) : Node() { override fun toString() = remote.name override fun getPresentableString() = remote.name } private inner class RemotesTableModel() : AbstractTableModel() { override fun getRowCount() = nodes.size override fun getColumnCount() = 2 override fun getColumnName(column: Int): String { if (column == NAME_COLUMN) return "Name" else return "URL" } override fun getValueAt(rowIndex: Int, columnIndex: Int): Any { val node = nodes[rowIndex] when { columnIndex == NAME_COLUMN -> return node node is RepoNode -> return "" node is RemoteNode -> return getUrl(node.remote) else -> { LOG.error("Unexpected position at row $rowIndex and column $columnIndex") return "" } } } } private inner class MyCellRenderer : ColoredTableCellRenderer() { override fun customizeCellRenderer(table: JTable?, value: Any?, selected: Boolean, hasFocus: Boolean, row: Int, column: Int) { if (value is RepoNode) { append(value.getPresentableString(), SimpleTextAttributes.REGULAR_BOLD_ATTRIBUTES) } else if (value is RemoteNode) { if (repositories.size > 1) append("", SimpleTextAttributes.REGULAR_ATTRIBUTES, REMOTE_PADDING, SwingConstants.LEFT) append(value.getPresentableString()) } else if (value is String) { append(value) } border = null } } } private fun getModalityType() = if (Registry.`is`("ide.perProjectModality")) PROJECT else IDE
apache-2.0
colriot/anko
dsl/test/org/jetbrains/android/anko/functional/FunctionalTestsForSdk19.kt
1
2209
package org.jetbrains.android.anko.functional import org.jetbrains.android.anko.config.* import org.junit.Test class FunctionalTestsForSdk19 : AbstractFunctionalTest() { val version = "sdk19" @Test fun testComplexListenerClassTest() { runFunctionalTest("ComplexListenerClassTest.kt", AnkoFile.LISTENERS, version) { files.add(AnkoFile.LISTENERS) tunes.add(ConfigurationTune.COMPLEX_LISTENER_CLASSES) } } @Test fun testComplexListenerSetterTest() { runFunctionalTest("ComplexListenerSetterTest.kt", AnkoFile.LISTENERS, version) { files.add(AnkoFile.LISTENERS) tunes.add(ConfigurationTune.COMPLEX_LISTENER_SETTERS) } } @Test fun testLayoutsTest() { runFunctionalTest("LayoutsTest.kt", AnkoFile.LAYOUTS, version) { files.add(AnkoFile.LAYOUTS) } } @Test fun testViewTest() { runFunctionalTest("ViewTest.kt", AnkoFile.VIEWS, version) { files.add(AnkoFile.VIEWS) tunes.add(ConfigurationTune.TOP_LEVEL_DSL_ITEMS) tunes.add(ConfigurationTune.HELPER_CONSTRUCTORS) } } @Test fun testPropertyTest() { runFunctionalTest("PropertyTest.kt", AnkoFile.PROPERTIES, version) { files.add(AnkoFile.PROPERTIES) } } @Test fun testServicesTest() { runFunctionalTest("ServicesTest.kt", AnkoFile.SERVICES, version) { files.add(AnkoFile.SERVICES) } } @Test fun testSimpleListenerTest() { runFunctionalTest("SimpleListenerTest.kt", AnkoFile.LISTENERS, version) { files.add(AnkoFile.LISTENERS) tunes.add(ConfigurationTune.SIMPLE_LISTENERS) } } @Test fun testInterfaceWorkaroundsTest() { runFunctionalTest("InterfaceWorkaroundsTest.kt", AnkoFile.INTERFACE_WORKAROUNDS_JAVA, version) { files.add(AnkoFile.INTERFACE_WORKAROUNDS_JAVA) } } @Test fun testSqlParserHelpersTest() { runFunctionalTest("SqlParserHelpersTest.kt", AnkoFile.SQL_PARSER_HELPERS, version) { files.add(AnkoFile.SQL_PARSER_HELPERS) } } }
apache-2.0
hartwigmedical/hmftools
paddle/src/test/kotlin/com/hartwig/hmftools/paddle/mutation/MutationsTest.kt
1
1187
package com.hartwig.hmftools.paddle.mutation import com.hartwig.hmftools.paddle.Impact import com.hartwig.hmftools.paddle.dnds.DndsMutation import com.hartwig.hmftools.paddle.dnds.DndsMutationTest import com.hartwig.hmftools.paddle.dnds.DndsMutationTest.Companion.GENE import org.junit.Assert object MutationsTest { fun mutation(known: Boolean, impact: Impact): DndsMutation { return DndsMutationTest.dndsMutation(GENE, known, false, 0, impact) } fun synonymousMutation(): DndsMutation { return DndsMutationTest.dndsMutation(GENE, false, false, 0, Impact.SYNONYMOUS) } internal fun assertRedundant(expected: Int, victim: MutationsGene) { Assert.assertEquals(expected, victim.redundant) } internal fun assertEmpty(victim: Mutations) { Assert.assertEquals(0, victim.known) Assert.assertEquals(0, victim.unknown) } internal fun assertMutations(expectedKnown: Int, expectedUnknown: Int, victim: Mutations) { Assert.assertEquals(expectedKnown, victim.known) Assert.assertEquals(expectedUnknown, victim.unknown) Assert.assertEquals(expectedKnown + expectedUnknown, victim.total) } }
gpl-3.0
tasks/tasks
app/src/main/java/org/tasks/sync/AddAccountDialog.kt
1
2012
package org.tasks.sync import android.app.Dialog import android.os.Bundle import androidx.core.os.bundleOf import androidx.fragment.app.DialogFragment import androidx.fragment.app.setFragmentResult import com.google.android.material.composethemeadapter.MdcTheme import dagger.hilt.android.AndroidEntryPoint import org.tasks.R import org.tasks.dialogs.DialogBuilder import org.tasks.extensions.Context.openUri import javax.inject.Inject @AndroidEntryPoint class AddAccountDialog : DialogFragment() { @Inject lateinit var dialogBuilder: DialogBuilder private val hasTasksAccount: Boolean get() = arguments?.getBoolean(EXTRA_HAS_TASKS_ACCOUNT) ?: false enum class Platform { TASKS_ORG, GOOGLE_TASKS, MICROSOFT, DAVX5, CALDAV, ETESYNC, DECSYNC_CC } override fun onCreateDialog(savedInstanceState: Bundle?): Dialog { return dialogBuilder .newDialog() .setTitle(R.string.choose_synchronization_service) .setContent { MdcTheme { org.tasks.compose.AddAccountDialog( hasTasksAccount = hasTasksAccount, selected = this::selected ) } } .setNeutralButton(R.string.help) { _, _ -> activity?.openUri(R.string.help_url_sync) } .setNegativeButton(R.string.cancel, null) .show() } private fun selected(platform: Platform) { setFragmentResult(ADD_ACCOUNT, bundleOf(EXTRA_SELECTED to platform)) dismiss() } companion object { const val ADD_ACCOUNT = "add_account" const val EXTRA_SELECTED = "selected" private const val EXTRA_HAS_TASKS_ACCOUNT = "extra_has_tasks_account" fun newAccountDialog(hasTasksAccount: Boolean) = AddAccountDialog().apply { arguments = bundleOf(EXTRA_HAS_TASKS_ACCOUNT to hasTasksAccount) } } }
gpl-3.0
sys1yagi/mastodon4j
mastodon4j/src/main/java/com/sys1yagi/mastodon4j/api/entity/auth/AccessToken.kt
1
416
package com.sys1yagi.mastodon4j.api.entity.auth import com.google.gson.annotations.SerializedName class AccessToken( @SerializedName("access_token") var accessToken: String = "", @SerializedName("token_type") var tokenType: String = "", @SerializedName("scope") var scope: String = "", @SerializedName("created_at") var createdAt: Long = 0L) { }
mit
natanieljr/droidmate
project/pcComponents/core/src/main/kotlin/org/droidmate/device/IMonitorClient.kt
1
1354
// DroidMate, an automated execution generator for Android apps. // Copyright (C) 2012-2018. Saarland University // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. // // Current Maintainers: // Nataniel Borges Jr. <nataniel dot borges at cispa dot saarland> // Jenny Hotzkow <jenny dot hotzkow at cispa dot saarland> // // Former Maintainers: // Konrad Jamrozik <jamrozik at st dot cs dot uni-saarland dot de> // // web: www.droidmate.org package org.droidmate.device import org.droidmate.device.error.DeviceException interface IMonitorClient { @Throws(DeviceException::class) fun anyMonitorIsReachable(): Boolean @Throws(DeviceException::class) fun closeMonitorServers() fun getPort(): Int @Throws(DeviceException::class) fun forwardPorts() }
gpl-3.0
RoyalDev/Fictitious
src/main/kotlin/org/royaldev/fictitious/commands/impl/StopCommand.kt
1
1686
/* * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package org.royaldev.fictitious.commands.impl import com.google.common.collect.Sets import org.kitteh.irc.client.library.element.User import org.kitteh.irc.client.library.event.channel.ChannelMessageEvent import org.kitteh.irc.client.library.event.helper.ActorEvent import org.royaldev.fictitious.FictitiousBot import org.royaldev.fictitious.games.FictitiousGame import xyz.cardstock.cardstock.commands.BaseCommand import xyz.cardstock.cardstock.commands.CallInfo import xyz.cardstock.cardstock.commands.Command @Command( name = "stop", aliases = arrayOf( "stopgame" ), description = "Stops a game in the channel", usage = "<command>", commandType = BaseCommand.CommandType.CHANNEL ) class StopCommand(val fictitious: FictitiousBot) : BaseCommand() { override fun run(event: ActorEvent<User>, callInfo: CallInfo, arguments: List<String>) { if (event !is ChannelMessageEvent) return val game = this.fictitious.gameRegistrar.find(event.channel) if (game == null) { event.actor.sendNotice("There is not a game in this channel!") return } val op = event.channel.getUserModes(event.actor).orElseGet { Sets.newHashSet() }.any { it.char == 'o' } if (!op && game.host != game.getPlayer(event.actor, false)) { event.actor.sendNotice("You are neither an op nor the host.") return } game.stop(FictitiousGame.GameEndCause.COMMAND) } }
mpl-2.0
arturbosch/detekt
detekt-core/src/main/kotlin/io/gitlab/arturbosch/detekt/core/suppressors/FunctionSuppressor.kt
1
1442
package io.gitlab.arturbosch.detekt.core.suppressors import io.github.detekt.tooling.api.FunctionSignature import io.gitlab.arturbosch.detekt.api.ConfigAware import org.jetbrains.kotlin.psi.KtElement import org.jetbrains.kotlin.psi.KtNamedFunction import org.jetbrains.kotlin.psi.psiUtil.getStrictParentOfType import org.jetbrains.kotlin.resolve.BindingContext internal fun functionSuppressorFactory(rule: ConfigAware, bindingContext: BindingContext): Suppressor? { val signatures = rule.valueOrDefault("ignoreFunction", emptyList<String>()).map(FunctionSignature::fromString) return if (signatures.isNotEmpty()) { { finding -> val element = finding.entity.ktElement element != null && functionSuppressor(element, bindingContext, signatures) } } else { null } } private fun functionSuppressor( element: KtElement, bindingContext: BindingContext, functionSignatures: List<FunctionSignature>, ): Boolean { return element.isInFunctionNamed(bindingContext, functionSignatures) } private fun KtElement.isInFunctionNamed( bindingContext: BindingContext, methodSignatures: List<FunctionSignature>, ): Boolean { return if (this is KtNamedFunction && methodSignatures.any { it.match(this, bindingContext) }) { true } else { getStrictParentOfType<KtNamedFunction>()?.isInFunctionNamed(bindingContext, methodSignatures) ?: false } }
apache-2.0
LachlanMcKee/gsonpath
compiler/standard/src/test/java/gsonpath/unit/adapter/standard/model/MutableGsonModelTest.kt
1
2621
package gsonpath.unit.adapter.standard.model import gsonpath.adapter.standard.model.* import gsonpath.emptyGsonObject import gsonpath.model.FieldInfo import gsonpath.processingExceptionMatcher import gsonpath.simpleGsonArray import org.hamcrest.CoreMatchers.`is` import org.junit.Assert import org.junit.Rule import org.junit.Test import org.junit.rules.ExpectedException import org.mockito.Mockito.mock class MutableGsonModelTest { @JvmField @Rule val expectedException: ExpectedException = ExpectedException.none() @Test fun testGsonField() { val fieldInfo = mock(FieldInfo::class.java) val mutableGsonField = MutableGsonField(0, fieldInfo, "variable", "path", true) Assert.assertEquals( GsonField(0, fieldInfo, "variable", "path", true), mutableGsonField.toImmutable()) } @Test fun testGsonObject() { val fieldInfo = mock(FieldInfo::class.java) val mutableGsonField = MutableGsonField(0, fieldInfo, "variable", "path", true) val mutableGsonObject = MutableGsonObject() mutableGsonObject.addField("field1", mutableGsonField) mutableGsonObject.addObject("object1", MutableGsonObject()) val array = mutableGsonObject.addArray("array1") array.getObjectAtIndex(0) Assert.assertEquals( GsonObject( mapOf( "field1" to GsonField(0, fieldInfo, "variable", "path", true), "object1" to emptyGsonObject(), "array1" to simpleGsonArray(0, emptyGsonObject()) ) ), mutableGsonObject.toImmutable()) } @Test fun testGsonArray() { val fieldInfo = mock(FieldInfo::class.java) val mutableGsonField = MutableGsonField(0, fieldInfo, "variable", "path", true) val mutableGsonArray = MutableGsonArray() mutableGsonArray.addField(0, mutableGsonField) mutableGsonArray.getObjectAtIndex(1) Assert.assertEquals( GsonArray( mapOf( 0 to GsonField(0, fieldInfo, "variable", "path", true), 1 to emptyGsonObject() ), 1 ), mutableGsonArray.toImmutable()) } @Test fun testInvalidGsonArray() { expectedException.expect(`is`(processingExceptionMatcher(null, "Array should not be empty"))) MutableGsonArray().toImmutable() } }
mit
cwoolner/flex-poker
src/main/kotlin/com/flexpoker/table/command/aggregate/eventproducers/hand/FinishHandIfAppropriateEventProducer.kt
1
545
package com.flexpoker.table.command.aggregate.eventproducers.hand import com.flexpoker.table.command.HandDealerState import com.flexpoker.table.command.aggregate.HandState import com.flexpoker.table.command.events.HandCompletedEvent import com.flexpoker.table.command.events.TableEvent fun finishHandIfAppropriate(state: HandState): List<TableEvent> { return if (state.handDealerState === HandDealerState.COMPLETE) listOf(HandCompletedEvent(state.tableId, state.gameId, state.entityId, state.chipsInBackMap)) else emptyList() }
gpl-2.0
adrcotfas/Goodtime
app/src/main/java/com/apps/adrcotfas/goodtime/statistics/main/HistorySpinnerRangeType.kt
1
707
/* * Copyright 2016-2019 Adrian Cotfas * * 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.apps.adrcotfas.goodtime.statistics.main enum class HistorySpinnerRangeType { DAYS, WEEKS, MONTHS }
apache-2.0
nickthecoder/paratask
paratask-app/src/main/kotlin/uk/co/nickthecoder/paratask/table/TableResults.kt
1
16407
/* ParaTask Copyright (C) 2017 Nick Robinson This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package uk.co.nickthecoder.paratask.table import com.sun.javafx.collections.ImmutableObservableList import com.sun.javafx.scene.control.skin.TableColumnHeader import com.sun.javafx.scene.control.skin.TableViewSkin import com.sun.javafx.scene.control.skin.VirtualFlow import javafx.application.Platform import javafx.collections.transformation.FilteredList import javafx.collections.transformation.SortedList import javafx.geometry.Side import javafx.scene.Node import javafx.scene.control.* import javafx.scene.image.ImageView import javafx.scene.input.KeyEvent import javafx.scene.input.MouseButton import javafx.scene.input.MouseEvent import javafx.util.Callback import uk.co.nickthecoder.paratask.ParaTask import uk.co.nickthecoder.paratask.ParaTaskApp import uk.co.nickthecoder.paratask.gui.DragHelper import uk.co.nickthecoder.paratask.gui.DropHelper import uk.co.nickthecoder.paratask.options.Option import uk.co.nickthecoder.paratask.options.OptionsManager import uk.co.nickthecoder.paratask.options.RowOptionsRunner import uk.co.nickthecoder.paratask.project.AbstractResults import uk.co.nickthecoder.paratask.project.ParataskActions import uk.co.nickthecoder.paratask.project.ResultsTab import uk.co.nickthecoder.paratask.project.ToolPane import uk.co.nickthecoder.paratask.table.filter.RowFilter open class TableResults<R : Any>( final override val tool: TableTool<R>, val list: List<R>, label: String = "Results", val columns: List<Column<R, *>>, val rowFilter: RowFilter<R>? = null, canClose: Boolean = false) : AbstractResults(tool, label, canClose = canClose) { val data = WrappedList(list) val tableView: TableView<WrappedRow<R>> = TableView() override val node = tableView private val codeColumn: TableColumn<WrappedRow<R>, String> = TableColumn("") val runner = RowOptionsRunner<R>(tool) var filteredData: FilteredList<WrappedRow<R>>? = null /** * Used to ensure that the currently selected row is always visible. See move() */ var virtualFlow: VirtualFlow<*>? = null var dropHelper: DropHelper? = null set(v) { field?.cancel() field = v v?.applyTo(tableView) } var dragHelper: DragHelper? = null init { // Find the VitualFlow as soon as the tableView's skin has been set tableView.skinProperty().addListener { _, _, skin -> if (skin is TableViewSkin<*>) { virtualFlow = skin.children.filterIsInstance<VirtualFlow<*>>().firstOrNull() } } } fun selectedRows(): List<R> { return tableView.selectionModel.selectedItems.map { it.row } } override fun attached(resultsTab: ResultsTab, toolPane: ToolPane) { super.attached(resultsTab, toolPane) with(codeColumn) { setCellValueFactory { p -> p.value.codeProperty } isEditable = true setCellFactory({ EditCell(this@TableResults, IdentityConverter()) }) prefWidth = 50.0 } tableView.columns.add(codeColumn) for (column in columns) { if (rowFilter?.filtersColumn(column) == true) { column.graphic = ImageView(ParaTask.imageResource("buttons/filter.png")) } else { column.graphic = null } tableView.columns.add(column) } val sortedList: SortedList<WrappedRow<R>> if (rowFilter == null) { sortedList = SortedList(data) } else { filteredData = FilteredList(data) { rowFilter.accept(it.row) } sortedList = SortedList(filteredData) } sortedList.comparatorProperty().bind(tableView.comparatorProperty()) with(tableView) { items = sortedList isEditable = true selectionModel.selectionMode = SelectionMode.MULTIPLE tableView.addEventFilter(KeyEvent.KEY_PRESSED) { onKeyPressed(it) } rowFactory = Callback { val tableRow = tool.createRow() dragHelper?.applyTo(tableRow) tableRow.setOnMouseClicked { onRowClicked(it, tableRow) } tableRow } } dropHelper?.applyTo(resultsTab) if (rowFilter != null) { tableView.addEventFilter(MouseEvent.MOUSE_PRESSED) { if (it.button == MouseButton.SECONDARY) it.consume() } tableView.addEventFilter(MouseEvent.MOUSE_RELEASED) { tableMouseEvent(it) } } } override fun detaching() { super.detaching() dropHelper?.cancel() } override fun selected() { super.selected() tool.tabDropHelper = dropHelper } override fun deselected() { stopEditing() tool.tabDropHelper = null super.deselected() } fun tableMouseEvent(event: MouseEvent) { if (event.button == MouseButton.SECONDARY) { event.consume() var node: Node? = event.target as Node while (node != null && node !== tableView) { if (node is TableColumnHeader) { changeColumnFilter(node) return } node = node.parent } } } fun changeColumnFilter(tch: TableColumnHeader) { val tchCol = tch.tableColumn val column: Column<R, *>? = if (tchCol is Column<*, *>) { @Suppress("UNCHECKED_CAST") tchCol as Column<R, *> } else { null } rowFilter?.editColumnFilters(column) { Platform.runLater { filteredData?.setPredicate { rowFilter.accept(it.row) } columns.forEach { col -> if (rowFilter.filtersColumn(col)) { col.graphic = ImageView(filterIcon) } else { col.graphic = null } } if (rowFilter.filtersColumn(null)) { codeColumn.graphic = ImageView(filterIcon) } else { codeColumn.graphic = null } } } } fun stopEditing() { tableView.edit(-1, null) } override fun focus() { ParaTaskApp.logFocus("TableResults focus. runLater(...)") Platform.runLater { if (tableView.items.isNotEmpty()) { ParaTaskApp.logFocus("TableResults focus. tableView.requestFocus()") tableView.requestFocus() val index = tableView.selectionModel.focusedIndex if (index < 0) { tableView.selectionModel.clearAndSelect(0) ParaTaskApp.logFocus("TableResults focus. tableView.selectionModel.focus(0)") tableView.selectionModel.focus(0) editOption(0) } else { tableView.selectionModel.select(index) editOption(index) } } } } fun editOption(rowIndex: Int = -1) { val index = if (rowIndex >= 0) rowIndex else tableView.selectionModel.focusedIndex stopEditing() tableView.edit(index, codeColumn) } open fun onRowClicked(event: MouseEvent, tableRow: TableRow<WrappedRow<R>>) { contextMenu.hide() if (tableRow.item != null) { if (event.button == MouseButton.PRIMARY) { when (event.clickCount) { 1 -> { // Edit the tabelRow's option field editOption(tableRow.index) } 2 -> { runner.runDefault(tableRow.item.row) } } } else if (event.button == MouseButton.MIDDLE) { runner.runDefault(tableRow.item.row, newTab = true) } else if (event.button == MouseButton.SECONDARY) { showContextMenu(tableRow, event) } } } fun showContextMenu(node: Node, event: Any) { val rows = tableView.selectionModel.selectedItems.map { it.row } runner.buildContextMenu(contextMenu, rows) if (event is MouseEvent) { contextMenu.show(node, Side.BOTTOM, event.x, 0.0) } else { contextMenu.show(node, Side.BOTTOM, 0.0, 0.0) } } val contextMenu = ContextMenu() /** * Looks for shortcuts for the row-options, and passes control to super if no row-base options were found. * If the option found only matches SOME of the selected rows, then the rows that match will be unselected, * leaving the unmatches rows selected. For example, using a shortcut that has different options for files and * directories, it will only process one half. * The user can then hit the shortcut again to apply the other half. */ override fun checkOptionShortcuts(event: KeyEvent) { val tableRows = tableView.selectionModel.selectedItems if (tableRows.isEmpty()) { return } val topLevelOptions = OptionsManager.getTopLevelOptions(tool.optionsName) topLevelOptions.listFileOptions().forEach { fileOptions -> fileOptions.listOptions().forEach { option -> if (option.isRow) { option.shortcut?.let { shortcut -> if (shortcut.match(event) && fileOptions.acceptRow(tableRows[0].row)) { val acceptedRows = tableRows.filter { fileOptions.acceptRow(it.row) } tableView.selectionModel.clearSelection() tableRows.filter { !acceptedRows.contains(it) }.forEach { tableView.selectionModel.select(it) } runner.runRows(option, acceptedRows.map { it.row }) return } } } } } super.checkOptionShortcuts(event) } open fun onKeyPressed(event: KeyEvent) { if (ParataskActions.PREV_ROW.match(event)) { if (!move(-1)) event.consume() } else if (ParataskActions.NEXT_ROW.match(event)) { if (!move(1)) event.consume() } else if (ParataskActions.SELECT_ROW_UP.match(event)) { if (!move(-1, false)) event.consume() } else if (ParataskActions.SELECT_ROW_DOWN.match(event)) { if (!move(1, false)) event.consume() } else if (ParataskActions.OPTION_RUN.match(event)) { runTableOptions() event.consume() } else if (ParataskActions.OPTION_RUN_NEW_TAB.match(event)) { runTableOptions(newTab = true) event.consume() } else if (ParataskActions.OPTION_PROMPT.match(event)) { runTableOptions(prompt = true) event.consume() } else if (ParataskActions.OPTION_PROMPT_NEW_TAB.match(event)) { runTableOptions(prompt = true, newTab = true) event.consume() } else if (ParataskActions.SELECT_ALL.match(event)) { selectAll() event.consume() } else if (ParataskActions.SELECT_NONE.match(event)) { selectNone() event.consume() } else if (ParataskActions.ESCAPE.match(event)) { event.consume() } } fun move(delta: Int, clearSelection: Boolean = true): Boolean { val row = tableView.selectionModel.focusedIndex + delta if (row < 0 || row >= tableView.items.size) { return false } // We need to run later so the EditCell has a chance to save the textfield to the WrappedRow.code Platform.runLater { if (clearSelection) { tableView.selectionModel.clearSelection() } else { // Copy the code from the old focused row. val code = tableView.items[row - delta].code tableView.items[row].code = code } tableView.selectionModel.select(row) ParaTaskApp.logFocus("TableResults move. tableView.selectionMode.focus(row)") tableView.selectionModel.focus(row) // Ensure the new row is visible virtualFlow?.let { val first = it.firstVisibleCell.index val last = it.lastVisibleCell.index if (row < first || row > last) { it.show(row) } } editOption(row) } return true } fun selectAll() { stopEditing() // We need to run later so the EditCell has a chance to save the textfield to the WrappedRow.code Platform.runLater { val selectedRow = tableView.selectionModel.selectedIndex val code = if (selectedRow >= 0 && selectedRow < tableView.items.count()) tableView.items[selectedRow].code else "" tableView.selectionModel.selectAll() tableView.items.forEach { it.code = code } if (selectedRow >= 0 && selectedRow < tableView.items.count()) { editOption(selectedRow) } } } fun selectNone() { stopEditing() Platform.runLater { val selectedRow = tableView.selectionModel.selectedIndex tableView.selectionModel.clearSelection() tableView.items.forEach { it.code = "" } if (selectedRow >= 0 && selectedRow < tableView.items.count()) { editOption(selectedRow) } } } fun runTableOptions(newTab: Boolean = false, prompt: Boolean = false) { ParaTaskApp.logFocus("TableResults runTableOptions tableView.requestFocus()") // Unfocus from the cell being edited allows it to be committed tableView.requestFocus() Platform.runLater { var foundCode = false val batchOptions = mutableMapOf<Option, MutableList<WrappedRow<R>>>() for (wrappedRow in tableView.items) { val code = wrappedRow.code if (code != "") { foundCode = true val option = OptionsManager.findOptionForRow(code, tool.optionsName, wrappedRow.row) if (option != null) { var list = batchOptions[option] if (list == null) { list = mutableListOf<WrappedRow<R>>() batchOptions.put(option, list) } list.add(wrappedRow) wrappedRow.clearOption() } } } if (batchOptions.isNotEmpty()) { runner.runBatch(batchOptions, newTab = newTab, prompt = prompt) } if (!foundCode) { // Run the "default" option against the current row val rowIndex = tableView.selectionModel.focusedIndex if (rowIndex >= 0) { runner.runDefault(tableView.items[rowIndex].row, newTab = newTab) } } } } companion object { val filterIcon = ParaTask.imageResource("buttons/filter.png") } } class WrappedList<R>(list: List<R>) : ImmutableObservableList<WrappedRow<R>>() { var list = list.map { row: R -> WrappedRow(row) } override fun get(index: Int): WrappedRow<R> = list[index] override val size = list.size }
gpl-3.0
pgutkowski/KGraphQL
src/main/kotlin/com/github/pgutkowski/kgraphql/request/ParsingContext.kt
1
1633
package com.github.pgutkowski.kgraphql.request import com.github.pgutkowski.kgraphql.RequestException data class ParsingContext( val fullString : String, val tokens: List<String>, val fragments: Document.Fragments, private var index : Int = 0, var nestedBrackets: Int = 0, var nestedParenthesis: Int = 0 ) { fun index() = index fun next(delta: Int = 1) { index += delta } fun currentToken() = tokens[index] fun currentTokenOrNull() = tokens.getOrNull(index) fun peekToken(delta: Int = 1) = tokens.getOrNull(index + delta) fun traverseObject(): List<String> { val subTokens = subTokens(tokens, index, "{", "}") next(subTokens.size + 1) return subTokens } fun traverseArguments(): List<String> { val subTokens = subTokens(tokens, index, "(", ")") next(subTokens.size + 1) return subTokens } private fun subTokens(allTokens: List<String>, startIndex: Int, openingToken: String, closingToken: String): List<String> { val tokens = allTokens.subList(startIndex, allTokens.size) var nestedLevel = 0 tokens.forEachIndexed { index, token -> when (token) { openingToken -> nestedLevel++ closingToken -> nestedLevel-- } if (nestedLevel == 0) return tokens.subList(1, index) } throw RequestException("Couldn't find matching closing token") } fun getFullStringIndex(tokenIndex : Int = index) : Int { //TODO: Provide reliable index return tokenIndex } }
mit
06needhamt/Neuroph-Intellij-Plugin
neuroph-plugin/src/com/thomas/needham/neurophidea/consumers/ExportSourceConsumer.kt
1
1889
/* The MIT License (MIT) Copyright (c) 2016 Tom Needham Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.thomas.needham.neurophidea.consumers import com.intellij.ide.util.PropertiesComponent import com.intellij.openapi.vfs.newvfs.impl.VirtualDirectoryImpl import com.intellij.util.Consumer import com.thomas.needham.neurophidea.Constants.SOURCE_TO_EXPORT_LOCATION_KEY import com.thomas.needham.neurophidea.Constants.VERSION_KEY /** * Created by Thomas Needham on 29/05/2016. */ class ExportSourceConsumer : Consumer<VirtualDirectoryImpl?> { constructor() { } companion object Data { @JvmStatic var properties = PropertiesComponent.getInstance() @JvmStatic var version = properties.getValue(VERSION_KEY) @JvmStatic var path: String? = "" } override fun consume(p0: VirtualDirectoryImpl?) { path = p0?.path properties.setValue(SOURCE_TO_EXPORT_LOCATION_KEY, path) } }
mit
nemerosa/ontrack
ontrack-extension-git/src/test/groovy/net/nemerosa/ontrack/extension/git/repository/GitRepositoryHelperIT.kt
1
1262
package net.nemerosa.ontrack.extension.git.repository import net.nemerosa.ontrack.extension.git.AbstractGitTestJUnit4Support import org.junit.Test import org.springframework.beans.factory.annotation.Autowired import kotlin.test.assertEquals import kotlin.test.assertNotNull import kotlin.test.assertNull class GitRepositoryHelperIT : AbstractGitTestJUnit4Support() { @Autowired private lateinit var gitRepositoryHelper: GitRepositoryHelper @Test fun `Getting a branch from its Git branch`() { // Creates a project with two branches // One configured for Git // The other not project { // Branch for Git val configuredBranch = branch { gitBranch("main") } // Branch not configured for Git branch {} // Looking for the "main" branch should return the configured branch assertNotNull(gitRepositoryHelper.findBranchWithProjectAndGitBranch(this, "main")) { assertEquals(configuredBranch.id(), it) } // Looking for any other branch should not return anything assertNull(gitRepositoryHelper.findBranchWithProjectAndGitBranch(this, "release/1.0")) } } }
mit
nemerosa/ontrack
ontrack-extension-indicators/src/main/java/net/nemerosa/ontrack/extension/indicators/ui/graphql/GQLTypeIndicatorCategory.kt
1
3125
package net.nemerosa.ontrack.extension.indicators.ui.graphql import graphql.schema.GraphQLNonNull import graphql.schema.GraphQLObjectType import net.nemerosa.ontrack.extension.indicators.model.IndicatorCategory import net.nemerosa.ontrack.extension.indicators.model.IndicatorTypeService import net.nemerosa.ontrack.extension.indicators.ui.ProjectIndicatorType import net.nemerosa.ontrack.graphql.schema.GQLFieldContributor import net.nemerosa.ontrack.graphql.schema.GQLType import net.nemerosa.ontrack.graphql.schema.GQLTypeCache import net.nemerosa.ontrack.graphql.schema.graphQLFieldContributions import net.nemerosa.ontrack.graphql.support.listType import net.nemerosa.ontrack.graphql.support.stringField import org.springframework.stereotype.Component @Component class GQLTypeIndicatorCategory( private val indicatorType: GQLTypeProjectIndicatorType, private val indicatorSource: GQLTypeIndicatorSource, private val indicatorTypeService: IndicatorTypeService, private val indicatorCategoryReportType: GQLTypeIndicatorCategoryReport, private val indicatorReportingService: GQLIndicatorReportingService, private val fieldContributors: List<GQLFieldContributor> ) : GQLType { override fun createType(cache: GQLTypeCache): GraphQLObjectType = GraphQLObjectType.newObject() .name(typeName) .description("Indicator category") // Core fields .stringField("id", "Indicator category ID") .stringField("name", "Indicator category name") .stringField("deprecated", "Indicator category deprecation reason if any") // Source .field { it.name(IndicatorCategory::source.name) .description("Source for this category") .type(indicatorSource.typeRef) } // List of types in this category .field { it.name("types") .description("List of indicator types belonging to this category.") .type(listType(indicatorType.typeRef)) .dataFetcher { env -> val category = env.getSource<IndicatorCategory>() indicatorTypeService.findByCategory(category).map { ProjectIndicatorType(it) } } } // Reporting for this category .field { it.name("report") .description("Reporting the indicators for the types in this category") .type(GraphQLNonNull(indicatorCategoryReportType.typeRef)) .arguments(indicatorReportingService.arguments) .dataFetcher { env -> val category = env.getSource<IndicatorCategory>() indicatorCategoryReportType.report(category, env) } } // Links .fields(IndicatorCategory::class.java.graphQLFieldContributions(fieldContributors)) // OK .build() override fun getTypeName(): String = INDICATOR_CATEGORY companion object { val INDICATOR_CATEGORY: String = IndicatorCategory::class.java.simpleName } }
mit
Jire/kotmem
src/main/kotlin/org/jire/kotmem/linux/LinuxModule.kt
1
243
package org.jire.kotmem.linux import com.sun.jna.Pointer import org.jire.kotmem.Module class LinuxModule(process: LinuxProcess, pointer: Pointer, override val name: String, override val size: Int) : Module(process, pointer)
lgpl-3.0
alpha-cross/ararat
library/src/main/java/org/akop/ararat/widget/Zoomer.kt
2
3428
/* * Copyright 2013 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 org.akop.ararat.widget import android.content.Context import android.os.SystemClock import android.view.animation.DecelerateInterpolator /** * A simple class that animates double-touch zoom gestures. Functionally similar to a [ ]. */ @Suppress("unused", "MemberVisibilityCanBePrivate") class Zoomer(context: Context) { /** * The interpolator, used for making zooms animate 'naturally.' */ private val interpolator = DecelerateInterpolator() /** * The total animation duration for a zoom. */ private val animationDurationMillis: Int = context.resources.getInteger( android.R.integer.config_shortAnimTime) /** * Returns whether the zoomer has finished zooming. * * @return True if the zoomer has finished zooming, false otherwise. */ var isFinished = true private set /** * The current zoom value; computed by [.computeZoom]. * * @see android.widget.Scroller.getCurrX */ var currZoom: Float = 0f private set /** * The time the zoom started, computed using [SystemClock.elapsedRealtime]. */ private var startRTC: Long = 0 /** * The destination zoom factor. */ private var endZoom: Float = 0f /** * Forces the zoom finished state to the given value. Unlike [.abortAnimation], the * current zoom value isn't set to the ending value. * * @see android.widget.Scroller.forceFinished */ fun forceFinished(finished: Boolean) { isFinished = finished } /** * Aborts the animation, setting the current zoom value to the ending value. * * @see android.widget.Scroller.abortAnimation */ fun abortAnimation() { isFinished = true currZoom = endZoom } /** * Starts a zoom from 1.0 to (1.0 + endZoom). That is, to zoom from 100% to 125%, endZoom should * by 0.25f. * * @see android.widget.Scroller.startScroll */ fun startZoom(endZoom: Float) { startRTC = SystemClock.elapsedRealtime() this.endZoom = endZoom isFinished = false currZoom = 1f } /** * Computes the current zoom level, returning true if the zoom is still active and false if the * zoom has finished. * * @see android.widget.Scroller.computeScrollOffset */ fun computeZoom(): Boolean { if (isFinished) { return false } val tRTC = SystemClock.elapsedRealtime() - startRTC if (tRTC >= animationDurationMillis) { isFinished = true currZoom = endZoom return false } val t = tRTC * 1f / animationDurationMillis currZoom = endZoom * interpolator.getInterpolation(t) return true } }
mit
nemerosa/ontrack
ontrack-model/src/main/java/net/nemerosa/ontrack/model/support/ConfigurationRepository.kt
1
1215
package net.nemerosa.ontrack.model.support import com.fasterxml.jackson.databind.JsonNode interface ConfigurationRepository { /** * Gets the list of items for this configuration class */ fun <T : Configuration<T>> list(configurationClass: Class<T>): List<T> /** * Gets a configuration using its name */ fun <T : Configuration<T>> find(configurationClass: Class<T>, name: String): T? /** * Saves or creates a configuration */ fun <T : Configuration<T>> save(configuration: T): T /** * Deletes a configuration */ fun <T : Configuration<T>> delete(configurationClass: Class<T>, name: String) /** * Method used to migrate existing configurations using their JSON representation as a source * and rewrites them before saving them. * * @param configurationClass Type of the configuration * @param migration This code takes the raw JSON representation and converts it into a new format just before * being saved. If it returns null, the configuration does not have to change. */ fun <T : Configuration<T>> migrate( configurationClass: Class<T>, migration: (raw: JsonNode) -> T? ) }
mit
JLLeitschuh/kotlin-guiced
core/src/test/kotlin/org/jlleitschuh/guice/TypeLiteralTest.kt
1
386
package org.jlleitschuh.guice import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.Test class TypeLiteralTest { @Test fun `should keep type data`() { val keySetType = typeLiteral<Map<Int, String>>().getReturnType(Map::class.java.getMethod("keySet")) assertEquals("java.util.Set<java.lang.Integer>", keySetType.toString()) } }
mit
bihe/mydms-java
Api/src/main/kotlin/net/binggl/mydms/features/filestore/amazon/S3FileService.kt
1
4088
package net.binggl.mydms.features.filestore.amazon import com.amazonaws.AmazonClientException import com.amazonaws.AmazonServiceException import com.amazonaws.auth.AWSStaticCredentialsProvider import com.amazonaws.auth.BasicAWSCredentials import com.amazonaws.regions.Regions import com.amazonaws.services.s3.AmazonS3 import com.amazonaws.services.s3.AmazonS3ClientBuilder import com.amazonaws.services.s3.model.ObjectMetadata import net.binggl.mydms.features.filestore.FileService import net.binggl.mydms.features.filestore.model.FileItem import org.apache.commons.io.IOUtils import org.slf4j.LoggerFactory import org.springframework.beans.factory.annotation.Value import org.springframework.stereotype.Service import java.io.ByteArrayInputStream import java.util.* @Service class S3FileService(@Value("\${aws.accessKey}") private val accessKey: String, @Value("\${aws.secretKey}") private val secretKey: String, @Value("\${aws.bucketName}") private val bucketName: String ) : FileService { private lateinit var s3client: AmazonS3 init { val credentials = BasicAWSCredentials( this.accessKey, this.secretKey ) this.s3client = AmazonS3ClientBuilder .standard() .withCredentials(AWSStaticCredentialsProvider(credentials)) .withRegion(Regions.EU_CENTRAL_1) // no need to configure this one! .build() } /** * use the given file and store it in the S3 backend */ override fun saveFile(file: FileItem): Boolean { var result = false val storagePath = "${file.folderName}/${file.fileName}" try { LOG.debug("Try to upload document to $storagePath.") val meta = ObjectMetadata() meta.contentEncoding = "UTF-8" meta.contentType = file.mimeType meta.contentLength = file.payload.size.toLong() var s3result = this.s3client.putObject( this.bucketName, storagePath, ByteArrayInputStream(file.payload.toByteArray()), meta) LOG.info("Upload operation result. eTag: ${s3result.eTag}") result = true } catch (awsEx: AmazonServiceException) { LOG.info("Could not upload object $storagePath. Reason: ${awsEx.message}") } catch (awsClientEx: AmazonClientException) { LOG.error("Error during interaction with S3: ${awsClientEx.message}", awsClientEx) } return result } /** * retrieve a item from the backend store */ override fun getFile(filePath: String): Optional<FileItem> { var file = Optional.empty<FileItem>() try { LOG.debug("Try to get S3 resource from bucket: ${this.bucketName} using path $filePath.") var fileUrlPath = filePath if (fileUrlPath.startsWith("/")) { fileUrlPath = fileUrlPath.substring(1, fileUrlPath.length) } val parts = fileUrlPath.split("/") val path = parts[0] val fileName = parts[1] val s3object = this.s3client.getObject(bucketName, fileUrlPath) val inputStream = s3object.objectContent val fileObject = FileItem(fileName = fileName, folderName = path, mimeType = s3object.objectMetadata.contentType, payload = IOUtils.toByteArray(inputStream).toTypedArray()) LOG.debug("Got object $fileObject") file = Optional.of(fileObject) } catch (awsEx: AmazonServiceException) { LOG.info("Could not get object $filePath. Reason: ${awsEx.message}") } catch (awsClientEx: AmazonClientException) { LOG.error("Error during interaction with S3: ${awsClientEx.message}", awsClientEx) } return file } companion object { private val LOG = LoggerFactory.getLogger(S3FileService::class.java) } }
apache-2.0
willmadison/AdventOfCode
kotlin/src/main/kotlin/com/willmadison/adventofcode/BathroomCodeDecoder.kt
1
4404
package com.willmadison.adventofcode enum class Movement { UP, DOWN, LEFT, RIGHT, INVALID } class Keypad { private val pad = listOf( listOf(1, 2, 3), listOf(4, 5, 6), listOf(7, 8, 9) ) fun canPress(coordinate: Coordinate) = coordinate.x >= 0 && coordinate.y >= 0 && coordinate.x < pad[0].size && coordinate.y < pad.size fun press(coordinate: Coordinate) = pad[coordinate.x][coordinate.y] } fun Char.parseMovement(): Movement { return when (this) { 'U' -> Movement.UP 'D' -> Movement.DOWN 'L' -> Movement.LEFT 'R' -> Movement.RIGHT else -> Movement.INVALID } } val keypad = Keypad() fun decodeBathRoomInstructions(instructionBlock: String): Int { val instructions = instructionBlock.split("\n") val digits = mutableListOf<Int>() var fingerPosition = Coordinate(1, 1) with (keypad) { instructions.forEach { instruction -> instruction.toCharArray().forEach { step -> val position: Coordinate when (step.parseMovement()) { Movement.UP -> position = fingerPosition.copy(fingerPosition.x - 1) Movement.DOWN -> position = fingerPosition.copy(fingerPosition.x + 1) Movement.LEFT -> position = fingerPosition.copy(y = fingerPosition.y - 1) Movement.RIGHT -> position = fingerPosition.copy(y = fingerPosition.y + 1) Movement.INVALID -> position = fingerPosition } if (canPress(position)) { fingerPosition = position } } digits.add(press(fingerPosition)) } } return digits.joinToString("").toInt() } fun main(args: Array<String>) { val passcode = decodeBathRoomInstructions("""DLRURUDLULRDRUDDRLUUUDLDLDLRLRRDRRRLLLLLDDRRRDRRDRRRLRRURLRDUULRLRRDDLULRLLDUDLULURRLRLDUDLURURLDRDDULDRDRDLDLLULULLDDLRRUDULLUULRRLLLURDRLDDLDDLDRLRRLLRURRUURRRRLUDLRDDDDRDULRLLDDUURDUDRLUDULLUDLUDURRDRDUUUUDDUDLLLRLUULRUURDLRLLRRLRLLDLLRLLRRRURLRRLURRLDLLLUUDURUDDLLUURRDRDRRDLLDDLLRDRDRRLURLDLDRDLURLDULDRURRRUDLLULDUDRURULDUDLULULRRRUDLUURRDURRURRLRRLLRDDUUUUUDUULDRLDLLRRUDRRDULLLDUDDUDUURLRDLULUUDLDRDUUUDDDUDLDURRULUULUUULDRUDDLLLDLULLRLRLUDULLDLLRLDLDDDUUDURDDDLURDRRDDLDRLLRLRR RLDUDURDRLLLLDDRRRURLLLRUUDDLRDRDDDUDLLUDDLRDURLDRDLLDRULDDRLDDDRLDRDDDRLLULDURRRLULDRLRDRDURURRDUDRURLDRLURDRLUULLULLDLUDUDRDRDDLDDDDRDURDLUDRDRURUDDLLLRLDDRURLLUDULULDDLLLDLUDLDULUUDLRLURLDRLURURRDUUDLRDDDDDRLDULUDLDDURDLURLUURDLURLDRURRLDLLRRUDRUULLRLDUUDURRLDURRLRUULDDLDLDUUDDRLDLLRRRUURLLUURURRURRLLLUDLDRRDLUULULUDDULLUDRLDDRURDRDUDULUDRLRRRUULLDRDRLULLLDURURURLURDLRRLLLDRLDUDLLLLDUUURULDDLDLLRRUDDDURULRLLUDLRDLUUDDRDDLLLRLUURLDLRUURDURDDDLLLLLULRRRURRDLUDLUURRDRLRUDUUUURRURLRDRRLRDRDULLDRDRLDURDDUURLRUDDDDDLRLLRUDDDDDURURRLDRRUUUDLURUUDRRDLLULDRRLRRRLUUUD RDRURLLUUDURURDUUULLRDRLRRLRUDDUDRURLLDLUUDLRLLDDURRURLUDUDDURLURLRRURLLURRUDRUDLDRLLURLRUUURRUDDDURRRLULLLLURDLRLLDDRLDRLLRRDLURDLRDLDUDRUULLDUUUDLURRLLRUDDDUUURLURUUDRLRULUURLLRLUDDLLDURULLLDURDLULDLDDUDULUDDULLRDRURDRRLLDLDDDDRUDLDRRLLLRLLLRRULDLRLRLRLLDLRDRDLLUDRDRULDUURRDDDRLLRLDLDRDUDRULUDRDLDLDDLLRULURLLURDLRRDUDLULLDLULLUDRRDDRLRURRLDUDLRRUUDLDRLRLDRLRRDURRDRRDDULURUUDDUUULRLDRLLDURRDLUULLUDRDDDLRUDLRULLDDDLURLURLRDRLLURRRUDLRRLURDUUDRLRUUDUULLRUUUDUUDDUURULDLDLURLRURLRUDLULLULRULDRDRLLLRRDLU RRRRDRLUUULLLRLDDLULRUUURRDRDRURRUURUDUULRULULRDRLRRLURDRRRULUUULRRUUULULRDDLLUURRLLDUDRLRRLDDLDLLDURLLUDLDDRRURLDLULRDUULDRLRDLLDLRULLRULLUDUDUDDUULDLUUDDLUDDUULLLLLURRDRULURDUUUDULRUDLLRUUULLUULLLRUUDDRRLRDUDDRULRDLDLLLLRLDDRRRULULLLDLRLURRDULRDRDUDDRLRLDRRDLRRRLLDLLDULLUDDUDDRULLLUDDRLLRRRLDRRURUUURRDLDLURRDLURULULRDUURLLULDULDUDLLULDDUURRRLDURDLUDURLDDRDUDDLLUULDRRLDLLUDRDURLLDRLDDUDURDLUUUUURRUULULLURLDUUULLRURLLLUURDULLUULDRULLUULRDRUULLRUDLDDLRLURRUUDRLRRRULRUUULRULRRLDLUDRRLL ULRLDLLURDRRUULRDUDDURDDDLRRRURLDRUDDLUDDDLLLRDLRLLRRUUDRRDRUULLLULULUUDRRRDRDRUUUUULRURUULULLULDULURRLURUDRDRUDRURURUDLDURUDUDDDRLRLLLLURULUDLRLDDLRUDDUUDURUULRLLLDDLLLLRRRDDLRLUDDUULRRLLRDUDLLDLRRUUULRLRDLRDUDLLLDLRULDRURDLLULLLRRRURDLLUURUDDURLDUUDLLDDRUUDULDRDRDRDDUDURLRRRRUDURLRRUDUDUURDRDULRLRLLRLUDLURUDRUDLULLULRLLULRUDDURUURDLRUULDURDRRRLLLLLUUUULUULDLDULLRURLUDLDRLRLRLRDLDRUDULDDRRDURDDULRULDRLRULDRLDLLUDLDRLRLRUDRDDR""") println("The bathroom passcode is $passcode.") }
mit
dewarder/Android-Kotlin-Commons
akommons-bindings/src/androidTest/java/com/dewarder/akommons/binding/integer/ActivityIntegerTest.kt
1
409
package com.dewarder.akommons.binding.integer import android.support.test.rule.ActivityTestRule import com.dewarder.akommons.binding.common.integer.BaseIntegerTest import org.junit.Rule class ActivityIntegerTest : BaseIntegerTest() { @get:Rule val activityRule = ActivityTestRule<TestIntegerActivity>(TestIntegerActivity::class.java) override fun getTestableInteger() = activityRule.activity }
apache-2.0
soywiz/korge
korge/src/commonMain/kotlin/com/soywiz/korge/tween/tweenbase.kt
1
8289
package com.soywiz.korge.tween import com.soywiz.klock.* import com.soywiz.korim.color.* import com.soywiz.korma.geom.* import com.soywiz.korma.interpolation.* import kotlin.jvm.* import kotlin.reflect.* @Suppress("UNCHECKED_CAST") data class V2<V>( val key: KMutableProperty0<V>, var initial: V, val end: V, val interpolator: (Double, V, V) -> V, val includeStart: Boolean, val startTime: TimeSpan = 0.nanoseconds, val duration: TimeSpan = TimeSpan.NIL ) { val endTime = startTime + duration.coalesce { 0.nanoseconds } fun init() { if (!includeStart) { initial = key.get() } } fun set(ratio: Double) = key.set(interpolator(ratio, initial, end)) override fun toString(): String = "V2(key=${key.name}, range=[$initial-$end], startTime=$startTime, duration=$duration)" } @JvmName("getInt") operator fun KMutableProperty0<Int>.get(end: Int) = V2(this, this.get(), end, ::_interpolateInt, includeStart = false) @JvmName("getInt") operator fun KMutableProperty0<Int>.get(initial: Int, end: Int) = V2(this, initial, end, ::_interpolateInt, includeStart = true) @JvmName("getMutableProperty") operator fun <V : Interpolable<V>> KMutableProperty0<V>.get(end: V) = V2(this, this.get(), end, ::_interpolateInterpolable, includeStart = false) @JvmName("getMutableProperty") operator fun <V : Interpolable<V>> KMutableProperty0<V>.get(initial: V, end: V) = V2(this, initial, end, ::_interpolateInterpolable, includeStart = true) @PublishedApi internal fun _interpolate(ratio: Double, l: Double, r: Double): Double = when { ratio < 0.0 -> l ratio >= 1.0 -> r else -> ratio.interpolate(l, r) } @PublishedApi internal fun _interpolateInt(ratio: Double, l: Int, r: Int): Int = when { ratio < 0.0 -> l ratio >= 1.0 -> r else -> ratio.interpolate(l, r) } @PublishedApi internal fun <V : Interpolable<V>> _interpolateInterpolable(ratio: Double, l: V, r: V): V = when { ratio < 0.0 -> l ratio >= 1.0 -> r else -> ratio.interpolate(l, r) } @PublishedApi internal fun _interpolateFloat(ratio: Double, l: Float, r: Float): Float = when { ratio < 0.0 -> l ratio >= 1.0 -> r else -> ratio.interpolate(l, r) } @PublishedApi internal fun _interpolateColor(ratio: Double, l: RGBA, r: RGBA): RGBA = RGBA.mixRgba(l, r, ratio) @PublishedApi internal fun _interpolateColorAdd(ratio: Double, l: ColorAdd, r: ColorAdd): ColorAdd = ColorAdd( ratio.interpolate(l.r, r.r), ratio.interpolate(l.g, r.g), ratio.interpolate(l.b, r.b), ratio.interpolate(l.a, r.a) ) @PublishedApi internal fun _interpolateAngle(ratio: Double, l: Angle, r: Angle): Angle = _interpolateAngleAny(ratio, l, r, minimizeAngle = true) @PublishedApi internal fun _interpolateAngleDenormalized(ratio: Double, l: Angle, r: Angle): Angle = _interpolateAngleAny(ratio, l, r, minimizeAngle = false) internal fun _interpolateAngleAny(ratio: Double, l: Angle, r: Angle, minimizeAngle: Boolean = true): Angle { if (!minimizeAngle) return Angle(_interpolate(ratio, l.radians, r.radians)) val ln = l.normalized val rn = r.normalized return when { (rn - ln).absoluteValue <= 180.degrees -> Angle(_interpolate(ratio, ln.radians, rn.radians)) ln < rn -> Angle(_interpolate(ratio, (ln + 360.degrees).radians, rn.radians)).normalized else -> Angle(_interpolate(ratio, ln.radians, (rn + 360.degrees).radians)).normalized } } @PublishedApi internal fun _interpolateTimeSpan(ratio: Double, l: TimeSpan, r: TimeSpan): TimeSpan = _interpolate(ratio, l.milliseconds, r.milliseconds).milliseconds //inline operator fun KMutableProperty0<Float>.get(end: Number) = V2(this, this.get(), end.toFloat(), ::_interpolateFloat) //inline operator fun KMutableProperty0<Float>.get(initial: Number, end: Number) = // V2(this, initial.toFloat(), end.toFloat(), ::_interpolateFloat) inline operator fun KMutableProperty0<Double>.get(end: Double) = V2(this, this.get(), end, ::_interpolate, includeStart = false) inline operator fun KMutableProperty0<Double>.get(initial: Double, end: Double) = V2(this, initial, end, ::_interpolate, true) inline operator fun KMutableProperty0<Double>.get(end: Int) = get(end.toDouble()) inline operator fun KMutableProperty0<Double>.get(initial: Int, end: Int) = get(initial.toDouble(), end.toDouble()) inline operator fun KMutableProperty0<Double>.get(end: Float) = get(end.toDouble()) inline operator fun KMutableProperty0<Double>.get(initial: Float, end: Float) = get(initial.toDouble(), end.toDouble()) inline operator fun KMutableProperty0<Double>.get(end: Long) = get(end.toDouble()) inline operator fun KMutableProperty0<Double>.get(initial: Long, end: Float) = get(initial.toDouble(), end.toDouble()) inline operator fun KMutableProperty0<Double>.get(end: Number) = get(end.toDouble()) inline operator fun KMutableProperty0<Double>.get(initial: Number, end: Number) = get(initial.toDouble(), end.toDouble()) inline operator fun KMutableProperty0<RGBA>.get(end: RGBA) = V2(this, this.get(), end, ::_interpolateColor, includeStart = false) inline operator fun KMutableProperty0<RGBA>.get(initial: RGBA, end: RGBA) = V2(this, initial, end, ::_interpolateColor, includeStart = true) inline operator fun KMutableProperty0<ColorAdd>.get(end: ColorAdd) = V2(this, this.get(), end, ::_interpolateColorAdd, includeStart = false) inline operator fun KMutableProperty0<ColorAdd>.get(initial: ColorAdd, end: ColorAdd) = V2(this, initial, end, ::_interpolateColorAdd, includeStart = true) inline operator fun KMutableProperty0<Angle>.get(end: Angle) = V2(this, this.get(), end, ::_interpolateAngle, includeStart = false) inline operator fun KMutableProperty0<Angle>.get(initial: Angle, end: Angle) = V2(this, initial, end, ::_interpolateAngle, includeStart = true) fun V2<Angle>.denormalized(): V2<Angle> = this.copy(interpolator = ::_interpolateAngleDenormalized) inline operator fun KMutableProperty0<TimeSpan>.get(end: TimeSpan) = V2(this, this.get(), end, ::_interpolateTimeSpan, includeStart = false) inline operator fun KMutableProperty0<TimeSpan>.get(initial: TimeSpan, end: TimeSpan) = V2(this, initial, end, ::_interpolateTimeSpan, includeStart = true) fun <V> V2<V>.easing(easing: Easing): V2<V> = this.copy(interpolator = { ratio, a, b -> this.interpolator(easing(ratio), a, b) }) inline fun <V> V2<V>.delay(startTime: TimeSpan) = this.copy(startTime = startTime) inline fun <V> V2<V>.duration(duration: TimeSpan) = this.copy(duration = duration) inline fun <V> V2<V>.linear() = this inline fun <V> V2<V>.smooth() = this.easing(Easing.SMOOTH) inline fun <V> V2<V>.easeIn() = this.easing(Easing.EASE_IN) inline fun <V> V2<V>.easeOut() = this.easing(Easing.EASE_OUT) inline fun <V> V2<V>.easeInOut() = this.easing(Easing.EASE_IN_OUT) inline fun <V> V2<V>.easeOutIn() = this.easing(Easing.EASE_OUT_IN) inline fun <V> V2<V>.easeInBack() = this.easing(Easing.EASE_IN_BACK) inline fun <V> V2<V>.easeOutBack() = this.easing(Easing.EASE_OUT_BACK) inline fun <V> V2<V>.easeInOutBack() = this.easing(Easing.EASE_IN_OUT_BACK) inline fun <V> V2<V>.easeOutInBack() = this.easing(Easing.EASE_OUT_IN_BACK) inline fun <V> V2<V>.easeInElastic() = this.easing(Easing.EASE_IN_ELASTIC) inline fun <V> V2<V>.easeOutElastic() = this.easing(Easing.EASE_OUT_ELASTIC) inline fun <V> V2<V>.easeInOutElastic() = this.easing(Easing.EASE_IN_OUT_ELASTIC) inline fun <V> V2<V>.easeOutInElastic() = this.easing(Easing.EASE_OUT_IN_ELASTIC) inline fun <V> V2<V>.easeInBounce() = this.easing(Easing.EASE_IN_BOUNCE) inline fun <V> V2<V>.easeOutBounce() = this.easing(Easing.EASE_OUT_BOUNCE) inline fun <V> V2<V>.easeInOutBounce() = this.easing(Easing.EASE_IN_OUT_BOUNCE) inline fun <V> V2<V>.easeOutInBounce() = this.easing(Easing.EASE_OUT_IN_BOUNCE) inline fun <V> V2<V>.easeInQuad() = this.easing(Easing.EASE_IN_QUAD) inline fun <V> V2<V>.easeOutQuad() = this.easing(Easing.EASE_OUT_QUAD) inline fun <V> V2<V>.easeInOutQuad() = this.easing(Easing.EASE_IN_OUT_QUAD) inline fun <V> V2<V>.easeSine() = this.easing(Easing.EASE_SINE) inline fun <V> V2<V>.easeClampStart() = this.easing(Easing.EASE_CLAMP_START) inline fun <V> V2<V>.easeClampEnd() = this.easing(Easing.EASE_CLAMP_END) inline fun <V> V2<V>.easeClampMiddle() = this.easing(Easing.EASE_CLAMP_MIDDLE)
apache-2.0
arslancharyev31/Anko-ExpandableTextView
demo/src/androidTest/java/tm/charlie/expandabletextview/demo/ConfigChangeTest.kt
1
1410
package tm.charlie.expandabletextview.demo import android.support.test.espresso.Espresso.pressBack import android.support.test.rule.ActivityTestRule import android.support.test.runner.AndroidJUnit4 import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith @RunWith(AndroidJUnit4::class) class ConfigChangeTest: ITest { @Rule @JvmField val mActivityRule = ActivityTestRule<KotlinActivity>(KotlinActivity::class.java) @Test fun orientationChangeTest() { // In Kotlin Activity clickOnExpandableTextView() checkIfExpanded() rotateLandscape() checkIfExpanded() clickOnView(currentActivity.getString(R.string.open_java_activity)) // In Java Activity clickOnExpandableTextView() checkIfExpanded() rotateLandscape() checkIfExpanded() clickOnExpandableTextView() checkIfCollapsed() pressBack() checkIfExpanded() // In Kotlin Activity rotatePortrait() checkIfExpanded() clickOnExpandableTextView() checkIfCollapsed() } @Test fun orientationStateChangeTest(){ clickOnExpandableTextView() checkIfExpanded() selectSpinnerItem(R.id.spinner_collapsed_lines, 0)// 1 checkIfExpanded() selectSpinnerItem(R.id.spinner_demo_text, 1)// "2 lines text in portrait, 1 line in landscape" checkIfExpanded() rotateLandscape(1000) checkIfStatic() rotatePortrait() checkIfCollapsed() // Should it be Expanded? } }
mit
tibbi/Simple-Calculator
app/src/main/kotlin/com/simplemobiletools/calculator/activities/MainActivity.kt
1
6073
package com.simplemobiletools.calculator.activities import android.content.Context import android.content.Intent import android.os.Bundle import android.view.Menu import android.view.MenuItem import android.view.View import android.view.WindowManager import com.simplemobiletools.calculator.BuildConfig import com.simplemobiletools.calculator.R import com.simplemobiletools.calculator.extensions.config import com.simplemobiletools.calculator.extensions.updateViewColors import com.simplemobiletools.calculator.helpers.* import com.simplemobiletools.commons.extensions.* import com.simplemobiletools.commons.helpers.LICENSE_AUTOFITTEXTVIEW import com.simplemobiletools.commons.helpers.LICENSE_ESPRESSO import com.simplemobiletools.commons.helpers.LICENSE_ROBOLECTRIC import com.simplemobiletools.commons.models.FAQItem import com.simplemobiletools.commons.models.Release import kotlinx.android.synthetic.main.activity_main.* import me.grantland.widget.AutofitHelper class MainActivity : SimpleActivity(), Calculator { private var storedTextColor = 0 private var vibrateOnButtonPress = true lateinit var calc: CalculatorImpl override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) appLaunched(BuildConfig.APPLICATION_ID) calc = CalculatorImpl(this, applicationContext) btn_plus.setOnClickListener { calc.handleOperation(PLUS); checkHaptic(it) } btn_minus.setOnClickListener { calc.handleOperation(MINUS); checkHaptic(it) } btn_multiply.setOnClickListener { calc.handleOperation(MULTIPLY); checkHaptic(it) } btn_divide.setOnClickListener { calc.handleOperation(DIVIDE); checkHaptic(it) } btn_percent.setOnClickListener { calc.handleOperation(PERCENT); checkHaptic(it) } btn_power.setOnClickListener { calc.handleOperation(POWER); checkHaptic(it) } btn_root.setOnClickListener { calc.handleOperation(ROOT); checkHaptic(it) } btn_clear.setOnClickListener { calc.handleClear(); checkHaptic(it) } btn_clear.setOnLongClickListener { calc.handleReset(); true } getButtonIds().forEach { it.setOnClickListener { calc.numpadClicked(it.id); checkHaptic(it) } } btn_equals.setOnClickListener { calc.handleEquals(); checkHaptic(it) } formula.setOnLongClickListener { copyToClipboard(false) } result.setOnLongClickListener { copyToClipboard(true) } AutofitHelper.create(result) AutofitHelper.create(formula) storeStateVariables() updateViewColors(calculator_holder, config.textColor) checkWhatsNewDialog() checkAppOnSDCard() } override fun onResume() { super.onResume() if (storedTextColor != config.textColor) { updateViewColors(calculator_holder, config.textColor) } if (config.preventPhoneFromSleeping) { window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON) } vibrateOnButtonPress = config.vibrateOnButtonPress } override fun onPause() { super.onPause() storeStateVariables() if (config.preventPhoneFromSleeping) { window.clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON) } } override fun onCreateOptionsMenu(menu: Menu): Boolean { menuInflater.inflate(R.menu.menu, menu) menu.findItem(R.id.scientific_calculator).isVisible = false // not implemented yet return true } override fun onOptionsItemSelected(item: MenuItem): Boolean { when (item.itemId) { R.id.settings -> launchSettings() R.id.about -> launchAbout() R.id.scientific_calculator -> launchScientific() else -> return super.onOptionsItemSelected(item) } return true } private fun storeStateVariables() { config.apply { storedTextColor = textColor } } private fun checkHaptic(view: View) { if (vibrateOnButtonPress) { view.performHapticFeedback() } } private fun launchSettings() { startActivity(Intent(applicationContext, SettingsActivity::class.java)) } private fun launchScientific() { startActivity(Intent(applicationContext, ScientificActivity::class.java)) } private fun launchAbout() { val licenses = LICENSE_AUTOFITTEXTVIEW or LICENSE_ROBOLECTRIC or LICENSE_ESPRESSO val faqItems = arrayListOf( FAQItem(R.string.faq_1_title, R.string.faq_1_text), FAQItem(R.string.faq_1_title_commons, R.string.faq_1_text_commons), FAQItem(R.string.faq_4_title_commons, R.string.faq_4_text_commons), FAQItem(R.string.faq_2_title_commons, R.string.faq_2_text_commons), FAQItem(R.string.faq_6_title_commons, R.string.faq_6_text_commons) ) startAboutActivity(R.string.app_name, licenses, BuildConfig.VERSION_NAME, faqItems, true) } private fun getButtonIds() = arrayOf(btn_decimal, btn_0, btn_1, btn_2, btn_3, btn_4, btn_5, btn_6, btn_7, btn_8, btn_9) private fun copyToClipboard(copyResult: Boolean): Boolean { var value = formula.value if (copyResult) { value = result.value } return if (value.isEmpty()) { false } else { copyToClipboard(value) true } } override fun setValue(value: String, context: Context) { result.text = value } private fun checkWhatsNewDialog() { arrayListOf<Release>().apply { add(Release(18, R.string.release_18)) checkWhatsNew(this, BuildConfig.VERSION_CODE) } } // used only by Robolectric override fun setValueDouble(d: Double) { calc.setValue(Formatter.doubleToString(d)) calc.lastKey = DIGIT } override fun setFormula(value: String, context: Context) { formula.text = value } }
gpl-2.0
izmajlowiczl/Expensive
storage/src/main/java/pl/expensive/storage/_Seeds.kt
1
1808
package pl.expensive.storage import android.database.sqlite.SQLiteDatabase import pl.expensive.storage._LabelSeeds.FOOD import pl.expensive.storage._LabelSeeds.HOUSEHOLD import pl.expensive.storage._LabelSeeds.RENT import pl.expensive.storage._LabelSeeds.TRANSPORT import pl.expensive.storage._Seeds.CHF import pl.expensive.storage._Seeds.CZK import pl.expensive.storage._Seeds.EUR import pl.expensive.storage._Seeds.GBP import pl.expensive.storage._Seeds.PLN import java.util.* object _Seeds { val EUR = CurrencyDbo("EUR", "##.##\u00a0\u20ac") val GBP = CurrencyDbo("GBP", "\u00a3##.##") val CHF = CurrencyDbo("CHF", "##.##\u00a0CHF") val PLN = CurrencyDbo("PLN", "##.##\u00a0zł") val CZK = CurrencyDbo("CZK", "##.##\u00a0K\u010d") } object _LabelSeeds { val FOOD = LabelDbo(UUID.fromString("78167ed1-a59a-431e-bfd4-57fb8dbed743"), "Food") val RENT = LabelDbo(UUID.fromString("edb24ade-2ac1-414e-9281-4d7a3b847d1b"), "Rent") val TRANSPORT = LabelDbo(UUID.fromString("7c108b80-c954-40bb-8464-0914d28426d5"), "Transportation") val HOUSEHOLD = LabelDbo(UUID.fromString("e4655b6b-3e75-4ca7-86b5-25d7e4906ada"), "Household") } fun applySeeds(db: SQLiteDatabase) { storeCurrency(db, EUR) storeCurrency(db, GBP) storeCurrency(db, CHF) storeCurrency(db, PLN) storeCurrency(db, CZK) storeLabel(db, FOOD) storeLabel(db, RENT) storeLabel(db, TRANSPORT) storeLabel(db, HOUSEHOLD) } private fun storeCurrency(db: SQLiteDatabase, currency: CurrencyDbo) { db.execSQL(String.format("INSERT INTO $tbl_currency VALUES('%s', '%s');", currency.code, currency.format)) } private fun storeLabel(db: SQLiteDatabase, label: LabelDbo) { db.execSQL(String.format("INSERT INTO $tbl_label VALUES('%s', '%s');", label.id.toString(), label.name)) }
gpl-3.0
ARostovsky/teamcity-rest-client
teamcity-rest-client-impl/src/test/kotlin/org/jetbrains/teamcity/rest/testUtils.kt
1
4676
package org.jetbrains.teamcity.rest import org.apache.log4j.* import java.io.File import java.io.FileInputStream import java.util.* import kotlin.reflect.KFunction import kotlin.reflect.KProperty import kotlin.reflect.full.valueParameters private val TEAMCITY_CONNECTION_FILE_PATH = "teamcity_connection.properties" //slf4j simple ignores debug output fun setupLog4jDebug() { LogManager.resetConfiguration() Logger.getRootLogger().removeAllAppenders() Logger.getRootLogger().addAppender(ConsoleAppender(PatternLayout("TEST[%d] %6p [%15.15t] - %30.30c - %m %n"))) Logger.getLogger("jetbrains").level = Level.DEBUG Logger.getLogger("org.apache.http").level = Level.ERROR } val publicInstanceUrl = "http://localhost:8111" fun publicInstance() = TeamCityInstanceFactory.guestAuth(publicInstanceUrl).withLogResponses() fun customInstance(serverUrl: String, username: String, password: String) = TeamCityInstanceFactory .httpAuth(serverUrl, username, password) .withLogResponses() fun haveCustomInstance(): Boolean = ConnectionPropertiesFileLoader(TEAMCITY_CONNECTION_FILE_PATH).validate() fun customInstanceByConnectionFile(): TeamCityInstance { val connectionPropertiesFileLoader = ConnectionPropertiesFileLoader(TEAMCITY_CONNECTION_FILE_PATH) return if (connectionPropertiesFileLoader.validate()) { val connectionConfig = connectionPropertiesFileLoader.fetch() customInstance(connectionConfig.serverUrl, connectionConfig.username, connectionConfig.password) } else { publicInstance() } } val reportProject = ProjectId("ProjectForReports") val testProject = ProjectId("TestProject") val changesBuildConfiguration = BuildConfigurationId("ProjectForSidebarCounters_MultibranchChange") val testsBuildConfiguration = BuildConfigurationId("ProjectForSidebarCounters_MultibranchTestResult") val runTestsBuildConfiguration = BuildConfigurationId("TestProject_RunTests") val dependantBuildConfiguration = BuildConfigurationId("TeamcityTestMetadataDemo_TestMetadataDemo") val pausedBuildConfiguration = BuildConfigurationId("ProjectForReports_TestPaused") val manyTestsBuildConfiguration = BuildConfigurationId("TeamcityTestData_Test") internal class ConnectionPropertiesFileLoader(filePath: String) { private val connectionFile: File? init { val classLoader = javaClass.classLoader connectionFile = classLoader.getResource(filePath)?.let { File(it.file) } } fun fetch(): ConnectionConfig { if (!validate()) { throw IllegalStateException("Properties are invalid") } val connectionProperties = Properties() connectionProperties.load(FileInputStream(connectionFile)) return ConnectionConfig( connectionProperties.getProperty(SERVER_URL), connectionProperties.getProperty(USERNAME), connectionProperties.getProperty(PASSWORD)) } fun validate(): Boolean { if (connectionFile == null || !connectionFile.exists()) return false val connectionProperties = Properties() connectionProperties.load(FileInputStream(connectionFile)) return validateConnectionProperties(connectionProperties) } private fun validateConnectionProperties(connectionProperties: Properties): Boolean { return validPropertyValue(connectionProperties.getProperty(SERVER_URL)) && validPropertyValue(connectionProperties.getProperty(USERNAME)) && validPropertyValue(connectionProperties.getProperty(PASSWORD)) } private fun validPropertyValue(value: String?): Boolean { return (value != null) && (!value.isNullOrEmpty()) } companion object { val SERVER_URL = "serverUrl" val USERNAME = "username" val PASSWORD = "password" } } internal class ConnectionConfig(val serverUrl: String, val username: String, val password: String) inline fun <reified T> callPublicPropertiesAndFetchMethods(instance: T) { instance.toString() for (member in T::class.members) { when (member) { is KProperty<*> -> { member.getter.call(instance) // println("${member.name} = ${member.getter.call(instance)}") } is KFunction<*> -> if ( member.name.startsWith("fetch") || member.name.startsWith("get")) { if (member.valueParameters.isEmpty()) { member.call(instance) // println("${member.name} = ${member.call(instance)}") } } } } }
apache-2.0
Dmedina88/SSB
example/app/src/main/kotlin/com/grayherring/devtalks/ui/home/events/HomeEvents.kt
1
1138
package com.grayherring.devtalks.ui.home.events import com.grayherring.devtalks.base.events.ClickEvent import com.grayherring.devtalks.base.events.Event import com.grayherring.devtalks.base.events.NetworkEvent import com.grayherring.devtalks.base.events.TextChangeEvent import com.grayherring.devtalks.data.model.Talk class Tab1Clicked : ClickEvent() class Tab2Clicked : ClickEvent() class Tab3Clicked : ClickEvent() class EditClicked : ClickEvent() class ItemClickEvent(val talk: Talk) : Event() class AllTalksEvent(val talks: List<Talk> = ArrayList()) : Event() class GetTalkEvent : NetworkEvent() class PresenterChangeEvent(string: String) : TextChangeEvent(string) class TitleChangeEvent(string: String) : TextChangeEvent(string) class PlatformChangeEvent(string: String) : TextChangeEvent(string) class DescriptionChangeEvent(string: String) : TextChangeEvent(string) class DateChangeEvent(string: String) : TextChangeEvent(string) class EmailChangeEvent(string: String) : TextChangeEvent(string) class SlidesChangeEvent(string: String) : TextChangeEvent(string) class StreamChangeEvent(string: String) : TextChangeEvent(string)
apache-2.0
hotchemi/khronos
src/test/kotlin/khronos/IntExtensionsTest.kt
1
2220
package khronos import org.junit.Test import java.util.* /** * Unit test for IntExtensions. */ class IntExtensionsTest { @Test fun year() { assertEquals(expected = Duration(unit = Calendar.YEAR, value = 1), actual = 1.year) } @Test fun years() { assertEquals(expected = Duration(unit = Calendar.YEAR, value = 5), actual = 5.years) } @Test fun month() { assertEquals(expected = Duration(unit = Calendar.MONTH, value = 1), actual = 1.month) } @Test fun months() { assertEquals(expected = Duration(unit = Calendar.MONTH, value = 3), actual = 3.months) } @Test fun week() { assertEquals(expected = Duration(unit = Calendar.WEEK_OF_MONTH, value = 1), actual = 1.week) } @Test fun weeks() { assertEquals(expected = Duration(unit = Calendar.WEEK_OF_MONTH, value = 7), actual = 7.weeks) } @Test fun day() { assertEquals(expected = Duration(unit = Calendar.DAY_OF_MONTH, value = 1), actual = 1.day) } @Test fun days() { assertEquals(expected = Duration(unit = Calendar.DAY_OF_MONTH, value = 9), actual = 9.days) } @Test fun hour() { assertEquals(expected = Duration(unit = Calendar.HOUR_OF_DAY, value = 1), actual = 1.hour) } @Test fun hours() { assertEquals(expected = Duration(unit = Calendar.HOUR_OF_DAY, value = 11), actual = 11.hours) } @Test fun minute() { assertEquals(expected = Duration(unit = Calendar.MINUTE, value = 1), actual = 1.minute) } @Test fun minutes() { assertEquals(expected = Duration(unit = Calendar.MINUTE, value = 13), actual = 13.minutes) } @Test fun second() { assertEquals(expected = Duration(unit = Calendar.SECOND, value = 1), actual = 1.second) } @Test fun seconds() { assertEquals(expected = Duration(unit = Calendar.SECOND, value = 15), actual = 15.seconds) } @Test fun millisecond() { assertEquals(expected = Duration(unit = Calendar.MILLISECOND, value = 1), actual = 1.millisecond) } @Test fun milliseconds() { assertEquals(expected = Duration(unit = Calendar.MILLISECOND, value = 15), actual = 15.milliseconds) } }
apache-2.0
sksamuel/scrimage
scrimage-tests/src/test/kotlin/com/sksamuel/scrimage/core/color/ColorTest.kt
1
6431
package com.sksamuel.scrimage.core.color import com.sksamuel.scrimage.color.CMYKColor import com.sksamuel.scrimage.color.Grayscale import com.sksamuel.scrimage.color.HSLColor import com.sksamuel.scrimage.color.HSVColor import com.sksamuel.scrimage.color.RGBColor import io.kotest.core.spec.style.WordSpec import io.kotest.matchers.floats.plusOrMinus import io.kotest.matchers.shouldBe class ColorTest : WordSpec({ "color conversions" should { "convert rgb to cmyk correctly" { val rgb = RGBColor(1, 2, 3) rgb.toCMYK().c shouldBe (0.667f plusOrMinus 0.2f) rgb.toCMYK().m shouldBe (0.333f plusOrMinus 0.2f) rgb.toCMYK().y shouldBe 0f rgb.toCMYK().k shouldBe (0.988f plusOrMinus 0.2f) } "convert rgb to hsl correctly" { val hsl = RGBColor(240, 150, 200).toHSL() hsl.hue shouldBe (326.66f plusOrMinus 0.2f) hsl.saturation shouldBe (0.75f plusOrMinus 0.2f) hsl.lightness shouldBe (0.765f plusOrMinus 0.2f) } "convert achromatic rgb to hsl correctly" { val hsl = RGBColor(50, 50, 50).toHSL() hsl.hue shouldBe (0f plusOrMinus 0.02f) hsl.saturation shouldBe (0f plusOrMinus 0.021f) hsl.lightness shouldBe (0.196f plusOrMinus 0.02f) } "convert rgb to hsv correctly" { val hsl = RGBColor(255, 150, 200).toHSV() hsl.hue shouldBe (331.42f plusOrMinus 0.2f) hsl.saturation shouldBe (0.4121f plusOrMinus 0.2f) hsl.value shouldBe (1f plusOrMinus 0.2f) } "convert rgb to grayscale correctly" { val rgb = RGBColor(100, 100, 100) rgb.toGrayscale().gray shouldBe 100 } "convert cmyk to rgb correctly" { val rgb = CMYKColor(0.1f, 0.2f, 0.3f, 0.4f).toRGB() rgb.red shouldBe 138 rgb.green shouldBe 122 rgb.blue shouldBe 107 rgb.alpha shouldBe 255 } "convert hsl to rgb correctly" { val rgb = HSLColor(100f, 0.5f, 0.3f, 1f).toRGB() rgb.red shouldBe 64 rgb.green shouldBe 115 rgb.blue shouldBe 38 rgb.alpha shouldBe 255 } "convert hsv to rgb correctly 1" { val rgb = HSVColor(150f, 0.2f, 0.3f, 1f).toRGB() rgb.red shouldBe 61 rgb.green shouldBe 77 rgb.blue shouldBe 69 rgb.alpha shouldBe 255 } "convert hsv to rgb correctly 2" { val rgb = HSVColor(2f, 0.99f, 0.61f, 1f).toRGB() rgb.red shouldBe 156 rgb.green shouldBe 7 rgb.blue shouldBe 2 rgb.alpha shouldBe 255 } "convert hsv to rgb correctly 3" { val rgb = HSVColor(99f, 0.51f, 0.61f, 1f).toRGB() rgb.red shouldBe 104 rgb.green shouldBe 156 rgb.blue shouldBe 76 rgb.alpha shouldBe 255 } "convert hsv to rgb correctly 4" { val rgb = HSVColor(99f, 0.51f, 0.62f, 1f).toRGB() rgb.red shouldBe 106 rgb.green shouldBe 158 rgb.blue shouldBe 77 rgb.alpha shouldBe 255 } "convert grayscale to rgb correctly" { val rgb = Grayscale(100, 128).toRGB() rgb.red shouldBe 100 rgb.green shouldBe 100 rgb.blue shouldBe 100 rgb.alpha shouldBe 128 } "be symmetric in rgb" { val rgb = RGBColor(1, 2, 3) rgb.toCMYK().toRGB() shouldBe rgb rgb.toHSL().toRGB() shouldBe rgb rgb.toHSV().toRGB() shouldBe rgb } "be symmetric in hsl" { val hsl = HSLColor(300f, 0.3f, 0.3f, 0.4f) hsl.toRGB().toHSL().hue shouldBe (hsl.hue plusOrMinus 0.02f) hsl.toRGB().toHSL().saturation shouldBe (hsl.saturation plusOrMinus 0.2f) hsl.toRGB().toHSL().lightness shouldBe (hsl.lightness plusOrMinus 0.2f) hsl.toHSV().toHSL().hue shouldBe (hsl.hue plusOrMinus 0.2f) hsl.toHSV().toHSL().saturation shouldBe (hsl.saturation plusOrMinus 0.2f) hsl.toHSV().toHSL().lightness shouldBe (hsl.lightness plusOrMinus 0.2f) hsl.toCMYK().toHSL().hue shouldBe (hsl.hue plusOrMinus 0.2f) hsl.toCMYK().toHSL().saturation shouldBe (hsl.saturation plusOrMinus 0.2f) hsl.toCMYK().toHSL().lightness shouldBe (hsl.lightness plusOrMinus 0.2f) } "be symmetric in HSV" { val hsv = HSVColor(300f, 0.2f, 0.3f, 0.4f) hsv.toRGB().toHSV().hue shouldBe (hsv.hue plusOrMinus 0.2f) hsv.toRGB().toHSV().saturation shouldBe (hsv.saturation plusOrMinus 0.2f) hsv.toRGB().toHSV().value shouldBe (hsv.value plusOrMinus 0.2f) hsv.toHSL().toHSV().hue shouldBe (hsv.hue plusOrMinus 0.2f) hsv.toHSL().toHSV().saturation shouldBe (hsv.saturation plusOrMinus 0.2f) hsv.toHSL().toHSV().value shouldBe (hsv.value plusOrMinus 0.2f) hsv.toCMYK().toHSV().hue shouldBe (hsv.hue plusOrMinus 0.2f) hsv.toCMYK().toHSV().saturation shouldBe (hsv.saturation plusOrMinus 0.2f) hsv.toCMYK().toHSV().value shouldBe (hsv.value plusOrMinus 0.2f) } "be symmetric in cmyk" { val cmyk = CMYKColor(0.1f, 0.2f, 0.3f, 0.4f) cmyk.toRGB().toCMYK().c shouldBe (cmyk.c plusOrMinus 0.2f) cmyk.toRGB().toCMYK().m shouldBe (cmyk.m plusOrMinus 0.2f) cmyk.toRGB().toCMYK().y shouldBe (cmyk.y plusOrMinus 0.2f) cmyk.toRGB().toCMYK().k shouldBe (cmyk.k plusOrMinus 0.2f) cmyk.toHSV().toCMYK().c shouldBe (cmyk.c plusOrMinus 0.2f) cmyk.toHSV().toCMYK().m shouldBe (cmyk.m plusOrMinus 0.2f) cmyk.toHSV().toCMYK().y shouldBe (cmyk.y plusOrMinus 0.2f) cmyk.toHSV().toCMYK().k shouldBe (cmyk.k plusOrMinus 0.2f) cmyk.toHSL().toCMYK().c shouldBe (cmyk.c plusOrMinus 0.2f) cmyk.toHSL().toCMYK().m shouldBe (cmyk.m plusOrMinus 0.2f) cmyk.toHSL().toCMYK().y shouldBe (cmyk.y plusOrMinus 0.2f) cmyk.toHSL().toCMYK().k shouldBe (cmyk.k plusOrMinus 0.2f) } "be reflexive" { val rgb = RGBColor(1, 2, 3) rgb.toRGB() shouldBe rgb val hsl = HSLColor(0.1f, 0.2f, 0.3f, 0.4f) hsl.toHSL() shouldBe hsl val hsv = HSVColor(0.1f, 0.2f, 0.3f, 0.4f) hsv.toHSV() shouldBe hsv val cmyk = CMYKColor(0.1f, 0.2f, 0.3f, 0.4f) cmyk.toCMYK() shouldBe cmyk val gray = Grayscale(100) gray.toGrayscale() shouldBe gray } } })
apache-2.0
hannesa2/owncloud-android
owncloudApp/src/main/java/com/owncloud/android/extensions/DialogExt.kt
2
1085
/** * ownCloud Android client application * * @author David Crespo Ríos * Copyright (C) 2022 ownCloud GmbH. * * This program 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. * * 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.owncloud.android.extensions import android.app.Dialog import android.view.WindowManager import com.owncloud.android.BuildConfig import com.owncloud.android.R fun Dialog.avoidScreenshotsIfNeeded() { if (!BuildConfig.DEBUG && context.resources?.getBoolean(R.bool.allow_screenshots) == false) { window?.addFlags(WindowManager.LayoutParams.FLAG_SECURE) } }
gpl-2.0
ioc1778/incubator
incubator-crypto/src/main/java/com/riaektiv/crypto/tree/Tree.kt
2
4111
package com.riaektiv.crypto.tree import org.apache.commons.codec.binary.Hex import org.bouncycastle.jcajce.provider.digest.SHA3 import java.io.UnsupportedEncodingException import java.util.* /** * Coding With Passion Since 1991 * Created: 6/26/2016, 7:31 PM Eastern Time * @author Sergey Chuykov */ abstract class Tree<E : Entity> : EntityFactory<E> { var root = Node<E>() fun path(s: String): IntArray { val hex = Hex.encodeHexString(s.toByteArray()) val encoded = IntArray(hex.length) for (i in 0..hex.length - 1) { val h = hex[i] encoded[i] = Integer.parseInt(h.toString(), 16) } return encoded } protected fun nvl(s: String?): String { return s ?: "" } fun sha3(message: String): String { val s = nvl(message) val md = SHA3.DigestSHA3(224) try { md.update(s.toByteArray(charset("UTF-8"))) } catch (ex: UnsupportedEncodingException) { md.update(s.toByteArray()) } val digest = md.digest() return Hex.encodeHexString(digest) } protected fun hash(node: Node<E>): String { return if (node.entity != null) node.entity!!.hash() else "" } protected fun message(node: Node<E>): String { val sb = StringBuilder() for (ref in node.refs) { sb.append(nvl(ref)).append(':') } sb.append(hash(node)) return sb.toString() } fun sha3(node: Node<E>): String { return sha3(message(node)) } protected fun find(n: Node<E>?, vararg path: Int): Node<E>? { var node = n for (idx in path) { node = node!!.next[idx] if (node == null) { break } } return node } fun nodes(n: Node<E>, vararg path: Int): LinkedList<Node<E>> { var node = n val nodes = LinkedList<Node<E>>() nodes.offer(node) for (idx in path) { var next: Node<E>? = node.next[idx] if (next == null) { next = Node<E>() node.next[idx] = next } node = next nodes.offer(node) } return nodes } fun find(vararg path: Int): Node<E>? { return find(root, *path) } fun get(key: String): E? { return find(*path(key))?.entity } fun put(key: String, entity: E) { val path = path(key) val nodes = nodes(root, *path) var node = nodes.pollLast() node.entity = entity node.hash = sha3(node) for (i in path.indices.reversed()) { node = nodes[i] val idx = path[i] node.setRef(idx, node.next[idx]?.hash!!) node.hash = sha3(node) } } fun validateHash(node: Node<E>?) { if (node == null) { return } val expected = sha3(node) if (expected != node.hash) { throw IllegalStateException("Invalid hash value:" + node) } } private inner class NodeCtx(var idx: Int, var node: Node<E>?) { override fun toString(): String { return "NodeCtx{" + "idx=" + idx + ", node=" + node + '}' } } @JvmOverloads fun validate(n: Node<E>? = root) { var node = n val stack = LinkedList<NodeCtx>() var i = 0 while (i < 0xF) { if (node!!.next[i] != null) { validateHash(node) val ctx = NodeCtx(i, node) println(ctx) stack.push(ctx) node = node.next[i] i = 0 } else { if (i == 0xF - 1 && !stack.isEmpty()) { if (node.entity != null) { println(node) } val ctx = stack.pop() node = ctx.node i = ctx.idx } } i++ } } }
bsd-3-clause
kiruto/debug-bottle
components/src/main/kotlin/com/exyui/android/debugbottle/components/StatusViewer.kt
1
148
package com.exyui.android.debugbottle.components /** * Created by yuriel on 9/3/16. */ internal object StatusViewer { val VERSION_CODE = 1 }
apache-2.0
HabitRPG/habitrpg-android
Habitica/src/main/java/com/habitrpg/android/habitica/api/Server.kt
1
737
package com.habitrpg.android.habitica.api class Server { private var addr: String constructor(addr: String) : this(addr, true) {} private constructor(addr: String, attachSuffix: Boolean) { if (attachSuffix) { if (addr.endsWith("/api/v4") || addr.endsWith("/api/v4/")) { this.addr = addr } else if (addr.endsWith("/")) { this.addr = addr + "api/v4/" } else { this.addr = "$addr/api/v4/" } } else { this.addr = addr } } constructor(server: Server) { addr = server.toString() } override fun toString(): String { return addr } }
gpl-3.0
HabitRPG/habitrpg-android
Habitica/src/main/java/com/habitrpg/android/habitica/models/Achievement.kt
2
470
package com.habitrpg.android.habitica.models import io.realm.RealmObject import io.realm.annotations.PrimaryKey open class Achievement : RealmObject(), BaseObject { @PrimaryKey var key: String? = null var type: String? = null var title: String? = null var text: String? = null var icon: String? = null var category: String? = null var earned: Boolean = false var index: Int = 0 var optionalCount: Int? = null }
gpl-3.0
foreverigor/TumCampusApp
app/src/main/java/de/tum/in/tumcampusapp/service/BackgroundService.kt
1
1510
package de.tum.`in`.tumcampusapp.service import android.content.Context import android.content.Intent import android.os.Looper import android.support.v4.app.JobIntentService import de.tum.`in`.tumcampusapp.utils.Const import de.tum.`in`.tumcampusapp.utils.Utils /** * Service used to sync data in background */ class BackgroundService : JobIntentService() { override fun onCreate() { super.onCreate() Utils.log("BackgroundService has started") } /** * Starts [DownloadService] with appropriate extras * * @param intent Intent */ override fun onHandleWork(intent: Intent) { // Download all from external val appLaunches = intent.getBooleanExtra(Const.APP_LAUNCHES, false) val service = Intent().apply { putExtra(Const.ACTION_EXTRA, Const.DOWNLOAD_ALL_FROM_EXTERNAL) putExtra(Const.FORCE_DOWNLOAD, false) putExtra(Const.APP_LAUNCHES, appLaunches) } DownloadService.enqueueWork(baseContext, service) if (Looper.myLooper() == null) { Looper.prepare() } WifiScanHandler.getInstance().startRepetition(this) } override fun onDestroy() { super.onDestroy() Utils.log("BackgroundService has stopped") } companion object { @JvmStatic fun enqueueWork(context: Context, work: Intent) { enqueueWork(context, BackgroundService::class.java, Const.BACKGROUND_SERVICE_JOB_ID, work) } } }
gpl-3.0
SimpleMobileTools/Simple-Commons
commons/src/main/kotlin/com/simplemobiletools/commons/views/MyRecyclerView.kt
1
12517
package com.simplemobiletools.commons.views import android.content.Context import android.os.Handler import android.util.AttributeSet import android.view.MotionEvent import android.view.ScaleGestureDetector import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import com.simplemobiletools.commons.R import com.simplemobiletools.commons.interfaces.RecyclerScrollCallback // drag selection is based on https://github.com/afollestad/drag-select-recyclerview open class MyRecyclerView : RecyclerView { private val AUTO_SCROLL_DELAY = 25L private var isZoomEnabled = false private var isDragSelectionEnabled = false private var zoomListener: MyZoomListener? = null private var dragListener: MyDragListener? = null private var autoScrollHandler = Handler() private var scaleDetector: ScaleGestureDetector private var dragSelectActive = false private var lastDraggedIndex = -1 private var minReached = 0 private var maxReached = 0 private var initialSelection = 0 private var hotspotHeight = 0 private var hotspotOffsetTop = 0 private var hotspotOffsetBottom = 0 private var hotspotTopBoundStart = 0 private var hotspotTopBoundEnd = 0 private var hotspotBottomBoundStart = 0 private var hotspotBottomBoundEnd = 0 private var autoScrollVelocity = 0 private var inTopHotspot = false private var inBottomHotspot = false private var currScaleFactor = 1.0f private var lastUp = 0L // allow only pinch zoom, not double tap // things related to parallax scrolling (for now only in the music player) // cut from https://github.com/ksoichiro/Android-ObservableScrollView var recyclerScrollCallback: RecyclerScrollCallback? = null private var mPrevFirstVisiblePosition = 0 private var mPrevScrolledChildrenHeight = 0 private var mPrevFirstVisibleChildHeight = -1 private var mScrollY = 0 // variables used for fetching additional items at scrolling to the bottom/top var endlessScrollListener: EndlessScrollListener? = null private var totalItemCount = 0 private var lastMaxItemIndex = 0 private var linearLayoutManager: LinearLayoutManager? = null constructor(context: Context) : super(context) constructor(context: Context, attrs: AttributeSet) : super(context, attrs) init { hotspotHeight = context.resources.getDimensionPixelSize(R.dimen.dragselect_hotspot_height) if (layoutManager is LinearLayoutManager) { linearLayoutManager = layoutManager as LinearLayoutManager } val gestureListener = object : MyGestureListener { override fun getLastUp() = lastUp override fun getScaleFactor() = currScaleFactor override fun setScaleFactor(value: Float) { currScaleFactor = value } override fun getZoomListener() = zoomListener } scaleDetector = ScaleGestureDetector(context, GestureListener(gestureListener)) } override fun onMeasure(widthSpec: Int, heightSpec: Int) { super.onMeasure(widthSpec, heightSpec) if (hotspotHeight > -1) { hotspotTopBoundStart = hotspotOffsetTop hotspotTopBoundEnd = hotspotOffsetTop + hotspotHeight hotspotBottomBoundStart = measuredHeight - hotspotHeight - hotspotOffsetBottom hotspotBottomBoundEnd = measuredHeight - hotspotOffsetBottom } } private val autoScrollRunnable = object : Runnable { override fun run() { if (inTopHotspot) { scrollBy(0, -autoScrollVelocity) autoScrollHandler.postDelayed(this, AUTO_SCROLL_DELAY) } else if (inBottomHotspot) { scrollBy(0, autoScrollVelocity) autoScrollHandler.postDelayed(this, AUTO_SCROLL_DELAY) } } } fun resetItemCount() { totalItemCount = 0 } override fun dispatchTouchEvent(ev: MotionEvent): Boolean { if (!dragSelectActive) { try { super.dispatchTouchEvent(ev) } catch (ignored: Exception) { } } when (ev.action) { MotionEvent.ACTION_UP, MotionEvent.ACTION_CANCEL -> { dragSelectActive = false inTopHotspot = false inBottomHotspot = false autoScrollHandler.removeCallbacks(autoScrollRunnable) currScaleFactor = 1.0f lastUp = System.currentTimeMillis() return true } MotionEvent.ACTION_MOVE -> { if (dragSelectActive) { val itemPosition = getItemPosition(ev) if (hotspotHeight > -1) { if (ev.y in hotspotTopBoundStart.toFloat()..hotspotTopBoundEnd.toFloat()) { inBottomHotspot = false if (!inTopHotspot) { inTopHotspot = true autoScrollHandler.removeCallbacks(autoScrollRunnable) autoScrollHandler.postDelayed(autoScrollRunnable, AUTO_SCROLL_DELAY) } val simulatedFactor = (hotspotTopBoundEnd - hotspotTopBoundStart).toFloat() val simulatedY = ev.y - hotspotTopBoundStart autoScrollVelocity = (simulatedFactor - simulatedY).toInt() / 2 } else if (ev.y in hotspotBottomBoundStart.toFloat()..hotspotBottomBoundEnd.toFloat()) { inTopHotspot = false if (!inBottomHotspot) { inBottomHotspot = true autoScrollHandler.removeCallbacks(autoScrollRunnable) autoScrollHandler.postDelayed(autoScrollRunnable, AUTO_SCROLL_DELAY) } val simulatedY = ev.y + hotspotBottomBoundEnd val simulatedFactor = (hotspotBottomBoundStart + hotspotBottomBoundEnd).toFloat() autoScrollVelocity = (simulatedY - simulatedFactor).toInt() / 2 } else if (inTopHotspot || inBottomHotspot) { autoScrollHandler.removeCallbacks(autoScrollRunnable) inTopHotspot = false inBottomHotspot = false } } if (itemPosition != RecyclerView.NO_POSITION && lastDraggedIndex != itemPosition) { lastDraggedIndex = itemPosition if (minReached == -1) { minReached = lastDraggedIndex } if (maxReached == -1) { maxReached = lastDraggedIndex } if (lastDraggedIndex > maxReached) { maxReached = lastDraggedIndex } if (lastDraggedIndex < minReached) { minReached = lastDraggedIndex } dragListener?.selectRange(initialSelection, lastDraggedIndex, minReached, maxReached) if (initialSelection == lastDraggedIndex) { minReached = lastDraggedIndex maxReached = lastDraggedIndex } } return true } } } return if (isZoomEnabled) { scaleDetector.onTouchEvent(ev) } else { true } } fun setupDragListener(dragListener: MyDragListener?) { isDragSelectionEnabled = dragListener != null this.dragListener = dragListener } fun setupZoomListener(zoomListener: MyZoomListener?) { isZoomEnabled = zoomListener != null this.zoomListener = zoomListener } fun setDragSelectActive(initialSelection: Int) { if (dragSelectActive || !isDragSelectionEnabled) return lastDraggedIndex = -1 minReached = -1 maxReached = -1 this.initialSelection = initialSelection dragSelectActive = true dragListener?.selectItem(initialSelection) } private fun getItemPosition(e: MotionEvent): Int { val v = findChildViewUnder(e.x, e.y) ?: return RecyclerView.NO_POSITION if (v.tag == null || v.tag !is RecyclerView.ViewHolder) { throw IllegalStateException("Make sure your adapter makes a call to super.onBindViewHolder(), and doesn't override itemView tags.") } val holder = v.tag as RecyclerView.ViewHolder return holder.adapterPosition } override fun onScrollStateChanged(state: Int) { super.onScrollStateChanged(state) if (endlessScrollListener != null) { if (totalItemCount == 0) { totalItemCount = adapter!!.itemCount } if (state == SCROLL_STATE_IDLE) { val lastVisiblePosition = linearLayoutManager?.findLastVisibleItemPosition() ?: 0 if (lastVisiblePosition != lastMaxItemIndex && lastVisiblePosition == totalItemCount - 1) { lastMaxItemIndex = lastVisiblePosition endlessScrollListener!!.updateBottom() } val firstVisiblePosition = linearLayoutManager?.findFirstVisibleItemPosition() ?: -1 if (firstVisiblePosition == 0) { endlessScrollListener!!.updateTop() } } } } override fun onScrollChanged(l: Int, t: Int, oldl: Int, oldt: Int) { super.onScrollChanged(l, t, oldl, oldt) if (recyclerScrollCallback != null) { if (childCount > 0) { val firstVisiblePosition = getChildAdapterPosition(getChildAt(0)) val firstVisibleChild = getChildAt(0) if (firstVisibleChild != null) { if (mPrevFirstVisiblePosition < firstVisiblePosition) { mPrevScrolledChildrenHeight += mPrevFirstVisibleChildHeight } if (firstVisiblePosition == 0) { mPrevFirstVisibleChildHeight = firstVisibleChild.height mPrevScrolledChildrenHeight = 0 } if (mPrevFirstVisibleChildHeight < 0) { mPrevFirstVisibleChildHeight = 0 } mScrollY = mPrevScrolledChildrenHeight - firstVisibleChild.top recyclerScrollCallback?.onScrolled(mScrollY) } } } } class GestureListener(val gestureListener: MyGestureListener) : ScaleGestureDetector.SimpleOnScaleGestureListener() { private val ZOOM_IN_THRESHOLD = -0.4f private val ZOOM_OUT_THRESHOLD = 0.15f override fun onScale(detector: ScaleGestureDetector): Boolean { gestureListener.apply { if (System.currentTimeMillis() - getLastUp() < 1000) return false val diff = getScaleFactor() - detector.scaleFactor if (diff < ZOOM_IN_THRESHOLD && getScaleFactor() == 1.0f) { getZoomListener()?.zoomIn() setScaleFactor(detector.scaleFactor) } else if (diff > ZOOM_OUT_THRESHOLD && getScaleFactor() == 1.0f) { getZoomListener()?.zoomOut() setScaleFactor(detector.scaleFactor) } } return false } } interface MyZoomListener { fun zoomOut() fun zoomIn() } interface MyDragListener { fun selectItem(position: Int) fun selectRange(initialSelection: Int, lastDraggedIndex: Int, minReached: Int, maxReached: Int) } interface MyGestureListener { fun getLastUp(): Long fun getScaleFactor(): Float fun setScaleFactor(value: Float) fun getZoomListener(): MyZoomListener? } interface EndlessScrollListener { fun updateTop() fun updateBottom() } }
gpl-3.0
androidx/androidx
fragment/fragment-ktx/src/main/java/androidx/fragment/app/Fragment.kt
3
3201
/* * Copyright 2020 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.fragment.app import android.os.Bundle /** * Sets the given result for the [requestKey]. This result will be delivered to a * [FragmentResultListener] that is called given to [setFragmentResultListener] with the same * [requestKey]. If no [FragmentResultListener] with the same key is set or the Lifecycle * associated with the listener is not at least [androidx.lifecycle.Lifecycle.State.STARTED], the * result is stored until one becomes available, or [clearFragmentResult] is called with the same * requestKey. * * @param requestKey key used to identify the result * @param result the result to be passed to another fragment. */ public fun Fragment.setFragmentResult(requestKey: String, result: Bundle) { parentFragmentManager.setFragmentResult(requestKey, result) } /** * Clears the stored result for the given requestKey. * * This clears a result that was previously set a call to [setFragmentResult]. * * If this is called with a requestKey that is not associated with any result, this method * does nothing. * * @param requestKey key used to identify the result */ public fun Fragment.clearFragmentResult(requestKey: String) { parentFragmentManager.clearFragmentResult(requestKey) } /** * Sets the [FragmentResultListener] for a given [requestKey]. Once this Fragment is * at least in the [androidx.lifecycle.Lifecycle.State.STARTED] state, any results set by * [setFragmentResult] using the same [requestKey] will be delivered to the * [FragmentResultListener.onFragmentResult] callback. The callback will remain active until this * Fragment reaches the [androidx.lifecycle.Lifecycle.State.DESTROYED] state or * [clearFragmentResultListener] is called with the same requestKey. * * @param requestKey requestKey used to store the result * @param listener listener for result changes. */ public fun Fragment.setFragmentResultListener( requestKey: String, listener: ((requestKey: String, bundle: Bundle) -> Unit) ) { parentFragmentManager.setFragmentResultListener(requestKey, this, listener) } /** * Clears the stored [FragmentResultListener] for the given requestKey. * * This clears a [FragmentResultListener] that was previously set a call to * [setFragmentResultListener]. * * If this is called with a requestKey that is not associated with any [FragmentResultListener], * this method does nothing. * * @param requestKey key used to identify the result */ public fun Fragment.clearFragmentResultListener(requestKey: String) { parentFragmentManager.clearFragmentResultListener(requestKey) }
apache-2.0
androidx/androidx
buildSrc/private/src/main/kotlin/androidx/build/ProjectExt.kt
3
2252
/** * Copyright 2018 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.build import org.gradle.api.Project import org.gradle.api.Task import org.gradle.api.tasks.TaskProvider import java.util.Collections import java.util.concurrent.locks.ReentrantLock import kotlin.concurrent.withLock /** * Holder class used for lazily registering tasks using the new Lazy task execution API. */ data class LazyTaskRegistry( private val names: MutableSet<String> = Collections.synchronizedSet(mutableSetOf()) ) { fun <T : Any?> once(name: String, f: () -> T): T? { if (names.add(name)) { return f() } return null } companion object { private const val KEY = "AndroidXAutoRegisteredTasks" private val lock = ReentrantLock() fun get(project: Project): LazyTaskRegistry { val existing = project.extensions.findByName(KEY) as? LazyTaskRegistry if (existing != null) { return existing } return lock.withLock { project.extensions.findByName(KEY) as? LazyTaskRegistry ?: LazyTaskRegistry().also { project.extensions.add(KEY, it) } } } } } inline fun <reified T : Task> Project.maybeRegister( name: String, crossinline onConfigure: (T) -> Unit, crossinline onRegister: (TaskProvider<T>) -> Unit ): TaskProvider<T> { @Suppress("UNCHECKED_CAST") return LazyTaskRegistry.get(project).once(name) { tasks.register(name, T::class.java) { onConfigure(it) }.also(onRegister) } ?: tasks.named(name) as TaskProvider<T> }
apache-2.0
jvsegarra/kotlin-koans
src/iii_conventions/_31_Invoke_.kt
1
630
package iii_conventions import util.* class Invokable { var numberOfInvocations = 0; operator fun invoke(): Invokable { numberOfInvocations++; return this; } } public fun Invokable.getNumberOfInvocations() = this.numberOfInvocations fun todoTask31(): Nothing = TODO( """ Task 31. Change class Invokable to count the number of invocations (round brackets). Uncomment the commented code - it should return 4. """, references = { invokable: Invokable -> }) fun task31(invokable: Invokable): Int { return invokable()()()().getNumberOfInvocations() }
mit
jean79/yested
src/main/docsite/demo/chartjs/chartjs_bar.kt
2
2204
package demo.chartjs import net.yested.Div import net.yested.div import net.yested.Chart import net.yested.BarChartData import net.yested.BarChartSeries import net.yested.randomColor import net.yested.toHTMLColor fun createChartJSBarSection(): Div { val chart = Chart(width = 300, height = 250) val temperatureCZE = arrayOf(-2.81, -1.06, 2.80, 7.49, 12.30, 15.41, 17.11, 16.90, 13.49, 8.59, 2.82, -1.06) val temperatureSVK = arrayOf(-2.03, 0.85, 5.44, 10.72, 15.49, 18.52, 20.11, 19.70, 16.13, 10.81, 4.89, 0.11) val colorCZE = randomColor(1.0) val colorSVK = randomColor(1.0) val chartData = BarChartData( labels = arrayOf("Jan", "Feb", "Mar", "Apr", "May", "Jun", "July", "Aug", "Sept", "Oct", "Nov", "Dec"), datasets = arrayOf( BarChartSeries( label = "Czech Re", strokeColor = colorCZE.copy(alpha = 0.8).toHTMLColor(), fillColor = colorCZE.copy(alpha = 0.5).toHTMLColor(), highlightStroke = colorCZE.copy(alpha = 1.0).toHTMLColor(), highlightFill = colorCZE.copy(alpha = 0.75).toHTMLColor(), data = temperatureCZE), BarChartSeries( label = "Slovakia", strokeColor = colorSVK.copy(alpha = 0.8).toHTMLColor(), fillColor = colorSVK.copy(alpha = 0.5).toHTMLColor(), highlightStroke = colorSVK.copy(alpha = 1.0).toHTMLColor(), highlightFill = colorSVK.copy(alpha = 0.75).toHTMLColor(), data = temperatureSVK))) val options = object { val responsive = true } chart.drawBarChart(chartData, options) return div { h4 { +"Bar Chart" } +chart a(href = "https://github.com/jean79/yested/blob/master/src/main/docsite/demo/chartjs/chartjs_bar.kt", target = "_blank") { +"Source code"} } }
mit
EventFahrplan/EventFahrplan
app/src/main/java/nerd/tuxmobil/fahrplan/congress/models/DateInfos.kt
1
1470
package nerd.tuxmobil.fahrplan.congress.models import info.metadude.android.eventfahrplan.commons.temporal.Moment import java.util.ArrayList class DateInfos : ArrayList<DateInfo>() { fun sameDay(timestamp: Moment, sessionListDay: Int): Boolean { val currentDate = timestamp.startOfDay() return any { (dayIndex, date) -> dayIndex == sessionListDay && date == currentDate } } /** * Returns the index of today if found, [DateInfo.DAY_INDEX_NOT_FOUND] otherwise. */ val indexOfToday: Int get() { if (isEmpty()) { return DateInfo.DAY_INDEX_NOT_FOUND } val today = Moment.now() .minusHours(DAY_CHANGE_HOUR_DEFAULT.toLong()) .minusMinutes(DAY_CHANGE_MINUTE_DEFAULT.toLong()) .startOfDay() forEach { dateInfo -> val dayIndex = dateInfo.getDayIndex(today) if (dayIndex != DateInfo.DAY_INDEX_NOT_FOUND) { return dayIndex } } return DateInfo.DAY_INDEX_NOT_FOUND } private companion object { const val serialVersionUID = 1L /** * Hour of day change (all sessions which start before count to the previous day). */ const val DAY_CHANGE_HOUR_DEFAULT = 4 /** * Minute of day change. */ const val DAY_CHANGE_MINUTE_DEFAULT = 0 } }
apache-2.0
bjzhou/Coolapk
app/src/main/kotlin/bjzhou/coolapk/app/util/Utils.kt
1
2503
/* * Copyright (C) 2012 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 bjzhou.coolapk.app.util import android.content.Context import android.content.Intent import android.net.ConnectivityManager import android.net.Uri import android.os.Build import android.preference.PreferenceManager import android.text.Html import bjzhou.coolapk.app.App import java.util.* /** * Class containing some static utility methods. */ object Utils { val userAgent: String get() { val stringBuilder = StringBuilder() val str = System.getProperty("http.agent") stringBuilder.append(str).append(" (#Build; ").append(Build.BRAND).append("; ").append(Build.MODEL).append("; ").append(Build.DISPLAY).append("; ").append(Build.VERSION.RELEASE).append(")") stringBuilder.append(" +CoolMarket/7.3") return Html.escapeHtml(stringBuilder.toString()) } val localeString: String get() { val locale = Locale.getDefault() return locale.language + "-" + locale.country } val uuid: String get() { val sp = PreferenceManager.getDefaultSharedPreferences(App.context) if (sp.contains("uuid")) { return sp.getString("uuid", "") } val uuid = UUID.randomUUID().toString() sp.edit().putString("uuid", uuid).apply() return uuid } val networkConnected: Boolean get() { val cm = App.context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager return cm.activeNetworkInfo != null && cm.activeNetworkInfo.isConnectedOrConnecting } fun installApk(uri: Uri) { val intent = Intent(Intent.ACTION_VIEW) intent.setDataAndType(uri, "application/vnd.android.package-archive") intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK App.context.startActivity(intent) } }
gpl-2.0
handstandsam/ShoppingApp
multiplatform/src/jsMain/kotlin/com/handstandsam/shoppingapp/multiplatform/ui/Composables.kt
1
2434
package com.handstandsam.shoppingapp.multiplatform.ui import androidx.compose.runtime.Composable import org.jetbrains.compose.web.css.CSSColorValue import org.jetbrains.compose.web.css.Color import org.jetbrains.compose.web.css.backgroundColor import org.jetbrains.compose.web.css.whiteSpace import org.jetbrains.compose.web.dom.Button import org.jetbrains.compose.web.dom.Div import org.jetbrains.compose.web.dom.H3 import org.jetbrains.compose.web.dom.H6 import org.jetbrains.compose.web.dom.Img import org.jetbrains.compose.web.dom.Pre import org.jetbrains.compose.web.dom.Text @Composable fun WrappedPreformattedText(str: String) { Pre( { style { whiteSpace("pre-wrap") } } ) { Text(str) } } @Composable fun ImageAndTextRow(label: String, imageUrl: String, onClick: () -> Unit = {}) { Div({ onClick { onClick() } classes("list-group-item", "list-group-item-action") }) { Div(attrs = { classes("row") }) { Div(attrs = { classes("col") }) { Img( attrs = { classes("flex-shrink-0") }, src = imageUrl ) } Div(attrs = { classes("col") }) { H3 { Text(label) } } } } } @Composable fun PrimaryButton(label: String, onClick: () -> Unit = {}) { ShoppingAppButton(label, ButtonType.PRIMARY, onClick) } enum class ButtonType(val cssClass: String) { PRIMARY("btn-primary"), GREEN("btn-success"), RED("btn-danger") } @Composable fun ShoppingAppButton(label: String, buttonType: ButtonType, onClick: () -> Unit = {}) { Button( attrs = { classes("btn", buttonType.cssClass) style { when(buttonType){ ButtonType.PRIMARY ->{} ButtonType.GREEN -> backgroundColor(Color.green) ButtonType.RED -> backgroundColor(Color.red) } } onClick { onClick() } } ) { Text(label) } } @Composable fun ShoppingAppList(content: (@Composable () -> Unit)) { Div(attrs = { classes("list-group") }) { content() } }
apache-2.0
EmmyLua/IntelliJ-EmmyLua
src/test/kotlin/com/tang/intellij/test/inspections/MatchFunctionSignatureTest.kt
2
2111
/* * Copyright (c) 2017. tangzx([email protected]) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* package com.tang.intellij.test.inspections import com.tang.intellij.lua.codeInsight.inspection.MatchFunctionSignatureInspection class MatchFunctionSignatureTest : LuaInspectionsTestBase(MatchFunctionSignatureInspection()) { fun testTypeMissMatch() = checkByText(""" ---@param p1 number ---@param p2 string local function test(p1, p2) end test(1, <warning>2</warning>) """) fun testTooManyArgs() = checkByText(""" ---@param p1 number ---@param p2 string local function test(p1, p2) end test(1, "2", <warning>3</warning>) """) fun testMissArgs() = checkByText(""" local function test(p1, p2) end test(1<warning>)</warning> """) fun testMultiReturn() = checkByText(""" local function ret_nn() return 1, 2 end local function ret_sn() return "1", 2 end ---@param n1 number ---@param n2 number local function acp_nn(n1, n2) end acp_nn(ret_nn()) acp_nn(<warning>ret_sn()</warning>) acp_nn(ret_nn(), 1) acp_nn(<warning>ret_sn()</warning>, 1) """) fun testParentIndex() = checkByText(""" local dummy, A = 1, {} ---@return number, string function A.a() return 1, "1" end ---@param n number ---@param s string local function acp_ns(n, s) end acp_ns(A.a()) """) }*/
apache-2.0
anlun/haskell-idea-plugin
plugin/src/org/jetbrains/haskell/psi/DataDeclaration.kt
1
647
package org.jetbrains.haskell.psi import com.intellij.lang.ASTNode import com.intellij.extapi.psi.ASTWrapperPsiElement import com.intellij.psi.util.PsiTreeUtil /** * Created by atsky on 4/11/14. */ public class DataDeclaration(node : ASTNode) : Declaration(node) { override fun getDeclarationName(): String? { return getNameElement()?.getNameText() } fun getNameElement(): TypeVariable? = PsiTreeUtil.getChildrenOfTypeAsList(this, javaClass<TypeVariable>()).firstOrNull() fun getConstructorDeclarationList() : List<ConstructorDeclaration> = PsiTreeUtil.getChildrenOfTypeAsList(this, javaClass()) }
apache-2.0
tasomaniac/OpenLinkWith
app/src/main/java/com/tasomaniac/openwith/resolver/DefaultResolverPresenter.kt
1
4607
package com.tasomaniac.openwith.resolver import android.content.Intent import android.content.res.Resources import android.net.Uri import com.tasomaniac.openwith.R import com.tasomaniac.openwith.data.PreferredApp import timber.log.Timber import javax.inject.Inject internal class DefaultResolverPresenter @Inject constructor( private val resources: Resources, private val sourceIntent: Intent, private val callerPackage: CallerPackage, private val useCase: ResolverUseCase, private val viewState: ViewState ) : ResolverPresenter { override fun bind(view: ResolverView, navigation: ResolverView.Navigation) { view.setListener(ViewListener(view, navigation)) useCase.bind(UseCaseListener(view, navigation)) } override fun unbind(view: ResolverView) { view.setListener(null) useCase.unbind() } override fun release() { useCase.release() } private inner class UseCaseListener( private val view: ResolverView, private val navigation: ResolverView.Navigation ) : ResolverUseCase.Listener { @Suppress("TooGenericExceptionCaught") override fun onPreferredResolved( uri: Uri, preferredApp: PreferredApp, displayActivityInfo: DisplayActivityInfo ) { if (preferredApp.preferred.not()) return if (displayActivityInfo.packageName().isCaller()) return try { val preferredIntent = Intent(Intent.ACTION_VIEW, uri) .setComponent(preferredApp.componentName) navigation.startPreferred(preferredIntent, displayActivityInfo.displayLabel) view.dismiss() } catch (e: Exception) { Timber.e(e, "Security Exception for the url: %s", uri) useCase.deleteFailedHost(uri) } } private fun String.isCaller() = this == callerPackage.callerPackage override fun onIntentResolved(result: IntentResolverResult) { viewState.filteredItem = result.filteredItem val handled = handleQuick(result) if (handled) { navigation.dismiss() } else { view.displayData(result) view.setTitle(titleForAction(result.filteredItem)) view.setupActionButtons() } } @Suppress("TooGenericExceptionCaught") private fun handleQuick(result: IntentResolverResult) = when { result.isEmpty -> { Timber.e("No app is found to handle url: %s", sourceIntent.dataString) view.toast(R.string.empty_resolver_activity) true } result.totalCount() == 1 -> { val activityInfo = result.filteredItem ?: result.resolved[0] try { navigation.startPreferred(activityInfo.intentFrom(sourceIntent), activityInfo.displayLabel) true } catch (e: Exception) { Timber.e(e) false } } else -> false } private fun titleForAction(filteredItem: DisplayActivityInfo?): String { return if (filteredItem != null) { resources.getString(R.string.which_view_application_named, filteredItem.displayLabel) } else { resources.getString(R.string.which_view_application) } } } private inner class ViewListener( private val view: ResolverView, private val navigation: ResolverView.Navigation ) : ResolverView.Listener { override fun onActionButtonClick(always: Boolean) { startAndPersist(viewState.checkedItem(), always) navigation.dismiss() } override fun onItemClick(activityInfo: DisplayActivityInfo) { if (viewState.shouldUseAlwaysOption() && activityInfo != viewState.lastSelected) { view.enableActionButtons() viewState.lastSelected = activityInfo } else { startAndPersist(activityInfo, alwaysCheck = false) } } private fun startAndPersist(activityInfo: DisplayActivityInfo, alwaysCheck: Boolean) { val intent = activityInfo.intentFrom(sourceIntent) navigation.startSelected(intent) useCase.persistSelectedIntent(intent, alwaysCheck) } override fun onPackagesChanged() { useCase.resolve() } } }
apache-2.0
0x1bad1d3a/Kaku
app/src/main/java/ca/fuwafuwa/kaku/TutorialEndFragment.kt
2
935
package ca.fuwafuwa.kaku import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.Button import androidx.fragment.app.Fragment import ca.fuwafuwa.kaku.Dialogs.GrantPermissionDialogFragment class TutorialEndFragment : Fragment() { private lateinit var rootView : View override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { rootView = inflater.inflate(R.layout.fragment_end, container, false) val button = rootView.findViewById<Button>(R.id.tutorial_end_start_kaku) button.setOnClickListener { GrantPermissionDialogFragment().show(fragmentManager!!, "GrantPermission") } return rootView } companion object { fun newInstance() : TutorialEndFragment { return TutorialEndFragment() } } }
bsd-3-clause
anlun/haskell-idea-plugin
plugin/src/org/jetbrains/grammar/bigTest/Main.kt
1
5084
package org.jetbrains.grammar.bigTest import java.io.File import java.io.FilenameFilter import org.jetbrains.grammar.parseFile import org.apache.commons.httpclient.methods.GetMethod import org.apache.commons.httpclient.HttpClient import org.apache.commons.httpclient.params.HttpMethodParams import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler import org.apache.commons.httpclient.HttpStatus import java.io.IOException import org.apache.commons.httpclient.HttpException import org.jetbrains.haskell.util.readLines import java.util.ArrayList import java.util.TreeMap import java.io.BufferedInputStream import java.io.FileInputStream import org.apache.commons.compress.compressors.gzip.GzipCompressorInputStream import org.apache.commons.compress.archivers.tar.TarArchiveInputStream import java.io.InputStream import java.io.ByteArrayOutputStream import com.sun.xml.internal.messaging.saaj.util.ByteInputStream import org.jetbrains.haskell.parser.lexer.HaskellLexer import org.jetbrains.haskell.parser.getCachedTokens import org.jetbrains.grammar.HaskellParser import org.jetbrains.grammar.dumb.LazyLLParser import java.io.FileWriter import java.io.FileOutputStream /** * Created by atsky on 12/12/14. */ fun main(args : Array<String>) { val map = TreeMap<String, MutableList<String>>() for (line in readLines(File("/home/atsky/.cabal/packages/hackage.haskell.org/00-index.cache"))) { val strings = line.split(' ') if (strings[0] == "pkg:") { val key = strings[1] val value = strings[2] map.getOrPut(key) { ArrayList<String>() }.add(value) } } for ((pkg, versions) in map) { versions.sort() val name = pkg + "-" + versions.lastOrNull() println(name) val tmp = File("hackage-cache") tmp.mkdirs() val file = File(tmp, name + ".tar.gz") if (!file.exists()) { val url = "http://hackage.haskell.org/package/${name}/${name}.tar.gz" println(url) val byteArray = fetchUrl(url) val stream = FileOutputStream(file) stream.write(byteArray) stream.close() } val byteArray = file.readBytes() val result = listHaskellFiles(name, ByteInputStream(byteArray, byteArray.size())) if (!result) { break } } } fun listHaskellFiles(packageName : String, stream : InputStream) : Boolean { val bin = BufferedInputStream(stream) val gzIn = GzipCompressorInputStream(bin); val tarArchiveInputStream = TarArchiveInputStream(gzIn) while (true) { val entry = tarArchiveInputStream.getNextTarEntry(); if (entry == null) { break } val name = entry.getName() if (name.endsWith(".hs")) { val content = readToArray(tarArchiveInputStream) if (!testFile(packageName, name, content)) { return false; } } } bin.close() return true } fun testFile(packageName: kotlin.String, name: kotlin.String?, content: kotlin.ByteArray) : Boolean { val lexer = HaskellLexer() lexer.start(String(content)) val cachedTokens = getCachedTokens(lexer, null) val grammar = HaskellParser(null).getGrammar() HaskellParser(null).findFirst(grammar) try { val parser = LazyLLParser(grammar, cachedTokens) val tree = parser.parse() if (tree == null) { println(packageName + " - " + name) println(String(content)) return false; } } catch (e : Exception) { println(packageName + " - " + name + " - exception") println(String(content)) return false; } return true; } fun readToArray(ins: InputStream): ByteArray { val buffer = ByteArrayOutputStream() var nRead: Int val data = ByteArray(16384) while (true) { nRead = ins.read(data, 0, data.size()) if (nRead == -1) { break; } buffer.write(data, 0, nRead); } buffer.flush(); return buffer.toByteArray(); } fun fetchUrl(url : String): ByteArray? { val client = HttpClient(); val method = GetMethod(url); // Provide custom retry handler is necessary method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, DefaultHttpMethodRetryHandler(3, false)); try { val statusCode = client.executeMethod(method); if (statusCode != HttpStatus.SC_OK) { System.err.println("Method failed: " + method.getStatusLine()); } // Read the response body. return method.getResponseBody() } catch (e : HttpException) { System.err.println("Fatal protocol violation: " + e.getMessage()); e.printStackTrace(); } catch (e : IOException) { System.err.println("Fatal transport error: " + e.getMessage()); e.printStackTrace(); } finally { // Release the connection. method.releaseConnection(); } return null }
apache-2.0
bazelbuild/rules_kotlin
src/main/kotlin/io/bazel/kotlin/builder/toolchain/CompilationTaskContext.kt
1
5609
/* * Copyright 2018 The Bazel Authors. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package io.bazel.kotlin.builder.toolchain import com.google.protobuf.MessageOrBuilder import com.google.protobuf.TextFormat import io.bazel.kotlin.model.CompilationTaskInfo import java.io.ByteArrayInputStream import java.io.ByteArrayOutputStream import java.io.File import java.io.PrintStream import java.nio.file.FileSystems class CompilationTaskContext( val info: CompilationTaskInfo, private val out: PrintStream, private val executionRoot: String = FileSystems.getDefault().getPath("").toAbsolutePath() .toString() + File.separator, ) { private val start = System.currentTimeMillis() private var timings: MutableList<String>? private var level = -1 private val isTracing: Boolean init { val debugging = info.debugList.toSet() timings = if (debugging.contains("timings")) mutableListOf() else null isTracing = debugging.contains("trace") } fun reportUnhandledException(throwable: Throwable) { throwable.printStackTrace(out) } @Suppress("unused") fun print(msg: String) { out.println(msg) } /** * Print a list of debugging lines. * * @param header a header string * @param lines a list of lines to print out * @param prefix a prefix to add to each line * @param filterEmpty if empty lines should be discarded or not */ fun printLines( header: String, lines: List<String>, prefix: String = "| ", filterEmpty: Boolean = false, ) { check(header.isNotEmpty()) out.println(if (header.endsWith(":")) header else "$header:") lines.forEach { if (it.isNotEmpty() || !filterEmpty) { out.println("$prefix$it") } } out.println() } fun <T> whenTracing(block: CompilationTaskContext.() -> T): T? { return if (isTracing) { block() } else { null } } /** * Print a proto message if debugging is enabled for the task. */ fun printProto(header: String, msg: MessageOrBuilder) { printLines(header, TextFormat.printToString(msg).split("\n"), filterEmpty = true) } /** * This method normalizes and reports the output from the Kotlin compiler. */ fun printCompilerOutput(lines: List<String>) { lines.map(::trimExecutionRootPrefix).forEach(out::println) } private fun trimExecutionRootPrefix(toPrint: String): String { // trim off the workspace component return if (toPrint.startsWith(executionRoot)) { toPrint.replaceFirst(executionRoot, "") } else { toPrint } } /** * Execute a compilation task. * * @throws CompilationStatusException if the compiler returns a status of anything but zero. * @param args the compiler command line switches * @param printOnFail if this is true the output will be printed if the task fails else the caller is responsible * for logging it by catching the [CompilationStatusException] exception. * @param compile the compilation method. */ fun executeCompilerTask( args: List<String>, compile: (Array<String>, PrintStream) -> Int, printOnFail: Boolean = true, printOnSuccess: Boolean = true, ): List<String> { val outputStream = ByteArrayOutputStream() val ps = PrintStream(outputStream) val result = compile(args.toTypedArray(), ps) val output = ByteArrayInputStream(outputStream.toByteArray()) .bufferedReader() .readLines() if (result != 0) { if (printOnFail) { printCompilerOutput(output) throw CompilationStatusException("compile phase failed", result) } throw CompilationStatusException("compile phase failed", result, output) } else if (printOnSuccess) { printCompilerOutput(output) } return output } /** * Runs a task and records the timings. */ fun <T> execute(name: String, task: () -> T): T = execute({ name }, task) /** * Runs a task and records the timings. */ @Suppress("MemberVisibilityCanBePrivate") fun <T> execute(name: () -> String, task: () -> T): T { return if (timings == null) { task() } else { pushTimedTask(name(), task) } } private inline fun <T> pushTimedTask(name: String, task: () -> T): T { level += 1 val previousTimings = timings timings = mutableListOf() return try { System.currentTimeMillis().let { start -> task().also { val stop = System.currentTimeMillis() previousTimings!! += "${" ".repeat(level)} * $name: ${stop - start} ms" previousTimings.addAll(timings!!) } } } finally { level -= 1 timings = previousTimings } } /** * This method should be called at the end of builder invocation. * * @param successful true if the task finished successfully. */ fun finalize(successful: Boolean) { if (successful) { timings?.also { printLines( "Task timings for ${info.label} (total: ${System.currentTimeMillis() - start} ms)", it, ) } } } }
apache-2.0
Finnerale/ExaCalc
src/main/kotlin/de/leopoldluley/exacalc/view/MainView.kt
1
1186
package de.leopoldluley.exacalc.view import javafx.scene.input.MouseEvent import tornadofx.* class MainView : View("ExaCalc") { val navigation: NavigationView by inject() val calculator: CalculatorView by inject() val settings: SettingsView by inject() val variables: VariablesView by inject() val functions: FunctionsView by inject() var current: View = calculator override val root = stackpane { prefHeight = 400.0 prefWidth = 600.0 setOnMouseDragged { doDrag(it) } setOnMousePressed { startDrag(it) } this += current this += navigation } fun show(view: View) { if (current !== view) { current.replaceWith(view, ViewTransition.Reveal(0.3.seconds)) current = view } } var lastXPos = 0.0 var lastYPos = 0.0 fun startDrag(event: MouseEvent) { lastXPos = event.screenX - FX.primaryStage.x lastYPos = event.screenY - FX.primaryStage.y } fun doDrag(event: MouseEvent) { println(event.screenX) FX.primaryStage.x = event.screenX - lastXPos FX.primaryStage.y = event.screenY - lastYPos } }
gpl-3.0
TCA-Team/TumCampusApp
app/src/main/java/de/tum/in/tumcampusapp/component/tumui/roomfinder/RoomFinderListAdapter.kt
1
1530
package de.tum.`in`.tumcampusapp.component.tumui.roomfinder import android.content.Context import android.view.View import android.view.ViewGroup import android.widget.TextView import de.tum.`in`.tumcampusapp.R import de.tum.`in`.tumcampusapp.component.other.generic.adapter.SimpleStickyListHeadersAdapter import de.tum.`in`.tumcampusapp.component.tumui.roomfinder.model.RoomFinderRoom /** * Custom UI adapter for a list of employees. */ class RoomFinderListAdapter( context: Context, items: List<RoomFinderRoom> ) : SimpleStickyListHeadersAdapter<RoomFinderRoom>(context, items.toMutableList()) { internal class ViewHolder { var tvRoomTitle: TextView? = null var tvBuildingTitle: TextView? = null } override fun getView(position: Int, convertView: View?, parent: ViewGroup): View { val holder: ViewHolder val view: View if (convertView == null) { view = inflater.inflate(R.layout.list_roomfinder_item, parent, false) holder = ViewHolder() holder.tvRoomTitle = view.findViewById(R.id.startup_actionbar_title) holder.tvBuildingTitle = view.findViewById(R.id.building) view.tag = holder } else { view = convertView holder = view.tag as ViewHolder } val room = itemList[position] // Setting all values in listView holder.tvRoomTitle?.text = room.info holder.tvBuildingTitle?.text = room.formattedAddress return view } }
gpl-3.0
DemonWav/StatCraftGradle
statcraft-bukkit/src/main/kotlin/com/demonwav/statcraft/sql/BukkitDatabaseManager.kt
1
345
/* * StatCraft Plugin * * Copyright (c) 2016 Kyle Wood (DemonWav) * https://www.demonwav.com * * MIT License */ package com.demonwav.statcraft.sql import org.apache.commons.lang.StringEscapeUtils class BukkitDatabaseManager : AbstractDatabaseManager() { override fun escapeSql(s: String): String = StringEscapeUtils.escapeSql(s) }
mit
Polidea/RxAndroidBle
sample-kotlin/src/main/kotlin/com/polidea/rxandroidble2/samplekotlin/util/ScanExceptionHandler.kt
1
3179
package com.polidea.rxandroidble2.samplekotlin.util import android.app.Activity import android.util.Log import com.polidea.rxandroidble2.exceptions.BleScanException import com.polidea.rxandroidble2.samplekotlin.R import java.util.Date import java.util.Locale import java.util.concurrent.TimeUnit /** * Helper functions to show BleScanException error messages as toasts. */ /** * Mapping of exception reasons to error string resource ids. Add new mappings here. */ private val ERROR_MESSAGES = mapOf( BleScanException.BLUETOOTH_NOT_AVAILABLE to R.string.error_bluetooth_not_available, BleScanException.BLUETOOTH_DISABLED to R.string.error_bluetooth_disabled, BleScanException.LOCATION_PERMISSION_MISSING to R.string.error_location_permission_missing, BleScanException.LOCATION_SERVICES_DISABLED to R.string.error_location_services_disabled, BleScanException.SCAN_FAILED_ALREADY_STARTED to R.string.error_scan_failed_already_started, BleScanException.SCAN_FAILED_APPLICATION_REGISTRATION_FAILED to R.string.error_scan_failed_application_registration_failed, BleScanException.SCAN_FAILED_FEATURE_UNSUPPORTED to R.string.error_scan_failed_feature_unsupported, BleScanException.SCAN_FAILED_INTERNAL_ERROR to R.string.error_scan_failed_internal_error, BleScanException.SCAN_FAILED_OUT_OF_HARDWARE_RESOURCES to R.string.error_scan_failed_out_of_hardware_resources, BleScanException.BLUETOOTH_CANNOT_START to R.string.error_bluetooth_cannot_start, BleScanException.UNKNOWN_ERROR_CODE to R.string.error_unknown_error ) /** * Show toast in this Activity with error message appropriate to exception reason. * * @param exception BleScanException to show error message for */ internal fun Activity.showError(exception: BleScanException) = getErrorMessage(exception).let { errorMessage -> Log.e("Scanning", errorMessage, exception) showSnackbarShort(errorMessage) } private fun Activity.getErrorMessage(exception: BleScanException): String = // Special case, as there might or might not be a retry date suggestion if (exception.reason == BleScanException.UNDOCUMENTED_SCAN_THROTTLE) { getScanThrottleErrorMessage(exception.retryDateSuggestion) } else { // Handle all other possible errors ERROR_MESSAGES[exception.reason]?.let { errorResId -> getString(errorResId) } ?: run { // unknown error - return default message Log.w("Scanning", String.format(getString(R.string.error_no_message), exception.reason)) getString(R.string.error_unknown_error) } } private fun Activity.getScanThrottleErrorMessage(retryDate: Date?): String = with(StringBuilder(getString(R.string.error_undocumented_scan_throttle))) { retryDate?.let { date -> String.format( Locale.getDefault(), getString(R.string.error_undocumented_scan_throttle_retry), date.secondsUntil ).let { append(it) } } toString() } private val Date.secondsUntil: Long get() = TimeUnit.MILLISECONDS.toSeconds(time - System.currentTimeMillis())
apache-2.0
lydia-schiff/hella-renderscript
hella/src/main/java/com/lydiaschiff/hella/renderer/Lut3dRsRenderer.kt
1
2123
package com.lydiaschiff.hella.renderer import android.renderscript.Allocation import android.renderscript.Element import android.renderscript.RenderScript import android.renderscript.ScriptIntrinsic3DLUT import com.lydiaschiff.hella.RsRenderer import com.lydiaschiff.hella.RsUtil open class Lut3dRsRenderer(val cubeDim: Int) : RsRenderer { // explicit zero-arg constructor constructor() : this(CUBE_DIM) // all guarded by "this" private lateinit var lut3dScript: ScriptIntrinsic3DLUT protected lateinit var lutAlloc: Allocation protected var firstDraw = true private set protected var hasUpdate = false protected val rgbFloatLut: FloatArray = FloatArray(cubeDim * cubeDim * cubeDim * 3) @Synchronized override fun renderFrame(rs: RenderScript, inAlloc: Allocation, outAlloc: Allocation) { if (firstDraw) { lut3dScript = ScriptIntrinsic3DLUT.create(rs, Element.RGBA_8888(rs)) lutAlloc = RsUtil.lut3dAlloc(rs, SET_IDENTITY_BY_DEFAULT, cubeDim) lut3dScript.setLUT(lutAlloc) onFirstDraw(rs) firstDraw = false } if (hasUpdate) { onUpdate() } lut3dScript.forEach(inAlloc, outAlloc) } protected open fun onFirstDraw(rs : RenderScript) = Unit protected open fun onUpdate() { RsUtil.copyRgbFloatsToAlloc(rgbFloatLut, lutAlloc) lut3dScript.setLUT(lutAlloc) hasUpdate = false } @Synchronized fun setLutData(rgbFloatLut: FloatArray) { require(rgbFloatLut.size == N_VALUES_RGB) if (!rgbFloatLut.contentEquals(this.rgbFloatLut)) { rgbFloatLut.copyInto(this.rgbFloatLut) hasUpdate = true } } override val name = "Lut3dRenderer Cool Algebra!" override val canRenderInPlace = true companion object { const val CUBE_DIM = 17 const val N_COLORS = CUBE_DIM * CUBE_DIM * CUBE_DIM const val N_VALUES_RGB = N_COLORS * 3 const val SET_IDENTITY_BY_DEFAULT = true fun emptyRgbFloatLut() = FloatArray(N_VALUES_RGB) } }
mit
TCA-Team/TumCampusApp
app/src/main/java/de/tum/in/tumcampusapp/component/ui/barrierfree/BarrierFreeFacilitiesActivity.kt
1
2898
package de.tum.`in`.tumcampusapp.component.ui.barrierfree import android.content.Intent import android.os.Bundle import android.view.View import android.widget.AdapterView import de.tum.`in`.tumcampusapp.R import de.tum.`in`.tumcampusapp.component.other.general.RecentsDao import de.tum.`in`.tumcampusapp.component.other.general.model.Recent import de.tum.`in`.tumcampusapp.component.other.generic.activity.ActivityForAccessingTumCabe import de.tum.`in`.tumcampusapp.component.other.locations.LocationManager import de.tum.`in`.tumcampusapp.component.tumui.roomfinder.RoomFinderDetailsActivity import de.tum.`in`.tumcampusapp.component.tumui.roomfinder.RoomFinderListAdapter import de.tum.`in`.tumcampusapp.component.tumui.roomfinder.model.RoomFinderRoom import de.tum.`in`.tumcampusapp.database.TcaDb import kotlinx.android.synthetic.main.activity_barrier_free_facilities.* import retrofit2.Call class BarrierFreeFacilitiesActivity : ActivityForAccessingTumCabe<List<RoomFinderRoom>>( R.layout.activity_barrier_free_facilities ), AdapterView.OnItemSelectedListener { private val recents: RecentsDao by lazy { TcaDb.getInstance(this).recentsDao() } private val locationManager: LocationManager by lazy { LocationManager(this) } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) spinnerToolbar.onItemSelectedListener = this } override fun onItemSelected(parent: AdapterView<*>, view: View, position: Int, id: Long) { when (position) { 0 -> fetchApiCallForCurrentLocation() 1 -> executeApiCall(apiClient.listOfElevators) else -> executeApiCall(apiClient.listOfElevators) } } private fun fetchApiCallForCurrentLocation() { locationManager.fetchBuildingIDFromCurrentLocation { val apiCall = apiClient.getListOfNearbyFacilities(it) executeApiCall(apiCall) } } private fun executeApiCall(apiCall: Call<List<RoomFinderRoom>>?) { apiCall?.let { fetch(it) } ?: showError(R.string.error_something_wrong) } override fun onDownloadSuccessful(response: List<RoomFinderRoom>) { barrierFreeFacilitiesListView.adapter = RoomFinderListAdapter(this, response) barrierFreeFacilitiesListView.setOnItemClickListener { _, _, index, _ -> val facility = response[index] recents.insert(Recent(facility.toString(), RecentsDao.ROOMS)) openRoomFinderDetails(facility) } } private fun openRoomFinderDetails(facility: RoomFinderRoom) { val intent = Intent(this, RoomFinderDetailsActivity::class.java) intent.putExtra(RoomFinderDetailsActivity.EXTRA_ROOM_INFO, facility) startActivity(intent) } override fun onNothingSelected(parent: AdapterView<*>) { // Nothing selected } }
gpl-3.0
rhdunn/xquery-intellij-plugin
src/lang-xpath/main/uk/co/reecedunn/intellij/plugin/xpath/ast/full/text/FTContainsExpr.kt
1
903
/* * Copyright (C) 2017, 2020 Reece H. Dunn * * 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 uk.co.reecedunn.intellij.plugin.xpath.ast.full.text import com.intellij.psi.PsiElement import uk.co.reecedunn.intellij.plugin.xpm.optree.expression.XpmExpression /** * An XQuery Full Text 1.0 `FTContainsExpr` node in the XQuery AST. */ interface FTContainsExpr : PsiElement, XpmExpression
apache-2.0
laurentvdl/sqlbuilder
src/main/kotlin/sqlbuilder/meta/JavaGetterSetterPropertyReference.kt
1
2107
package sqlbuilder.meta import sqlbuilder.PersistenceException import java.lang.reflect.Method /** * Wrapper for bean property using getter/setter reflection. */ class JavaGetterSetterPropertyReference(override var name: String, private val method: Method, override var classType: Class<*>) : PropertyReference { override val columnName: String = findColumnName() override fun set(bean: Any, value: Any?) { try { if (!(value == null && classType.isPrimitive)) { method.invoke(bean, value) } } catch (e: Exception) { val signature = "${method.name}(${method.parameterTypes?.joinToString(",")})" throw PersistenceException("unable to set value $name to '$value' on bean $bean using setter <$signature>, expected argument of type <$classType>, but got <${value?.javaClass}>", e) } } override fun get(bean: Any): Any? { try { if (!method.isAccessible) { method.isAccessible = true } return method.invoke(bean) } catch (e: Exception) { val signature = "${method.name}(${method.parameterTypes?.joinToString(",")})" throw PersistenceException("unable to get value $name from bean $bean using getter $signature", e) } } private fun findColumnName(): String { return try { method.declaringClass.getDeclaredField(name).getAnnotation(Column::class.java)?.name ?: name } catch (ignore: NoSuchFieldException) { name } } override fun equals(other: Any?): Boolean { if (this === other) return true if (other == null || javaClass != other.javaClass) return false val setter = other as JavaGetterSetterPropertyReference return name == setter.name } override fun hashCode(): Int { var result = name.hashCode() result = 31 * result + classType.hashCode() return result } override fun toString(): String { return "property <${method.declaringClass}.$name>" } }
apache-2.0
mitallast/netty-queue
src/main/java/org/mitallast/queue/crdt/bucket/BucketFactory.kt
1
119
package org.mitallast.queue.crdt.bucket interface BucketFactory { fun create(index: Int, replica: Long): Bucket }
mit
StepicOrg/stepic-android
app/src/main/java/org/stepik/android/view/injection/profile/UserId.kt
2
116
package org.stepik.android.view.injection.profile import javax.inject.Qualifier @Qualifier annotation class UserId
apache-2.0
NerdNumber9/TachiyomiEH
app/src/main/java/eu/kanade/tachiyomi/ui/reader/loader/ZipPageLoader.kt
1
1813
package eu.kanade.tachiyomi.ui.reader.loader import eu.kanade.tachiyomi.source.model.Page import eu.kanade.tachiyomi.ui.reader.model.ReaderPage import eu.kanade.tachiyomi.util.ImageUtil import net.greypanther.natsort.CaseInsensitiveSimpleNaturalComparator import rx.Observable import java.io.File import java.util.zip.ZipEntry import java.util.zip.ZipFile /** * Loader used to load a chapter from a .zip or .cbz file. */ class ZipPageLoader(file: File) : PageLoader() { /** * The zip file to load pages from. */ private val zip = ZipFile(file) /** * Recycles this loader and the open zip. */ override fun recycle() { super.recycle() zip.close() } /** * Returns an observable containing the pages found on this zip archive ordered with a natural * comparator. */ override fun getPages(): Observable<List<ReaderPage>> { val comparator = CaseInsensitiveSimpleNaturalComparator.getInstance<String>() return zip.entries().toList() .filter { !it.isDirectory && ImageUtil.isImage(it.name) { zip.getInputStream(it) } } .sortedWith(Comparator<ZipEntry> { f1, f2 -> comparator.compare(f1.name, f2.name) }) .mapIndexed { i, entry -> val streamFn = { zip.getInputStream(entry) } ReaderPage(i).apply { stream = streamFn status = Page.READY } } .let { Observable.just(it) } } /** * Returns an observable that emits a ready state unless the loader was recycled. */ override fun getPage(page: ReaderPage): Observable<Int> { return Observable.just(if (isRecycled) { Page.ERROR } else { Page.READY }) } }
apache-2.0
hitoshura25/Media-Player-Omega-Android
auth_framework/src/main/java/com/vmenon/mpo/auth/framework/openid/viewmodel/OpenIdHandlerViewModel.kt
1
4449
package com.vmenon.mpo.auth.framework.openid.viewmodel import android.app.Activity import android.content.Intent import androidx.activity.result.ActivityResultLauncher import androidx.activity.result.contract.ActivityResultContracts.StartActivityForResult import androidx.fragment.app.Fragment import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.vmenon.mpo.auth.framework.Authenticator import com.vmenon.mpo.auth.framework.openid.OpenIdAuthenticator import com.vmenon.mpo.auth.framework.openid.fragment.OpenIdHandlerFragment.Companion.EXTRA_OPERATION import com.vmenon.mpo.auth.framework.openid.fragment.OpenIdHandlerFragment.Companion.Operation import com.vmenon.mpo.system.domain.Logger import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import net.openid.appauth.AuthorizationException import net.openid.appauth.AuthorizationResponse import net.openid.appauth.EndSessionResponse import java.lang.IllegalStateException import javax.inject.Inject class OpenIdHandlerViewModel : ViewModel() { @Inject lateinit var authenticator: Authenticator @Inject lateinit var logger: Logger private val authenticated = MutableLiveData<Boolean>() private var startAuthContract: ActivityResultLauncher<Intent>? = null private var logoutContract: ActivityResultLauncher<Intent>? = null fun authenticated(): LiveData<Boolean> = authenticated fun onCreated(fragment: Fragment) { startAuthContract = fragment.registerForActivityResult( StartActivityForResult() ) { activityResult -> handlePerformAuthOperationResult(activityResult.resultCode, activityResult.data) } logoutContract = fragment.registerForActivityResult( StartActivityForResult() ) { activityResult -> handleEndSessionOperationResult(activityResult.resultCode, activityResult.data) } } fun onResume(fragment: Fragment) { val operation = fragment.arguments?.getSerializable(EXTRA_OPERATION) as Operation? if (operation != null) { fragment.arguments?.remove(EXTRA_OPERATION) when (operation) { Operation.PERFORM_AUTH -> startAuthContract?.let { contract -> handlePerformAuthOperationRequest(contract) } ?: throw IllegalStateException("startAuthContract should not be null!") Operation.LOGOUT -> logoutContract?.let { contract -> handleEndSessionRequest(contract) } ?: throw IllegalStateException("logoutContract should not be null!") } } } private fun handlePerformAuthOperationRequest(launcher: ActivityResultLauncher<Intent>) { viewModelScope.launch(Dispatchers.IO) { (authenticator as OpenIdAuthenticator).performAuthenticate(launcher) } } private fun handleEndSessionRequest(launcher: ActivityResultLauncher<Intent>) { viewModelScope.launch(Dispatchers.IO) { if (!(authenticator as OpenIdAuthenticator).performLogoutIfNecessary(launcher)) { authenticated.postValue(false) // Already logged out I Guess } } } private fun handlePerformAuthOperationResult(resultCode: Int, data: Intent?) { if (resultCode == Activity.RESULT_OK && data != null) { viewModelScope.launch(Dispatchers.IO) { (authenticator as OpenIdAuthenticator).handleAuthResponse( AuthorizationResponse.fromIntent(data), AuthorizationException.fromIntent(data) ) authenticated.postValue(true) } } else { logger.println("Issue with handling auth result $resultCode $data") authenticated.postValue(false) } } private fun handleEndSessionOperationResult(resultCode: Int, data: Intent?) { var exception: AuthorizationException? = null if (resultCode == Activity.RESULT_OK && data != null) { exception = AuthorizationException.fromIntent(data) } viewModelScope.launch(Dispatchers.IO) { (authenticator as OpenIdAuthenticator).handleEndSessionResponse( exception ) authenticated.postValue(false) } } }
apache-2.0
FelixKlauke/mercantor
core/src/main/kotlin/de/d3adspace/mercantor/core/MercantorImpl.kt
1
2015
package de.d3adspace.mercantor.core import de.d3adspace.mercantor.commons.model.HeartbeatModel import de.d3adspace.mercantor.commons.model.ServiceModel import de.d3adspace.mercantor.commons.model.ServiceStatus import de.d3adspace.mercantor.core.service.ServiceRepository import org.slf4j.LoggerFactory import java.util.* class MercantorImpl(private val serviceRepository: ServiceRepository) : Mercantor { private val logger = LoggerFactory.getLogger(MercantorImpl::class.java) init { serviceRepository.getServiceExpiration().subscribe(this::handleExpiration) } override fun registerService(service: ServiceModel) { logger.info("Registering new instance for vip address ${service.vipAddress}.") serviceRepository.register(service) logger.info("Registered new instance for vip address ${service.vipAddress} with instance id ${service.instanceId}") } override fun serviceExists(instanceId: UUID): Boolean { return serviceRepository.exists(instanceId) } override fun deleteService(instanceId: UUID) { logger.info("Invalidating instance with id $instanceId.") serviceRepository.delete(instanceId) logger.info("Invalidated instance with id $instanceId") } override fun handleHeartbeat(heartbeat: HeartbeatModel) { logger.info("Got heartbeat from instance with id ${heartbeat.instanceId}") serviceRepository.updateStatus(heartbeat) } override fun getService(vipAddress: String): List<ServiceModel> { logger.info("Querying instances behind vip address $vipAddress.") val service = serviceRepository.getService(vipAddress) logger.info("We currently know about of ${service.size} instances for $vipAddress.") return service.filter { serviceModel -> serviceModel.status == ServiceStatus.UP } } private fun handleExpiration(service: ServiceModel) { logger.info("The service ${service.instanceId} expired.") } }
mit