repo_name
stringlengths 7
79
| path
stringlengths 8
206
| copies
stringclasses 36
values | size
stringlengths 2
6
| content
stringlengths 55
523k
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 7.18
99.5
| line_max
int64 16
979
| alpha_frac
float64 0.3
0.87
| ratio
float64 2.01
8.07
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
spark/photon-tinker-android
|
meshui/src/main/java/io/particle/mesh/ui/setup/ScanForWiFiNetworksFragment.kt
|
1
|
4016
|
package io.particle.mesh.ui.setup
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.FragmentActivity
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.ListAdapter
import androidx.recyclerview.widget.RecyclerView
import io.particle.android.common.easyDiffUtilCallback
import io.particle.firmwareprotos.ctrl.wifi.WifiNew
import io.particle.firmwareprotos.ctrl.wifi.WifiNew.ScanNetworksReply
import io.particle.mesh.common.truthy
import io.particle.mesh.setup.WiFiStrength
import io.particle.mesh.setup.flow.FlowRunnerUiListener
import io.particle.mesh.ui.BaseFlowFragment
import io.particle.mesh.ui.R
import io.particle.mesh.ui.inflateRow
import kotlinx.android.synthetic.main.fragment_scan_for_wi_fi_networks.*
import kotlinx.android.synthetic.main.p_mesh_row_wifi_scan.view.*
import mu.KotlinLogging
class ScanForWiFiNetworksFragment : BaseFlowFragment() {
private lateinit var adapter: ScannedWifiNetworksAdapter
private val log = KotlinLogging.logger {}
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
return inflater.inflate(R.layout.fragment_scan_for_wi_fi_networks, container, false)
}
override fun onFragmentReady(activity: FragmentActivity, flowUiListener: FlowRunnerUiListener) {
super.onFragmentReady(activity, flowUiListener)
adapter = ScannedWifiNetworksAdapter { onWifiNetworkSelected(it.network) }
p_scanforwifi_list.adapter = adapter
flowUiListener.wifi.getWifiScannerForTargetDevice().observe(
this,
Observer { onNetworksUpdated(it) }
)
}
private fun onNetworksUpdated(networks: List<ScanNetworksReply.Network>?) {
adapter.submitList(networks?.asSequence()
?.filter { it.ssid.truthy() }
?.distinctBy { it.ssid }
?.map { ScannedWifiNetwork(it.ssid, it) }
?.sortedBy { it.ssid }
?.sortedByDescending { it.wiFiStrength.sortValue }
?.toList()
)
}
private fun onWifiNetworkSelected(networkInfo: ScanNetworksReply.Network) {
flowUiListener?.wifi?.setWifiNetworkToConfigure(networkInfo)
}
}
private data class ScannedWifiNetwork(
val ssid: String,
val network: ScanNetworksReply.Network
) {
val wiFiStrength: WiFiStrength = WiFiStrength.fromInt(network.rssi)
}
private class ScannedWifiNetworkHolder(var rowRoot: View) : RecyclerView.ViewHolder(rowRoot) {
val ssid = rowRoot.p_scanforwifi_ssid
val securityIcon = rowRoot.p_scanforwifi_security_icon
val strengthIcon = rowRoot.p_scanforwifi_strength_icon
}
private class ScannedWifiNetworksAdapter(
private val onItemClicked: (ScannedWifiNetwork) -> Unit
) : ListAdapter<ScannedWifiNetwork, ScannedWifiNetworkHolder>(
easyDiffUtilCallback { rowEntry: ScannedWifiNetwork -> rowEntry.network.ssid }
) {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ScannedWifiNetworkHolder {
return ScannedWifiNetworkHolder(parent.inflateRow(R.layout.p_mesh_row_wifi_scan))
}
override fun onBindViewHolder(holder: ScannedWifiNetworkHolder, position: Int) {
val item = getItem(position)
holder.ssid.text = item.ssid
holder.securityIcon.isVisible = item.network.security != WifiNew.Security.NO_SECURITY
holder.strengthIcon.setImageResource(item.wiFiStrength.iconValue)
holder.rowRoot.setOnClickListener { onItemClicked(item) }
}
private val WiFiStrength.iconValue: Int
get() {
return when (this) {
WiFiStrength.STRONG -> R.drawable.p_mesh_ic_wifi_strength_high
WiFiStrength.MEDIUM -> R.drawable.p_mesh_ic_wifi_strength_medium
WiFiStrength.WEAK -> R.drawable.p_mesh_ic_wifi_strength_low
}
}
}
|
apache-2.0
|
a9cf4473a150f0d0dc3655bb937583c2
| 34.22807 | 100 | 0.730329 | 4.27234 | false | false | false | false |
robinverduijn/gradle
|
buildSrc/subprojects/buildquality/src/main/kotlin/org/gradle/gradlebuild/buildquality/TaskPropertyValidationPlugin.kt
|
1
|
3533
|
/*
* Copyright 2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gradle.gradlebuild.buildquality
import accessors.java
import accessors.reporting
import org.gradle.api.Plugin
import org.gradle.api.Project
import org.gradle.api.artifacts.Configuration
import org.gradle.api.attributes.Attribute
import org.gradle.api.attributes.Usage
import org.gradle.api.tasks.testing.Test
import org.gradle.kotlin.dsl.*
import org.gradle.plugin.devel.tasks.ValidateTaskProperties
private
const val validateTaskName = "validateTaskProperties"
private
const val reportFileName = "task-properties/report.txt"
open class TaskPropertyValidationPlugin : Plugin<Project> {
override fun apply(project: Project): Unit = project.run {
afterEvaluate {
// This is in an after evaluate block to defer the decision until after the `java-gradle-plugin` may have been applied, so as to not collide with it
// It would be better to use some convention plugins instead, that apply a fixes set of plugins (including this one)
if (plugins.hasPlugin("java-base")) {
val validationRuntime by configurations.creating {
isCanBeConsumed = false
attributes.attribute(Usage.USAGE_ATTRIBUTE, objects.named(Usage.JAVA_RUNTIME))
// Required to select the right :distributions variant
attributes.attribute(Attribute.of("org.gradle.runtime", String::class.java), "minimal")
}
dependencies.add(
validationRuntime.name,
dependencies.project(":distributions")
)
val validateTask = if (plugins.hasPlugin("java-gradle-plugin")) {
tasks.named(validateTaskName, ValidateTaskProperties::class)
} else {
tasks.register(validateTaskName, ValidateTaskProperties::class)
}
validateTask {
configureValidateTask(validationRuntime)
}
tasks.named("codeQuality") {
dependsOn(validateTask)
}
tasks.withType(Test::class).configureEach {
shouldRunAfter(validateTask)
}
}
}
}
private
fun ValidateTaskProperties.configureValidateTask(validationRuntime: Configuration) {
val main by project.java.sourceSets
dependsOn(main.output)
classes.setFrom(main.output.classesDirs)
classpath.from(main.output) // to pick up resources too
classpath.from(main.runtimeClasspath)
classpath.from(validationRuntime)
// TODO Should we provide a more intuitive way in the task definition to configure this property from Kotlin?
outputFile.set(project.reporting.baseDirectory.file(reportFileName))
failOnWarning = true
enableStricterValidation = true
}
}
|
apache-2.0
|
fc3f0f9d9242ae247b9f2846bb741e59
| 38.255556 | 160 | 0.662893 | 4.906944 | false | true | false | false |
f-droid/fdroidclient
|
libs/index/src/androidTest/kotlin/org/fdroid/index/v2/ReflectionDifferTest.kt
|
1
|
6945
|
package org.fdroid.index.v2
import kotlinx.serialization.SerializationException
import kotlinx.serialization.json.JsonArray
import kotlinx.serialization.json.JsonNull
import kotlinx.serialization.json.JsonObject
import kotlinx.serialization.json.JsonPrimitive
import kotlinx.serialization.json.jsonObject
import org.fdroid.index.IndexParser
import org.fdroid.index.IndexParser.json
import org.fdroid.index.assetPath
import org.fdroid.index.parseV2
import org.fdroid.test.DiffUtils.clean
import org.fdroid.test.DiffUtils.cleanMetadata
import org.fdroid.test.DiffUtils.cleanRepo
import org.fdroid.test.DiffUtils.cleanVersion
import java.io.File
import java.io.FileInputStream
import kotlin.reflect.full.primaryConstructor
import kotlin.test.Test
import kotlin.test.assertContains
import kotlin.test.assertEquals
import kotlin.test.assertFailsWith
internal class ReflectionDifferTest {
@Test
fun testEmptyToMin() = testDiff(
diffPath = "$assetPath/diff-empty-min/23.json",
startPath = "$assetPath/index-empty-v2.json",
endPath = "$assetPath/index-min-v2.json",
)
@Test
fun testEmptyToMid() = testDiff(
diffPath = "$assetPath/diff-empty-mid/23.json",
startPath = "$assetPath/index-empty-v2.json",
endPath = "$assetPath/index-mid-v2.json",
)
@Test
fun testEmptyToMax() = testDiff(
diffPath = "$assetPath/diff-empty-max/23.json",
startPath = "$assetPath/index-empty-v2.json",
endPath = "$assetPath/index-max-v2.json",
)
@Test
fun testMinToMid() = testDiff(
diffPath = "$assetPath/diff-empty-mid/42.json",
startPath = "$assetPath/index-min-v2.json",
endPath = "$assetPath/index-mid-v2.json",
)
@Test
fun testMinToMax() = testDiff(
diffPath = "$assetPath/diff-empty-max/42.json",
startPath = "$assetPath/index-min-v2.json",
endPath = "$assetPath/index-max-v2.json",
)
@Test
fun testMidToMax() = testDiff(
diffPath = "$assetPath/diff-empty-max/1337.json",
startPath = "$assetPath/index-mid-v2.json",
endPath = "$assetPath/index-max-v2.json",
)
@Test
fun testClassWithoutPrimaryConstructor() {
class NoConstructor {
@Suppress("ConvertSecondaryConstructorToPrimary", "UNUSED_PARAMETER")
constructor(i: Int)
}
assertFailsWith<SerializationException> {
ReflectionDiffer.applyDiff(NoConstructor(0), JsonObject(emptyMap()))
}.also { assertContains(it.message!!, "no primary constructor") }
}
@Test
fun testNoMemberForConstructorParameter() {
@Suppress("UNUSED_PARAMETER")
class NoConstructor(i: Int)
assertFailsWith<SerializationException> {
ReflectionDiffer.applyDiff(NoConstructor(0), JsonObject(emptyMap()))
}.also { assertContains(it.message!!, "no member property for constructor") }
}
@Test
fun testNullingRequiredParameter() {
data class Required(val test: String)
assertFailsWith<SerializationException> {
ReflectionDiffer.applyDiff(
Required("foo"),
JsonObject(mapOf("test" to JsonNull))
)
}.also { assertContains(it.message!!, "not nullable: test") }
}
@Test
fun testWrongTypes() {
data class Types(val str: String? = null, val i: Int? = null, val l: Long? = null)
// string as object
assertFailsWith<SerializationException> {
ReflectionDiffer.applyDiff(
Types(str = "foo"),
JsonObject(mapOf("str" to JsonObject(emptyMap())))
)
}.also { assertContains(it.message!!, "str no string") }
// int as string
assertFailsWith<SerializationException> {
ReflectionDiffer.applyDiff(
Types(i = 23),
JsonObject(mapOf("i" to JsonPrimitive("test")))
)
}.also { assertContains(it.message!!, "i no int") }
// int as long
assertFailsWith<SerializationException> {
ReflectionDiffer.applyDiff(
Types(i = 23),
JsonObject(mapOf("i" to JsonPrimitive(Long.MAX_VALUE)))
)
}.also { assertContains(it.message!!, "i no int") }
// long as array
assertFailsWith<SerializationException> {
ReflectionDiffer.applyDiff(
Types(l = 23L),
JsonObject(mapOf("l" to JsonArray(emptyList())))
)
}.also { assertContains(it.message!!, "l no long") }
}
private fun testDiff(diffPath: String, startPath: String, endPath: String) {
val diffFile = File(diffPath)
val startFile = File(startPath)
val endFile = File(endPath)
val diff = json.parseToJsonElement(diffFile.readText()).jsonObject
val start = IndexParser.parseV2(FileInputStream(startFile))
val end = IndexParser.parseV2(FileInputStream(endFile))
// diff repo
val repoJson = diff["repo"]!!.jsonObject.cleanRepo()
val repo: RepoV2 = ReflectionDiffer.applyDiff(start.repo.clean(), repoJson)
assertEquals(end.repo.clean(), repo)
// apply diff to all start packages present in end index
end.packages.forEach packages@{ (packageName, packageV2) ->
val packageDiff = diff["packages"]?.jsonObject?.get(packageName)?.jsonObject
?: return@packages
// apply diff to metadata
val metadataDiff = packageDiff.jsonObject["metadata"]?.jsonObject?.cleanMetadata()
if (metadataDiff != null) {
val startMetadata = start.packages[packageName]?.metadata?.clean() ?: run {
val factory = MetadataV2::class.primaryConstructor!!
ReflectionDiffer.constructFromJson(factory, metadataDiff)
}
val metadataV2: MetadataV2 = ReflectionDiffer.applyDiff(startMetadata, metadataDiff)
assertEquals(packageV2.metadata.clean(), metadataV2)
}
// apply diff to all start versions present in end index
packageV2.versions.forEach versions@{ (versionId, packageVersionV2) ->
val versionsDiff = packageDiff.jsonObject["versions"]?.jsonObject
?.get(versionId)?.jsonObject?.cleanVersion() ?: return@versions
val startVersion = start.packages[packageName]?.versions?.get(versionId)?.clean()
?: run {
val factory = PackageVersionV2::class.primaryConstructor!!
ReflectionDiffer.constructFromJson(factory, versionsDiff)
}
val version: PackageVersionV2 =
ReflectionDiffer.applyDiff(startVersion, versionsDiff)
assertEquals(packageVersionV2.clean(), version)
}
}
}
}
|
gpl-3.0
|
61ec55526453014bd8660b73cf78efe5
| 37.798883 | 100 | 0.630382 | 4.554098 | false | true | false | false |
google/horologist
|
media-ui/src/androidTest/java/com/google/android/horologist/media/ui/components/MediaControlButtonsWithProgressTest.kt
|
1
|
11226
|
/*
* Copyright 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
@file:OptIn(ExperimentalHorologistMediaUiApi::class)
package com.google.android.horologist.media.ui.components
import androidx.compose.ui.test.assertIsDisplayed
import androidx.compose.ui.test.assertIsEnabled
import androidx.compose.ui.test.assertIsNotEnabled
import androidx.compose.ui.test.junit4.createComposeRule
import androidx.compose.ui.test.onNodeWithContentDescription
import androidx.compose.ui.test.performClick
import com.google.android.horologist.media.ui.ExperimentalHorologistMediaUiApi
import com.google.android.horologist.test.toolbox.matchers.hasProgressBar
import org.junit.Rule
import org.junit.Test
class MediaControlButtonsWithProgressTest {
@get:Rule
val composeTestRule = createComposeRule()
@Test
fun givenIsPlaying_thenPauseButtonIsDisplayed() {
// given
val playing = true
composeTestRule.setContent {
MediaControlButtons(
onPlayButtonClick = {},
onPauseButtonClick = {},
playPauseButtonEnabled = true,
playing = playing,
onSeekToPreviousButtonClick = {},
seekToPreviousButtonEnabled = true,
onSeekToNextButtonClick = {},
seekToNextButtonEnabled = true,
percent = 0.25f
)
}
// then
composeTestRule.onNodeWithContentDescription("Pause")
.assertIsDisplayed()
composeTestRule.onNodeWithContentDescription("Play")
.assertDoesNotExist()
}
@Test
fun givenIsPlaying_whenPauseIsClicked_thenCorrectEventIsTriggered() {
// given
val playing = true
var clicked = false
composeTestRule.setContent {
MediaControlButtons(
onPlayButtonClick = {},
onPauseButtonClick = { clicked = true },
playPauseButtonEnabled = true,
playing = playing,
onSeekToPreviousButtonClick = {},
seekToPreviousButtonEnabled = true,
onSeekToNextButtonClick = {},
seekToNextButtonEnabled = true,
percent = 0.25f
)
}
// when
composeTestRule.onNodeWithContentDescription("Pause")
.performClick()
// then
// assert that the click event was assigned to the correct button
composeTestRule.waitUntil(timeoutMillis = 1_000) { clicked }
}
@Test
fun givenIsNOTPlaying_thenPlayButtonIsDisplayed() {
// given
val playing = false
composeTestRule.setContent {
MediaControlButtons(
onPlayButtonClick = {},
onPauseButtonClick = {},
playPauseButtonEnabled = true,
playing = playing,
onSeekToPreviousButtonClick = {},
seekToPreviousButtonEnabled = true,
onSeekToNextButtonClick = {},
seekToNextButtonEnabled = true,
percent = 0.25f
)
}
// then
composeTestRule.onNodeWithContentDescription("Play")
.assertIsDisplayed()
composeTestRule.onNodeWithContentDescription("Pause")
.assertDoesNotExist()
}
@Test
fun givenIsNOTPlaying_whenPlayIsClicked_thenCorrectEventIsTriggered() {
// given
val playing = false
var clicked = false
composeTestRule.setContent {
MediaControlButtons(
onPlayButtonClick = { clicked = true },
onPauseButtonClick = {},
playPauseButtonEnabled = true,
playing = playing,
onSeekToPreviousButtonClick = {},
seekToPreviousButtonEnabled = true,
onSeekToNextButtonClick = {},
seekToNextButtonEnabled = true,
percent = 0.25f
)
}
// when
composeTestRule.onNodeWithContentDescription("Play")
.performClick()
// then
// assert that the click event was assigned to the correct button
composeTestRule.waitUntil(timeoutMillis = 1_000) { clicked }
}
@Test
fun whenSeekToPreviousIsClicked_thenCorrectEventIsTriggered() {
// given
var clicked = false
composeTestRule.setContent {
MediaControlButtons(
onPlayButtonClick = {},
onPauseButtonClick = {},
playPauseButtonEnabled = true,
playing = false,
onSeekToPreviousButtonClick = { clicked = true },
seekToPreviousButtonEnabled = true,
onSeekToNextButtonClick = {},
seekToNextButtonEnabled = true,
percent = 0.25f
)
}
// when
composeTestRule.onNodeWithContentDescription("Previous")
.performClick()
// then
// assert that the click event was assigned to the correct button
composeTestRule.waitUntil(timeoutMillis = 1_000) { clicked }
}
@Test
fun whenSeekToNextIsClicked_thenCorrectEventIsTriggered() {
// given
var clicked = false
composeTestRule.setContent {
MediaControlButtons(
onPlayButtonClick = {},
onPauseButtonClick = {},
playPauseButtonEnabled = true,
playing = false,
onSeekToPreviousButtonClick = {},
seekToPreviousButtonEnabled = true,
onSeekToNextButtonClick = { clicked = true },
seekToNextButtonEnabled = true,
percent = 0.25f
)
}
// when
composeTestRule.onNodeWithContentDescription("Next")
.performClick()
// then
// assert that the click event was assigned to the correct button
composeTestRule.waitUntil(timeoutMillis = 1_000) { clicked }
}
@Test
fun givenPercentParam_thenProgressBarIsDisplayed() {
// given
composeTestRule.setContent {
MediaControlButtons(
onPlayButtonClick = {},
onPauseButtonClick = {},
playPauseButtonEnabled = true,
playing = false,
onSeekToPreviousButtonClick = {},
seekToPreviousButtonEnabled = true,
onSeekToNextButtonClick = {},
seekToNextButtonEnabled = true,
percent = 0.25f
)
}
// then
composeTestRule.onNode(hasProgressBar())
.assertIsDisplayed()
}
@Test
fun givenIsPlayingAndPlayPauseEnabledIsTrue_thenPauseButtonIsEnabled() {
// given
val playing = true
val playPauseButtonEnabled = true
composeTestRule.setContent {
MediaControlButtons(
onPlayButtonClick = {},
onPauseButtonClick = {},
playPauseButtonEnabled = playPauseButtonEnabled,
playing = playing,
onSeekToPreviousButtonClick = {},
seekToPreviousButtonEnabled = false,
onSeekToNextButtonClick = {},
seekToNextButtonEnabled = false,
percent = 0.25f
)
}
// then
composeTestRule.onNodeWithContentDescription("Pause")
.assertIsEnabled()
composeTestRule.onNodeWithContentDescription("Previous")
.assertIsNotEnabled()
composeTestRule.onNodeWithContentDescription("Next")
.assertIsNotEnabled()
}
@Test
fun givenIsNOTPlayingAndPlayPauseEnabledIsTrue_thenPlayButtonIsEnabled() {
// given
val playing = false
val playPauseButtonEnabled = true
composeTestRule.setContent {
MediaControlButtons(
onPlayButtonClick = {},
onPauseButtonClick = {},
playPauseButtonEnabled = playPauseButtonEnabled,
playing = playing,
onSeekToPreviousButtonClick = {},
seekToPreviousButtonEnabled = false,
onSeekToNextButtonClick = {},
seekToNextButtonEnabled = false,
percent = 0.25f
)
}
// then
composeTestRule.onNodeWithContentDescription("Play")
.assertIsEnabled()
composeTestRule.onNodeWithContentDescription("Previous")
.assertIsNotEnabled()
composeTestRule.onNodeWithContentDescription("Next")
.assertIsNotEnabled()
}
@Test
fun givenSeekToPreviousButtonEnabledIsTrue_thenSeekToPreviousButtonIsEnabled() {
// given
val seekToPreviousButtonEnabled = true
composeTestRule.setContent {
MediaControlButtons(
onPlayButtonClick = {},
onPauseButtonClick = {},
playPauseButtonEnabled = false,
playing = false,
onSeekToPreviousButtonClick = {},
seekToPreviousButtonEnabled = seekToPreviousButtonEnabled,
onSeekToNextButtonClick = {},
seekToNextButtonEnabled = false,
percent = 0.25f
)
}
// then
composeTestRule.onNodeWithContentDescription("Previous")
.assertIsEnabled()
composeTestRule.onNodeWithContentDescription("Play")
.assertIsNotEnabled()
composeTestRule.onNodeWithContentDescription("Next")
.assertIsNotEnabled()
}
@Test
fun givenSeekToNextButtonEnabledIsTrue_thenSeekToNextButtonIsEnabled() {
// given
val seekToNextButtonEnabled = true
composeTestRule.setContent {
MediaControlButtons(
onPlayButtonClick = {},
onPauseButtonClick = {},
playPauseButtonEnabled = false,
playing = false,
onSeekToPreviousButtonClick = {},
seekToPreviousButtonEnabled = false,
onSeekToNextButtonClick = {},
seekToNextButtonEnabled = seekToNextButtonEnabled,
percent = 0.25f
)
}
// then
composeTestRule.onNodeWithContentDescription("Next")
.assertIsEnabled()
composeTestRule.onNodeWithContentDescription("Previous")
.assertIsNotEnabled()
composeTestRule.onNodeWithContentDescription("Play")
.assertIsNotEnabled()
}
}
|
apache-2.0
|
5b5d331eaed037a6ca0efaf5ef0140bc
| 31.633721 | 84 | 0.590593 | 6.462867 | false | true | false | false |
JavaEden/OrchidCore
|
plugins/OrchidPosts/src/main/kotlin/com/eden/orchid/posts/PostsGenerator.kt
|
1
|
9645
|
package com.eden.orchid.posts
import com.caseyjbrooks.clog.Clog
import com.eden.common.util.EdenUtils
import com.eden.orchid.api.OrchidContext
import com.eden.orchid.api.generators.FolderCollection
import com.eden.orchid.api.generators.OrchidCollection
import com.eden.orchid.api.generators.OrchidGenerator
import com.eden.orchid.api.options.annotations.Description
import com.eden.orchid.api.options.annotations.ImpliedKey
import com.eden.orchid.api.options.annotations.Option
import com.eden.orchid.api.options.annotations.StringDefault
import com.eden.orchid.api.resources.resource.StringResource
import com.eden.orchid.api.theme.pages.OrchidPage
import com.eden.orchid.api.theme.permalinks.PermalinkStrategy
import com.eden.orchid.posts.model.Author
import com.eden.orchid.posts.model.CategoryModel
import com.eden.orchid.posts.model.PostsModel
import com.eden.orchid.posts.pages.AuthorPage
import com.eden.orchid.posts.pages.PostPage
import com.eden.orchid.posts.utils.LatestPostsCollection
import com.eden.orchid.posts.utils.PostsUtils
import com.eden.orchid.posts.utils.isToday
import com.eden.orchid.utilities.OrchidUtils
import com.eden.orchid.utilities.dashCase
import com.eden.orchid.utilities.from
import com.eden.orchid.utilities.titleCase
import com.eden.orchid.utilities.to
import com.eden.orchid.utilities.words
import org.json.JSONObject
import java.time.LocalDate
import java.util.regex.Pattern
import java.util.stream.Stream
import javax.inject.Inject
@Description("Share your thoughts and interests with blog posts.", name = "Blog Posts")
class PostsGenerator
@Inject
constructor(
context: OrchidContext,
val permalinkStrategy: PermalinkStrategy,
val postsModel: PostsModel
) : OrchidGenerator(context, GENERATOR_KEY, OrchidGenerator.PRIORITY_EARLY) {
companion object {
const val GENERATOR_KEY = "posts"
val pageTitleRegex = Pattern.compile("(\\d{4})-(\\d{1,2})-(\\d{1,2})-([\\w-]+)")
}
@Option
@StringDefault("<!--more-->")
@Description("The shortcode used to manually set the breakpoint for a page summary, otherwise the summary is the " +
"first 240 characters of the post."
)
lateinit var excerptSeparator: String
@Option
@ImpliedKey("name")
@Description("A list of Author objects denoting the 'regular' or known authors of the blog. Authors can also be " +
"set up from a resource in the `authorsBaseDir`. All known authors will have a page generated for them " +
"and will be linked to the pages they author. Guest authors may be set up directly in the post " +
"configuration, but they will not have their own pages."
)
lateinit var authors: List<Author>
@Option
@ImpliedKey("key")
@Description("An array of Category configurations, which may be just the path of the category or a full " +
"configuration object. Categories are strictly hierarchical, which is denoted by the category path. If a " +
"category does not have an entry for its parent category, an error is thrown and Posts generation " +
"will not continue."
)
lateinit var categories: MutableList<CategoryModel>
@Option
@StringDefault("posts")
@Description("The base directory in local resources to look for blog post entries in.")
lateinit var baseDir: String
@Option
@StringDefault("posts/authors")
@Description("The base directory in local resources to look for author configs/bios in.")
lateinit var authorsBaseDir: String
@Option
@Description("The configuration for the default category, when no other categories are set up.")
lateinit var defaultConfig: CategoryModel
override fun startIndexing(): List<OrchidPage> {
val authorPages = getAuthorPages()
if (EdenUtils.isEmpty(categories)) {
categories.add(defaultConfig)
}
postsModel.initialize(excerptSeparator, categories, authorPages)
val allPages = ArrayList<OrchidPage>()
if (postsModel.validateCategories()) {
allPages.addAll(authorPages)
postsModel.categories.values.forEach { categoryModel ->
categoryModel.first = getPostsPages(categoryModel)
allPages.addAll(categoryModel.first)
}
}
else {
Clog.e("Categories are not hierarchical, cannot continue generating posts.")
}
return allPages
}
override fun startGeneration(posts: Stream<out OrchidPage>) {
posts.forEach { context.renderTemplate(it) }
}
private fun getAuthorPages(): List<AuthorPage> {
val authorPages = ArrayList<AuthorPage>()
// add Author pages from content pages in the authorsBaseDir
val resourcesList = context.getLocalResourceEntries(authorsBaseDir, null, false)
for (entry in resourcesList) {
val newAuthor = Author()
val authorName = entry.reference.originalFileName from { dashCase() } to { titleCase() }
val options = (entry.embeddedData.element as? JSONObject)?.toMap() ?: mutableMapOf<String, Any?>("name" to authorName)
if(!options.containsKey("name")) {
options["name"] = authorName
}
newAuthor.extractOptions(context, options)
val authorPage = AuthorPage(entry, newAuthor, postsModel)
authorPage.author.authorPage = authorPage
permalinkStrategy.applyPermalink(authorPage, authorPage.permalink)
authorPages.add(authorPage)
}
// add Author pages from those specified in config.yml
for (author in this.authors) {
val authorPage = AuthorPage(StringResource(context, "index.md", ""), author, postsModel)
authorPage.author.authorPage = authorPage
permalinkStrategy.applyPermalink(authorPage, authorPage.permalink)
authorPages.add(authorPage)
}
return authorPages
}
private fun getPostsPages(categoryModel: CategoryModel): List<PostPage> {
val baseCategoryPath = OrchidUtils.normalizePath(baseDir + "/" + categoryModel.path)
val resourcesList = context.getLocalResourceEntries(baseCategoryPath, null, true)
val posts = ArrayList<PostPage>()
for (entry in resourcesList) {
val formattedFilename = PostsUtils.getPostFilename(entry, baseCategoryPath)
val matcher = pageTitleRegex.matcher(formattedFilename)
if (matcher.matches()) {
val title = matcher.group(4).from { dashCase() }.to { words { capitalize() } }
val post = PostPage(entry, categoryModel, title)
if (post.publishDate.toLocalDate().isToday()) {
post.publishDate = LocalDate.of(
Integer.parseInt(matcher.group(1)),
Integer.parseInt(matcher.group(2)),
Integer.parseInt(matcher.group(3))
).atStartOfDay()
}
// TODO: when setting the permalink, check all categories in the hierarchy until you find one
val permalink = if (!EdenUtils.isEmpty(post.permalink)) post.permalink else categoryModel.permalink
permalinkStrategy.applyPermalink(post, permalink)
posts.add(post)
}
}
posts.sortWith(PostsModel.postPageComparator)
posts.mapIndexed { i, post ->
if (next(posts, i) != null) {
post.previous = next(posts, i)
}
if (previous(posts, i) != null) {
post.next = previous(posts, i)
}
}
return posts.filter { !it.isDraft }
}
override fun getCollections(): List<OrchidCollection<*>> {
val collectionsList = ArrayList<OrchidCollection<*>>()
postsModel.categories.values.forEach {
if (EdenUtils.isEmpty(it.key)) {
val collection = FolderCollection(
this,
"blog",
it.first as List<OrchidPage>,
PostPage::class.java,
baseDir
)
collection.slugFormat = "{year}-{month}-{day}-{slug}"
collectionsList.add(collection)
}
else {
val collection = FolderCollection(
this,
it.key,
it.first as List<OrchidPage>,
PostPage::class.java,
baseDir + "/" + it.key
)
collection.slugFormat = "{year}-{month}-{day}-{slug}"
collectionsList.add(collection)
}
}
val collection = FolderCollection(
this,
"authors",
postsModel.authorPages,
AuthorPage::class.java,
authorsBaseDir
)
collectionsList.add(collection)
collectionsList.add(LatestPostsCollection(this, postsModel))
return collectionsList
}
private fun previous(posts: List<OrchidPage>, i: Int): OrchidPage? {
if (posts.size > 1) {
if (i != 0) {
return posts[i - 1]
}
}
return null
}
private fun next(posts: List<OrchidPage>, i: Int): OrchidPage? {
if (posts.size > 1) {
if (i < posts.size - 1) {
return posts[i + 1]
}
}
return null
}
}
|
mit
|
3e76f8f8d424703745a1758afffe6352
| 36.972441 | 130 | 0.629445 | 4.670702 | false | false | false | false |
googleapis/gax-kotlin
|
showcase-test/src/test/kotlin/com/google/api/kotlin/EchoTest.kt
|
1
|
6336
|
/*
* Copyright 2019 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.api.kotlin
import com.google.api.kgax.grpc.ServerStreamingCall
import com.google.api.kgax.grpc.StubFactory
import com.google.common.truth.Truth.assertThat
import com.google.rpc.Code
import com.google.rpc.Status
import com.google.showcase.v1alpha3.EchoGrpc
import com.google.showcase.v1alpha3.EchoRequest
import com.google.showcase.v1alpha3.EchoResponse
import com.google.showcase.v1alpha3.ExpandRequest
import io.grpc.ManagedChannel
import io.grpc.ManagedChannelBuilder
import io.grpc.StatusRuntimeException
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
import org.junit.AfterClass
import java.util.Random
import java.util.concurrent.TimeUnit
import kotlin.test.Test
/**
* Integration tests via Showcase:
* https://github.com/googleapis/gapic-showcase
*
* Note: gapic-generator-kotlin contains all these tests, and more.
* Only a subset is maintained here.
*/
@ExperimentalCoroutinesApi
class EchoTest {
// client / connection to server
companion object {
private val host = System.getenv("HOST") ?: "localhost"
private val port = System.getenv("PORT") ?: "7469"
// use insecure client
val channel: ManagedChannel = ManagedChannelBuilder.forAddress(host, port.toInt())
.usePlaintext()
.build()
val futureStub = StubFactory(
EchoGrpc.EchoFutureStub::class, channel = channel
).newStub()
val streamingStub = StubFactory(
EchoGrpc.EchoStub::class, channel = channel
).newStub()
@AfterClass
@JvmStatic
fun destroyClient() {
channel.shutdownNow().awaitTermination(5, TimeUnit.SECONDS)
}
}
@Test
fun `echos a request`() = runBlocking<Unit> {
val result = futureStub.execute {
it.echo(with(EchoRequest.newBuilder()) {
content = "Hi there!"
build()
})
}
assertThat(result.content).isEqualTo("Hi there!")
}
@Test(expected = StatusRuntimeException::class)
fun `throws an error`() = runBlocking<Unit> {
try {
futureStub.execute {
it.echo(
with(EchoRequest.newBuilder()) {
content = "junk"
error = with(Status.newBuilder()) {
code = Code.DATA_LOSS_VALUE
message = "oh no!"
build()
}
build()
})
}
} catch (error: StatusRuntimeException) {
assertThat(error.message).isEqualTo("DATA_LOSS: oh no!")
assertThat(error.status.code.value()).isEqualTo(Code.DATA_LOSS_VALUE)
throw error
}
}
@Test
fun `can expand a stream of responses`() = runBlocking<Unit> {
val expansions = mutableListOf<String>()
val streams: ServerStreamingCall<EchoResponse> = streamingStub.executeServerStreaming { stub, observer ->
stub.expand(with(ExpandRequest.newBuilder()) {
content = "well hello there how are you"
build()
}, observer)
}
for (response in streams.responses) {
expansions.add(response.content)
}
assertThat(expansions).containsExactly("well", "hello", "there", "how", "are", "you").inOrder()
}
@Test
fun `can expand a stream of responses and then error`() = runBlocking<Unit> {
val expansions = mutableListOf<String>()
val streams: ServerStreamingCall<EchoResponse> = streamingStub.executeServerStreaming { stub, observer ->
stub.expand(with(ExpandRequest.newBuilder()) {
content = "one two zee"
error = with(Status.newBuilder()) {
code = Code.ABORTED_VALUE
message = "yikes"
build()
}
build()
}, observer)
}
var error: Throwable? = null
try {
for (response in streams.responses) {
expansions.add(response.content)
}
} catch (t: Throwable) {
error = t
}
assertThat(error).isNotNull()
assertThat(expansions).containsExactly("one", "two", "zee").inOrder()
}
@Test
fun `can collect a stream of requests`() = runBlocking<Unit> {
val streams = streamingStub.executeClientStreaming { it::collect }
listOf("a", "b", "c", "done").map {
streams.requests.send(with(EchoRequest.newBuilder()) {
content = it
build()
})
}
streams.requests.close()
assertThat(streams.response.await().content).isEqualTo("a b c done")
}
@Test
fun `can have a random chat`() = runBlocking<Unit> {
val inputs = Array(5) { _ ->
Random().ints(20)
.boxed()
.map { it.toString() }
.toArray()
.joinToString("->")
}
val streams = streamingStub.executeStreaming { it::chat }
launch {
for (str in inputs) {
streams.requests.send(with(EchoRequest.newBuilder()) {
content = str
build()
})
}
streams.requests.close()
}
val responses = mutableListOf<String>()
for (response in streams.responses) {
responses.add(response.content)
}
assertThat(responses).containsExactly(*inputs).inOrder()
}
}
|
apache-2.0
|
661101d68de9b909bc29aeec8971df97
| 30.839196 | 113 | 0.584122 | 4.676015 | false | true | false | false |
valich/intellij-markdown
|
src/commonMain/kotlin/org/intellij/markdown/parser/MarkerProcessor.kt
|
1
|
7774
|
package org.intellij.markdown.parser
import org.intellij.markdown.lexer.Compat.assert
import org.intellij.markdown.parser.constraints.MarkdownConstraints
import org.intellij.markdown.parser.constraints.getCharsEaten
import org.intellij.markdown.parser.markerblocks.MarkerBlock
import org.intellij.markdown.parser.markerblocks.MarkerBlockProvider
import org.intellij.markdown.parser.markerblocks.impl.ParagraphMarkerBlock
abstract class MarkerProcessor<T : MarkerProcessor.StateInfo>(private val productionHolder: ProductionHolder,
protected val startConstraints: MarkdownConstraints) {
protected val NO_BLOCKS: List<MarkerBlock> = emptyList()
protected val markersStack: MutableList<MarkerBlock> = ArrayList()
protected var topBlockConstraints: MarkdownConstraints = startConstraints
protected abstract val stateInfo: T
protected abstract fun getMarkerBlockProviders(): List<MarkerBlockProvider<T>>
protected abstract fun updateStateInfo(pos: LookaheadText.Position)
protected abstract fun populateConstraintsTokens(pos: LookaheadText.Position,
constraints: MarkdownConstraints,
productionHolder: ProductionHolder)
private var nextInterestingPosForExistingMarkers: Int = -1
private val interruptsParagraph: (LookaheadText.Position, MarkdownConstraints) -> Boolean = { position, constraints ->
var result = false
for (provider in getMarkerBlockProviders()) {
if (provider.interruptsParagraph(position, constraints)) {
result = true
break
}
}
result
}
open fun createNewMarkerBlocks(pos: LookaheadText.Position,
productionHolder: ProductionHolder): List<MarkerBlock> {
assert(MarkerBlockProvider.isStartOfLineWithConstraints(pos, stateInfo.currentConstraints))
for (provider in getMarkerBlockProviders()) {
val list = provider.createMarkerBlocks(pos, productionHolder, stateInfo)
if (list.isNotEmpty()) {
return list
}
}
if (//!Character.isWhitespace(pos.char) &&
//stateInfo.paragraphBlock == null &&
pos.offsetInCurrentLine >= stateInfo.nextConstraints.getCharsEaten(pos.currentLine)
&& pos.charsToNonWhitespace() != null) {
return listOf(ParagraphMarkerBlock(stateInfo.currentConstraints, productionHolder.mark(), interruptsParagraph))
}
return emptyList()
}
fun processPosition(pos: LookaheadText.Position): LookaheadText.Position? {
updateStateInfo(pos)
var shouldRecalcNextPos = false
if (pos.offset >= nextInterestingPosForExistingMarkers) {
processMarkers(pos)
shouldRecalcNextPos = true
}
if (MarkerBlockProvider.isStartOfLineWithConstraints(pos, stateInfo.currentConstraints)
&& markersStack.lastOrNull()?.allowsSubBlocks() != false) {
val newMarkerBlocks = createNewMarkerBlocks(pos, productionHolder)
for (newMarkerBlock in newMarkerBlocks) {
addNewMarkerBlock(newMarkerBlock)
shouldRecalcNextPos = true
}
}
if (shouldRecalcNextPos) {
nextInterestingPosForExistingMarkers = calculateNextPosForExistingMarkers(pos)
}
if (pos.offsetInCurrentLine == -1
|| MarkerBlockProvider.isStartOfLineWithConstraints(pos, stateInfo.currentConstraints)) {
val delta = stateInfo.nextConstraints.getCharsEaten(pos.currentLine) - pos.offsetInCurrentLine
if (delta > 0) {
if (pos.offsetInCurrentLine != -1 && stateInfo.nextConstraints.indent <= topBlockConstraints.indent) {
populateConstraintsTokens(pos, stateInfo.nextConstraints, productionHolder)
}
return pos.nextPosition(delta)
}
}
return pos.nextPosition(nextInterestingPosForExistingMarkers - pos.offset)
}
private fun calculateNextPosForExistingMarkers(pos: LookaheadText.Position): Int {
val result = markersStack.lastOrNull()?.getNextInterestingOffset(pos) ?: pos.nextLineOrEofOffset
return if (result == -1)
Int.MAX_VALUE
else
result
}
fun addNewMarkerBlock(newMarkerBlock: MarkerBlock) {
markersStack.add(newMarkerBlock)
relaxTopConstraints()
}
fun flushMarkers() {
closeChildren(-1, MarkerBlock.ClosingAction.DEFAULT)
}
/**
* @return true if some markerBlock has canceled the event, false otherwise
*/
private fun processMarkers(pos: LookaheadText.Position): Boolean {
var index = markersStack.size
while (index > 0) {
index--
if (index >= markersStack.size) {
continue
}
val markerBlock = markersStack.get(index)
val processingResult = markerBlock.processToken(pos, stateInfo.currentConstraints)
if (processingResult == MarkerBlock.ProcessingResult.PASS) {
continue
}
applyProcessingResult(index, markerBlock, processingResult)
if (processingResult.eventAction == MarkerBlock.EventAction.CANCEL) {
return true
}
}
return false
}
private fun applyProcessingResult(index: Int, markerBlock: MarkerBlock, processingResult: MarkerBlock.ProcessingResult) {
closeChildren(index, processingResult.childrenAction)
// process self
if (markerBlock.acceptAction(processingResult.selfAction)) {
markersStack.removeAt(index)
relaxTopConstraints()
}
}
private fun closeChildren(index: Int, childrenAction: MarkerBlock.ClosingAction) {
if (childrenAction != MarkerBlock.ClosingAction.NOTHING) {
var latterIndex = markersStack.size - 1
while (latterIndex > index) {
val result = markersStack.get(latterIndex).acceptAction(childrenAction)
assert(result) { "If closing action is not NOTHING, marker should be gone" }
markersStack.removeAt(latterIndex)
--latterIndex
}
relaxTopConstraints()
}
}
private fun relaxTopConstraints() {
topBlockConstraints = if (markersStack.isEmpty())
startConstraints
else
markersStack.last().getBlockConstraints()
}
open class StateInfo(val currentConstraints: MarkdownConstraints,
val nextConstraints: MarkdownConstraints,
private val markersStack: List<MarkerBlock>) {
val paragraphBlock: ParagraphMarkerBlock?
get() = markersStack.firstOrNull { block -> block is ParagraphMarkerBlock } as ParagraphMarkerBlock?
val lastBlock: MarkerBlock?
get() = markersStack.lastOrNull()
override fun equals(other: Any?): Boolean {
val otherStateInfo = other as? StateInfo ?: return false
return currentConstraints == otherStateInfo.currentConstraints &&
nextConstraints == otherStateInfo.nextConstraints &&
markersStack == otherStateInfo.markersStack
}
override fun hashCode(): Int {
var result = currentConstraints.hashCode()
result = result * 37 + nextConstraints.hashCode()
result = result * 37 + markersStack.hashCode()
return result
}
}
}
|
apache-2.0
|
f35b3cdf0eec4c7ee8ed159bb608bfe6
| 38.065327 | 125 | 0.642269 | 5.57276 | false | false | false | false |
Yubyf/QuoteLock
|
app/src/main/java/com/crossbowffs/quotelock/backup/RemoteBackup.kt
|
1
|
16301
|
/*
* Copyright 2016 Marco Gomiero
*
* 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.crossbowffs.quotelock.backup
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.net.Uri
import androidx.core.util.Pair
import com.crossbowffs.quotelock.R
import com.crossbowffs.quotelock.utils.Xlog
import com.crossbowffs.quotelock.utils.ioScope
import com.crossbowffs.quotelock.utils.md5String
import com.crossbowffs.quotelock.utils.toFile
import com.google.android.gms.auth.api.signin.GoogleSignIn
import com.google.android.gms.auth.api.signin.GoogleSignInAccount
import com.google.android.gms.auth.api.signin.GoogleSignInOptions
import com.google.android.gms.common.ConnectionResult
import com.google.android.gms.common.GoogleApiAvailability
import com.google.android.gms.common.api.Scope
import com.google.api.client.googleapis.extensions.android.gms.auth.GoogleAccountCredential
import com.google.api.client.http.InputStreamContent
import com.google.api.client.http.javanet.NetHttpTransport
import com.google.api.client.json.gson.GsonFactory
import com.google.api.services.drive.Drive
import com.google.api.services.drive.DriveScopes
import com.google.api.services.drive.model.File
import com.google.api.services.drive.model.FileList
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
import java.io.*
import java.security.DigestInputStream
import java.security.MessageDigest
import java.security.NoSuchAlgorithmException
/**
* @author Yubyf
*/
class RemoteBackup {
private lateinit var drive: Drive
private val scope: Scope by lazy { Scope(DriveScopes.DRIVE_FILE) }
fun checkGooglePlayService(context: Context): Boolean {
return GoogleApiAvailability.getInstance()
.isGooglePlayServicesAvailable(context) == ConnectionResult.SUCCESS
}
private fun checkGoogleAccount(activity: Activity, requestCode: Int): Boolean {
return if (!ensureDriveService(activity)) {
requestSignIn(activity, requestCode)
false
} else true
}
private fun ensureDriveService(context: Context): Boolean {
if (::drive.isInitialized) {
return true
}
getGoogleAccount(context).also {
// Use the authenticated account to sign in to the Drive service.
val credential = GoogleAccountCredential.usingOAuth2(
context, setOf(DriveScopes.DRIVE_FILE))
credential.selectedAccount = it.account
drive = Drive.Builder(
NetHttpTransport(),
GsonFactory(),
credential)
.setApplicationName(context.getString(R.string.quotelock))
.build()
}
return ::drive.isInitialized
}
private fun getGoogleAccount(context: Context): GoogleSignInAccount =
GoogleSignIn.getAccountForScopes(context, scope)
fun isGoogleAccountSignedIn(context: Context): Boolean {
return checkGooglePlayService(context)
&& GoogleSignIn.hasPermissions(getGoogleAccount(context), scope)
}
fun getSignedInGoogleAccountEmail(context: Context): String? {
return getGoogleAccount(context).email
}
fun getSignedInGoogleAccountPhoto(context: Context): Uri? {
return getGoogleAccount(context).photoUrl
}
/**
* Starts a sign-in activity using [.REQUEST_CODE_SIGN_IN],
* [.REQUEST_CODE_SIGN_IN_BACKUP] or [.REQUEST_CODE_SIGN_IN_RESTORE].
*/
fun requestSignIn(activity: Activity, code: Int) {
Xlog.d(TAG, "Requesting sign-in")
val signInOptions = GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestProfile()
.requestEmail()
.requestScopes(scope)
.build()
val client = GoogleSignIn.getClient(activity, signInOptions)
// The result of the sign-in Intent is handled in onActivityResult.
activity.startActivityForResult(client.signInIntent, code)
}
fun switchAccount(activity: Activity, code: Int, callback: ProgressCallback) {
val signInOptions = GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestEmail()
.build()
val client = GoogleSignIn.getClient(activity, signInOptions)
callback.safeInProcessing("Signing out Google account...")
val signedEmail = getSignedInGoogleAccountEmail(activity)
client.signOut().addOnCompleteListener {
callback.safeSuccess(signedEmail)
requestSignIn(activity, code)
}.addOnFailureListener { callback.safeFailure(it.message) }
}
/**
* Handles the `result` of a completed sign-in activity initiated from [ ][.requestSignIn].
*/
fun handleSignInResult(
activity: Activity, result: Intent?, callback: ProgressCallback,
action: Runnable,
) {
GoogleSignIn.getSignedInAccountFromIntent(result)
.addOnSuccessListener {
Xlog.d(TAG, "Signed in as " + it.email)
// Use the authenticated account to sign in to the Drive service.
val credential = GoogleAccountCredential.usingOAuth2(
activity, setOf(DriveScopes.DRIVE_FILE))
credential.selectedAccount = it.account
drive = Drive.Builder(
NetHttpTransport(),
GsonFactory(),
credential)
.setApplicationName(activity.getString(R.string.quotelock))
.build()
action.run()
}
.addOnFailureListener {
Xlog.e(TAG, "Unable to sign in.", it)
callback.safeFailure("Unable to sign in.")
}
}
/**
* Get the md5 checksum and last modification time of given database file.
*/
fun getDatabaseInfo(context: Context, databaseName: String?): Pair<String?, Long?> {
// database path
val databaseFilePath = context.getDatabasePath(databaseName).toString()
val dbFile = File(databaseFilePath)
return if (!dbFile.exists()) {
Pair(null, null)
} else try {
Pair(dbFile.md5String(), dbFile.lastModified())
} catch (e: Exception) {
e.printStackTrace()
Pair(null, null)
}
}
/**
* Creates a text file in the user's My Drive folder and returns its file ID.
*/
private fun Drive.createFileSync(name: String?): String? {
return try {
val metadata = File()
.setParents(listOf("root"))
.setMimeType("application/vnd.sqlite3")
.setName(name)
files().create(metadata).execute()?.id
?: throw IOException("Null result when requesting file creation.")
} catch (e: Exception) {
Xlog.e(TAG, "Couldn't create file.", e)
null
}
}
/**
* Returns a [FileList] containing all the visible files in the user's My Drive.
*
*
* The returned list will only contain files visible to this app, i.e. those which were
* created by this app. To perform operations on files not created by the app, the project must
* request Drive Full Scope in the [Google
* Developer's Console](https://play.google.com/apps/publish) and be submitted to Google for verification.
*/
private fun Drive.queryFilesSync(): FileList? {
return try {
files().list().setSpaces("drive").execute()
} catch (e: IOException) {
Xlog.e(TAG, "Unable to query files.", e)
null
}
}
/**
* Opens the file identified by `fileId` and returns a [Pair] of its name and
* stream.
*/
@Throws(IOException::class)
fun Drive.readFile(fileId: String?): Pair<Result, InputStream> {
// Retrieve the metadata as a File object.
val metadata = files()[fileId].setFields(NEEDED_FILE_FIELDS).execute()
val result = Result().apply {
success = true
md5 = metadata.md5Checksum
timestamp = if (metadata.modifiedTime == null) -1 else metadata.modifiedTime.value
}
// Get the stream of file.
return Pair.create(result, files()[fileId].executeMediaAsInputStream())
}
/**
* Import the file identified by `fileId`.
*/
@Suppress("BlockingMethodInNonBlockingContext")
private suspend fun Drive.importDbFileSync(
context: Context,
fileId: String?,
databaseName: String,
): Result {
return try {
val temporaryDatabaseFile = File(context.cacheDir, databaseName)
val digest = MessageDigest.getInstance("MD5")
val readFileResult = readFile(fileId)
readFileResult.second.use { inputStream ->
inputStream?.run {
DigestInputStream(this, digest).use { it.toFile(temporaryDatabaseFile) }
} ?: throw IOException()
}
importCollectionDatabaseFrom(context, temporaryDatabaseFile)
readFileResult.first
} catch (e: Exception) {
Xlog.e(TAG, "Unable to read file via REST.", e)
Result()
}
}
/**
* Updates the file identified by `fileId` with the given `name`.
*/
private fun Drive.saveFileSync(context: Context, fileId: String?, name: String?): Result {
try {
//database path
val inFileName = context.getDatabasePath(name).toString()
val dbFile = File(inFileName)
val fis = FileInputStream(dbFile)
// Create a File containing any metadata changes.
val metadata = File().setName(name)
// Convert content to an InputStreamContent instance.
val contentStream = InputStreamContent("application/vnd.sqlite3", fis)
// Update the metadata and contents.
val remoteFile = files().update(fileId, metadata, contentStream)
.setFields(NEEDED_FILE_FIELDS).execute()
return Result().apply {
success = true
md5 = remoteFile.md5Checksum
timestamp =
if (remoteFile.modifiedTime == null) -1 else remoteFile.modifiedTime.value
}
} catch (e: Exception) {
Xlog.e(TAG, "Unable to save file via REST.", e)
return Result()
}
}
fun performDriveBackupAsync(
activity: Activity,
databaseName: String,
callback: ProgressCallback,
) {
if (!checkGoogleAccount(activity, REQUEST_CODE_SIGN_IN_BACKUP)) {
return
}
drive.run {
ioScope.launch scope@{
callback.safeInProcessing("Querying backup file on Google Drive...")
val queryFiles = queryFilesSync()
queryFiles ?: run {
callback.safeFailure("Unable to query files on Google Drive.")
return@scope
}
val databaseFile = queryFiles.files.find { it.name == databaseName }
databaseFile?.run {
callback.safeInProcessing("Importing the existing backup file via Google Drive...")
val saveResult = saveFileSync(activity, id, databaseName)
if (saveResult.success) {
callback.safeSuccess()
} else {
callback.safeFailure("Unable to save file on Google Drive.")
}
return@scope
}
callback.safeInProcessing("There is no existing backup file on Google Drive. Creating now...")
val createFileResult = createFileSync(databaseName)
if (createFileResult == null) {
callback.safeSuccess()
} else {
callback.safeFailure("Couldn't create file on Google Drive.")
}
}
}
}
fun performSafeDriveBackupSync(context: Context, databaseName: String): Result {
val result = Result()
return if (!ensureDriveService(context)) {
result
} else try {
val fileList = drive.queryFilesSync() ?: return result
var fileId: String? = null
for (file in fileList.files) {
if (file.name == databaseName) {
fileId = file.id
break
}
}
if (fileId == null) {
fileId = drive.createFileSync(databaseName)
}
return drive.saveFileSync(context, fileId, databaseName)
} catch (e: Exception) {
Xlog.e(TAG, "Unable to backup files.", e)
result
}
}
fun performDriveRestoreAsync(
activity: Activity,
databaseName: String,
callback: ProgressCallback,
) {
if (!checkGoogleAccount(activity, REQUEST_CODE_SIGN_IN_RESTORE)) {
return
}
drive.run {
ioScope.launch scope@{
callback.safeInProcessing("Querying backup file on Google Drive...")
val queryFiles = queryFilesSync()
queryFiles ?: run {
callback.safeFailure("Unable to query files on Google Drive.")
return@scope
}
val databaseFile = queryFiles.files.find { it.name == databaseName }
databaseFile?.run {
callback.safeInProcessing("Importing the existing backup file via Google Drive...")
if (importDbFileSync(activity, id, databaseName).success) {
callback.safeSuccess()
} else {
callback.safeFailure("Unable to read file via Google Drive.")
}
return@scope
}
Xlog.e(TAG, "There is no $databaseName on drive")
callback.safeFailure("There is no existing backup file on Google Drive.")
}
}
}
fun performSafeDriveRestoreSync(context: Context, databaseName: String): Result {
val result = Result()
if (!ensureDriveService(context)) {
return result
}
try {
val fileList = drive.queryFilesSync() ?: return result
for (file in fileList.files) {
if (file.name == databaseName) {
return runBlocking { drive.importDbFileSync(context, file.id, databaseName) }
}
}
} catch (e: IOException) {
Xlog.e(TAG, "Unable to restore files.", e)
} catch (e: NoSuchAlgorithmException) {
Xlog.e(TAG, "Unable to restore files.", e)
}
return result
}
/**
* @author Yubyf
* @date 2021/8/15.
*/
class Result(var success: Boolean = false, var md5: String? = null, var timestamp: Long = -1L) {
override fun toString(): String {
return "Result{" +
"success=" + success +
", md5='" + md5 + '\'' +
", timestamp=" + timestamp +
'}'
}
}
companion object {
private const val TAG = "RemoteBackup"
private const val NEEDED_FILE_FIELDS = "md5Checksum,name,modifiedTime"
const val REQUEST_CODE_SIGN_IN = 1
const val REQUEST_CODE_SIGN_IN_BACKUP = 2
const val REQUEST_CODE_SIGN_IN_RESTORE = 3
val INSTANCE = RemoteBackup()
}
}
|
mit
|
66c22b83ac65b9a6ea0c2cb028752d0d
| 37.267606 | 110 | 0.598982 | 4.845719 | false | false | false | false |
alashow/music-android
|
modules/core-playback/src/main/java/tm/alashow/datmusic/playback/models/PlaybackProgressState.kt
|
1
|
638
|
/*
* Copyright (C) 2021, Alashov Berkeli
* All rights reserved.
*/
package tm.alashow.datmusic.playback.models
import tm.alashow.base.util.millisToDuration
data class PlaybackProgressState(
val total: Long = 0L,
val position: Long = 0L,
val elapsed: Long = 0L,
val buffered: Long = 0L,
) {
val progress get() = ((position.toFloat() + elapsed) / (total + 1).toFloat()).coerceIn(0f, 1f)
val bufferedProgress get() = ((buffered.toFloat()) / (total + 1).toFloat()).coerceIn(0f, 1f)
val currentDuration get() = (position + elapsed).millisToDuration()
val totalDuration get() = total.millisToDuration()
}
|
apache-2.0
|
2769de6ff04f48829d05404bf031bdad
| 29.380952 | 98 | 0.675549 | 3.645714 | false | false | false | false |
vilnius/tvarkau-vilniu
|
app/src/main/java/lt/vilnius/tvarkau/viewmodel/NewReportViewModel.kt
|
1
|
3071
|
package lt.vilnius.tvarkau.viewmodel
import android.arch.lifecycle.LiveData
import android.arch.lifecycle.MutableLiveData
import io.reactivex.Scheduler
import io.reactivex.rxkotlin.subscribeBy
import lt.vilnius.tvarkau.analytics.Analytics
import lt.vilnius.tvarkau.dagger.UiScheduler
import lt.vilnius.tvarkau.entity.Profile
import lt.vilnius.tvarkau.entity.ReportEntity
import lt.vilnius.tvarkau.entity.ReportType
import lt.vilnius.tvarkau.mvp.interactors.PersonalDataInteractor
import lt.vilnius.tvarkau.mvp.presenters.NewReportData
import lt.vilnius.tvarkau.repository.ReportsRepository
import lt.vilnius.tvarkau.utils.FieldAwareValidator
import java.io.File
import javax.inject.Inject
class NewReportViewModel @Inject constructor(
@UiScheduler
private val uiScheduler: Scheduler,
private val personalDataInteractor: PersonalDataInteractor,
private val analytics: Analytics,
private val repository: ReportsRepository
) : BaseViewModel() {
private val _personalData = MutableLiveData<Profile>()
val personalData: LiveData<Profile>
get() = _personalData
private val _validationError = SingleLiveEvent<FieldAwareValidator.ValidationException>()
val validationError: LiveData<FieldAwareValidator.ValidationException>
get() = _validationError
private val _submittedReport = MutableLiveData<ReportEntity>()
val submittedReport: LiveData<ReportEntity>
get() = _submittedReport
fun initWith(reportType: ReportType) {
if (reportType.isParkingViolation) {
val profile = if (!personalDataInteractor.isUserAnonymous()) {
personalDataInteractor.getPersonalData()
} else {
null
}
_personalData.value = profile
}
}
/**
* Missing support from backend for:
* - personal code field
* - email
* - phone
* - full name
*
* All fields should be available from user's personal data after sign-in via Vilniaus Vartai
*/
fun submit(validator: FieldAwareValidator<NewReportData>) {
validator.toSingle()
.flatMap { repository.submitReport(it) }
.observeOn(uiScheduler)
.bindProgress()
.subscribeBy(
onSuccess = this::handleSuccess,
onError = this::handleError
)
}
private fun handleSuccess(report: ReportEntity) {
analytics.trackReportRegistration(
reportType = report.reportType.title,
photoCount = 0 //TODO set photo count
)
_submittedReport.value = report
}
private fun handleError(error: Throwable) {
when (error) {
is FieldAwareValidator.ValidationException -> {
_validationError.value = error
analytics.trackReportValidation(error.message ?: "no message")
}
else -> _errorEvents.value = error
}
}
fun onImagesPicked(imageFiles: List<File>) {
//TODO implement image upload with new API
}
}
|
mit
|
ebbf7fff0a1d762679f6587335e55a2f
| 32.021505 | 97 | 0.680234 | 4.843849 | false | false | false | false |
matkoniecz/StreetComplete
|
app/src/main/java/de/westnordost/streetcomplete/quests/clothing_bin_operator/AddClothingBinOperator.kt
|
1
|
2286
|
package de.westnordost.streetcomplete.quests.clothing_bin_operator
import de.westnordost.streetcomplete.data.osm.mapdata.MapDataWithGeometry
import de.westnordost.streetcomplete.R
import de.westnordost.streetcomplete.data.elementfilter.toElementFilterExpression
import de.westnordost.streetcomplete.data.osm.edits.update_tags.StringMapChangesBuilder
import de.westnordost.streetcomplete.data.osm.mapdata.Element
import de.westnordost.streetcomplete.data.osm.osmquests.OsmElementQuestType
import de.westnordost.streetcomplete.data.user.achievements.QuestTypeAchievement.CITIZEN
class AddClothingBinOperator : OsmElementQuestType<String> {
/* not the complete filter, see below: we want to filter out additionally all elements that
contain any recycling:* = yes that is not shoes or clothes but this can not be expressed
in the elements filter syntax */
private val filter by lazy { """
nodes with amenity = recycling and recycling_type = container
and recycling:clothes = yes
and !operator and !name and !brand
""".toElementFilterExpression() }
override val commitMessage = "Add clothing bin operator"
override val wikiLink = "Tag:amenity=recycling"
override val icon = R.drawable.ic_quest_recycling_clothes
override val isDeleteElementEnabled = true
override val questTypeAchievements = listOf(CITIZEN)
override fun getApplicableElements(mapData: MapDataWithGeometry): Iterable<Element> =
mapData.nodes.filter { filter.matches(it) && it.tags.hasNoOtherRecyclingTags() }
override fun isApplicableTo(element: Element): Boolean =
filter.matches(element) && element.tags.hasNoOtherRecyclingTags()
private fun Map<String, String>.hasNoOtherRecyclingTags(): Boolean {
return entries.find {
it.key.startsWith("recycling:")
it.key != "recycling:shoes" &&
it.key != "recycling:clothes" &&
it.value == "yes"
} == null
}
override fun getTitle(tags: Map<String, String>) = R.string.quest_clothes_container_operator_title
override fun createForm() = AddClothingBinOperatorForm()
override fun applyAnswerTo(answer: String, changes: StringMapChangesBuilder) {
changes.add("operator", answer)
}
}
|
gpl-3.0
|
80fbed20cc2398810e536e0ad8c1f7f9
| 42.132075 | 102 | 0.73972 | 4.599598 | false | false | false | false |
sksamuel/elasticsearch-river-neo4j
|
streamops-datastore/src/test/kotlin/com/octaldata/datastore/IntegrationDatastoreTest.kt
|
1
|
3621
|
package com.octaldata.datastore
import com.octaldata.domain.integrations.Integration
import com.octaldata.domain.integrations.IntegrationConfig
import com.octaldata.domain.integrations.IntegrationId
import com.octaldata.domain.integrations.IntegrationName
import com.octaldata.domain.integrations.IntegrationType
import io.kotest.core.extensions.install
import io.kotest.core.spec.style.FunSpec
import io.kotest.extensions.testcontainers.JdbcTestContainerExtension
import io.kotest.matchers.nulls.shouldBeNull
import io.kotest.matchers.shouldBe
import org.flywaydb.core.Flyway
import org.testcontainers.containers.MySQLContainer
class IntegrationDatastoreTest : FunSpec({
val mysql = MySQLContainer<Nothing>("mysql:8.0.26").apply {
startupAttempts = 1
withUrlParam("connectionTimeZone", "Z")
withUrlParam("zeroDateTimeBehavior", "convertToNull")
}
val ds = install(JdbcTestContainerExtension(mysql)) {
poolName = "myconnectionpool"
maximumPoolSize = 8
idleTimeout = 10000
}
beforeSpec {
Class.forName(com.mysql.jdbc.Driver::class.java.name)
Flyway
.configure()
.dataSource(ds)
.locations("classpath:changesets")
.load()
.migrate()
}
val datastore = IntegrationDatastore(ds)
test("insert happy path") {
datastore.insert(
Integration(
IntegrationId("foo"),
IntegrationName("int1"),
IntegrationType.Datadog,
IntegrationConfig.Datadog("zxy", 1000, 50)
)
).getOrThrow()
datastore.insert(
Integration(
IntegrationId("bar"),
IntegrationName("int2"),
IntegrationType.Datadog,
IntegrationConfig.Datadog("abc123", 555, 33)
)
).getOrThrow()
datastore.findAll().getOrThrow().toSet().shouldBe(
setOf(
Integration(
IntegrationId("bar"),
IntegrationName("int2"),
IntegrationType.Datadog,
IntegrationConfig.Datadog("abc123", 555, 33)
),
Integration(
IntegrationId("foo"),
IntegrationName("int1"),
IntegrationType.Datadog,
IntegrationConfig.Datadog("zxy", 1000, 50)
),
)
)
}
test("get by id") {
datastore.getById(IntegrationId("foo")).getOrThrow() shouldBe Integration(
IntegrationId("foo"),
IntegrationName("int1"),
IntegrationType.Datadog,
IntegrationConfig.Datadog("zxy", 1000, 50)
)
}
test("get by id for non existing id") {
datastore.getById(IntegrationId("qwerty")).getOrThrow().shouldBeNull()
}
test("delete") {
datastore.delete(IntegrationId("foo")).getOrThrow()
datastore.findAll().getOrThrow().shouldBe(
listOf(
Integration(
IntegrationId("bar"),
IntegrationName("int2"),
IntegrationType.Datadog,
IntegrationConfig.Datadog("abc123", 555, 33)
),
)
)
}
test("update") {
datastore.update(
IntegrationId("bar"),
IntegrationName("int2"),
IntegrationConfig.Datadog("agwer", 555, 33),
).getOrThrow()
datastore.findAll().getOrThrow().toSet().shouldBe(
setOf(
Integration(
IntegrationId("bar"),
IntegrationName("int2"),
IntegrationType.Datadog,
IntegrationConfig.Datadog("agwer", 555, 33)
),
)
)
}
})
|
apache-2.0
|
ef605d128340663d8083278ffbbaf50f
| 28.92562 | 80 | 0.604529 | 4.739529 | false | true | false | false |
ccomeaux/boardgamegeek4android
|
app/src/main/java/com/boardgamegeek/ui/ForumFragment.kt
|
1
|
4306
|
package com.boardgamegeek.ui
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.core.os.bundleOf
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.recyclerview.widget.DividerItemDecoration
import com.boardgamegeek.R
import com.boardgamegeek.databinding.FragmentForumBinding
import com.boardgamegeek.entities.ForumEntity
import com.boardgamegeek.provider.BggContract
import com.boardgamegeek.ui.adapter.ForumPagedListAdapter
import com.boardgamegeek.ui.viewmodel.ForumViewModel
import kotlinx.coroutines.launch
class ForumFragment : Fragment() {
private var _binding: FragmentForumBinding? = null
private val binding get() = _binding!!
private var forumId = BggContract.INVALID_ID
private var forumTitle = ""
private var objectId = BggContract.INVALID_ID
private var objectName = ""
private var objectType = ForumEntity.ForumType.REGION
private val viewModel by activityViewModels<ForumViewModel>()
private val adapter: ForumPagedListAdapter by lazy {
ForumPagedListAdapter(forumId, forumTitle, objectId, objectName, objectType)
}
@Suppress("RedundantNullableReturnType")
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
_binding = FragmentForumBinding.inflate(inflater, container, false)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
arguments?.let {
forumId = it.getInt(KEY_FORUM_ID, BggContract.INVALID_ID)
forumTitle = it.getString(KEY_FORUM_TITLE).orEmpty()
objectId = it.getInt(KEY_OBJECT_ID, BggContract.INVALID_ID)
objectName = it.getString(KEY_OBJECT_NAME).orEmpty()
objectType = it.getSerializable(KEY_OBJECT_TYPE) as ForumEntity.ForumType
}
binding.recyclerView.setHasFixedSize(true)
binding.recyclerView.addItemDecoration(DividerItemDecoration(requireContext(), 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_forum)
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.threads.observe(viewLifecycleOwner) { threads ->
lifecycleScope.launch { adapter.submitData(threads) }
binding.recyclerView.isVisible = true
}
viewModel.setForumId(forumId)
}
override fun onDestroyView() {
super.onDestroyView()
_binding = null
}
companion object {
private const val KEY_FORUM_ID = "FORUM_ID"
private const val KEY_FORUM_TITLE = "FORUM_TITLE"
private const val KEY_OBJECT_ID = "OBJECT_ID"
private const val KEY_OBJECT_NAME = "OBJECT_NAME"
private const val KEY_OBJECT_TYPE = "OBJECT_TYPE"
fun newInstance(forumId: Int, forumTitle: String?, objectId: Int, objectName: String?, objectType: ForumEntity.ForumType?): ForumFragment {
return ForumFragment().apply {
arguments = bundleOf(
KEY_FORUM_ID to forumId,
KEY_FORUM_TITLE to forumTitle,
KEY_OBJECT_ID to objectId,
KEY_OBJECT_NAME to objectName,
KEY_OBJECT_TYPE to objectType,
)
}
}
}
}
|
gpl-3.0
|
6fc66f348c7c46c60a8be1d426399bab
| 39.242991 | 147 | 0.660706 | 5.071849 | false | false | false | false |
lure0xaos/CoffeeTime
|
util/src/main/kotlin/gargoyle/ct/util/pref/prop/CTPrefProperty.kt
|
1
|
2020
|
package gargoyle.ct.util.pref.prop
import gargoyle.ct.util.convert.Converter
import gargoyle.ct.util.convert.Converters
import gargoyle.ct.util.log.Log
import gargoyle.ct.util.pref.CTPreferencesProvider
import gargoyle.ct.util.prop.impl.CTBaseObservableProperty
import java.util.prefs.BackingStoreException
import java.util.prefs.Preferences
import kotlin.reflect.KClass
open class CTPrefProperty<T : Any>
protected constructor(
type: KClass<T>,
converter: Converter<T>,
provider: CTPreferencesProvider,
name: String,
def: T?
) : CTBaseObservableProperty<T>(type, name) {
private val converter: Converter<T>
private val def: String?
private val preferences: Preferences
protected constructor(type: KClass<T>, provider: CTPreferencesProvider, name: String, def: T) :
this(type, Converters.get<T>(type), provider, name, def)
init {
this.converter = converter
this.def = if (def == null) null else converter.format(def)
preferences = provider.preferences()
}
override val isPresent: Boolean
get() = preferences[name, null] != null
override fun set(value: T) {
val s = preferences[name, null]
val oldValue: T? =(if(s==null) null else converter.parse(s ?: def ?: ""))
if (oldValue != value) {
preferences.put(name, converter.format(value)) //XXX
sync()
firePropertyChange(value, oldValue)
}
}
override fun get(): T = converter.parse(preferences[name, null] ?: def ?: error("")) //XXX
override fun get(def: T): T {
val value: String = preferences[name, null] ?: return def
return try {
converter.parse(value)
} catch (ex: IllegalArgumentException) {
Log.warn(ex, ex.message ?: "")
def
}
}
private fun sync() {
try {
preferences.flush()
} catch (ex: BackingStoreException) {
Log.error(ex, ex.message ?: "")
}
}
}
|
unlicense
|
9d56013553306a41c381722256f52c16
| 29.606061 | 99 | 0.632673 | 4.130879 | false | false | false | false |
songzhw/Hello-kotlin
|
AdvancedJ/src/main/kotlin/design_pattern/Decorator_Pattern.kt
|
1
|
796
|
package design_pattern
// java版就是一个接口Beverage, 其有子类Milk, Mocha,... . 它们之间可以互相套
// Kotlin版就更方便了,
interface CoffeePart {
fun cost(): Double
}
class DarkRoast : CoffeePart {
override fun cost(): Double {
return 0.99
}
}
class Mocha(val before: CoffeePart) : CoffeePart {
override fun cost(): Double {
return 0.5 + before.cost()
}
}
class Whip(val before: CoffeePart) : CoffeePart {
override fun cost(): Double {
return 0.3 + before.cost()
}
}
fun main(args: Array<String>) {
// 两份Mocha, 一份whip的DarkRoast
var drink: CoffeePart = DarkRoast()
drink = Mocha(drink)
drink = Mocha(drink)
drink = Whip(drink)
println("szw price = ${drink.cost()}") //=> 2.29
}
|
apache-2.0
|
d46d73188ac6e4b6df22f77daed9ab5c
| 19.388889 | 55 | 0.622616 | 3.097046 | false | false | false | false |
Ruben-Sten/TeXiFy-IDEA
|
src/nl/hannahsten/texifyidea/editor/ControlTracker.kt
|
1
|
1734
|
package nl.hannahsten.texifyidea.editor
import com.intellij.codeInsight.editorActions.TypedHandlerDelegate
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.fileTypes.FileType
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiFile
import java.awt.event.KeyEvent
import java.awt.event.KeyListener
import javax.swing.JComponent
/**
* Tracks the control key.
*
* @see ShiftTracker
*/
object ControlTracker : KeyListener, TypedHandlerDelegate() {
/**
* `true` if the control key is pressed, `false` if the control key is not pressed.
*/
var isControlPressed = false
private set
/**
* Set of all components that have been tracked.
*/
private var registered: MutableSet<JComponent> = HashSet()
/**
* Set up the control tracker.
*/
@JvmStatic
fun setup(component: JComponent) {
if (registered.contains(component)) {
return
}
component.addKeyListener(this)
registered.add(component)
}
override fun beforeCharTyped(c: Char, project: Project, editor: Editor, file: PsiFile, fileType: FileType): Result {
setup(editor.contentComponent)
return super.beforeCharTyped(c, project, editor, file, fileType)
}
override fun keyTyped(e: KeyEvent?) {
// Do nothing.
}
override fun keyPressed(e: KeyEvent?) {
if (e?.keyCode == KeyEvent.VK_CONTROL) {
isControlPressed = true
}
}
override fun keyReleased(e: KeyEvent?) {
if (e?.keyCode == KeyEvent.VK_CONTROL) {
isControlPressed = false
}
}
fun unload() {
registered.forEach { it.removeKeyListener(this) }
}
}
|
mit
|
c23797e6b9532c0329e49bc53bc22f60
| 24.880597 | 120 | 0.654556 | 4.401015 | false | false | false | false |
if710/if710.github.io
|
2019-10-02/SystemServices/app/src/main/java/br/ufpe/cin/android/systemservices/phonesms/SmsReceiver.kt
|
1
|
1178
|
package br.ufpe.cin.android.systemservices.phonesms
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.telephony.SmsMessage
import android.util.Log
class SmsReceiver : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
val rawMsgs = intent.extras!!.get("pdus") as Array<Any>
for (raw in rawMsgs) {
//int activePhone = TelephonyManager.getDefault().getCurrentPhoneType();
//String format = (PHONE_TYPE_CDMA == activePhone) ? SmsConstants.FORMAT_3GPP2 : SmsConstants.FORMAT_3GPP;
val msg = SmsMessage.createFromPdu(raw as ByteArray)
Log.w("SMS:" + msg.originatingAddress, msg.messageBody)
if (msg.messageBody.toUpperCase().contains("IF710")) {
val i = Intent(context, SmsReceivedActivity::class.java)
i.putExtra("msgFrom", msg.originatingAddress)
i.putExtra("msgBody", msg.messageBody)
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
context.startActivity(i)
abortBroadcast()
}
}
}
}
|
mit
|
2dbba23758ce3b783ac447b9f3c4e1bf
| 37 | 118 | 0.650255 | 4.283636 | false | false | false | false |
googlesamples/mlkit
|
android/vision-quickstart/app/src/main/java/com/google/mlkit/vision/demo/kotlin/StillImageActivity.kt
|
1
|
21060
|
/*
* Copyright 2020 Google LLC. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.mlkit.vision.demo.kotlin
import android.app.Activity
import android.content.ContentValues
import android.content.Intent
import android.content.res.Configuration
import android.graphics.Bitmap
import android.net.Uri
import android.os.Bundle
import android.provider.MediaStore
import androidx.appcompat.app.AppCompatActivity
import android.util.Log
import android.util.Pair
import android.view.MenuItem
import android.view.View
import android.view.ViewTreeObserver
import android.widget.AdapterView
import android.widget.AdapterView.OnItemSelectedListener
import android.widget.ArrayAdapter
import android.widget.ImageView
import android.widget.PopupMenu
import android.widget.Spinner
import android.widget.Toast
import com.google.android.gms.common.annotation.KeepName
import com.google.mlkit.common.model.LocalModel
import com.google.mlkit.vision.demo.BitmapUtils
import com.google.mlkit.vision.demo.GraphicOverlay
import com.google.mlkit.vision.demo.R
import com.google.mlkit.vision.demo.VisionImageProcessor
import com.google.mlkit.vision.demo.kotlin.barcodescanner.BarcodeScannerProcessor
import com.google.mlkit.vision.demo.kotlin.facedetector.FaceDetectorProcessor
import com.google.mlkit.vision.demo.kotlin.labeldetector.LabelDetectorProcessor
import com.google.mlkit.vision.demo.kotlin.objectdetector.ObjectDetectorProcessor
import com.google.mlkit.vision.demo.kotlin.posedetector.PoseDetectorProcessor
import com.google.mlkit.vision.demo.kotlin.segmenter.SegmenterProcessor
import com.google.mlkit.vision.demo.kotlin.facemeshdetector.FaceMeshDetectorProcessor;
import com.google.mlkit.vision.demo.kotlin.textdetector.TextRecognitionProcessor
import com.google.mlkit.vision.demo.preference.PreferenceUtils
import com.google.mlkit.vision.demo.preference.SettingsActivity
import com.google.mlkit.vision.demo.preference.SettingsActivity.LaunchSource
import com.google.mlkit.vision.label.custom.CustomImageLabelerOptions
import com.google.mlkit.vision.label.defaults.ImageLabelerOptions
import com.google.mlkit.vision.text.chinese.ChineseTextRecognizerOptions
import com.google.mlkit.vision.text.devanagari.DevanagariTextRecognizerOptions
import com.google.mlkit.vision.text.japanese.JapaneseTextRecognizerOptions
import com.google.mlkit.vision.text.korean.KoreanTextRecognizerOptions
import com.google.mlkit.vision.text.latin.TextRecognizerOptions
import java.io.IOException
import java.util.ArrayList
/** Activity demonstrating different image detector features with a still image from camera. */
@KeepName
class StillImageActivity : AppCompatActivity() {
private var preview: ImageView? = null
private var graphicOverlay: GraphicOverlay? = null
private var selectedMode =
OBJECT_DETECTION
private var selectedSize: String? =
SIZE_SCREEN
private var isLandScape = false
private var imageUri: Uri? = null
// Max width (portrait mode)
private var imageMaxWidth = 0
// Max height (portrait mode)
private var imageMaxHeight = 0
private var imageProcessor: VisionImageProcessor? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_still_image)
findViewById<View>(R.id.select_image_button)
.setOnClickListener { view: View ->
// Menu for selecting either: a) take new photo b) select from existing
val popup =
PopupMenu(this@StillImageActivity, view)
popup.setOnMenuItemClickListener { menuItem: MenuItem ->
val itemId =
menuItem.itemId
if (itemId == R.id.select_images_from_local) {
startChooseImageIntentForResult()
return@setOnMenuItemClickListener true
} else if (itemId == R.id.take_photo_using_camera) {
startCameraIntentForResult()
return@setOnMenuItemClickListener true
}
false
}
val inflater = popup.menuInflater
inflater.inflate(R.menu.camera_button_menu, popup.menu)
popup.show()
}
preview = findViewById(R.id.preview)
graphicOverlay = findViewById(R.id.graphic_overlay)
populateFeatureSelector()
populateSizeSelector()
isLandScape =
resources.configuration.orientation == Configuration.ORIENTATION_LANDSCAPE
if (savedInstanceState != null) {
imageUri =
savedInstanceState.getParcelable(KEY_IMAGE_URI)
imageMaxWidth =
savedInstanceState.getInt(KEY_IMAGE_MAX_WIDTH)
imageMaxHeight =
savedInstanceState.getInt(KEY_IMAGE_MAX_HEIGHT)
selectedSize =
savedInstanceState.getString(KEY_SELECTED_SIZE)
}
val rootView = findViewById<View>(R.id.root)
rootView.viewTreeObserver.addOnGlobalLayoutListener(
object : ViewTreeObserver.OnGlobalLayoutListener {
override fun onGlobalLayout() {
rootView.viewTreeObserver.removeOnGlobalLayoutListener(this)
imageMaxWidth = rootView.width
imageMaxHeight =
rootView.height - findViewById<View>(R.id.control).height
if (SIZE_SCREEN == selectedSize) {
tryReloadAndDetectInImage()
}
}
})
val settingsButton = findViewById<ImageView>(R.id.settings_button)
settingsButton.setOnClickListener {
val intent =
Intent(
applicationContext,
SettingsActivity::class.java
)
intent.putExtra(
SettingsActivity.EXTRA_LAUNCH_SOURCE,
LaunchSource.STILL_IMAGE
)
startActivity(intent)
}
}
public override fun onResume() {
super.onResume()
Log.d(TAG, "onResume")
createImageProcessor()
tryReloadAndDetectInImage()
}
public override fun onPause() {
super.onPause()
imageProcessor?.run {
this.stop()
}
}
public override fun onDestroy() {
super.onDestroy()
imageProcessor?.run {
this.stop()
}
}
private fun populateFeatureSelector() {
val featureSpinner = findViewById<Spinner>(R.id.feature_selector)
val options: MutableList<String> = ArrayList()
options.add(OBJECT_DETECTION)
options.add(OBJECT_DETECTION_CUSTOM)
options.add(CUSTOM_AUTOML_OBJECT_DETECTION)
options.add(FACE_DETECTION)
options.add(BARCODE_SCANNING)
options.add(IMAGE_LABELING)
options.add(IMAGE_LABELING_CUSTOM)
options.add(CUSTOM_AUTOML_LABELING)
options.add(POSE_DETECTION)
options.add(SELFIE_SEGMENTATION)
options.add(TEXT_RECOGNITION_LATIN)
options.add(TEXT_RECOGNITION_CHINESE)
options.add(TEXT_RECOGNITION_DEVANAGARI)
options.add(TEXT_RECOGNITION_JAPANESE)
options.add(TEXT_RECOGNITION_KOREAN)
options.add(FACE_MESH_DETECTION);
// Creating adapter for featureSpinner
val dataAdapter =
ArrayAdapter(this, R.layout.spinner_style, options)
// Drop down layout style - list view with radio button
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
// attaching data adapter to spinner
featureSpinner.adapter = dataAdapter
featureSpinner.onItemSelectedListener = object : OnItemSelectedListener {
override fun onItemSelected(
parentView: AdapterView<*>,
selectedItemView: View?,
pos: Int,
id: Long
) {
if (pos >= 0) {
selectedMode = parentView.getItemAtPosition(pos).toString()
createImageProcessor()
tryReloadAndDetectInImage()
}
}
override fun onNothingSelected(arg0: AdapterView<*>?) {}
}
}
private fun populateSizeSelector() {
val sizeSpinner = findViewById<Spinner>(R.id.size_selector)
val options: MutableList<String> = ArrayList()
options.add(SIZE_SCREEN)
options.add(SIZE_1024_768)
options.add(SIZE_640_480)
options.add(SIZE_ORIGINAL)
// Creating adapter for featureSpinner
val dataAdapter =
ArrayAdapter(this, R.layout.spinner_style, options)
// Drop down layout style - list view with radio button
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
// attaching data adapter to spinner
sizeSpinner.adapter = dataAdapter
sizeSpinner.onItemSelectedListener = object : OnItemSelectedListener {
override fun onItemSelected(
parentView: AdapterView<*>,
selectedItemView: View?,
pos: Int,
id: Long
) {
if (pos >= 0) {
selectedSize = parentView.getItemAtPosition(pos).toString()
tryReloadAndDetectInImage()
}
}
override fun onNothingSelected(arg0: AdapterView<*>?) {}
}
}
public override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
outState.putParcelable(
KEY_IMAGE_URI,
imageUri
)
outState.putInt(
KEY_IMAGE_MAX_WIDTH,
imageMaxWidth
)
outState.putInt(
KEY_IMAGE_MAX_HEIGHT,
imageMaxHeight
)
outState.putString(
KEY_SELECTED_SIZE,
selectedSize
)
}
private fun startCameraIntentForResult() { // Clean up last time's image
imageUri = null
preview!!.setImageBitmap(null)
val takePictureIntent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
if (takePictureIntent.resolveActivity(packageManager) != null) {
val values = ContentValues()
values.put(MediaStore.Images.Media.TITLE, "New Picture")
values.put(MediaStore.Images.Media.DESCRIPTION, "From Camera")
imageUri = contentResolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values)
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri)
startActivityForResult(
takePictureIntent,
REQUEST_IMAGE_CAPTURE
)
}
}
private fun startChooseImageIntentForResult() {
val intent = Intent()
intent.type = "image/*"
intent.action = Intent.ACTION_GET_CONTENT
startActivityForResult(
Intent.createChooser(intent, "Select Picture"),
REQUEST_CHOOSE_IMAGE
)
}
override fun onActivityResult(
requestCode: Int,
resultCode: Int,
data: Intent?
) {
if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == Activity.RESULT_OK) {
tryReloadAndDetectInImage()
} else if (requestCode == REQUEST_CHOOSE_IMAGE && resultCode == Activity.RESULT_OK) {
// In this case, imageUri is returned by the chooser, save it.
imageUri = data!!.data
tryReloadAndDetectInImage()
} else {
super.onActivityResult(requestCode, resultCode, data)
}
}
private fun tryReloadAndDetectInImage() {
Log.d(
TAG,
"Try reload and detect image"
)
try {
if (imageUri == null) {
return
}
if (SIZE_SCREEN == selectedSize && imageMaxWidth == 0) {
// UI layout has not finished yet, will reload once it's ready.
return
}
val imageBitmap = BitmapUtils.getBitmapFromContentUri(contentResolver, imageUri) ?: return
// Clear the overlay first
graphicOverlay!!.clear()
val resizedBitmap: Bitmap
resizedBitmap = if (selectedSize == SIZE_ORIGINAL) {
imageBitmap
} else {
// Get the dimensions of the image view
val targetedSize: Pair<Int, Int> = targetedWidthHeight
// Determine how much to scale down the image
val scaleFactor = Math.max(
imageBitmap.width.toFloat() / targetedSize.first.toFloat(),
imageBitmap.height.toFloat() / targetedSize.second.toFloat()
)
Bitmap.createScaledBitmap(
imageBitmap,
(imageBitmap.width / scaleFactor).toInt(),
(imageBitmap.height / scaleFactor).toInt(),
true
)
}
preview!!.setImageBitmap(resizedBitmap)
if (imageProcessor != null) {
graphicOverlay!!.setImageSourceInfo(
resizedBitmap.width, resizedBitmap.height, /* isFlipped= */false
)
imageProcessor!!.processBitmap(resizedBitmap, graphicOverlay)
} else {
Log.e(
TAG,
"Null imageProcessor, please check adb logs for imageProcessor creation error"
)
}
} catch (e: IOException) {
Log.e(
TAG,
"Error retrieving saved image"
)
imageUri = null
}
}
private val targetedWidthHeight: Pair<Int, Int>
get() {
val targetWidth: Int
val targetHeight: Int
when (selectedSize) {
SIZE_SCREEN -> {
targetWidth = imageMaxWidth
targetHeight = imageMaxHeight
}
SIZE_640_480 -> {
targetWidth = if (isLandScape) 640 else 480
targetHeight = if (isLandScape) 480 else 640
}
SIZE_1024_768 -> {
targetWidth = if (isLandScape) 1024 else 768
targetHeight = if (isLandScape) 768 else 1024
}
else -> throw IllegalStateException("Unknown size")
}
return Pair(targetWidth, targetHeight)
}
private fun createImageProcessor() {
try {
when (selectedMode) {
OBJECT_DETECTION -> {
Log.i(
TAG,
"Using Object Detector Processor"
)
val objectDetectorOptions =
PreferenceUtils.getObjectDetectorOptionsForStillImage(this)
imageProcessor =
ObjectDetectorProcessor(
this,
objectDetectorOptions
)
}
OBJECT_DETECTION_CUSTOM -> {
Log.i(
TAG,
"Using Custom Object Detector Processor"
)
val localModel = LocalModel.Builder()
.setAssetFilePath("custom_models/object_labeler.tflite")
.build()
val customObjectDetectorOptions =
PreferenceUtils.getCustomObjectDetectorOptionsForStillImage(this, localModel)
imageProcessor =
ObjectDetectorProcessor(
this,
customObjectDetectorOptions
)
}
CUSTOM_AUTOML_OBJECT_DETECTION -> {
Log.i(
TAG,
"Using Custom AutoML Object Detector Processor"
)
val customAutoMLODTLocalModel = LocalModel.Builder()
.setAssetManifestFilePath("automl/manifest.json")
.build()
val customAutoMLODTOptions = PreferenceUtils
.getCustomObjectDetectorOptionsForStillImage(this, customAutoMLODTLocalModel)
imageProcessor =
ObjectDetectorProcessor(
this,
customAutoMLODTOptions
)
}
FACE_DETECTION -> {
Log.i(TAG, "Using Face Detector Processor")
val faceDetectorOptions =
PreferenceUtils.getFaceDetectorOptions(this)
imageProcessor =
FaceDetectorProcessor(this, faceDetectorOptions)
}
BARCODE_SCANNING ->
imageProcessor =
BarcodeScannerProcessor(this)
TEXT_RECOGNITION_LATIN ->
imageProcessor =
TextRecognitionProcessor(this, TextRecognizerOptions.Builder().build())
TEXT_RECOGNITION_CHINESE ->
imageProcessor =
TextRecognitionProcessor(this, ChineseTextRecognizerOptions.Builder().build())
TEXT_RECOGNITION_DEVANAGARI ->
imageProcessor =
TextRecognitionProcessor(this, DevanagariTextRecognizerOptions.Builder().build())
TEXT_RECOGNITION_JAPANESE ->
imageProcessor =
TextRecognitionProcessor(this, JapaneseTextRecognizerOptions.Builder().build())
TEXT_RECOGNITION_KOREAN ->
imageProcessor =
TextRecognitionProcessor(this, KoreanTextRecognizerOptions.Builder().build())
IMAGE_LABELING ->
imageProcessor =
LabelDetectorProcessor(
this,
ImageLabelerOptions.DEFAULT_OPTIONS
)
IMAGE_LABELING_CUSTOM -> {
Log.i(
TAG,
"Using Custom Image Label Detector Processor"
)
val localClassifier = LocalModel.Builder()
.setAssetFilePath("custom_models/bird_classifier.tflite")
.build()
val customImageLabelerOptions =
CustomImageLabelerOptions.Builder(localClassifier).build()
imageProcessor =
LabelDetectorProcessor(
this,
customImageLabelerOptions
)
}
CUSTOM_AUTOML_LABELING -> {
Log.i(
TAG,
"Using Custom AutoML Image Label Detector Processor"
)
val customAutoMLLabelLocalModel = LocalModel.Builder()
.setAssetManifestFilePath("automl/manifest.json")
.build()
val customAutoMLLabelOptions = CustomImageLabelerOptions
.Builder(customAutoMLLabelLocalModel)
.setConfidenceThreshold(0f)
.build()
imageProcessor =
LabelDetectorProcessor(
this,
customAutoMLLabelOptions
)
}
POSE_DETECTION -> {
val poseDetectorOptions =
PreferenceUtils.getPoseDetectorOptionsForStillImage(this)
Log.i(TAG, "Using Pose Detector with options $poseDetectorOptions")
val shouldShowInFrameLikelihood =
PreferenceUtils.shouldShowPoseDetectionInFrameLikelihoodStillImage(this)
val visualizeZ = PreferenceUtils.shouldPoseDetectionVisualizeZ(this)
val rescaleZ = PreferenceUtils.shouldPoseDetectionRescaleZForVisualization(this)
val runClassification = PreferenceUtils.shouldPoseDetectionRunClassification(this)
imageProcessor =
PoseDetectorProcessor(
this, poseDetectorOptions, shouldShowInFrameLikelihood, visualizeZ, rescaleZ,
runClassification, isStreamMode = false
)
}
SELFIE_SEGMENTATION -> {
imageProcessor = SegmenterProcessor(this, isStreamMode = false)
}
FACE_MESH_DETECTION -> {
imageProcessor = FaceMeshDetectorProcessor(this)
}
else -> Log.e(
TAG,
"Unknown selectedMode: $selectedMode"
)
}
} catch (e: Exception) {
Log.e(
TAG,
"Can not create image processor: $selectedMode",
e
)
Toast.makeText(
applicationContext,
"Can not create image processor: " + e.message,
Toast.LENGTH_LONG
)
.show()
}
}
companion object {
private const val TAG = "StillImageActivity"
private const val OBJECT_DETECTION = "Object Detection"
private const val OBJECT_DETECTION_CUSTOM = "Custom Object Detection"
private const val CUSTOM_AUTOML_OBJECT_DETECTION = "Custom AutoML Object Detection (Flower)"
private const val FACE_DETECTION = "Face Detection"
private const val BARCODE_SCANNING = "Barcode Scanning"
private const val TEXT_RECOGNITION_LATIN = "Text Recognition Latin"
private const val TEXT_RECOGNITION_CHINESE = "Text Recognition Chinese (Beta)"
private const val TEXT_RECOGNITION_DEVANAGARI = "Text Recognition Devanagari (Beta)"
private const val TEXT_RECOGNITION_JAPANESE = "Text Recognition Japanese (Beta)"
private const val TEXT_RECOGNITION_KOREAN = "Text Recognition Korean (Beta)"
private const val IMAGE_LABELING = "Image Labeling"
private const val IMAGE_LABELING_CUSTOM = "Custom Image Labeling (Birds)"
private const val CUSTOM_AUTOML_LABELING = "Custom AutoML Image Labeling (Flower)"
private const val POSE_DETECTION = "Pose Detection"
private const val SELFIE_SEGMENTATION = "Selfie Segmentation"
private const val FACE_MESH_DETECTION = "Face Mesh Detection (Beta)";
private const val SIZE_SCREEN = "w:screen" // Match screen width
private const val SIZE_1024_768 = "w:1024" // ~1024*768 in a normal ratio
private const val SIZE_640_480 = "w:640" // ~640*480 in a normal ratio
private const val SIZE_ORIGINAL = "w:original" // Original image size
private const val KEY_IMAGE_URI = "com.google.mlkit.vision.demo.KEY_IMAGE_URI"
private const val KEY_IMAGE_MAX_WIDTH = "com.google.mlkit.vision.demo.KEY_IMAGE_MAX_WIDTH"
private const val KEY_IMAGE_MAX_HEIGHT = "com.google.mlkit.vision.demo.KEY_IMAGE_MAX_HEIGHT"
private const val KEY_SELECTED_SIZE = "com.google.mlkit.vision.demo.KEY_SELECTED_SIZE"
private const val REQUEST_IMAGE_CAPTURE = 1001
private const val REQUEST_CHOOSE_IMAGE = 1002
}
}
|
apache-2.0
|
a3da3d6cc6cb572d4f7aca91572c8a80
| 35.247849 | 96 | 0.674786 | 4.661355 | false | false | false | false |
QuickBlox/quickblox-android-sdk
|
sample-conference-kotlin/app/src/main/java/com/quickblox/sample/conference/kotlin/presentation/screens/settings/views/CustomSeekBar.kt
|
1
|
3189
|
package com.quickblox.sample.conference.kotlin.presentation.screens.settings.views
import android.content.Context
import android.content.res.TypedArray
import android.util.AttributeSet
import android.util.Log
import android.view.View
import android.widget.FrameLayout
import android.widget.SeekBar
import androidx.constraintlayout.widget.ConstraintLayout
import com.quickblox.sample.conference.kotlin.R
import com.quickblox.sample.conference.kotlin.databinding.ItemCustomSeekbarBinding
/*
* Created by Injoit in 2021-09-30.
* Copyright © 2021 Quickblox. All rights reserved.
*/
class CustomSeekBar : ConstraintLayout {
private lateinit var binding: ItemCustomSeekbarBinding
private var seekBarCAllBack: SeekBarCAllBack? = null
private var textTitle: String?
get() = binding.tvTitle.text?.toString()
set(text) {
binding.tvTitle.text = text
}
constructor(context: Context) : super(context) {
init(context, null)
}
constructor(context: Context, attrs: AttributeSet?) : super(context, attrs) {
init(context, attrs)
}
constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr) {
init(context, attrs)
}
private fun init(context: Context, attrs: AttributeSet?) {
val rootView: View = FrameLayout.inflate(context, R.layout.item_custom_seekbar, this)
binding = ItemCustomSeekbarBinding.bind(rootView)
if (attrs != null) {
val attributes = context.obtainStyledAttributes(attrs, R.styleable.CustomSeekBar, 0, 0)
try {
proceedAttributes(attributes)
} finally {
attributes.recycle()
}
}
}
private fun proceedAttributes(attributes: TypedArray) {
val min = attributes.getInt(R.styleable.CustomSeekBar_min, 0)
val max = attributes.getInt(R.styleable.CustomSeekBar_max, 0)
binding.tvMinValue.text = min.toString()
binding.tvMaxValue.text = max.toString()
val step = attributes.getInt(R.styleable.CustomSeekBar_step, 1)
textTitle = attributes.getString(R.styleable.CustomSeekBar_title)
binding.seekbar.max = max
binding.seekbar.setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener {
override fun onProgressChanged(seekBar: SeekBar?, progress: Int, fromUser: Boolean) {
val newProgress = (progress / step) * step
seekBar?.progress = newProgress
binding.tvValue.text = newProgress.toString()
}
override fun onStartTrackingTouch(seekBar: SeekBar?) {
// empty
}
override fun onStopTrackingTouch(seekBar: SeekBar?) {
seekBarCAllBack?.changedValue(seekBar?.progress)
}
})
}
fun setSeekBarValue(value: Int?) {
value?.let {
binding.seekbar.progress = value
}
}
fun setCallBack(seekBarCAllBack: SeekBarCAllBack) {
this.seekBarCAllBack = seekBarCAllBack
}
interface SeekBarCAllBack {
fun changedValue(value: Int?)
}
}
|
bsd-3-clause
|
c2c7afd813f562c5979db7875d285660
| 33.290323 | 114 | 0.664366 | 4.58046 | false | false | false | false |
bravelocation/yeltzland-android
|
app/src/main/java/com/bravelocation/yeltzlandnew/dataproviders/YouTubeDataProvider.kt
|
1
|
2349
|
package com.bravelocation.yeltzlandnew.dataproviders
import android.util.Log
import com.bravelocation.yeltzlandnew.models.ThreadSafeList
import com.bravelocation.yeltzlandnew.models.YouTubeVideo
import okhttp3.*
import org.xmlpull.v1.XmlPullParserException
import java.io.IOException
interface YouTubeDataProviderInterface {
fun fetchVideos(completion: ((ThreadSafeList<YouTubeVideo>) -> Unit))
}
class YouTubeDataProvider(channelId: String) : YouTubeDataProviderInterface {
private val client = OkHttpClient()
private val parser = YouTubeChannelXmlParser()
private var cId: String = channelId
override fun fetchVideos(completion: (ThreadSafeList<YouTubeVideo>) -> Unit) {
val channelUrl = "https://www.youtube.com/feeds/videos.xml?channel_id=$cId"
Log.d("YouTubeDataProvider", "Fetching YouTube data from $channelUrl")
val request = Request.Builder()
.url(channelUrl)
.build()
client.newCall(request).enqueue(object : Callback {
override fun onFailure(call: Call, e: IOException) {
e.printStackTrace()
}
override fun onResponse(call: Call, response: Response) {
response.use {
if (!response.isSuccessful) {
Log.e("YouTubeDataProvider", "A problem occurred fetching the YouTube feed: $response")
return
}
try {
val result = response.body?.string()
result?.let {
val parsedVideos = parser.parse(it)
Log.d("YouTubeDataProvider", "YouTube videos parsed: ${parsedVideos.count()}")
val videos = ThreadSafeList<YouTubeVideo>()
videos.resetList(parsedVideos)
completion(videos)
}
} catch (e: XmlPullParserException) {
Log.e("YouTubeDataProvider", "A problem occurred parsing the YouTube feed: $e")
} catch (e: XmlPullParserException) {
Log.e("YouTubeDataProvider", "A problem occurred fetching the YouTube feed: $e")
}
}
}
})
}
}
|
mit
|
6f24d89d6364b13d61e5f2ab9e07f166
| 36.903226 | 111 | 0.57599 | 5.31448 | false | false | false | false |
GeoffreyMetais/vlc-android
|
application/television/src/main/java/org/videolan/television/viewmodel/MainTvModel.kt
|
1
|
14135
|
/*
* *************************************************************************
* MainTvModel.kt
* **************************************************************************
* Copyright © 2019 VLC authors and VideoLAN
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
* ***************************************************************************
*/
package org.videolan.television.viewmodel
import android.app.Application
import android.content.Intent
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentActivity
import androidx.lifecycle.*
import kotlinx.coroutines.*
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.channels.actor
import kotlinx.coroutines.flow.launchIn
import kotlinx.coroutines.flow.onEach
import org.videolan.medialibrary.interfaces.Medialibrary
import org.videolan.medialibrary.interfaces.media.MediaWrapper
import org.videolan.medialibrary.media.DummyItem
import org.videolan.medialibrary.media.MediaLibraryItem
import org.videolan.moviepedia.database.models.MediaMetadataWithImages
import org.videolan.moviepedia.repository.MediaMetadataRepository
import org.videolan.resources.*
import org.videolan.resources.util.getFromMl
import org.videolan.television.ui.MainTvActivity
import org.videolan.television.ui.NowPlayingDelegate
import org.videolan.television.ui.audioplayer.AudioPlayerActivity
import org.videolan.television.ui.browser.TVActivity
import org.videolan.television.ui.browser.VerticalGridActivity
import org.videolan.tools.NetworkMonitor
import org.videolan.tools.PLAYBACK_HISTORY
import org.videolan.tools.Settings
import org.videolan.vlc.ExternalMonitor
import org.videolan.vlc.PlaybackService
import org.videolan.vlc.R
import org.videolan.vlc.gui.DialogActivity
import org.videolan.vlc.media.MediaUtils
import org.videolan.vlc.media.PlaylistManager
import org.videolan.vlc.mediadb.models.BrowserFav
import org.videolan.vlc.repository.BrowserFavRepository
import org.videolan.vlc.repository.DirectoryRepository
import org.videolan.vlc.util.convertFavorites
import org.videolan.vlc.util.scanAllowed
private const val NUM_ITEMS_PREVIEW = 5
private const val TAG = "MainTvModel"
@ObsoleteCoroutinesApi
@ExperimentalCoroutinesApi
class MainTvModel(app: Application) : AndroidViewModel(app), Medialibrary.OnMedialibraryReadyListener,
Medialibrary.OnDeviceChangeListener {
val context = getApplication<Application>().baseContext!!
private val medialibrary = Medialibrary.getInstance()
private val networkMonitor = NetworkMonitor.getInstance(context)
val settings = Settings.getInstance(context)
private val showInternalStorage = AndroidDevices.showInternalStorage()
private val browserFavRepository = BrowserFavRepository.getInstance(context)
private val mediaMetadataRepository = MediaMetadataRepository.getInstance(context)
private var updatedFavoritList: List<MediaWrapper> = listOf()
var showHistory = false
private set
// LiveData
private val favorites: LiveData<List<BrowserFav>> = browserFavRepository.browserFavorites.asLiveData(viewModelScope.coroutineContext)
val nowPlaying: LiveData<List<MediaLibraryItem>> = MutableLiveData()
val videos: LiveData<List<MediaLibraryItem>> = MutableLiveData()
val audioCategories: LiveData<List<MediaLibraryItem>> = MutableLiveData()
val browsers: LiveData<List<MediaLibraryItem>> = MutableLiveData()
val history: LiveData<List<MediaWrapper>> = MutableLiveData()
val playlist: LiveData<List<MediaLibraryItem>> = MutableLiveData()
val recentlyPlayed: MediatorLiveData<List<MediaMetadataWithImages>> = MediatorLiveData()
val recentlyAdded: MediatorLiveData<List<MediaMetadataWithImages>> = MediatorLiveData()
private val nowPlayingDelegate = NowPlayingDelegate(this)
private val updateActor = viewModelScope.actor<Unit>(capacity = Channel.CONFLATED) {
for (action in channel) updateBrowsers()
}
private val historyActor = viewModelScope.actor<Unit>(capacity = Channel.CONFLATED) {
for (action in channel) setHistory()
}
private val favObserver = Observer<List<BrowserFav>> { list ->
updatedFavoritList = convertFavorites(list)
if (!updateActor.isClosedForSend) updateActor.offer(Unit)
}
private val playerObserver = Observer<Boolean> { updateAudioCategories() }
private val videoObserver = Observer<Any> { updateVideos() }
init {
medialibrary.addOnMedialibraryReadyListener(this)
medialibrary.addOnDeviceChangeListener(this)
favorites.observeForever(favObserver)
networkMonitor.connectionFlow.onEach { updateActor.offer(Unit) }.launchIn(viewModelScope)
ExternalMonitor.storageEvents.onEach { updateActor.offer(Unit) }.launchIn(viewModelScope)
PlaylistManager.showAudioPlayer.observeForever(playerObserver)
mediaMetadataRepository.getAllLive().observeForever(videoObserver)
}
fun refresh() = viewModelScope.launch {
updateNowPlaying()
updateVideos()
updateRecentlyPlayed()
updateRecentlyAdded()
updateAudioCategories()
historyActor.offer(Unit)
updateActor.offer(Unit)
updatePlaylists()
}
private suspend fun setHistory() {
if (!medialibrary.isStarted) return
val historyEnabled = settings.getBoolean(PLAYBACK_HISTORY, true)
showHistory = historyEnabled
if (!historyEnabled) (history as MutableLiveData).value = emptyList()
else updateHistory()
}
suspend fun updateHistory() {
if (!showHistory) return
(history as MutableLiveData).value = context.getFromMl { lastMediaPlayed().toMutableList() }
}
private fun updateVideos() = viewModelScope.launch {
val allMovies = withContext(Dispatchers.IO) { mediaMetadataRepository.getMovieCount() }
val allTvshows = withContext(Dispatchers.IO) { mediaMetadataRepository.getTvshowsCount() }
val videoNb = context.getFromMl { videoCount }
context.getFromMl {
getPagedVideos(Medialibrary.SORT_INSERTIONDATE, true, NUM_ITEMS_PREVIEW, 0)
}.let {
(videos as MutableLiveData).value = mutableListOf<MediaLibraryItem>().apply {
add(DummyItem(HEADER_VIDEO, context.getString(R.string.videos_all), context.resources.getQuantityString(R.plurals.videos_quantity, videoNb, videoNb)))
if (allMovies > 0) {
add(DummyItem(HEADER_MOVIES, context.getString(R.string.header_movies), context.resources.getQuantityString(R.plurals.movies_quantity, allMovies, allMovies)))
}
if (allTvshows > 0) {
add(DummyItem(HEADER_TV_SHOW, context.getString(R.string.header_tvshows), context.resources.getQuantityString(R.plurals.tvshow_quantity, allTvshows, allTvshows)))
}
addAll(it)
}
}
}
private fun updateRecentlyPlayed() = viewModelScope.launch {
val history = context.getFromMl { lastMediaPlayed().toMutableList() }
recentlyPlayed.addSource(withContext(Dispatchers.IO) { mediaMetadataRepository.getByIds(history.map { it.id }) }) {
recentlyPlayed.value = it.sortedBy { history.indexOf(history.find { media -> media.id == it.metadata.mlId }) }
}
}
private fun updateRecentlyAdded() = viewModelScope.launch {
recentlyAdded.addSource(withContext(Dispatchers.IO) { mediaMetadataRepository.getRecentlyAdded() }) {
recentlyAdded.value = it
}
}
fun updateNowPlaying() = viewModelScope.launch {
val list = mutableListOf<MediaLibraryItem>()
PlaybackService.instance?.run {
currentMediaWrapper?.let {
DummyItem(CATEGORY_NOW_PLAYING, it.title, it.artist).apply { setArtWork(coverArt) }
}
}?.let { list.add(0, it) }
(nowPlaying as MutableLiveData).value = list
}
private fun updatePlaylists() = viewModelScope.launch {
context.getFromMl {
getPagedPlaylists(Medialibrary.SORT_INSERTIONDATE, true, NUM_ITEMS_PREVIEW, 0)
}.let {
(playlist as MutableLiveData).value = mutableListOf<MediaLibraryItem>().apply {
// add(DummyItem(HEADER_PLAYLISTS, context.getString(R.string.playlists), ""))
addAll(it)
}
}
}
private fun updateAudioCategories() {
val list = mutableListOf<MediaLibraryItem>(
DummyItem(CATEGORY_ARTISTS, context.getString(R.string.artists), ""),
DummyItem(CATEGORY_ALBUMS, context.getString(R.string.albums), ""),
DummyItem(CATEGORY_GENRES, context.getString(R.string.genres), ""),
DummyItem(CATEGORY_SONGS, context.getString(R.string.tracks), "")
)
(audioCategories as MutableLiveData).value = list
}
private suspend fun updateBrowsers() {
val list = mutableListOf<MediaLibraryItem>()
val directories = DirectoryRepository.getInstance(context).getMediaDirectoriesList(context).toMutableList()
if (!showInternalStorage && directories.isNotEmpty()) directories.removeAt(0)
directories.forEach { if (it.location.scanAllowed()) list.add(it) }
if (networkMonitor.isLan) {
list.add(DummyItem(HEADER_NETWORK, context.getString(R.string.network_browsing), null))
list.add(DummyItem(HEADER_STREAM, context.getString(R.string.streams), null))
list.add(DummyItem(HEADER_SERVER, context.getString(R.string.server_add_title), null))
updatedFavoritList.forEach {
it.description = it.uri.scheme
list.add(it)
}
}
(browsers as MutableLiveData).value = list
delay(500L)
}
override fun onMedialibraryIdle() {
refresh()
}
override fun onMedialibraryReady() {
refresh()
}
override fun onDeviceChange() {
refresh()
}
override fun onCleared() {
super.onCleared()
medialibrary.removeOnMedialibraryReadyListener(this)
medialibrary.removeOnDeviceChangeListener(this)
favorites.removeObserver(favObserver)
PlaylistManager.showAudioPlayer.removeObserver(playerObserver)
nowPlayingDelegate.onClear()
}
fun open(activity: FragmentActivity, item: Any?) {
when (item) {
is MediaWrapper -> when {
item.type == MediaWrapper.TYPE_DIR -> {
val intent = Intent(activity, VerticalGridActivity::class.java)
intent.putExtra(MainTvActivity.BROWSER_TYPE, if ("file" == item.uri.scheme) HEADER_DIRECTORIES else HEADER_NETWORK)
intent.putExtra(FAVORITE_TITLE, item.title)
intent.data = item.uri
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_NEW_TASK)
activity.startActivity(intent)
}
else -> {
MediaUtils.openMedia(activity, item)
if (item.type == MediaWrapper.TYPE_AUDIO) {
activity.startActivity(Intent(activity, AudioPlayerActivity::class.java))
}
}
}
is DummyItem -> when {
item.id == HEADER_STREAM -> {
val intent = Intent(activity, TVActivity::class.java)
intent.putExtra(MainTvActivity.BROWSER_TYPE, HEADER_STREAM)
activity.startActivity(intent)
}
item.id == HEADER_SERVER -> activity.startActivity(Intent(activity, DialogActivity::class.java).setAction(DialogActivity.KEY_SERVER)
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK))
else -> {
val intent = Intent(activity, VerticalGridActivity::class.java)
intent.putExtra(MainTvActivity.BROWSER_TYPE, item.id)
activity.startActivity(intent)
}
}
is MediaMetadataWithImages -> {
item.metadata.mlId?.let {
viewModelScope.launch {
context.getFromMl {
getMedia(it)
}.let {
val intent = Intent(activity, org.videolan.television.ui.DetailsActivity::class.java)
// pass the item information
intent.putExtra("media", it)
intent.putExtra("item", org.videolan.television.ui.MediaItemDetails(it.title, it.artist, it.album, it.location, it.artworkURL))
activity.startActivity(intent)
}
}
}
}
is MediaLibraryItem -> org.videolan.television.ui.TvUtil.openAudioCategory(activity, item)
}
}
companion object {
fun Fragment.getMainTvModel() = ViewModelProviders.of(requireActivity(), Factory(requireActivity().application)).get(MainTvModel::class.java)
}
class Factory(private val app: Application) : ViewModelProvider.NewInstanceFactory() {
override fun <T : ViewModel> create(modelClass: Class<T>): T {
@Suppress("UNCHECKED_CAST")
return MainTvModel(app) as T
}
}
}
|
gpl-2.0
|
8178112a268f30688268b5c346d0e697
| 44.301282 | 182 | 0.664709 | 4.943687 | false | false | false | false |
arturbosch/detekt
|
detekt-metrics/src/test/kotlin/io/github/detekt/metrics/processors/package.kt
|
1
|
4328
|
package io.github.detekt.metrics.processors
val default = """
package cases
/**
* A comment
*/
@Suppress("Unused")
class Default
""".trimStart()
val emptyEnum = """
package empty
@Suppress("Unused")
enum class EmptyEnum
""".trimStart()
val emptyInterface = """
package empty
@Suppress("Unused")
interface EmptyInterface
""".trimStart()
val classWithFields = """
package fields
@Suppress("unused")
class ClassWithFields {
private var x = 0
val y = 0
}
""".trimStart()
val commentsClass = """
package comments
@Suppress("Unused")
class CommentsClass {
/**
* Doc comment
*
* @param args
*/
fun x(args: String) { // comment total: 10
/*
comment
*/
//Comment
println(args)
println("/* no comment */")
println("// no comment //")
}
}
""".trimStart()
val complexClass = """
package cases
import org.jetbrains.kotlin.utils.sure
@Suppress("unused")
class ComplexClass {// McCabe: 44, LLOC: 20 + 20 + 4x4
class NestedClass { //14
fun complex() { //1 +
try {//4
while (true) {
if (true) {
when ("string") {
"" -> println()
else -> println()
}
}
}
} catch (ex: Exception) { //1 + 3
try {
println()
} catch (ex: Exception) {
while (true) {
if (false) {
println()
} else {
println()
}
}
}
} finally { // 3
try {
println()
} catch (ex: Exception) {
while (true) {
if (false) {
println()
} else {
println()
}
}
}
}
(1..10).forEach {
//1
println()
}
for (i in 1..10) { //1
println()
}
}
}
fun complex() { //1 +
try {//4
while (true) {
if (true) {
when ("string") {
"" -> println()
else -> println()
}
}
}
} catch (ex: Exception) { //1 + 3
try {
println()
} catch (ex: Exception) {
while (true) {
if (false) {
println()
} else {
println()
}
}
}
} finally { // 3
try {
println()
} catch (ex: Exception) {
while (true) {
if (false) {
println()
} else {
println()
}
}
}
}
(1..10).forEach {
//1
println()
}
for (i in 1..10) { //1
println()
}
}
fun manyClosures() {//4
true.let {
true.apply {
true.run {
true.sure {
""
}
}
}
}
}
fun manyClosures2() {//4
true.let {
true.apply {
true.run {
true.sure {
""
}
}
}
}
}
fun manyClosures3() {//4
true.let {
true.apply {
true.run {
true.sure {
""
}
}
}
}
}
fun manyClosures4() {//4
true.let {
true.apply {
true.run {
true.sure {
""
}
}
}
}
}
}
""".trimStart()
|
apache-2.0
|
60c8e2bff9c41b57ffa0dd5969bf702d
| 19.708134 | 54 | 0.304067 | 5.290954 | false | false | false | false |
cout970/Magneticraft
|
src/main/kotlin/com/cout970/magneticraft/features/decoration/TileRenderers.kt
|
2
|
1304
|
package com.cout970.magneticraft.features.decoration
import com.cout970.magneticraft.misc.RegisterRenderer
import com.cout970.magneticraft.misc.tileentity.getTile
import com.cout970.magneticraft.systems.tilerenderers.BaseTileRenderer
import com.cout970.magneticraft.systems.tilerenderers.FilterRegex
import com.cout970.magneticraft.systems.tilerenderers.ModelSelector
import com.cout970.magneticraft.systems.tilerenderers.Utilities
/**
* Created by cout970 on 2017/08/10.
*/
@RegisterRenderer(TileTubeLight::class)
object TileRendererTubeLight : BaseTileRenderer<TileTubeLight>() {
override fun init() {
createModel(Blocks.tubeLight,
ModelSelector("left", FilterRegex("Left\\d")),
ModelSelector("right", FilterRegex("Right\\d"))
)
}
override fun render(te: TileTubeLight) {
Utilities.rotateFromCenter(te.facing, 90f)
val front = te.world.getTile<TileTubeLight>(te.pos.offset(te.facing, 1))
val back = te.world.getTile<TileTubeLight>(te.pos.offset(te.facing, -1))
renderModel("default")
if (front == null || front.facing.axis != te.facing.axis) {
renderModel("left")
}
if (back == null || back.facing.axis != te.facing.axis) {
renderModel("right")
}
}
}
|
gpl-2.0
|
14c1665a4fc2043bd1888ef9d6e46c68
| 34.27027 | 80 | 0.697853 | 4.037152 | false | false | false | false |
arturbosch/detekt
|
detekt-psi-utils/src/main/kotlin/io/gitlab/arturbosch/detekt/rules/Junk.kt
|
1
|
1951
|
package io.gitlab.arturbosch.detekt.rules
import org.jetbrains.kotlin.com.intellij.openapi.util.Key
import org.jetbrains.kotlin.com.intellij.psi.PsiComment
import org.jetbrains.kotlin.com.intellij.psi.PsiElement
import org.jetbrains.kotlin.psi.KtBlockExpression
import org.jetbrains.kotlin.psi.KtCallExpression
import org.jetbrains.kotlin.psi.KtClass
import org.jetbrains.kotlin.psi.KtClassOrObject
import org.jetbrains.kotlin.psi.KtConstantExpression
import org.jetbrains.kotlin.psi.KtQualifiedExpression
import org.jetbrains.kotlin.psi.KtTreeVisitorVoid
import org.jetbrains.kotlin.psi.psiUtil.getCallNameExpression
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.bindingContextUtil.isUsedAsExpression
fun KtCallExpression.isUsedForNesting(): Boolean = when (getCallNameExpression()?.text) {
"run", "let", "apply", "with", "use", "forEach" -> true
else -> false
}
fun KtClassOrObject.hasCommentInside() = this.body?.hasCommentInside() ?: false
fun PsiElement.hasCommentInside(): Boolean {
val commentKey = Key<Boolean>("comment")
this.acceptChildren(object : KtTreeVisitorVoid() {
override fun visitComment(comment: PsiComment) {
putUserData(commentKey, true)
}
})
return getUserData(commentKey) == true
}
fun getIntValueForPsiElement(element: PsiElement): Int? {
return (element as? KtConstantExpression)?.text?.toIntOrNull()
}
fun KtClass.companionObject() = this.companionObjects.singleOrNull { it.isCompanion() }
inline fun <reified T : Any> Any.safeAs(): T? = this as? T
fun KtCallExpression.receiverIsUsed(context: BindingContext): Boolean =
(parent as? KtQualifiedExpression)?.let {
val scopeOfApplyCall = parent.parent
!(
(scopeOfApplyCall == null || scopeOfApplyCall is KtBlockExpression) &&
(context == BindingContext.EMPTY || !it.isUsedAsExpression(context))
)
} ?: true
|
apache-2.0
|
ccd75f6388a06446d09a342706b2774d
| 38.816327 | 89 | 0.750897 | 4.364653 | false | false | false | false |
adrcotfas/Goodtime
|
app/src/main/java/com/apps/adrcotfas/goodtime/backup/BackupFragment.kt
|
1
|
3962
|
/*
* Copyright 2016-2021 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.backup
import com.google.android.material.bottomsheet.BottomSheetDialogFragment
import com.apps.adrcotfas.goodtime.statistics.SessionViewModel
import android.view.LayoutInflater
import android.view.ViewGroup
import android.os.Bundle
import androidx.databinding.DataBindingUtil
import com.apps.adrcotfas.goodtime.R
import android.content.Intent
import android.app.Activity
import com.apps.adrcotfas.goodtime.database.AppDatabase
import android.content.DialogInterface
import android.widget.Toast
import android.view.View
import androidx.appcompat.app.AlertDialog
import androidx.fragment.app.activityViewModels
import androidx.lifecycle.lifecycleScope
import com.apps.adrcotfas.goodtime.database.Session
import com.apps.adrcotfas.goodtime.databinding.DialogBackupBinding
import dagger.hilt.android.AndroidEntryPoint
@AndroidEntryPoint
class BackupFragment : BottomSheetDialogFragment() {
private val sessionViewModel: SessionViewModel by activityViewModels()
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View {
val binding: DialogBackupBinding =
DataBindingUtil.inflate(inflater, R.layout.dialog_backup, container, false)
binding.exportBackup.setOnClickListener { exportBackup() }
binding.importBackup.setOnClickListener { importBackup() }
binding.exportCsv.setOnClickListener { exportCsv() }
return binding.root
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
if (requestCode == IMPORT_BACKUP_REQUEST && data != null) {
val uri = data.data
if (uri != null && resultCode == Activity.RESULT_OK) {
AppDatabase.getDatabase(requireContext())
BackupOperations.doImport(lifecycleScope, requireContext(), uri)
}
}
}
private fun importBackup() {
AlertDialog.Builder(requireContext())
.setTitle(R.string.backup_import_title)
.setMessage(R.string.backup_import_message)
.setPositiveButton(android.R.string.ok) { _: DialogInterface?, _: Int ->
val intent = Intent(Intent.ACTION_GET_CONTENT)
intent.addCategory(Intent.CATEGORY_OPENABLE)
intent.type = "*/*"
startActivityForResult(intent, IMPORT_BACKUP_REQUEST)
}
.setNegativeButton(android.R.string.cancel) { dialog: DialogInterface, _: Int -> dialog.cancel() }
.show()
}
private fun exportBackup() {
BackupOperations.doExport(lifecycleScope, requireContext())
}
private fun exportCsv() {
val sessionsLiveData = sessionViewModel.allSessions
sessionsLiveData.observe(viewLifecycleOwner, { sessions: List<Session> ->
if (sessions.isEmpty()) {
Toast.makeText(
requireActivity(),
R.string.backup_no_completed_sessions,
Toast.LENGTH_SHORT
).show()
dismiss()
} else {
BackupOperations.doExportToCSV(lifecycleScope, requireContext(), sessions)
}
})
}
companion object {
private const val IMPORT_BACKUP_REQUEST = 0
}
}
|
apache-2.0
|
35b53b5e41db552b3eb1e113f32a85b8
| 38.63 | 128 | 0.683241 | 4.964912 | false | false | false | false |
FFlorien/AmpachePlayer
|
app/src/main/java/be/florien/anyflow/feature/player/filter/display/DisplayFilterFragment.kt
|
1
|
10696
|
package be.florien.anyflow.feature.player.filter.display
import android.annotation.SuppressLint
import android.content.Context
import android.graphics.Bitmap
import android.graphics.Rect
import android.graphics.drawable.BitmapDrawable
import android.graphics.drawable.Drawable
import android.os.Bundle
import android.text.Spannable
import android.text.SpannableString
import android.text.style.StyleSpan
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.annotation.DrawableRes
import androidx.core.content.res.ResourcesCompat
import androidx.core.graphics.BlendModeColorFilterCompat
import androidx.core.graphics.BlendModeCompat
import androidx.core.view.ViewCompat
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.DividerItemDecoration
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import be.florien.anyflow.R
import be.florien.anyflow.data.view.Filter
import be.florien.anyflow.databinding.FragmentDisplayFilterBinding
import be.florien.anyflow.databinding.ItemFilterActiveBinding
import be.florien.anyflow.extension.GlideApp
import be.florien.anyflow.extension.viewModelFactory
import be.florien.anyflow.feature.player.filter.BaseFilterFragment
import be.florien.anyflow.feature.player.filter.BaseFilterViewModel
import be.florien.anyflow.feature.player.filter.saved.SavedFilterGroupFragment
import be.florien.anyflow.feature.player.filter.selectType.SelectFilterTypeFragment
import com.bumptech.glide.request.target.CustomTarget
import com.bumptech.glide.request.target.Target
import com.bumptech.glide.request.transition.Transition
class DisplayFilterFragment : BaseFilterFragment() {
override fun getTitle(): String = getString(R.string.menu_filters)
private val targets: MutableList<Target<Bitmap>> = mutableListOf()
override val baseViewModel: BaseFilterViewModel
get() = viewModel
lateinit var viewModel: DisplayFilterViewModel
private lateinit var binding: FragmentDisplayFilterBinding
private lateinit var filterListAdapter: FilterListAdapter
override fun onAttach(context: Context) {
super.onAttach(context)
viewModel = ViewModelProvider(this, requireActivity().viewModelFactory).get(DisplayFilterViewModel::class.java)
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
viewModel.resetFilterChanges()
}
@SuppressLint("NotifyDataSetChanged")
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View {
binding = FragmentDisplayFilterBinding.inflate(inflater, container, false)
binding.vm = viewModel
binding.lifecycleOwner = viewLifecycleOwner
filterListAdapter = FilterListAdapter()
binding.filterList.layoutManager = LinearLayoutManager(requireContext())
binding.filterList.adapter = filterListAdapter
ResourcesCompat.getDrawable(resources, R.drawable.sh_divider, requireActivity().theme)?.let {
binding
.filterList
.addItemDecoration(DividerItemDecoration(requireActivity(), DividerItemDecoration.VERTICAL).apply { setDrawable(it) })
}
baseViewModel.currentFilters.observe(viewLifecycleOwner) {
filterListAdapter.notifyDataSetChanged()
saveMenuHolder.isVisible = baseViewModel.currentFilters.value?.isNotEmpty() == true
}
binding.fabSavedFilterGroups.setOnClickListener {
requireActivity()
.supportFragmentManager
.beginTransaction()
.replace(R.id.container, SavedFilterGroupFragment(), SavedFilterGroupFragment::class.java.simpleName)
.addToBackStack(null)
.commit()
}
saveMenuHolder.isVisible = viewModel.currentFilters.value?.isNotEmpty() == true
ViewCompat.setTranslationZ(binding.root, 1f)
return binding.root
}
override fun onDetach() {
targets.forEach {
it.request?.clear()
}
viewModel.cancelChanges()
super.onDetach()
}
inner class FilterListAdapter : RecyclerView.Adapter<FilterViewHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): FilterViewHolder {
return FilterViewHolder(parent)
}
override fun onBindViewHolder(holder: FilterViewHolder, position: Int) {
when (position) {
0 -> {
holder.bind(getString(R.string.action_filter_add), R.drawable.ic_add)
holder.itemView.setOnClickListener {
requireActivity()
.supportFragmentManager
.beginTransaction()
.replace(R.id.container, SelectFilterTypeFragment(), SelectFilterTypeFragment::class.java.simpleName)
.addToBackStack(null)
.commit()
}
}
1 -> {
holder.bind(getString(R.string.action_filter_clear), R.drawable.ic_delete)
holder.itemView.setOnClickListener { viewModel.clearFilters() }
}
else -> {
val filter = viewModel.currentFilters.value?.getOrNull(position - 2) ?: return
holder.bind(filter)
holder.itemView.setOnClickListener(null)
}
}
}
override fun getItemCount(): Int {
val value = viewModel.currentFilters.value ?: return 1
return value.size + (if (value.isNotEmpty()) 2 else 1)
}
}
inner class FilterViewHolder(
parent: ViewGroup,
val binding: ItemFilterActiveBinding = ItemFilterActiveBinding.inflate(layoutInflater, parent, false)
) : RecyclerView.ViewHolder(binding.root) {
private val leftDrawableSize = resources.getDimensionPixelSize(R.dimen.xLargeDimen)
fun bind(filter: Filter<*>) {
val charSequence: CharSequence = when (filter) {
is Filter.TitleIs -> getString(R.string.filter_display_title_is, filter.displayText)
is Filter.TitleContain -> getString(R.string.filter_display_title_contain, filter.displayText)
is Filter.GenreIs -> getString(R.string.filter_display_genre_is, filter.displayText)
is Filter.Search -> getString(R.string.filter_display_search, filter.displayText)
is Filter.SongIs -> getString(R.string.filter_display_song_is, filter.displayText)
is Filter.ArtistIs -> getString(R.string.filter_display_artist_is, filter.displayText)
is Filter.AlbumArtistIs -> getString(R.string.filter_display_album_artist_is, filter.displayText)
is Filter.AlbumIs -> getString(R.string.filter_display_album_is, filter.displayText)
is Filter.PlaylistIs -> getString(R.string.filter_display_playlist_is, filter.displayText)
is Filter.DownloadedStatusIs -> getString(if (filter.argument) R.string.filter_display_is_downloaded else R.string.filter_display_is_not_downloaded)
}
if (filter.displayText.isNotBlank() && charSequence.contains(filter.displayText)) {
val valueStart = charSequence.lastIndexOf(filter.displayText)
val stylizedText = SpannableString(charSequence)
stylizedText.setSpan(
StyleSpan(android.graphics.Typeface.BOLD),
valueStart,
charSequence.length,
Spannable.SPAN_INCLUSIVE_INCLUSIVE
)
binding.filterName.text = stylizedText
} else {
binding.filterName.text = charSequence
}
binding.vm = viewModel
binding.filter = filter
binding.lifecycleOwner = viewLifecycleOwner
if (filter.displayImage != null) {
targets.add(
GlideApp.with(requireActivity())
.asBitmap()
.load(filter.displayImage)
.into(object : CustomTarget<Bitmap>() {
override fun onLoadCleared(placeholder: Drawable?) {
}
override fun onResourceReady(resource: Bitmap, transition: Transition<in Bitmap>?) {
val drawable = BitmapDrawable(resources, resource)
drawable.bounds = Rect(0, 0, leftDrawableSize, leftDrawableSize)
binding.filterName.setCompoundDrawables(drawable, null, null, null) //todo verify threading
}
})
)
} else {
when (filter) {
is Filter.AlbumArtistIs,
is Filter.ArtistIs -> setCompoundDrawableFromResources(R.drawable.ic_artist)
is Filter.GenreIs -> setCompoundDrawableFromResources(R.drawable.ic_genre)
is Filter.AlbumIs -> setCompoundDrawableFromResources(R.drawable.ic_album)
is Filter.PlaylistIs -> setCompoundDrawableFromResources(R.drawable.ic_playlist)
is Filter.DownloadedStatusIs -> setCompoundDrawableFromResources(R.drawable.ic_download)
is Filter.Search,
is Filter.TitleIs,
is Filter.TitleContain,
is Filter.SongIs -> setCompoundDrawableFromResources(R.drawable.ic_song)
}
}
}
fun bind(text: String, @DrawableRes icon: Int) {
binding.filter = null
binding.vm = null
binding.filterName.text = text
binding.lifecycleOwner = viewLifecycleOwner
setCompoundDrawableFromResources(icon)
}
private fun setCompoundDrawableFromResources(resId: Int) {
ResourcesCompat.getDrawable(resources, resId, requireActivity().theme)?.apply {
val color = ResourcesCompat.getColor(resources, R.color.primaryDark, requireActivity().theme)
colorFilter = BlendModeColorFilterCompat.createBlendModeColorFilterCompat(color, BlendModeCompat.SRC_IN)
bounds = Rect(0, 0, leftDrawableSize, leftDrawableSize)
binding.filterName.setCompoundDrawables(this, null, null, null)
}
}
}
}
|
gpl-3.0
|
c6456602272d718d8a4ba8a8bbfb0380
| 47.844749 | 164 | 0.649963 | 5.318747 | false | false | false | false |
LarsKrogJensen/graphql-kotlin
|
src/main/kotlin/graphql/language/DirectiveDefinition.kt
|
1
|
1086
|
package graphql.language
import java.util.ArrayList
class DirectiveDefinition(private val name: String) : AbstractNode(), Definition {
val inputValueDefinitions: MutableList<InputValueDefinition> = ArrayList()
val directiveLocations: MutableList<DirectiveLocation> = ArrayList()
override val children: List<Node>
get() {
val result = ArrayList<Node>()
result.addAll(inputValueDefinitions)
result.addAll(directiveLocations)
return result
}
override fun isEqualTo(node: Node): Boolean {
if (this === node) return true
if (javaClass != node.javaClass) return false
val that = node as DirectiveDefinition
if (name != that.name) {
return false
}
return true
}
override fun toString(): String {
return "DirectiveDefinition{" +
"name='" + name + "'" +
", inputValueDefinitions=" + inputValueDefinitions +
", directiveLocations=" + directiveLocations +
"}"
}
}
|
mit
|
8b6e4cdfefd17c36547abe32860ce4fc
| 27.578947 | 82 | 0.601289 | 5.323529 | false | false | false | false |
DemonWav/IntelliJBukkitSupport
|
src/main/kotlin/platform/sponge/insight/SpongeImplicitUsageProvider.kt
|
1
|
1570
|
/*
* Minecraft Dev for IntelliJ
*
* https://minecraftdev.org
*
* Copyright (c) 2021 minecraft-dev
*
* MIT License
*/
package com.demonwav.mcdev.platform.sponge.insight
import com.demonwav.mcdev.platform.sponge.util.isInSpongePluginClass
import com.demonwav.mcdev.platform.sponge.util.isInjected
import com.intellij.codeInsight.daemon.ImplicitUsageProvider
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiField
import com.intellij.psi.PsiMethod
class SpongeImplicitUsageProvider : ImplicitUsageProvider {
override fun isImplicitWrite(element: PsiElement): Boolean = isPluginClassInjectedField(element, false)
override fun isImplicitRead(element: PsiElement): Boolean = false
override fun isImplicitUsage(element: PsiElement): Boolean =
isPluginClassEmptyConstructor(element) || isPluginClassInjectedSetter(element)
override fun isImplicitlyNotNullInitialized(element: PsiElement): Boolean =
isPluginClassInjectedField(element, true)
private fun isPluginClassEmptyConstructor(element: PsiElement): Boolean =
element is PsiMethod && element.isInSpongePluginClass() && element.isConstructor && !element.hasParameters()
private fun isPluginClassInjectedField(element: PsiElement, optionalSensitive: Boolean): Boolean =
element is PsiField && element.isInSpongePluginClass() && isInjected(element, optionalSensitive)
private fun isPluginClassInjectedSetter(element: PsiElement): Boolean =
element is PsiMethod && element.isInSpongePluginClass() && isInjected(element, false)
}
|
mit
|
28260a714f07716eaa977150b908882d
| 39.25641 | 116 | 0.785987 | 4.700599 | false | false | false | false |
ArdentDiscord/ArdentKotlin
|
src/main/kotlin/utils/functionality/KotlinUtils.kt
|
1
|
6473
|
package utils.functionality
import com.google.gson.GsonBuilder
import com.rethinkdb.net.Cursor
import com.sedmelluq.discord.lavaplayer.track.AudioTrack
import commands.info.formatter
import commands.music.load
import main.conn
import main.r
import main.waiter
import net.dv8tion.jda.api.entities.TextChannel
import org.apache.commons.lang3.RandomStringUtils
import org.apache.commons.lang3.exception.ExceptionUtils
import org.json.simple.JSONObject
import utils.discord.getGuildById
import java.lang.management.ManagementFactory
import java.net.URLEncoder
import java.time.Instant
import java.util.*
import java.util.concurrent.TimeUnit
import java.util.stream.Collectors
import javax.management.Attribute
import javax.management.ObjectName
class Quadruple<A, B, C, D>(var first: A, var second: B, var third: C, var fourth: D)
var logChannel: TextChannel? = null
val random = Random()
val gson = GsonBuilder().serializeSpecialFloatingPointValues().create()
fun Throwable.log() {
logChannel?.sendMessage("```${ExceptionUtils.getStackTrace(this)}```")?.queue() ?: printStackTrace()
}
fun Float.format(): String {
return "%.2f".format(this)
}
fun <E> MutableList<E>.shuffle(): MutableList<E> {
Collections.shuffle(this)
return this
}
fun <E> List<E>.getWithIndex(e: E): Pair<Int, E>? {
var index = 0
forEach { if (it == e) return Pair(index, it) else index++ }
return null
}
/**
* Append a [List] of items using a comma as a separator
*/
fun <T> List<T>.stringify(): String {
return if (size == 0) "none" else map { it.toString() }.stream().collect(Collectors.joining(", "))
}
fun String.loadExternally(consumerFoundTrack: (AudioTrack, String?) -> Unit) {
val guild = getGuildById("351220166018727936")!!
load(guild.selfMember, guild.textChannels[0], consumerFoundTrack)
}
/**
* Creates an equivalent string out of the constituent strings
*/
fun List<String>.concat(): String {
return stream().collect(Collectors.joining(" "))
}
fun String.encode(): String {
return URLEncoder.encode(this, "UTF-8")
}
fun <E> MutableList<E>.putIfNotThere(e: E) {
if (!contains(e)) add(e)
}
fun Any.insert(table: String) {
r.table(table).insert(r.json(gson.toJson(this))).runNoReply(conn)
}
fun Any.update(table: String, key: String) {
r.table(table).get(key).update(r.json(gson.toJson(this))).run<Any>(conn)
}
fun genId(length: Int, table: String?): String {
val gen = RandomStringUtils.randomAlphanumeric(length)
return if (table == null) gen
else {
if (r.table(table).get(gen).run<Any?>(conn) != null) genId(length, table)
else gen
}
}
fun <T> asPojo(map: HashMap<*, *>?, tClass: Class<T>): T? {
return gson.fromJson(JSONObject.toJSONString(map), tClass)
}
fun <T> Any.queryAsArrayList(t: Class<T>): MutableList<T?> {
val tS = mutableListOf<T?>()
val cursor = this as Cursor<HashMap<*, *>>
cursor.forEach { hashMap -> tS.add(asPojo(hashMap, t)) }
cursor.close()
return tS
}
fun Long.readableDate(): String {
return "${Date.from(Instant.ofEpochMilli(this)).toLocaleString()} EST"
}
fun Int.format(): String {
return formatter.format(this)
}
fun Double.format(): String {
return formatter.format(this)
}
fun Long.format(): String {
return formatter.format(this)
}
fun String.shortenIf(numChars: Int): String {
return if (length <= numChars) this
else substring(0, numChars)
}
fun <K> MutableList<K>.forEach(consumer: (MutableIterator<K>, current: K) -> Unit) {
val iterator = iterator()
while (iterator.hasNext()) consumer.invoke(iterator, iterator.next())
}
fun <K> MutableMap<K, Int>.increment(key: K): Int {
val value = putIfAbsent(key, 0) ?: 0
replace(key, value + 1)
return value
}
fun Long.toMinutesAndSeconds(): String {
val seconds = this % 60
val minutes = (this % 3600) / 60
return if (minutes.compareTo(0) == 0) "$seconds seconds"
else "$minutes minutes, $seconds seconds"
}
fun after(consumer: () -> Unit, time: Int, unit: TimeUnit = TimeUnit.SECONDS) {
waiter.executor.schedule({ consumer.invoke() }, time.toLong(), unit)
}
fun Double.toMinutes(): Int {
return ((this % 1) * 60).toInt()
}
fun <E> List<E>.limit(int: Int): List<E> {
return if (size <= int) this
else subList(0, int - 1)
}
inline fun <E, T> Map<E, T>.forEachIndexed(function: (index: Int, E, T) -> Unit) {
var current = 0
forEach {
function.invoke(current, it.key, it.value)
current++
}
}
fun <A, B : Number> Map<A, B>.sort(descending: Boolean = true): MutableMap<A, B> {
var list = toList().sortedWith(compareBy { (it.second as Number).toDouble() })
if (descending) list = list.reversed()
return list.toMap().toMutableMap()
}
fun Any.toJson(): String {
return gson.toJson(this)
}
fun <T> MutableList<T>.without(index: Int): MutableList<T> {
removeAt(index)
return this
}
fun <T> MutableList<T>.without(t: T): MutableList<T> {
remove(t)
return this
}
fun String.removeStarting(t: String): String {
return if (startsWith(t)) removePrefix(t).removeStarting(t)
else this
}
fun Int.getListEmoji(): String {
return (if (this % 2 == 0) Emoji.SMALL_ORANGE_DIAMOND
else Emoji.SMALL_BLUE_DIAMOND).symbol
}
fun String.commandSplit(): MutableList<String> {
val split = split(" ").toMutableList()
return if (split.size == 1 && split[0] == "") mutableListOf()
else split
}
fun List<String>.containsEqualsIgnoreCase(string: String): Boolean {
forEach { if (string.toLowerCase().equals(it, true)) return true }
return false
}
/**
* Full credit goes to http://stackoverflow.com/questions/18489273/how-to-getWithIndex-percentage-of-cpu-usage-of-os-from-java
*/
fun getProcessCpuLoad(): Double {
val mbs = ManagementFactory.getPlatformMBeanServer()
val name = ObjectName.getInstance("java.lang:type=OperatingSystem")
val list = mbs.getAttributes(name, arrayOf("ProcessCpuLoad"))
if (list.isEmpty()) return java.lang.Double.NaN
val att = list[0] as Attribute
val value = att.value as Double
// usually takes a couple of seconds before we getWithIndex real values
if (value == -1.0) return Double.NaN
// returns a percentage value with 1 decimal point precision
return (value * 1000).toInt() / 10.0
}
fun replaceLast(text: String, regex: String, replacement: String): String {
return text.replaceFirst(("(?s)(.*)" + regex).toRegex(), "$1$replacement")
}
|
apache-2.0
|
34b9c90f246e0a653816f0f35719d754
| 27.147826 | 126 | 0.684072 | 3.467059 | false | false | false | false |
vanita5/twittnuker
|
twittnuker/src/main/kotlin/de/vanita5/twittnuker/extension/PreferenceExtension.kt
|
1
|
1609
|
/*
* Twittnuker - Twitter client for Android
*
* Copyright (C) 2013-2017 vanita5 <[email protected]>
*
* This program incorporates a modified version of Twidere.
* Copyright (C) 2012-2017 Mariotaku Lee <[email protected]>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package de.vanita5.twittnuker.extension
import android.support.v7.preference.Preference
import android.support.v7.preference.PreferenceGroup
import android.support.v7.preference.PreferenceScreen
import java.util.*
fun Preference.findParent(screen: PreferenceScreen): PreferenceGroup? {
val curParents = Stack<PreferenceGroup>()
curParents.add(screen)
while (!curParents.isEmpty()) {
val parent = curParents.pop()
for (i in 0 until parent.preferenceCount) {
val child = parent.getPreference(i)
if (child == this) return parent
if (child is PreferenceGroup) {
curParents.push(child)
}
}
}
return null
}
|
gpl-3.0
|
4eeb55711b11a9e934de987cc85ffa50
| 35.590909 | 73 | 0.703543 | 4.094148 | false | false | false | false |
ARostovsky/teamcity-rest-client
|
teamcity-rest-client-impl/src/test/kotlin/org/jetbrains/teamcity/rest/Hackathon17Tests.kt
|
1
|
3393
|
@file:Suppress("unused")
package org.jetbrains.teamcity.rest
import org.junit.Before
/**
* Created with IntelliJ IDEA.
*
* @author Oleg Rybak ([email protected])
*/
class Hackathon17Tests {
private lateinit var teamcity: TeamCityInstance
@Before
fun setupLog4j() {
setupLog4jDebug()
teamcity = customInstanceByConnectionFile()
}
val buildTypeID = BuildConfigurationId("TestProjectForRest_Build")
//@Test
fun test_run_build() {
val build = teamcity.buildConfiguration(buildTypeID).runBuild()
println(build)
}
//@Test
fun test_run_build_and_get_info() {
// trigger build -> Get triggered build from TC
val triggeredBuild = teamcity.buildConfiguration(buildTypeID).runBuild()
println(triggeredBuild.name)
}
// @Test
fun run_with_parameters() {
val triggeredBuild = teamcity.buildConfiguration(buildTypeID).runBuild(
parameters = mapOf("a" to "b"))
triggeredBuild.parameters.forEach { println("${it.name}=${it.value}") }
}
//@Test
fun trigger_and_cancel() {
val triggeredBuild = teamcity.buildConfiguration(buildTypeID).runBuild()
triggeredBuild.cancel(comment = "hello!")
awaitState(triggeredBuild.id, BuildState.FINISHED, 60000L)
}
//@Test
fun test_for_build_finishing() {
val triggeredBuild = teamcity.buildConfiguration(buildTypeID).runBuild()
val build = awaitState(triggeredBuild.id, BuildState.FINISHED, 60000)
println(build)
println(build.state)
}
//@Test
fun test_trigger_from_build() {
val triggeredBuild = teamcity.buildConfiguration(buildTypeID).runBuild(
parameters = mapOf("a" to "b"))
val build = getBuild(triggeredBuild.id)
val newTriggeredBuild = teamcity.buildConfiguration(buildTypeID).runBuild(
parameters = build.parameters.associate { it.name to it.value }
)
val newBuild = awaitState(newTriggeredBuild.id, BuildState.FINISHED, 60000)
println(newBuild)
newBuild.parameters.forEach { println("${it.name}=${it.value}") }
}
private fun awaitState(id: BuildId, buildState: BuildState, timeoutMsec: Long): Build {
val curTime = System.currentTimeMillis()
var b: Build? = null
var state: BuildState? = null
while (buildState != state && System.currentTimeMillis() - curTime < timeoutMsec) {
try {
b = teamcity.build(id)
state = b.state
} catch (e: KotlinNullPointerException) {
}
Thread.sleep(1000)
}
if (buildState != state) {
throw RuntimeException("Timeout")
}
return b!!
}
private fun getBuild(id: BuildId): Build {
// get build by build id
var flag = false
var buildStatus: BuildStatus? = null
var b: Build? = null
var attempts = 10
while (!flag && attempts-- > 0) {
try {
b = teamcity.build(id)
buildStatus = b.status
flag = true
} catch (e: KotlinNullPointerException) {
Thread.sleep(1000)
}
}
b?.let { println(it) }
buildStatus?.let { println(it) }
return b!!
}
}
|
apache-2.0
|
f3920500ffc51976eca7915681085d0b
| 28.763158 | 91 | 0.597406 | 4.35 | false | true | false | false |
salRoid/Filmy
|
app/src/main/java/tech/salroid/filmy/ui/activities/FullMovieActivity.kt
|
1
|
2485
|
package tech.salroid.filmy.ui.activities
import android.content.Intent
import android.os.Bundle
import android.view.MenuItem
import androidx.appcompat.app.AppCompatActivity
import androidx.preference.PreferenceManager
import androidx.recyclerview.widget.GridLayoutManager
import tech.salroid.filmy.R
import tech.salroid.filmy.data.local.model.CastMovie
import tech.salroid.filmy.databinding.ActivityFullMovieBinding
import tech.salroid.filmy.ui.adapters.CharacterDetailsActivityAdapter
class FullMovieActivity : AppCompatActivity() {
private var movieList: List<CastMovie>? = null
private var nightMode = false
private lateinit var binding: ActivityFullMovieBinding
override fun onCreate(savedInstanceState: Bundle?) {
val sp = PreferenceManager.getDefaultSharedPreferences(this)
nightMode = sp.getBoolean("dark", false)
if (nightMode) setTheme(R.style.AppTheme_Base_Dark) else setTheme(R.style.AppTheme_Base)
super.onCreate(savedInstanceState)
binding = ActivityFullMovieBinding.inflate(layoutInflater)
setContentView(binding.root)
setSupportActionBar(binding.toolbar)
binding.fullMovieRecycler.layoutManager = GridLayoutManager(this@FullMovieActivity, 3)
movieList = intent?.getSerializableExtra("cast_movies") as List<CastMovie>
supportActionBar?.setDisplayHomeAsUpEnabled(true)
supportActionBar?.title = intent?.getStringExtra("toolbar_title")
movieList?.let {
val movieAdapter =
CharacterDetailsActivityAdapter(it, false) { movie, _ ->
val intent = Intent(this, MovieDetailsActivity::class.java)
intent.putExtra("id", movie.id.toString())
intent.putExtra("title", movie.title)
intent.putExtra("network_applicable", true)
intent.putExtra("activity", false)
startActivity(intent)
}
binding.fullMovieRecycler.adapter = movieAdapter
}
}
override fun onResume() {
super.onResume()
val sp = PreferenceManager.getDefaultSharedPreferences(this)
val nightModeNew = sp.getBoolean("dark", false)
if (nightMode != nightModeNew) recreate()
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
if (item.itemId == android.R.id.home) {
finish()
}
return super.onOptionsItemSelected(item)
}
}
|
apache-2.0
|
2ce2620349d5e08a284cac7b7a13775e
| 38.460317 | 96 | 0.692555 | 5.144928 | false | false | false | false |
thanksmister/androidthings-mqtt-alarm-panel
|
app/src/main/java/com/thanksmister/iot/mqtt/alarmpanel/persistence/Message.kt
|
1
|
1241
|
/*
* Copyright (c) 2017. ThanksMister LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed
* under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.thanksmister.iot.mqtt.alarmpanel.persistence
import android.arch.persistence.room.ColumnInfo
import android.arch.persistence.room.Entity
import android.arch.persistence.room.PrimaryKey
@Entity(tableName = "Messages")
class Message {
@PrimaryKey(autoGenerate = true)
var uid: Int = 0
@ColumnInfo(name = "type")
var type: String? = null
@ColumnInfo(name = "messageId")
var messageId: String? = null
@ColumnInfo(name = "topic")
var topic: String? = null
@ColumnInfo(name = "payload")
var payload: String? = null
@ColumnInfo(name = "createdAt")
var createdAt: String? = null
}
|
apache-2.0
|
2776797db935cdfece9d74c0543b13ca
| 28.571429 | 82 | 0.717969 | 3.952229 | false | false | false | false |
AndroidX/androidx
|
wear/wear-phone-interactions/src/main/java/androidx/wear/phone/interactions/authentication/CodeChallenge.kt
|
3
|
1872
|
/*
* Copyright 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.wear.phone.interactions.authentication
import android.os.Build
import androidx.annotation.RequiresApi
import java.nio.charset.StandardCharsets
import java.security.MessageDigest
import java.util.Base64
/* ktlint-disable max-line-length */
/**
* Authorization code challenge.
*
* Related specifications:
* [Proof Key for Code Exchange by OAuth Public Clients (RFC 7636)](https://tools.ietf.org/html/rfc7636)
*/
/* ktlint-enable max-line-length */
@RequiresApi(Build.VERSION_CODES.O)
public class CodeChallenge constructor(
codeVerifier: CodeVerifier
) {
/**
* The challenge value.
*/
public val value: String
/**
* Computes the code challenge value using the specified verifier with SHA-256.
*/
init {
val md = MessageDigest.getInstance("SHA-256")
val hash: ByteArray = md.digest(codeVerifier.getValueBytes())
value = Base64.getUrlEncoder().withoutPadding().encodeToString(hash)
}
override fun equals(other: Any?): Boolean {
if (other is CodeChallenge) {
return other.value == value
}
return false
}
override fun hashCode(): Int {
return value.toByteArray(StandardCharsets.UTF_8).contentHashCode()
}
}
|
apache-2.0
|
2d05b84e92af781982dfaae1c397ac3a
| 29.704918 | 104 | 0.706197 | 4.283753 | false | false | false | false |
MeilCli/Twitter4HK
|
library/src/main/kotlin/com/twitter/meil_mitu/twitter4hk/api/lists/members/Show.kt
|
1
|
2278
|
package com.twitter.meil_mitu.twitter4hk.api.lists.members
import com.twitter.meil_mitu.twitter4hk.AbsGet
import com.twitter.meil_mitu.twitter4hk.AbsOauth
import com.twitter.meil_mitu.twitter4hk.OauthType
import com.twitter.meil_mitu.twitter4hk.ResponseData
import com.twitter.meil_mitu.twitter4hk.converter.IUserConverter
import com.twitter.meil_mitu.twitter4hk.exception.Twitter4HKException
class Show<TUser> : AbsGet<ResponseData<TUser>> {
protected val json: IUserConverter<TUser>
var listId: Long? by longParam("list_id")
var userId: Long? by longParam("user_id")
var screenName: String? by stringParam("screen_name")
var slug: String? by stringParam("slug")
var ownerScreenName: String? by stringParam("owner_screen_name")
var ownerId: Long? by longParam("owner_id")
var includeEntities: Boolean? by booleanParam("include_entities")
var skipStatus: Boolean? by booleanParam("skip_status")
override val url = "https://api.twitter.com/1.1/lists/members/show.json"
override val allowOauthType = OauthType.oauth1 or OauthType.oauth2
override val isAuthorization = true
constructor(
oauth: AbsOauth,
json: IUserConverter<TUser>,
listId: Long,
userId: Long) : super(oauth) {
this.json = json
this.listId = listId
this.userId = userId
}
constructor(
oauth: AbsOauth,
json: IUserConverter<TUser>,
listId: Long,
screenName: String) : super(oauth) {
this.json = json
this.listId = listId
this.screenName = screenName
}
constructor(
oauth: AbsOauth,
json: IUserConverter<TUser>,
slug: String,
userId: Long) : super(oauth) {
this.json = json
this.slug = slug
this.userId = userId
}
constructor(
oauth: AbsOauth,
json: IUserConverter<TUser>,
slug: String,
screenName: String) : super(oauth) {
this.json = json
this.slug = slug
this.screenName = screenName
}
@Throws(Twitter4HKException::class)
override fun call(): ResponseData<TUser> {
return json.toUserResponseData(oauth.get(this))
}
}
|
mit
|
97ce85e94ce404d84be69bc342b32147
| 32.014493 | 76 | 0.64662 | 4.25 | false | false | false | false |
Undin/intellij-rust
|
src/main/kotlin/org/rust/lang/core/psi/ext/RsLitExpr.kt
|
2
|
4317
|
/*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.lang.core.psi.ext
import com.intellij.lang.ASTNode
import com.intellij.psi.*
import com.intellij.psi.impl.source.tree.LeafElement
import com.intellij.psi.stubs.IStubElementType
import org.intellij.lang.regexp.DefaultRegExpPropertiesProvider
import org.intellij.lang.regexp.RegExpLanguageHost
import org.intellij.lang.regexp.psi.RegExpChar
import org.intellij.lang.regexp.psi.RegExpGroup
import org.intellij.lang.regexp.psi.RegExpNamedGroupRef
import org.rust.ide.injected.escaperForLiteral
import org.rust.lang.core.psi.RS_ALL_STRING_LITERALS
import org.rust.lang.core.psi.RsLitExpr
import org.rust.lang.core.psi.RsLiteralKind
import org.rust.lang.core.psi.impl.RsExprImpl
import org.rust.lang.core.psi.kind
import org.rust.lang.core.stubs.RsLitExprStub
import org.rust.lang.core.stubs.RsPlaceholderStub
import org.rust.lang.core.stubs.RsStubLiteralKind
import org.rust.lang.core.types.ty.TyFloat
import org.rust.lang.core.types.ty.TyInteger
val RsLitExpr.stubKind: RsStubLiteralKind?
get() {
val stub = (greenStub as? RsLitExprStub)
if (stub != null) return stub.kind
return when (val kind = kind) {
is RsLiteralKind.Boolean -> RsStubLiteralKind.Boolean(kind.value)
is RsLiteralKind.Char -> RsStubLiteralKind.Char(kind.value, kind.isByte)
is RsLiteralKind.String -> RsStubLiteralKind.String(kind.value, kind.isByte)
is RsLiteralKind.Integer -> RsStubLiteralKind.Integer(kind.value, TyInteger.fromSuffixedLiteral(integerLiteral!!))
is RsLiteralKind.Float -> RsStubLiteralKind.Float(kind.value, TyFloat.fromSuffixedLiteral(floatLiteral!!))
else -> null
}
}
val RsLitExpr.booleanValue: Boolean? get() = (stubKind as? RsStubLiteralKind.Boolean)?.value
val RsLitExpr.integerValue: Long? get() = (stubKind as? RsStubLiteralKind.Integer)?.value
val RsLitExpr.floatValue: Double? get() = (stubKind as? RsStubLiteralKind.Float)?.value
val RsLitExpr.charValue: String? get() = (stubKind as? RsStubLiteralKind.Char)?.value
val RsLitExpr.stringValue: String? get() = (stubKind as? RsStubLiteralKind.String)?.value
abstract class RsLitExprMixin : RsExprImpl, RsLitExpr, RegExpLanguageHost {
constructor(node: ASTNode) : super(node)
constructor(stub: RsPlaceholderStub<*>, nodeType: IStubElementType<*, *>) : super(stub, nodeType)
override fun isValidHost(): Boolean =
node.findChildByType(RS_ALL_STRING_LITERALS) != null
override fun updateText(text: String): PsiLanguageInjectionHost {
val valueNode = node.firstChildNode
assert(valueNode is LeafElement)
(valueNode as LeafElement).replaceWithText(text)
return this
}
override fun createLiteralTextEscaper(): LiteralTextEscaper<RsLitExpr> =
escaperForLiteral(this)
override fun getReferences(): Array<PsiReference> =
PsiReferenceService.getService().getContributedReferences(this)
override fun characterNeedsEscaping(c: Char): Boolean = false
override fun supportsPerl5EmbeddedComments(): Boolean = false
override fun supportsPossessiveQuantifiers(): Boolean = true
override fun supportsPythonConditionalRefs(): Boolean = false
override fun supportsNamedGroupSyntax(group: RegExpGroup): Boolean = true
override fun supportsNamedGroupRefSyntax(ref: RegExpNamedGroupRef): Boolean =
ref.isNamedGroupRef
override fun supportsExtendedHexCharacter(regExpChar: RegExpChar): Boolean = true
override fun isValidCategory(category: String): Boolean =
DefaultRegExpPropertiesProvider.getInstance().isValidCategory(category)
override fun getAllKnownProperties(): Array<Array<String>> =
DefaultRegExpPropertiesProvider.getInstance().allKnownProperties
override fun getPropertyDescription(name: String?): String? =
DefaultRegExpPropertiesProvider.getInstance().getPropertyDescription(name)
override fun getKnownCharacterClasses(): Array<Array<String>> =
DefaultRegExpPropertiesProvider.getInstance().knownCharacterClasses
}
fun RsLitExpr.containsOffset(offset: Int): Boolean =
ElementManipulators.getValueTextRange(this).shiftRight(textOffset).containsOffset(offset)
|
mit
|
564423722f4e813c3baf1b7f30a446ca
| 44.442105 | 126 | 0.764188 | 4.338693 | false | false | false | false |
androidx/androidx
|
paging/samples/src/main/java/androidx/paging/samples/InsertSeparatorsSample.kt
|
3
|
4656
|
/*
* 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.
*/
@file:Suppress("unused") // Currently, all samples incorrectly labeled as unused.
package androidx.paging.samples
import androidx.annotation.Sampled
import androidx.paging.AdjacentItems
import androidx.paging.PagingData
import androidx.paging.insertSeparators
import androidx.paging.insertSeparatorsAsync
import androidx.paging.rxjava2.insertSeparatorsAsync
import com.google.common.util.concurrent.AsyncFunction
import com.google.common.util.concurrent.Futures
import io.reactivex.Maybe
import io.reactivex.schedulers.Schedulers
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.map
import java.util.concurrent.Callable
import java.util.concurrent.Executors
private lateinit var pagingDataStream: Flow<PagingData<String>>
@Sampled
fun insertSeparatorsSample() {
/*
* Create letter separators in an alphabetically sorted list.
*
* For example, if the input is:
* "apple", "apricot", "banana", "carrot"
*
* The operator would output:
* "A", "apple", "apricot", "B", "banana", "C", "carrot"
*/
pagingDataStream.map { pagingData ->
// map outer stream, so we can perform transformations on each paging generation
pagingData.insertSeparators { before: String?, after: String? ->
if (after != null && before?.first() != after.first()) {
// separator - after is first item that starts with its first letter
after.first().uppercaseChar().toString()
} else {
// no separator - either end of list, or first letters of before/after are the same
null
}
}
}
}
@Sampled
fun insertSeparatorsRxSample() {
/*
* Create letter separators in an alphabetically sorted list.
*
* For example, if the input is:
* "apple", "apricot", "banana", "carrot"
*
* The operator would output:
* "A", "apple", "apricot", "B", "banana", "C", "carrot"
*/
pagingDataStream.map { pagingData ->
// map outer stream, so we can perform transformations on each paging generation
pagingData.insertSeparatorsAsync { before: String?, after: String? ->
Maybe.fromCallable<String> {
if (after != null && before?.first() != after.first()) {
// separator - after is first item that starts with its first letter
after.first().uppercaseChar().toString()
} else {
// no separator - either end of list, or first letters of before/after are the same
null
}
}.subscribeOn(Schedulers.computation())
}
}
}
private val executor = Executors.newSingleThreadExecutor()
@Suppress("UnstableApiUsage")
@Sampled
fun insertSeparatorsFutureSample() {
/*
* Create letter separators in an alphabetically sorted list.
*
* For example, if the input is:
* "apple", "apricot", "banana", "carrot"
*
* The operator would output:
* "A", "apple", "apricot", "B", "banana", "C", "carrot"
*/
pagingDataStream.map { pagingData ->
// map outer stream, so we can perform transformations on each paging generation
pagingData.insertSeparatorsAsync(
AsyncFunction<AdjacentItems<String>, String?> {
Futures.submit(
Callable<String?> {
val (before, after) = it!!
if (after != null && before?.first() != after.first()) {
// separator - after is first item that starts with its first letter
after.first().uppercaseChar().toString()
} else {
// no separator - either end of list, or first letters of before/after are the same
null
}
},
executor
)
},
executor
)
}
}
|
apache-2.0
|
e5af7947e7c766455d40dcd7674589c4
| 36.248 | 111 | 0.609321 | 4.707786 | false | false | false | false |
jean79/yested
|
src/main/kotlin/net/yested/utils/dom.kt
|
2
|
771
|
package net.yested.utils
import org.w3c.dom.HTMLElement
import org.w3c.dom.Node
import org.w3c.dom.Window
/**
* @return true if given element is included in page DOM
*
* check this:
* http://stackoverflow.com/questions/19669786/check-if-element-is-visible-in-dom
* return (node as HTMLElement).offsetParent != null // this is fast but does not work in IE9
*/
external class CSSStyleDeclaration {
val display:String
}
@Suppress("NOTHING_TO_INLINE")
inline fun Window.getComputedStyle(node:Node):CSSStyleDeclaration = asDynamic().getComputedStyle(node)
fun isIncludedInDOM(node:Node):Boolean {
/*var style = window.getComputedStyle(node);
return style.display != "none" && style.display != ""*/
return (node as HTMLElement).offsetParent != null
}
|
mit
|
ab5b889930803ab4006363a47879d17d
| 28.692308 | 102 | 0.7393 | 3.488688 | false | false | false | false |
mvosske/comlink
|
app/src/main/java/org/tnsfit/dragon/comlink/AroManager.kt
|
1
|
2657
|
package org.tnsfit.dragon.comlink
import android.content.Context
import android.os.Handler
import android.view.ViewGroup
import android.widget.ImageView
import java.util.*
/**
* Created by dragon on 11.10.16.
* Pings sind kurzeitiger Anzeiger
* Marker sind Dauerhafte Anzeiger
* Pings und Marker sind zusammen AROs
*
* X und Y sind in Bezug auf Portrait, also Invertierung für Landscape
*/
class AroManager(val imageDimension: ImageDimensions) {
private val mHandler: Handler
private val mPingList: MutableList<ImageView> = LinkedList()
private val mMarkerList: MutableList<ImageView> = LinkedList()
private val deleteListener: AroDeleter = AroDeleter()
init {
mHandler = Handler()
}
fun rePlaceMarker() {
for (marker in mMarkerList) {
if (!marker.isAttachedToWindow) continue
val frame = marker.parent as? ViewGroup ?: continue
val coords = marker.tag as? AroCoordinates ?: continue
frame.removeView(marker)
frame.addView(marker, coords.layoutParams(imageDimension))
}
}
fun getPing (c: Context): ImageView {
val result = get(c, mPingList)
result.setImageResource(R.drawable.ping_image)
result.setOnClickListener(deleteListener)
return result
}
fun getMarker (c: Context): ImageView {
val result = get(c, mMarkerList)
result.setImageResource(R.drawable.marker_image)
result.setOnLongClickListener(deleteListener)
return result
}
private fun get(c: Context, list: MutableList<ImageView>): ImageView {
for (v in list) {
if (v.isAttachedToWindow) {
continue
} else {
return v
}
}
val result = ImageView(c)
list.add(result)
return result
}
fun placePing(c: Context, frame: ViewGroup, coords: AroCoordinates) {
val view = getPing(c)
frame.addView(view, coords.layoutParams(imageDimension))
mHandler.postDelayed(deleteListener.OnTime(view), 4000)
}
fun placeMarker (c: Context, frame: ViewGroup, coords: AroCoordinates) {
val view = getMarker(c)
view.tag = coords
frame.addView(view, coords.layoutParams(imageDimension))
}
fun removeMarker(frame: ViewGroup, coords: AroCoordinates) {
for (i in 0..frame.childCount-1) {
val child = frame.getChildAt(i)
val tag = child?.tag ?: continue
if (coords.equals(tag)) {
frame.removeViewAt(i)
child.tag = null
}
}
}
}
|
gpl-3.0
|
735a47bdd3a07a354caa4e96f38d126e
| 28.842697 | 76 | 0.628012 | 4.236045 | false | false | false | false |
EventFahrplan/EventFahrplan
|
app/src/test/java/nerd/tuxmobil/fahrplan/congress/extensions/TextViewExtensionsTest.kt
|
1
|
2330
|
package nerd.tuxmobil.fahrplan.congress.extensions
import android.text.Spannable
import android.text.method.MovementMethod
import android.text.style.URLSpan
import android.widget.TextView
import androidx.core.text.set
import androidx.core.text.toSpannable
import com.google.common.truth.Truth.assertThat
import org.junit.Test
import org.mockito.kotlin.any
import org.mockito.kotlin.argumentCaptor
import org.mockito.kotlin.mock
import org.mockito.kotlin.verify
class TextViewExtensionsTest {
@Test
fun `setLinkText applies formatted link text with title and MovementMethod and LinkTextColor`() {
val textView = mock<TextView>()
val movementMethod = mock<MovementMethod>()
val plainLinkUrl = "https://example.com"
val urlTitle = "Example website"
textView.setLinkText(
plainLinkUrl = plainLinkUrl,
urlTitle = urlTitle,
movementMethod = movementMethod,
linkTextColor = 23
)
val linkTextSpannableCaptor = argumentCaptor<Spannable>()
verify(textView).setText(linkTextSpannableCaptor.capture(), any())
verify(textView).movementMethod = movementMethod
verify(textView).setLinkTextColor(23)
val linkText = urlTitle.toSpannable().apply { set(0, urlTitle.length, URLSpan(plainLinkUrl)) }
assertThat(linkTextSpannableCaptor.lastValue.toString()).isEqualTo(linkText.toString())
}
@Test
fun `setLinkText applies formatted link text without title and MovementMethod and LinkTextColor`() {
val textView = mock<TextView>()
val movementMethod = mock<MovementMethod>()
val plainLinkUrl = "https://example.com"
textView.setLinkText(
plainLinkUrl = plainLinkUrl,
movementMethod = movementMethod,
linkTextColor = 23
)
val linkTextSpannableCaptor = argumentCaptor<Spannable>()
verify(textView).setText(linkTextSpannableCaptor.capture(), any())
verify(textView).movementMethod = movementMethod
verify(textView).setLinkTextColor(23)
val linkText = plainLinkUrl.toSpannable().apply { set(0, plainLinkUrl.length, URLSpan(plainLinkUrl)) }
assertThat(linkTextSpannableCaptor.lastValue.toString()).isEqualTo(linkText.toString())
}
}
|
apache-2.0
|
493e47acd2110a7ba51660e1b69fb128
| 40.607143 | 110 | 0.703433 | 4.957447 | false | true | false | false |
vitorsalgado/android-boilerplate
|
api/src/main/kotlin/br/com/vitorsalgado/example/api/ApiAdapterFactory.kt
|
1
|
1028
|
package br.com.vitorsalgado.example.api
import io.reactivex.Observable
import retrofit2.CallAdapter
import retrofit2.Retrofit
import java.lang.reflect.ParameterizedType
import java.lang.reflect.Type
class ApiAdapterFactory : CallAdapter.Factory() {
override fun get(returnType: Type, annotations: Array<Annotation>, retrofit: Retrofit): CallAdapter<*, *>? {
if (CallAdapter.Factory.getRawType(returnType) != Observable::class.java) {
return null
}
val observableType = CallAdapter.Factory.getParameterUpperBound(0, returnType as ParameterizedType)
val rawObservableType = CallAdapter.Factory.getRawType(observableType)
if (rawObservableType != ApiResponse::class.java) {
throw IllegalArgumentException("type must be a resource")
}
if (observableType !is ParameterizedType) {
throw IllegalArgumentException("resource must be parametrized")
}
val bodyType = CallAdapter.Factory.getParameterUpperBound(0, observableType)
return ApiCallAdapter<Any>(bodyType)
}
}
|
apache-2.0
|
15ee13c18ee6b61f5c95f77524e511b2
| 33.266667 | 110 | 0.764591 | 4.759259 | false | false | false | false |
CruGlobal/android-gto-support
|
gto-support-material-components/src/main/kotlin/org/ccci/gto/android/common/material/textfield/databinding/TextInputLayoutBindingAdapter.kt
|
2
|
865
|
@file:BindingMethods(
BindingMethod(
type = TextInputLayout::class,
attribute = ANDROID_TEXT_COLOR_HINT,
method = "setDefaultHintTextColor"
)
)
package org.ccci.gto.android.common.material.textfield.databinding
import android.content.res.ColorStateList
import androidx.databinding.BindingAdapter
import androidx.databinding.BindingMethod
import androidx.databinding.BindingMethods
import com.google.android.material.textfield.TextInputLayout
private const val ANDROID_TEXT_COLOR_HINT = "android:textColorHint"
private const val HINT_TEXT_COLOR = "hintTextColor"
@BindingAdapter(ANDROID_TEXT_COLOR_HINT, HINT_TEXT_COLOR)
internal fun TextInputLayout.bindHintTextColors(defaultHintTextColor: ColorStateList?, hintTextColor: ColorStateList?) {
setDefaultHintTextColor(defaultHintTextColor)
setHintTextColor(hintTextColor)
}
|
mit
|
f3fdf7529ee3b3df2c002b850c017cfe
| 35.041667 | 120 | 0.806936 | 4.458763 | false | false | false | false |
pmiddend/org-parser
|
src/main/java/de/plapadoo/orgparser/Structure.kt
|
1
|
7362
|
package de.plapadoo.orgparser
import java.time.LocalDate
import java.time.LocalTime
/**
* Created by philipp on 8/7/16.
*/
data class Headline(
val level: Int,
val keyword: String?,
val priority: Char?,
val title: String,
val tags: List<String>)
data class GreaterBlock(
val type: String,
val parameters: String?,
val content: List<String>)
data class DynamicBlock(
val type: String,
val parameters: String?,
val content: List<String>)
data class Property(
val name: String,
val value: String?,
val plus: Boolean)
data class PropertyDrawer(
val properties: List<Property>)
data class Drawer(
val name: String,
val content: List<String>)
data class FootnoteLabel(
val label: String,
val numeric: Boolean)
data class Footnote(
val label: FootnoteLabel,
val content: String)
data class AffiliatedKeyword(
val key: String,
val optional: String?,
val value: String)
data class Date(
val date: LocalDate)
data class Time(
val time: LocalTime)
enum class Repeater {
CUMULATE,
CATCH_UP,
RESTART,
ALL,
FIRST
}
enum class RepeaterUnit {
HOUR,
DAY,
WEEK,
MONTH,
YEAR
}
data class RepeaterOrDelay(
val mark: Repeater,
val value: Int,
val unit: RepeaterUnit)
sealed class Timestamp {
class Sexp(val descriptor: String) : Timestamp() {
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other?.javaClass != javaClass) return false
other as Sexp
if (descriptor != other.descriptor) return false
return true
}
override fun hashCode(): Int {
return descriptor.hashCode()
}
override fun toString(): String {
return "Sexp(descriptor='$descriptor')"
}
}
class Active(val date: Date, val time: Time?, val repeater1: RepeaterOrDelay?, val repeater2: RepeaterOrDelay?) : Timestamp() {
override fun toString(): String {
return "Active(date=$date, time=$time, repeater1=$repeater1, repeater2=$repeater2)"
}
override fun equals(other: Any?): Boolean{
if (this === other) return true
if (other?.javaClass != javaClass) return false
other as Active
if (date != other.date) return false
if (time != other.time) return false
if (repeater1 != other.repeater1) return false
if (repeater2 != other.repeater2) return false
return true
}
override fun hashCode(): Int{
var result = date.hashCode()
result = 31 * result + (time?.hashCode() ?: 0)
result = 31 * result + (repeater1?.hashCode() ?: 0)
result = 31 * result + (repeater2?.hashCode() ?: 0)
return result
}
}
class Inactive(val date: Date, val time: Time?, val repeater1: RepeaterOrDelay?, val repeater2: RepeaterOrDelay?) : Timestamp() {
override fun toString(): String {
return "Inactive(date=$date, time=$time, repeater1=$repeater1, repeater2=$repeater2)"
}
override fun equals(other: Any?): Boolean{
if (this === other) return true
if (other?.javaClass != javaClass) return false
other as Inactive
if (date != other.date) return false
if (time != other.time) return false
if (repeater1 != other.repeater1) return false
if (repeater2 != other.repeater2) return false
return true
}
override fun hashCode(): Int{
var result = date.hashCode()
result = 31 * result + (time?.hashCode() ?: 0)
result = 31 * result + (repeater1?.hashCode() ?: 0)
result = 31 * result + (repeater2?.hashCode() ?: 0)
return result
}
}
class ActiveRange(val from: Active, val to: Active) : Timestamp() {
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other?.javaClass != javaClass) return false
other as ActiveRange
if (from != other.from) return false
if (to != other.to) return false
return true
}
override fun hashCode(): Int {
var result = from.hashCode()
result = 31 * result + to.hashCode()
return result
}
override fun toString(): String {
return "ActiveRange(from=$from, to=$to)"
}
}
class InactiveRange(val from: Inactive, val to: Inactive) : Timestamp() {
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other?.javaClass != javaClass) return false
other as InactiveRange
if (from != other.from) return false
if (to != other.to) return false
return true
}
override fun hashCode(): Int {
var result = from.hashCode()
result = 31 * result + to.hashCode()
return result
}
override fun toString(): String {
return "InactiveRange(from=$from, to=$to)"
}
}
}
data class Duration(val hours: Int, val minutes: Int)
data class Clock(val timestamp: Timestamp, val duration: Duration)
enum class PlanningKeyword {
DEADLINE,
SCHEDULED,
CLOSED
}
data class Planning(val keyword: PlanningKeyword, val timestamp: Timestamp) {
}
data class PlanningLine(val plannings: List<Planning>)
data class BabelCall(val value: String?)
enum class BulletType {
ASTERISK,
HYPHEN,
PLUS,
COUNTER_DOT,
COUNTER_PAREN
}
data class Bullet(val type: BulletType, val counter: Counter?)
fun asterisk() = Bullet(type = BulletType.ASTERISK, counter = null)
fun hyphen() = Bullet(type = BulletType.HYPHEN, counter = null)
fun plus() = Bullet(type = BulletType.PLUS, counter = null)
data class Counter(val numberValue: Int?, val charValue: Char?)
enum class CheckboxType {
EMPTY,
HALF,
FULL
}
data class ListItem(val indentation: Int, val bulletType: Bullet, val counterSet: Counter?, val checkbox: CheckboxType?, val tag: String?, val content: String)
data class TableRow(val indentation: Int, val columns: List<String>?)
data class Table(val rows: List<TableRow>, val formulas: List<String>)
data class Keyword(val key: String, val value: String)
data class LatexEnvironment(val name: String, val content: String)
data class ExportSnippet(val name: String, val value: String)
data class Paragraph(val content: String)
data class DocumentElement(
val paragraph: Paragraph? = null,
val planningLine: PlanningLine? = null,
val horizontalRule: String? = null,
val greaterBlock: GreaterBlock? = null,
val propertyDrawer: PropertyDrawer? = null,
val drawer: Drawer? = null,
val dynamicBlock: DynamicBlock? = null,
val footnote: Footnote? = null,
val listItem: ListItem? = null,
val table: Table? = null,
val headline: Headline? = null) {
}
data class Document(val elements: List<DocumentElement>)
|
mit
|
147d86d9003c441d82db9f9f98b4e780
| 26.066176 | 159 | 0.598071 | 4.253033 | false | false | false | false |
handstandsam/ShoppingApp
|
app/src/main/java/com/handstandsam/shoppingapp/features/category/CategoryViewModel.kt
|
1
|
2341
|
package com.handstandsam.shoppingapp.features.category
import com.handstandsam.shoppingapp.MviViewModel
import com.handstandsam.shoppingapp.models.Item
import com.handstandsam.shoppingapp.network.Response
import com.handstandsam.shoppingapp.repository.ItemRepo
import com.handstandsam.shoppingapp.utils.exhaustive
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
class CategoryViewModel(
private val scope: CoroutineScope,
private val itemRepo: ItemRepo
) : MviViewModel<
CategoryViewModel.State,
CategoryViewModel.Intention,
CategoryViewModel.SideEffect>(
scope = scope,
initialState = State()
) {
private fun getItemsForCategory(categoryLabel: String) {
scope.launch(Dispatchers.IO) {
val categoriesResult = itemRepo.getItemsForCategory(categoryLabel)
when (categoriesResult) {
is Response.Success -> {
send(Intention.CategoriesReceived(categoriesResult.body))
}
is Response.Failure -> {
error("Ooops")
}
}.exhaustive
}
}
override fun reduce(state: State, intention: Intention): State {
return when (intention) {
is Intention.ItemClicked -> {
sideEffect(SideEffect.LaunchItemDetailActivity(intention.item))
state
}
is Intention.CategoriesReceived -> {
state.copy(
items = intention.items
)
}
is Intention.CategoryLabelSet -> {
getItemsForCategory(intention.categoryLabel)
state.copy(
categoryLabel = intention.categoryLabel
)
}
}.exhaustive
}
data class State(
val items: List<Item> = listOf(),
val categoryLabel: String? = null
)
sealed class Intention {
data class CategoriesReceived(val items: List<Item>) : Intention()
data class ItemClicked(val item: Item) : Intention()
data class CategoryLabelSet(val categoryLabel: String) : Intention()
}
sealed class SideEffect {
data class LaunchItemDetailActivity(val item: Item) : SideEffect()
}
}
|
apache-2.0
|
b9f5c82416b22f27b8355e8a86c94cb3
| 31.513889 | 79 | 0.624947 | 5.202222 | false | false | false | false |
Tvede-dk/CommonsenseAndroidKotlin
|
widgets/src/main/kotlin/com/commonsense/android/kotlin/views/features/SectionRecyclerTransaction.kt
|
1
|
6981
|
@file:Suppress("unused", "NOTHING_TO_INLINE", "MemberVisibilityCanBePrivate")
package com.commonsense.android.kotlin.views.features
import com.commonsense.android.kotlin.base.*
import com.commonsense.android.kotlin.base.extensions.collections.*
import com.commonsense.android.kotlin.base.patterns.*
import com.commonsense.android.kotlin.views.databinding.adapters.*
/**
* Created by Kasper Tvede on 21-07-2017.
*/
typealias SectionOperation<T> = DataBindingRecyclerAdapter<T>.() -> Unit
typealias FunctionAdapterBoolean<T> = (DataBindingRecyclerAdapter<T>) -> Boolean
private class SectionTransactionCommando<T : IRenderModelItem<*, *>>(
val applyOperation: SectionOperation<T>,
val resetOperation: SectionOperation<T>)
class SectionRecyclerTransaction<T : IRenderModelItem<*, *>>
private constructor(
private val applyTransactions: List<SectionOperation<T>>,
private val resetTransactions: List<SectionOperation<T>>,
private val adapter: DataBindingRecyclerAdapter<T>,
private val allowExternalModifications: Boolean) {
private val isApplied = ToggleBoolean(false)
private var oldSize = 0
init {
oldSize = adapter.itemCount
}
fun apply() = isApplied.ifFalse {
performTransactions(applyTransactions)
}
fun applySafe(ifNotSafe: EmptyFunction? = null) {
if (canPerformTransaction()) {
apply()
} else {
ifNotSafe?.invoke()
}
}
fun resetSafe(ifNotSafe: EmptyFunction? = null) {
if (canPerformTransaction()) {
reset()
} else {
ifNotSafe?.invoke()
}
}
fun reset() = isApplied.ifTrue {
performTransactions(resetTransactions)
}
private fun canPerformTransaction(): Boolean =
adapter.itemCount == oldSize || allowExternalModifications
private fun performTransactions(opertaions: List<SectionOperation<T>>) {
if (!canPerformTransaction()) {
throw RuntimeException("External changes are not permitted on the adapter for this transaction;\r\n" +
"if this is expected, set allow external modifications to true.")
//WARNING this is super dangerous, we are potentially unable to do our transaction.
}
opertaions.invokeEachWith(adapter)
oldSize = adapter.itemCount
}
class Builder<T : IRenderModelItem<*, *>>(private val adapter: DataBindingRecyclerAdapter<T>) {
private val operations = mutableListOf<SectionTransactionCommando<T>>()
var allowExternalModifications = false
private fun addOperation(applyOperation: SectionOperation<T>, resetOperation: SectionOperation<T>) {
operations.add(SectionTransactionCommando(applyOperation, resetOperation))
}
fun hideSection(sectionIndex: Int) {
val visibilityBefore = adapter.isSectionVisible(sectionIndex)
addOperation({ this.hideSection(sectionIndex) }, { this.setSectionVisibility(sectionIndex, visibilityBefore) })
}
fun showSection(sectionIndex: Int) {
val visibilityBefore = adapter.isSectionVisible(sectionIndex)
addOperation({ this.showSection(sectionIndex) }, { this.setSectionVisibility(sectionIndex, visibilityBefore) })
}
fun addItems(items: List<T>, inSection: Int) {
addOperation({ this.addAll(items, inSection) }, { this.removeAll(items, inSection) })
}
fun removeItems(items: List<T>, inSection: Int) {
addOperation({ this.removeAll(items, inSection) }, { addAll(items, inSection) })
}
fun addItem(item: T, inSection: Int) {
addOperation({ this.add(item, inSection) }, { this.remove(item, inSection) })
}
/**
* should turn invisible given the condition
*/
fun hideSectionIf(condition: FunctionAdapterBoolean<T>, inSection: Int) {
val visibilityBefore = adapter.isSectionVisible(inSection)
addOperation({
if (condition(this)) {
this.hideSection(inSection)
}
}, { this.setSectionVisibility(inSection, visibilityBefore) }) //double showing a section cannot go wrong.
}
/**
* should turn visible given the condition
*/
fun showSectionIf(condition: FunctionAdapterBoolean<T>, inSection: Int) {
val visibilityBefore = adapter.isSectionVisible(inSection)
addOperation({
if (condition(this)) {
this.showSection(inSection)
}
}, { this.setSectionVisibility(inSection, visibilityBefore) }) //double hiding a section cannot go wrong.
}
/**
*
*/
fun setSectionsVisibility(sectionToShow: Int, SectionToHide: Int) {
addOperation({
this.showSection(sectionToShow)
this.hideSection(SectionToHide)
}, {
this.hideSection(sectionToShow)
this.showSection(SectionToHide)
})
}
fun removeItem(item: T, inSection: Int) {
adapter.getIndexFor(item, inSection)?.let {
this.removeItemAt(item, it.row, it.section)
}
}
fun insert(item: T, row: Int, inSection: Int) {
addOperation({ this.insert(item, row, inSection) }, { this.removeAt(row, inSection) })
}
fun removeItemAt(item: T, row: Int, inSection: Int) {
addOperation({ this.removeAt(row, inSection) }, {
if (this.getSectionSize(inSection) == null) {
//section dies, recreate it.
this.add(item, inSection)
} else {
this.insert(item, row, inSection)
}
})
}
fun saveSectionsVisibilies(vararg sections: Int) {
val states = sections.map { Pair(it, adapter.isSectionVisible(it)) }
saveVisibilityForSectionsAction(states)
}
//TODO requies further api expansion (query the section indexes somehow)
/* fun saveAllSectionsVisibilities() {
val states = adapter.section .map { adapter.isSectionVisible(it) }
saveVisibilityForSectionsAction(states)
}*/
private fun saveVisibilityForSectionsAction(sectionToVisibility: List<Pair<Int, Boolean>>) {
addOperation({}, {
sectionToVisibility.forEach {
adapter.setSectionVisibility(it.first, it.second)
}
})
}
fun build(): SectionRecyclerTransaction<T> = SectionRecyclerTransaction(
operations.map { it.applyOperation },
operations.reversed().map { it.resetOperation },
adapter, allowExternalModifications
)
}
}
|
mit
|
bb48c11783caaec1be6c721274d27c74
| 34.984536 | 123 | 0.615814 | 4.96162 | false | false | false | false |
inorichi/tachiyomi-extensions
|
src/zh/tohomh123/src/eu/kanade/tachiyomi/extension/zh/tohomh123/Tohomh.kt
|
1
|
5480
|
package eu.kanade.tachiyomi.extension.zh.tohomh123
import com.github.salomonbrys.kotson.fromJson
import com.google.gson.Gson
import com.google.gson.JsonObject
import eu.kanade.tachiyomi.network.GET
import eu.kanade.tachiyomi.source.model.FilterList
import eu.kanade.tachiyomi.source.model.Page
import eu.kanade.tachiyomi.source.model.SChapter
import eu.kanade.tachiyomi.source.model.SManga
import eu.kanade.tachiyomi.source.online.ParsedHttpSource
import eu.kanade.tachiyomi.util.asJsoup
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.Response
import org.jsoup.nodes.Document
import org.jsoup.nodes.Element
import java.text.SimpleDateFormat
import java.util.Locale
class Tohomh : ParsedHttpSource() {
override val name = "Tohomh123"
override val baseUrl = "https://www.tohomh123.com"
override val lang = "zh"
override val supportsLatest = true
override val client: OkHttpClient = network.cloudflareClient
// Popular
override fun popularMangaRequest(page: Int): Request {
return GET("$baseUrl/f-1-------hits--$page.html", headers)
}
override fun popularMangaSelector() = "div.mh-item"
override fun popularMangaFromElement(element: Element): SManga {
val manga = SManga.create()
element.select("h2 a").let {
manga.setUrlWithoutDomain(it.attr("href"))
manga.title = it.attr("title")
}
manga.thumbnail_url = element.select("p").attr("style").substringAfter("(").substringBefore(")")
return manga
}
override fun popularMangaNextPageSelector() = "div.page-pagination li a:contains(>)"
// Latest
override fun latestUpdatesRequest(page: Int): Request {
return GET("$baseUrl/f-1------updatetime--$page.html", headers)
}
override fun latestUpdatesSelector() = popularMangaSelector()
override fun latestUpdatesFromElement(element: Element) = popularMangaFromElement(element)
override fun latestUpdatesNextPageSelector() = popularMangaNextPageSelector()
// Search
override fun searchMangaRequest(page: Int, query: String, filters: FilterList): Request {
return GET("$baseUrl/action/Search?keyword=$query&page=$page", headers)
}
override fun searchMangaSelector() = popularMangaSelector()
override fun searchMangaFromElement(element: Element) = popularMangaFromElement(element)
override fun searchMangaNextPageSelector() = popularMangaNextPageSelector()
// Manga summary page
override fun mangaDetailsParse(document: Document): SManga {
val infoElement = document.select("div.banner_detail_form").first()
val manga = SManga.create()
manga.title = infoElement.select("h1").first().text()
manga.author = infoElement.select("div.info p.subtitle").text().substringAfter(":").trim()
val status = infoElement.select("div.banner_detail_form div.info span.block:contains(状态) span").text()
manga.status = parseStatus(status)
manga.description = infoElement.select("div.info p.content").text()
manga.thumbnail_url = infoElement.select("div.banner_detail_form div.cover img").first().attr("src")
return manga
}
private fun parseStatus(status: String?) = when {
status == null -> SManga.UNKNOWN
status.contains("连载中") -> SManga.ONGOING
status.contains("完结") -> SManga.COMPLETED
else -> SManga.UNKNOWN
}
// Chapters
override fun chapterListSelector() = "ul#detail-list-select-1 li a"
override fun chapterListParse(response: Response): List<SChapter> {
val document = response.asJsoup()
val chapters = mutableListOf<SChapter>()
document.select(chapterListSelector()).map { chapters.add(chapterFromElement(it)) }
// Add date for most recent chapter
document.select("div.banner_detail_form div.info span:contains(更新时间)").text()
.substringAfter(":").trim().let { chapters[0].date_upload = parseChapterDate(it) }
return chapters
}
override fun chapterFromElement(element: Element): SChapter {
val chapter = SChapter.create()
chapter.setUrlWithoutDomain(element.attr("href"))
chapter.name = element.ownText()
return chapter
}
companion object {
val dateFormat by lazy {
SimpleDateFormat("yyyy-MM-dd", Locale.CHINA)
}
}
private fun parseChapterDate(string: String): Long {
return dateFormat.parse(string)?.time ?: 0L
}
// Pages
override fun pageListParse(document: Document): List<Page> {
val pages = mutableListOf<Page>()
val script = document.select("script:containsData(imgDomain)").first().data()
val did = script.substringAfter("did=").substringBefore(";")
val sid = script.substringAfter("sid=").substringBefore(";")
val lastPage = script.substringAfter("pcount =").substringBefore(";").trim().toInt()
for (i in 1..lastPage) {
pages.add(Page(i, "$baseUrl/action/play/read?did=$did&sid=$sid&iid=$i", ""))
}
return pages
}
private val gson = Gson()
override fun imageUrlParse(response: Response): String {
return gson.fromJson<JsonObject>(response.body!!.string())["Code"].asString
}
override fun imageUrlParse(document: Document): String = throw UnsupportedOperationException("Not used")
override fun getFilterList() = FilterList()
}
|
apache-2.0
|
3b13bcf254d4e7bc2b6721b32dbf41c6
| 34.428571 | 110 | 0.686034 | 4.612003 | false | false | false | false |
pbauerochse/youtrack-worklog-viewer
|
application/src/main/java/de/pbauerochse/worklogviewer/details/IssueDetailsModel.kt
|
1
|
1259
|
package de.pbauerochse.worklogviewer.details
import de.pbauerochse.worklogviewer.details.events.CloseIssueDetailsRequestEvent
import de.pbauerochse.worklogviewer.details.events.ShowIssueDetailsRequestEvent
import de.pbauerochse.worklogviewer.events.EventBus
import de.pbauerochse.worklogviewer.events.Subscribe
import de.pbauerochse.worklogviewer.timereport.Issue
import javafx.collections.FXCollections
import javafx.collections.ObservableList
import org.slf4j.LoggerFactory
object IssueDetailsModel {
init {
EventBus.subscribe(this)
}
private val LOGGER = LoggerFactory.getLogger(IssueDetailsPane::class.java)
val issuesForDetailsPanel: ObservableList<Issue> = FXCollections.observableArrayList()
@Subscribe
fun onOpenIssueDetailsRequest(event: ShowIssueDetailsRequestEvent) {
if (issuesForDetailsPanel.none { it.id == event.issue.id }) {
LOGGER.debug("Adding ${event.issue} to show in the details pane")
issuesForDetailsPanel.add(event.issue)
}
}
@Subscribe
fun remove(event: CloseIssueDetailsRequestEvent): Boolean {
LOGGER.debug("Removing ${event.issue} from details pane")
return issuesForDetailsPanel.removeIf { it.id == event.issue.id }
}
}
|
mit
|
8f0d81d6d4215e4926cd774ba53bda09
| 35 | 90 | 0.764893 | 4.645756 | false | false | false | false |
inorichi/tachiyomi-extensions
|
src/zh/kuaikanmanhua/src/eu/kanade/tachiyomi/extension/zh/kuaikanmanhua/KuaikanmanhuaUrlActivity.kt
|
1
|
1272
|
package eu.kanade.tachiyomi.extension.zh.kuaikanmanhua
import android.app.Activity
import android.content.ActivityNotFoundException
import android.content.Intent
import android.os.Bundle
import android.util.Log
import kotlin.system.exitProcess
class KuaikanmanhuaUrlActivity : Activity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val host = intent?.data?.host
val pathSegments = intent?.data?.pathSegments
if (pathSegments != null && pathSegments.size > 1) {
val id = when (host) {
"m.kuaikanmanhua.com" -> pathSegments[1]
else -> pathSegments[2]
}
val mainIntent = Intent().apply {
action = "eu.kanade.tachiyomi.SEARCH"
putExtra("query", "${Kuaikanmanhua.TOPIC_ID_SEARCH_PREFIX}$id")
putExtra("filter", packageName)
}
try {
startActivity(mainIntent)
} catch (e: ActivityNotFoundException) {
Log.e("KkmhUrlActivity", e.toString())
}
} else {
Log.e("KkmhUrlActivity", "could not parse uri from intent $intent")
}
finish()
exitProcess(0)
}
}
|
apache-2.0
|
0062499b87c355fae46d954135363ae0
| 32.473684 | 79 | 0.597484 | 4.55914 | false | false | false | false |
Etik-Tak/backend
|
src/main/kotlin/dk/etiktak/backend/service/infochannel/InfoChannelService.kt
|
1
|
6427
|
// Copyright (c) 2017, Daniel Andersen ([email protected])
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
// 3. The name of the author may not be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
package dk.etiktak.backend.service.infochannel
import dk.etiktak.backend.model.acl.AclRole
import dk.etiktak.backend.model.infochannel.InfoChannel
import dk.etiktak.backend.model.infochannel.InfoChannelClient
import dk.etiktak.backend.model.infochannel.InfoChannelFollower
import dk.etiktak.backend.model.user.Client
import dk.etiktak.backend.repository.infochannel.InfoChannelClientRepository
import dk.etiktak.backend.repository.infochannel.InfoChannelFollowerRepository
import dk.etiktak.backend.repository.infochannel.InfoChannelRepository
import dk.etiktak.backend.repository.user.ClientRepository
import dk.etiktak.backend.service.security.ClientValid
import dk.etiktak.backend.service.security.ClientVerified
import dk.etiktak.backend.util.CryptoUtil
import org.slf4j.LoggerFactory
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Service
import org.springframework.transaction.annotation.Transactional
@Service
@Transactional
open class InfoChannelService @Autowired constructor(
private val clientRepository: ClientRepository,
private val infoChannelRepository: InfoChannelRepository,
private val infoChannelClientRepository: InfoChannelClientRepository,
private val infoChannelFollowerRepository: InfoChannelFollowerRepository) {
private val logger = LoggerFactory.getLogger(InfoChannelService::class.java)
/**
* Finds an info channel from the given UUID.
*
* @param uuid UUID
* @return Info channel with given UUID
*/
open fun getInfoChannelByUuid(uuid: String): InfoChannel? {
return infoChannelRepository.findByUuid(uuid)
}
/**
* Creates an info channel with the given client as owner.
*
* @param client Owner
* @param name Name of info channel
* @param modifyValues Function called with modified client
* @return Created info channel
*/
@ClientVerified
open fun createInfoChannel(client: Client, name: String, modifyValues: (Client) -> Unit = {}): InfoChannel {
logger.info("Creating new info channel with name: $name")
// Create info channel
val infoChannel = InfoChannel()
infoChannel.uuid = CryptoUtil().uuid()
infoChannel.name = name
// Create info channel client
val infoChannelClient = InfoChannelClient()
infoChannelClient.uuid = CryptoUtil().uuid()
infoChannelClient.client = client
infoChannelClient.infoChannel = infoChannel
infoChannelClient.roles.add(AclRole.OWNER)
// Glue them together
infoChannel.infoChannelClients.add(infoChannelClient)
client.infoChannelClients.add(infoChannelClient)
// Save them all
var modifiedClient = clientRepository.save(client)
var modifiedInfoChannel = infoChannelRepository.save(infoChannel)
infoChannelClientRepository.save(infoChannelClient)
modifiedClient = clientRepository.findByUuid(modifiedClient.uuid)
// Follow ones own info channel
followInfoChannel(modifiedClient, modifiedInfoChannel,
modifyValues = {client, infoChannel -> modifiedClient = client; modifiedInfoChannel = infoChannel})
modifyValues(modifiedClient)
return modifiedInfoChannel
}
/**
* Marks the client as following the given info channel.
*
* @param client Client
* @param infoChannel Info channel
* @param modifyValues Function called with modified client and info channel
*/
@ClientValid
open fun followInfoChannel(client: Client, infoChannel: InfoChannel, modifyValues: (Client, InfoChannel) -> Unit = {client, infoChannel -> Unit}) {
// Create info channel client
val infoChannelFollower = InfoChannelFollower()
infoChannelFollower.uuid = CryptoUtil().uuid()
infoChannelFollower.client = client
infoChannelFollower.infoChannel = infoChannel
// Glue them together
infoChannel.followers.add(infoChannelFollower)
client.followingInfoChannels.add(infoChannelFollower)
// Save them all
val modifiedClient = clientRepository.save(client)
val modifiedInfoChannel = infoChannelRepository.save(infoChannel)
infoChannelFollowerRepository.save(infoChannelFollower)
modifyValues(modifiedClient, modifiedInfoChannel)
}
/**
* Checks whether the given client is member of the given info channel.
*
* @param client Client
* @param infoChannel Info channel
* @return True, if client is member of info channel, else false
*/
open fun isClientMemberOfInfoChannel(client: Client, infoChannel: InfoChannel): Boolean {
return infoChannel.infoChannelClients.any { it.client.uuid == client.uuid }
}
}
|
bsd-3-clause
|
f766ad94aa739fca296ad41d2298fb82
| 42.721088 | 151 | 0.735958 | 4.928681 | false | false | false | false |
neworld/spanner
|
lib/src/main/java/lt/neworld/spanner/ImageSpanBuilder.kt
|
1
|
805
|
package lt.neworld.spanner
import android.graphics.Bitmap
import android.graphics.drawable.Drawable
import android.text.style.DrawableMarginSpan
import android.text.style.IconMarginSpan
internal class ImageSpanBuilder(private val drawable: Drawable?, private val bitmap: Bitmap?, private val pad: Int?) : SpanBuilder {
override fun build(): Any {
return if (drawable != null && pad != null) {
DrawableMarginSpan(drawable, pad)
} else if (drawable != null) {
DrawableMarginSpan(drawable)
} else if (bitmap != null && pad != null) {
IconMarginSpan(bitmap, pad)
} else if (bitmap != null) {
IconMarginSpan(bitmap)
} else {
throw RuntimeException("drawable or bitmap must be not null")
}
}
}
|
apache-2.0
|
0f93af54ff0cce6da5c95bae08089ddf
| 35.636364 | 132 | 0.648447 | 4.398907 | false | false | false | false |
felipebz/sonar-plsql
|
zpa-core/src/main/kotlin/org/sonar/plsqlopen/squid/PlSqlAstWalker.kt
|
1
|
3788
|
/**
* Z PL/SQL Analyzer
* Copyright (C) 2015-2022 Felipe Zorzo
* mailto:felipe AT felipezorzo DOT com DOT br
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.plsqlopen.squid
import com.felipebz.flr.api.AstNode
import com.felipebz.flr.api.AstNodeType
import com.felipebz.flr.api.Token
import org.sonar.plugins.plsqlopen.api.PlSqlVisitorContext
import org.sonar.plugins.plsqlopen.api.checks.PlSqlVisitor
import org.sonar.plugins.plsqlopen.api.squid.PlSqlCommentAnalyzer
import java.util.*
class PlSqlAstWalker(private val checks: Collection<PlSqlVisitor>) {
private val visitorsByNodeType = IdentityHashMap<AstNodeType, MutableList<PlSqlVisitor>>()
private var lastVisitedToken: Token? = null
fun walk(context: PlSqlVisitorContext) {
for (check in checks) {
check.context = context
check.startScan()
check.init()
for (type in check.subscribedKinds()) {
visitorsByNodeType.getOrPut(type) { mutableListOf() }.add(check)
}
}
val tree = context.rootTree()
if (tree != null) {
try {
for (check in checks) {
check.visitFile(tree)
}
visit(tree)
for (check in checks) {
check.leaveFile(tree)
}
} catch (e: Exception) {
val plsqlFile = context.plSqlFile()
if (plsqlFile != null) {
throw AnalysisException("Error executing checks on file ${plsqlFile.fileName()}: ${e.message}", e)
} else {
throw AnalysisException("Error executing checks: ${e.message}", e)
}
}
}
}
private fun visit(ast: AstNode) {
val nodeVisitors = getNodeVisitors(ast)
visitNode(ast, nodeVisitors)
visitToken(ast)
visitChildren(ast)
leaveNode(ast, nodeVisitors)
}
private fun leaveNode(ast: AstNode, nodeVisitors: List<PlSqlVisitor>) {
for (i in nodeVisitors.indices.reversed()) {
nodeVisitors[i].leaveNode(ast)
}
}
private fun visitChildren(ast: AstNode) {
for (child in ast.children) {
visit(child)
}
}
private fun visitToken(ast: AstNode) {
if (ast.hasToken() && lastVisitedToken !== ast.token) {
lastVisitedToken = ast.token
for (astAndTokenVisitor in checks) {
astAndTokenVisitor.visitToken(ast.token)
for (trivia in ast.token.trivia) {
astAndTokenVisitor.visitComment(trivia,
PlSqlCommentAnalyzer.getContents(trivia.token.originalValue))
}
}
}
}
private fun visitNode(ast: AstNode, nodeVisitors: List<PlSqlVisitor>) {
for (nodeVisitor in nodeVisitors) {
nodeVisitor.visitNode(ast)
}
}
private fun getNodeVisitors(ast: AstNode) =
visitorsByNodeType[ast.type] ?: emptyList()
}
|
lgpl-3.0
|
0f486e74dd17010b0d56f35e345fc78f
| 33.436364 | 118 | 0.617212 | 4.384259 | false | false | false | false |
jeffgbutler/mybatis-dynamic-sql
|
src/test/kotlin/examples/kotlin/mybatis3/canonical/PersonWithAddressMapperExtensions.kt
|
1
|
2685
|
/*
* Copyright 2016-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package examples.kotlin.mybatis3.canonical
import examples.kotlin.mybatis3.canonical.AddressDynamicSqlSupport.address
import examples.kotlin.mybatis3.canonical.PersonDynamicSqlSupport.person
import examples.kotlin.mybatis3.canonical.PersonDynamicSqlSupport.birthDate
import examples.kotlin.mybatis3.canonical.PersonDynamicSqlSupport.employed
import examples.kotlin.mybatis3.canonical.PersonDynamicSqlSupport.firstName
import examples.kotlin.mybatis3.canonical.PersonDynamicSqlSupport.id
import examples.kotlin.mybatis3.canonical.PersonDynamicSqlSupport.lastName
import examples.kotlin.mybatis3.canonical.PersonDynamicSqlSupport.occupation
import org.mybatis.dynamic.sql.util.kotlin.SelectCompleter
import org.mybatis.dynamic.sql.util.kotlin.elements.`as`
import org.mybatis.dynamic.sql.util.kotlin.mybatis3.select
import org.mybatis.dynamic.sql.util.kotlin.mybatis3.selectDistinct
private val columnList = listOf(id `as` "A_ID", firstName, lastName, birthDate,
employed, occupation, address.id, address.streetAddress, address.city, address.state, address.addressType
)
fun PersonWithAddressMapper.selectOne(completer: SelectCompleter): PersonWithAddress? =
select(columnList) {
from(person)
fullJoin(address) {
on(person.addressId) equalTo address.id
}
completer()
}.run(this::selectOne)
fun PersonWithAddressMapper.select(completer: SelectCompleter): List<PersonWithAddress> =
select(columnList) {
from(person, "p")
fullJoin(address) {
on(person.addressId) equalTo address.id
}
completer()
}.run(this::selectMany)
fun PersonWithAddressMapper.selectDistinct(completer: SelectCompleter): List<PersonWithAddress> =
selectDistinct(columnList) {
from(person)
fullJoin(address) {
on(person.addressId) equalTo address.id
}
completer()
}.run(this::selectMany)
fun PersonWithAddressMapper.selectByPrimaryKey(id_: Int) =
selectOne {
where { id isEqualTo id_ }
}
|
apache-2.0
|
dd6074747c0372cb19be2635c0df22a9
| 40.307692 | 109 | 0.749348 | 4.337641 | false | false | false | false |
jiaminglu/kotlin-native
|
backend.native/tests/external/codegen/box/reflection/properties/getDelegate/notDelegatedProperty.kt
|
2
|
911
|
// IGNORE_BACKEND: JS, NATIVE
// WITH_REFLECT
import kotlin.reflect.KProperty2
import kotlin.reflect.jvm.isAccessible
import kotlin.test.*
val topLevel: Boolean = true
val String.extension: Boolean get() = true
class Foo {
val member: Boolean = true
val String.memberExtension: Boolean get() = true
}
fun box(): String {
assertNull(::topLevel.apply { isAccessible = true }.getDelegate())
assertNull(String::extension.apply { isAccessible = true }.getDelegate(""))
assertNull(""::extension.apply { isAccessible = true }.getDelegate())
assertNull(Foo::member.apply { isAccessible = true }.getDelegate(Foo()))
assertNull(Foo()::member.apply { isAccessible = true }.getDelegate())
val me = Foo::class.members.single { it.name == "memberExtension" } as KProperty2<Foo, String, Boolean>
assertNull(me.apply { isAccessible = true }.getDelegate(Foo(), ""))
return "OK"
}
|
apache-2.0
|
bf1527e7a1edb1aece4696eabb017661
| 30.413793 | 107 | 0.698134 | 4.178899 | false | false | false | false |
NerdNumber9/TachiyomiEH
|
app/src/main/java/exh/metadata/metadata/base/FlatMetadata.kt
|
1
|
3557
|
package exh.metadata.metadata.base
import com.pushtorefresh.storio.operations.PreparedOperation
import eu.kanade.tachiyomi.data.database.DatabaseHelper
import exh.metadata.sql.models.SearchMetadata
import exh.metadata.sql.models.SearchTag
import exh.metadata.sql.models.SearchTitle
import rx.Completable
import rx.Single
import kotlin.reflect.KClass
data class FlatMetadata(
val metadata: SearchMetadata,
val tags: List<SearchTag>,
val titles: List<SearchTitle>
) {
inline fun <reified T : RaisedSearchMetadata> raise(): T = raise(T::class)
fun <T : RaisedSearchMetadata> raise(clazz: KClass<T>)
= RaisedSearchMetadata.raiseFlattenGson
.fromJson(metadata.extra, clazz.java).apply {
fillBaseFields(this@FlatMetadata)
}
}
fun DatabaseHelper.getFlatMetadataForManga(mangaId: Long): PreparedOperation<FlatMetadata?> {
// We have to use fromCallable because StorIO messes up the thread scheduling if we use their rx functions
val single = Single.fromCallable {
val meta = getSearchMetadataForManga(mangaId).executeAsBlocking()
if(meta != null) {
val tags = getSearchTagsForManga(mangaId).executeAsBlocking()
val titles = getSearchTitlesForManga(mangaId).executeAsBlocking()
FlatMetadata(meta, tags, titles)
} else null
}
return preparedOperationFromSingle(single)
}
private fun <T> preparedOperationFromSingle(single: Single<T>): PreparedOperation<T> {
return object : PreparedOperation<T> {
/**
* Creates [rx.Observable] that emits result of Operation.
*
*
* Observable may be "Hot" or "Cold", please read documentation of the concrete implementation.
*
* @return observable result of operation with only one [rx.Observer.onNext] call.
*/
override fun createObservable() = single.toObservable()
/**
* Executes operation synchronously in current thread.
*
*
* Notice: Blocking I/O operation should not be executed on the Main Thread,
* it can cause ANR (Activity Not Responding dialog), block the UI and drop animations frames.
* So please, execute blocking I/O operation only from background thread.
* See [WorkerThread].
*
* @return nullable result of operation.
*/
override fun executeAsBlocking() = single.toBlocking().value()
/**
* Creates [rx.Observable] that emits result of Operation.
*
*
* Observable may be "Hot" (usually "Warm") or "Cold", please read documentation of the concrete implementation.
*
* @return observable result of operation with only one [rx.Observer.onNext] call.
*/
override fun asRxObservable() = single.toObservable()
/**
* Creates [rx.Single] that emits result of Operation lazily when somebody subscribes to it.
*
*
*
* @return single result of operation.
*/
override fun asRxSingle() = single
}
}
fun DatabaseHelper.insertFlatMetadata(flatMetadata: FlatMetadata) = Completable.fromCallable {
require(flatMetadata.metadata.mangaId != -1L)
inTransaction {
insertSearchMetadata(flatMetadata.metadata).executeAsBlocking()
setSearchTagsForManga(flatMetadata.metadata.mangaId, flatMetadata.tags)
setSearchTitlesForManga(flatMetadata.metadata.mangaId, flatMetadata.titles)
}
}
|
apache-2.0
|
c0537b4446b078845c0211ad3590b323
| 36.452632 | 120 | 0.667135 | 4.755348 | false | false | false | false |
NerdNumber9/TachiyomiEH
|
app/src/main/java/exh/ui/migration/manga/process/MigrationProcedureAdapter.kt
|
1
|
11072
|
package exh.ui.migration.manga.process
import android.support.v4.view.PagerAdapter
import android.view.View
import android.view.ViewGroup
import com.bumptech.glide.load.engine.DiskCacheStrategy
import com.elvishew.xlog.XLog
import com.google.gson.Gson
import eu.kanade.tachiyomi.R
import eu.kanade.tachiyomi.data.database.DatabaseHelper
import eu.kanade.tachiyomi.data.database.models.Manga
import eu.kanade.tachiyomi.data.database.models.MangaCategory
import eu.kanade.tachiyomi.data.glide.GlideApp
import eu.kanade.tachiyomi.source.Source
import eu.kanade.tachiyomi.source.SourceManager
import eu.kanade.tachiyomi.source.model.SManga
import eu.kanade.tachiyomi.source.online.all.MergedSource
import eu.kanade.tachiyomi.ui.base.controller.withFadeTransaction
import eu.kanade.tachiyomi.ui.manga.MangaController
import eu.kanade.tachiyomi.ui.migration.MigrationFlags
import eu.kanade.tachiyomi.util.*
import exh.MERGED_SOURCE_ID
import exh.util.await
import kotlinx.android.synthetic.main.eh_manga_card.view.*
import kotlinx.android.synthetic.main.eh_migration_process_item.view.*
import kotlinx.coroutines.*
import kotlinx.coroutines.flow.asFlow
import kotlinx.coroutines.flow.collect
import uy.kohesive.injekt.injectLazy
import java.text.DateFormat
import java.text.DecimalFormat
import java.util.*
import kotlin.coroutines.CoroutineContext
class MigrationProcedureAdapter(val controller: MigrationProcedureController,
val migratingManga: List<MigratingManga>,
override val coroutineContext: CoroutineContext) : PagerAdapter(), CoroutineScope {
private val db: DatabaseHelper by injectLazy()
private val gson: Gson by injectLazy()
private val sourceManager: SourceManager by injectLazy()
private val logger = XLog.tag(this::class.simpleName)
override fun isViewFromObject(p0: View, p1: Any): Boolean {
return p0 == p1
}
override fun getCount() = migratingManga.size
override fun instantiateItem(container: ViewGroup, position: Int): Any {
val item = migratingManga[position]
val view = container.inflate(R.layout.eh_migration_process_item)
container.addView(view)
view.skip_migration.setOnClickListener {
controller.nextMigration()
}
val viewTag = ViewTag(coroutineContext)
view.tag = viewTag
view.setupView(viewTag, item)
view.accept_migration.setOnClickListener {
viewTag.launch(Dispatchers.Main) {
view.migrating_frame.visible()
try {
withContext(Dispatchers.Default) {
performMigration(item)
}
controller.nextMigration()
} catch(e: Exception) {
logger.e("Migration failure!", e)
controller.migrationFailure()
}
view.migrating_frame.gone()
}
}
return view
}
suspend fun performMigration(manga: MigratingManga) {
if(!manga.searchResult.initialized) {
return
}
val toMangaObj = db.getManga(manga.searchResult.get() ?: return).await() ?: return
withContext(Dispatchers.IO) {
migrateMangaInternal(
manga.manga() ?: return@withContext,
toMangaObj,
!controller.config.copy
)
}
}
private fun migrateMangaInternal(prevManga: Manga,
manga: Manga,
replace: Boolean) {
db.inTransaction {
// Update chapters read
if (MigrationFlags.hasChapters(controller.config.migrationFlags)) {
val prevMangaChapters = db.getChapters(prevManga).executeAsBlocking()
val maxChapterRead = prevMangaChapters.filter { it.read }
.maxBy { it.chapter_number }?.chapter_number
if (maxChapterRead != null) {
val dbChapters = db.getChapters(manga).executeAsBlocking()
for (chapter in dbChapters) {
if (chapter.isRecognizedNumber && chapter.chapter_number <= maxChapterRead) {
chapter.read = true
}
}
db.insertChapters(dbChapters).executeAsBlocking()
}
}
// Update categories
if (MigrationFlags.hasCategories(controller.config.migrationFlags)) {
val categories = db.getCategoriesForManga(prevManga).executeAsBlocking()
val mangaCategories = categories.map { MangaCategory.create(manga, it) }
db.setMangaCategories(mangaCategories, listOf(manga))
}
// Update track
if (MigrationFlags.hasTracks(controller.config.migrationFlags)) {
val tracks = db.getTracks(prevManga).executeAsBlocking()
for (track in tracks) {
track.id = null
track.manga_id = manga.id!!
}
db.insertTracks(tracks).executeAsBlocking()
}
// Update favorite status
if (replace) {
prevManga.favorite = false
db.updateMangaFavorite(prevManga).executeAsBlocking()
}
manga.favorite = true
db.updateMangaFavorite(manga).executeAsBlocking()
// SearchPresenter#networkToLocalManga may have updated the manga title, so ensure db gets updated title
db.updateMangaTitle(manga).executeAsBlocking()
}
}
fun View.setupView(tag: ViewTag, migratingManga: MigratingManga) {
tag.launch {
val manga = migratingManga.manga()
val source = migratingManga.mangaSource()
if(manga != null) {
withContext(Dispatchers.Main) {
eh_manga_card_from.loading_group.gone()
eh_manga_card_from.attachManga(tag, manga, source)
eh_manga_card_from.setOnClickListener {
controller.router.pushController(MangaController(manga, true).withFadeTransaction())
}
}
tag.launch {
migratingManga.progress.asFlow().collect { (max, progress) ->
withContext(Dispatchers.Main) {
eh_manga_card_to.search_progress.let { progressBar ->
progressBar.max = max
progressBar.progress = progress
}
}
}
}
val searchResult = migratingManga.searchResult.get()?.let {
db.getManga(it).await()
}
val resultSource = searchResult?.source?.let {
sourceManager.get(it)
}
withContext(Dispatchers.Main) {
if(searchResult != null && resultSource != null) {
eh_manga_card_to.loading_group.gone()
eh_manga_card_to.attachManga(tag, searchResult, resultSource)
eh_manga_card_to.setOnClickListener {
controller.router.pushController(MangaController(searchResult, true).withFadeTransaction())
}
accept_migration.isEnabled = true
accept_migration.alpha = 1.0f
} else {
eh_manga_card_to.search_progress.gone()
eh_manga_card_to.search_status.text = "Found no manga"
}
}
}
}
}
suspend fun View.attachManga(tag: ViewTag, manga: Manga, source: Source) {
// TODO Duplicated in MangaInfoController
GlideApp.with(context)
.load(manga)
.diskCacheStrategy(DiskCacheStrategy.RESOURCE)
.centerCrop()
.into(manga_cover)
manga_full_title.text = if (manga.title.isBlank()) {
context.getString(R.string.unknown)
} else {
manga.title
}
manga_artist.text = if (manga.artist.isNullOrBlank()) {
context.getString(R.string.unknown)
} else {
manga.artist
}
manga_author.text = if (manga.author.isNullOrBlank()) {
context.getString(R.string.unknown)
} else {
manga.author
}
manga_source.text = if (source.id == MERGED_SOURCE_ID) {
MergedSource.MangaConfig.readFromUrl(gson, manga.url).children.map {
sourceManager.getOrStub(it.source).toString()
}.distinct().joinToString()
} else {
source.toString()
}
if (source.id == MERGED_SOURCE_ID) {
manga_source_label.text = "Sources"
} else {
manga_source_label.setText(R.string.manga_info_source_label)
}
manga_status.setText(when (manga.status) {
SManga.ONGOING -> R.string.ongoing
SManga.COMPLETED -> R.string.completed
SManga.LICENSED -> R.string.licensed
else -> R.string.unknown
})
val mangaChapters = db.getChapters(manga).await()
manga_chapters.text = mangaChapters.size.toString()
val latestChapter = mangaChapters.maxBy { it.chapter_number }?.chapter_number ?: -1f
val lastUpdate = Date(mangaChapters.maxBy { it.date_upload }?.date_upload ?: 0)
if (latestChapter > 0f) {
manga_last_chapter.text = DecimalFormat("#.#").format(latestChapter)
} else {
manga_last_chapter.setText(R.string.unknown)
}
if (lastUpdate.time != 0L) {
manga_last_update.text = DateFormat.getDateInstance(DateFormat.SHORT).format(lastUpdate)
} else {
manga_last_update.setText(R.string.unknown)
}
}
override fun destroyItem(container: ViewGroup, position: Int, `object`: Any) {
val objectAsView = `object` as View
container.removeView(objectAsView)
(objectAsView.tag as? ViewTag)?.destroy()
}
class ViewTag(parent: CoroutineContext): CoroutineScope {
/**
* The context of this scope.
* Context is encapsulated by the scope and used for implementation of coroutine builders that are extensions on the scope.
* Accessing this property in general code is not recommended for any purposes except accessing the [Job] instance for advanced usages.
*
* By convention, should contain an instance of a [job][Job] to enforce structured concurrency.
*/
override val coroutineContext = parent + Job() + Dispatchers.Default
fun destroy() {
cancel()
}
}
}
|
apache-2.0
|
0f5cdc6e57ae0aa3d28874d1f6e7ea74
| 38.688172 | 143 | 0.583544 | 4.920889 | false | false | false | false |
savvasdalkitsis/gameframe
|
account/src/main/java/com/savvasdalkitsis/gameframe/feature/account/view/AccountActivity.kt
|
1
|
4686
|
/**
* Copyright 2017 Savvas Dalkitsis
* 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.
*
* 'Game Frame' is a registered trademark of LEDSEQ
*/
package com.savvasdalkitsis.gameframe.feature.account.view
import android.content.Intent
import android.os.Bundle
import android.text.method.LinkMovementMethod
import android.view.Menu
import android.view.View
import com.afollestad.materialdialogs.MaterialDialog
import com.savvasdalkitsis.gameframe.feature.account.R
import com.savvasdalkitsis.gameframe.feature.account.injector.AccountInjector
import com.savvasdalkitsis.gameframe.feature.account.presenter.AccountPresenter
import com.savvasdalkitsis.gameframe.feature.authentication.model.SignedInAccount
import com.savvasdalkitsis.gameframe.feature.message.injector.MessageDisplayInjector
import com.savvasdalkitsis.gameframe.infra.android.BaseActivity
import com.savvasdalkitsis.gameframe.kotlin.Action
import com.savvasdalkitsis.gameframe.kotlin.gone
import com.savvasdalkitsis.gameframe.kotlin.visible
import kotlinx.android.synthetic.main.activity_account.*
import kotlinx.android.synthetic.main.activity_account_logged_in.*
import kotlinx.android.synthetic.main.activity_account_logged_out.*
class AccountActivity : BaseActivity<AccountView, AccountPresenter<Intent>>(), AccountView {
override val layoutId = R.layout.activity_account
override val presenter: AccountPresenter<Intent> = AccountInjector.accountPresenter()
override val view = this
private val messageDisplay = MessageDisplayInjector.messageDisplay()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
supportActionBar?.setDisplayHomeAsUpEnabled(true)
view_account_log_in.setOnClickListener { presenter.logIn() }
view_account_log_out.setOnClickListener { presenter.logOut() }
view_account_re_upload.setOnClickListener { presenter.reUpload() }
view_account_delete_account.setOnClickListener { presenter.deleteAccount() }
listOf(view_account_privacy_policy_logged_in, view_account_privacy_policy_logged_out).forEach {
it.movementMethod = LinkMovementMethod.getInstance()
}
}
public override fun onStart() {
super.onStart()
presenter.start()
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
menuInflater.inflate(R.menu.menu_account, menu)
return true
}
override fun displayLoading() {
switchTo(view_account_progress)
}
@Suppress("DEPRECATION")
override fun displaySignedInAccount(account: SignedInAccount) {
view_account_name.text = getString(R.string.hello_name, account.name)
account.image?.let {
view_account_image.setImageURI(it)
}
switchTo(view_account_logged_in)
}
override fun displaySignedOut() {
switchTo(view_account_logged_out)
}
override fun displayErrorLoadingAccount() {
messageDisplay.show(R.string.sign_in_error)
}
override fun askUserToVerifyAccountDeletion(onVerified: () -> Unit) {
MaterialDialog.Builder(this)
.title(R.string.delete_account)
.content(R.string.delete_account_verification)
.positiveText(R.string.delete)
.negativeText(R.string.cancel)
.onPositive { _, _ -> onVerified() }
.show()
}
override fun askUserToUploadSavedProjects(onUpload: Action) {
MaterialDialog.Builder(this)
.title(R.string.upload_saved_projects)
.content(R.string.upload_saved_projects_description)
.positiveText(R.string.upload)
.negativeText(R.string.skip)
.onPositive { _, _ -> onUpload() }
.show()
}
private fun switchTo(view: View) {
listOf(view_account_logged_in, view_account_logged_out, view_account_progress).forEach {
it.gone()
}
view.visible()
}
public override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
presenter.handleResultForLoginRequest(requestCode, resultCode, data)
}
}
|
apache-2.0
|
e2bb60c3a4b13e851e4e441c8aa73cba
| 38.386555 | 103 | 0.713402 | 4.531915 | false | false | false | false |
zlyne0/colonization
|
core/src/promitech/colonization/screen/ui/ReadonlyCargoSummaryPanel.kt
|
1
|
2437
|
package promitech.colonization.screen.ui
import com.badlogic.gdx.graphics.g2d.Batch
import com.badlogic.gdx.scenes.scene2d.ui.Widget
import com.badlogic.gdx.utils.Array
import com.badlogic.gdx.utils.FloatArray
import net.sf.freecol.common.model.Unit
import net.sf.freecol.common.model.specification.AbstractGoods
import promitech.colonization.GameResources
import promitech.colonization.gdx.Frame
internal class ReadonlyCargoSummaryPanel(
private val unit: Unit,
private val gameResources: GameResources
) : Widget() {
private val imagesXPos: FloatArray
private val images: Array<Frame>
private val width: Float
init {
var imgCount = 0
var goodsList: List<AbstractGoods> = emptyList()
if (unit.goodsContainer != null) {
goodsList = unit.goodsContainer.slotedGoods()
imgCount += goodsList.size
}
if (unit.unitContainer != null) {
imgCount += unit.unitContainer.units.size()
}
imagesXPos = FloatArray(imgCount)
images = Array<Frame>(imgCount)
var x = 0f
var imgWidth = 0
for (goods in goodsList) {
val goodsImage = gameResources.goodsImage(goods.typeId)
imgWidth = goodsImage.texture.regionWidth
images.add(goodsImage)
imagesXPos.add(x)
x += goodsImage.texture.regionWidth / 2
}
x += imgWidth / 2
if (unit.unitContainer != null) {
for (unit in unit.unitContainer.units) {
val unitImage = gameResources.getFrame(unit.resourceImageKey())
imgWidth = unitImage.texture.regionWidth
images.add(unitImage)
imagesXPos.add(x)
x += unitImage.texture.regionWidth / 2
}
}
width = (x + imgWidth / 2).toFloat()
}
override fun draw(batch: Batch, parentAlpha: Float) {
for (index in 0 .. imagesXPos.size-1) {
val image = images.get(index)
batch.draw(image.texture, getX() + imagesXPos.get(index), getY() - image.texture.regionHeight / 2)
}
}
override fun getWidth(): Float {
return prefWidth
}
override fun getHeight(): Float {
return prefHeight
}
override fun getPrefHeight(): Float {
return super.getPrefHeight()
}
override fun getPrefWidth(): Float {
return width
}
}
|
gpl-2.0
|
03810055cc107e666232fe15d91c11ff
| 27.682353 | 110 | 0.620435 | 4.201724 | false | false | false | false |
kronenpj/iqtimesheet
|
IQTimeSheet/src/main/com/github/kronenpj/iqtimesheet/IQTimeSheet/ChangeEntryHandler.kt
|
1
|
11939
|
/*
* Copyright 2010 TimeSheet authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.kronenpj.iqtimesheet.IQTimeSheet
import android.app.Activity
import android.app.AlertDialog
import android.app.Dialog
import android.content.Intent
import android.database.Cursor
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.util.Log
import android.view.View
import android.view.View.OnClickListener
import android.widget.Button
import android.widget.Toast
import com.github.kronenpj.iqtimesheet.TimeHelpers
import kotlinx.android.synthetic.main.changeentry.*
/**
* Activity to provide an interface to change an entry.
* @author Paul Kronenwetter <[email protected]>
*/
class ChangeEntryHandler : AppCompatActivity() {
private var entryCursor: Cursor? = null
private var child: Array<Button>? = null
private var db: TimeSheetDbAdapter? = null
private var entryID: Long = -1
private var newTask: String? = null
private var newTimeIn: Long = -1
private var newTimeOut: Long = -1
private var newDate: Long = -1
private var alignMinutes = 0
private var alignMinutesAuto = false
/**
* Called when the activity is first created.
*/
public override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
try {
showChangeLayout()
} catch (e: RuntimeException) {
Log.e(TAG, "$e calling showChangeLayout")
}
alignMinutes = TimeSheetActivity.prefs!!.alignMinutes
alignMinutesAuto = TimeSheetActivity.prefs!!.alignMinutesAuto
changealign.text = "Align ($alignMinutes min)"
if (alignMinutesAuto) changealign.visibility = View.INVISIBLE
db = TimeSheetDbAdapter(this)
retrieveData()
fillData()
}
/**
* Called when the activity destroyed.
*/
public override fun onDestroy() {
entryCursor!!.close()
super.onDestroy()
}
/**
* Called when the activity is first created to create a dialog.
*/
override fun onCreateDialog(dialogId: Int): Dialog {
val dialog: Dialog
val builder = AlertDialog.Builder(this)
builder.setMessage("Are you sure you want to delete this entry?")
.setCancelable(true)
.setPositiveButton("Yes")
{ dialog, id ->
val intent = Intent()
intent.putExtra(EditDayEntriesHandler.ENTRY_ID, entryID)
intent.action = "delete"
setResult(Activity.RESULT_OK, intent)
[email protected]()
}
.setNegativeButton("No") { dialog, id -> dialog.cancel() }
dialog = builder.create()
return dialog
}
internal fun showChangeLayout() {
setContentView(R.layout.changeentry)
// NOTE: The order of these is important, the array is referenced
// by index a few times below.
child = arrayOf(defaulttask, date, starttime, endtime, changeok,
changecancel, changedelete, changealign, changeadjacent)
for (aChild in child!!) {
try {
aChild.setOnClickListener(mButtonListener)
} catch (e: NullPointerException) {
Toast.makeText(this@ChangeEntryHandler, "NullPointerException",
Toast.LENGTH_SHORT).show()
}
}
}
private fun retrieveData() {
val extras = intent.extras
if (extras == null) {
Log.d(TAG, "Extras bundle is empty.")
return
}
entryID = extras.getLong(EditDayEntriesHandler.ENTRY_ID)
entryCursor = db!!.fetchEntry(entryID)
val chargeNo = entryCursor!!.getLong(entryCursor!!.getColumnIndex("chargeno"))
newTask = db!!.getTaskNameByID(chargeNo)
newTimeIn = entryCursor!!.getLong(entryCursor!!.getColumnIndex("timein"))
newTimeOut = entryCursor!!.getLong(entryCursor!!.getColumnIndex("timeout"))
newDate = TimeHelpers.millisToStartOfDay(newTimeIn)
}
private fun fillData() {
var hour: Int
var minute: Int
child!![0].text = newTask
child!![1].text = TimeHelpers.millisToDate(newDate)
if (alignMinutesAuto) {
newTimeIn = TimeHelpers.millisToAlignMinutes(newTimeIn, alignMinutes)
}
hour = TimeHelpers.millisToHour(newTimeIn)
minute = TimeHelpers.millisToMinute(newTimeIn)
child!![2].text = "${TimeHelpers.formatHours(hour)}:${TimeHelpers.formatMinutes(minute)}"
if (newTimeOut == 0L) {
child!![3].text = "Now"
} else {
if (alignMinutesAuto) {
newTimeOut = TimeHelpers.millisToAlignMinutes(newTimeOut, alignMinutes)
}
hour = TimeHelpers.millisToHour(newTimeOut)
minute = TimeHelpers.millisToMinute(newTimeOut)
child!![3].text = "${TimeHelpers.formatHours(hour)}:${TimeHelpers.formatMinutes(minute)}"
}
}
/**
* This method is what is registered with the button to cause an action to
* occur when it is pressed.
*/
private val mButtonListener = OnClickListener { v ->
val intent: Intent
// Perform action on selected list item.
Log.d(TAG, "onClickListener view id: ${v.id}")
Log.d(TAG, "onClickListener defaulttask id: ${R.id.defaulttask}")
when (v.id) {
R.id.changecancel -> {
setResult(Activity.RESULT_CANCELED, Intent().setAction("cancel"))
finish()
}
R.id.defaulttask -> {
intent = Intent(this@ChangeEntryHandler, ChangeTaskList::class.java)
try {
startActivityForResult(intent, TASKCHOOSE_CODE)
} catch (e: RuntimeException) {
Log.e(TAG, "startActivity ChangeTaskList: $e")
}
}
R.id.date -> {
intent = Intent(this@ChangeEntryHandler, ChangeDate::class.java)
intent.putExtra("time", newDate)
try {
startActivityForResult(intent, CHANGEDATE_CODE)
} catch (e: RuntimeException) {
Log.e(TAG, "startActivity ChangeDate: $e")
}
}
R.id.starttime -> {
intent = Intent(this@ChangeEntryHandler, ChangeTime::class.java)
intent.putExtra("time", newTimeIn)
try {
startActivityForResult(intent, CHANGETIMEIN_CODE)
} catch (e: RuntimeException) {
Log.e(TAG, "startActivity ChangeTime: $e")
}
}
R.id.endtime -> {
intent = Intent(this@ChangeEntryHandler, ChangeTime::class.java)
intent.putExtra("time", newTimeOut)
try {
startActivityForResult(intent, CHANGETIMEOUT_CODE)
} catch (e: RuntimeException) {
Log.e(TAG, "startActivity ChangeTime: $e")
}
}
R.id.changealign -> {
newTimeIn = TimeHelpers.millisToAlignMinutes(newTimeIn, alignMinutes)
if (newTimeOut != 0L)
newTimeOut = TimeHelpers.millisToAlignMinutes(newTimeOut, alignMinutes)
fillData()
}
R.id.changeok -> {
intent = Intent()
intent.putExtra(EditDayEntriesHandler.ENTRY_ID, entryID)
// Push task title into response.
intent.putExtra("task", newTask)
// Push start and end time milliseconds into response bundle.
intent.putExtra("timein", newTimeIn)
intent.putExtra("timeout", newTimeOut)
intent.action = "accept"
setResult(Activity.RESULT_OK, intent)
finish()
}
R.id.changeadjacent -> {
intent = Intent()
intent.putExtra(EditDayEntriesHandler.ENTRY_ID, entryID)
// Push task title into response.
intent.putExtra("task", newTask)
// Push start and end time milliseconds into response bundle.
intent.putExtra("timein", newTimeIn)
intent.putExtra("timeout", newTimeOut)
intent.action = "acceptadjacent"
setResult(Activity.RESULT_OK, intent)
finish()
}
R.id.changedelete -> showDialog(CONFIRM_DELETE_DIALOG)
}
}
/**
* This method is called when the sending activity has finished, with the
* result it supplied.
* @param requestCode The original request code as given to startActivity().
* *
* @param resultCode From sending activity as per setResult().
* *
* @param data From sending activity as per setResult().
*/
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
// Check to see that what we received is what we wanted to see.
when (requestCode) {
TASKCHOOSE_CODE -> if (resultCode == Activity.RESULT_OK) {
if (data != null) {
Log.d(TAG, "onActivityResult action: " + data.action)
// db.updateEntry(entryID, Long.parseLong(data.getAction()),
// null, -1, -1);
newTask = db!!.getTaskNameByID(java.lang.Long.valueOf(data.action))
fillData()
}
}
CHANGETIMEIN_CODE -> if (resultCode == Activity.RESULT_OK) {
if (data != null) {
newTimeIn = java.lang.Long.valueOf(data.action)
Log.d(TAG, "onActivityResult action: $newTimeIn")
fillData()
}
}
CHANGETIMEOUT_CODE -> if (resultCode == Activity.RESULT_OK) {
if (data != null) {
newTimeOut = java.lang.Long.valueOf(data.action)
Log.d(TAG, "onActivityResult action: $newTimeOut")
fillData()
}
}
CHANGEDATE_CODE -> if (resultCode == Activity.RESULT_OK) {
if (data != null) {
Log.d(TAG, "onActivityResult action: " + data.action)
newDate = java.lang.Long.valueOf(data.action)
newTimeIn = TimeHelpers.millisSetTime(newDate,
TimeHelpers.millisToHour(newTimeIn),
TimeHelpers.millisToMinute(newTimeIn))
newTimeOut = TimeHelpers.millisSetTime(newDate,
TimeHelpers.millisToHour(newTimeOut),
TimeHelpers.millisToMinute(newTimeOut))
fillData()
}
}
}
}
companion object {
private const val TAG = "ChangeEntryHandler"
private const val TASKCHOOSE_CODE = 0x01
private const val CHANGETIMEIN_CODE = 0x02
private const val CHANGETIMEOUT_CODE = 0x03
private const val CHANGEDATE_CODE = 0x04
private const val CONFIRM_DELETE_DIALOG = 0x10
}
}
|
apache-2.0
|
8070985dc3d7385c4bca6f6a1ecccb48
| 37.266026 | 101 | 0.576598 | 4.728317 | false | false | false | false |
Maccimo/intellij-community
|
plugins/package-search/src/com/jetbrains/packagesearch/intellij/plugin/ui/toolwindow/models/ProjectDataProvider.kt
|
3
|
5997
|
/*******************************************************************************
* Copyright 2000-2022 JetBrains s.r.o. and contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
package com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models
import com.jetbrains.packagesearch.intellij.plugin.api.PackageSearchApiClient
import com.jetbrains.packagesearch.intellij.plugin.util.CoroutineLRUCache
import com.jetbrains.packagesearch.intellij.plugin.util.TraceInfo
import com.jetbrains.packagesearch.intellij.plugin.util.logDebug
import com.jetbrains.packagesearch.intellij.plugin.util.logInfo
import com.jetbrains.packagesearch.intellij.plugin.util.logTrace
import kotlinx.coroutines.flow.asFlow
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.toList
import org.jetbrains.packagesearch.api.v2.ApiPackagesResponse
import org.jetbrains.packagesearch.api.v2.ApiRepository
import org.jetbrains.packagesearch.api.v2.ApiStandardPackage
internal class ProjectDataProvider(
private val apiClient: PackageSearchApiClient,
private val packageCache: CoroutineLRUCache<InstalledDependency, ApiStandardPackage>
) {
suspend fun fetchKnownRepositories(): List<ApiRepository> = apiClient.repositories().repositories
suspend fun doSearch(
searchQuery: String,
filterOptions: FilterOptions
): ApiPackagesResponse<ApiStandardPackage, ApiStandardPackage.ApiStandardVersion> {
val repositoryIds = filterOptions.onlyRepositoryIds
return apiClient.packagesByQuery(
searchQuery = searchQuery,
onlyStable = filterOptions.onlyStable,
onlyMpp = filterOptions.onlyKotlinMultiplatform,
repositoryIds = repositoryIds.toList()
)
}
suspend fun fetchInfoFor(installedDependencies: List<InstalledDependency>, traceInfo: TraceInfo): Map<InstalledDependency, ApiStandardPackage> {
if (installedDependencies.isEmpty()) {
return emptyMap()
}
val apiInfoByDependency = fetchInfoFromCacheOrApiFor(installedDependencies, traceInfo)
val (emptyApiInfoByDependency, successfulApiInfoByDependency) =
apiInfoByDependency.partition { (_, v) -> v == null }
if (emptyApiInfoByDependency.isNotEmpty() && emptyApiInfoByDependency.size != installedDependencies.size) {
val failedDependencies = emptyApiInfoByDependency.keys
logInfo(traceInfo, "ProjectDataProvider#fetchInfoFor()") {
"Failed obtaining data for ${failedDependencies.size} dependencies"
}
}
return successfulApiInfoByDependency.filterNotNullValues()
}
private suspend fun fetchInfoFromCacheOrApiFor(
dependencies: List<InstalledDependency>,
traceInfo: TraceInfo
): Map<InstalledDependency, ApiStandardPackage?> {
logDebug(traceInfo, "ProjectDataProvider#fetchInfoFromCacheOrApiFor()") {
"Fetching data for ${dependencies.count()} dependencies..."
}
val remoteInfoByDependencyMap = mutableMapOf<InstalledDependency, ApiStandardPackage?>()
val packagesToFetch = mutableListOf<InstalledDependency>()
for (dependency in dependencies) {
val standardV2Package = packageCache.get(dependency)
remoteInfoByDependencyMap[dependency] = standardV2Package
if (standardV2Package == null) {
packagesToFetch += dependency
}
}
if (packagesToFetch.isEmpty()) {
logTrace(traceInfo, "ProjectDataProvider#fetchInfoFromCacheOrApiFor()") {
"Found all ${dependencies.count() - packagesToFetch.count()} packages in cache"
}
return remoteInfoByDependencyMap
}
logTrace(traceInfo, "ProjectDataProvider#fetchInfoFromCacheOrApiFor()") {
"Found ${dependencies.count() - packagesToFetch.count()} packages in cache, still need to fetch ${packagesToFetch.count()} from API"
}
val fetchedPackages = packagesToFetch.asSequence()
.map { dependency -> dependency.coordinatesString }
.chunked(size = 25)
.asFlow()
.map { dependenciesToFetch -> apiClient.packagesByRange(dependenciesToFetch) }
.map { it.packages }
.catch {
logDebug(
"${this::class.run { qualifiedName ?: simpleName ?: this }}#fetchedPackages",
it,
) { "Error while retrieving packages" }
emit(emptyList())
}
.toList()
.flatten()
for (v2Package in fetchedPackages) {
val dependency = InstalledDependency.from(v2Package)
packageCache.put(dependency, v2Package)
remoteInfoByDependencyMap[dependency] = v2Package
}
return remoteInfoByDependencyMap
}
}
private fun <K, V> Map<K, V>.partition(transform: (Map.Entry<K, V>) -> Boolean): Pair<Map<K, V>, Map<K, V>> {
val trueMap = mutableMapOf<K, V>()
val falseMap = mutableMapOf<K, V>()
forEach { if (transform(it)) trueMap[it.key] = it.value else falseMap[it.key] = it.value }
return trueMap to falseMap
}
private fun <K, V> Map<K, V?>.filterNotNullValues() = buildMap<K, V> {
[email protected] { (k, v) -> if (v != null) put(k, v) }
}
|
apache-2.0
|
6936b40266f182104deee6b794ba9e88
| 42.143885 | 148 | 0.67267 | 5.152062 | false | false | false | false |
Yubico/yubioath-desktop
|
android/app/src/main/kotlin/com/yubico/authenticator/oath/Conversion.kt
|
1
|
1848
|
/*
* Copyright (C) 2022 Yubico.
*
* 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.yubico.authenticator.oath
import com.yubico.authenticator.device.Version
import com.yubico.yubikit.oath.Code
import com.yubico.yubikit.oath.Credential
import com.yubico.yubikit.oath.OathSession
import com.yubico.yubikit.oath.OathType
fun ByteArray.asString() = joinToString(
separator = ""
) { b -> "%02x".format(b) }
// convert yubikit types to Model types
fun OathSession.model(isRemembered: Boolean) = Model.Session(
deviceId,
Version(
version.major,
version.minor,
version.micro
),
isAccessKeySet,
isRemembered,
isLocked
)
fun Credential.model(deviceId: String) = Model.Credential(
deviceId = deviceId,
id = id.asString(),
oathType = when (oathType) {
OathType.HOTP -> Model.OathType.HOTP
else -> Model.OathType.TOTP
},
period = period,
issuer = issuer,
accountName = accountName,
touchRequired = isTouchRequired
)
fun Code.model() = Model.Code(
value,
validFrom / 1000,
validUntil / 1000
)
fun Map<Credential, Code?>.model(deviceId: String): Map<Model.Credential, Model.Code?> =
map { (credential, code) ->
Pair(
credential.model(deviceId),
code?.model()
)
}.toMap()
|
apache-2.0
|
d9b9c3b92e9ecd52ab34da26f5b89656
| 26.58209 | 88 | 0.682359 | 3.710843 | false | false | false | false |
Hexworks/zircon
|
zircon.jvm.swing/src/test/kotlin/org/hexworks/zircon/internal/tileset/transformer/Java2DUnderlineTransformerTest.kt
|
1
|
900
|
package org.hexworks.zircon.internal.tileset.transformer
import org.hexworks.zircon.api.Modifiers
import org.hexworks.zircon.api.data.Tile
import org.hexworks.zircon.internal.tileset.impl.DefaultTileTexture
import org.junit.Before
import org.junit.Ignore
import org.junit.Test
import java.awt.image.BufferedImage
@Ignore
class Java2DUnderlineTransformerTest {
lateinit var target: Java2DUnderlineTransformer
@Before
fun setUp() {
target = Java2DUnderlineTransformer()
}
@Test
fun shouldProperlyRun() {
val image = BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_ARGB)
target.transform(DefaultTileTexture(WIDTH, HEIGHT, image, CHAR.toString()), CHAR)
}
companion object {
val WIDTH = 10
val HEIGHT = 10
val CHAR = Tile.newBuilder()
.withModifiers(Modifiers.underline())
.build()
}
}
|
apache-2.0
|
0c2b384879eb8a0eb9085e2338b2efa0
| 25.470588 | 89 | 0.706667 | 4.245283 | false | true | false | false |
wordpress-mobile/WordPress-Android
|
WordPress/src/main/java/org/wordpress/android/ui/stats/refresh/lists/StatsBlockAdapter.kt
|
1
|
2268
|
package org.wordpress.android.ui.stats.refresh.lists
import android.view.ViewGroup
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.RecyclerView.Adapter
import org.wordpress.android.fluxc.store.StatsStore.StatsType
import org.wordpress.android.ui.stats.refresh.lists.StatsBlock.Type.EMPTY
import org.wordpress.android.ui.stats.refresh.lists.StatsBlock.Type.ERROR
import org.wordpress.android.ui.stats.refresh.lists.StatsBlock.Type.LOADING
import org.wordpress.android.ui.stats.refresh.lists.StatsBlock.Type.SUCCESS
import org.wordpress.android.ui.stats.refresh.lists.StatsBlock.Type.values
import org.wordpress.android.ui.stats.refresh.lists.viewholders.BaseStatsViewHolder
import org.wordpress.android.ui.stats.refresh.lists.viewholders.BlockListViewHolder
import org.wordpress.android.ui.stats.refresh.lists.viewholders.LoadingViewHolder
import org.wordpress.android.util.image.ImageManager
class StatsBlockAdapter(val imageManager: ImageManager) : Adapter<BaseStatsViewHolder>() {
private var items: List<StatsBlock> = listOf()
fun update(newItems: List<StatsBlock>) {
val diffResult = DiffUtil.calculateDiff(
StatsBlockDiffCallback(
items,
newItems
)
)
items = newItems
diffResult.dispatchUpdatesTo(this)
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): BaseStatsViewHolder {
return when (values()[viewType]) {
SUCCESS, ERROR, EMPTY -> BlockListViewHolder(parent, imageManager)
LOADING -> LoadingViewHolder(parent, imageManager)
}
}
override fun getItemViewType(position: Int): Int {
return items[position].type.ordinal
}
override fun getItemCount() = items.size
fun positionOf(statsType: StatsType): Int {
return items.indexOfFirst { it.statsType == statsType }
}
override fun onBindViewHolder(holder: BaseStatsViewHolder, position: Int, payloads: List<Any>) {
val item = items[position]
holder.bind(item.statsType, item.data)
}
override fun onBindViewHolder(holder: BaseStatsViewHolder, position: Int) {
onBindViewHolder(holder, position, listOf())
}
}
|
gpl-2.0
|
756bd79c712bb7099e76396ad436ac02
| 39.5 | 100 | 0.7306 | 4.508946 | false | false | false | false |
dbrant/apps-android-commons
|
app/src/test/kotlin/fr/free/nrw/commons/explore/PagingDataSourceFactoryTest.kt
|
2
|
1891
|
package fr.free.nrw.commons.explore
import com.nhaarman.mockitokotlin2.mock
import com.nhaarman.mockitokotlin2.spy
import com.nhaarman.mockitokotlin2.verify
import fr.free.nrw.commons.explore.depictions.DepictsClient
import fr.free.nrw.commons.explore.paging.LoadingState
import fr.free.nrw.commons.explore.paging.PagingDataSource
import fr.free.nrw.commons.explore.paging.PagingDataSourceFactory
import io.reactivex.processors.PublishProcessor
import org.hamcrest.MatcherAssert.assertThat
import org.hamcrest.Matchers.instanceOf
import org.junit.Before
import org.junit.Ignore
import org.junit.Test
import org.mockito.Mock
import org.mockito.Mockito
import org.mockito.MockitoAnnotations
class PagingDataSourceFactoryTest {
@Mock
private lateinit var depictsClient: DepictsClient
@Mock
private lateinit var loadingStates: PublishProcessor<LoadingState>
private lateinit var factory: PagingDataSourceFactory<String>
private var function: (Int, Int) -> List<String> = mock()
@Before
fun setUp() {
MockitoAnnotations.initMocks(this)
factory = object : PagingDataSourceFactory<String>(loadingStates) {
override val loadFunction get() = function
}
}
@Test
fun `create returns a dataSource`() {
assertThat(
factory.create(),
instanceOf(PagingDataSource::class.java)
)
}
@Test
@Ignore("Rewrite with Mockk constructor mocks")
fun `retryFailedRequest invokes method if not null`() {
val spyFactory = spy(factory)
val dataSource = mock<PagingDataSource<String>>()
Mockito.doReturn(dataSource).`when`(spyFactory).create()
factory.retryFailedRequest()
verify(dataSource).retryFailedRequest()
}
@Test
fun `retryFailedRequest does not invoke method if null`() {
factory.retryFailedRequest()
}
}
|
apache-2.0
|
ecd4088e44b260901d4c9c236a1fd31d
| 30 | 75 | 0.730301 | 4.502381 | false | true | false | false |
Major-/Vicis
|
modern/src/test/kotlin/rs/emulate/modern/codec/ArchiveTest.kt
|
1
|
4642
|
package rs.emulate.modern.codec
import io.netty.buffer.Unpooled
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.Assertions.assertThrows
import org.junit.jupiter.api.Test
import rs.emulate.modern.codec.Archive.Companion.readArchive
class ArchiveTest {
@Test
fun `read no entry`() {
val table = ReferenceTable()
val entry = table.createEntry(0)
assertThrows(IllegalArgumentException::class.java) {
Unpooled.EMPTY_BUFFER.readArchive(entry)
}
}
@Test
fun `write no entry`() {
val archive = Archive()
assertThrows(IllegalStateException::class.java) {
archive.write()
}
}
@Test
fun `read single entry`() {
val table = ReferenceTable()
val entry = table.createEntry(0)
entry.createChild(0)
val buf = Unpooled.wrappedBuffer("Hello, world!".toByteArray())
val archive = buf.readArchive(entry)
assertEquals(buf, archive[0])
}
@Test
fun `write single entry`() {
val buf = Unpooled.wrappedBuffer("Hello, world!".toByteArray())
val archive = Archive()
archive[0] = buf
assertEquals(archive.write(), buf)
}
@Test
fun `read zero stripes`() {
val table = ReferenceTable()
val entry = table.createEntry(0)
val buf = Unpooled.wrappedBuffer(byteArrayOf(0))
assertThrows(IllegalArgumentException::class.java) {
buf.readArchive(entry)
}
}
@Test
fun `read single stripe`() {
val table = ReferenceTable()
val entry = table.createEntry(0)
entry.createChild(0)
entry.createChild(1)
entry.createChild(2)
val buf0 = Unpooled.wrappedBuffer("Hello".toByteArray())
val buf1 = Unpooled.wrappedBuffer("world".toByteArray())
val buf2 = Unpooled.wrappedBuffer("!".toByteArray())
val trailer = Unpooled.buffer()
trailer.writeInt(5)
trailer.writeInt(0)
trailer.writeInt(-4)
trailer.writeByte(1)
val buf = Unpooled.wrappedBuffer(buf0, buf1, buf2, trailer)
val archive = buf.readArchive(entry)
assertEquals(3, archive.size)
assertEquals(buf0, archive[0])
assertEquals(buf1, archive[1])
assertEquals(buf2, archive[2])
}
@Test
fun `read multiple stripes`() {
val table = ReferenceTable()
val entry = table.createEntry(0)
entry.createChild(0)
entry.createChild(1)
entry.createChild(2)
val buf00 = Unpooled.wrappedBuffer("He".toByteArray())
val buf01 = Unpooled.wrappedBuffer("ll".toByteArray())
val buf02 = Unpooled.wrappedBuffer("o".toByteArray())
val buf10 = Unpooled.wrappedBuffer("wo".toByteArray())
val buf11 = Unpooled.wrappedBuffer("r".toByteArray())
val buf12 = Unpooled.wrappedBuffer("ld".toByteArray())
val buf20 = Unpooled.wrappedBuffer("".toByteArray())
val buf21 = Unpooled.wrappedBuffer("!".toByteArray())
val buf22 = Unpooled.wrappedBuffer("".toByteArray())
val buf0 = Unpooled.wrappedBuffer(buf00, buf01, buf02)
val buf1 = Unpooled.wrappedBuffer(buf10, buf11, buf12)
val buf2 = Unpooled.wrappedBuffer(buf20, buf21, buf22)
val trailer = Unpooled.buffer()
trailer.writeInt(2)
trailer.writeInt(0)
trailer.writeInt(-2)
trailer.writeInt(2)
trailer.writeInt(-1)
trailer.writeInt(0)
trailer.writeInt(1)
trailer.writeInt(1)
trailer.writeInt(-2)
trailer.writeByte(3)
val buf = Unpooled.wrappedBuffer(buf00, buf10, buf20, buf01, buf11, buf21, buf02, buf12, buf22, trailer)
val archive = buf.readArchive(entry)
assertEquals(3, archive.size)
assertEquals(buf0, archive[0])
assertEquals(buf1, archive[1])
assertEquals(buf2, archive[2])
}
@Test
fun `write single stripe`() {
val buf0 = Unpooled.wrappedBuffer("Hello".toByteArray())
val buf1 = Unpooled.wrappedBuffer("world".toByteArray())
val buf2 = Unpooled.wrappedBuffer("!".toByteArray())
val archive = Archive()
archive[0] = buf0.slice()
archive[1] = buf1.slice()
archive[2] = buf2.slice()
val trailer = Unpooled.buffer()
trailer.writeInt(5)
trailer.writeInt(0)
trailer.writeInt(-4)
trailer.writeByte(1)
val expected = Unpooled.wrappedBuffer(buf0, buf1, buf2, trailer)
assertEquals(expected, archive.write())
}
}
|
isc
|
82e85e8390779d41c0a323b17c734db7
| 28.0125 | 112 | 0.618914 | 4.262626 | false | true | false | false |
markusressel/TutorialTooltip
|
library/src/main/java/de/markusressel/android/library/tutorialtooltip/builder/TutorialTooltipBuilder.kt
|
1
|
7767
|
/*
* Copyright (c) 2016 Markus Ressel
*
* 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 de.markusressel.android.library.tutorialtooltip.builder
import android.app.Dialog
import android.content.Context
import android.graphics.Point
import androidx.annotation.StringRes
import android.util.Log
import android.view.View
import de.markusressel.android.library.tutorialtooltip.view.TooltipId
import de.markusressel.android.library.tutorialtooltip.view.TutorialTooltipView
/**
* Use this Builder to create a TutorialTooltip
*
*
* Created by Markus on 01.12.2016.
*/
class TutorialTooltipBuilder
/**
* Constructor for the builder.
* Chain methods and call ".build()" as your last step to make this object immutable.
*/
(
/**
* activity context that the TutorialTooltip will be added to.
* Application context will not suffice!
*/
internal val context: Context,
/**
* Indicator configuration
*/
internal val indicatorConfiguration: IndicatorConfiguration = IndicatorConfiguration(),
/**
* Message configuration
*/
internal val messageConfiguration: MessageConfiguration = MessageConfiguration(),
/**
* OnClick listener for the whole TutorialTooltipView
*/
internal val onClick: ((id: TooltipId, tutorialTooltipView: TutorialTooltipView) -> Unit)? = null,
/**
* Listener for TutorialTooltip remove() events, called before the view is removed
*/
internal val onPreRemove: ((id: TooltipId, view: TutorialTooltipView) -> Unit)? = null,
/**
* Listener for TutorialTooltip remove() events, called after the view is removed
*/
internal var onPostRemove: ((id: TooltipId, view: TutorialTooltipView) -> Unit)? = null
) : Builder<TutorialTooltipBuilder>() {
/**
* AttachMode used to distinguish between activity, dialog and window scope
*/
var attachMode: AttachMode
private set
/**
* Dialog the TutorialTooltip will be attached to (if AttachMode is Dialog)
*/
var dialog: Dialog? = null
private set
/**
* ID the TutorialTooltip will get
*/
var tooltipId: TooltipId
private set
/**
* The amount of times to show this TutorialTooltip
*/
var showCount: Int? = null
private set
/**
* Anchor view
* This view is used to position the indicator view
*/
var anchorView: View? = null
private set
/**
* Anchor gravity used to position the indicator using the anchorView borders (or center)
*/
var anchorGravity: TutorialTooltipView.Gravity? = null
private set
/**
* Exact coordinates the indicator should be positioned
*/
var anchorPoint: Point? = null
private set
init {
this.tooltipId = TooltipId()
// set default values
this.attachMode = AttachMode.Activity
}
/**
* Specify whether the TutorialTooltip should be attached to the Window or the activity.
*
*
* This can be handy if you want to show TutorialTooltips above all other content, like in FragmentDialogs.
* @return TutorialTooltipBuilder
*/
fun attachToWindow(): TutorialTooltipBuilder {
throwIfCompleted()
attachMode = AttachMode.Window
return this
}
/**
* Specify the activity this TutorialTooltip should be attached to.
*
*
* @param dialog dialog to attach this view to
* *
* @return TutorialTooltipBuilder
*/
fun attachToDialog(dialog: Dialog): TutorialTooltipBuilder {
throwIfCompleted()
attachMode = AttachMode.Dialog
this.dialog = dialog
return this
}
/**
* Set the anchor for the TutorialTooltip
* @param view view which will be used as an anchor
* *
* @param gravity position relative to the anchor view which the indicator will point to
* *
* @return TutorialTooltipBuilder
*/
@JvmOverloads
fun anchor(view: View,
gravity: TutorialTooltipView.Gravity = TutorialTooltipView.Gravity.CENTER): TutorialTooltipBuilder {
throwIfCompleted()
this.anchorPoint = null
this.anchorView = view
this.anchorGravity = gravity
return this
}
/**
* Set the anchor point for the TutorialTooltip
* @param point position where the indicator will be located at
* *
* @return TutorialTooltipBuilder
*/
fun anchor(point: Point): TutorialTooltipBuilder {
throwIfCompleted()
this.anchorView = null
this.anchorPoint = point
return this
}
/**
* Call this to show this TutorialTooltip only once.
*
*
* The counter will increase when the TutorialTooltip is **removed** from the sceen.
* NOT when it is **shown**.
* @param identifierRes an tooltipId resource for the TutorialTooltip that will be used to save
* * how often it was shown
* *
* @return TutorialTooltipBuilder
*/
fun oneTimeUse(@StringRes identifierRes: Int): TutorialTooltipBuilder {
return showCount(context.getString(identifierRes), 1)
}
/**
* Set how often this TutorialTooltip should be shown
* The counter will increase when the TutorialTooltip is **removed** from the sceen.
* NOT when it is **shown**.
* @param identifierRes an tooltipId resource for the TutorialTooltip that will be used to save
* * how often it was shown
* *
* @param count the number of times to show this TutorialTooltip, `null` for infinity
* *
* @return TutorialTooltipBuilder
*/
fun showCount(@StringRes identifierRes: Int, count: Int?): TutorialTooltipBuilder {
return showCount(context.getString(identifierRes), count)
}
/**
* Set how often this TutorialTooltip should be shown
* The counter will increase when the TutorialTooltip is **removed** from the sceen.
* NOT when it is **shown**.
* @param identifier an tooltipId for the TutorialTooltip that will be used to save
* * how often it was shown already
* *
* @param count the number of times to show this TutorialTooltip, `null` for infinity
* *
* @return TutorialTooltipBuilder
*/
fun showCount(identifier: String, count: Int?): TutorialTooltipBuilder {
throwIfCompleted()
this.tooltipId = TooltipId(identifier)
this.showCount = count
return this
}
override fun build(): TutorialTooltipBuilder {
if (anchorView == null && anchorPoint == null) {
Log.w(TAG,
"You did not specify an anchor or anchor position! The view will be positioned at [0,0].")
}
return super.build()
}
/**
* Determines how the TutorialTooltip is attached to the parent view
* This is used only internally
*/
enum class AttachMode {
Window,
Activity,
Dialog
}
companion object {
private const val TAG = "TutorialTooltipBuilder"
}
}
|
apache-2.0
|
59f2b943b68b15cd16d3c20981c064a9
| 29.703557 | 115 | 0.644393 | 4.925174 | false | false | false | false |
darkoverlordofdata/entitas-kotlin
|
entitas/src/main/java/com/darkoverlordofdata/entitas/Events.kt
|
1
|
1459
|
package com.darkoverlordofdata.entitas
enum class GroupEventType {
OnEntityAdded,
OnEntityRemoved,
OnEntityAddedOrRemoved
}
class EntityReleasedArgs(entity: Entity) : EventArgs {
val entity = entity
}
class EntityChangedArgs(entity: Entity, index:Int, component: IComponent?) : EventArgs {
val entity = entity
val index = index
val component = component
}
class ComponentReplacedArgs(entity: Entity, index:Int, previous: IComponent, replacement: IComponent?) : EventArgs {
val entity = entity
val index = index
val previous = previous
val replacement = replacement
}
class GroupChangedArgs(group: Group, entity: Entity, index:Int, newComponent: IComponent?) : EventArgs {
val group = group
val entity = entity
val index = index
val newComponent = newComponent
}
class GroupUpdatedArgs(group: Group, entity: Entity, index:Int, prevComponent: IComponent, newComponent: IComponent?) : EventArgs {
val group = group
val entity = entity
val index = index
val prevComponent = prevComponent
val newComponent = newComponent
}
class PoolEntityChangedArgs(pool: Pool, entity: Entity) : EventArgs {
val pool = pool
val entity = entity
}
class PoolGroupChangedArgs(pool: Pool, group: Group) : EventArgs {
val pool = pool
val group = group
}
class TriggerOnEvent(trigger: Matcher, eventType: GroupEventType) {
val trigger = trigger
val eventType = eventType
}
|
mit
|
780f6302dd97ad30cf9f385e79bdaf40
| 26.037037 | 131 | 0.723098 | 4.241279 | false | false | false | false |
GunoH/intellij-community
|
python/testSrc/com/jetbrains/python/refactoring/suggested/PySuggestedRefactoringTest.kt
|
8
|
20763
|
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.jetbrains.python.refactoring.suggested
import com.intellij.openapi.actionSystem.IdeActions
import com.intellij.openapi.command.CommandProcessor
import com.intellij.openapi.command.WriteCommandAction
import com.intellij.openapi.util.TextRange
import com.intellij.psi.PsiDocumentManager
import com.intellij.refactoring.RefactoringBundle
import com.intellij.refactoring.suggested.SuggestedRefactoringExecution
import com.intellij.refactoring.suggested._suggestedChangeSignatureNewParameterValuesForTests
import com.jetbrains.python.PythonFileType
import com.jetbrains.python.fixtures.PyTestCase
import com.jetbrains.python.psi.LanguageLevel
import com.jetbrains.python.psi.PyElementGenerator
class PySuggestedRefactoringTest : PyTestCase() {
override fun setUp() {
super.setUp()
_suggestedChangeSignatureNewParameterValuesForTests = {
SuggestedRefactoringExecution.NewParameterValue.Expression(
PyElementGenerator.getInstance(myFixture.project).createExpressionFromText(LanguageLevel.getLatest(), "$it")
)
}
}
// PY-42285
fun testImportedClassRename() {
doRenameImportedTest(
"""
class A<caret>C:
pass
""".trimIndent(),
"""
class ABC:
pass
""".trimIndent(),
"AC",
"ABC",
"B"
)
}
// PY-42285
fun testImportedFunctionRename() {
doRenameImportedTest(
"""
def a<caret>c():
pass
""".trimIndent(),
"""
def abc():
pass
""".trimIndent(),
"ac",
"abc",
"b",
changeSignatureIntention()
)
}
// PY-42285
fun testMethodRename() {
doRenameTest(
"""
class A:
def method<caret>(self):
pass
a = A()
a.method()
""".trimIndent(),
"""
class A:
def method1(self):
pass
a = A()
a.method1()
""".trimIndent(),
"method",
"method1",
"1",
changeSignatureIntention()
)
}
// PY-49466
fun testMethodRenameToStartingWithKeywordName() {
doNoIntentionTest(
"""
def test<caret>(): pass
""".trimIndent(),
{
repeat("test".length, this::performBackspace)
myFixture.type("def")
},
intention = changeSignatureIntention()
)
}
// PY-42285
fun testImportedVariableRename() {
doRenameImportedTest(
"""
A<caret>C = 10
""".trimIndent(),
"""
ABC = 10
""".trimIndent(),
"AC",
"ABC",
"B"
)
}
// PY-42285
fun testInstanceVariableRename() {
doRenameTest(
"""
class A:
def __init__(self):
self.a<caret>c = 10
a = A()
a.ac
""".trimIndent(),
"""
class A:
def __init__(self):
self.abc = 10
a = A()
a.abc
""".trimIndent(),
"ac",
"abc",
"b"
)
}
// PY-42285
fun testClassVariableRename() {
doRenameTest(
"""
class A:
a<caret>c = 10
A.ac
""".trimIndent(),
"""
class A:
abc = 10
A.abc
""".trimIndent(),
"ac",
"abc",
"b"
)
}
// PY-42285
fun testParameterRename() {
doRenameTest(
"""
def foo(pa<caret>am):
print(paam)
""".trimIndent(),
"""
def foo(param):
print(param)
""".trimIndent(),
"paam",
"param",
"r",
changeSignatureIntention()
)
}
// PY-42285
fun testPropertySetterParameterRename() {
doRenameTest(
"""
class A:
def __init__(self):
self._a = 0
@property
def a(self):
return self._a
@a.setter
def a(self, val<caret>):
self._a = val
a = A()
print(a.a)
a.a = 10
print(a.a)
""".trimIndent(),
"""
class A:
def __init__(self):
self._a = 0
@property
def a(self):
return self._a
@a.setter
def a(self, value):
self._a = value
a = A()
print(a.a)
a.a = 10
print(a.a)
""".trimIndent(),
"val",
"value",
"ue"
)
}
// PY-42285
fun testPropertySetterParameterRetype() {
// rename has no ability to track disappeared parameter
doNoIntentionTest(
"""
class A:
def __init__(self):
self._a = 0
@property
def a(self):
return self._a
@a.setter
def a(self, bbb<caret>):
self._a = bbb
a = A()
print(a.a)
a.a = 10
print(a.a)
""".trimIndent(),
{ repeat(3, this::performBackspace) },
{ myFixture.type("zzz") },
intention = RefactoringBundle.message("suggested.refactoring.rename.intention.text", "bbb", "zzz")
)
}
// PY-42285
fun testReorderParametersWithDefaultValues() {
doChangeSignatureTest(
"""
def foo(<caret>a="a", b="b"): pass
foo("a", "b")
foo("a")
""".trimIndent(),
"""
def foo(b="b", a="a"): pass
foo("b", "a")
foo(a="a")
""".trimIndent(),
{ replaceTextAtCaret("a=\"a\", b=\"b\"", "b=\"b\", a=\"a\"") }
)
}
// PY-42285
fun testAddPositionalOnlyMarkerAtTheEnd() {
doChangeSignatureTest(
"""
def foo(p1=None, p2=None<caret>):
print(p1, p2)
foo(p2=2)
""".trimIndent(),
"""
def foo(p1=None, p2=None, /):
print(p1, p2)
foo(None, 2)
""".trimIndent(),
{ myFixture.type(", /") }
)
}
// PY-42285
fun testAddPositionalOnlyParameterWithDefaultValueAtTheBeginning() {
_suggestedChangeSignatureNewParameterValuesForTests = { SuggestedRefactoringExecution.NewParameterValue.None }
doChangeSignatureTest(
"""
def foo(<caret>p2=None, /):
print(p2)
foo(2)
""".trimIndent(),
"""
def foo(p1=None, p2=None, /):
print(p2)
foo(None, 2)
""".trimIndent(),
{ myFixture.type("p1=None, ") }
)
}
// PY-42285
fun testAddKeywordOnlyMarkerInTheMiddle() {
doChangeSignatureTest(
"""
def foo(a, <caret>b):
pass
def bar():
foo(1, 2)
foo(3, 4)
""".trimIndent(),
"""
def foo(a, *, b):
pass
def bar():
foo(1, b=2)
foo(3, b=4)
""".trimIndent(),
{ myFixture.type("*, ") }
)
}
// PY-42285
fun testRemoveDefaultValueNothingSpecifiedInstead() {
_suggestedChangeSignatureNewParameterValuesForTests = { SuggestedRefactoringExecution.NewParameterValue.None }
doChangeSignatureTest(
"""
def foo(a<caret>=1): pass
foo()
""".trimIndent(),
"""
def foo(a): pass
foo(1)
""".trimIndent(),
{ replaceTextAtCaret("=1", "") }
)
}
// PY-42285
fun testRemoveDefaultValue() {
doChangeSignatureTest(
"""
def foo(a<caret>=1): pass
foo()
""".trimIndent(),
"""
def foo(a): pass
foo(0)
""".trimIndent(),
{ replaceTextAtCaret("=1", "") }
)
}
// PY-42285
fun testAddParameterBeforeKeywordContainer() {
doChangeSignatureTest(
"""
def foo(<caret>**kwargs):
for key, value in kwargs.items():
print("%s = %s" % (key, value))
foo(name="geeks", ID="101", language="Python")
""".trimIndent(),
"""
def foo(a, **kwargs):
for key, value in kwargs.items():
print("%s = %s" % (key, value))
foo(0, name="geeks", ID="101", language="Python")
""".trimIndent(),
{ myFixture.type("a, ") }
)
}
// PY-42285
fun testDontMergeWithParameterAfter1() {
doChangeSignatureTest(
"""
def foo(<caret>**kwargs): pass
foo(b=2, c=3)
""".trimIndent(),
"""
def foo(a=0, **kwargs): pass
foo(b=2, c=3)
""".trimIndent(),
{ myFixture.type("a=") },
{ myFixture.type("0, ") } // don't squash actions, sequence is important
)
}
// PY-42285
fun testDontMergeWithParameterAfter2() {
doChangeSignatureTest(
"""
def foo(<caret>b=2): pass
foo(b=2)
""".trimIndent(),
"""
def foo(a=0, b=2): pass
foo(b=2)
""".trimIndent(),
{ myFixture.type("a=") },
{ myFixture.type("0, ") } // don't squash actions, sequence is important
)
}
// PY-42285
fun testSpecifyAnotherDefaultValueInBalloon() {
doChangeSignatureTest(
"""
def foo(<caret>): pass
foo()
""".trimIndent(),
"""
def foo(b=123): pass
foo(0)
""".trimIndent(),
{ myFixture.type("b=123") }
)
}
// PY-42285
fun testDontSpecifyDefaultValueInBalloon() {
_suggestedChangeSignatureNewParameterValuesForTests = { SuggestedRefactoringExecution.NewParameterValue.None }
doChangeSignatureTest(
"""
def foo(<caret>): pass
foo()
""".trimIndent(),
"""
def foo(b=123): pass
foo()
""".trimIndent(),
{ myFixture.type("b=123") }
)
}
// PY-42285
fun testPuttingOptionalBetweenOptionalAndSlash() {
doChangeSignatureTest(
"""
def f(p2<caret>=None, /): pass
f(1)
""".trimIndent(),
"""
def f(p1=None, p2=None, /): pass
f(1, 0)
""".trimIndent(),
{ performBackspace() },
{ myFixture.type("1") },
{ myFixture.editor.caretModel.moveCaretRelatively(7, 0, false, false, false) },
{ myFixture.type("p2=") },
{ myFixture.type("N") },
{ myFixture.type("o") },
{ myFixture.type("n") },
{ myFixture.type("e") },
{ myFixture.type(",") },
{ myFixture.type(" ") } // don't squash actions, sequence is important
)
}
// PY-42285
fun testPuttingNamedBetweenNamed() {
doChangeSignatureTest(
"""
def f(p2<caret>, p3): pass
f(2, 3)
""".trimIndent(),
"""
def f(p1, p2, p3): pass
f(2, 0, 3)
""".trimIndent(),
{ performBackspace() },
{ myFixture.type("1") },
{ myFixture.editor.caretModel.moveCaretRelatively(2, 0, false, false, false) },
{ myFixture.type("p") },
{ myFixture.type("2") },
{ myFixture.type(",") },
{ myFixture.type(" ") } // don't squash actions, sequence is important
)
}
// PY-42285
fun testPuttingOptionalBetweenNamedAndOptional() {
doChangeSignatureTest(
"""
def f(p2<caret>, p3=None): pass
f(2, 3)
""".trimIndent(),
"""
def f(p1, p2=None, p3=None): pass
f(2, 0, 3)
""".trimIndent(),
{ performBackspace() },
{ myFixture.type("1") },
{ myFixture.editor.caretModel.moveCaretRelatively(2, 0, false, false, false) },
{ myFixture.type("p2=") },
{ myFixture.type("N") },
{ myFixture.type("o") },
{ myFixture.type("n") },
{ myFixture.type("e") },
{ myFixture.type(",") },
{ myFixture.type(" ") } // don't squash actions, sequence is important
)
}
// PY-42285
fun testRenamingParameterOnSeparateLine() {
doChangeSignatureTest(
"""
def f(
base<caret>
): pass
f(f("base"))
""".trimIndent(),
"""
def f(
bases
): pass
f(f("base"))
""".trimIndent(),
{ myFixture.type("s") }
)
}
// PY-42285
fun testNoIntentionOnMakingFunctionAsync() {
doNoIntentionTest(
"""
<caret>def foo(a, b): pass
""".trimIndent(),
{ myFixture.type("async ") },
intention = changeSignatureIntention()
)
}
// PY-42285
fun testNoIntentionOnMakingFunctionSync() {
doNoIntentionTest(
"""
async <caret>def foo(a, b): pass
""".trimIndent(),
{ repeat("async ".length, this::performBackspace) },
intention = changeSignatureIntention()
)
}
// PY-42285
fun testRetypedFunctionName() {
doChangeSignatureTest(
"""
def foo<caret>(a, b): pass
foo(1, 2)
""".trimIndent(),
"""
def bar(a, b): pass
bar(1, 2)
""".trimIndent(),
{ repeat(" foo".length, this::performBackspace) },
{ myFixture.type(" bar") }
)
}
// PY-42285
fun testClassMethodSignature() {
doChangeSignatureTest(
"""
class A:
@classmethod
def method(cls, a<caret>):
pass
A.method(5)
""".trimIndent(),
"""
class A:
@classmethod
def method(cls, a, b):
pass
A.method(5, 0)
""".trimIndent(),
{ myFixture.type(", b") }
)
}
// PY-42285
fun testRetypedParameter1() {
doChangeSignatureTest(
"""
def __func__0(a<caret>):
return a.swapcase()
d = {'1': __func__0(__func__0("abc")), '2': __func__0(__func__0("abc"))}
""".trimIndent(),
"""
def __func__0(b):
return b.swapcase()
d = {'1': __func__0(__func__0("abc")), '2': __func__0(__func__0("abc"))}
""".trimIndent(),
{ performBackspace() },
{ myFixture.type("b") }
)
}
// PY-42285
fun testRetypedParameter2() {
doChangeSignatureTest(
"""
def __func__0(a<caret>):
return a.swapcase()
d = {'1': __func__0(__func__0("abc")), '2': __func__0(__func__0("abc"))}
""".trimIndent(),
"""
def __func__0(bbb):
return bbb.swapcase()
d = {'1': __func__0(__func__0("abc")), '2': __func__0(__func__0("abc"))}
""".trimIndent(),
{ performBackspace() },
{ myFixture.type("bbb") }
)
}
// PY-42285
fun testRetypedParameter3() {
doChangeSignatureTest(
"""
def __func__0(aaa<caret>):
return aaa.swapcase()
d = {'1': __func__0(__func__0("abc")), '2': __func__0(__func__0("abc"))}
""".trimIndent(),
"""
def __func__0(b):
return b.swapcase()
d = {'1': __func__0(__func__0("abc")), '2': __func__0(__func__0("abc"))}
""".trimIndent(),
{ repeat("aaa".length) { performBackspace() } },
{ myFixture.type("b") }
)
}
// PY-42285
fun testRenameToUnsupportedIdentifier() {
doNoIntentionTest(
"""
class A:
def print_r<caret>(self): pass
A().print_r()
""".trimIndent(),
{ repeat("_r".length, this::performBackspace) },
intention = RefactoringBundle.message("suggested.refactoring.rename.intention.text", "print_r", "print")
)
}
// PY-42285
fun testInvalidElementAccessOnNewParameter() {
doChangeSignatureTest(
"""
def greeting(<caret>
number: int,
/,
position: float = 21234,
*,
name_family: str
) -> str:
return 'Hello ' + name_family + " " + str(number)
greeting(12345432123, 1234, name_family="DIZEL")
""".trimIndent(),
"""
def greeting(
minor: int,
number: int,
/,
position: float = 21234,
*,
name_family: str
) -> str:
return 'Hello ' + name_family + " " + str(number)
greeting(0, 12345432123, 1234, name_family="DIZEL")
""".trimIndent(),
{ myFixture.performEditorAction(IdeActions.ACTION_EDITOR_START_NEW_LINE) },
{ myFixture.type("m") },
{ myFixture.type("i") },
{ myFixture.type("n") },
{ myFixture.type("o") },
{ myFixture.type("r") },
{ myFixture.type(":") },
{ myFixture.type(" ") },
{ myFixture.type("i") },
{ myFixture.type("n") },
{ myFixture.type("t") },
{ myFixture.type(",") } // don't squash actions, sequence is important
)
}
// PY-42285
fun testRenameParameterOfFunctionWithStub() {
val testDataPathPrefix = "refactoring/suggested/${getTestName(true)}"
val source = "aaa.pyi"
myFixture.copyFileToProject("$testDataPathPrefix/$source", source)
doNoIntentionTest(
"""
def foo(p1<caret>):
print(p1)
""".trimIndent(),
{ myFixture.type("2") },
intention = changeSignatureIntention()
)
}
// EA-252027
fun testOverload() {
doNoIntentionTest(
"""
from typing import overload
@overload
def foo(p<caret>1: int, p2: int) -> int: ...
def foo(p1, p2): ...
""".trimIndent(),
{ myFixture.type("aram") },
intention = changeSignatureIntention()
)
}
private fun doRenameTest(before: String, after: String, oldName: String, newName: String, type: String, intention: String? = null) {
myFixture.configureByText(PythonFileType.INSTANCE, before)
myFixture.checkHighlighting()
myFixture.type(type)
PsiDocumentManager.getInstance(myFixture.project).commitAllDocuments()
executeIntention(intention ?: RefactoringBundle.message("suggested.refactoring.rename.intention.text", oldName, newName))
myFixture.checkResult(after)
myFixture.checkHighlighting()
}
private fun doRenameImportedTest(
importedBefore: String,
importedAfter: String,
oldName: String,
newName: String,
type: String,
intention: String? = null
) {
val testDataPathPrefix = "refactoring/suggested/${getTestName(true)}"
val source = "a.py"
myFixture.copyFileToProject("$testDataPathPrefix/$source", source)
doRenameTest(importedBefore, importedAfter, oldName, newName, type, intention)
myFixture.checkResultByFile(source, "$testDataPathPrefix/a.after.py", true)
}
private fun doChangeSignatureTest(
before: String,
after: String,
vararg editingActions: () -> Unit
) {
myFixture.configureByText(PythonFileType.INSTANCE, before)
myFixture.checkHighlighting()
editingActions.forEach {
WriteCommandAction.runWriteCommandAction(myFixture.project, it)
PsiDocumentManager.getInstance(myFixture.project).commitAllDocuments()
}
executeIntention(changeSignatureIntention())
myFixture.checkResult(after)
myFixture.checkHighlighting()
}
private fun doNoIntentionTest(text: String, vararg editingActions: () -> Unit, intention: String) {
myFixture.configureByText(PythonFileType.INSTANCE, text)
myFixture.checkHighlighting()
editingActions.forEach {
WriteCommandAction.runWriteCommandAction(myFixture.project, it)
PsiDocumentManager.getInstance(myFixture.project).commitAllDocuments()
}
assertNull(myFixture.getAvailableIntention(intention))
}
private fun executeIntention(intention: String) {
val project = myFixture.project
myFixture.findSingleIntention(intention).also {
CommandProcessor.getInstance().executeCommand(project, { it.invoke(project, myFixture.editor, myFixture.file) }, it.text, null)
}
}
private fun replaceTextAtCaret(oldText: String, newText: String) {
val editor = myFixture.editor
val offset = editor.caretModel.offset
val actualText = editor.document.getText(TextRange(offset, offset + oldText.length))
require(actualText == oldText)
editor.document.replaceString(offset, offset + oldText.length, newText)
}
private fun performBackspace(@Suppress("UNUSED_PARAMETER") unused: Int = 0) {
myFixture.performEditorAction(IdeActions.ACTION_EDITOR_BACKSPACE)
}
private fun changeSignatureIntention(): String {
return RefactoringBundle.message("suggested.refactoring.change.signature.intention.text",
RefactoringBundle.message("suggested.refactoring.usages"))
}
}
|
apache-2.0
|
c65ed6a9099ad4597ad988d8f988291d
| 22.304153 | 140 | 0.525117 | 4.218407 | false | true | false | false |
GunoH/intellij-community
|
platform/workspaceModel/storage/testEntities/testSrc/com/intellij/workspaceModel/storage/entities/unknowntypes/test/api/UnknownFieldEntity.kt
|
2
|
1446
|
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.workspaceModel.storage.entities.unknowntypes.test.api
import com.intellij.workspaceModel.storage.WorkspaceEntity
import java.util.Date
import com.intellij.workspaceModel.storage.EntitySource
import com.intellij.workspaceModel.storage.GeneratedCodeApiVersion
import com.intellij.workspaceModel.storage.MutableEntityStorage
import org.jetbrains.deft.ObjBuilder
import org.jetbrains.deft.Type
interface UnknownFieldEntity : WorkspaceEntity {
val data: Date
//region generated code
@GeneratedCodeApiVersion(1)
interface Builder : UnknownFieldEntity, WorkspaceEntity.Builder<UnknownFieldEntity>, ObjBuilder<UnknownFieldEntity> {
override var data: Date
override var entitySource: EntitySource
}
companion object : Type<UnknownFieldEntity, Builder>() {
operator fun invoke(data: Date, entitySource: EntitySource, init: (Builder.() -> Unit)? = null): UnknownFieldEntity {
val builder = builder()
builder.data = data
builder.entitySource = entitySource
init?.invoke(builder)
return builder
}
}
//endregion
}
//region generated code
fun MutableEntityStorage.modifyEntity(entity: UnknownFieldEntity, modification: UnknownFieldEntity.Builder.() -> Unit) = modifyEntity(
UnknownFieldEntity.Builder::class.java, entity, modification)
//endregion
|
apache-2.0
|
321a9297c1ca93eb2b4de8ef6782ae16
| 36.076923 | 134 | 0.783541 | 4.901695 | false | false | false | false |
walleth/kethereum
|
method_signatures/src/main/kotlin/org/kethereum/methodsignatures/FileBackedMethodSignatureStore.kt
|
1
|
1188
|
package org.kethereum.methodsignatures
import org.kethereum.methodsignatures.model.TextMethodSignature
import java.io.File
private fun toStringSet(file: File) = semicolonSeparatedStringArray(file).toHashSet()
private fun toTextSignatureSet(file: File) = semicolonSeparatedStringArray(file).map { TextMethodSignature(it) }.toHashSet()
private fun semicolonSeparatedStringArray(file: File) = file.readText().split(";")
class FileBackedMethodSignatureStore(private val storeDir: File) {
fun upsert(signatureHash: String, signatureText: String): Boolean {
val file = File(storeDir, signatureHash)
val isNewEntry = !file.exists()
return isNewEntry.also {
val res = if (isNewEntry) {
HashSet()
} else {
toStringSet(file)
}
res.add(signatureText)
file.writeText(res.joinToString(";"))
}
}
fun get(signatureHash: String) = toTextSignatureSet(toFile(signatureHash))
fun has(signatureHash: String) = toFile(signatureHash).exists()
fun all() = storeDir.list().toList()
private fun toFile(signatureHash: String) = File(storeDir, signatureHash)
}
|
mit
|
e58bdd9845ecd963c5dde76cf94924ed
| 36.15625 | 124 | 0.689394 | 4.351648 | false | false | false | false |
jimandreas/BottomNavigationView-plus-LeakCanary
|
app/src/main/java/com/jimandreas/android/designlibdemo/Leak1TestActivity.kt
|
2
|
6872
|
/*
* Copyright (C) 2015 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.jimandreas.android.designlibdemo
import android.Manifest
import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.location.Location
import android.location.LocationListener
import android.location.LocationManager
import android.net.Uri
import android.os.Bundle
import android.support.design.widget.BottomNavigationView
import android.support.design.widget.CollapsingToolbarLayout
import android.support.design.widget.FloatingActionButton
import android.support.v4.app.ActivityCompat
import android.support.v7.widget.Toolbar
import android.text.Html
import android.text.Spanned
import android.view.View
import android.widget.ImageView
import android.widget.TextView
import android.widget.Toast
import com.bumptech.glide.Glide
import com.jimandreas.android.base.BottomNavActivity
import timber.log.Timber
import java.util.concurrent.TimeUnit
class Leak1TestActivity : BottomNavActivity(), LocationListener {
private lateinit var leak_title: TextView
private lateinit var leak_text: TextView
private lateinit var more_button: FloatingActionButton
private lateinit var bottom_navigation: BottomNavigationView
// private static Drawable leaked_drawable;
private var locationManager: LocationManager? = null
override val activityMenuID: Int
get() = WHOAMI_NAVBAR_MENUID
override val contentViewId: Int
get() = R.layout.leak_detail
@SuppressLint("SetTextI18n")
public override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
// setContentView(R.layout.leak_detail);
leak_title = findViewById(R.id.leak_title)
leak_text = findViewById(R.id.leak_text)
more_button = findViewById(R.id.more_button)
bottom_navigation = findViewById(R.id.bottom_navigation)
val intent = intent
val leakTestName = intent.getStringExtra(EXTRA_NAME)
val toolbar = findViewById<View>(R.id.toolbar) as Toolbar
setSupportActionBar(toolbar)
val collapsingToolbar = findViewById<View>(R.id.collapsing_toolbar) as CollapsingToolbarLayout
collapsingToolbar.title = leakTestName
loadBackdrop()
/**
* This leak is courtesy of:
*
* https://medium.com/freenet-engineering/memory-leaks-in-android-identify-treat-and-avoid-d0b1233acc8#.9sanu6r7h
*/
leak_title.setText(R.string.leak1)
var desc_raw = ("Switch between the activities by selecting the BottomNavigationView item."
+ " This should leak the listener in the code"
+ " and produce a LeakCanary response.\n\n"
+ "This leak is courtesy of the entry by: \n\n"
+ "<big><strong>Johan Olsson</big></strong>\n\n"
+ "on his post to medium.com titled:\n\n"
+ "<big><strong>Memory leaks in Android — identify, treat and avoid</big></strong>\n"
+ "\nFor more information, press the FAB (floating action button).")
desc_raw = desc_raw.replace("\n", "<br>")
val desc: Spanned
desc = if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
Html.fromHtml(desc_raw,
Html.FROM_HTML_MODE_LEGACY)
} else {
Html.fromHtml(desc_raw)
}
leak_text.text = desc
/**
* And here is the actual leak!
*/
locationManager = getSystemService(Context.LOCATION_SERVICE) as LocationManager
if (ActivityCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
&& ActivityCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
Timber.e("******* Do not have Manifest permission for Location access!!")
return
}
try {
locationManager!!.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,
TimeUnit.MINUTES.toMillis(5), 100f, this)
} catch (e: Exception) {
Toast.makeText(this, "Sorry can't do this test, no location service", Toast.LENGTH_LONG)
.show()
}
/*
* FAB button (floating action button = FAB) to get more information
* No more snackbar - until it is "BottomNavigationView" sensitive...
*/
more_button.setOnClickListener {
val myintent = Intent(Intent.ACTION_VIEW)
myintent.data = Uri.parse(
"https://medium.com/freenet-engineering/memory-leaks-in-android-identify-treat-and-avoid-d0b1233acc8#.9sanu6r7h")
startActivity(myintent)
}
}
private fun loadBackdrop() {
val imageView = findViewById<View>(R.id.backdrop) as ImageView
Glide.with(this)
.load(R.drawable.leak_1)
.centerCrop()
.into(imageView)
}
/**
* required methods for LocationListener interface implementation
*/
override fun onLocationChanged(location: Location?) {}
override fun onStatusChanged(s: String?, i: Int, bundle: Bundle?) {}
override fun onProviderEnabled(s: String?) {}
override fun onProviderDisabled(s: String?) {}
override fun onBackPressed() {
val intent = Intent(this, MainActivityKotlin::class.java)
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
startActivity(intent)
}
companion object {
private const val WHOAMI_NAVBAR_MENUID = R.id.action_leak1
const val EXTRA_NAME = "plumber"
}
}
|
apache-2.0
|
73ebebf49e33c728c00e71bf74854f7d
| 37.144444 | 133 | 0.666472 | 4.608054 | false | false | false | false |
ktorio/ktor
|
ktor-shared/ktor-serialization/ktor-serialization-jackson/jvm/src/JacksonWebsocketContentConverter.kt
|
1
|
2043
|
/*
* Copyright 2014-2021 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license.
*/
package io.ktor.serialization.jackson
import com.fasterxml.jackson.core.*
import com.fasterxml.jackson.databind.*
import com.fasterxml.jackson.module.kotlin.*
import io.ktor.serialization.*
import io.ktor.util.reflect.*
import io.ktor.utils.io.charsets.*
import io.ktor.utils.io.core.*
import io.ktor.utils.io.jvm.javaio.*
import io.ktor.websocket.*
import kotlinx.coroutines.*
import java.io.*
/**
* A jackson converter for the [WebSockets] plugin
*/
public class JacksonWebsocketContentConverter(
private val objectmapper: ObjectMapper = jacksonObjectMapper()
) : WebsocketContentConverter {
override suspend fun serializeNullable(charset: Charset, typeInfo: TypeInfo, value: Any?): Frame {
val convertedValue = objectmapper.writeValueAsString(value).toByteArray(charset = charset)
return Frame.Text(true, convertedValue)
}
override suspend fun deserialize(charset: Charset, typeInfo: TypeInfo, content: Frame): Any? {
if (!isApplicable(content)) {
throw WebsocketConverterNotFoundException("Unsupported frame ${content.frameType.name}")
}
try {
return withContext(Dispatchers.IO) {
val data = charset.newDecoder().decode(buildPacket { writeFully(content.readBytes()) })
objectmapper.readValue(data, objectmapper.constructType(typeInfo.reifiedType))
}
} catch (deserializeFailure: Exception) {
val convertException = JsonConvertException("Illegal json parameter found", deserializeFailure)
when (deserializeFailure) {
is JsonParseException -> throw convertException
is JsonMappingException -> throw convertException
else -> throw deserializeFailure
}
}
}
override fun isApplicable(frame: Frame): Boolean {
return frame is Frame.Text || frame is Frame.Binary
}
}
|
apache-2.0
|
e743ee15aeb77063f2171d6b93c44728
| 37.54717 | 119 | 0.696035 | 4.696552 | false | false | false | false |
marius-m/wt4
|
app/src/main/java/lt/markmerkk/ui_2/views/ContextMenuEditLog.kt
|
1
|
3669
|
package lt.markmerkk.ui_2.views
import com.jfoenix.svg.SVGGlyph
import javafx.scene.control.ContextMenu
import javafx.scene.control.MenuItem
import javafx.scene.paint.Color
import lt.markmerkk.Glyph
import lt.markmerkk.Graphics
import lt.markmerkk.Strings
import lt.markmerkk.Tags
import lt.markmerkk.WTEventBus
import lt.markmerkk.WorklogStorage
import lt.markmerkk.entities.LogEditType
import lt.markmerkk.events.EventEditLog
import org.slf4j.LoggerFactory
/**
* Represents a context menu that is reused throughout the app
*/
class ContextMenuEditLog(
private val strings: Strings,
private val graphics: Graphics<SVGGlyph>,
private val eventBus: WTEventBus,
private val worklogStorage: WorklogStorage,
private val editTypes: List<LogEditType>
) {
val root: ContextMenu = ContextMenu()
.apply {
items.addAll(menuItemsFromEditTypes(editTypes, strings, graphics))
setOnAction { event ->
val logEditType = LogEditType.valueOf((event.target as MenuItem).id)
val selectedLogs = selectedLogIds
.mapNotNull { worklogStorage.findById(it) }
eventBus.post(EventEditLog(logEditType, selectedLogs))
}
}
private var selectedLogIds = emptyList<Long>()
/**
* Binds [SimpleLog] that is triggered for editing
*/
fun bindLogs(logIds: List<Long>) {
selectedLogIds = logIds
}
companion object {
val logger = LoggerFactory.getLogger(Tags.INTERNAL)!!
fun menuItemsFromEditTypes(
logEditTypes: List<LogEditType>,
strings: Strings,
graphics: Graphics<SVGGlyph>
): List<MenuItem> {
return logEditTypes.map {
when (it) {
LogEditType.NEW -> MenuItem(
strings.getString("general_new"),
graphics.from(Glyph.NEW, Color.BLACK, 16.0, 16.0)
).apply { id = LogEditType.NEW.name }
LogEditType.UPDATE -> MenuItem(
strings.getString("general_update"),
graphics.from(Glyph.UPDATE, Color.BLACK, 16.0, 16.0)
).apply { id = LogEditType.UPDATE.name }
LogEditType.DELETE -> MenuItem(
strings.getString("general_delete"),
graphics.from(Glyph.DELETE, Color.BLACK, 12.0, 16.0)
).apply { id = LogEditType.DELETE.name }
LogEditType.CLONE -> MenuItem(
strings.getString("general_clone"),
graphics.from(Glyph.CLONE, Color.BLACK, 16.0, 12.0)
).apply { id = LogEditType.CLONE.name }
LogEditType.SPLIT -> MenuItem(
strings.getString("general_split"),
graphics.from(Glyph.SPLIT, Color.BLACK, 16.0, 12.0)
).apply { id = LogEditType.SPLIT.name }
LogEditType.WEBLINK -> MenuItem(
strings.getString("general_weblink"),
graphics.from(Glyph.LINK, Color.BLACK, 14.0, 16.0)
).apply { id = LogEditType.WEBLINK.name }
LogEditType.BROWSER -> MenuItem(
strings.getString("general_browser"),
graphics.from(Glyph.NEW, Color.BLACK, 16.0, 16.0)
).apply { id = LogEditType.BROWSER.name }
}
}
}
}
}
|
apache-2.0
|
8d646e09585b3baf3137956dba1e9508
| 40.704545 | 88 | 0.554374 | 4.74031 | false | false | false | false |
marius-m/wt4
|
remote/src/test/java/lt/markmerkk/interactors/AuthServiceImplTestLoginTest.kt
|
1
|
4971
|
package lt.markmerkk.interactors
import com.nhaarman.mockitokotlin2.*
import lt.markmerkk.JiraMocks
import lt.markmerkk.UserSettings
import net.rcarz.jiraclient.RestException
import org.junit.Assert.assertEquals
import org.junit.Before
import org.junit.Test
import org.mockito.Mock
import org.mockito.MockitoAnnotations
import rx.Single
import rx.schedulers.Schedulers
import rx.schedulers.TestScheduler
class AuthServiceImplTestLoginTest {
@Mock lateinit var view: AuthService.View
@Mock lateinit var authInteractor: AuthService.AuthInteractor
@Mock lateinit var userSettings: UserSettings
lateinit var service: AuthServiceImpl
@Before
fun setUp() {
MockitoAnnotations.initMocks(this)
service = AuthServiceImpl(
view,
Schedulers.immediate(),
Schedulers.immediate(),
authInteractor,
userSettings
)
}
@Test
fun showProgressWhenLoading() {
// Assemble
doReturn(Single.just(JiraMocks.createJiraUser()))
.whenever(authInteractor).jiraTestValidConnection(any(), any(), any())
// Act
service.testLogin(
"valid_host",
"valid_username",
"valid_password"
)
// Assert
verify(view).showProgress()
verify(view).hideProgress()
}
@Test
fun validLogin() {
// Assemble
doReturn(Single.just(JiraMocks.createJiraUser()))
.whenever(authInteractor).jiraTestValidConnection(any(), any(), any())
// Act
service.testLogin(
"valid_host",
"valid_username",
"valid_password"
)
// Assert
val resultCaptor = argumentCaptor<AuthService.AuthResult>()
verify(view).showAuthResult(resultCaptor.capture())
assertEquals(AuthService.AuthResult.SUCCESS, resultCaptor.firstValue)
verify(userSettings).changeJiraUser(any(), any(), any(), any())
}
@Test
fun noInputValues() {
// Assemble
doReturn(Single.error<Any>(IllegalArgumentException("empty hostname")))
.whenever(authInteractor).jiraTestValidConnection(any(), any(), any())
// Act
service.testLogin(
"",
"",
""
)
// Assert
val resultCaptor = argumentCaptor<AuthService.AuthResult>()
verify(view).showAuthResult(resultCaptor.capture())
assertEquals(AuthService.AuthResult.ERROR_EMPTY_FIELDS, resultCaptor.firstValue)
verify(userSettings).resetUserData()
}
@Test
fun validInvalidUnauthorised() {
// Assemble
val restException = RestException(
"message",
401,
"hostname_not_found",
emptyArray()
)
doReturn(Single.error<Any>(RuntimeException(restException)))
.whenever(authInteractor).jiraTestValidConnection(any(), any(), any())
// Act
service.testLogin(
"valid_host",
"valid_username",
"valid_password"
)
// Assert
val resultCaptor = argumentCaptor<AuthService.AuthResult>()
verify(view).showAuthResult(resultCaptor.capture())
assertEquals(AuthService.AuthResult.ERROR_UNAUTHORISED, resultCaptor.firstValue)
verify(userSettings).resetUserData()
}
@Test
fun validInvalidHostname() {
// Assemble
val restException = RestException(
"message",
404,
"hostname_not_found",
emptyArray()
)
doReturn(Single.error<Any>(RuntimeException(restException)))
.whenever(authInteractor).jiraTestValidConnection(any(), any(), any())
// Act
service.testLogin(
"valid_host",
"valid_username",
"valid_password"
)
// Assert
val resultCaptor = argumentCaptor<AuthService.AuthResult>()
verify(view).showAuthResult(resultCaptor.capture())
assertEquals(AuthService.AuthResult.ERROR_INVALID_HOSTNAME, resultCaptor.firstValue)
verify(userSettings).resetUserData()
}
@Test
fun validInvalidUndefined() {
// Assemble
doReturn(Single.error<Any>(RuntimeException()))
.whenever(authInteractor).jiraTestValidConnection(any(), any(), any())
// Act
service.testLogin(
"valid_host",
"valid_username",
"valid_password"
)
// Assert
val resultCaptor = argumentCaptor<AuthService.AuthResult>()
verify(view).showAuthResult(resultCaptor.capture())
assertEquals(AuthService.AuthResult.ERROR_UNDEFINED, resultCaptor.firstValue)
verify(userSettings).resetUserData()
}
}
|
apache-2.0
|
06152376128815864dfd8c0c992a4135
| 29.317073 | 92 | 0.596258 | 5.098462 | false | true | false | false |
WilliamHester/Breadit-2
|
app/app/src/main/java/me/williamhester/reddit/models/managers/AccountManager.kt
|
1
|
1206
|
package me.williamhester.reddit.models.managers
import android.content.SharedPreferences
import android.util.Log
import io.realm.Realm
import me.williamhester.reddit.models.Account
/** A singleton containing the current logged-in account */
class AccountManager(private val sharedPreferences: SharedPreferences) {
var username: String? = null
private set
var accessToken: String? = null
private set
var refreshToken: String? = null
private set
fun setAccount(account: Account?) {
val prefs = sharedPreferences.edit()
prefs.putString("activeUser", account?.username)
prefs.apply()
username = account?.username
accessToken = account?.accessToken
refreshToken = account?.refreshToken
}
val isLoggedIn: Boolean
get() = accessToken != null
init {
val activeUser = sharedPreferences.getString("activeUser", null)
if (activeUser != null) {
Log.d("AccountManager", "Logged in as $activeUser")
setAccount(
Realm.getDefaultInstance()
.where(Account::class.java)
.equalTo("username", activeUser)
.findFirst())
} else {
Log.d("AccountManager", "Not logged in")
}
}
}
|
apache-2.0
|
1e00393de75ff2952a03bd2194ed581c
| 25.217391 | 72 | 0.682421 | 4.62069 | false | false | false | false |
mdanielwork/intellij-community
|
platform/vcs-impl/src/com/intellij/openapi/vcs/changes/ui/DefaultChangesGroupingPolicy.kt
|
6
|
2119
|
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.openapi.vcs.changes.ui
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.Key
import com.intellij.openapi.vcs.FileStatus
import com.intellij.openapi.vcs.changes.ChangeListManager
import javax.swing.tree.DefaultTreeModel
object NoneChangesGroupingPolicy : ChangesGroupingPolicy {
override fun getParentNodeFor(nodePath: StaticFilePath, subtreeRoot: ChangesBrowserNode<*>): ChangesBrowserNode<*>? = null
}
object NoneChangesGroupingFactory : ChangesGroupingPolicyFactory() {
override fun createGroupingPolicy(model: DefaultTreeModel): ChangesGroupingPolicy {
return NoneChangesGroupingPolicy
}
}
class DefaultChangesGroupingPolicy(val project: Project, val model: DefaultTreeModel) : BaseChangesGroupingPolicy() {
override fun getParentNodeFor(nodePath: StaticFilePath, subtreeRoot: ChangesBrowserNode<*>): ChangesBrowserNode<*>? {
val vFile = nodePath.resolve() ?: return null
val status = ChangeListManager.getInstance(project).getStatus(vFile)
if (status == FileStatus.MERGED_WITH_CONFLICTS) {
val cachingRoot = getCachingRoot(subtreeRoot, subtreeRoot)
CONFLICTS_NODE_CACHE[cachingRoot]?.let { return it }
return ChangesBrowserConflictsNode(project).also {
it.markAsHelperNode()
model.insertNodeInto(it, subtreeRoot, subtreeRoot.childCount)
CONFLICTS_NODE_CACHE[cachingRoot] = it
TreeModelBuilder.IS_CACHING_ROOT.set(it, true)
}
}
return null
}
companion object {
val CONFLICTS_NODE_CACHE: Key<ChangesBrowserNode<*>> = Key.create<ChangesBrowserNode<*>>("ChangesTree.ConflictsNodeCache")
}
class Factory @JvmOverloads constructor(val project: Project, val forLocalChanges: Boolean = false) : ChangesGroupingPolicyFactory() {
override fun createGroupingPolicy(model: DefaultTreeModel): ChangesGroupingPolicy =
if (forLocalChanges) DefaultChangesGroupingPolicy(project, model) else NoneChangesGroupingPolicy
}
}
|
apache-2.0
|
49b7473d7314c19ea9cc23f10ab7bc89
| 43.145833 | 140 | 0.775366 | 4.794118 | false | false | false | false |
Scavi/BrainSqueeze
|
src/main/kotlin/com/scavi/brainsqueeze/adventofcode/Day2PasswordPhilosophy.kt
|
1
|
1059
|
package com.scavi.brainsqueeze.adventofcode
class Day2PasswordPhilosophy {
private val split = """(\d+)-(\d+) (.): (.*)""".toRegex()
fun solveA(input: List<String>, policy: (rule: Rule) -> Boolean): Int {
var validPasswords = 0
for (pwSetup in input) {
val rule = parse(pwSetup)
validPasswords = if (policy(rule)) validPasswords + 1 else validPasswords
}
return validPasswords
}
private fun parse(pwSetup: String): Rule {
val (f, t, ch, pass) = split.find(pwSetup)!!.destructured
return Rule(f.toInt(), t.toInt(), ch[0], pass)
}
fun oldPolicyRule(rule: Rule): Boolean {
return rule.pass.filter { it == rule.ch }.count().let { it in rule.f..rule.t }
}
fun newPolicyRule(rule: Rule): Boolean {
return (rule.pass.length >= rule.f && rule.pass[rule.f - 1] == rule.ch) xor
(rule.pass.length >= rule.t && rule.pass[rule.t - 1] == rule.ch)
}
data class Rule(val f: Int, val t: Int, val ch: Char, val pass: String)
}
|
apache-2.0
|
2079654db95ccd3800b282aaef2abc4d
| 34.3 | 86 | 0.584514 | 3.460784 | false | false | false | false |
JetBrains/spek
|
spek-ide-plugin-intellij-base/src/main/kotlin/org/spekframework/intellij/domain/synonym.kt
|
1
|
4370
|
package org.spekframework.intellij.domain
import com.intellij.psi.PsiAnnotation
import com.intellij.psi.PsiArrayInitializerMemberValue
import org.jetbrains.kotlin.asJava.elements.KtLightAnnotationForSourceEntry
import org.jetbrains.kotlin.psi.KtCallExpression
import org.jetbrains.kotlin.psi.KtStringTemplateExpression
enum class PsiSynonymType {
GROUP,
TEST
}
// Keep the defaults in sync with org.spekframework.spek2.meta.Synonym
data class PsiSynonym(val annotation: PsiAnnotation) {
val type: PsiSynonymType by lazy {
val type = annotation.findAttributeValue("type")!!.text
when {
type.endsWith("SynonymType.GROUP") -> PsiSynonymType.GROUP
type.endsWith("SynonymType.TEST") -> PsiSynonymType.TEST
else -> throw IllegalArgumentException("Unsupported synonym: $type.")
}
}
val prefix: String by lazy {
annotation.findAttributeValue("prefix")?.text?.removeSurrounding("\"") ?: ""
}
val excluded: Boolean by lazy {
annotation.findAttributeValue("excluded")?.text?.toBoolean() ?: false
}
val runnable: Boolean by lazy {
annotation.findAttributeValue("runnable")?.text?.toBoolean() ?: true
}
}
enum class PsiDescriptionLocation {
TYPE_PARAMETER,
VALUE_PARAMETER
}
// Keep the defaults in sync with org.spekframework.spek2.meta.Description
class PsiDescription(val annotation: PsiAnnotation) {
val index: Int by lazy {
annotation.findAttributeValue("index")!!.text.toInt()
}
val location: PsiDescriptionLocation by lazy {
val text = annotation.findAttributeValue("location")!!.text
when {
text.endsWith("DescriptionLocation.TYPE_PARAMETER") -> PsiDescriptionLocation.TYPE_PARAMETER
text.endsWith("DescriptionLocation.VALUE_PARAMETER") -> PsiDescriptionLocation.VALUE_PARAMETER
else -> throw IllegalArgumentException("Unknown location type: $text")
}
}
}
class PsiDescriptions(val annotation: PsiAnnotation) {
val sources: Array<PsiDescription> by lazy {
val value = annotation.findAttributeValue("sources")!!
if (value is PsiArrayInitializerMemberValue) {
value.initializers.map { it as PsiAnnotation }
.map(::PsiDescription)
.toTypedArray()
} else if (value is KtLightAnnotationForSourceEntry) {
arrayOf(PsiDescription(value))
} else {
throw AssertionError("Can not defer sources from $value.")
}
}
}
class UnsupportedFeatureException(msg: String): Throwable(msg)
class SynonymContext(val synonym: PsiSynonym, val descriptions: PsiDescriptions) {
fun isExcluded() = synonym.excluded
fun isRunnable() = synonym.runnable
fun constructDescription(callExpression: KtCallExpression): String {
return descriptions.sources.map {
when (it.location) {
PsiDescriptionLocation.TYPE_PARAMETER -> throw UnsupportedFeatureException("Type parameter description is currently unsupported.")
PsiDescriptionLocation.VALUE_PARAMETER -> {
val argument = callExpression.valueArguments.getOrNull(it.index)
val expression = argument?.getArgumentExpression()
when (expression) {
is KtStringTemplateExpression -> {
if (!expression.hasInterpolation()) {
// might be empty at some point, especially when user is still typing
expression.entries.firstOrNull()?.text ?: ""
} else {
throw UnsupportedFeatureException("Descriptions with interpolation are currently unsupported.")
}
}
// can happen when user is still typing
else -> throw UnsupportedFeatureException("Value argument description should be a string.")
}
}
else -> throw IllegalArgumentException("Invalid location: ${it.location}")
}
}.fold(synonym.prefix) { prev, current ->
if (prev.isNotEmpty()) {
"$prev$current"
} else {
current
}
}
}
}
|
bsd-3-clause
|
8637f7dc32212f222252b903e3b5608f
| 37.672566 | 146 | 0.628604 | 5.524652 | false | false | false | false |
dbrant/apps-android-wikipedia
|
app/src/main/java/org/wikipedia/util/MathUtil.kt
|
1
|
654
|
package org.wikipedia.util
object MathUtil {
private const val PERCENTAGE_BASE = 100
@JvmStatic
fun percentage(numerator: Float, denominator: Float): Float {
return numerator / denominator * PERCENTAGE_BASE
}
class Averaged<T : Number?> {
private var sampleSum = 0.0
private var sampleSize = 0
fun addSample(sample: T) {
sampleSum += sample!!.toDouble()
++sampleSize
}
val average: Double
get() = if (sampleSize == 0) 0.0 else sampleSum / sampleSize
fun reset() {
sampleSum = 0.0
sampleSize = 0
}
}
}
|
apache-2.0
|
30f900296a538cbd7b824636cb766f02
| 23.222222 | 72 | 0.561162 | 4.541667 | false | false | false | false |
dahlstrom-g/intellij-community
|
plugins/kotlin/idea/tests/testData/refactoring/move/kotlin/moveNestedClass/nonInnerToTopLevelClass/after/test.kt
|
13
|
538
|
package test
inline fun <T, R> with(receiver: T, block: T.() -> R): R = receiver.block()
class A {
class B {
class X {
}
companion object {
class Y
fun foo(n: Int) {}
val bar = 1
fun Int.extFoo(n: Int) {}
val Int.extBar: Int get() = 1
}
object O {
class Y
fun foo(n: Int) {}
val bar = 1
fun Int.extFoo(n: Int) {}
val Int.extBar: Int get() = 1
}
}
}
|
apache-2.0
|
d99c0800d5d02f47f22229b4b227f5e8
| 13.972222 | 75 | 0.394052 | 3.870504 | false | false | false | false |
ogarcia/ultrasonic
|
core/subsonic-api/src/main/kotlin/org/moire/ultrasonic/api/subsonic/SubsonicAPIDefinition.kt
|
2
|
11080
|
package org.moire.ultrasonic.api.subsonic
import okhttp3.ResponseBody
import org.moire.ultrasonic.api.subsonic.models.AlbumListType
import org.moire.ultrasonic.api.subsonic.models.JukeboxAction
import org.moire.ultrasonic.api.subsonic.response.BookmarksResponse
import org.moire.ultrasonic.api.subsonic.response.ChatMessagesResponse
import org.moire.ultrasonic.api.subsonic.response.GenresResponse
import org.moire.ultrasonic.api.subsonic.response.GetAlbumList2Response
import org.moire.ultrasonic.api.subsonic.response.GetAlbumListResponse
import org.moire.ultrasonic.api.subsonic.response.GetAlbumResponse
import org.moire.ultrasonic.api.subsonic.response.GetArtistResponse
import org.moire.ultrasonic.api.subsonic.response.GetArtistsResponse
import org.moire.ultrasonic.api.subsonic.response.GetIndexesResponse
import org.moire.ultrasonic.api.subsonic.response.GetLyricsResponse
import org.moire.ultrasonic.api.subsonic.response.GetMusicDirectoryResponse
import org.moire.ultrasonic.api.subsonic.response.GetPlaylistResponse
import org.moire.ultrasonic.api.subsonic.response.GetPlaylistsResponse
import org.moire.ultrasonic.api.subsonic.response.GetPodcastsResponse
import org.moire.ultrasonic.api.subsonic.response.GetRandomSongsResponse
import org.moire.ultrasonic.api.subsonic.response.GetSongsByGenreResponse
import org.moire.ultrasonic.api.subsonic.response.GetStarredResponse
import org.moire.ultrasonic.api.subsonic.response.GetStarredTwoResponse
import org.moire.ultrasonic.api.subsonic.response.GetUserResponse
import org.moire.ultrasonic.api.subsonic.response.JukeboxResponse
import org.moire.ultrasonic.api.subsonic.response.LicenseResponse
import org.moire.ultrasonic.api.subsonic.response.MusicFoldersResponse
import org.moire.ultrasonic.api.subsonic.response.SearchResponse
import org.moire.ultrasonic.api.subsonic.response.SearchThreeResponse
import org.moire.ultrasonic.api.subsonic.response.SearchTwoResponse
import org.moire.ultrasonic.api.subsonic.response.SharesResponse
import org.moire.ultrasonic.api.subsonic.response.SubsonicResponse
import org.moire.ultrasonic.api.subsonic.response.VideosResponse
import retrofit2.Call
import retrofit2.http.GET
import retrofit2.http.Header
import retrofit2.http.Query
import retrofit2.http.Streaming
/**
* Subsonic API calls.
*
* For methods description see [http://www.subsonic.org/pages/api.jsp].
*/
@Suppress("TooManyFunctions", "LongParameterList")
interface SubsonicAPIDefinition {
@GET("ping.view")
fun ping(): Call<SubsonicResponse>
@GET("getLicense.view")
fun getLicense(): Call<LicenseResponse>
@GET("getMusicFolders.view")
fun getMusicFolders(): Call<MusicFoldersResponse>
@GET("getIndexes.view")
fun getIndexes(
@Query("musicFolderId") musicFolderId: String?,
@Query("ifModifiedSince") ifModifiedSince: Long?
): Call<GetIndexesResponse>
@GET("getMusicDirectory.view")
fun getMusicDirectory(@Query("id") id: String): Call<GetMusicDirectoryResponse>
@GET("getArtists.view")
fun getArtists(@Query("musicFolderId") musicFolderId: String?): Call<GetArtistsResponse>
@GET("star.view")
fun star(
@Query("id") id: String? = null,
@Query("albumId") albumId: String? = null,
@Query("artistId") artistId: String? = null
): Call<SubsonicResponse>
@GET("unstar.view")
fun unstar(
@Query("id") id: String? = null,
@Query("albumId") albumId: String? = null,
@Query("artistId") artistId: String? = null
): Call<SubsonicResponse>
@GET("setRating.view")
fun setRating(
@Query("id") id: String,
@Query("rating") rating: Int
): Call<SubsonicResponse>
@GET("getArtist.view")
fun getArtist(@Query("id") id: String): Call<GetArtistResponse>
@GET("getAlbum.view")
fun getAlbum(@Query("id") id: String): Call<GetAlbumResponse>
@GET("search.view")
fun search(
@Query("artist") artist: String? = null,
@Query("album") album: String? = null,
@Query("title") title: String? = null,
@Query("any") any: String? = null,
@Query("count") count: Int? = null,
@Query("offset") offset: Int? = null,
@Query("newerThan") newerThan: Long? = null
): Call<SearchResponse>
@GET("search2.view")
fun search2(
@Query("query") query: String,
@Query("artistCount") artistCount: Int? = null,
@Query("artistOffset") artistOffset: Int? = null,
@Query("albumCount") albumCount: Int? = null,
@Query("albumOffset") albumOffset: Int? = null,
@Query("songCount") songCount: Int? = null,
@Query("musicFolderId") musicFolderId: String? = null
): Call<SearchTwoResponse>
@GET("search3.view")
fun search3(
@Query("query") query: String,
@Query("artistCount") artistCount: Int? = null,
@Query("artistOffset") artistOffset: Int? = null,
@Query("albumCount") albumCount: Int? = null,
@Query("albumOffset") albumOffset: Int? = null,
@Query("songCount") songCount: Int? = null,
@Query("musicFolderId") musicFolderId: String? = null
): Call<SearchThreeResponse>
@GET("getPlaylist.view")
fun getPlaylist(@Query("id") id: String): Call<GetPlaylistResponse>
@GET("getPlaylists.view")
fun getPlaylists(@Query("username") username: String? = null): Call<GetPlaylistsResponse>
@GET("createPlaylist.view")
fun createPlaylist(
@Query("playlistId") id: String? = null,
@Query("name") name: String? = null,
@Query("songId") songIds: List<String>? = null
): Call<SubsonicResponse>
@GET("deletePlaylist.view")
fun deletePlaylist(@Query("id") id: String): Call<SubsonicResponse>
@GET("updatePlaylist.view")
fun updatePlaylist(
@Query("playlistId") id: String,
@Query("name") name: String? = null,
@Query("comment") comment: String? = null,
@Query("public") public: Boolean? = null,
@Query("songIdToAdd") songIdsToAdd: List<String>? = null,
@Query("songIndexToRemove") songIndexesToRemove: List<Int>? = null
):
Call<SubsonicResponse>
@GET("getPodcasts.view")
fun getPodcasts(
@Query("includeEpisodes") includeEpisodes: Boolean? = null,
@Query("id") id: String? = null
): Call<GetPodcastsResponse>
@GET("getLyrics.view")
fun getLyrics(
@Query("artist") artist: String? = null,
@Query("title") title: String? = null
): Call<GetLyricsResponse>
@GET("scrobble.view")
fun scrobble(
@Query("id") id: String,
@Query("time") time: Long? = null,
@Query("submission") submission: Boolean? = null
): Call<SubsonicResponse>
@GET("getAlbumList.view")
fun getAlbumList(
@Query("type") type: AlbumListType,
@Query("size") size: Int? = null,
@Query("offset") offset: Int? = null,
@Query("fromYear") fromYear: Int? = null,
@Query("toYear") toYear: Int? = null,
@Query("genre") genre: String? = null,
@Query("musicFolderId") musicFolderId: String? = null
): Call<GetAlbumListResponse>
@GET("getAlbumList2.view")
fun getAlbumList2(
@Query("type") type: AlbumListType,
@Query("size") size: Int? = null,
@Query("offset") offset: Int? = null,
@Query("fromYear") fromYear: Int? = null,
@Query("toYear") toYear: Int? = null,
@Query("genre") genre: String? = null,
@Query("musicFolderId") musicFolderId: String? = null
): Call<GetAlbumList2Response>
@GET("getRandomSongs.view")
fun getRandomSongs(
@Query("size") size: Int? = null,
@Query("genre") genre: String? = null,
@Query("fromYear") fromYear: Int? = null,
@Query("toYear") toYear: Int? = null,
@Query("musicFolderId") musicFolderId: String? = null
): Call<GetRandomSongsResponse>
@GET("getStarred.view")
fun getStarred(@Query("musicFolderId") musicFolderId: String? = null): Call<GetStarredResponse>
@GET("getStarred2.view")
fun getStarred2(
@Query("musicFolderId") musicFolderId: String? = null
): Call<GetStarredTwoResponse>
@Streaming
@GET("getCoverArt.view")
fun getCoverArt(
@Query("id") id: String,
@Query("size") size: Long? = null
): Call<ResponseBody>
@Streaming
@GET("stream.view")
fun stream(
@Query("id") id: String,
@Query("maxBitRate") maxBitRate: Int? = null,
@Query("format") format: String? = null,
@Query("timeOffset") timeOffset: Int? = null,
@Query("size") videoSize: String? = null,
@Query("estimateContentLength") estimateContentLength: Boolean? = null,
@Query("converted") converted: Boolean? = null,
@Header("Range") offset: Long? = null
): Call<ResponseBody>
@GET("jukeboxControl.view")
fun jukeboxControl(
@Query("action") action: JukeboxAction,
@Query("index") index: Int? = null,
@Query("offset") offset: Int? = null,
@Query("id") ids: List<String>? = null,
@Query("gain") gain: Float? = null
): Call<JukeboxResponse>
@GET("getShares.view")
fun getShares(): Call<SharesResponse>
@GET("createShare.view")
fun createShare(
@Query("id") idsToShare: List<String>,
@Query("description") description: String? = null,
@Query("expires") expires: Long? = null
): Call<SharesResponse>
@GET("deleteShare.view")
fun deleteShare(@Query("id") id: String): Call<SubsonicResponse>
@GET("updateShare.view")
fun updateShare(
@Query("id") id: String,
@Query("description") description: String? = null,
@Query("expires") expires: Long? = null
): Call<SubsonicResponse>
@GET("getGenres.view")
fun getGenres(): Call<GenresResponse>
@GET("getSongsByGenre.view")
fun getSongsByGenre(
@Query("genre") genre: String,
@Query("count") count: Int = 10,
@Query("offset") offset: Int = 0,
@Query("musicFolderId") musicFolderId: String? = null
): Call<GetSongsByGenreResponse>
@GET("getUser.view")
fun getUser(@Query("username") username: String): Call<GetUserResponse>
@GET("getChatMessages.view")
fun getChatMessages(@Query("since") since: Long? = null): Call<ChatMessagesResponse>
@GET("addChatMessage.view")
fun addChatMessage(@Query("message") message: String): Call<SubsonicResponse>
@GET("getBookmarks.view")
fun getBookmarks(): Call<BookmarksResponse>
@GET("createBookmark.view")
fun createBookmark(
@Query("id") id: String,
@Query("position") position: Long,
@Query("comment") comment: String? = null
): Call<SubsonicResponse>
@GET("deleteBookmark.view")
fun deleteBookmark(@Query("id") id: String): Call<SubsonicResponse>
@GET("getVideos.view")
fun getVideos(): Call<VideosResponse>
@GET("getAvatar.view")
fun getAvatar(@Query("username") username: String): Call<ResponseBody>
}
|
gpl-3.0
|
88db59f8fdac396da81a9650f90ed589
| 36.056856 | 99 | 0.671209 | 3.844552 | false | false | false | false |
dahlstrom-g/intellij-community
|
plugins/markdown/core/src/org/intellij/plugins/markdown/lang/psi/impl/MarkdownHeaderContent.kt
|
7
|
1243
|
package org.intellij.plugins.markdown.lang.psi.impl
import com.intellij.extapi.psi.ASTWrapperPsiElement
import com.intellij.lang.ASTNode
import com.intellij.openapi.util.TextRange
import com.intellij.psi.PsiWhiteSpace
import org.intellij.plugins.markdown.lang.MarkdownTokenTypes
import org.intellij.plugins.markdown.lang.psi.MarkdownPsiElement
import org.intellij.plugins.markdown.lang.psi.util.children
import org.intellij.plugins.markdown.lang.psi.util.hasType
/**
* Corresponds to:
* ```
* # Some header
* ^----------^
* ```
* (starting whitespaces are included).
*/
class MarkdownHeaderContent(node: ASTNode): ASTWrapperPsiElement(node), MarkdownPsiElement {
/**
* Range inside this element, excluding starting whitespaces.
*/
val nonWhitespaceRange: TextRange
get() = when (val child = children().filterNot { it is PsiWhiteSpace }.firstOrNull()) {
null -> TextRange(0, textLength)
else -> TextRange(child.startOffsetInParent, textLength)
}
val isSetextContent: Boolean
get() = node.hasType(MarkdownTokenTypes.SETEXT_CONTENT)
val isAtxContent: Boolean
get() = node.hasType(MarkdownTokenTypes.ATX_CONTENT)
val relevantContent: String
get() = nonWhitespaceRange.substring(text)
}
|
apache-2.0
|
5ae28f3bfbd2100012255a711f85b44c
| 31.710526 | 92 | 0.752212 | 4.171141 | false | false | false | false |
tateisu/SubwayTooter
|
apng/src/main/java/jp/juggler/apng/ApngPalette.kt
|
1
|
982
|
@file:Suppress("JoinDeclarationAndAssignment", "MemberVisibilityCanBePrivate")
package jp.juggler.apng
import jp.juggler.apng.util.getUInt8
import kotlin.math.min
class ApngPalette(
src : ByteArray // repeat of R,G,B
) {
companion object {
// full opaque black
const val OPAQUE = 255 shl 24
}
val list : IntArray // repeat of 0xAARRGGBB
var hasAlpha : Boolean = false
init {
val entryCount = src.size / 3
list = IntArray(entryCount)
var pos = 0
for(i in 0 until entryCount) {
list[i] = OPAQUE or
(src.getUInt8(pos) shl 16) or
(src.getUInt8(pos + 1) shl 8) or
src.getUInt8(pos + 2)
pos += 3
}
}
override fun toString() = "palette(${list.size} entries,hasAlpha=$hasAlpha)"
// update alpha value from tRNS chunk data
fun parseTRNS(ba : ByteArray) {
hasAlpha = true
for(i in 0 until min(list.size, ba.size)) {
list[i] = (list[i] and 0xffffff) or (ba.getUInt8(i) shl 24)
}
}
}
|
apache-2.0
|
4133faedc2ba379782eda290f5fe4738
| 20.837209 | 78 | 0.639511 | 2.766197 | false | false | false | false |
tateisu/SubwayTooter
|
app/src/main/java/jp/juggler/subwaytooter/table/MutedWord.kt
|
1
|
3491
|
package jp.juggler.subwaytooter.table
import android.content.ContentValues
import android.database.Cursor
import android.database.sqlite.SQLiteDatabase
import jp.juggler.subwaytooter.global.appDatabase
import jp.juggler.util.LogCategory
import jp.juggler.util.TableCompanion
import jp.juggler.util.WordTrieTree
object MutedWord : TableCompanion {
private val log = LogCategory("MutedWord")
override val table = "word_mute"
const val COL_ID = "_id"
const val COL_NAME = "name"
private const val COL_TIME_SAVE = "time_save"
override fun onDBCreate(db: SQLiteDatabase) {
log.d("onDBCreate!")
db.execSQL(
"""create table if not exists $table
($COL_ID INTEGER PRIMARY KEY
,$COL_NAME text not null
,$COL_TIME_SAVE integer not null
)""".trimIndent()
)
db.execSQL("create unique index if not exists ${table}_name on $table(name)")
}
override fun onDBUpgrade(db: SQLiteDatabase, oldVersion: Int, newVersion: Int) {
if (oldVersion < 11 && newVersion >= 11) {
onDBCreate(db)
}
}
fun save(word: String?) {
if (word == null) return
try {
val now = System.currentTimeMillis()
val cv = ContentValues()
cv.put(COL_NAME, word)
cv.put(COL_TIME_SAVE, now)
appDatabase.replace(table, null, cv)
} catch (ex: Throwable) {
log.e(ex, "save failed.")
}
}
fun createCursor(): Cursor {
return appDatabase.query(table, null, null, null, null, null, "$COL_NAME asc")
}
fun delete(name: String) {
try {
appDatabase.delete(table, "$COL_NAME=?", arrayOf(name))
} catch (ex: Throwable) {
log.e(ex, "delete failed.")
}
}
// private static final String[] isMuted_projection = new String[]{COL_NAME};
// private static final String isMuted_where = COL_NAME+"=?";
// private static final ThreadLocal<String[]> isMuted_where_arg = new ThreadLocal<String[]>() {
// @Override protected String[] initialValue() {
// return new String[1];
// }
// };
// public static boolean isMuted( String app_name ){
// if( app_name == null ) return false;
// try{
// String[] where_arg = isMuted_where_arg.get();
// where_arg[0] = app_name;
// Cursor cursor = App1.getDB().query( table, isMuted_projection,isMuted_where , where_arg, null, null, null );
// try{
// if( cursor.moveToFirst() ){
// return true;
// }
// }finally{
// cursor.close();
// }
// }catch( Throwable ex ){
// warning.e( ex, "load failed." );
// }
// return false;
// }
val nameSet: WordTrieTree
get() {
val dst = WordTrieTree()
try {
appDatabase.query(table, null, null, null, null, null, null)
.use { cursor ->
val idx_name = cursor.getColumnIndex(COL_NAME)
while (cursor.moveToNext()) {
val s = cursor.getString(idx_name)
dst.add(s)
}
}
} catch (ex: Throwable) {
log.trace(ex)
}
return dst
}
}
|
apache-2.0
|
a9a011e5d9f4053c04d2ed9a4b2bf55c
| 30.324074 | 117 | 0.526497 | 4.059302 | false | false | false | false |
BreakOutEvent/breakout-backend
|
src/main/java/backend/view/TeamView.kt
|
1
|
2435
|
package backend.view
import backend.model.event.Team
import backend.model.removeBlockedBy
import backend.util.data.DonateSums
import backend.view.user.BasicUserView
import org.hibernate.validator.constraints.SafeHtml
import org.hibernate.validator.constraints.SafeHtml.WhiteListType.NONE
import java.util.*
import javax.validation.Valid
class TeamView() {
var id: Long? = null
@Valid
@SafeHtml(whitelistType = NONE)
var name: String? = null
var event: Long? = null
@Valid
@SafeHtml(whitelistType = NONE)
var description: String? = null
var hasStarted: Boolean? = null
var members: MutableList<BasicUserView>? = null
var profilePic: MediaView? = null
var invoiceId: Long? = null
var hasFullyPaid: Boolean? = null
var isFull: Boolean? = null
var distance: Double? = null
var donateSum: DonateSums? = null
var score: Double? = null
var asleep: Boolean? = null
var postaddress: String? = null
constructor(team: Team, userId: Long?) : this() {
this.id = team.id
this.name = team.name
this.event = team.event.id
this.description = team.description
this.members = ArrayList()
team.members.removeBlockedBy(userId).forEach { this.members!!.add(BasicUserView(it)) }
this.profilePic = team.profilePic?.let(::MediaView)
this.invoiceId = team.invoice?.id
this.hasStarted = team.hasStarted
this.hasFullyPaid = team.invoice?.isFullyPaid() ?: true
this.isFull = team.isFull()
this.asleep = team.asleep
this.postaddress = team.postaddress
}
constructor(team: Team, distance: Double, donateSum: DonateSums, score: Double, userId: Long?) : this() {
this.id = team.id
this.name = team.name
this.event = team.event.id
this.description = team.description
this.members = ArrayList()
team.members.removeBlockedBy(userId).forEach { this.members!!.add(BasicUserView(it)) }
this.profilePic = team.profilePic?.let(::MediaView)
this.invoiceId = team.invoice?.id
this.hasStarted = team.hasStarted
this.hasFullyPaid = team.invoice?.isFullyPaid() ?: true
this.isFull = team.isFull()
this.distance = distance
this.donateSum = donateSum
this.score = score
this.asleep = team.asleep
this.postaddress = team.postaddress
}
}
|
agpl-3.0
|
de94e3b7f3587392721358129fcc4382
| 27.313953 | 109 | 0.66037 | 4.024793 | false | false | false | false |
paplorinc/intellij-community
|
python/src/com/jetbrains/python/sdk/add/PyAddSdkGroupPanel.kt
|
7
|
3558
|
/*
* 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.sdk.add
import com.intellij.openapi.projectRoots.Sdk
import com.intellij.openapi.ui.ValidationInfo
import com.intellij.ui.components.JBRadioButton
import com.intellij.util.ui.FormBuilder
import com.intellij.util.ui.JBUI
import com.intellij.util.ui.UIUtil
import java.awt.BorderLayout
import javax.swing.ButtonGroup
import javax.swing.Icon
import javax.swing.JComponent
import javax.swing.JPanel
/**
* @author vlan
*/
class PyAddSdkGroupPanel(name: String,
panelIcon: Icon,
val panels: List<PyAddSdkPanel>,
defaultPanel: PyAddSdkPanel) : PyAddSdkPanel() {
override val panelName: String = name
override val icon: Icon = panelIcon
var selectedPanel: PyAddSdkPanel = defaultPanel
private val changeListeners: MutableList<Runnable> = mutableListOf()
override var newProjectPath: String?
get() = selectedPanel.newProjectPath
set(value) {
for (panel in panels) {
panel.newProjectPath = value
}
}
init {
layout = BorderLayout()
val contentPanel = when (panels.size) {
1 -> panels[0]
else -> createRadioButtonPanel(panels, defaultPanel)
}
add(contentPanel, BorderLayout.NORTH)
}
override fun validateAll(): List<ValidationInfo> = panels.filter { it.isEnabled }.flatMap { it.validateAll() }
override val sdk: Sdk?
get() = selectedPanel.sdk
override fun getOrCreateSdk(): Sdk? = selectedPanel.getOrCreateSdk()
override fun addChangeListener(listener: Runnable) {
changeListeners += listener
for (panel in panels) {
panel.addChangeListener(listener)
}
}
private fun createRadioButtonPanel(panels: List<PyAddSdkPanel>, defaultPanel: PyAddSdkPanel): JPanel? {
val buttonMap = panels.map { JBRadioButton(it.panelName) to it }.toMap(linkedMapOf())
ButtonGroup().apply {
for (button in buttonMap.keys) {
add(button)
}
}
val formBuilder = FormBuilder.createFormBuilder()
for ((button, panel) in buttonMap) {
panel.border = JBUI.Borders.emptyLeft(30)
val name: JComponent = panel.nameExtensionComponent?.let {
JPanel(BorderLayout()).apply {
val inner = JPanel().apply {
add(button)
add(it)
}
add(inner, BorderLayout.WEST)
}
} ?: button
formBuilder.addComponent(name)
formBuilder.addComponent(panel)
button.addItemListener {
for (c in panels) {
UIUtil.setEnabled(c, c == panel, true)
c.nameExtensionComponent?.let {
UIUtil.setEnabled(it, c == panel, true)
}
}
if (button.isSelected) {
selectedPanel = panel
for (listener in changeListeners) {
listener.run()
}
}
}
}
buttonMap.filterValues { it == defaultPanel }.keys.first().isSelected = true
return formBuilder.panel
}
}
|
apache-2.0
|
7817496a6f5e08a2141b2979b5ef2b22
| 30.776786 | 112 | 0.666386 | 4.492424 | false | false | false | false |
google/intellij-community
|
plugins/maven/src/main/java/org/jetbrains/idea/maven/execution/run/configuration/MavenRunConfigurationSettingsEditor.kt
|
5
|
27645
|
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.idea.maven.execution.run.configuration
import com.intellij.compiler.options.CompileStepBeforeRun
import com.intellij.diagnostic.logging.LogsGroupFragment
import com.intellij.execution.ExecutionBundle
import com.intellij.execution.configurations.RuntimeConfigurationError
import com.intellij.execution.impl.RunnerAndConfigurationSettingsImpl
import com.intellij.execution.ui.*
import com.intellij.ide.plugins.newui.HorizontalLayout
import com.intellij.openapi.externalSystem.service.execution.configuration.*
import com.intellij.openapi.externalSystem.service.ui.getSelectedJdkReference
import com.intellij.openapi.externalSystem.service.ui.project.path.WorkingDirectoryField
import com.intellij.openapi.externalSystem.service.ui.properties.PropertiesFiled
import com.intellij.openapi.externalSystem.service.ui.properties.PropertiesInfo
import com.intellij.openapi.externalSystem.service.ui.properties.PropertiesTable
import com.intellij.openapi.externalSystem.service.ui.setSelectedJdkReference
import com.intellij.openapi.externalSystem.service.ui.util.LabeledSettingsFragmentInfo
import com.intellij.openapi.externalSystem.service.ui.util.PathFragmentInfo
import com.intellij.openapi.externalSystem.service.ui.util.SettingsFragmentInfo
import com.intellij.openapi.fileChooser.FileChooserDescriptorFactory
import com.intellij.openapi.observable.operations.AnonymousParallelOperationTrace
import com.intellij.openapi.observable.operations.AnonymousParallelOperationTrace.Companion.task
import com.intellij.openapi.options.ShowSettingsUtil
import com.intellij.openapi.roots.ui.configuration.SdkComboBox
import com.intellij.openapi.roots.ui.configuration.SdkComboBoxModel.Companion.createProjectJdkComboBoxModel
import com.intellij.openapi.roots.ui.configuration.SdkLookupProvider
import com.intellij.openapi.roots.ui.distribution.DistributionComboBox
import com.intellij.openapi.roots.ui.distribution.FileChooserInfo
import com.intellij.openapi.ui.TextFieldWithBrowseButton
import com.intellij.openapi.util.NlsContexts
import com.intellij.ui.components.ActionLink
import com.intellij.ui.components.JBTextField
import com.intellij.ui.dsl.builder.columns
import com.intellij.ui.dsl.builder.impl.CollapsibleTitledSeparatorImpl
import com.intellij.openapi.observable.util.lockOrSkip
import com.intellij.openapi.ui.getCanonicalPath
import com.intellij.util.ui.UIUtil
import org.jetbrains.annotations.Nls
import org.jetbrains.idea.maven.execution.MavenRunConfiguration
import org.jetbrains.idea.maven.execution.MavenRunner
import org.jetbrains.idea.maven.execution.MavenRunnerSettings
import org.jetbrains.idea.maven.execution.RunnerBundle
import org.jetbrains.idea.maven.execution.run.configuration.MavenDistributionsInfo.Companion.asDistributionInfo
import org.jetbrains.idea.maven.execution.run.configuration.MavenDistributionsInfo.Companion.asMavenHome
import org.jetbrains.idea.maven.project.MavenConfigurableBundle
import org.jetbrains.idea.maven.project.MavenGeneralSettings
import org.jetbrains.idea.maven.project.MavenProjectBundle
import org.jetbrains.idea.maven.project.MavenProjectsManager
import org.jetbrains.idea.maven.server.MavenServerManager
import org.jetbrains.idea.maven.utils.MavenUtil
import org.jetbrains.idea.maven.utils.MavenWslUtil
import java.awt.Component
import java.util.concurrent.atomic.AtomicBoolean
import javax.swing.JCheckBox
import javax.swing.JComponent
import javax.swing.JLabel
import javax.swing.JPanel
class MavenRunConfigurationSettingsEditor(
runConfiguration: MavenRunConfiguration
) : RunConfigurationFragmentedEditor<MavenRunConfiguration>(
runConfiguration,
runConfiguration.extensionsManager
) {
private val resetOperation = AnonymousParallelOperationTrace()
override fun resetEditorFrom(s: RunnerAndConfigurationSettingsImpl) {
resetOperation.task {
super.resetEditorFrom(s)
}
}
override fun resetEditorFrom(settings: MavenRunConfiguration) {
resetOperation.task {
super.resetEditorFrom(settings)
}
}
override fun createRunFragments() = SettingsFragmentsContainer.fragments<MavenRunConfiguration> {
add(CommonParameterFragments.createRunHeader())
addBeforeRunFragment(CompileStepBeforeRun.ID)
addAll(BeforeRunFragment.createGroup())
add(CommonTags.parallelRun())
val workingDirectoryField = addWorkingDirectoryFragment().component().component
addCommandLineFragment(workingDirectoryField)
addProfilesFragment(workingDirectoryField)
addMavenOptionsGroupFragment()
addJavaOptionsGroupFragment()
add(LogsGroupFragment())
}
private val MavenRunConfiguration.generalSettingsOrDefault: MavenGeneralSettings
get() = generalSettings ?: MavenProjectsManager.getInstance(project).generalSettings.clone()
private val MavenRunConfiguration.runnerSettingsOrDefault: MavenRunnerSettings
get() = runnerSettings ?: MavenRunner.getInstance(project).settings.clone()
private fun SettingsFragmentsContainer<MavenRunConfiguration>.addMavenOptionsGroupFragment() =
addOptionsGroup(
"maven.general.options.group",
MavenConfigurableBundle.message("maven.run.configuration.general.options.group.name"),
MavenConfigurableBundle.message("maven.run.configuration.general.options.group"),
MavenProjectBundle.message("configurable.MavenSettings.display.name"),
{ generalSettings },
{ generalSettingsOrDefault },
{ generalSettings = it }
) {
val distributionComponent = addDistributionFragment().component().component
val userSettingsComponent = addUserSettingsFragment().component().component
addLocalRepositoryFragment(distributionComponent, userSettingsComponent)
addOutputLevelFragment()
addThreadsFragment()
addUsePluginRegistryTag()
addPrintStacktracesTag()
addUpdateSnapshotsTag()
addExecuteNonRecursivelyTag()
addWorkOfflineTag()
addCheckSumPolicyTag()
addMultiProjectBuildPolicyTag()
}
private fun SettingsFragmentsContainer<MavenRunConfiguration>.addJavaOptionsGroupFragment() =
addOptionsGroup(
"maven.runner.options.group",
MavenConfigurableBundle.message("maven.run.configuration.runner.options.group.name"),
MavenConfigurableBundle.message("maven.run.configuration.runner.options.group"),
RunnerBundle.message("maven.tab.runner"),
{ runnerSettings },
{ runnerSettingsOrDefault },
{ runnerSettings = it }
) {
addJreFragment()
addEnvironmentFragment()
addVmOptionsFragment()
addPropertiesFragment()
addSkipTestsTag()
addResolveWorkspaceArtifactsTag()
}
private fun <S : FragmentedSettings, Settings> SettingsFragmentsContainer<S>.addOptionsGroup(
id: String,
name: @Nls(capitalization = Nls.Capitalization.Sentence) String,
group: @Nls(capitalization = Nls.Capitalization.Title) String,
settingsName: @NlsContexts.ConfigurableName String,
getSettings: S.() -> Settings?,
getDefaultSettings: S.() -> Settings,
setSettings: S.(Settings?) -> Unit,
configure: SettingsFragmentsContainer<S>.() -> Unit
) = add(object : NestedGroupFragment<S>(id, name, group, { true }) {
private val separator = CollapsibleTitledSeparatorImpl(group)
private val checkBox: JCheckBox
private val checkBoxWithLink: JComponent
init {
val labelText = MavenConfigurableBundle.message("maven.run.configuration.options.group.inherit")
@Suppress("HardCodedStringLiteral") val leadingLabelText = labelText.substringBefore("<a>")
@Suppress("HardCodedStringLiteral") val linkLabelText = labelText.substringAfter("<a>").substringBefore("</a>")
@Suppress("HardCodedStringLiteral") val trailingLabelText = labelText.substringAfter("</a>")
checkBox = JCheckBox(leadingLabelText)
checkBoxWithLink = JPanel().apply {
layout = HorizontalLayout(0)
add(checkBox)
add(ActionLink(linkLabelText) {
val showSettingsUtil = ShowSettingsUtil.getInstance()
showSettingsUtil.showSettingsDialog(project, settingsName)
})
add(JLabel(trailingLabelText))
}
}
override fun createChildren() = SettingsFragmentsContainer.fragments<S> {
addSettingsEditorFragment(
checkBoxWithLink,
object : SettingsFragmentInfo {
override val settingsId: String = "$id.checkbox"
override val settingsName: String? = null
override val settingsGroup: String? = null
override val settingsPriority: Int = 0
override val settingsType = SettingsEditorFragmentType.EDITOR
override val settingsHint: String? = null
override val settingsActionHint: String? = null
},
{ it, _ -> checkBox.isSelected = it.getSettings() == null },
{ it, _ -> it.setSettings(if (checkBox.isSelected) null else (it.getSettings() ?: it.getDefaultSettings())) }
)
for (fragment in SettingsFragmentsContainer.fragments(configure)) {
bind(checkBox, fragment)
add(fragment)
}
}
override fun getBuilder() = object : FragmentedSettingsBuilder<S>(children, this, this) {
override fun createHeaderSeparator() = separator
override fun addLine(component: Component, top: Int, left: Int, bottom: Int) {
if (component === checkBoxWithLink) {
super.addLine(component, top, left, bottom + TOP_INSET)
myGroupInset += LEFT_INSET
}
else {
super.addLine(component, top, left, bottom)
}
}
init {
children.forEach { bind(separator, it) }
resetOperation.afterOperation {
separator.expanded = !checkBox.isSelected
}
}
}
}).apply { isRemovable = false }
private fun bind(checkBox: JCheckBox, fragment: SettingsEditorFragment<*, *>) {
checkBox.addItemListener {
val component = fragment.component()
if (component != null) {
UIUtil.setEnabledRecursively(component, !checkBox.isSelected)
}
}
fragment.addSettingsEditorListener {
if (resetOperation.isOperationCompleted()) {
checkBox.isSelected = false
}
}
}
private fun bind(separator: CollapsibleTitledSeparatorImpl, fragment: SettingsEditorFragment<*, *>) {
val mutex = AtomicBoolean()
separator.onAction {
mutex.lockOrSkip {
fragment.component.isVisible = fragment.isSelected && separator.expanded
fragment.hintComponent?.isVisible = fragment.isSelected && separator.expanded
}
}
fragment.addSettingsEditorListener {
mutex.lockOrSkip {
if (resetOperation.isOperationCompleted()) {
separator.expanded = true
}
}
}
}
private fun SettingsFragmentsContainer<MavenRunConfiguration>.addSkipTestsTag() {
addTag(
"maven.skip.tests.tag",
MavenConfigurableBundle.message("maven.settings.runner.skip.tests"),
MavenConfigurableBundle.message("maven.run.configuration.runner.options.group"),
null,
{ runnerSettingsOrDefault.isSkipTests },
{ runnerSettingsOrDefault.isSkipTests = it }
)
}
private fun SettingsFragmentsContainer<MavenRunConfiguration>.addUsePluginRegistryTag() {
addTag(
"maven.use.plugin.registry.tag",
MavenConfigurableBundle.message("maven.settings.general.use.plugin.registry"),
MavenConfigurableBundle.message("maven.run.configuration.general.options.group"),
MavenConfigurableBundle.message("maven.settings.general.use.plugin.registry.tooltip"),
{ generalSettingsOrDefault.isUsePluginRegistry },
{ generalSettingsOrDefault.isUsePluginRegistry = it }
)
}
private fun SettingsFragmentsContainer<MavenRunConfiguration>.addPrintStacktracesTag() {
addTag(
"maven.print.stacktraces.tag",
MavenConfigurableBundle.message("maven.settings.general.print.stacktraces"),
MavenConfigurableBundle.message("maven.run.configuration.general.options.group"),
MavenConfigurableBundle.message("maven.settings.general.print.stacktraces.tooltip"),
{ generalSettingsOrDefault.isPrintErrorStackTraces },
{ generalSettingsOrDefault.isPrintErrorStackTraces = it }
)
}
private fun SettingsFragmentsContainer<MavenRunConfiguration>.addUpdateSnapshotsTag() {
addTag(
"maven.update.snapshots.tag",
MavenConfigurableBundle.message("maven.settings.general.update.snapshots"),
MavenConfigurableBundle.message("maven.run.configuration.general.options.group"),
MavenConfigurableBundle.message("maven.settings.general.update.snapshots.tooltip"),
{ generalSettingsOrDefault.isAlwaysUpdateSnapshots },
{ generalSettingsOrDefault.isAlwaysUpdateSnapshots = it }
)
}
private fun SettingsFragmentsContainer<MavenRunConfiguration>.addResolveWorkspaceArtifactsTag() {
addTag(
"maven.workspace.artifacts.tag",
MavenConfigurableBundle.message("maven.settings.runner.resolve.workspace.artifacts"),
MavenConfigurableBundle.message("maven.run.configuration.runner.options.group"),
MavenConfigurableBundle.message("maven.settings.runner.resolve.workspace.artifacts.tooltip"),
{ runnerParameters.isResolveToWorkspace },
{ runnerParameters.isResolveToWorkspace = it }
)
}
private fun SettingsFragmentsContainer<MavenRunConfiguration>.addExecuteNonRecursivelyTag() {
addTag(
"maven.execute.non.recursively.tag",
MavenConfigurableBundle.message("maven.settings.general.execute.non.recursively"),
MavenConfigurableBundle.message("maven.run.configuration.general.options.group"),
MavenConfigurableBundle.message("maven.settings.general.execute.recursively.tooltip"),
{ generalSettingsOrDefault.isNonRecursive },
{ generalSettingsOrDefault.isNonRecursive = it }
)
}
private fun SettingsFragmentsContainer<MavenRunConfiguration>.addWorkOfflineTag() {
addTag(
"maven.work.offline.tag",
MavenConfigurableBundle.message("maven.settings.general.work.offline"),
MavenConfigurableBundle.message("maven.run.configuration.general.options.group"),
MavenConfigurableBundle.message("maven.settings.general.work.offline.tooltip"),
{ generalSettingsOrDefault.isWorkOffline },
{ generalSettingsOrDefault.isWorkOffline = it }
)
}
private fun SettingsFragmentsContainer<MavenRunConfiguration>.addCheckSumPolicyTag() {
addVariantTag(
"maven.checksum.policy.tag",
MavenConfigurableBundle.message("maven.run.configuration.checksum.policy"),
MavenConfigurableBundle.message("maven.run.configuration.general.options.group"),
{ generalSettingsOrDefault.checksumPolicy },
{ generalSettingsOrDefault.checksumPolicy = it },
{ it.displayString }
)
}
private fun SettingsFragmentsContainer<MavenRunConfiguration>.addOutputLevelFragment() =
addVariantFragment(
object : LabeledSettingsFragmentInfo {
override val editorLabel: String = MavenConfigurableBundle.message("maven.run.configuration.output.level.label")
override val settingsId: String = "maven.output.level.fragment"
override val settingsName: String = MavenConfigurableBundle.message("maven.run.configuration.output.level.name")
override val settingsGroup: String = MavenConfigurableBundle.message("maven.run.configuration.general.options.group")
override val settingsHint: String? = null
override val settingsActionHint: String? = null
},
{ generalSettingsOrDefault.outputLevel },
{ generalSettingsOrDefault.outputLevel = it },
{ it.displayString }
).modifyLabeledComponentSize { columns(10) }
private fun SettingsFragmentsContainer<MavenRunConfiguration>.addMultiProjectBuildPolicyTag() {
addVariantTag(
"maven.multi.project.build.policy.tag",
MavenConfigurableBundle.message("maven.run.configuration.multi.project.build.policy"),
MavenConfigurableBundle.message("maven.run.configuration.general.options.group"),
{ generalSettingsOrDefault.failureBehavior },
{ generalSettingsOrDefault.failureBehavior = it },
{ it.displayString }
)
}
private fun SettingsFragmentsContainer<MavenRunConfiguration>.addDistributionFragment() =
addDistributionFragment(
project,
MavenDistributionsInfo(),
{ asDistributionInfo(generalSettingsOrDefault.mavenHome.ifEmpty { MavenServerManager.BUNDLED_MAVEN_3 }) },
{ generalSettingsOrDefault.mavenHome = it?.let(::asMavenHome) ?: MavenServerManager.BUNDLED_MAVEN_3 }
).addValidation {
if (!MavenUtil.isValidMavenHome(it.generalSettingsOrDefault.mavenHome)) {
throw RuntimeConfigurationError(MavenConfigurableBundle.message("maven.run.configuration.distribution.invalid.home.error"))
}
}
private fun SettingsFragmentsContainer<MavenRunConfiguration>.addWorkingDirectoryFragment() =
addWorkingDirectoryFragment(
project,
MavenWorkingDirectoryInfo(project),
{ runnerParameters.workingDirPath },
{ runnerParameters.workingDirPath = it }
)
private fun SettingsFragmentsContainer<MavenRunConfiguration>.addCommandLineFragment(
workingDirectoryField: WorkingDirectoryField
) = addCommandLineFragment(
project,
MavenCommandLineInfo(project, workingDirectoryField),
{ runnerParameters.commandLine },
{ runnerParameters.commandLine = it }
)
private fun SettingsFragmentsContainer<MavenRunConfiguration>.addEnvironmentFragment() =
addEnvironmentFragment(
object : LabeledSettingsFragmentInfo {
override val editorLabel: String = ExecutionBundle.message("environment.variables.component.title")
override val settingsId: String = "maven.environment.variables.fragment"
override val settingsName: String = ExecutionBundle.message("environment.variables.fragment.name")
override val settingsGroup: String = MavenConfigurableBundle.message("maven.run.configuration.runner.options.group")
override val settingsHint: String = ExecutionBundle.message("environment.variables.fragment.hint")
override val settingsActionHint: String = ExecutionBundle.message("set.custom.environment.variables.for.the.process")
},
{ runnerSettingsOrDefault.environmentProperties },
{ runnerSettingsOrDefault.environmentProperties = it },
{ runnerSettingsOrDefault.isPassParentEnv },
{ runnerSettingsOrDefault.isPassParentEnv = it },
hideWhenEmpty = true
)
private fun SettingsFragmentsContainer<MavenRunConfiguration>.addVmOptionsFragment() =
addVmOptionsFragment(
object : LabeledSettingsFragmentInfo {
override val editorLabel: String = ExecutionBundle.message("run.configuration.java.vm.parameters.label")
override val settingsId: String = "maven.vm.options.fragment"
override val settingsName: String = ExecutionBundle.message("run.configuration.java.vm.parameters.name")
override val settingsGroup: String = MavenConfigurableBundle.message("maven.run.configuration.runner.options.group")
override val settingsHint: String = ExecutionBundle.message("run.configuration.java.vm.parameters.hint")
override val settingsActionHint: String = ExecutionBundle.message("specify.vm.options.for.running.the.application")
},
{ runnerSettingsOrDefault.vmOptions.ifEmpty { null } },
{ runnerSettingsOrDefault.setVmOptions(it) }
)
private fun SettingsFragmentsContainer<MavenRunConfiguration>.addJreFragment() =
SdkLookupProvider.getInstance(project, object : SdkLookupProvider.Id {})
.let { sdkLookupProvider ->
addRemovableLabeledSettingsEditorFragment(
SdkComboBox(createProjectJdkComboBoxModel(project, this@MavenRunConfigurationSettingsEditor)),
object : LabeledSettingsFragmentInfo {
override val editorLabel: String = MavenConfigurableBundle.message("maven.run.configuration.jre.label")
override val settingsId: String = "maven.jre.fragment"
override val settingsName: String = MavenConfigurableBundle.message("maven.run.configuration.jre.name")
override val settingsGroup: String = MavenConfigurableBundle.message("maven.run.configuration.runner.options.group")
override val settingsHint: String? = null
override val settingsActionHint: String = MavenConfigurableBundle.message("maven.run.configuration.jre.action.hint")
},
{ getSelectedJdkReference(sdkLookupProvider) },
{ setSelectedJdkReference(sdkLookupProvider, it) },
{ runnerSettingsOrDefault.jreName },
{ runnerSettingsOrDefault.setJreName(it) },
{ MavenRunnerSettings.USE_PROJECT_JDK }
)
}
private fun SettingsFragmentsContainer<MavenRunConfiguration>.addPropertiesFragment() =
addLabeledSettingsEditorFragment(
PropertiesFiled(project, object : PropertiesInfo {
override val dialogTitle: String = MavenConfigurableBundle.message("maven.run.configuration.properties.dialog.title")
override val dialogTooltip: String = MavenConfigurableBundle.message("maven.run.configuration.properties.dialog.tooltip")
override val dialogLabel: String = MavenConfigurableBundle.message("maven.run.configuration.properties.dialog.label")
override val dialogEmptyState: String = MavenConfigurableBundle.message("maven.run.configuration.properties.dialog.empty.state")
override val dialogOkButton: String = MavenConfigurableBundle.message("maven.run.configuration.properties.dialog.ok.button")
}),
object : LabeledSettingsFragmentInfo {
override val editorLabel: String = MavenConfigurableBundle.message("maven.run.configuration.properties.label")
override val settingsId: String = "maven.properties.fragment"
override val settingsName: String = MavenConfigurableBundle.message("maven.run.configuration.properties.name")
override val settingsGroup: String = MavenConfigurableBundle.message("maven.run.configuration.runner.options.group")
override val settingsHint: String? = null
override val settingsActionHint: String? = null
},
{ it, c -> c.properties = it.runnerSettingsOrDefault.mavenProperties.map { PropertiesTable.Property(it.key, it.value) } },
{ it, c -> it.runnerSettingsOrDefault.mavenProperties = c.properties.associate { it.name to it.value } },
{ it.runnerSettingsOrDefault.mavenProperties.isNotEmpty() }
)
private fun SettingsFragmentsContainer<MavenRunConfiguration>.addProfilesFragment(
workingDirectoryField: WorkingDirectoryField
) = addLabeledSettingsEditorFragment(
MavenProfilesFiled(project, workingDirectoryField),
object : LabeledSettingsFragmentInfo {
override val editorLabel: String = MavenConfigurableBundle.message("maven.run.configuration.profiles.label")
override val settingsId: String = "maven.profiles.fragment"
override val settingsName: String = MavenConfigurableBundle.message("maven.run.configuration.profiles.name")
override val settingsGroup: String? = null
override val settingsHint: String = MavenConfigurableBundle.message("maven.run.configuration.profiles.hint")
override val settingsActionHint: String? = null
},
{ it, c -> c.profiles = it.runnerParameters.profilesMap },
{ it, c -> it.runnerParameters.profilesMap = c.profiles }
)
private fun SettingsFragmentsContainer<MavenRunConfiguration>.addUserSettingsFragment() =
addPathFragment(
project,
object : PathFragmentInfo {
override val editorLabel: String = MavenConfigurableBundle.message("maven.run.configuration.user.settings.label")
override val settingsId: String = "maven.user.settings.fragment"
override val settingsName: String = MavenConfigurableBundle.message("maven.run.configuration.user.settings.name")
override val settingsGroup: String = MavenConfigurableBundle.message("maven.run.configuration.general.options.group")
override val fileChooserTitle: String = MavenConfigurableBundle.message("maven.run.configuration.user.settings.title")
override val fileChooserDescriptor = FileChooserDescriptorFactory.createSingleFileNoJarsDescriptor()
override val fileChooserMacroFilter = FileChooserInfo.DIRECTORY_PATH
},
{ generalSettingsOrDefault.userSettingsFile },
{ generalSettingsOrDefault.setUserSettingsFile(it) },
{
val mavenConfig = MavenProjectsManager.getInstance(project)?.generalSettings?.mavenConfig
val userSettings = MavenWslUtil.getUserSettings(project, "", mavenConfig)
getCanonicalPath(userSettings.path)
}
)
private fun SettingsFragmentsContainer<MavenRunConfiguration>.addLocalRepositoryFragment(
distributionComponent: DistributionComboBox,
userSettingsComponent: TextFieldWithBrowseButton
) = addPathFragment(
project,
object : PathFragmentInfo {
override val editorLabel: String = MavenConfigurableBundle.message("maven.run.configuration.local.repository.label")
override val settingsId: String = "maven.local.repository.fragment"
override val settingsName: String = MavenConfigurableBundle.message("maven.run.configuration.local.repository.name")
override val settingsGroup: String = MavenConfigurableBundle.message("maven.run.configuration.general.options.group")
override val fileChooserTitle: String = MavenConfigurableBundle.message("maven.run.configuration.local.repository.title")
override val fileChooserDescriptor = FileChooserDescriptorFactory.createSingleFolderDescriptor()
override val fileChooserMacroFilter = FileChooserInfo.DIRECTORY_PATH
},
{ generalSettingsOrDefault.localRepository },
{ generalSettingsOrDefault.setLocalRepository(it) },
{
val mavenConfig = MavenProjectsManager.getInstance(project)?.generalSettings?.mavenConfig
val distributionInfo = distributionComponent.selectedDistribution
val distribution = distributionInfo?.let(::asMavenHome) ?: MavenServerManager.BUNDLED_MAVEN_3
val userSettingsPath = getCanonicalPath(userSettingsComponent.text)
val userSettingsFile = MavenWslUtil.getUserSettings(project, userSettingsPath, mavenConfig)
val userSettings = getCanonicalPath(userSettingsFile.path)
val localRepository = MavenWslUtil.getLocalRepo(project, "", distribution, userSettings, mavenConfig)
getCanonicalPath(localRepository.path)
}
)
private fun SettingsFragmentsContainer<MavenRunConfiguration>.addThreadsFragment() =
addRemovableLabeledTextSettingsEditorFragment(
JBTextField(),
object : LabeledSettingsFragmentInfo {
override val editorLabel: String = MavenConfigurableBundle.message("maven.run.configuration.threads.label")
override val settingsId: String = "maven.threads.fragment"
override val settingsName: String = MavenConfigurableBundle.message("maven.run.configuration.threads.name")
override val settingsGroup: String = MavenConfigurableBundle.message("maven.run.configuration.general.options.group")
override val settingsHint: String? = null
override val settingsActionHint: String = MavenConfigurableBundle.message("maven.settings.general.thread.count.tooltip")
},
{ generalSettingsOrDefault.threads },
{ generalSettingsOrDefault.threads = it }
).modifyLabeledComponentSize { columns(10) }
}
|
apache-2.0
|
9e9ea9c9f86f790ec4d0e89b50dec2b2
| 49.357013 | 158 | 0.761186 | 5.187652 | false | true | false | false |
google/intellij-community
|
platform/collaboration-tools/src/com/intellij/collaboration/ui/codereview/list/search/DropDownComponentFactory.kt
|
1
|
3072
|
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.collaboration.ui.codereview.list.search
import com.intellij.openapi.ui.popup.JBPopup
import com.intellij.openapi.util.NlsContexts
import com.intellij.ui.awt.RelativePoint
import com.intellij.ui.popup.PopupState
import com.intellij.ui.scale.JBUIScale
import com.intellij.util.ui.FilterComponent
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch
import org.jetbrains.annotations.Nls
import java.awt.Point
import java.util.function.Supplier
import javax.swing.JComponent
class DropDownComponentFactory<T : Any>(private val state: MutableStateFlow<T?>) {
fun create(vmScope: CoroutineScope,
filterName: @Nls String,
valuePresenter: (T) -> @Nls String = Any::toString,
chooseValue: suspend (RelativePoint, PopupState<JBPopup>) -> T?): JComponent {
val popupState: PopupState<JBPopup> = PopupState.forPopup()
return object : FilterComponent(Supplier<@NlsContexts.Label String?> { filterName }) {
override fun getCurrentText(): String {
val value = state.value
return if (value != null) valuePresenter(value) else emptyFilterValue
}
override fun getEmptyFilterValue(): String = ""
override fun isValueSelected(): Boolean = state.value != null
override fun installChangeListener(onChange: Runnable) {
vmScope.launch {
state.collectLatest {
onChange.run()
}
}
}
override fun createResetAction(): Runnable = Runnable { state.update { null } }
override fun shouldDrawLabel(): DrawLabelMode = DrawLabelMode.WHEN_VALUE_NOT_SET
}.apply {
setShowPopupAction {
val point = RelativePoint(this, Point(0, this.height + JBUIScale.scale(4)))
if (popupState.isRecentlyHidden) return@setShowPopupAction
vmScope.launch {
val newValue = chooseValue(point, popupState)
state.update { newValue }
}
}
}.initUi()
}
fun create(vmScope: CoroutineScope,
filterName: @Nls String,
items: List<T>,
valuePresenter: (T) -> @Nls String = Any::toString): JComponent =
create(vmScope, filterName, valuePresenter) { point, popupState ->
ChooserPopupUtil.showChooserPopup(point, popupState, items) {
ChooserPopupUtil.PopupItemPresentation.Simple(valuePresenter(it))
}
}
fun create(vmScope: CoroutineScope,
filterName: @Nls String,
items: List<T>,
valuePresenter: (T) -> @Nls String = Any::toString,
popupItemPresenter: (T) -> ChooserPopupUtil.PopupItemPresentation): JComponent =
create(vmScope, filterName, valuePresenter) { point, popupState ->
ChooserPopupUtil.showChooserPopup(point, popupState, items, popupItemPresenter)
}
}
|
apache-2.0
|
1c1e75066d1f1118f2c95f99a8bb321d
| 36.463415 | 120 | 0.694336 | 4.478134 | false | false | false | false |
google/intellij-community
|
platform/lang-impl/src/com/intellij/util/indexing/roots/builders/indexableIteratorBuilders.kt
|
3
|
5038
|
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.util.indexing.roots.builders
import com.intellij.openapi.diagnostic.thisLogger
import com.intellij.openapi.progress.ProgressManager
import com.intellij.openapi.project.Project
import com.intellij.openapi.projectRoots.Sdk
import com.intellij.openapi.roots.SyntheticLibrary
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.util.indexing.IndexableSetContributor
import com.intellij.util.indexing.roots.IndexableEntityProvider.IndexableIteratorBuilder
import com.intellij.util.indexing.roots.IndexableFilesIterator
import com.intellij.workspaceModel.storage.EntityStorage
import com.intellij.workspaceModel.storage.bridgeEntities.api.LibraryId
import com.intellij.workspaceModel.storage.bridgeEntities.api.ModuleId
import com.intellij.workspaceModel.storage.url.VirtualFileUrl
object IndexableIteratorBuilders {
val logger = thisLogger()
fun forModuleRoots(moduleId: ModuleId, urls: Collection<VirtualFileUrl>): Collection<IndexableIteratorBuilder> =
if (urls.isEmpty()) emptyList() else listOf(ModuleRootsIteratorBuilder(moduleId, urls))
fun forModuleRoots(moduleId: ModuleId, url: VirtualFileUrl): Collection<IndexableIteratorBuilder> =
listOf(ModuleRootsIteratorBuilder(moduleId, url))
fun forModuleRoots(moduleId: ModuleId,
newRoots: List<VirtualFileUrl>,
oldRoots: List<VirtualFileUrl>): Collection<IndexableIteratorBuilder> {
val roots = newRoots.toMutableList()
roots.removeAll(oldRoots)
return forModuleRoots(moduleId, roots)
}
@JvmOverloads
fun forLibraryEntity(libraryId: LibraryId, dependencyChecked: Boolean, root: VirtualFile? = null): Collection<IndexableIteratorBuilder> =
listOf(LibraryIdIteratorBuilder(libraryId, root, dependencyChecked))
fun forSdk(sdkName: String, sdkType: String): Collection<IndexableIteratorBuilder> = listOf(SdkIteratorBuilder(sdkName, sdkType))
fun forSdk(sdk: Sdk, file: VirtualFile): Collection<IndexableIteratorBuilder> = listOf(SdkIteratorBuilder(sdk, file))
fun forInheritedSdk(): Collection<IndexableIteratorBuilder> = listOf(InheritedSdkIteratorBuilder)
fun forModuleContent(moduleId: ModuleId): Collection<IndexableIteratorBuilder> = listOf(FullModuleContentIteratorBuilder(moduleId))
fun instantiateBuilders(builders: List<IndexableIteratorBuilder>,
project: Project,
entityStorage: EntityStorage): List<IndexableFilesIterator> {
if (builders.isEmpty()) return emptyList()
val result = ArrayList<IndexableFilesIterator>(builders.size)
var buildersToProceed = builders
val handlers = IndexableIteratorBuilderHandler.EP_NAME.extensionList
for (handler in handlers) {
ProgressManager.checkCanceled()
val partition = buildersToProceed.partition { handler.accepts(it) }
buildersToProceed = partition.second
if (partition.first.isNotEmpty()) {
result.addAll(handler.instantiate(partition.first, project, entityStorage))
}
}
if (buildersToProceed.isNotEmpty()) {
logger.error("Failed to find handlers for IndexableIteratorBuilders: ${buildersToProceed};\n" +
"available handlers: $handlers")
}
return result
}
}
internal data class LibraryIdIteratorBuilder(val libraryId: LibraryId,
val root: VirtualFile? = null,
val dependencyChecked: Boolean = false) : IndexableIteratorBuilder
internal data class SdkIteratorBuilder(val sdkName: String, val sdkType: String, val root: VirtualFile? = null) : IndexableIteratorBuilder {
constructor(sdk: Sdk, root: VirtualFile? = null) : this(sdk.name, sdk.sdkType.name, root)
}
internal object InheritedSdkIteratorBuilder : IndexableIteratorBuilder
internal data class FullModuleContentIteratorBuilder(val moduleId: ModuleId) : IndexableIteratorBuilder
internal class ModuleRootsIteratorBuilder(val moduleId: ModuleId, val urls: Collection<VirtualFileUrl>) : IndexableIteratorBuilder {
constructor(moduleId: ModuleId, url: VirtualFileUrl) : this(moduleId, listOf(url))
}
internal data class SyntheticLibraryIteratorBuilder(val syntheticLibrary: SyntheticLibrary,
val name: String?,
val roots: Collection<VirtualFile>) : IndexableIteratorBuilder
internal data class IndexableSetContributorFilesIteratorBuilder(val name: String?,
val debugName: String,
val providedRootsToIndex: Set<VirtualFile>,
val projectAware: Boolean,
val contributor: IndexableSetContributor) : IndexableIteratorBuilder
|
apache-2.0
|
6d443bcc169280da9bf3dcf466cd5acb
| 52.606383 | 140 | 0.718341 | 5.518072 | false | false | false | false |
JetBrains/intellij-community
|
plugins/kotlin/base/scripting/src/org/jetbrains/kotlin/idea/core/script/ucache/KotlinScriptLibraryIndexableFilesIteratorImpl.kt
|
1
|
4517
|
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.kotlin.idea.core.script.ucache
import com.intellij.openapi.application.runReadAction
import com.intellij.openapi.project.Project
import com.intellij.openapi.roots.ContentIterator
import com.intellij.openapi.roots.OrderRootType
import com.intellij.openapi.roots.impl.libraries.LibraryEx
import com.intellij.openapi.util.NlsSafe
import com.intellij.openapi.vfs.VfsUtil
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.openapi.vfs.VirtualFileFilter
import com.intellij.openapi.vfs.VirtualFileManager
import com.intellij.util.concurrency.annotations.RequiresReadLock
import com.intellij.util.indexing.IndexingBundle
import com.intellij.util.indexing.roots.IndexableFilesIterationMethods
import com.intellij.util.indexing.roots.LibraryIndexableFilesIterator
import com.intellij.util.indexing.roots.kind.LibraryOrigin
class KotlinScriptLibraryIndexableFilesIteratorImpl
private constructor(
private val libraryName: @NlsSafe String?,
private val presentableLibraryName: String,
private val classRoots: List<VirtualFile>,
private val sourceRoots: List<VirtualFile>
) : LibraryIndexableFilesIterator {
override fun getDebugName() = "Library ${presentableLibraryName} " +
"(#${classRoots.validCount()} class roots, " +
"#${sourceRoots.validCount()} source roots)"
override fun getIndexingProgressText(): String = IndexingBundle.message(
"indexable.files.provider.indexing.library.name",
presentableLibraryName
)
override fun getRootsScanningProgressText(): String {
if (!libraryName.isNullOrEmpty()) {
return IndexingBundle.message("indexable.files.provider.scanning.library.name", libraryName)
}
return IndexingBundle.message("indexable.files.provider.scanning.additional.dependencies")
}
override fun getOrigin(): LibraryOrigin {
return KotlinScriptLibraryOriginImpl(classRoots, sourceRoots)
}
override fun iterateFiles(
project: Project,
fileIterator: ContentIterator,
fileFilter: VirtualFileFilter
): Boolean {
val roots = runReadAction {
(classRoots.asSequence() + sourceRoots.asSequence()).filter { it.isValid }.toSet()
}
return IndexableFilesIterationMethods.iterateRoots(project, roots, fileIterator, fileFilter)
}
override fun getRootUrls(project: Project): Set<String> {
return (classRoots + sourceRoots).map { it.url }.toSet()
}
companion object {
private fun collectFiles(
library: KotlinScriptLibraryEntity,
rootType: OrderRootType,
rootsToFilter: List<VirtualFile>? = null
): List<VirtualFile> {
val reqType = when (rootType) {
OrderRootType.CLASSES -> KotlinScriptLibraryRootTypeId.COMPILED
OrderRootType.SOURCES -> KotlinScriptLibraryRootTypeId.SOURCES
else -> error("unexpected: $rootType")
}
val virtualFileManager = VirtualFileManager.getInstance()
val libraryRoots = library.roots
.filter { it.type == reqType }
.mapNotNull { virtualFileManager.findFileByUrl(it.url.url) }
val rootsToIterate: List<VirtualFile> = rootsToFilter?.filter { root ->
libraryRoots.find { libraryRoot ->
VfsUtil.isAncestor(libraryRoot, root, false)
} != null
} ?: libraryRoots.toList()
return rootsToIterate
}
@RequiresReadLock
@JvmStatic
fun createIterator(
library: KotlinScriptLibraryEntity,
roots: List<VirtualFile>? = null
): KotlinScriptLibraryIndexableFilesIteratorImpl? =
if (library is LibraryEx && library.isDisposed)
null
else
KotlinScriptLibraryIndexableFilesIteratorImpl(
library.name, library.name,
collectFiles(library, OrderRootType.CLASSES, roots),
collectFiles(library, OrderRootType.SOURCES, roots)
)
}
private fun List<VirtualFile>.validCount(): Int = filter { it.isValid }.size
}
internal data class KotlinScriptLibraryOriginImpl(
override val classRoots: List<VirtualFile>,
override val sourceRoots: List<VirtualFile>
) : LibraryOrigin
|
apache-2.0
|
d0d558ee08e53fea4e3161d0aae957a7
| 39.702703 | 120 | 0.69006 | 5.240139 | false | false | false | false |
customerly/Customerly-Android-SDK
|
customerly-android-sdk/src/main/java/io/customerly/utils/download/imagehandler/ClyImageHandler.kt
|
1
|
8418
|
package io.customerly.utils.download.imagehandler
/*
* Copyright (C) 2017 Customerly
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.os.Handler
import android.os.Looper
import android.util.LruCache
import android.util.SparseArray
import io.customerly.sxdependencies.annotations.SXUiThread
import io.customerly.utils.ggkext.resolveBitmapUrl
import io.customerly.utils.ggkext.useSkipExeption
import java.io.File
import java.io.FileOutputStream
import java.io.IOException
import java.util.concurrent.ExecutorService
import java.util.concurrent.Executors
/**
* Created by Gianni on 16/04/18.
* Project: Customerly-KAndroid-SDK
*/
private const val MAX_DISK_CACHE_SIZE = 1024 * 1024 * 2
private const val MAX_LRU_CACHE_SIZE = 1024 * 1024 * 2
internal object ClyImageHandler {
private val lruCache = LruCache<String, Bitmap>(MAX_LRU_CACHE_SIZE)
private val pendingRequests = SparseArray<ClyImageRequest>()
private var executorService: ExecutorService = Executors.newFixedThreadPool(5)
private var diskCacheSize = -1L
@SXUiThread
internal fun request(request: ClyImageRequest) {
assert(request.handlerValidateRequest())
request.handlerSetScaleType()
val diskKey = request.handlerGetDiskKey()
try {
this.lruCache.get(diskKey)?.takeUnless { it.isRecycled }
} catch (ignored: OutOfMemoryError) {
null
}?.let {
request.handlerOnResponse(bmp = it)
} ?: this.handleDisk(request = request, hashCode = request.handlerGetHashCode, diskKey = diskKey)
}
@SXUiThread
private fun handleDisk(request: ClyImageRequest, hashCode : Int, diskKey: String) {
request.handlerLoadPlaceholder()
synchronized(this.pendingRequests) {
this.pendingRequests.get(hashCode)?.cancel()
this.pendingRequests.remove(hashCode)
this.pendingRequests.put(hashCode, request)
}
this.executorService.submit {
if(this.pendingRequests.get(hashCode) == request) {
//Searching image in cache (LRU and Disk)
try {
request.customerlyCacheDirPath.let { cacheDirPath ->
val bitmapFile = File(cacheDirPath, diskKey)
if (bitmapFile.exists()) {
if (System.currentTimeMillis() - bitmapFile.lastModified() < 24 * 60 * 60 * 1000) {
BitmapFactory.decodeFile(bitmapFile.toString())?.also { bmp ->
if(synchronized(this.pendingRequests) {
if(this.pendingRequests.get(hashCode) == request) {
this.pendingRequests.remove(hashCode)
true
} else {
false
}
}) {
Handler(Looper.getMainLooper()).post {
request.handlerOnResponse(bmp = bmp)
}
}
// //Add Bitmap to LruMemory
this.lruCache.put(diskKey, bmp)
}
} else {
bitmapFile.delete()
this.handleNetwork(request = request, hashCode = hashCode, diskKey = diskKey)
}
} else {
this.handleNetwork(request = request, hashCode = hashCode, diskKey = diskKey)
}
}
} catch (ignored: OutOfMemoryError) {
this.handleNetwork(request = request, hashCode = hashCode, diskKey = diskKey)
}
}
}
}
private fun handleNetwork(request: ClyImageRequest, hashCode : Int, diskKey: String) {
this.executorService.submit {
if(this.pendingRequests.get(hashCode) == request) {
if(!try {
request.url.resolveBitmapUrl()
?.let { request.handlerApplyResize(it) }
?.let { request.handlerApplyTransformations(it) }
?.let { bmp ->
if (synchronized(this.pendingRequests) {
if(this.pendingRequests.get(hashCode) == request) {
this.pendingRequests.remove(hashCode)
true
} else {
false
}
}) {
Handler(Looper.getMainLooper()).post {
request.handlerOnResponse(bmp = bmp)
}
//Caching image (LRU and Disk)
this.lruCache.put(diskKey, bmp)
request.customerlyCacheDirPath.let { cacheDirPath ->
val cacheDir = File(cacheDirPath)
if (!cacheDir.exists()) {
cacheDir.mkdirs()
try {
File(cacheDirPath, ".nomedia").createNewFile()
} catch (ignored: IOException) {
}
}
val bitmapFile = File(cacheDirPath, diskKey)
FileOutputStream(bitmapFile).useSkipExeption {
bmp.compress(Bitmap.CompressFormat.PNG, 100, it)
if (this.diskCacheSize == -1L) {
this.diskCacheSize = cacheDir.listFiles { file -> file.isFile }?.asSequence()?.map { file -> file.length() }?.sum() ?: 0
} else {
this.diskCacheSize += bitmapFile.length()
}
}
if (this.diskCacheSize > MAX_DISK_CACHE_SIZE) {
cacheDir.listFiles { file -> file.isFile }?.minBy { file -> file.lastModified() }?.let {
val fileSize = it.length()
if (it.delete()) {
this.diskCacheSize -= fileSize
}
}
}
}
} else {
bmp.recycle()
}
true
} == true
} catch (exception: Throwable) {
false
}) {
Handler(Looper.getMainLooper()).post {
request.handlerLoadError()
}
}
}
}
}
}
|
apache-2.0
|
edc03f82ab8713abb8d2a2c65d2a508b
| 46.297753 | 168 | 0.444405 | 6.122182 | false | false | false | false |
googlecodelabs/android-gestural-navigation
|
app/src/main/java/com/example/android/uamp/utils/InjectorUtils.kt
|
1
|
2486
|
/*
* Copyright 2020 Google Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.android.uamp.utils
import android.app.Application
import android.content.ComponentName
import android.content.Context
import com.example.android.uamp.common.MusicServiceConnection
import com.example.android.uamp.media.MusicService
import com.example.android.uamp.viewmodels.MainActivityViewModel
import com.example.android.uamp.viewmodels.MediaItemFragmentViewModel
import com.example.android.uamp.viewmodels.NowPlayingFragmentViewModel
/**
* Static methods used to inject classes needed for various Activities and Fragments.
*/
object InjectorUtils {
private fun provideMusicServiceConnection(context: Context): MusicServiceConnection {
return MusicServiceConnection.getInstance(context,
ComponentName(context, MusicService::class.java))
}
fun provideMainActivityViewModel(context: Context): MainActivityViewModel.Factory {
val applicationContext = context.applicationContext
val musicServiceConnection = provideMusicServiceConnection(applicationContext)
return MainActivityViewModel.Factory(musicServiceConnection)
}
fun provideMediaItemFragmentViewModel(context: Context, mediaId: String)
: MediaItemFragmentViewModel.Factory {
val applicationContext = context.applicationContext
val musicServiceConnection = provideMusicServiceConnection(applicationContext)
return MediaItemFragmentViewModel.Factory(mediaId, musicServiceConnection)
}
fun provideNowPlayingFragmentViewModel(context: Context)
: NowPlayingFragmentViewModel.Factory {
val applicationContext = context.applicationContext
val musicServiceConnection = provideMusicServiceConnection(applicationContext)
return NowPlayingFragmentViewModel.Factory(
applicationContext as Application, musicServiceConnection)
}
}
|
apache-2.0
|
826d1e02bf0ce92d0f08bc3a701c03d1
| 42.614035 | 89 | 0.778359 | 5.463736 | false | false | false | false |
grover-ws-1/http4k
|
http4k-core/src/main/kotlin/org/http4k/lens/body.kt
|
1
|
6934
|
package org.http4k.lens
import org.http4k.asByteBuffer
import org.http4k.asString
import org.http4k.core.Body
import org.http4k.core.ContentType
import org.http4k.core.HttpMessage
import org.http4k.core.Status.Companion.NOT_ACCEPTABLE
import org.http4k.core.with
import org.http4k.lens.ContentNegotiation.Companion.None
import org.http4k.lens.Header.Common.CONTENT_TYPE
import org.http4k.lens.ParamMeta.FileParam
import org.http4k.lens.ParamMeta.StringParam
import java.nio.ByteBuffer
/**
* A BodyLens provides the uni-directional extraction of an entity from a target body.
*/
open class BodyLens<out FINAL>(val metas: List<Meta>, val contentType: ContentType, private val get: (HttpMessage) -> FINAL) : LensExtractor<HttpMessage, FINAL> {
override operator fun invoke(target: HttpMessage): FINAL = try {
get(target)
} catch (e: LensFailure) {
throw e
} catch (e: Exception) {
throw LensFailure(metas.map(::Invalid), cause = e)
}
}
/**
* A BiDiBodyLens provides the bi-directional extraction of an entity from a target body, or the insertion of an entity
* into a target body.
*/
class BiDiBodyLens<FINAL>(metas: List<Meta>,
contentType: ContentType,
get: (HttpMessage) -> FINAL,
private val set: (FINAL, HttpMessage) -> HttpMessage)
: LensInjector<HttpMessage, FINAL>, BodyLens<FINAL>(metas, contentType, get) {
@Suppress("UNCHECKED_CAST")
override operator fun <R : HttpMessage> invoke(value: FINAL, target: R): R = set(value, target) as R
}
/**
* Represents a uni-directional extraction of an entity from a target Body.
*/
open class BodyLensSpec<out OUT>(internal val metas: List<Meta>, internal val contentType: ContentType, internal val get: LensGet<HttpMessage, ByteBuffer, OUT>) {
/**
* Create a lens for this Spec
*/
open fun toLens(): BodyLens<OUT> {
val getLens = get("")
return BodyLens(metas, contentType, { getLens(it).firstOrNull() ?: throw LensFailure(metas.map(::Missing)) })
}
/**
* Create another BodyLensSpec which applies the uni-directional transformation to the result. Any resultant Lens can only be
* used to extract the final type from a Body.
*/
fun <NEXT> map(nextIn: (OUT) -> NEXT): BodyLensSpec<NEXT> = BodyLensSpec(metas, contentType, get.map(nextIn))
}
/**
* Represents a bi-directional extraction of an entity from a target Body, or an insertion into a target Body.
*/
open class BiDiBodyLensSpec<OUT>(metas: List<Meta>,
contentType: ContentType,
get: LensGet<HttpMessage, ByteBuffer, OUT>,
private val set: LensSet<HttpMessage, ByteBuffer, OUT>) : BodyLensSpec<OUT>(metas, contentType, get) {
/**
* Create another BiDiBodyLensSpec which applies the bi-directional transformations to the result. Any resultant Lens can be
* used to extract or insert the final type from/into a Body.
*/
fun <NEXT> map(nextIn: (OUT) -> NEXT, nextOut: (NEXT) -> OUT) = BiDiBodyLensSpec(metas, contentType, get.map(nextIn), set.map(nextOut))
/**
* Create a lens for this Spec
*/
override fun toLens(): BiDiBodyLens<OUT> {
val getLens = get("")
val setLens = set("")
return BiDiBodyLens(metas, contentType,
{ getLens(it).let { if (it.isEmpty()) throw LensFailure(metas.map(::Missing)) else it.first() } },
{ out: OUT, target: HttpMessage -> setLens(out?.let { listOf(it) } ?: kotlin.collections.emptyList(), target) }
)
}
}
fun root(metas: List<Meta>, acceptedContentType: ContentType, contentNegotiation: ContentNegotiation) =
BiDiBodyLensSpec(metas, acceptedContentType,
LensGet { _, target ->
contentNegotiation(acceptedContentType, CONTENT_TYPE(target))
target.body.let { listOf(it.payload) }
},
LensSet { _, values, target -> values.fold(target) { a, b -> a.body(Body(b)) }.with(CONTENT_TYPE of acceptedContentType) }
)
/**
* Modes for determining if a passed content type is acceptable.
*/
interface ContentNegotiation {
@Throws(LensFailure::class)
operator fun invoke(expected: ContentType, actual: ContentType?)
companion object {
/**
* The received Content-type header passed back MUST equal the expected Content-type, including directive
*/
val Strict = object : ContentNegotiation {
override fun invoke(expected: ContentType, actual: ContentType?) {
if (actual != expected) throw LensFailure(CONTENT_TYPE.invalid(), status = NOT_ACCEPTABLE)
}
}
/**
* The received Content-type header passed back MUST equal the expected Content-type, not including the directive
*/
val StrictNoDirective = object : ContentNegotiation {
override fun invoke(expected: ContentType, actual: ContentType?) {
if (expected.value != actual?.value) throw LensFailure(CONTENT_TYPE.invalid(), status = NOT_ACCEPTABLE)
}
}
/**
* If present, the received Content-type header passed back MUST equal the expected Content-type, including directive
*/
val NonStrict = object : ContentNegotiation {
override fun invoke(expected: ContentType, actual: ContentType?) {
if (actual != null && actual != expected) throw LensFailure(CONTENT_TYPE.invalid(), status = NOT_ACCEPTABLE)
}
}
/**
* No validation is done on the received content type at all
*/
val None = object : ContentNegotiation {
override fun invoke(expected: ContentType, actual: ContentType?) {}
}
}
}
fun Body.Companion.string(contentType: ContentType, description: String? = null, contentNegotiation: ContentNegotiation = None)
= root(listOf(Meta(true, "body", StringParam, "body", description)), contentType, contentNegotiation).map(ByteBuffer::asString, String::asByteBuffer)
fun Body.Companion.nonEmptyString(contentType: ContentType, description: String? = null, contentNegotiation: ContentNegotiation = None)
= string(contentType, description, contentNegotiation).map(::nonEmpty, { it })
fun Body.Companion.binary(contentType: ContentType, description: String? = null, contentNegotiation: ContentNegotiation = None)
= root(listOf(Meta(true, "body", FileParam, "body", description)), contentType, contentNegotiation)
fun Body.Companion.regex(pattern: String, group: Int = 1, contentType: ContentType = ContentType.TEXT_PLAIN, description: String? = null, contentNegotiation: ContentNegotiation = None) =
pattern.toRegex().let { regex ->
string(contentType, description, contentNegotiation).map({ regex.matchEntire(it)?.groupValues?.get(group)!! }, { it })
}
|
apache-2.0
|
cd8079a931cc6fb0f6ebd16f75c0562b
| 43.735484 | 186 | 0.668445 | 4.264453 | false | false | false | false |
JuliusKunze/kotlin-native
|
backend.native/tests/external/codegen/box/secondaryConstructors/varargs.kt
|
5
|
587
|
fun join(x: Array<out String>): String {
var result = ""
for (i in x) {
result += i
result += "#"
}
return result
}
open class B {
val parentProp: String
constructor(vararg x: String) {
parentProp = join(x)
}
}
class A : B {
val prop: String
constructor(vararg x: String): super("0", *x, "4") {
prop = join(x)
}
}
fun box(): String {
val a1 = A("1", "2", "3")
if (a1.prop != "1#2#3#") return "fail1: ${a1.prop}"
if (a1.parentProp != "0#1#2#3#4#") return "fail2: ${a1.parentProp}"
return "OK"
}
|
apache-2.0
|
d76514d0729dd66d50d8d775ea8cdc6c
| 17.935484 | 71 | 0.505963 | 2.891626 | false | false | false | false |
samirma/MeteoriteLandings
|
app/src/main/java/com/antonio/samir/meteoritelandingsspots/features/list/recyclerView/MeteoriteAdapter.kt
|
1
|
1822
|
package com.antonio.samir.meteoritelandingsspots.features.list.recyclerView
import android.location.Location
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.lifecycle.MutableLiveData
import androidx.paging.PagedListAdapter
import com.antonio.samir.meteoritelandingsspots.R
import com.antonio.samir.meteoritelandingsspots.data.repository.model.Meteorite
import java.util.*
/**
* Custom RecyclerView.Adapter to deal with meteorites cursor
*/
class MeteoriteAdapter : PagedListAdapter<Meteorite, ViewHolderMeteorite>(MeteoriteDiffCallback()) {
var location: Location? = null
var openMeteorite = MutableLiveData<Meteorite>()
private var selectedMeteorite: Meteorite? = null
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolderMeteorite {
val view = LayoutInflater.from(parent.context).inflate(R.layout.list_item_meteorite, parent, false)
return ViewHolderMeteorite(view)
}
fun updateListUI(current: Meteorite?, previous: Meteorite? = selectedMeteorite) {
if (!Objects.equals(previous, current)) {
getPosition(current)?.let { notifyItemChanged(it) }
getPosition(previous)?.let { notifyItemChanged(it) }
}
selectedMeteorite = current
}
fun getPosition(current: Meteorite?): Int? {
return currentList?.indexOf(current)
}
override fun onBindViewHolder(viewHolder: ViewHolderMeteorite, position: Int) {
getItem(position)?.let { meteorite ->
val isSelected = selectedMeteorite == meteorite
viewHolder.onBind(meteorite, isSelected, location) {
openMeteorite.value = meteorite
}
}
}
fun clearSelectedMeteorite() {
openMeteorite = MutableLiveData<Meteorite>()
}
}
|
mit
|
de757024fae381a7b05664e218ca4d51
| 32.759259 | 107 | 0.718441 | 5.075209 | false | false | false | false |
chromeos/video-composition-sample
|
VideoCompositionSample/src/main/java/dev/chromeos/videocompositionsample/presentation/ui/screens/settings/adapter/SelectedClipAdapter.kt
|
1
|
2355
|
/*
* Copyright (c) 2021 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dev.chromeos.videocompositionsample.presentation.ui.screens.settings.adapter
import android.view.View
import androidx.recyclerview.widget.RecyclerView
import dev.chromeos.videocompositionsample.presentation.R
import dev.chromeos.videocompositionsample.presentation.ui.base.BaseRecyclerViewAdapter
import dev.chromeos.videocompositionsample.presentation.ui.model.TrackModel
import kotlinx.android.extensions.LayoutContainer
import kotlinx.android.synthetic.main.selected_clip_item.*
class SelectedClipAdapter(dataList: MutableList<TrackModel> = ArrayList(),
var onRemoveClickListener: ((TrackModel) -> Unit)? = null,
var onEffectClickListener: ((TrackModel) -> Unit)? = null,
callback: ((TrackModel) -> Unit)? = null)
: BaseRecyclerViewAdapter<TrackModel>(dataList, R.layout.selected_clip_item, callback) {
override fun getViewHolder(view: View): RecyclerView.ViewHolder {
return Holder(view)
}
inner class Holder(override val containerView: View)
: RecyclerView.ViewHolder(containerView), LayoutContainer {
fun bind(data: TrackModel, position: Int) {
tvClipTitle.text = containerView.context.getString(data.nameResId)
tvPosition.text = (position + 1).toString()
tvEffect.html = containerView.context.getString(R.string.settings__effect, data.effectId)
tvEffect.setOnClickListener { onEffectClickListener?.invoke(data) }
ivRemove.setOnClickListener { onRemoveClickListener?.invoke(data) }
}
}
override fun onBindViewHolder(holder: RecyclerView.ViewHolder, item: TrackModel, position: Int) {
(holder as Holder).bind(item, position)
}
}
|
apache-2.0
|
49a9ec0fd141915b3f87a15395bd2f4e
| 43.45283 | 101 | 0.722293 | 4.626719 | false | false | false | false |
smmribeiro/intellij-community
|
build/tasks/src/org/jetbrains/intellij/build/tasks/blockmap.kt
|
1
|
2875
|
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.intellij.build.tasks
import com.fasterxml.jackson.jr.ob.JSON
import com.jetbrains.plugin.blockmap.core.BlockMap
import com.jetbrains.plugin.blockmap.core.FileHash
import io.opentelemetry.api.common.AttributeKey
import org.jetbrains.intellij.build.io.ZipArchiver
import org.jetbrains.intellij.build.io.compressDir
import org.jetbrains.intellij.build.io.writeNewZip
import java.nio.file.Files
import java.nio.file.Path
import java.util.concurrent.ForkJoinTask
private const val algorithm = "SHA-256"
@Suppress("unused")
fun bulkZipWithPrefix(commonSourceDir: Path, items: List<Map.Entry<String, Path>>, compress: Boolean) {
tracer.spanBuilder("archive directories")
.setAttribute(AttributeKey.longKey("count"), items.size.toLong())
.setAttribute(AttributeKey.stringKey("commonSourceDir"), commonSourceDir.toString())
.startSpan()
.use { parentSpan ->
val json = JSON.std.without(JSON.Feature.USE_FIELDS)
ForkJoinTask.invokeAll(items.map { item ->
ForkJoinTask.adapt {
parentSpan.makeCurrent().use {
val target = item.value
val dir = commonSourceDir.resolve(item.key)
tracer.spanBuilder("build plugin archive")
.setAttribute("inputDir", dir.toString())
.setAttribute("outputFile", target.toString())
.startSpan()
.use {
writeNewZip(target, compress = compress) { zipCreator ->
ZipArchiver(zipCreator).use { archiver ->
archiver.setRootDir(dir, item.key)
compressDir(dir, archiver, excludes = null)
}
}
}
if (compress) {
tracer.spanBuilder("build plugin blockmap")
.setAttribute("file", target.toString())
.startSpan()
.use {
buildBlockMap(target, json)
}
}
}
}
})
}
}
/**
* Builds a blockmap and hash files for plugin to provide downloading plugins via incremental downloading algorithm Blockmap.
*/
internal fun buildBlockMap(file: Path, json: JSON) {
val bytes = Files.newInputStream(file).use { input ->
json.asBytes(BlockMap(input, algorithm))
}
val fileParent = file.parent
val fileName = file.fileName.toString()
writeNewZip(fileParent.resolve("$fileName.blockmap.zip"), compress = true) {
it.compressedData("blockmap.json", bytes)
}
val hashFile = fileParent.resolve("$fileName.hash.json")
Files.newInputStream(file).use { input ->
Files.newOutputStream(hashFile).use { output ->
json.write(FileHash(input, algorithm), output)
}
}
}
|
apache-2.0
|
2e5d20b1ce23c4fa5042ee5eb3d70991
| 36.842105 | 158 | 0.653913 | 4.278274 | false | false | false | false |
google/intellij-community
|
plugins/package-search/src/com/jetbrains/packagesearch/intellij/plugin/extensibility/ModuleChangesSignalProviders.kt
|
1
|
2621
|
/*******************************************************************************
* Copyright 2000-2022 JetBrains s.r.o. and contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
package com.jetbrains.packagesearch.intellij.plugin.extensibility
import com.intellij.openapi.project.Project
import com.intellij.openapi.vfs.LocalFileSystem
import com.jetbrains.packagesearch.intellij.plugin.util.filesChangedEventFlow
import com.jetbrains.packagesearch.intellij.plugin.util.send
import kotlinx.coroutines.channels.awaitClose
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.asFlow
import kotlinx.coroutines.flow.channelFlow
import kotlinx.coroutines.flow.filter
import kotlinx.coroutines.flow.flatMapMerge
import kotlinx.coroutines.flow.launchIn
import kotlinx.coroutines.flow.onEach
import java.nio.file.Path
import kotlin.io.path.absolutePathString
import kotlin.io.path.name
open class FileWatcherSignalProvider(private val paths: List<Path>) : FlowModuleChangesSignalProvider {
constructor(vararg paths: Path) : this(paths.toList())
private val absolutePathStrings = paths.map { it.absolutePathString() }
override fun registerModuleChangesListener(project: Project): Flow<Unit> {
val localFs: LocalFileSystem = LocalFileSystem.getInstance()
val watchRequests = absolutePathStrings.asSequence()
.onEach { localFs.findFileByPath(it) }
.mapNotNull { localFs.addRootToWatch(it, false) }
return channelFlow {
project.filesChangedEventFlow.flatMapMerge { it.asFlow() }
.filter { vFileEvent -> paths.any { it.name == vFileEvent.file?.name } } // check the file name before resolving the absolute path string
.filter { vFileEvent -> absolutePathStrings.any { it == vFileEvent.file?.toNioPath()?.absolutePathString() } }
.onEach { send() }
.launchIn(this)
awaitClose { watchRequests.forEach { request -> localFs.removeWatchedRoot(request) } }
}
}
}
|
apache-2.0
|
cff1c4c63a084c93955fca0bc9eec185
| 46.654545 | 153 | 0.69897 | 4.774135 | false | false | false | false |
fabmax/kool
|
kool-core/src/commonMain/kotlin/de/fabmax/kool/util/TextCaretNavigation.kt
|
1
|
1270
|
package de.fabmax.kool.util
import de.fabmax.kool.math.clamp
object TextCaretNavigation {
fun startOfWord(text: String, caretPos: Int): Int {
var i = caretPos.clamp(0, text.lastIndex)
while (i > 0 && !text[i].isWhitespace()) i--
if (text[i].isWhitespace()) i++
return i
}
fun endOfWord(text: String, caretPos: Int): Int {
var i = caretPos.clamp(0, text.lastIndex)
while (i < text.length && !text[i].isWhitespace()) i++
return i
}
fun moveWordLeft(text: String, caretPos: Int): Int {
var i = (caretPos - 1).clamp(0, text.lastIndex)
return when {
i == 0 -> 0
!text[i].isWhitespace() -> startOfWord(text, i)
else -> {
while (i > 0 && text[i].isWhitespace()) i--
startOfWord(text, i)
}
}
}
fun moveWordRight(text: String, caretPos: Int): Int {
var i = (caretPos + 1).clamp(0, text.length)
return when {
i == text.length -> text.length
!text[i].isWhitespace() -> endOfWord(text, i)
else -> {
while (i < text.length && text[i].isWhitespace()) i++
endOfWord(text, i)
}
}
}
}
|
apache-2.0
|
0d26e3da6b1fa3d54f59e13c43b14c36
| 27.886364 | 69 | 0.511024 | 3.746313 | false | false | false | false |
nuxusr/walkman
|
okreplay-sample/src/main/kotlin/okreplay/sample/DependencyGraph.kt
|
1
|
1525
|
package okreplay.sample
import com.squareup.moshi.Moshi
import io.reactivex.schedulers.Schedulers
import okhttp3.Interceptor
import okhttp3.OkHttpClient
import okreplay.OkReplayInterceptor
import retrofit2.Retrofit
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory
import retrofit2.converter.moshi.MoshiConverterFactory
internal class DependencyGraph private constructor() {
private val API_BASE_URL = "https://api.github.com"
val okReplayInterceptor = OkReplayInterceptor()
private val moshi = Moshi.Builder()
.add(OkReplayAdapterFactory.create())
.build()
private val acceptHeaderInterceptor = Interceptor {
it.proceed(it.request()
.newBuilder()
.addHeader("Accept", "application/vnd.github.v3+json")
.build())
}
val okHttpClient: OkHttpClient = OkHttpClient.Builder()
.addInterceptor(acceptHeaderInterceptor)
.addInterceptor(okReplayInterceptor)
.build()
private val retrofit = Retrofit.Builder()
.baseUrl(API_BASE_URL)
.client(okHttpClient)
.addConverterFactory(MoshiConverterFactory.create(moshi))
.addCallAdapterFactory(RxJava2CallAdapterFactory.createWithScheduler(Schedulers.io()))
.build()
val service: GithubService = retrofit.create(GithubService::class.java)
companion object {
private var instance: DependencyGraph? = null
fun instance(): DependencyGraph {
if (instance == null) {
instance = DependencyGraph()
}
return instance as DependencyGraph
}
}
}
|
apache-2.0
|
ea2fa4b5fcc1f04097c35d29ee3199a7
| 32.152174 | 92 | 0.738361 | 4.721362 | false | false | false | false |
mdaniel/intellij-community
|
platform/workspaceModel/storage/src/com/intellij/workspaceModel/storage/impl/Entities.kt
|
2
|
25456
|
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.workspaceModel.storage.impl
import com.intellij.util.ReflectionUtil
import com.intellij.workspaceModel.storage.*
import com.intellij.workspaceModel.storage.impl.indices.VirtualFileIndex
import com.intellij.workspaceModel.storage.impl.indices.WorkspaceMutableIndex
import com.intellij.workspaceModel.storage.url.VirtualFileUrl
import kotlin.reflect.KClass
/**
* For creating a new entity, you should perform the following steps:
*
* - Choose the name of the entity, e.g. MyModuleEntity
* - Create [WorkspaceEntity] representation:
* - The entity should inherit [WorkspaceEntityBase]
* - Properties (not references to other entities) should be listed in a primary constructor as val's
* - If the entity has PersistentId, the entity should extend [WorkspaceEntityWithPersistentId]
* - If the entity has references to other entities, they should be implement using property delegation objects listed in [com.intellij.workspaceModel.storage.impl.references] package.
* E.g. [OneToMany] or [ManyToOne.NotNull]
*
* Example:
*
* ```kotlin
* class MyModuleEntity(val name: String) : WorkspaceEntityBase(), WorkspaceEntityWithPersistentId {
*
* val childModule: MyModuleEntity? by OneToOneParent.Nullable(MyModuleEntity::class.java, true)
*
* fun persistentId = NameId(name)
* }
* ```
*
* The above entity describes an entity with `name` property, persistent id and the reference to "ChildModule"
*
* This object will be used by users and it's returned by methods like `resolve`, `entities` and so on.
*
* -------------------------------------------------------------------------------------------------------------------------------
*
* - Create EntityData representation:
* - Entity data should have the name ${entityName}Data. E.g. MyModuleEntityData.
* - Entity data should inherit [WorkspaceEntityData]
* - Properties (not references to other entities) should be listed in the body as lateinit var's or with default value (null, 0, false).
* - If the entity has PersistentId, the Entity data should extend [WorkspaceEntityData.WithCalculablePersistentId]
* - References to other entities should not be listed in entity data.
*
* - If the entity contains soft references to other entities (persistent id to other entities), entity data should extend SoftLinkable
* interface and implement the required methods. Check out the [FacetEntityData] implementation, but keep in mind the this might
* be more complicated like in [ModuleEntityData].
* - Entity data should implement [WorkspaceEntityData.createEntity] method. This method should return an instance of
* [WorkspaceEntity]. This instance should be passed to [addMetaData] after creation!
* E.g.:
*
* override fun createEntity(snapshot: WorkspaceEntityStorage): ModuleEntity = ModuleEntity(name, type, dependencies).also {
* addMetaData(it, snapshot)
* }
*
* Example:
*
* ```kotlin
* class MyModuleEntityData : WorkspaceEntityData.WithCalculablePersistentId<MyModuleEntity>() {
* lateinit var name: String
*
* override fun persistentId(): NameId = NameId(name)
*
* override fun createEntity(snapshot: WorkspaceEntityStorage): MyModuleEntity = MyModuleEntity(name).also {
* addMetaData(it, snapshot)
* }
* }
* ```
*
* This is an internal representation of WorkspaceEntity. It's not passed to users.
*
* -------------------------------------------------------------------------------------------------------------------------------
*
* - Create [ModifiableWorkspaceEntity] representation:
* - The name should be: Modifiable${entityName}. E.g. ModifiableMyModuleEntity
* - This should be inherited from [ModifiableWorkspaceEntityBase]
* - Properties (not references to other entities) should be listed in the body as delegation to [EntityDataDelegation()]
* - References to other entities should be listed as in [WorkspaceEntity], but with corresponding modifiable delegates
*
* Example:
*
* ```kotlin
* class ModifiableMyModuleEntity : ModifiableWorkspaceEntityBase<MyModuleEntity>() {
* var name: String by EntityDataDelegation()
*
* var childModule: MyModuleEntity? by MutableOneToOneParent.NotNull(MyModuleEntity::class.java, MyModuleEntity::class.java, true)
* }
* ```
*/
abstract class WorkspaceEntityBase : ReferableWorkspaceEntity, Any() {
override lateinit var entitySource: EntitySource
internal set
var id: EntityId = invalidEntityId
lateinit var snapshot: EntityStorage
abstract fun connectionIdList(): List<ConnectionId>
override fun <R : WorkspaceEntity> referrers(entityClass: Class<R>, propertyName: String): Sequence<R> {
val mySnapshot = snapshot as AbstractEntityStorage
return getReferences(mySnapshot, entityClass)
}
internal fun <R : WorkspaceEntity> getReferences(
mySnapshot: AbstractEntityStorage,
entityClass: Class<R>
): Sequence<R> {
var connectionId =
mySnapshot.refs.findConnectionId(getEntityInterface(), entityClass)
if (connectionId != null) {
return when (connectionId.connectionType) {
ConnectionId.ConnectionType.ONE_TO_MANY -> mySnapshot.extractOneToManyChildren(connectionId, id)
ConnectionId.ConnectionType.ONE_TO_ONE -> mySnapshot.extractOneToOneChild<R>(connectionId, id)
?.let { sequenceOf(it) }
?: emptySequence()
ConnectionId.ConnectionType.ONE_TO_ABSTRACT_MANY -> mySnapshot.extractOneToAbstractManyChildren(
connectionId,
id.asParent()
)
ConnectionId.ConnectionType.ABSTRACT_ONE_TO_ONE -> /*mySnapshot.extractAbstractOneToOneChild<R>(connectionId, id.asParent())?.let {
sequenceOf(it)
} ?: */emptySequence()
}
}
connectionId =
mySnapshot.refs.findConnectionId(entityClass, getEntityInterface())
if (connectionId != null) {
return when (connectionId.connectionType) {
ConnectionId.ConnectionType.ONE_TO_MANY -> mySnapshot.extractOneToManyParent<R>(connectionId, id)?.let { sequenceOf(it) } ?: emptySequence()
ConnectionId.ConnectionType.ONE_TO_ONE -> mySnapshot.extractOneToOneParent<R>(connectionId, id)
?.let { sequenceOf(it) }
?: emptySequence()
ConnectionId.ConnectionType.ONE_TO_ABSTRACT_MANY -> mySnapshot.extractOneToAbstractManyParent<R>(
connectionId,
id.asChild()
)
?.let { sequenceOf(it) }
?: emptySequence()
ConnectionId.ConnectionType.ABSTRACT_ONE_TO_ONE -> /*mySnapshot.extractAbstractOneToOneChild<R>(connectionId, id.asParent())?.let {
sequenceOf(it)
} ?: */emptySequence()
}
}
return emptySequence()
}
override fun <E : WorkspaceEntity> createReference(): EntityReference<E> {
return EntityReferenceImpl(this.id)
}
override fun getEntityInterface(): Class<out WorkspaceEntity> = id.clazz.findWorkspaceEntity()
override fun toString(): String = id.asString()
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other !is WorkspaceEntityBase) return false
if (id != other.id) return false
if ((this.snapshot as AbstractEntityStorage).entityDataById(id) !==
(other.snapshot as AbstractEntityStorage).entityDataById(other.id)
) return false
return true
}
override fun hashCode(): Int = id.hashCode()
}
data class EntityLink(
val isThisFieldChild: Boolean,
val connectionId: ConnectionId,
)
val EntityLink.remote: EntityLink
get() = EntityLink(!this.isThisFieldChild, connectionId)
abstract class ModifiableWorkspaceEntityBase<T : WorkspaceEntity> : WorkspaceEntityBase(), ModifiableWorkspaceEntity<T>, ModifiableReferableWorkspaceEntity {
/**
* In case any of two referred entities is not added to diff, the reference between entities will be stored in this field
*/
val entityLinks: MutableMap<EntityLink, Any?> = HashMap()
internal lateinit var original: WorkspaceEntityData<T>
var diff: MutableEntityStorage? = null
val modifiable: ThreadLocal<Boolean> = ThreadLocal.withInitial { false }
val changedProperty: MutableSet<String> = mutableSetOf()
override fun linkExternalEntity(entityClass: KClass<out WorkspaceEntity>,
isThisFieldChild: Boolean,
entities: List<WorkspaceEntity?>) {
val foundConnectionId = findConnectionId(entityClass, entities)
if (foundConnectionId == null) return
// If the diff is empty, we should link entities using the internal map
// If it's not, we should add entity to store and update indexes
val myDiff = diff
if (myDiff != null) {
//if (foundConnectionId.parentClass == getEntityClass().toClassId()) {
if (isThisFieldChild) {
// Branch for case `this` entity is a parent
if (foundConnectionId.connectionType == ConnectionId.ConnectionType.ONE_TO_MANY || foundConnectionId.connectionType == ConnectionId.ConnectionType.ONE_TO_ABSTRACT_MANY) {
// One - to - many connection
for (item in entities) {
if (item != null && item is ModifiableWorkspaceEntityBase<*> && item.diff == null) {
@Suppress("KotlinConstantConditions")
item.entityLinks[EntityLink(!isThisFieldChild, foundConnectionId)] = this
myDiff.addEntity(item)
}
}
myDiff.updateOneToManyChildrenOfParent(foundConnectionId, this, entities.filterNotNull())
} else {
// One - to -one connection
val item = entities.single()
if (item != null && item is ModifiableWorkspaceEntityBase<*> && item.diff == null) {
@Suppress("KotlinConstantConditions")
item.entityLinks[EntityLink(!isThisFieldChild, foundConnectionId)] = this
myDiff.addEntity(item)
}
myDiff.updateOneToOneChildOfParent(foundConnectionId, this, item)
}
}
else {
// Branch for case `this` entity is a child
if (foundConnectionId.connectionType == ConnectionId.ConnectionType.ONE_TO_MANY || foundConnectionId.connectionType == ConnectionId.ConnectionType.ONE_TO_ABSTRACT_MANY) {
// One - to - many connection
val item = entities.single()
if (item != null && item is ModifiableWorkspaceEntityBase<*> && item.diff == null) {
@Suppress("KotlinConstantConditions", "UNCHECKED_CAST")
item.entityLinks[EntityLink(!isThisFieldChild, foundConnectionId)] = (item.entityLinks[EntityLink(!isThisFieldChild, foundConnectionId)] as? List<Any> ?: emptyList()) + this
myDiff.addEntity(item)
}
myDiff.updateOneToManyParentOfChild(foundConnectionId, this, item)
}
else {
// One - to -one connection
val item = entities.single()
if (item != null && item is ModifiableWorkspaceEntityBase<*> && item.diff == null) {
@Suppress("KotlinConstantConditions")
item.entityLinks[EntityLink(!isThisFieldChild, foundConnectionId)] = this
myDiff.addEntity(item)
}
myDiff.updateOneToOneParentOfChild(foundConnectionId, this, item)
}
}
}
else {
//if (foundConnectionId.parentClass == getEntityClass().toClassId()) {
if (isThisFieldChild) {
// Branch for case `this` entity is a parent
if (foundConnectionId.connectionType == ConnectionId.ConnectionType.ONE_TO_MANY || foundConnectionId.connectionType == ConnectionId.ConnectionType.ONE_TO_ABSTRACT_MANY) {
// One - to - many connection
@Suppress("KotlinConstantConditions")
this.entityLinks[EntityLink(isThisFieldChild, foundConnectionId)] = entities
for (item in entities) {
if (item != null && item is ModifiableWorkspaceEntityBase<*>) {
@Suppress("KotlinConstantConditions")
item.entityLinks[EntityLink(!isThisFieldChild, foundConnectionId)] = this
}
}
} else {
// One - to -one connection
val item = entities.single()
@Suppress("KotlinConstantConditions")
this.entityLinks[EntityLink(isThisFieldChild, foundConnectionId)] = item
if (item != null && item is ModifiableWorkspaceEntityBase<*>) {
@Suppress("KotlinConstantConditions")
item.entityLinks[EntityLink(!isThisFieldChild, foundConnectionId)] = this
}
}
}
else {
// Branch for case `this` entity is a child
if (foundConnectionId.connectionType == ConnectionId.ConnectionType.ONE_TO_MANY || foundConnectionId.connectionType == ConnectionId.ConnectionType.ONE_TO_ABSTRACT_MANY) {
// One - to - many connection
val item = entities.single()
@Suppress("KotlinConstantConditions")
this.entityLinks[EntityLink(isThisFieldChild, foundConnectionId)] = item
if (item != null && item is ModifiableWorkspaceEntityBase<*>) {
@Suppress("KotlinConstantConditions", "UNCHECKED_CAST")
item.entityLinks[EntityLink(!isThisFieldChild, foundConnectionId)] = (item.entityLinks[EntityLink(!isThisFieldChild, foundConnectionId)] as? List<Any> ?: emptyList()) + this
}
} else {
// One - to -one connection
val item = entities.single()
@Suppress("KotlinConstantConditions")
this.entityLinks[EntityLink(isThisFieldChild, foundConnectionId)] = item
if (item != null && item is ModifiableWorkspaceEntityBase<*>) {
@Suppress("KotlinConstantConditions")
item.entityLinks[EntityLink(!isThisFieldChild, foundConnectionId)] = this
}
}
}
}
}
private fun findConnectionId(entityClass: KClass<out WorkspaceEntity>, entity: List<WorkspaceEntity?>): ConnectionId? {
val someEntity = entity.filterNotNull().firstOrNull()
return if (someEntity != null) {
val firstClass = this.getEntityClass()
(someEntity as WorkspaceEntityBase).connectionIdList().single { it.parentClass == firstClass.toClassId() && it.childClass == entityClass.java.toClassId() || it.childClass == firstClass.toClassId() && it.parentClass == entityClass.java.toClassId() }
}
else {
val firstClass = this.getEntityClass()
entityLinks.keys.asSequence().map { it.connectionId }.singleOrNull { it.parentClass == firstClass.toClassId() && it.childClass == entityClass.java.toClassId() || it.childClass == firstClass.toClassId() && it.parentClass == entityClass.java.toClassId() }
}
}
override fun <R : WorkspaceEntity> referrers(entityClass: Class<R>, propertyName: String): Sequence<R> {
val myDiff = diff
val entitiesFromDiff = if (myDiff != null) {
getReferences(myDiff as AbstractEntityStorage, entityClass)
} else emptySequence()
val entityClassId = entityClass.toClassId()
val thisClassId = getEntityClass().toClassId()
val res = entityLinks.entries.singleOrNull {
it.key.connectionId.parentClass == entityClassId && it.key.connectionId.childClass == thisClassId
|| it.key.connectionId.parentClass == thisClassId && it.key.connectionId.childClass == entityClassId
}?.value
return entitiesFromDiff + if (res == null) {
emptySequence()
} else {
if (res is List<*>) {
@Suppress("UNCHECKED_CAST")
res.asSequence() as Sequence<R>
} else {
@Suppress("UNCHECKED_CAST")
sequenceOf(res as R)
}
}
}
inline fun allowModifications(action: () -> Unit) {
modifiable.set(true)
try {
action()
}
finally {
modifiable.remove()
}
}
protected fun checkModificationAllowed() {
if (diff != null && !modifiable.get()) {
throw IllegalStateException("Modifications are allowed inside `modifyEntity` method only!")
}
}
abstract fun getEntityClass(): Class<T>
open fun applyToBuilder(builder: MutableEntityStorage) {
throw NotImplementedError()
}
fun processLinkedEntities(builder: MutableEntityStorage) {
val parentKeysToRemove = ArrayList<EntityLink>()
for ((key, entity) in HashMap(entityLinks)) {
if (key.isThisFieldChild) {
processLinkedChildEntity(entity, builder, key.connectionId)
}
else {
processLinkedParentEntity(entity, builder, key, parentKeysToRemove)
}
}
for (key in parentKeysToRemove) {
val data = entityLinks[key]
if (data != null) {
if (data is List<*>) {
error("Cannot have parent lists")
}
else if (data is ModifiableWorkspaceEntityBase<*>) {
val remoteData = data.entityLinks[key.remote]
if (remoteData != null) {
if (remoteData is List<*>) {
data.entityLinks[key.remote] = remoteData.filterNot { it === this }
}
else {
data.entityLinks.remove(key.remote)
}
}
this.entityLinks.remove(key)
}
}
}
}
private fun processLinkedParentEntity(entity: Any?,
builder: MutableEntityStorage,
entityLink: EntityLink,
parentKeysToRemove: ArrayList<EntityLink>) {
if (entity is List<*>) {
error("Cannot have parent lists")
}
else if (entity is WorkspaceEntity) {
if (entity is ModifiableWorkspaceEntityBase<*> && entity.diff == null) {
builder.addEntity(entity)
}
applyParentRef(entityLink.connectionId, entity)
parentKeysToRemove.add(entityLink)
}
}
private fun processLinkedChildEntity(entity: Any?,
builder: MutableEntityStorage,
connectionId: ConnectionId) {
if (entity is List<*>) {
for (item in entity) {
if (item is ModifiableWorkspaceEntityBase<*>) {
builder.addEntity(item)
}
@Suppress("UNCHECKED_CAST")
entity as List<WorkspaceEntity>
val withBuilder_entity = entity.filter { it is ModifiableWorkspaceEntityBase<*> && it.diff != null }
applyRef(connectionId, withBuilder_entity)
}
}
else if (entity is WorkspaceEntity) {
builder.addEntity(entity)
applyRef(connectionId, entity)
}
}
open fun getEntityData(): WorkspaceEntityData<T> {
val actualEntityData = (diff as MutableEntityStorageImpl).entityDataById(id)
?: error("Requested entity data doesn't exist at entity family")
@Suppress("UNCHECKED_CAST")
return actualEntityData as WorkspaceEntityData<T>
}
// For generated entities
fun addToBuilder() {
val builder = diff as MutableEntityStorageImpl
builder.putEntity(this)
}
// For generated entities
private fun applyRef(connectionId: ConnectionId, child: WorkspaceEntity) {
val builder = diff as MutableEntityStorageImpl
when (connectionId.connectionType) {
ConnectionId.ConnectionType.ONE_TO_ONE -> builder.updateOneToOneChildOfParent(connectionId, this, child)
ConnectionId.ConnectionType.ABSTRACT_ONE_TO_ONE -> builder.updateOneToAbstractOneChildOfParent(connectionId, this, child)
else -> error("Unexpected branch")
}
}
private fun applyRef(connectionId: ConnectionId, children: List<WorkspaceEntity>) {
val builder = diff as MutableEntityStorageImpl
when (connectionId.connectionType) {
ConnectionId.ConnectionType.ONE_TO_MANY -> builder.updateOneToManyChildrenOfParent(connectionId, this, children)
ConnectionId.ConnectionType.ONE_TO_ABSTRACT_MANY -> builder.updateOneToAbstractManyChildrenOfParent(connectionId, this, children.asSequence())
else -> error("Unexpected branch")
}
}
private fun applyParentRef(connectionId: ConnectionId, parent: WorkspaceEntity) {
val builder = diff as MutableEntityStorageImpl
when (connectionId.connectionType) {
ConnectionId.ConnectionType.ONE_TO_ONE -> builder.updateOneToOneParentOfChild(connectionId, this, parent)
ConnectionId.ConnectionType.ABSTRACT_ONE_TO_ONE -> builder.updateOneToAbstractOneParentOfChild(connectionId, this, parent)
ConnectionId.ConnectionType.ONE_TO_MANY -> builder.updateOneToManyParentOfChild(connectionId, this, parent)
ConnectionId.ConnectionType.ONE_TO_ABSTRACT_MANY -> builder.updateOneToAbstractManyParentOfChild(connectionId, this, parent)
}
}
fun existsInBuilder(builder: MutableEntityStorage): Boolean {
builder as MutableEntityStorageImpl
val entityData = getEntityData()
return builder.entityDataById(entityData.createEntityId()) != null
}
// For generated entities
fun index(entity: WorkspaceEntity, propertyName: String, virtualFileUrl: VirtualFileUrl?) {
val builder = diff as MutableEntityStorageImpl
builder.getMutableVirtualFileUrlIndex().index(entity, propertyName, virtualFileUrl)
}
// For generated entities
fun index(entity: WorkspaceEntity, propertyName: String, virtualFileUrls: Set<VirtualFileUrl>) {
val builder = diff as MutableEntityStorageImpl
(builder.getMutableVirtualFileUrlIndex() as VirtualFileIndex.MutableVirtualFileIndex).index((entity as WorkspaceEntityBase).id,
propertyName, virtualFileUrls)
}
// For generated entities
fun indexJarDirectories(entity: WorkspaceEntity, virtualFileUrls: Set<VirtualFileUrl>) {
val builder = diff as MutableEntityStorageImpl
(builder.getMutableVirtualFileUrlIndex() as VirtualFileIndex.MutableVirtualFileIndex).indexJarDirectories(
(entity as WorkspaceEntityBase).id, virtualFileUrls)
}
}
interface SoftLinkable {
fun getLinks(): Set<PersistentEntityId<*>>
fun index(index: WorkspaceMutableIndex<PersistentEntityId<*>>)
fun updateLinksIndex(prev: Set<PersistentEntityId<*>>, index: WorkspaceMutableIndex<PersistentEntityId<*>>)
fun updateLink(oldLink: PersistentEntityId<*>, newLink: PersistentEntityId<*>): Boolean
}
abstract class WorkspaceEntityData<E : WorkspaceEntity> : Cloneable, SerializableEntityData {
lateinit var entitySource: EntitySource
var id: Int = -1
fun isEntitySourceInitialized(): Boolean = ::entitySource.isInitialized
fun createEntityId(): EntityId = createEntityId(id, getEntityInterface().toClassId())
abstract fun createEntity(snapshot: EntityStorage): E
abstract fun wrapAsModifiable(diff: MutableEntityStorage): ModifiableWorkspaceEntity<E>
abstract fun getEntityInterface(): Class<out WorkspaceEntity>
@Suppress("UNCHECKED_CAST")
public override fun clone(): WorkspaceEntityData<E> = super.clone() as WorkspaceEntityData<E>
override fun equals(other: Any?): Boolean {
if (other == null) return false
if (this::class != other::class) return false
return ReflectionUtil.collectFields(this.javaClass).filterNot { it.name == WorkspaceEntityData<*>::id.name }
.onEach { it.isAccessible = true }
.all { it.get(this) == it.get(other) }
}
open fun equalsIgnoringEntitySource(other: Any?): Boolean {
if (other == null) return false
if (this::class != other::class) return false
return ReflectionUtil.collectFields(this.javaClass)
.filterNot { it.name == WorkspaceEntityData<*>::id.name }
.filterNot { it.name == WorkspaceEntityData<*>::entitySource.name }
.onEach { it.isAccessible = true }
.all { it.get(this) == it.get(other) }
}
override fun hashCode(): Int {
return ReflectionUtil.collectFields(this.javaClass).filterNot { it.name == WorkspaceEntityData<*>::id.name }
.onEach { it.isAccessible = true }
.mapNotNull { it.get(this)?.hashCode() }
.fold(31) { acc, i -> acc * 17 + i }
}
override fun toString(): String {
val fields = ReflectionUtil.collectFields(this.javaClass).toList().onEach { it.isAccessible = true }
.joinToString(separator = ", ") { f -> "${f.name}=${f.get(this)}" }
return "${this::class.simpleName}($fields, id=${this.id})"
}
/**
* Temporally solution.
* Get persistent Id without creating of TypedEntity. Should be in sync with TypedEntityWithPersistentId.
* But it doesn't everywhere. E.g. FacetEntity where we should resolve module before creating persistent id.
*/
abstract class WithCalculablePersistentId<E : WorkspaceEntity> : WorkspaceEntityData<E>() {
abstract fun persistentId(): PersistentEntityId<*>
}
}
fun WorkspaceEntityData<*>.persistentId(): PersistentEntityId<*>? = when (this) {
is WorkspaceEntityData.WithCalculablePersistentId -> this.persistentId()
else -> null
}
/**
* This interface is a solution for checking consistency of some entities that can't be checked automatically
*
* For example, we can mark LibraryPropertiesEntityData with this interface and check that entity source of properties is the same as
* entity source of the library itself.
*
* Interface should be applied to *entity data*.
*
* [assertConsistency] method is called during [MutableEntityStorageImpl.assertConsistency].
*/
interface WithAssertableConsistency {
fun assertConsistency(storage: EntityStorage)
}
|
apache-2.0
|
c5d7b31442e4a93c0308f00c750194e3
| 42.516239 | 259 | 0.680468 | 5.158257 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.