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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
googlesamples/mlkit | android/material-showcase/app/src/main/java/com/google/mlkit/md/camera/FrameProcessorBase.kt | 1 | 3666 | /*
* Copyright 2020 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.mlkit.md.camera
import android.os.SystemClock
import android.util.Log
import androidx.annotation.GuardedBy
import com.google.android.gms.tasks.OnFailureListener
import com.google.android.gms.tasks.Task
import com.google.android.gms.tasks.TaskExecutors
import com.google.mlkit.md.addOnFailureListener
import com.google.mlkit.md.addOnSuccessListener
import com.google.mlkit.md.CameraInputInfo
import com.google.mlkit.md.InputInfo
import com.google.mlkit.md.ScopedExecutor
import com.google.mlkit.vision.common.InputImage
import java.nio.ByteBuffer
/** Abstract base class of [FrameProcessor]. */
abstract class FrameProcessorBase<T> : FrameProcessor {
// To keep the latest frame and its metadata.
@GuardedBy("this")
private var latestFrame: ByteBuffer? = null
@GuardedBy("this")
private var latestFrameMetaData: FrameMetadata? = null
// To keep the frame and metadata in process.
@GuardedBy("this")
private var processingFrame: ByteBuffer? = null
@GuardedBy("this")
private var processingFrameMetaData: FrameMetadata? = null
private val executor = ScopedExecutor(TaskExecutors.MAIN_THREAD)
@Synchronized
override fun process(
data: ByteBuffer,
frameMetadata: FrameMetadata,
graphicOverlay: GraphicOverlay
) {
latestFrame = data
latestFrameMetaData = frameMetadata
if (processingFrame == null && processingFrameMetaData == null) {
processLatestFrame(graphicOverlay)
}
}
@Synchronized
private fun processLatestFrame(graphicOverlay: GraphicOverlay) {
processingFrame = latestFrame
processingFrameMetaData = latestFrameMetaData
latestFrame = null
latestFrameMetaData = null
val frame = processingFrame ?: return
val frameMetaData = processingFrameMetaData ?: return
val image = InputImage.fromByteBuffer(
frame,
frameMetaData.width,
frameMetaData.height,
frameMetaData.rotation,
InputImage.IMAGE_FORMAT_NV21
)
val startMs = SystemClock.elapsedRealtime()
detectInImage(image)
.addOnSuccessListener(executor) { results: T ->
Log.d(TAG, "Latency is: ${SystemClock.elapsedRealtime() - startMs}")
[email protected](CameraInputInfo(frame, frameMetaData), results, graphicOverlay)
processLatestFrame(graphicOverlay)
}
.addOnFailureListener(executor) { e -> OnFailureListener { [email protected](it) } }
}
override fun stop() {
executor.shutdown()
}
protected abstract fun detectInImage(image: InputImage): Task<T>
/** Be called when the detection succeeds. */
protected abstract fun onSuccess(
inputInfo: InputInfo,
results: T,
graphicOverlay: GraphicOverlay
)
protected abstract fun onFailure(e: Exception)
companion object {
private const val TAG = "FrameProcessorBase"
}
}
| apache-2.0 | 484ebc329323f7d5cef223dc60d8ee38 | 33.261682 | 113 | 0.699673 | 4.748705 | false | true | false | false |
lukashaertel/megal-vm | src/main/kotlin/org/softlang/util/cli/OptionParser.kt | 1 | 5740 | package org.softlang.util.cli
import org.softlang.util.*
import java.io.PrintStream
/**
* Base class for objects that parse arguments
*/
abstract class OptionParser(val args: Array<String>,
val name: String? = null,
val description: String? = null,
val example: String? = null) {
/**
* All rules
*/
var rules: List<OptionDelegate> = emptyList()
/**
* Gets all indicators of keys
*/
val keys by lazy {
rules.flatMap {
listOf("-${it.shorthand}", "--${it.name}")
}
}
/**
* Gets all indicators of boolean flags
*/
val flags by lazy {
rules.filter { it.flag }.flatMap {
listOf("-${it.shorthand}", "--${it.name}")
}
}
/**
* All arguments in a parsed fashion.
*/
val parsed: List<Pair<String?, String>> by lazy {
fun eval(input: List<String>): List<Pair<String?, String>> {
val head = input.getOrNull(0)
val next = input.getOrNull(1)
// No head, end of list
if (head == null)
return listOf()
// Head is a boolean, special treatment applies
if (head in flags)
return when (next) {
// Consume following true or false
"true", "false" -> head to next then eval(input.skip(2))
// Otherwise regard as true
else -> head to "true" then eval(input.tail())
}
// Head does not start with dash, it's a free argument
if (!head.startsWith("-"))
return null to head then eval(input.tail())
// If no next, regard head as free argument anyways, otherwise
// standard treatment applies
if (next == null)
return listOf(null to head)
else
return head to next then eval(input.skip(2))
}
// Return by recursive evaluator application
eval(args.toList())
}
/**
* All unknown assignments
*/
val unknown by lazy {
parsed.filter { it.first !in keys }.map { it.second }
}
/**
* Prints the help message to the given output stream.
* @param printStream The output to print to, defaults to stdout
*/
fun printHelp(printStream: PrintStream = System.out) = printStream.apply {
// Print title
if (name != null) {
println("$name")
println()
}
// Print program description
if (description != null) {
println("Description:")
println(description.indent(" "))
println()
}
// Print program description
if (example != null) {
println("Example:")
println(example.indent(" "))
println()
}
// Prefix arguments
if (rules.isNotEmpty()) {
println("Arguments:")
}
// Print parser rules
for (rule in rules) {
val shorthand = rule.shorthand
val flag = rule.flag
val name = rule.name
val description = rule.description
when (rule) {
// Handle regular options
is OptionSingleDelegate<*>, is OptionListDelegate<*> -> {
print(" ")
// Format shorthand if present
if (shorthand != null)
print("-$shorthand, ")
else
print(" ")
// Format long name
print("--$name")
// Prepare value
val value = when (rule) {
is OptionSingleDelegate<*> ->
if (rule.flag)
"(true|false)"
else
rule.default?.toString() ?: "VALUE"
is OptionListDelegate<*> ->
if (rule.flag)
"(true|false)"
else
rule.default?.toString() ?: "VALUE"
else -> error("Should never get here")
}
// Print value and finalize line
println(" $value:")
// If description present print description
if (description != null)
println(description.indent(" "))
}
// Handle extra options
is ExtraDelegate -> {
// Prepare value
val value = rule.default?.toString() ?: "VALUE"
// Print value and finalize line
println(" Extra arguments $value:")
// If description present print description
if (description != null)
println(description.indent(" "))
}
// Handle unknown options
is UnknownDelegate -> {
println(" For all unknown options:")
// If description present print description
if (description != null)
println(description.indent(" "))
else
println("Handled but not specified any further."
.indent(" "))
}
}
// Separate rules
if (rule != rules.last())
println()
}
}
} | mit | adac610de98957c307ef226f03bf7c60 | 30.032432 | 78 | 0.444077 | 5.578231 | false | false | false | false |
eraga/rxusb | core/src/main/kotlin/net/eraga/rxusb/UsbEndpoint.kt | 1 | 3725 | package net.eraga.rxusb
/**
* A class representing an endpoint on a [UsbInterface].
* Endpoints are the channels for sending and receiving data over USB.
* Typically bulk endpoints are used for sending non-trivial amounts of data.
* Interrupt endpoints are used for sending small amounts of data, typically events,
* separately from the main data streams.
*
* The endpoint zero is a special endpoint for control messages sent from the host
* to device.
*
* Isochronous endpoints are currently unsupported.
*
* UsbEndpoint should only be instantiated by UsbService implementation
* @hide
*/
class UsbEndpoint(
val address: Int,
val attributes: Int,
val maxPacketSize: Int,
val interval: Int
) {
private var _usbInterface: UsbInterface? = null
var usbInterface: UsbInterface
set(value) = if (_usbInterface == null) _usbInterface = value else throw IllegalStateException("Field can be " +
"initialized only once")
get() = _usbInterface ?: throw IllegalStateException("Initialization is not completed")
// private var _inChannel: ReadableByteChannel? = null
// private var _outChannel: WritableByteChannel? = null
//
// val readableChannel: ReadableByteChannel
// get() {
// return _inChannel ?: throw NonReadableChannelException()
// }
//
// val writableChannel: WritableByteChannel
// get() {
// return _outChannel ?: throw NonWritableChannelException()
// }
/**
* Extracts the endpoint's endpoint number from its address
*
* @return the endpoint's endpoint number
*/
fun getEndpointNumber(): Int {
return address and UsbConstants.USB_ENDPOINT_NUMBER_MASK
}
/**
* Returns the endpoint's direction.
* Returns [UsbConstants.USB_DIR_OUT]
* if the direction is host to device, and
* [UsbConstants.USB_DIR_IN] if the
* direction is device to host.
*
* @see UsbConstants.USB_DIR_IN
* @see UsbConstants.USB_DIR_OUT
*
* @return the endpoint's direction
*/
fun getDirection(): Int {
return address and UsbConstants.USB_ENDPOINT_DIR_MASK
}
/**
* Returns the endpoint's type.
* Possible results are:
*
* * [UsbConstants.USB_ENDPOINT_XFER_CONTROL] (endpoint zero)
* * [UsbConstants.USB_ENDPOINT_XFER_ISOC] (isochronous endpoint)
* * [UsbConstants.USB_ENDPOINT_XFER_BULK] (bulk endpoint)
* * [UsbConstants.USB_ENDPOINT_XFER_INT] (interrupt endpoint)
*
* @return the endpoint's type
*/
fun getType(): Int {
return attributes and UsbConstants.USB_ENDPOINT_XFERTYPE_MASK
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other !is UsbEndpoint) return false
if (address != other.address) return false
if (attributes != other.attributes) return false
if (maxPacketSize != other.maxPacketSize) return false
if (interval != other.interval) return false
if (_usbInterface != other._usbInterface) return false
return true
}
override fun hashCode(): Int {
var result = address
result = 31 * result + attributes
result = 31 * result + maxPacketSize
result = 31 * result + interval
result = 31 * result + (_usbInterface?.hashCode() ?: 0)
return result
}
override fun toString(): String {
return "\n\t\tUsbEndpoint(\n" +
"\t\t\taddress=$address\n" +
"\t\t\tattributes=$attributes\n" +
"\t\t\tmaxPacketSize=$maxPacketSize\n" +
"\t\t\tinterval=$interval)"
}
}
| apache-2.0 | 23e3bd11ce4284ca046f76339d1931ef | 30.041667 | 120 | 0.632752 | 4.22815 | false | false | false | false |
NextFaze/dev-fun | devfun-internal/src/main/java/com/nextfaze/devfun/internal/android/ActivityCallbacks.kt | 1 | 2506 | package com.nextfaze.devfun.internal.android
import android.app.Activity
import android.app.Application
import android.content.Context
import android.os.Bundle
typealias OnActivityCreated = (activity: Activity, savedInstanceState: Bundle?) -> Unit
typealias OnActivityStarted = (activity: Activity) -> Unit
typealias OnActivityResumed = (activity: Activity) -> Unit
typealias OnActivityPaused = (activity: Activity) -> Unit
typealias OnActivityStopped = (activity: Activity) -> Unit
typealias OnActivitySave = (activity: Activity, outState: Bundle) -> Unit
typealias OnActivityDestroyed = (activity: Activity) -> Unit
abstract class AbstractActivityLifecycleCallbacks : Application.ActivityLifecycleCallbacks {
override fun onActivityCreated(activity: Activity, savedInstanceState: Bundle?) = Unit
override fun onActivityStarted(activity: Activity) = Unit
override fun onActivityResumed(activity: Activity) = Unit
override fun onActivityPaused(activity: Activity) = Unit
override fun onActivityStopped(activity: Activity) = Unit
override fun onActivitySaveInstanceState(activity: Activity, outState: Bundle) = Unit
override fun onActivityDestroyed(activity: Activity) = Unit
}
inline fun Context.registerActivityCallbacks(
crossinline onCreated: OnActivityCreated = { _, _ -> },
crossinline onStarted: OnActivityStarted = {},
crossinline onResumed: OnActivityResumed = {},
crossinline onPaused: OnActivityPaused = {},
crossinline onStopped: OnActivityStopped = {},
crossinline onSave: OnActivitySave = { _, _ -> },
crossinline onDestroyed: OnActivityDestroyed = {}
) = registerActivityLifecycleCallbacks(object : AbstractActivityLifecycleCallbacks() {
override fun onActivityCreated(activity: Activity, savedInstanceState: Bundle?) = onCreated.invoke(activity, savedInstanceState)
override fun onActivityStarted(activity: Activity) = onStarted.invoke(activity)
override fun onActivityResumed(activity: Activity) = onResumed.invoke(activity)
override fun onActivityPaused(activity: Activity) = onPaused.invoke(activity)
override fun onActivityStopped(activity: Activity) = onStopped.invoke(activity)
override fun onActivitySaveInstanceState(activity: Activity, outState: Bundle) = onSave.invoke(activity, outState)
override fun onActivityDestroyed(activity: Activity) = onDestroyed.invoke(activity)
})
fun Application.ActivityLifecycleCallbacks.unregister(context: Context) = context.unregisterActivityCallbacks(this)
| apache-2.0 | 024fd2d2f7606c1e49bd20906e75421a | 55.954545 | 132 | 0.789705 | 5.16701 | false | false | false | false |
cwoolner/flex-poker | src/main/kotlin/com/flexpoker/table/command/aggregate/HandEvaluation.kt | 1 | 5574 | package com.flexpoker.table.command.aggregate
import com.flexpoker.table.command.CardRank
import com.flexpoker.table.command.HandRanking
import java.util.UUID
class HandEvaluation : Comparable<HandEvaluation> {
var playerId: UUID? = null
var handRanking: HandRanking? = null
var primaryCardRank: CardRank? = null
var secondaryCardRank: CardRank? = null
var firstKicker: CardRank? = null
var secondKicker: CardRank? = null
var thirdKicker: CardRank? = null
var fourthKicker: CardRank? = null
override fun compareTo(other: HandEvaluation): Int {
return if (handRanking !== other.handRanking) {
handRanking!!.compareTo(other.handRanking!!)
} else when (handRanking) {
HandRanking.HIGH_CARD -> highCardCompareTo(other)
HandRanking.ONE_PAIR -> onePairCompareTo(other)
HandRanking.TWO_PAIR -> twoPairCompareTo(other)
HandRanking.THREE_OF_A_KIND -> threeOfAKindCompareTo(other)
HandRanking.STRAIGHT -> straightCompareTo(other)
HandRanking.FLUSH -> flushCompareTo(other)
HandRanking.FULL_HOUSE -> fullHouseCompareTo(other)
HandRanking.FOUR_OF_A_KIND -> fourOfAKindCompareTo(other)
HandRanking.STRAIGHT_FLUSH -> straightFlushCompareTo(other)
else -> throw IllegalArgumentException("The given HandEvaluation could not be correctly compared.")
}
}
private fun highCardCompareTo(otherHandEvaluation: HandEvaluation): Int {
return if (primaryCardRank == otherHandEvaluation.primaryCardRank) {
if (firstKicker == otherHandEvaluation.firstKicker) {
if (secondKicker == otherHandEvaluation.secondKicker) {
if (thirdKicker == otherHandEvaluation.thirdKicker) {
fourthKicker!!.compareTo(otherHandEvaluation.fourthKicker!!)
} else thirdKicker!!.compareTo(otherHandEvaluation.thirdKicker!!)
} else secondKicker!!.compareTo(otherHandEvaluation.secondKicker!!)
} else firstKicker!!.compareTo(otherHandEvaluation.firstKicker!!)
} else primaryCardRank!!.compareTo(otherHandEvaluation.primaryCardRank!!)
}
private fun onePairCompareTo(otherHandEvaluation: HandEvaluation): Int {
return if (primaryCardRank == otherHandEvaluation.primaryCardRank) {
if (firstKicker == otherHandEvaluation.firstKicker) {
if (secondKicker == otherHandEvaluation.secondKicker) {
thirdKicker!!.compareTo(otherHandEvaluation.thirdKicker!!)
} else secondKicker!!.compareTo(otherHandEvaluation.secondKicker!!)
} else firstKicker!!.compareTo(otherHandEvaluation.firstKicker!!)
} else primaryCardRank!!.compareTo(otherHandEvaluation.primaryCardRank!!)
}
private fun twoPairCompareTo(otherHandEvaluation: HandEvaluation): Int {
return if (primaryCardRank == otherHandEvaluation.primaryCardRank) {
if (secondaryCardRank == otherHandEvaluation.secondaryCardRank) {
firstKicker!!.compareTo(otherHandEvaluation.firstKicker!!)
} else secondaryCardRank!!.compareTo(otherHandEvaluation.secondaryCardRank!!)
} else primaryCardRank!!.compareTo(otherHandEvaluation.primaryCardRank!!)
}
private fun threeOfAKindCompareTo(otherHandEvaluation: HandEvaluation): Int {
return if (primaryCardRank == otherHandEvaluation.primaryCardRank) {
if (firstKicker == otherHandEvaluation.firstKicker) {
secondKicker!!.compareTo(otherHandEvaluation.secondKicker!!)
} else firstKicker!!.compareTo(otherHandEvaluation.firstKicker!!)
} else primaryCardRank!!.compareTo(otherHandEvaluation.primaryCardRank!!)
}
private fun straightCompareTo(otherHandEvaluation: HandEvaluation): Int {
return primaryCardRank!!.compareTo(otherHandEvaluation.primaryCardRank!!)
}
private fun flushCompareTo(otherHandEvaluation: HandEvaluation): Int {
return if (primaryCardRank == otherHandEvaluation.primaryCardRank) {
if (firstKicker == otherHandEvaluation.firstKicker) {
if (secondKicker == otherHandEvaluation.secondKicker) {
if (thirdKicker == otherHandEvaluation.thirdKicker) {
fourthKicker!!.compareTo(otherHandEvaluation.fourthKicker!!)
} else thirdKicker!!.compareTo(otherHandEvaluation.thirdKicker!!)
} else secondKicker!!.compareTo(otherHandEvaluation.secondKicker!!)
} else firstKicker!!.compareTo(otherHandEvaluation.firstKicker!!)
} else primaryCardRank!!.compareTo(otherHandEvaluation.primaryCardRank!!)
}
private fun fullHouseCompareTo(otherHandEvaluation: HandEvaluation): Int {
return if (primaryCardRank == otherHandEvaluation.primaryCardRank) {
secondaryCardRank!!.compareTo(otherHandEvaluation.secondaryCardRank!!)
} else primaryCardRank!!.compareTo(otherHandEvaluation.primaryCardRank!!)
}
private fun fourOfAKindCompareTo(otherHandEvaluation: HandEvaluation): Int {
return if (primaryCardRank == otherHandEvaluation.primaryCardRank) {
firstKicker!!.compareTo(otherHandEvaluation.firstKicker!!)
} else primaryCardRank!!.compareTo(otherHandEvaluation.primaryCardRank!!)
}
private fun straightFlushCompareTo(otherHandEvaluation: HandEvaluation): Int {
return primaryCardRank!!.compareTo(otherHandEvaluation.primaryCardRank!!)
}
} | gpl-2.0 | d6a4622f37af3e071d5ba5fa02df4f38 | 53.126214 | 111 | 0.700574 | 4.855401 | false | false | false | false |
nemerosa/ontrack | ontrack-extension-general/src/test/java/net/nemerosa/ontrack/extension/general/BuildLinkDecorationIT.kt | 1 | 4407 | package net.nemerosa.ontrack.extension.general
import net.nemerosa.ontrack.it.AbstractDSLTestJUnit4Support
import net.nemerosa.ontrack.model.structure.Build
import net.nemerosa.ontrack.model.structure.Project
import net.nemerosa.ontrack.test.TestUtils.uid
import org.junit.Test
import org.springframework.beans.factory.annotation.Autowired
import kotlin.test.assertEquals
/**
* In this test, we assume the source project is part of the main labels (see [MainBuildLinksProjectPropertyType])
* and that it is always displayed.
*/
class BuildLinkDecorationIT : AbstractDSLTestJUnit4Support() {
private val targetBuildName = "2"
private val targetLabel = "v2.0.0"
@Autowired
private lateinit var buildLinkDecorationExtension: BuildLinkDecorationExtension
@Test
fun `Build link decoration using build name when not having label when project not configured`() {
testBuildLinkDisplayOptions(
useLabel = null,
label = null,
expectedLabel = targetBuildName
)
}
@Test
fun `Build link decoration using build name when having label when project not configured`() {
testBuildLinkDisplayOptions(
useLabel = null,
label = targetLabel,
expectedLabel = targetBuildName
)
}
@Test
fun `Build link decoration using build name when having label when project configured to not use label`() {
testBuildLinkDisplayOptions(
useLabel = false,
label = targetLabel,
expectedLabel = targetBuildName
)
}
@Test
fun `Build link decoration using build name when not having label when project configured to not use label`() {
testBuildLinkDisplayOptions(
useLabel = false,
label = null,
expectedLabel = targetBuildName
)
}
@Test
fun `Build link decoration using label when having label when project configured to use label`() {
testBuildLinkDisplayOptions(
useLabel = true,
label = targetLabel,
expectedLabel = targetLabel
)
}
@Test
fun `Build link decoration using build name when not having label when project configured to use label`() {
testBuildLinkDisplayOptions(
useLabel = true,
label = null,
expectedLabel = targetBuildName
)
}
private fun testBuildLinkDisplayOptions(
useLabel: Boolean?,
label: String?,
expectedLabel: String
) {
val projectLabel = uid("L")
withMainBuildLinksSettings {
setMainBuildLinksSettings(projectLabel)
project target@{
labels = listOf(label(category = null, name = projectLabel))
if (useLabel != null) {
buildLinkDisplaysOptions(useLabel)
}
branch {
build("2") {
if (label != null) {
label(label)
}
}
project {
branch {
build("1") {
linkTo(this@target, "2")
checkLabel(expectedLabel)
}
}
}
}
}
}
}
private fun Project.buildLinkDisplaysOptions(useLabel: Boolean) {
setProperty(
this,
BuildLinkDisplayPropertyType::class.java,
BuildLinkDisplayProperty(useLabel)
)
}
private fun Build.label(label: String) {
setProperty(
this,
ReleasePropertyType::class.java,
ReleaseProperty(label)
)
}
private fun Build.checkLabel(expectedLabel: String) {
val decorations = buildLinkDecorationExtension.getDecorations(this)
assertEquals(1, decorations.size)
val mainDecorations = decorations[0].data.decorations
assertEquals(1, mainDecorations.size)
val decoration = mainDecorations[0]
assertEquals(expectedLabel, decoration.label, "Build $name decoration's label is expected to be $expectedLabel")
}
} | mit | db8112ed1f0d4763db3cd301274c6f79 | 31.895522 | 120 | 0.576583 | 5.316043 | false | true | false | false |
mockk/mockk | modules/mockk/src/commonMain/kotlin/io/mockk/impl/verify/VerificationHelpers.kt | 1 | 3379 | package io.mockk.impl.verify
import io.mockk.Invocation
import io.mockk.MockKSettings
import io.mockk.RecordedCall
import io.mockk.StackElement
import io.mockk.StackTracesAlignment
import io.mockk.impl.InternalPlatform
import io.mockk.impl.stub.StubRepository
object VerificationHelpers {
fun formatCalls(calls: List<Invocation>, verifiedCalls: List<Invocation> = listOf()): String {
return calls.mapIndexed { idx, call ->
val plusSign = (if (verifiedCalls.contains(call)) "+" else "")
"${idx + 1}) $plusSign$call"
}.joinToString("\n")
}
fun stackTraces(calls: List<Invocation>): String {
return calls.mapIndexed { idx, call ->
val prefix = "${idx + 1})"
"$prefix ${stackTrace(prefix.length + 1, call.callStack())}"
}.joinToString("\n\n")
}
fun stackTrace(prefix: Int, stackTrace: List<StackElement>): String {
@Suppress("DEPRECATION_ERROR")
fun columnSize(block: StackElement.() -> String) =
stackTrace.map(block).map { it.length }.maxOfOrNull { it } ?: 0
fun StackElement.fileLine() =
"($fileName:$line)${if (nativeMethod) "N" else ""}"
fun spaces(n: Int) = if (n < 0) "" else (1..n).joinToString("") { " " }
fun columnRight(s: String, sz: Int) = spaces(sz - s.length) + s
fun columnLeft(s: String, sz: Int) = s + spaces(sz - s.length)
val maxClassNameLen = columnSize { className }
val maxMethodLen = columnSize { methodName }
val maxThirdColumn = columnSize { fileLine() }
val lineFormatter: (StackElement) -> String = if(MockKSettings.stackTracesAlignment == StackTracesAlignment.CENTER) {
{
spaces(prefix) +
columnRight(it.className, maxClassNameLen) + "." +
columnLeft(it.methodName, maxMethodLen) + " " +
columnLeft(it.fileLine(), maxThirdColumn)
}
} else {
{
spaces(prefix) +
it.className + "." +
it.methodName + " " +
it.fileLine()
}
}
return stackTrace.joinToString("\n") {
lineFormatter(it)
}.substring(prefix)
}
fun List<RecordedCall>.allInvocations(stubRepo: StubRepository) =
this.map { InternalPlatform.ref(it.matcher.self) }
.distinct()
.map { it.value }
.flatMap { stubRepo.stubFor(it).allRecordedCalls() }
.sortedBy { it.timestamp }
fun reportCalls(
matchers: List<RecordedCall>,
allCalls: List<Invocation>,
lcs: LCSMatchingAlgo = LCSMatchingAlgo(allCalls, matchers).apply { lcs() }
): String {
return "\n\nMatchers: \n" + formatMatchers(matchers, lcs.verifiedMatchers) +
"\n\nCalls:\n" +
formatCalls(allCalls, lcs.verifiedCalls) +
"\n" +
if (MockKSettings.stackTracesOnVerify)
"\nStack traces:\n" + stackTraces(allCalls)
else
""
}
private fun formatMatchers(matchers: List<RecordedCall>, verifiedMatchers: List<RecordedCall>) =
matchers.joinToString("\n") {
(if (verifiedMatchers.contains(it)) "+" else "") + it.matcher.toString()
}
}
| apache-2.0 | 459c17a94c6ffd73e05c3d808fc6b0e9 | 35.333333 | 125 | 0.570583 | 4.29352 | false | false | false | false |
ptrgags/holo-pyramid | app/src/main/java/io/github/ptrgags/holopyramid/HoloPyramidScene2D.kt | 1 | 3253 | package io.github.ptrgags.holopyramid
import android.util.Log
import org.rajawali3d.materials.Material
import org.rajawali3d.materials.textures.ATexture
import org.rajawali3d.primitives.ScreenQuad
import org.rajawali3d.renderer.RenderTarget
import org.rajawali3d.renderer.Renderer
import org.rajawali3d.scene.Scene
/**
* A 2D scene with the four ScreenQuads that are textured
* with the four views of the object.
*
* Scene layout
*
* quad 2 (cam 2)
*
* quad 3 (cam 3) quad 1 (cam 1)
*
* quad 0 (cam 0)
*
* +y
* |
* |
* |
* +------- +x
*
* @param renderer the parent renderer (needed by Scene)
* @param renderTargets list of the four render targets, one for each
* view of the objectt
* @param aspectRatio aspect ratio. This is used to position the screen quads
*/
class HoloPyramidScene2D(
renderer: Renderer,
renderTargets: List<RenderTarget>,
val aspectRatio: Double) : Scene(renderer) {
companion object {
/** There are four views for the four sides of the pyramid */
val NUM_QUADS = 4
/** shrink each quad a bit so we can fit them all on screen*/
val QUAD_SCALE = 0.25
/**
* The quads are arranged at the four corners of a circle
* with this radius
*/
val QUAD_RADIUS = 0.25
/** Logging tag */
val TAG = "holopyramid-scene2d"
}
init {
createQuads(renderTargets)
createCenterMarker()
}
/**
* Create four ScreenQuads, one for each view of the object
* @param targets the render targets that are used to texture
* the ScreenQuads
*/
private fun createQuads(targets: List<RenderTarget>) {
for (i in 0 until NUM_QUADS) {
// Make a texture from the render target
val mat = Material()
mat.colorInfluence = 0.0f
try {
mat.addTexture(targets[i].texture)
} catch (e: ATexture.TextureException) {
Log.e(TAG, "Error adding material", e)
}
// Make the quad and attach the render target's texture.
// The quad is scaled down since we need to fit four
// of them on the screen
val quad = ScreenQuad()
quad.setScale(QUAD_SCALE, QUAD_SCALE, 1.0)
quad.material = mat
// Position the quads.
quad.x = QUAD_RADIUS * Math.sin(i * Math.PI / 2.0)
quad.y = QUAD_RADIUS * aspectRatio * -Math.cos(i * Math.PI / 2.0)
addChild(quad)
}
}
/**
* Make another screen quad in the center of the screen.
* This will make it easier to line up the pyramid mirror
*/
private fun createCenterMarker() {
// Simple solid color material. It's dark
// so it doesn't show up much in the mirror yet it stands out
// against the black background
val mat = Material()
mat.color = 0x202020
// Add a small quad to mark the center of the screen
val quad = ScreenQuad()
val MARKER_SCALE = 0.1
quad.setScale(MARKER_SCALE, MARKER_SCALE * aspectRatio, 1.0)
quad.material = mat
addChild(quad)
}
} | gpl-3.0 | 6f83b56a14141fefc4b27b52380fe234 | 29.411215 | 77 | 0.594836 | 4.011097 | false | false | false | false |
mockk/mockk | modules/mockk-agent-api/src/jvmMain/kotlin/io/mockk/proxy/common/transformation/ClassTransformationSpecMap.kt | 2 | 2105 | package io.mockk.proxy.common.transformation
import io.mockk.proxy.common.transformation.TransformationType.*
import java.util.*
import java.util.concurrent.locks.ReentrantLock
import kotlin.concurrent.withLock
class ClassTransformationSpecMap {
private val classSpecs = WeakHashMap<Class<*>, ClassTransformationSpec>()
private val transformationLock = ReentrantLock(true)
private val specLock = ReentrantLock()
fun applyTransformation(
request: TransformationRequest,
retransformClasses: (TransformationRequest) -> Unit
) = transformationLock.withLock {
val result = mutableListOf<Class<*>>()
specLock.withLock {
for (cls in request.classes) {
val spec = classSpecs[cls]
?: ClassTransformationSpec(cls)
val diff = if (request.untransform) -1 else 1
val newSpec =
when (request.type) {
SIMPLE -> spec.copy(simpleIntercept = spec.simpleIntercept + diff)
STATIC -> spec.copy(staticIntercept = spec.staticIntercept + diff)
CONSTRUCTOR -> spec.copy(constructorIntercept = spec.constructorIntercept + diff)
}
classSpecs[cls] = newSpec
if (!(spec sameTransforms newSpec)) {
result.add(cls)
}
}
}
retransformClasses(request.copy(classes = result.toSet()))
}
fun shouldTransform(clazz: Class<*>?) =
specLock.withLock {
classSpecs[clazz] != null
}
operator fun get(clazz: Class<*>?) =
specLock.withLock {
classSpecs[clazz]
?.apply {
if (!shouldDoSomething) {
classSpecs.remove(clazz)
}
}
}
fun transformationMap(request: TransformationRequest): Map<String, String> =
specLock.withLock {
request.classes.map { it.simpleName to classSpecs[it].toString() }.toMap()
}
} | apache-2.0 | a14019cbc6c8f2692fb758492f1db53a | 31.90625 | 105 | 0.574822 | 5.210396 | false | false | false | false |
kiruto/kotlin-android-mahjong | mahjanmodule/src/main/kotlin/dev/yuriel/kotmahjan/ai/analysis/analysis_core.kt | 1 | 14718 | /*
* The MIT License (MIT)
*
* Copyright (c) 2016 yuriel<[email protected]>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package dev.yuriel.kotmahjan.ai.analysis
import android.util.SparseArray
import dev.yuriel.kotmahjan.models.Hai
import dev.yuriel.kotmahjan.models.IllegalIntArrayException
import dev.yuriel.kotmahjan.models.NoSuchTileException
import java.util.*
import kotlin.annotation.AnnotationTarget.*
/**
* Created by yuriel on 7/28/16.
* 注意:
* 牌のIDは配列のインデックスを等しくないこと。
* IntArrayから得たIntはインデックスを指し、それほかのIntはID
* IntArrayはツールだけとして使用している、それ以外の牌(例えば赤ドラ牌)の表示はできません。
*/
/**
* range(1, 34)
*/
@Target(TYPE, TYPE_PARAMETER, LOCAL_VARIABLE, PROPERTY, FIELD, FUNCTION, EXPRESSION, VALUE_PARAMETER)
@Retention(AnnotationRetention.SOURCE)
annotation class ID
/**
* range(1, 33)
*/
@Target(TYPE, TYPE_PARAMETER, LOCAL_VARIABLE, PROPERTY, FIELD, FUNCTION, EXPRESSION, VALUE_PARAMETER)
@Retention(AnnotationRetention.SOURCE)
annotation class Index
/**
* @param distance 2つの牌の距離
* @param key1 id
* @param key2 id
*/
data class Distance2Key(val distance: Int = -1, val key1: @ID Int = -1, val key2: @ID Int = -1)
/**
* @param efficiency 効率、高いほど効率が悪い
* @param keys 欲しいの牌のID
*/
data class Efficiency2Key(val efficiency: Int = 0, val keys: Set<@ID Int> = mutableSetOf())
data class Group2KeyList(val group: List<@ID Int>,
val keys: List<@ID Int>,
var probability: Float? = null): Comparable<Group2KeyList> {
override fun compareTo(other: Group2KeyList): Int {
return (((probability?:0F) - (other.probability?:0F)) * 10000).toInt()
}
}
/**
* @param useless 捨てるはずの牌
* @param keys また手に入れなくて欲しい牌
* @param k2gMap キー牌ID:キー牌を判断する根拠
*/
data class Useless2Key2KeyMap(val useless: IntArray = IntArray(34),
val keys: IntArray = IntArray(34),
val k2gMap: HashMap<@ID Int, MutableList<@ID Int>> = HashMap(),
/*val map: SparseArray<MutableList<Int>> = SparseArray(),*/
val g2kList: List<Group2KeyList> = listOf<Group2KeyList>()) {
override fun hashCode(): Int {
return (0.3 * useless.hashCode() +
0.3 * keys.hashCode() +
0.2 * k2gMap.hashCode() +
0.2 * g2kList.hashCode())
.hashCode()
}
override fun equals(other: Any?): Boolean {
return super.equals(other)
}
}
/**
* 牌の効率
*/
@Throws(IllegalIntArrayException::class, NoSuchTileException::class)
fun efficiencyByHand(tehai: IntArray, id: @ID Int): Efficiency2Key {
if (tehai.size != 34) {
throw IllegalIntArrayException(tehai.size)
}
if (id < 1 || id > 34) {
throw NoSuchTileException(id)
}
var result = 0
val keys = mutableSetOf<Int>()
for (i in 0..tehai.size - 1) {
if (tehai[i] == 0) continue
if (id == i + 1) {
keys.addAll(getTileGroupRangeWith(id))
}
val (d, k1, k2) = distance(id, i + 1)
if (-1 == d) {
result += 10
} else {
result += d
if (k1 != -1) keys.add(k1)
if (k2 != -1) keys.add(k2)
}
}
return Efficiency2Key(result, keys)
}
@Throws(IllegalIntArrayException::class, NoSuchTileException::class)
fun efficiencyByProbability(range: IntArray, id: @ID Int): Float {
if (range.size != 34) {
throw IllegalIntArrayException(range.size)
}
if (id < 1 || id > 34) {
throw NoSuchTileException(id)
}
val keys = mutableSetOf<Int>()
var result = 0F
keys.addAll(getTileGroupRangeWith(id))
for (k in keys) {
result += range[k - 1].toFloat() / range.sum().toFloat()
}
return result
}
/**
* 牌の距離
* -1: 無関係
* 0: 同じ牌
* 1: 隣の牌
* 2: 離れてる牌
*/
@Throws(NoSuchTileException::class)
fun distance(fromId: @ID Int, toId: @ID Int): Distance2Key {
if (fromId < 1 || fromId > 34) {
throw NoSuchTileException(fromId)
}
if (toId < 1 || toId > 34) {
throw NoSuchTileException(toId)
}
if (fromId == toId) return Distance2Key(0, fromId)
if (Math.abs(fromId - toId) > 2) return Distance2Key()
if (fromId > 27 || toId > 27) return Distance2Key()
when (fromId + toId) {
18, 19, 20, 36, 37, 38 -> return Distance2Key()
}
val distance = Math.abs(fromId - toId)
var k1: Int = -1
var k2: Int = -1
when (distance) {
1 -> {
k1 = when (fromId + toId) {
3, 21, 39 -> -1
else -> (fromId + toId - 1) / 2 - 1
}
k2 = when (fromId + toId) {
17, 35, 53 -> -1
else -> (fromId + toId + 1) /2 + 1
}
}
2 -> {
k1 = (fromId + toId) / 2
k2 = -1
}
}
return Distance2Key(distance, k1, k2)
}
@Throws(IllegalIntArrayException::class)
fun excludeShuntsu(tehai: IntArray,
antiOriented: Boolean = false,
confirm: ((@ID Int, @ID Int, @ID Int, last: @Index IntArray) -> Boolean)? = null): IntArray {
if (tehai.size != 34) {
throw IllegalIntArrayException(tehai.size)
}
val result = tehai.clone()
val range = if (antiOriented) (tehai.size - 3 - 7) downTo 0 else 0..tehai.size - 3 - 7
loop@
for (@Index i in range) {
when (i + 1) {
8, 9, 17, 18, 26, 27 -> continue@loop
else -> {
while (result[i] != 0) {
if (result[i] > 0 && result[i + 1] > 0 && result[i + 2] > 0) {
if (confirm?.invoke(i + 1, i + 2, i + 3, result)?:true) {
result[i] -= 1
result[i + 1] -= 1
result[i + 2] -= 1
}
} else {
continue@loop
}
}
}
}
}
return result
}
@Throws(IllegalIntArrayException::class)
fun excludeKotsu(tehai: IntArray, confirm: ((@ID Int, @Index IntArray) -> Boolean)? = null): IntArray {
if (tehai.size != 34) {
throw IllegalIntArrayException(tehai.size)
}
val result = tehai.clone()
loop@
for (i in 0..tehai.size - 1) {
if (result[i] > 2) {
if (confirm?.invoke(i + 1, result)?:true) result[i] -= 3
} else {
continue@loop
}
}
return result
}
@Throws(IllegalIntArrayException::class)
fun exclude2Correlation(tehai: IntArray,
confirm: ((@ID Int, @ID Int, useless: @Index IntArray) -> Boolean)? = null): Useless2Key2KeyMap {
if (tehai.size != 34) {
throw IllegalIntArrayException(tehai.size)
}
//val map = SparseArray<MutableList<Int>>()
val k2gMap = HashMap<Int, MutableList<Int>>()
val g2kList = mutableListOf<Group2KeyList>()
var hasJanto = false
/*
fun SparseArray<MutableList<Int>>.addTo(id: Int, addId: Int) {
if (this[id] == null) {
put(id, mutableListOf(addId))
} else {
this[id]!!.add(addId)
}
}
*/
fun HashMap<Int, MutableList<Int>>.addTo(id: @ID Int, addId: @ID Int) {
if (this[id] == null) {
put(id, mutableListOf(addId))
} else {
this[id]!!.add(addId)
}
}
fun IntArray.addKey(k1: @ID Int, k2: @ID Int, vararg fromId: @ID Int) {
val keys = fromId.toList()
val group = mutableListOf<Int>()
if (0 < k1) {
this[k1 - 1] += 1
for (i in fromId) {
k2gMap.addTo(k1, i)
group.add(i)
}
}
if (0 < k2) {
this[k2 - 1] += 1
for (i in fromId) {
k2gMap.addTo(k2, i)
group.add(i)
}
}
g2kList.add(Group2KeyList(group, keys))
}
val useless = tehai.clone()
val keyList = IntArray(34)
for (i in 0..tehai.size - 1) {
while (useless[i] > 0) {
//print(i)
var found = false
var key: Distance2Key
if (!hasJanto && useless[i] > 1 && confirm?.invoke(i + 1, i + 1, useless)?: true) {
useless[i] -= 2
key = Distance2Key(0, i + 1, -1)
found = true
keyList.addKey(key.key1, key.key2, i + 1)
hasJanto = true
}
if (found) continue
if (i < useless.size - 2 && useless[i + 1] > 0) {
key = distance(i + 1, i + 2)
if (key.distance != -1 && confirm?.invoke(i + 1, i + 2, useless)?: true) {
useless[i] -= 1
useless[i + 1] -= 1
found = true
keyList.addKey(key.key1, key.key2, i + 1, i + 2)
}
}
if (found) continue
if (i < useless.size - 2 && useless[i + 2] > 0) {
key = distance(i + 1, i + 3)
if (key.distance != -1 && confirm?.invoke(i + 1, i + 3, useless)?: true) {
useless[i] -= 1
useless[i + 2] -= 1
found = true
keyList.addKey(key.key1, key.key2, i + 1, i + 3)
}
}
if (found) continue
if (useless[i] > 1 && confirm?.invoke(i + 1, i + 1, useless)?: true) {
useless[i] -= 2
key = Distance2Key(0, i + 1, -1)
found = true
keyList.addKey(key.key1, key.key2, i + 1)
}
if (!found) break
}
}
return Useless2Key2KeyMap(useless, keyList, k2gMap, g2kList)
}
@Throws(IllegalIntArrayException::class)
fun getUselessGeneralized(tehai: IntArray): Useless2Key2KeyMap {
return getUselessByMerged(tehai) { list1, list2 ->
IntArray(34) { i ->
val value = list1[i]
if (value == list2[i]) value else 0
}
}
}
// todo: 何かの違いがあるかも
@Deprecated("この方法は通用しないので、別の方法を考えてみて")
@Throws(IllegalIntArrayException::class)
fun getUselessSpecialized(tehai: IntArray): Useless2Key2KeyMap = getUselessByMerged(tehai) {
list1, list2 -> list1 or list2
}
/**
* @param mergeFunc フォワードで順子を除く結果とリバースの結果を併合する
* @return 計算した結果
*/
@Throws(IllegalIntArrayException::class)
fun getUselessByMerged(tehai: IntArray,
mergeFunc: (IntArray, IntArray) -> IntArray): Useless2Key2KeyMap {
if (tehai.size != 34) {
throw IllegalIntArrayException(tehai.size)
}
val list1 = excludeKotsu(excludeShuntsu(tehai))
val list2 = excludeKotsu(excludeShuntsu(tehai, true))
val merge = mergeFunc(list1, list2)
return exclude2Correlation(merge)
}
/**
* どの牌の組みを分けるかを決めるメソード
*/
@Throws(IllegalIntArrayException::class)
fun sortEffectInRange(data: Useless2Key2KeyMap,
tehai: IntArray,
range: IntArray? = null): Useless2Key2KeyMap{
if (data.useless.size != 34) {
throw IllegalIntArrayException(data.useless.size)
}
if (data.keys.size != 34) {
throw IllegalIntArrayException(data.keys.size)
}
val list = range?: IntArray(34) { i -> 4 - tehai[i] }
val probabilityTable = HashMap<Int, Float>()
for (i in 0..data.keys.size - 1) {
if (data.keys[i] == 0) continue
probabilityTable.put(i + 1, list[i].toFloat() / list.sum().toFloat())
}
for (id in data.g2kList) {
id.probability = 0F
for (j in id.keys) {
id.probability = id.probability?:0F + (probabilityTable[j]?: 0F)
}
}
Collections.sort(data.g2kList)
return data
}
private fun getTileGroupRangeWith(id: @ID Int): List<Int> {
val result = mutableListOf<Int>()
if (id > 27) {
result.add(id)
} else {
when (id) {
1, 10, 19 -> {
result.add(id)
result.add(id + 1)
}
9, 18, 27 -> {
result.add(id - 1)
result.add(id)
}
else -> {
result.add(id - 1)
result.add(id)
result.add(id + 1)
}
}
}
return result
}
@Throws(RuntimeException::class)
operator fun IntArray.minus(other: IntArray): IntArray {
if (size != other.size) {
throw RuntimeException()
}
val result = IntArray(size)
for (i in 0..size - 1) {
result[i] = this[i] - other[i]
}
return result
}
@Throws(RuntimeException::class)
operator fun IntArray.plus(other: IntArray): IntArray {
if (size != other.size) {
throw RuntimeException()
}
val result = IntArray(size)
for (i in 0..size - 1) {
result[i] = this[i] + other[i]
}
return result
}
@Throws(RuntimeException::class)
private infix fun IntArray.or(other: IntArray): IntArray {
if (size != other.size) {
throw RuntimeException()
}
val result = IntArray(size)
for (i in 0..size - 1) {
result[i] = if (this[i] != 0) this[i] else if (other[i] != 0) other[i] else 0
}
return result
}
| mit | 41dfa314cae43e0e5d4c95d76d213964 | 30.188596 | 121 | 0.548727 | 3.450267 | false | false | false | false |
Ztiany/Repository | Kotlin/Kotlin-Basic/src/main/kotlin/me/ztiany/functions/TailRecursiveFunction.kt | 2 | 1201 | package me.ztiany.functions
/**
*尾递归函数
*
* @author Ztiany
* Email [email protected]
* Date 17.6.3 0:16
*/
/**
* 尾递归函数:
*
* Kotlin 支持一种称为尾递归的函数式编程风格。 这允许一些通常用循环写的算法改用递归函数来写,而无堆栈溢出的风险。
* 当一个函数用 tailrec 修饰符标记并满足所需的形式时,编译器会优化该递归,留下一个快速而高效的基于循环的版本。
*
* 要符合 tailrec 修饰符的条件的话,函数必须将其自身调用作为它执行的最后一个操作。在递归调用后有更多代码时,不能使用尾递归,
* 并且不能用在 try/catch/finally 块中。目前尾部递归只在 JVM 后端中支持。
*/
private tailrec fun findFixPoint(x: Double = 1.0): Double = if (x == Math.cos(x)) x else findFixPoint(Math.cos(x))
//最终代码相当于这种更传统风格的代码
private fun findFixPoint(): Double {
var x = 1.0
while (true) {
val y = Math.cos(x)
if (x == y) return y
x = y
}
}
fun main(args: Array<String>) {
val point = findFixPoint(1.0)
println(point)
} | apache-2.0 | 0ac8864214b2d94c57d047d8994ee0bd | 20.297297 | 114 | 0.639136 | 2.174033 | false | false | false | false |
tibbi/Simple-Calculator | app/src/main/kotlin/com/simplemobiletools/calculator/operation/FactorialOperation.kt | 1 | 559 | package com.simplemobiletools.calculator.operation
import com.simplemobiletools.calculator.operation.base.Operation
import com.simplemobiletools.calculator.operation.base.UnaryOperation
class FactorialOperation(value: Double) : UnaryOperation(value), Operation {
override fun getResult(): Double{
var result = 1.0
if (value==0.0 || value==1.0){
return result
}else{
var base = value.toInt()
for(i in 1..base){
result *= i
}
}
return result
}
}
| gpl-2.0 | 4ef82e865f10da5d60f44a59af31e373 | 26.95 | 76 | 0.617174 | 4.508065 | false | false | false | false |
Asphere/StellaMagicaMod | src/main/java/stellamagicamod/core/StellaMagicaModCore.kt | 1 | 1449 | package stellamagicamod.core;
import c6h2cl2.YukariLib.Util.RegisterHandler
import cpw.mods.fml.common.Mod
import cpw.mods.fml.common.ModMetadata
import cpw.mods.fml.common.event.FMLInitializationEvent
import cpw.mods.fml.common.event.FMLPreInitializationEvent
@Mod(modid = StellaMagicaModCore.MOD_ID, useMetadata = true, dependencies = "required-after:Forge@[10.13.4.1558,);required-after:YukariLib")
class StellaMagicaModCore {
companion object {
const val MOD_ID = "StellaMagicaMod"
const val MOD_NAME = "StellaMagicaMod Core"
const val MOD_VERSION = "1.0.0"
@Mod.Metadata
var meta: ModMetadata? = null
}
@Mod.EventHandler
fun preinit(event: FMLPreInitializationEvent){
RegisterHandler().build(SMMRegistry).handle()
}
@Mod.Instance(MOD_ID)
val INSTANCE: StellaMagicaModCore
@Mod.EventHandler
@SuppressWarnings("unused")
fun init(event:FMLInitializationEvent) {
SMMRegistry.INSTANCE.handleInit()
}
@Mod.EventHandler
@SuppressWarnings("unused")
fun init(event:FMLPreInitializationEvent) {
SMMRegistry.INSTANCE.handleInit()
}
fun loadMeta() {
val meta = meta as ModMetadata
meta.modId = MOD_ID
meta.name = MOD_NAME
meta.version = MOD_VERSION
meta.authorList.add("Asphere103")
meta.description = "Make StellaMagica in Minecraft!"
meta.autogenerated = false
}
} | mpl-2.0 | 5f23ddc2692e4bf3c7391458da6fa156 | 29.851064 | 140 | 0.694272 | 3.705882 | false | false | false | false |
stripe/stripe-android | payments-core/src/main/java/com/stripe/android/model/SourceParams.kt | 1 | 43087 | package com.stripe.android.model
import android.os.Parcel
import android.os.Parcelable
import androidx.annotation.IntRange
import androidx.annotation.Size
import com.stripe.android.core.model.StripeJsonUtils
import com.stripe.android.model.Source.Companion.asSourceType
import com.stripe.android.model.Source.SourceType
import kotlinx.parcelize.Parceler
import kotlinx.parcelize.Parcelize
import org.json.JSONException
import org.json.JSONObject
/**
* Represents a grouping of parameters needed to create a [Source] object on the server.
*/
@Parcelize
data class SourceParams internal constructor(
/**
* The type of the source to create.
*/
@SourceType val typeRaw: String,
internal var typeData: TypeData? = null,
/**
* Amount associated with the source. This is the amount for which the source will
* be chargeable once ready. Required for `single_use` sources. Not supported for `receiver`
* type sources, where charge amount may not be specified until funds land.
*
* See [amount](https://stripe.com/docs/api/sources/create#create_source-amount)
*/
var amount: Long? = null,
/**
* Three-letter ISO code for the currency associated with the source.
* This is the currency for which the source will be chargeable once ready.
*
* See [currency](https://stripe.com/docs/api/sources/create#create_source-currency)
*/
var currency: String? = null,
/**
* Information about the owner of the payment instrument that may be used or required by
* particular source types.
*/
var owner: OwnerParams? = null,
/**
* Either `reusable` or `single_use`. Whether this source should be reusable or not.
* Some source types may or may not be reusable by construction, while others may leave the
* option at creation. If an incompatible value is passed, an error will be returned.
*
* See [usage](https://stripe.com/docs/api/sources/create#create_source-usage)
*/
var usage: Source.Usage? = null,
/**
* The URL you provide to redirect the customer back to you after they authenticated their
* payment. It can use your application URI scheme in the context of a mobile application.
*/
var returnUrl: String? = null,
/**
* The authentication `flow` of the source to create. `flow` is one of `redirect`, `receiver`,
* `code_verification`, `none`. It is generally inferred unless a type supports multiple flows.
*
* See [flow](https://stripe.com/docs/api/sources/create#create_source-flow)
*/
var flow: Flow? = null,
/**
* Information about the items and shipping associated with the source. Required for
* transactional credit (for example Klarna) sources before you can charge it.
*
* See [source_order](https://stripe.com/docs/api/sources/create#create_source-source_order)
*/
var sourceOrder: SourceOrderParams? = null,
/**
* An optional token used to create the source. When passed, token properties will
* override source parameters.
*
* See [token](https://stripe.com/docs/api/sources/create#create_source-token)
*/
var token: String? = null,
/**
* Set of key-value pairs that you can attach to an object. This can be useful for storing
* additional information about the object in a structured format.
*/
var metadata: Map<String, String>? = null,
private var weChatParams: WeChatParams? = null,
private var apiParams: ApiParams = ApiParams(),
/**
* A set of identifiers representing the component that created this instance.
*/
internal val attribution: Set<String> = emptySet()
) : StripeParamsModel, Parcelable {
/**
* The type of the source to create.
*/
@get:SourceType
@SourceType
val type: String
get() = asSourceType(typeRaw)
/**
* A [Map] of the parameters specific to the Source type.
*/
val apiParameterMap: Map<String, Any?> get() = apiParams.value
/*---- Setters ----*/
/**
* @param apiParameterMap a map of parameters specific for this type of source
*/
fun setApiParameterMap(
apiParameterMap: Map<String, Any?>?
): SourceParams = apply {
this.apiParams = ApiParams(apiParameterMap.orEmpty())
}
/**
* Create a string-keyed map representing this object that is ready to be sent over the network.
*/
@Suppress("LongMethod")
override fun toParamMap(): Map<String, Any> {
return mapOf<String, Any>(PARAM_TYPE to typeRaw)
.plus(
apiParams.value.takeIf {
it.isNotEmpty()
}?.let {
mapOf(typeRaw to it)
}.orEmpty()
)
.plus(
typeData?.createParams().orEmpty()
)
.plus(
amount?.let {
mapOf(PARAM_AMOUNT to it)
}.orEmpty()
)
.plus(
currency?.let {
mapOf(PARAM_CURRENCY to it)
}.orEmpty()
)
.plus(
flow?.let {
mapOf(PARAM_FLOW to it.code)
}.orEmpty()
)
.plus(
sourceOrder?.let {
mapOf(PARAM_SOURCE_ORDER to it.toParamMap())
}.orEmpty()
)
.plus(
owner?.let {
mapOf(PARAM_OWNER to it.toParamMap())
}.orEmpty()
)
.plus(
returnUrl?.let {
mapOf(PARAM_REDIRECT to mapOf(PARAM_RETURN_URL to it))
}.orEmpty()
)
.plus(
metadata?.let {
mapOf(PARAM_METADATA to it)
}.orEmpty()
)
.plus(
token?.let {
mapOf(PARAM_TOKEN to it)
}.orEmpty()
)
.plus(
usage?.let {
mapOf(PARAM_USAGE to it.code)
}.orEmpty()
)
.plus(
weChatParams?.let {
mapOf(PARAM_WECHAT to it.toParamMap())
}.orEmpty()
)
}
@Parcelize
internal data class WeChatParams(
private val appId: String? = null,
private val statementDescriptor: String? = null
) : StripeParamsModel, Parcelable {
override fun toParamMap(): Map<String, Any> {
return emptyMap<String, Any>()
.plus(
appId?.let {
mapOf(PARAM_APPID to it)
}.orEmpty()
)
.plus(
statementDescriptor?.let {
mapOf(PARAM_STATEMENT_DESCRIPTOR to it)
}.orEmpty()
)
}
companion object {
private const val PARAM_APPID = "appid"
private const val PARAM_STATEMENT_DESCRIPTOR = "statement_descriptor"
}
}
/**
* Information about the owner of the payment instrument that may be used or required by
* particular source types.
*
* See [owner](https://stripe.com/docs/api/sources/create#create_source-owner).
*/
@Parcelize
data class OwnerParams @JvmOverloads constructor(
internal var address: Address? = null,
internal var email: String? = null,
internal var name: String? = null,
internal var phone: String? = null
) : StripeParamsModel, Parcelable {
override fun toParamMap(): Map<String, Any> {
return emptyMap<String, Any>()
.plus(
address?.let {
mapOf(PARAM_ADDRESS to it.toParamMap())
}.orEmpty()
)
.plus(
email?.let {
mapOf(PARAM_EMAIL to it)
}.orEmpty()
)
.plus(
name?.let {
mapOf(PARAM_NAME to it)
}.orEmpty()
)
.plus(
phone?.let {
mapOf(PARAM_PHONE to it)
}.orEmpty()
)
}
private companion object {
private const val PARAM_ADDRESS = "address"
private const val PARAM_EMAIL = "email"
private const val PARAM_NAME = "name"
private const val PARAM_PHONE = "phone"
}
}
enum class Flow(
internal val code: String
) {
Redirect("redirect"),
Receiver("receiver"),
CodeVerification("code_verification"),
None("none")
}
companion object {
private const val PARAM_AMOUNT = "amount"
private const val PARAM_CLIENT_SECRET = "client_secret"
private const val PARAM_CURRENCY = "currency"
private const val PARAM_FLOW = "flow"
private const val PARAM_METADATA = "metadata"
private const val PARAM_OWNER = "owner"
private const val PARAM_REDIRECT = "redirect"
private const val PARAM_RETURN_URL = "return_url"
private const val PARAM_SOURCE_ORDER = "source_order"
private const val PARAM_TOKEN = "token"
private const val PARAM_TYPE = "type"
private const val PARAM_USAGE = "usage"
private const val PARAM_WECHAT = "wechat"
/**
* Create P24 Source params.
*
* @param amount A positive integer in the smallest currency unit representing the amount to
* charge the customer (e.g., 1099 for a €10.99 payment).
* @param currency `eur` or `pln` (P24 payments must be in either Euros
* or Polish Zloty).
* @param name The name of the account holder (optional).
* @param email The email address of the account holder.
* @param returnUrl The URL the customer should be redirected to after the authorization
* process.
* @return a [SourceParams] that can be used to create a P24 source
*
* @see [Przelewy24 Payments with Sources](https://stripe.com/docs/sources/p24)
*/
@JvmStatic
fun createP24Params(
@IntRange(from = 0) amount: Long,
currency: String,
name: String?,
email: String,
returnUrl: String
): SourceParams {
return SourceParams(
SourceType.P24,
amount = amount,
currency = currency,
returnUrl = returnUrl,
owner = OwnerParams(
email = email,
name = name
)
)
}
/**
* Create reusable Alipay Source params.
*
* @param currency The currency of the payment. Must be the default currency for your country.
* Can be aud, cad, eur, gbp, hkd, jpy, nzd, sgd, or usd. Users in Denmark,
* Norway, Sweden, or Switzerland must use eur.
* @param name The name of the account holder (optional).
* @param email The email address of the account holder (optional).
* @param returnUrl The URL the customer should be redirected to after the authorization
* process.
* @return a [SourceParams] that can be used to create an Alipay reusable source
*
* @see [Alipay Payments with Sources](https://stripe.com/docs/sources/alipay)
*/
@JvmStatic
fun createAlipayReusableParams(
currency: String,
name: String? = null,
email: String? = null,
returnUrl: String
): SourceParams {
return SourceParams(
SourceType.ALIPAY,
currency = currency,
returnUrl = returnUrl,
usage = Source.Usage.Reusable,
owner = OwnerParams(
email = email,
name = name
)
)
}
/**
* Create single-use Alipay Source params.
*
* @param amount A positive integer in the smallest currency unit representing the amount to
* charge the customer (e.g., 1099 for a $10.99 payment).
* @param currency The currency of the payment. Must be the default currency for your country.
* Can be aud, cad, eur, gbp, hkd, jpy, nzd, sgd, or usd. Users in Denmark,
* Norway, Sweden, or Switzerland must use eur.
* @param name The name of the account holder (optional).
* @param email The email address of the account holder (optional).
* @param returnUrl The URL the customer should be redirected to after the authorization
* process.
* @return a [SourceParams] that can be used to create an Alipay single-use source
*
* @see [Alipay Payments with Sources](https://stripe.com/docs/sources/alipay)
*/
@JvmStatic
fun createAlipaySingleUseParams(
@IntRange(from = 0) amount: Long,
currency: String,
name: String? = null,
email: String? = null,
returnUrl: String
): SourceParams {
return SourceParams(
SourceType.ALIPAY,
currency = currency,
amount = amount,
returnUrl = returnUrl,
owner = OwnerParams(
email = email,
name = name
)
)
}
/**
* Create WeChat Pay Source params.
*
* @param amount A positive integer in the
* [smallest currency unit](https://stripe.com/docs/currencies#zero-decimal)
* representing the amount to charge the customer (e.g., 1099 for a $10.99 payment).
* @param currency The currency of the payment. Must be the default currency for your
* country. Can be aud, cad, eur, gbp, hkd, jpy, sgd, or usd.
* @param weChatAppId Your registered WeChat Pay App ID from
* [WeChat Open Platform](https://open.weixin.qq.com/).
* @param statementDescriptor (optional) A custom statement descriptor for the payment,
* maximum 32 characters. By default, your Stripe account’s statement descriptor is
* used (you can review this in the [Dashboard](https://dashboard.stripe.com/account).
*/
@JvmStatic
fun createWeChatPayParams(
@IntRange(from = 0) amount: Long,
currency: String,
weChatAppId: String,
statementDescriptor: String? = null
): SourceParams {
return SourceParams(
SourceType.WECHAT,
currency = currency,
amount = amount,
weChatParams = WeChatParams(
weChatAppId,
statementDescriptor
)
)
}
/**
* Create params for a Klarna Source
*
* [Klarna Payments with Sources](https://stripe.com/docs/sources/klarna)
*
* @param returnUrl The URL you provide to redirect the customer back to you after they
* authenticated their payment. It can use your application URI scheme in the context of
* a mobile application.
* @param currency Three-letter ISO code for the currency associated with the source.
* This is the currency for which the source will be chargeable once ready.
* @param klarnaParams Klarna-specific params
*/
@JvmStatic
fun createKlarna(
returnUrl: String,
currency: String,
klarnaParams: KlarnaSourceParams
): SourceParams {
val totalAmount = klarnaParams.lineItems.sumBy { it.totalAmount }
val sourceOrderParams = SourceOrderParams(
items = klarnaParams.lineItems.map {
val type = when (it.itemType) {
KlarnaSourceParams.LineItem.Type.Sku ->
SourceOrderParams.Item.Type.Sku
KlarnaSourceParams.LineItem.Type.Tax ->
SourceOrderParams.Item.Type.Tax
KlarnaSourceParams.LineItem.Type.Shipping ->
SourceOrderParams.Item.Type.Shipping
}
SourceOrderParams.Item(
type = type,
amount = it.totalAmount,
currency = currency,
description = it.itemDescription,
quantity = it.quantity
)
}
)
return SourceParams(
SourceType.KLARNA,
flow = Flow.Redirect,
sourceOrder = sourceOrderParams,
amount = totalAmount.toLong(),
currency = currency,
returnUrl = returnUrl,
owner = OwnerParams(
address = klarnaParams.billingAddress,
email = klarnaParams.billingEmail,
phone = klarnaParams.billingPhone
),
apiParams = ApiParams(klarnaParams.toParamMap())
)
}
/**
* Create Bancontact Source params.
*
* @param amount A positive integer in the smallest currency unit representing the amount to
* charge the customer (e.g., 1099 for a €10.99 payment). The charge amount must be
* at least €1 or its equivalent in the given currency.
* @param name The full name of the account holder.
* @param returnUrl The URL the customer should be redirected to after the authorization
* process.
* @param statementDescriptor A custom statement descriptor for the payment (optional).
* @param preferredLanguage The preferred language of the Bancontact authorization page that the
* customer is redirected to. Supported values are: en, de, fr, or nl
* (optional).
* @return a [SourceParams] object that can be used to create a Bancontact source
*
* @see [Bancontact Payments with Sources](https://stripe.com/docs/sources/bancontact)
*/
@JvmStatic
fun createBancontactParams(
@IntRange(from = 0) amount: Long,
name: String,
returnUrl: String,
statementDescriptor: String? = null,
preferredLanguage: String? = null
): SourceParams {
return SourceParams(
SourceType.BANCONTACT,
typeData = TypeData.Bancontact(
statementDescriptor,
preferredLanguage
),
currency = Source.EURO,
amount = amount,
owner = OwnerParams(name = name),
returnUrl = returnUrl
)
}
/**
* Create a custom [SourceParams] object. Incorrect attributes may result in errors
* when connecting to Stripe's API.
*
* @param type a custom type
* @return an empty [SourceParams] object.
*/
@JvmStatic
fun createCustomParams(type: String): SourceParams {
return SourceParams(type)
}
/**
* Create parameters necessary for converting a token into a source
*
* @param tokenId the id of the [Token] to be converted into a source.
* @return a [SourceParams] object that can be used to create a source.
*/
@JvmStatic
fun createSourceFromTokenParams(tokenId: String): SourceParams {
return SourceParams(
SourceType.CARD,
token = tokenId
)
}
/**
* Create Card Source params.
*
* @param cardParams A [CardParams] object containing the details necessary for the source.
* @return a [SourceParams] object that can be used to create a card source.
*
* @see [Card Payments with Sources](https://stripe.com/docs/sources/cards)
*/
@JvmStatic
fun createCardParams(
cardParams: CardParams
): SourceParams {
return SourceParams(
SourceType.CARD,
typeData = TypeData.Card(
cardParams.number,
cardParams.expMonth,
cardParams.expYear,
cardParams.cvc
),
attribution = cardParams.attribution,
owner = OwnerParams(
address = cardParams.address,
name = cardParams.name
),
metadata = cardParams.metadata
)
}
/**
* @param googlePayPaymentData a [JSONObject] derived from Google Pay's
* [PaymentData#toJson()](https://developers.google.com/pay/api/android/reference/client#tojson)
*/
@Throws(JSONException::class)
@JvmStatic
fun createCardParamsFromGooglePay(
googlePayPaymentData: JSONObject
): SourceParams {
val googlePayResult = GooglePayResult.fromJson(googlePayPaymentData)
val token = googlePayResult.token
return SourceParams(
SourceType.CARD,
token = token?.id.orEmpty(),
attribution = setOfNotNull(
token?.card?.tokenizationMethod?.toString()
),
owner = OwnerParams(
address = googlePayResult.address,
email = googlePayResult.email,
name = googlePayResult.name,
phone = googlePayResult.phoneNumber
)
)
}
/**
* Create EPS Source params.
*
* @param amount A positive integer in the smallest currency unit representing the amount to
* charge the customer (e.g., 1099 for a €10.99 payment).
* @param name The full name of the account holder.
* @param returnUrl The URL the customer should be redirected to after the authorization
* process.
* @param statementDescriptor A custom statement descriptor for the payment (optional).
* @return a [SourceParams] object that can be used to create an EPS source
*
* @see [EPS Payments with Sources](https://stripe.com/docs/sources/eps)
*/
@JvmStatic
fun createEPSParams(
@IntRange(from = 0) amount: Long,
name: String,
returnUrl: String,
statementDescriptor: String? = null
): SourceParams {
return SourceParams(
SourceType.EPS,
typeData = TypeData.Eps(statementDescriptor),
currency = Source.EURO,
amount = amount,
owner = OwnerParams(name = name),
returnUrl = returnUrl
)
}
/**
* Create Giropay Source params.
*
* @param amount A positive integer in the smallest currency unit representing the amount to
* charge the customer (e.g., 1099 for a €10.99 payment).
* @param name The full name of the account holder.
* @param returnUrl The URL the customer should be redirected to after the authorization
* process.
* @param statementDescriptor A custom statement descriptor for the payment (optional).
* @return a [SourceParams] object that can be used to create a Giropay source
*
* @see [Giropay Payments with Sources](https://stripe.com/docs/sources/giropay)
*/
@JvmStatic
fun createGiropayParams(
@IntRange(from = 0) amount: Long,
name: String,
returnUrl: String,
statementDescriptor: String? = null
): SourceParams {
return SourceParams(
SourceType.GIROPAY,
typeData = TypeData.Giropay(statementDescriptor),
currency = Source.EURO,
amount = amount,
owner = OwnerParams(name = name),
returnUrl = returnUrl
)
}
/**
* Create iDEAL Source params.
*
* @param amount A positive integer in the smallest currency unit representing the amount to
* charge the customer (e.g., 1099 for a €10.99 payment).
* @param name The full name of the account holder (optional).
* @param returnUrl The URL the customer should be redirected to after the authorization
* process.
* @param statementDescriptor A custom statement descriptor for the payment (optional).
* @param bank The customer’s bank (optional).
* @return a [SourceParams] object that can be used to create an iDEAL source
*
* @see [iDEAL Payments with Sources](https://stripe.com/docs/sources/ideal)
*/
@JvmStatic
fun createIdealParams(
@IntRange(from = 0) amount: Long,
name: String?,
returnUrl: String,
statementDescriptor: String? = null,
bank: String? = null
): SourceParams {
return SourceParams(
SourceType.IDEAL,
typeData = TypeData.Ideal(
statementDescriptor,
bank
),
currency = Source.EURO,
amount = amount,
returnUrl = returnUrl,
owner = OwnerParams(name = name)
)
}
/**
* Create Multibanco Source params.
*
* @param amount A positive integer in the smallest currency unit representing the amount to
* charge the customer (e.g., 1099 for a €10.99 payment).
* @param returnUrl The URL the customer should be redirected to after the authorization
* process.
* @param email The full email address of the customer.
* @return a [SourceParams] object that can be used to create a Multibanco source
*
* @see [Multibanco Payments with Sources](https://stripe.com/docs/sources/multibanco)
*/
@JvmStatic
fun createMultibancoParams(
@IntRange(from = 0) amount: Long,
returnUrl: String,
email: String
): SourceParams {
return SourceParams(
SourceType.MULTIBANCO,
currency = Source.EURO,
amount = amount,
returnUrl = returnUrl,
owner = OwnerParams(email = email)
)
}
/**
* Create SEPA Debit Source params.
*
* @param name The full name of the account holder.
* @param iban The IBAN number for the bank account that you wish to debit.
* @param addressLine1 The first line of the owner's address (optional).
* @param city The city of the owner's address.
* @param postalCode The postal code of the owner's address.
* @param country The ISO-3166 2-letter country code of the owner's address.
* @return a [SourceParams] object that can be used to create a SEPA debit source
*
* @see [SEPA Direct Debit Payments with Sources](https://stripe.com/docs/sources/sepa-debit)
*/
@JvmStatic
fun createSepaDebitParams(
name: String,
iban: String,
addressLine1: String?,
city: String,
postalCode: String,
@Size(2) country: String
): SourceParams {
return createSepaDebitParams(
name,
iban,
null,
addressLine1,
city,
postalCode,
country
)
}
/**
* Create SEPA Debit Source params.
*
* @param name The full name of the account holder.
* @param iban The IBAN number for the bank account that you wish to debit.
* @param email The full email address of the owner (optional).
* @param addressLine1 The first line of the owner's address (optional).
* @param city The city of the owner's address.
* @param postalCode The postal code of the owner's address.
* @param country The ISO-3166 2-letter country code of the owner's address.
* @return a [SourceParams] object that can be used to create a SEPA debit source
*
* @see [SEPA Direct Debit Payments with Sources](https://stripe.com/docs/sources/sepa-debit)
*/
@JvmStatic
fun createSepaDebitParams(
name: String,
iban: String,
email: String?,
addressLine1: String?,
city: String?,
postalCode: String?,
@Size(2) country: String?
): SourceParams {
return SourceParams(
SourceType.SEPA_DEBIT,
currency = Source.EURO,
typeData = TypeData.SepaDebit(iban),
owner = OwnerParams(
address = Address.Builder()
.setLine1(addressLine1)
.setCity(city)
.setPostalCode(postalCode)
.setCountry(country)
.build(),
email = email,
name = name
)
)
}
/**
* Create SOFORT Source params.
*
* @param amount A positive integer in the smallest currency unit representing the amount to
* charge the customer (e.g., 1099 for a €10.99 payment).
* @param returnUrl The URL the customer should be redirected to after the authorization
* process.
* @param country The ISO-3166 2-letter country code of the customer’s bank.
* @param statementDescriptor A custom statement descriptor for the payment (optional).
* @return a [SourceParams] object that can be used to create a SOFORT source
*
* @see [SOFORT Payments with Sources](https://stripe.com/docs/sources/sofort)
*/
@JvmStatic
fun createSofortParams(
@IntRange(from = 0) amount: Long,
returnUrl: String,
@Size(2) country: String,
statementDescriptor: String? = null
): SourceParams {
return SourceParams(
SourceType.SOFORT,
typeData = TypeData.Sofort(country, statementDescriptor),
currency = Source.EURO,
amount = amount,
returnUrl = returnUrl
)
}
/**
* Create 3D Secure Source params.
*
* @param amount A positive integer in the smallest currency unit representing the amount to
* charge the customer (e.g., 1099 for a €10.99 payment).
* @param currency The currency the payment is being created in (e.g., eur).
* @param returnUrl The URL the customer should be redirected to after the verification process.
* @param cardId The ID of the card source.
* @return a [SourceParams] object that can be used to create a 3D Secure source
*
* @see [3D Secure Card Payments with Sources](https://stripe.com/docs/sources/three-d-secure)
*/
@JvmStatic
fun createThreeDSecureParams(
@IntRange(from = 0) amount: Long,
currency: String,
returnUrl: String,
cardId: String
): SourceParams {
return SourceParams(
SourceType.THREE_D_SECURE,
typeData = TypeData.ThreeDSecure(cardId),
currency = currency,
amount = amount,
returnUrl = returnUrl
)
}
/**
* Create parameters needed to make a Visa Checkout source.
*
* @param callId The payment request ID (callId) from the Visa Checkout SDK.
* @return a [SourceParams] object that can be used to create a Visa Checkout Card Source.
*
* @see [https://stripe.com/docs/visa-checkout](https://stripe.com/docs/visa-checkout)
*
* @see [https://developer.visa.com/capabilities/visa_checkout/docs](https://developer.visa.com/capabilities/visa_checkout/docs)
*/
@JvmStatic
fun createVisaCheckoutParams(callId: String): SourceParams {
return SourceParams(
SourceType.CARD,
typeData = TypeData.VisaCheckout(callId)
)
}
/**
* Create parameters needed to make a Masterpass source
*
* @param transactionId The transaction ID from the Masterpass SDK.
* @param cartId A unique string that you generate to identify the purchase when creating a cart
* for checkout in the Masterpass SDK.
*
* @return a [SourceParams] object that can be used to create a Masterpass Card Source.
*
* @see [https://stripe.com/docs/masterpass](https://stripe.com/docs/masterpass)
*
* @see [https://developer.mastercard.com/product/masterpass](https://developer.mastercard.com/product/masterpass)
*
* @see [https://developer.mastercard.com/page/masterpass-merchant-mobile-checkout-sdk-for-android-v2](https://developer.mastercard.com/page/masterpass-merchant-mobile-checkout-sdk-for-android-v2)
*/
@JvmStatic
fun createMasterpassParams(
transactionId: String,
cartId: String
): SourceParams {
return SourceParams(
SourceType.CARD,
typeData = TypeData.Masterpass(
transactionId,
cartId
)
)
}
/**
* Create parameters needed to retrieve a source.
*
* @param clientSecret the client secret for the source, needed because the Android SDK uses
* a public key
* @return a [Map] matching the parameter name to the client secret, ready to send to
* the server.
*/
@JvmStatic
fun createRetrieveSourceParams(
@Size(min = 1) clientSecret: String
): Map<String, String> {
return mapOf(PARAM_CLIENT_SECRET to clientSecret)
}
}
@Parcelize
internal data class ApiParams(
val value: Map<String, Any?> = emptyMap()
) : Parcelable {
internal companion object : Parceler<ApiParams> {
override fun ApiParams.write(parcel: Parcel, flags: Int) {
parcel.writeString(
StripeJsonUtils.mapToJsonObject(value)?.toString()
)
}
override fun create(parcel: Parcel): ApiParams {
return ApiParams(
StripeJsonUtils.jsonObjectToMap(
parcel.readString()?.let {
JSONObject(it)
}
).orEmpty()
)
}
}
}
internal sealed class TypeData : Parcelable {
abstract val type: String
abstract val params: List<Pair<String, Any?>>
fun createParams(): Map<String, Map<String, Any>> {
return params.fold(
emptyMap<String, Any>()
) { acc, (key, value) ->
acc.plus(
value?.let { mapOf(key to it) }.orEmpty()
)
}.takeIf { it.isNotEmpty() }?.let {
mapOf(
type to it
)
}.orEmpty()
}
@Parcelize
data class Card(
/**
* The [number] of this card
*/
val number: String? = null,
/**
* Two-digit number representing the card’s expiration month.
*
* See [API Reference](https://stripe.com/docs/api/cards/object#card_object-exp_month).
*/
@get:IntRange(from = 1, to = 12)
val expMonth: Int?,
/**
* Four-digit number representing the card’s expiration year.
*
* See [API Reference](https://stripe.com/docs/api/cards/object#card_object-exp_year).
*/
val expYear: Int?,
/**
* The [cvc] for this card
*/
val cvc: String? = null
) : TypeData() {
override val type: String get() = SourceType.CARD
override val params: List<Pair<String, Any?>>
get() = listOf(
PARAM_NUMBER to number,
PARAM_EXP_MONTH to expMonth,
PARAM_EXP_YEAR to expYear,
PARAM_CVC to cvc
)
private companion object {
private const val PARAM_NUMBER = "number"
private const val PARAM_EXP_MONTH = "exp_month"
private const val PARAM_EXP_YEAR = "exp_year"
private const val PARAM_CVC = "cvc"
}
}
@Parcelize
data class Eps(
var statementDescriptor: String? = null
) : TypeData() {
override val type: String get() = SourceType.EPS
override val params: List<Pair<String, String?>>
get() = listOf(PARAM_STATEMENT_DESCRIPTOR to statementDescriptor)
private companion object {
private const val PARAM_STATEMENT_DESCRIPTOR = "statement_descriptor"
}
}
@Parcelize
data class Giropay(
var statementDescriptor: String? = null
) : TypeData() {
override val type: String get() = SourceType.GIROPAY
override val params: List<Pair<String, String?>>
get() = listOf(
PARAM_STATEMENT_DESCRIPTOR to statementDescriptor
)
private companion object {
private const val PARAM_STATEMENT_DESCRIPTOR = "statement_descriptor"
}
}
@Parcelize
data class Ideal(
var statementDescriptor: String? = null,
var bank: String? = null
) : TypeData() {
override val type: String get() = SourceType.IDEAL
override val params: List<Pair<String, String?>>
get() = listOf(
PARAM_STATEMENT_DESCRIPTOR to statementDescriptor,
PARAM_BANK to bank
)
private companion object {
private const val PARAM_STATEMENT_DESCRIPTOR = "statement_descriptor"
private const val PARAM_BANK = "bank"
}
}
@Parcelize
data class Masterpass(
var transactionId: String,
var cartId: String
) : TypeData() {
override val type: String get() = SourceType.CARD
override val params: List<Pair<String, Map<String, String>>>
get() = listOf(
PARAM_MASTERPASS to mapOf(
PARAM_TRANSACTION_ID to transactionId,
PARAM_CART_ID to cartId
)
)
private companion object {
private const val PARAM_CART_ID = "cart_id"
private const val PARAM_MASTERPASS = "masterpass"
private const val PARAM_TRANSACTION_ID = "transaction_id"
}
}
@Parcelize
data class Sofort(
@Size(2) var country: String,
var statementDescriptor: String? = null
) : TypeData() {
override val type: String get() = SourceType.SOFORT
override val params: List<Pair<String, String?>>
get() = listOf(
PARAM_COUNTRY to country,
PARAM_STATEMENT_DESCRIPTOR to statementDescriptor
)
private companion object {
private const val PARAM_COUNTRY = "country"
private const val PARAM_STATEMENT_DESCRIPTOR = "statement_descriptor"
}
}
@Parcelize
data class SepaDebit(
var iban: String
) : TypeData() {
override val type: String get() = SourceType.SEPA_DEBIT
override val params: List<Pair<String, String?>>
get() = listOf(PARAM_IBAN to iban)
private companion object {
private const val PARAM_IBAN = "iban"
}
}
@Parcelize
data class ThreeDSecure(
var cardId: String
) : TypeData() {
override val type: String get() = SourceType.THREE_D_SECURE
override val params: List<Pair<String, String?>>
get() = listOf(PARAM_CARD to cardId)
private companion object {
private const val PARAM_CARD = "card"
}
}
@Parcelize
data class VisaCheckout(
var callId: String
) : TypeData() {
override val type: String get() = SourceType.CARD
override val params: List<Pair<String, Any?>>
get() = listOf(
PARAM_VISA_CHECKOUT to mapOf(
PARAM_CALL_ID to callId
)
)
private companion object {
private const val PARAM_VISA_CHECKOUT = "visa_checkout"
private const val PARAM_CALL_ID = "callid"
}
}
@Parcelize
data class Bancontact(
var statementDescriptor: String? = null,
var preferredLanguage: String? = null
) : TypeData() {
override val type: String get() = SourceType.BANCONTACT
override val params: List<Pair<String, String?>>
get() = listOf(
PARAM_STATEMENT_DESCRIPTOR to statementDescriptor,
PARAM_PREFERRED_LANGUAGE to preferredLanguage
)
private companion object {
private const val PARAM_STATEMENT_DESCRIPTOR = "statement_descriptor"
private const val PARAM_PREFERRED_LANGUAGE = "preferred_language"
}
}
}
}
| mit | ffd824d5d467639c11ad130e082ce448 | 36.151855 | 204 | 0.541211 | 4.991769 | false | false | false | false |
Undin/intellij-rust | coverage/src/main/kotlin/org/rust/coverage/RsCoverageEngine.kt | 3 | 9436 | /*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.coverage
import com.intellij.codeEditor.printing.ExportToHTMLSettings
import com.intellij.coverage.*
import com.intellij.coverage.view.CoverageViewExtension
import com.intellij.coverage.view.CoverageViewManager
import com.intellij.coverage.view.DirectoryCoverageViewExtension
import com.intellij.coverage.view.PercentageCoverageColumnInfo
import com.intellij.execution.configurations.RunConfigurationBase
import com.intellij.execution.configurations.coverage.CoverageEnabledConfiguration
import com.intellij.execution.testframework.AbstractTestProxy
import com.intellij.ide.util.treeView.AbstractTreeNode
import com.intellij.ide.util.treeView.AlphaComparator
import com.intellij.ide.util.treeView.NodeDescriptor
import com.intellij.openapi.actionSystem.DataContext
import com.intellij.openapi.application.runWriteAction
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.module.Module
import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.Messages
import com.intellij.openapi.util.io.FileUtil
import com.intellij.openapi.vfs.VfsUtil
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiFile
import com.intellij.rt.coverage.data.ClassData
import com.intellij.util.ui.ColumnInfo
import org.rust.cargo.runconfig.command.CargoCommandConfiguration
import org.rust.coverage.LcovCoverageReport.Serialization.writeLcov
import org.rust.lang.RsFileType
import org.rust.lang.core.psi.RsFile
import java.io.File
import java.io.IOException
import java.util.*
class RsCoverageEngine : CoverageEngine() {
override fun getQualifiedNames(sourceFile: PsiFile): Set<String> {
val qName = getQName(sourceFile)
return if (qName != null) setOf(qName) else emptySet()
}
override fun acceptedByFilters(psiFile: PsiFile, suite: CoverageSuitesBundle): Boolean = psiFile is RsFile
override fun coverageEditorHighlightingApplicableTo(psiFile: PsiFile): Boolean = psiFile is RsFile
override fun createCoverageEnabledConfiguration(conf: RunConfigurationBase<*>): CoverageEnabledConfiguration =
RsCoverageEnabledConfiguration(conf)
override fun getQualifiedName(outputFile: File, sourceFile: PsiFile): String? = getQName(sourceFile)
override fun includeUntouchedFileInCoverage(
qualifiedName: String,
outputFile: File,
sourceFile: PsiFile,
suite: CoverageSuitesBundle
): Boolean = false
override fun coverageProjectViewStatisticsApplicableTo(fileOrDir: VirtualFile): Boolean =
!fileOrDir.isDirectory && fileOrDir.fileType == RsFileType
override fun getTestMethodName(element: PsiElement, testProxy: AbstractTestProxy): String? = null
override fun getCoverageAnnotator(project: Project): CoverageAnnotator = RsCoverageAnnotator.getInstance(project)
override fun isApplicableTo(conf: RunConfigurationBase<*>): Boolean = conf is CargoCommandConfiguration
override fun createEmptyCoverageSuite(coverageRunner: CoverageRunner): CoverageSuite = RsCoverageSuite()
override fun getPresentableText(): String = "Rust Coverage"
override fun createCoverageViewExtension(
project: Project,
suiteBundle: CoverageSuitesBundle,
stateBean: CoverageViewManager.StateBean
): CoverageViewExtension =
object : DirectoryCoverageViewExtension(project, getCoverageAnnotator(project), suiteBundle, stateBean) {
override fun createColumnInfos(): Array<ColumnInfo<NodeDescriptor<*>, String>> {
val percentage = PercentageCoverageColumnInfo(
1,
"Covered, %",
mySuitesBundle,
myStateBean
)
val files = object : ColumnInfo<NodeDescriptor<*>, String>("File") {
override fun valueOf(item: NodeDescriptor<*>?): String = item.toString()
override fun getComparator(): Comparator<NodeDescriptor<*>>? = AlphaComparator.INSTANCE
}
return arrayOf(files, percentage)
}
override fun getChildrenNodes(node: AbstractTreeNode<*>): List<AbstractTreeNode<*>> =
super.getChildrenNodes(node).filter { child ->
val value = child.value
if (value is PsiFile) {
value.fileType == RsFileType
} else {
child.name != Project.DIRECTORY_STORE_FOLDER
}
}
}
override fun recompileProjectAndRerunAction(
module: Module,
suite: CoverageSuitesBundle,
chooseSuiteAction: Runnable
): Boolean = false
override fun canHavePerTestCoverage(conf: RunConfigurationBase<*>): Boolean = false
override fun findTestsByNames(testNames: Array<out String>, project: Project): List<PsiElement> = emptyList()
override fun isReportGenerationAvailable(
project: Project,
dataContext: DataContext,
currentSuite: CoverageSuitesBundle
): Boolean = true
override fun generateReport(project: Project, dataContext: DataContext, currentSuiteBundle: CoverageSuitesBundle) {
val coverageReport = LcovCoverageReport()
val dataManager = CoverageDataManager.getInstance(project)
for (suite in currentSuiteBundle.suites) {
val projectData = suite.getCoverageData(dataManager) ?: continue
val classDataMap = projectData.classes
for ((filePath, classData) in classDataMap) {
val lineHitsList = convertClassDataToLineHits(classData)
coverageReport.mergeFileReport(null, filePath, lineHitsList)
}
}
val settings = ExportToHTMLSettings.getInstance(project)
val outputDir = File(settings.OUTPUT_DIRECTORY)
FileUtil.createDirectory(outputDir)
val outputFileName = getOutputFileName(currentSuiteBundle)
val title = "Coverage Report Generation"
try {
val output = File(outputDir, outputFileName)
writeLcov(coverageReport, output)
refresh(output)
// TODO: generate html report ourselves
val url = "https://github.com/linux-test-project/lcov"
Messages.showInfoMessage(
"<html>Coverage report has been successfully saved as '$outputFileName' file.<br>" +
"Use instruction in <a href='$url'>$url</a> to generate HTML output.</html>",
title
)
} catch (e: IOException) {
LOG.warn("Can not export coverage data", e)
Messages.showErrorDialog("Can not generate coverage report: ${e.message}", title)
}
}
private fun refresh(file: File) {
val vFile = VfsUtil.findFileByIoFile(file, true)
if (vFile != null) {
runWriteAction { vFile.refresh(false, false) }
}
}
private fun getOutputFileName(currentSuitesBundle: CoverageSuitesBundle): String = buildString {
for (suite in currentSuitesBundle.suites) {
val presentableName = suite.presentableName
append(presentableName)
}
append(".lcov")
}
private fun convertClassDataToLineHits(classData: ClassData): List<LcovCoverageReport.LineHits> {
val lineCount = classData.lines.size
val lineHitsList = ArrayList<LcovCoverageReport.LineHits>(lineCount)
for (lineInd in 0 until lineCount) {
val lineData = classData.getLineData(lineInd)
if (lineData != null) {
val lineHits = LcovCoverageReport.LineHits(lineData.lineNumber, lineData.hits)
lineHitsList.add(lineHits)
}
}
return lineHitsList
}
override fun collectSrcLinesForUntouchedFile(classFile: File, suite: CoverageSuitesBundle): List<Int>? = null
override fun createCoverageSuite(
covRunner: CoverageRunner,
name: String,
coverageDataFileProvider: CoverageFileProvider,
filters: Array<out String?>?,
lastCoverageTimeStamp: Long,
suiteToMerge: String?,
coverageByTestEnabled: Boolean,
tracingEnabled: Boolean,
trackTestFolders: Boolean,
project: Project?
): CoverageSuite? = null
override fun createCoverageSuite(
covRunner: CoverageRunner,
name: String,
coverageDataFileProvider: CoverageFileProvider,
config: CoverageEnabledConfiguration
): CoverageSuite? {
if (config !is RsCoverageEnabledConfiguration) return null
val configuration = config.configuration as? CargoCommandConfiguration ?: return null
return RsCoverageSuite(
configuration.project,
name,
coverageDataFileProvider,
covRunner,
configuration.workingDirectory?.toString(),
config.coverageProcess
)
}
companion object {
private val LOG: Logger = logger<RsCoverageEngine>()
fun getInstance(): RsCoverageEngine = EP_NAME.findExtensionOrFail(RsCoverageEngine::class.java)
private fun getQName(sourceFile: PsiFile): String? = sourceFile.virtualFile?.path
}
}
| mit | 897cf7d930ad64ed28fab57510669045 | 40.752212 | 119 | 0.691607 | 5.062232 | false | true | false | false |
mvarnagiris/expensius | app/src/main/kotlin/com/mvcoding/expensius/feature/premium/RealBillingProductsService.kt | 1 | 2793 | /*
* Copyright (C) 2017 Mantas Varnagiris.
*
* 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.
*/
package com.mvcoding.expensius.feature.premium
import android.app.Activity
import android.content.Context
import android.content.Intent
import com.mvcoding.billing.BillingHelper
import com.mvcoding.billing.Inventory
import com.mvcoding.billing.Product
import com.mvcoding.billing.ProductId
import com.mvcoding.billing.ProductType.SINGLE
import com.mvcoding.expensius.model.SubscriptionType.FREE
import com.mvcoding.expensius.model.SubscriptionType.PREMIUM_PAID
import rx.Observable
class RealBillingProductsService(context: Context) : Billing {
private val premiumItemsIds = listOf("premium_1", "premium_2", "premium_3")
private val billingHelper = BillingHelper(
context,
"MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAm5OUB6qySEUQnCDvVKEq3CXOvr2Pm7voQftfe2keqsk/0CsGFKJOzcaSwwI459cl65O3ns/DROvMGPRtyb"
+ "5WJz0nTinj/STPlBTb1DptOniIx/ex5+gXDyvVcxjC4A67bJcy12Wm6fWh10xKoBEWyKBIao5zM1Z5ZJnD4lgh6XyylhvwBZvL2jIKE27hTPSpnglfqlZbqH6SaV"
+ "4Rs+8Jscq72xUPJffrj8M8gFosLgsyNLZ0Ci7ubSpfuKEfkUiCq30R8A0vbeFsXaevu0Luv9BlaUxYBEgMTg4Qt+emVqWfrMYqc0k9IEmd0/hRapCSPMhYHY9Gfy"
+ "LU7pyUkMYmsQIDAQAB")
override fun billingProducts(): Observable<List<BillingProduct>> = billingHelper.startSetup().map {
val inventory = billingHelper.queryInventory(true, premiumItemsIds.map { ProductId(it) })
inventory.products().map { it.toBillingProduct(inventory) }
}
override fun close() = billingHelper.dispose()
override fun startPurchase(activity: Activity, requestCode: Int, productId: String): Observable<Unit> =
billingHelper.launchPurchaseFlow(activity, requestCode, ProductId(productId), SINGLE, emptyList(), "").map { Unit }
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) =
billingHelper.onActivityResult(requestCode, resultCode, data)
private fun ProductId.toSubscriptionType() = if (id.startsWith("premium")) FREE else PREMIUM_PAID
private fun Product.toBillingProduct(inventory: Inventory) = BillingProduct(productId.id,
productId.toSubscriptionType(),
title,
description,
price.price,
inventory.hasPurchase(productId))
} | gpl-3.0 | b561f89e6e4f043884d9d9b24254fa20 | 45.566667 | 140 | 0.761905 | 3.603871 | false | false | false | false |
noud02/Akatsuki | src/main/kotlin/moe/kyubey/akatsuki/commands/Setup.kt | 1 | 8092 | /*
* Copyright (c) 2017-2019 Yui
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following
* conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*/
package moe.kyubey.akatsuki.commands
import io.sentry.Sentry
import me.aurieh.ares.exposed.async.asyncTransaction
import moe.kyubey.akatsuki.Akatsuki
import moe.kyubey.akatsuki.EventListener
import moe.kyubey.akatsuki.annotations.Argument
import moe.kyubey.akatsuki.annotations.Load
import moe.kyubey.akatsuki.annotations.Perm
import moe.kyubey.akatsuki.db.schema.Guilds
import moe.kyubey.akatsuki.entities.Command
import moe.kyubey.akatsuki.entities.Context
import moe.kyubey.akatsuki.extensions.searchTextChannels
import moe.kyubey.akatsuki.utils.TextChannelPicker
import net.dv8tion.jda.core.Permission
import net.dv8tion.jda.core.entities.TextChannel
import net.dv8tion.jda.core.events.message.MessageReceivedEvent
import org.jetbrains.exposed.sql.update
import java.util.concurrent.CompletableFuture
@Load
@Perm(Permission.MANAGE_SERVER)
@Argument("topic", "string", true)
class Setup : Command() {
override val desc = "Easy setup of Kyubey."
override val guildOnly = true
private val topics = listOf(
"starboard",
"modlogs",
"logs"
)
override fun run(ctx: Context) {
val topic = ctx.args.getOrDefault("topic", "choose") as String
if (topic == "choose") {
ctx.channel.sendMessage("What would you like to set up? (`cancel` to cancel, `list` for a list of topics)").queue {
EventListener.waiter.await<MessageReceivedEvent>(1, 60000L) { event ->
if (event.author.id == ctx.author.id && event.channel.id == ctx.channel.id) {
if (event.message.contentRaw == "list") {
ctx.sendCode("asciidoc", topics.joinToString("\n"))
return@await true
}
if (event.message.contentRaw != "cancel") {
setupTopic(ctx, event.message.contentRaw)
}
true
} else {
false
}
}
}
} else {
setupTopic(ctx, topic)
}
}
private fun setupTopic(ctx: Context, topic: String) {
when (topic) {
"starboard" -> setupStarboard(ctx)
"modlogs" -> setupModlogs(ctx)
"modlog" -> setupModlogs(ctx)
"logs" -> setupLogs(ctx)
else -> ctx.send("Setup topic not found!")
}
}
private fun askChannel(ctx: Context): CompletableFuture<TextChannel> {
val fut = CompletableFuture<TextChannel>()
EventListener.waiter.await<MessageReceivedEvent>(1, 60000L) { event ->
if (event.author.id == ctx.author.id && event.channel.id == ctx.channel.id) {
if (event.message.contentRaw == "cancel") {
return@await true
}
val channels = ctx.guild!!.searchTextChannels(event.message.contentRaw)
if (channels.isEmpty()) {
ctx.channel.sendMessage("Couldn't find that channel, mind trying again?").queue {
askChannel(ctx).thenAccept { fut.complete(it) }
}
return@await true
}
if (channels.size == 1) {
fut.complete(channels[0])
return@await true
}
val picker = TextChannelPicker(EventListener.waiter, ctx.member!!, channels, ctx.guild)
picker.build(ctx.msg).thenAccept { fut.complete(it) }
true
} else {
false
}
}
return fut
}
private fun setupStarboard(ctx: Context) {
ctx.channel.sendMessage("What channel would you like to have the starboard in? (`cancel` to cancel)").queue {
askChannel(ctx).thenAccept { channel ->
asyncTransaction(Akatsuki.pool) {
Guilds.update({
Guilds.id.eq(ctx.guild!!.idLong)
}) {
it[starboard] = true
it[starboardChannel] = channel.idLong
}
}.execute().thenAccept {
ctx.send("Successfully set up starboard! (You can disable starboard using `k;config disable starboard`)")
}.thenApply {}.exceptionally {
Sentry.capture(it)
ctx.sendError(it)
ctx.logger.error("Error while trying to set up starboard", it)
}
}
}
}
private fun setupModlogs(ctx: Context) {
ctx.channel.sendMessage("What channel would you like to have the modlog in? (`cancel` to cancel)").queue {
askChannel(ctx).thenAccept { channel ->
asyncTransaction(Akatsuki.pool) {
Guilds.update({
Guilds.id.eq(ctx.guild!!.idLong)
}) {
it[modlogs] = true
it[modlogChannel] = channel.idLong
}
}.execute().thenAccept {
ctx.send("Successfully set up modlogs! (You can disable modlogs using `k;config disable modlogs`)")
}.thenApply {}.exceptionally {
Sentry.capture(it)
ctx.sendError(it)
ctx.logger.error("Error while trying to set up modlogs", it)
}
}
}
}
private fun setupLogs(ctx: Context) {
ctx.channel.sendMessage("Are you sure you want to enable message logs for **all** channels? [y/N]").queue {
EventListener.waiter.await<MessageReceivedEvent>(1, 60000L) { event ->
if (event.author.id == ctx.author.id && event.channel.id == ctx.channel.id) {
if (event.message.contentRaw.toLowerCase().startsWith("y")) {
asyncTransaction(Akatsuki.pool) {
Guilds.update({
Guilds.id.eq(ctx.guild!!.idLong)
}) {
it[logs] = true
}
}.execute().thenAccept {
ctx.send("Successfully set up message logs! (You can disable logs using `k;config disable logs`)")
}.thenApply {}.exceptionally {
Sentry.capture(it)
ctx.sendError(it)
ctx.logger.error("Error while trying to set up logs", it)
}
} else {
ctx.send("Logs will **not** be enabled.")
}
true
} else {
false
}
}
}
}
} | mit | 3fa67c5d4cbb83c622e80dd7bc95c4f8 | 38.866995 | 127 | 0.544736 | 4.779681 | false | false | false | false |
HabitRPG/habitrpg-android | Habitica/src/main/java/com/habitrpg/android/habitica/ui/helpers/AutocompleteAdapter.kt | 1 | 5775 | package com.habitrpg.android.habitica.ui.helpers
import android.content.Context
import android.view.View
import android.view.ViewGroup
import android.widget.BaseAdapter
import android.widget.Filter
import android.widget.Filterable
import android.widget.TextView
import com.habitrpg.android.habitica.R
import com.habitrpg.android.habitica.data.SocialRepository
import com.habitrpg.android.habitica.extensions.inflate
import com.habitrpg.android.habitica.models.auth.LocalAuthentication
import com.habitrpg.android.habitica.models.social.ChatMessage
import com.habitrpg.android.habitica.models.social.FindUsernameResult
import com.habitrpg.android.habitica.models.user.Authentication
import com.habitrpg.android.habitica.models.user.Profile
import com.habitrpg.android.habitica.ui.views.social.UsernameLabel
import java.util.Date
class AutocompleteAdapter(val context: Context, val socialRepository: SocialRepository? = null, var autocompleteContext: String? = null, var groupID: String? = null, val remoteAutocomplete: Boolean = false) : BaseAdapter(), Filterable {
var chatMessages: List<ChatMessage> = arrayListOf()
private var userResults: List<FindUsernameResult> = arrayListOf()
private var emojiResults: List<String> = arrayListOf()
private var isAutocompletingUsers = true
private var lastAutocomplete: Long = 0
override fun getFilter(): Filter {
return object : Filter() {
override fun performFiltering(constraint: CharSequence?): FilterResults {
val filterResults = FilterResults()
if (constraint != null && constraint.isNotEmpty()) {
if (constraint[0] == '@' && constraint.length >= 3 && socialRepository != null && remoteAutocomplete) {
if (Date().time - lastAutocomplete > 2000) {
lastAutocomplete = Date().time
userResults = arrayListOf()
isAutocompletingUsers = true
socialRepository.findUsernames(constraint.toString().drop(1), autocompleteContext, groupID).blockingSubscribe {
userResults = it
filterResults.values = userResults
filterResults.count = userResults.size
}
} else {
filterResults.values = userResults
filterResults.count = userResults.size
}
} else if (constraint[0] == '@') {
lastAutocomplete = Date().time
isAutocompletingUsers = true
userResults = chatMessages.distinctBy {
it.username
}.filter { it.username?.startsWith(constraint.toString().drop(1)) ?: false }.map { message ->
val result = FindUsernameResult()
result.authentication = Authentication()
result.authentication?.localAuthentication = LocalAuthentication()
result.authentication?.localAuthentication?.username = message.username
result.contributor = message.contributor
result.profile = Profile()
result.profile?.name = message.user
result
}
filterResults.values = userResults
filterResults.count = userResults.size
} else if (constraint[0] == ':') {
isAutocompletingUsers = false
emojiResults = EmojiMap.invertedEmojiMap.keys.filter { it.startsWith(constraint) }
filterResults.values = emojiResults
filterResults.count = emojiResults.size
}
}
return filterResults
}
override fun publishResults(contraint: CharSequence?, results: FilterResults?) {
if (results != null && results.count > 0) {
notifyDataSetChanged()
} else {
notifyDataSetInvalidated()
}
}
}
}
override fun getView(position: Int, convertView: View?, parent: ViewGroup?): View {
return if (isAutocompletingUsers) {
val view = parent?.inflate(R.layout.autocomplete_username)
val result = getItem(position) as? FindUsernameResult
val displaynameView = view?.findViewById<UsernameLabel>(R.id.display_name_view)
displaynameView?.username = result?.profile?.name
displaynameView?.tier = result?.contributor?.level ?: 0
view?.findViewById<TextView>(R.id.username_view)?.text = result?.formattedUsername
view
} else {
val view = parent?.inflate(R.layout.autocomplete_emoji)
val result = getItem(position) as? String
val emojiTextView = view?.findViewById<TextView>(R.id.emoji_textview)
emojiTextView?.text = EmojiParser.parseEmojis(result)
view?.findViewById<TextView>(R.id.label)?.text = result
view
} ?: View(context)
}
override fun getItem(position: Int): Any? {
return if (isAutocompletingUsers) userResults.getOrNull(position) else emojiResults.getOrNull(position)
}
override fun getItemId(position: Int): Long {
return getItem(position).hashCode().toLong()
}
override fun getCount(): Int {
return if (isAutocompletingUsers) userResults.size else emojiResults.size
}
}
| gpl-3.0 | 48e4a96b39f08ebca4053029f18a2408 | 49.657895 | 236 | 0.596537 | 5.48433 | false | false | false | false |
androidx/androidx | compose/compiler/compiler-hosted/integration-tests/src/test/java/androidx/compose/compiler/plugins/kotlin/ControlFlowTransformTestsNoSource.kt | 3 | 6019 | /*
* Copyright 2020 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.compose.compiler.plugins.kotlin
import org.junit.Test
class ControlFlowTransformTestsNoSource : AbstractControlFlowTransformTests() {
override val sourceInformationEnabled: Boolean get() = false
@Test
fun testPublicFunctionAlwaysMarkedAsCall(): Unit = controlFlow(
"""
@Composable
fun Test() {
A(a)
A(b)
}
""",
"""
@Composable
fun Test(%composer: Composer?, %changed: Int) {
%composer = %composer.startRestartGroup(<>)
sourceInformation(%composer, "C(Test)")
if (%changed !== 0 || !%composer.skipping) {
if (isTraceInProgress()) {
traceEventStart(<>, %changed, -1, <>)
}
A(a, %composer, 0)
A(b, %composer, 0)
if (isTraceInProgress()) {
traceEventEnd()
}
} else {
%composer.skipToGroupEnd()
}
%composer.endRestartGroup()?.updateScope { %composer: Composer?, %force: Int ->
Test(%composer, updateChangedFlags(%changed or 0b0001))
}
}
"""
)
@Test
fun testPrivateFunctionDoNotGetMarkedAsCall(): Unit = controlFlow(
"""
@Composable
private fun Test() {
A(a)
A(b)
}
""",
"""
@Composable
private fun Test(%composer: Composer?, %changed: Int) {
%composer = %composer.startRestartGroup(<>)
if (%changed !== 0 || !%composer.skipping) {
if (isTraceInProgress()) {
traceEventStart(<>, %changed, -1, <>)
}
A(a, %composer, 0)
A(b, %composer, 0)
if (isTraceInProgress()) {
traceEventEnd()
}
} else {
%composer.skipToGroupEnd()
}
%composer.endRestartGroup()?.updateScope { %composer: Composer?, %force: Int ->
Test(%composer, updateChangedFlags(%changed or 0b0001))
}
}
"""
)
@Test
fun testCallingAWrapperComposable(): Unit = controlFlow(
"""
@Composable
fun Test() {
W {
A()
}
}
""",
"""
@Composable
fun Test(%composer: Composer?, %changed: Int) {
%composer = %composer.startRestartGroup(<>)
sourceInformation(%composer, "C(Test)")
if (%changed !== 0 || !%composer.skipping) {
if (isTraceInProgress()) {
traceEventStart(<>, %changed, -1, <>)
}
W(ComposableSingletons%TestKt.lambda-1, %composer, 0b0110)
if (isTraceInProgress()) {
traceEventEnd()
}
} else {
%composer.skipToGroupEnd()
}
%composer.endRestartGroup()?.updateScope { %composer: Composer?, %force: Int ->
Test(%composer, updateChangedFlags(%changed or 0b0001))
}
}
internal object ComposableSingletons%TestKt {
val lambda-1: Function2<Composer, Int, Unit> = composableLambdaInstance(<>, false) { %composer: Composer?, %changed: Int ->
if (%changed and 0b1011 !== 0b0010 || !%composer.skipping) {
if (isTraceInProgress()) {
traceEventStart(<>, %changed, -1, <>)
}
A(%composer, 0)
if (isTraceInProgress()) {
traceEventEnd()
}
} else {
%composer.skipToGroupEnd()
}
}
}
"""
)
@Test
fun testCallingAnInlineWrapperComposable(): Unit = controlFlow(
"""
@Composable
fun Test() {
IW {
A()
}
}
""",
"""
@Composable
fun Test(%composer: Composer?, %changed: Int) {
%composer = %composer.startRestartGroup(<>)
sourceInformation(%composer, "C(Test)")
if (%changed !== 0 || !%composer.skipping) {
if (isTraceInProgress()) {
traceEventStart(<>, %changed, -1, <>)
}
IW({ %composer: Composer?, %changed: Int ->
%composer.startReplaceableGroup(<>)
if (%changed and 0b1011 !== 0b0010 || !%composer.skipping) {
A(%composer, 0)
} else {
%composer.skipToGroupEnd()
}
%composer.endReplaceableGroup()
}, %composer, 0)
if (isTraceInProgress()) {
traceEventEnd()
}
} else {
%composer.skipToGroupEnd()
}
%composer.endRestartGroup()?.updateScope { %composer: Composer?, %force: Int ->
Test(%composer, updateChangedFlags(%changed or 0b0001))
}
}
"""
)
}
| apache-2.0 | 03b717eccfc7db171ffa3e338ff80625 | 32.814607 | 137 | 0.467021 | 5.461887 | false | true | false | false |
sebasjm/deepdiff | src/main/kotlin/diff/equality/strategies/ArrayEqualityStrategy.kt | 1 | 1097 | package diff.equality.strategies
import diff.equality.EqualityStrategy
import diff.equality.EqualityStrategy.UndecidibleMoreToCompare
import diff.patch.Coordinate
import diff.patch.coords.ArrayCoordinates
import java.lang.reflect.Array
/**
* @author Sebastian Marchano [email protected]
*/
class ArrayEqualityStrategy<ArrayType: Any> : EqualityStrategy<ArrayType> {
/**
* Arrays should have the same size
* @param pair
* *
* @return
*/
override fun compare(before: ArrayType, after: ArrayType): EqualityStrategy.CompareResult {
val lengthBefore = Array.getLength(before)
val lengthAfter = Array.getLength(after)
if (lengthBefore == 0 && lengthAfter == 0) return EqualityStrategy.CompareResult.EQUALS
val max = Math.max(lengthBefore, lengthAfter) - 1
val result = (0..max).map {
{ parent: Coordinate<Any, Any> -> ArrayCoordinates<Any, Any>(it, parent) }
}
return UndecidibleMoreToCompare(result)
}
override fun shouldUseThisStrategy(clazz: Class<ArrayType>) = clazz.isArray
}
| apache-2.0 | 4110b310c45a1b25fdd9bfad65351375 | 27.128205 | 95 | 0.700091 | 4.423387 | false | false | false | false |
SevenLines/Celebs-Image-Viewer | src/main/kotlin/theplace/parsers/ThePlaceParser.kt | 1 | 2900 | package theplace.parsers
import com.mashape.unirest.http.Unirest
import org.jsoup.Jsoup
import org.jsoup.nodes.Element
import theplace.parsers.elements.*
import java.io.InputStream
class ThePlaceParser() : BaseParser("http://www.theplace.ru", "theplace") {
override var isAlwaysOneAlbum = true
override var isAlwaysOneSubGallery = true
override fun getAlbumPages(album: GalleryAlbum): List<GalleryAlbumPage> {
val response = Unirest.get(album.url).asString()
val doc = Jsoup.parse(response.body)
val links = doc.select(".listalka.ltop a")
val items = links.map { it.text() }.filter { "\\d+".toRegex().matches(it) }.map { it.toInt() }
val count = when (items.size) {
0 -> 1
else -> items.max()
}
return IntRange(1, count ?: 1).map {
var href = "$url/photos/gallery.php?id=${album.id}&page=$it"
GalleryAlbumPage(url = href, album = album)
}
}
private fun galleryItemForLink(link: Element): Gallery {
val href = link.attr("href")
val id = """mid(\d+).html""".toRegex().find(href)?.groups!![1]?.value
return Gallery(title = link.text(), url = "$url/photos/$href", parser = this, id = id!!.toInt())
}
private fun galleryImageForLink(el: Element, albumPage: GalleryAlbumPage): GalleryImage {
var thumb = el.attr("src")
var url = """^(.*?)(_s)(\.\w+)$""".toRegex().replace(thumb, """$1$3""")
return GalleryImage(
url_thumb = "${this.url}$thumb",
url = "${this.url}$url",
page = albumPage,
album = albumPage.album
)
}
override fun downloadImage(image_url: String): InputStream? {
return Unirest.get(image_url).header("referer", "$url").asBinary().body
}
override fun getImages(albumPage: GalleryAlbumPage): List<GalleryImage> {
var response = Unirest.get(albumPage.url).asString()
var doc = Jsoup.parse(response.body)
var links = doc.select(".gallery-pics-list .pic_box a img")
return links.map { galleryImageForLink(it, albumPage) }
}
override fun getGalleries_internal(): List<Gallery> {
var out = IntRange(0, 3).map {
val response = Unirest.get("${url}/photos").queryString("s_id", it.toString()).asString()
val doc = Jsoup.parse(response.body)
val links = doc.select(".td_all .main-col-content .clearfix a")
return@map links.map { galleryItemForLink(it) }
}.reduce { list, list2 -> list + list2 }
return out
}
override fun getAlbums(subGallery: SubGallery): List<GalleryAlbum> {
return listOf(GalleryAlbum(
url = subGallery.url,
title = subGallery.title,
id = subGallery.id,
subgallery = subGallery)
)
}
} | mit | c0decf2dce22907c29e600096e786ca4 | 37.171053 | 104 | 0.593448 | 4.011065 | false | false | false | false |
52inc/android-52Kit | library/src/main/java/com/ftinc/kit/extensions/IntentExtensions.kt | 1 | 1695 | /*
* Copyright (c) 2019 52inc.
*
* 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.ftinc.kit.extensions
import android.content.Intent
import android.os.Parcel
import com.ftinc.kit.util.BundleBuilder
/**
* Add the [Intent.FLAG_ACTIVITY_NEW_TASK] and [Intent.FLAG_ACTIVITY_CLEAR_TASK] flags to an intent
*/
fun Intent.clear(): Intent = this.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK)
/**
* Add the [Intent.FLAG_ACTIVITY_CLEAR_TOP] and [Intent.FLAG_ACTIVITY_SINGLE_TOP] flags to an intent
*/
fun Intent.top(): Intent = this.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_SINGLE_TOP)
/**
* Generate a Data based Intent for returning in [Context.startActivityForResult(intent, requestCode)]
*/
fun dataIntent(init: BundleBuilder.() -> Unit): Intent {
val intent = Intent()
val bundler = BundleBuilder()
bundler.init()
intent.putExtras(bundler.build())
return intent
}
/**
* Get the data size in Bytes for this intent when it is parceled
*/
fun Intent.bytes(): Int {
val p = Parcel.obtain()
this.writeToParcel(p, 0)
val bytes = p.dataSize()
p.recycle()
return bytes
}
| apache-2.0 | 5ec91e49b9f5a8c7f69d3d0d4a84e5d5 | 28.224138 | 108 | 0.718584 | 3.717105 | false | false | false | false |
codehz/container | app/src/main/java/one/codehz/container/fragment/BasicDetailFragment.kt | 1 | 3576 | package one.codehz.container.fragment
import android.content.ClipData
import android.os.Bundle
import android.support.design.widget.Snackbar
import android.support.v4.app.Fragment
import android.support.v7.widget.DefaultItemAnimator
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import one.codehz.container.R
import one.codehz.container.adapters.LogListAdapter
import one.codehz.container.adapters.PropertyListAdapter
import one.codehz.container.ext.MakeLoaderCallbacks
import one.codehz.container.ext.clipboardManager
import one.codehz.container.ext.get
import one.codehz.container.ext.virtualCore
import one.codehz.container.models.AppModel
import one.codehz.container.models.AppPropertyModel
import one.codehz.container.models.LogModel
import one.codehz.container.provider.MainProvider
class BasicDetailFragment(val model: AppModel, onSnack: (Snackbar) -> Unit) : Fragment() {
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?) = inflater.inflate(R.layout.application_basic_detail, container, false)!!
val contentList by lazy<RecyclerView> { view!![R.id.content_list] }
val logList by lazy<RecyclerView> { view!![R.id.log_list] }
val clearLogButton by lazy<Button> { view!![R.id.clear_log] }
val propertyLoader by MakeLoaderCallbacks({ context }, { it() }) { ctx ->
contentAdapter.updateModels(AppPropertyModel(model).getItems())
}
val logLoader by MakeLoaderCallbacks({ context }, { it() }) { ctx ->
ctx.contentResolver.query(MainProvider.LOG_URI, arrayOf("time", "data"), "`package` = \"${model.packageName}\"", null, "time ASC").use {
generateSequence { if (it.moveToNext()) it else null }.map { LogModel(it.getString(0), it.getString(1)) }.toList()
}.run {
logListAdapter.updateModels(this)
}
}
val contentAdapter by lazy {
PropertyListAdapter<AppPropertyModel> { key, value ->
clipboardManager.primaryClip = ClipData.newPlainText(key, value)
onSnack(Snackbar.make(contentList, virtualCore.context.getString(R.string.value_copied, key), Snackbar.LENGTH_SHORT))
}
}
val logListAdapter by lazy {
LogListAdapter { time, value ->
clipboardManager.primaryClip = ClipData.newPlainText("log", value)
onSnack(Snackbar.make(contentList, getString(R.string.log_copied), Snackbar.LENGTH_SHORT))
}
}
override fun onViewCreated(view: View?, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
with(contentList) {
adapter = contentAdapter
layoutManager = LinearLayoutManager(context)
}
with(logList) {
adapter = logListAdapter
layoutManager = LinearLayoutManager(context)
itemAnimator = DefaultItemAnimator()
}
loaderManager.restartLoader(0, null, propertyLoader)
loaderManager.restartLoader(1, null, logLoader)
clearLogButton.setOnClickListener {
context.contentResolver.delete(MainProvider.LOG_URI, "`package` = \"${model.packageName}\"", null)
loaderManager.restartLoader(1, null, logLoader)
}
}
override fun onResume() {
super.onResume()
loaderManager.restartLoader(0, null, propertyLoader)
loaderManager.restartLoader(1, null, logLoader)
}
} | gpl-3.0 | 81e2751e01ffa4e02327ebb2e80fcd7b | 43.160494 | 181 | 0.714485 | 4.47 | false | false | false | false |
Tvede-dk/CommonsenseAndroidKotlin | widgets/src/test/kotlin/com/commonsense/android/kotlin/views/widgets/UpdateVariableTest.kt | 1 | 1174 | package com.commonsense.android.kotlin.views.widgets
import com.commonsense.android.kotlin.views.datastructures.*
import org.junit.*
/**
* Created by Kasper Tvede on 15-06-2017.
*/
class UpdateVariableTest {
@Test
fun testValue() {
val toTest = UpdateVariable("testValue") {}
Assert.assertEquals(toTest.value, "testValue")
toTest.value = "newValue"
Assert.assertEquals(toTest.value, "newValue")
toTest.setWithNoUpdate("a-hidden-value")
Assert.assertEquals(toTest.value, "a-hidden-value")
}
@Test
fun testNotification() {
var updatedVal = 0
val toTest = UpdateVariable("testValue") { updatedVal += 1 }
Assert.assertEquals(toTest.value, "testValue")
toTest.value = "qwe"
Assert.assertEquals(updatedVal, 1)//first update
toTest.value = "qwe"
Assert.assertEquals(updatedVal, 1)//nothing changed, so no update
toTest.value = "qwe2"
Assert.assertEquals(updatedVal, 2)//changed, so update
toTest.setWithNoUpdate("qwe3")
Assert.assertEquals(updatedVal, 2)//we told do not call update, so it should not happen
}
} | mit | a0bf3e25a3fb9f25725ecdcc07318972 | 29.128205 | 95 | 0.658433 | 4.223022 | false | true | false | false |
tasomaniac/OpenLinkWith | app/src/main/java/com/tasomaniac/openwith/settings/rating/AskForRatingSettings.kt | 1 | 3786 | package com.tasomaniac.openwith.settings.rating
import android.content.Intent
import android.net.Uri
import androidx.appcompat.app.AlertDialog
import androidx.core.app.ShareCompat
import androidx.preference.PreferenceCategory
import com.tasomaniac.openwith.R
import com.tasomaniac.openwith.data.Analytics
import com.tasomaniac.openwith.settings.Settings
import com.tasomaniac.openwith.settings.SettingsFragment
import javax.inject.Inject
class AskForRatingSettings @Inject constructor(
fragment: SettingsFragment,
private val condition: AskForRatingCondition,
private val analytics: Analytics
) : Settings(fragment) {
private var preferenceCategory: PreferenceCategory? = null
override fun setup() {
if (isNotDisplayed() && condition.shouldDisplay()) {
addAskForRatingPreference()
analytics.sendEvent("AskForRating", "Added", "New")
}
}
private fun addAskForRatingPreference() {
addPreferencesFromResource(R.xml.pref_ask_for_rating)
preferenceCategory = findPreference(R.string.pref_key_category_ask_for_rating) as PreferenceCategory
setupRatingBar()
}
private fun setupRatingBar() {
val preference = findPreference(R.string.pref_key_ask_for_rating) as AskForRatingPreference
preference.onRatingChange = ::handleRatingChange
}
private fun handleRatingChange(rating: Float) {
if (rating >= GOOD_RATING) {
displayPositiveRatingDialog()
} else {
displayNegativeRatingDialog()
}
analytics.sendEvent("AskForRating", "Rating Clicked", rating.toString())
}
private fun displayPositiveRatingDialog() {
AlertDialog.Builder(context)
.setTitle(R.string.pref_title_category_ask_for_rating)
.setMessage(R.string.ask_for_rating_rating_message)
.setPositiveButton(R.string.ask_for_rating_rating_positive_button) { _, _ ->
analytics.sendEvent("AskForRating", "Dialog", "Play Store")
}
.setOnDismissListener {
context.startActivity(STORE_INTENT)
condition.alreadyShown = true
remove()
}
.show()
}
private fun displayNegativeRatingDialog() {
AlertDialog.Builder(context)
.setTitle(R.string.ask_for_rating_feedback)
.setMessage(R.string.ask_for_rating_feedback_message)
.setNegativeButton(R.string.cancel, null)
.setNeutralButton("Never") { _, _ ->
condition.alreadyShown = true
analytics.sendEvent("AskForRating", "Dialog", "Never")
}
.setPositiveButton(android.R.string.ok) { _, _ ->
condition.alreadyShown = true
startContactEmailChooser()
analytics.sendEvent("AskForRating", "Dialog", "Send Email")
}
.setOnDismissListener {
remove()
}
.show()
}
private fun startContactEmailChooser() {
ShareCompat.IntentBuilder(activity)
.addEmailTo("Said Tahsin Dane <[email protected]>")
.setSubject(context.getString(R.string.ask_for_rating_feedback_email_subject))
.setType("message/rfc822")
.startChooser()
}
private fun remove() {
removePreference(preferenceCategory!!)
preferenceCategory = null
}
private fun isNotDisplayed() = preferenceCategory == null
companion object {
private val STORE_INTENT = Intent(
Intent.ACTION_VIEW,
Uri.parse("https://play.google.com/store/apps/details?id=com.tasomaniac.openwith")
)
private const val GOOD_RATING = 4
}
}
| apache-2.0 | 42ba9912f884728a098bf444900bfa88 | 34.716981 | 108 | 0.642895 | 4.738423 | false | false | false | false |
jguerinet/form-generator | library/src/main/java/Morf.kt | 1 | 10563 | /*
* Copyright 2015-2019 Julien Guerinet
*
* 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.guerinet.morf
import android.graphics.Color
import android.graphics.Typeface
import android.view.View
import android.widget.Button
import android.widget.LinearLayout
import androidx.annotation.ColorInt
import androidx.annotation.ColorRes
import androidx.annotation.DimenRes
import androidx.annotation.DrawableRes
/**
* Creates the various form items and adds them to a given container
* @author Julien Guerinet
* @since 1.0.0
*/
class Morf internal constructor(
internal val shape: Shape,
private val container: LinearLayout
) {
internal val context = container.context
/**
* @return [SpaceItem] added to the form
*/
@JvmOverloads
inline fun space(block: (SpaceItem.() -> Unit) = {}): SpaceItem =
SpaceItem(this).apply(block).build()
/**
* @return [LineItem] added to the form
*/
@JvmOverloads
inline fun line(block: (LineItem.() -> Unit) = {}): LineItem =
LineItem(this).apply(block).build()
/**
* Creates a [TextViewItem], applies the block, and returns it
*/
@JvmOverloads
inline fun text(block: (TextViewItem.() -> Unit) = {}): TextViewItem =
TextViewItem(this).apply(block).build()
/**
* Creates a [ButtonItem], applies the block, and returns it
*/
@JvmOverloads
fun button(block: (ButtonItem.() -> Unit) = {}): ButtonItem =
ButtonItem(this, Button(context)).apply(block).build()
/**
* Creates a borderless [ButtonItem], applies the block, and returns it
*/
@JvmOverloads
fun borderlessButton(block: (ButtonItem.() -> Unit) = {}): ButtonItem =
ButtonItem(this, Button(context, null, R.attr.borderlessButtonStyle))
.apply(block).build()
/**
* Creates an [EditTextItem], applies the block, and returns it
*/
@JvmOverloads
inline fun input(block: (EditTextItem.() -> Unit) = {}): EditTextItem =
EditTextItem(this).apply(block).build()
/**
* Creates a [TextInputItem], applies the block, and returns it
*/
@JvmOverloads
inline fun textInput(block: (TextInputItem.() -> Unit) = {}): TextInputItem =
TextInputItem(this).apply(block).build()
/**
* Creates a [AutoCompleteTextInputItem], applies the block, and returns it
*/
@JvmOverloads
inline fun autoCompleteTextInput(block: (AutoCompleteTextInputItem.() -> Unit) = {}):
AutoCompleteTextInputItem = AutoCompleteTextInputItem(this).apply(block).build()
/**
* Creates a [SwitchItem], applies the block, and returns it
*/
@JvmOverloads
inline fun aSwitch(block: (SwitchItem.() -> Unit) = {}): SwitchItem =
SwitchItem(this).apply(block).build()
/**
* Adds the [view] to the [container]
*/
internal fun addView(view: View) = container.addView(view)
companion object {
/**
* Default shape to use everywhere, null if none set
*/
private var innerShape: Shape? = null
var shape: Shape
get() = innerShape ?: Shape()
set(value) {
innerShape = value
}
/**
* Binds the default [Shape] to the given layout and returns the corresponding [Morf].
* This will use either the [Shape] set by the user, or a [Shape] with default values.
*/
fun bind(container: LinearLayout): Morf = Morf(shape, container)
inline fun createAndSetShape(block: Shape.() -> Unit) {
shape = createShape(block)
}
inline fun createShape(block: Shape.() -> Unit): Shape =
Shape().apply(block)
}
/**
* Contains all of the customizable settings for a [Morf] instance
*/
class Shape {
/* Space */
/**
* Background resource for a space, defaults to transparent
*/
@ColorRes
@DrawableRes
var spaceBackgroundId: Int = android.R.color.transparent
/**
* Resolved color for a space, defaults to null (in order to use spaceBackgroundId)
* Note: this takes precedence over spaceBackgroundId if set
*/
@ColorInt
var spaceColor: Int? = null
/**
* Height (in dp) of a space, defaults to 8
*/
var spaceDpHeight: Float = 8f
/**
* Height (in pixels) of a space, defaults to null
* Note: this takes precedence over spaceDpHeight if set
*/
var spacePixelHeight: Int? = null
/**
* Height from a dimension Id of a space, defaults to null
* Note: this takes precedence over spaceDpHeight and spacePixelHeight if set
*/
@DimenRes
var spaceHeightId: Int? = null
/* Line */
/**
* Height (in dp) of a line, defaults to 0.5
*/
var lineDpHeight: Float = 0.5f
/**
* Height (in pixels) of a line, defaults to null
* Note: this takes precedence over lineDpHeight if set
*/
var linePixelHeight: Int? = null
/**
* Height from a dimension Id of a line, defaults to null
* Note: this takes precedence over lineDpHeight and linePixelHeight if set
*/
@DimenRes
var lineHeightId: Int? = null
/**
* Resolved color for a line, defaults to #EEEEEE
*/
@ColorInt
var lineColor: Int = Color.parseColor("#EEEEEE")
/**
* Id of the background resource for a line, defaults to null
* Note: this takes precedence over lineColor if set
*/
@ColorRes
@DrawableRes
var lineBackgroundId: Int? = null
/**
* True if we should show a line after a form item, false otherwise (defaults to true)
*/
var isLineShown: Boolean = true
/* Text */
/**
* Id of the size of the text, defaults to null (which is the app's default)
*/
@DimenRes
var textSizeId: Int? = null
/**
* Color of the text, defaults to black
*/
@ColorInt
var textColor: Int = Color.BLACK
/**
* Typeface to use for the text, null if none (defaults to null)
*/
var textTypeface: Typeface? = null
/* Padding */
/**
* Padding size in pixels for non-space/line items,
* defaults to null (which is the app's default)
*/
var pixelPadding: Int? = null
/**
* Padding size in DP for non-space/line items, defaults to null.
* Note: This takes precedence over pixelPadding
*/
var dpPadding: Float? = null
/**
* Dimension Id for a padding size for non-space/line items, defaults to null
* Note: This takes precedence over pixelPadding and dpPadding
*/
var paddingId: Int? = null
/**
* Padding size in pixels between a view and its compound drawable, defaults to null
* (which is the app's default)
*/
var drawablePixelPadding: Int? = null
/**
* Padding size in DP between a view and its compound drawable, defaults to null.
* Note: This takes precedence over drawablePixelPadding
*/
var drawableDpPadding: Float? = null
/**
* Dimension Id for a padding size between a view and its compound drawable, defaults to
* null
* Note: This takes precedence over drawablePaddingId
*/
var drawablePaddingId: Int? = null
/* Resources */
/**
* Color to tint the icons, null if none (defaults to null)
*/
@ColorInt
var iconColor: Int? = null
/**
* Id of the background to use, null if none (defaults to null)
*/
@ColorRes
@DrawableRes
var backgroundId: Int? = null
/**
* Id of the background to use for input items, null if none (defaults to null)
*/
@ColorRes
@DrawableRes
var inputBackgroundId: Int? = null
/**
* @return New [Shape] instance, generated from the current one
*/
fun newShape(): Shape {
val settings = Shape()
settings.spaceBackgroundId = spaceBackgroundId
settings.spaceColor = spaceColor
settings.spaceDpHeight = spaceDpHeight
settings.spacePixelHeight = spacePixelHeight
settings.spaceHeightId = spaceHeightId
settings.lineDpHeight = lineDpHeight
settings.linePixelHeight = linePixelHeight
settings.lineHeightId = lineHeightId
settings.lineColor = lineColor
settings.lineBackgroundId = lineBackgroundId
settings.isLineShown = isLineShown
settings.textSizeId = textSizeId
settings.textColor = textColor
settings.textTypeface = textTypeface
settings.pixelPadding = pixelPadding
settings.dpPadding = dpPadding
settings.paddingId = paddingId
settings.drawablePixelPadding = drawablePixelPadding
settings.drawableDpPadding = drawableDpPadding
settings.drawablePaddingId = drawablePaddingId
settings.iconColor = iconColor
settings.backgroundId = backgroundId
settings.inputBackgroundId = inputBackgroundId
return settings
}
/**
* @return New [Shape] instance, generated from the current one and the block
*/
inline fun newShape(block: Shape.() -> Unit): Shape = newShape().apply(block)
/**
* @return [Morf] created from binding this [Shape] to the given [container]
*/
fun bind(container: LinearLayout): Morf = Morf(this, container)
}
}
| apache-2.0 | ddd0cc8f013bf051cb3ddd2a19a8b3ca | 30.531343 | 96 | 0.593771 | 4.709318 | false | false | false | false |
GLodi/GitNav | app/src/main/java/giuliolodi/gitnav/ui/stargazerlist/StargazerListPresenter.kt | 1 | 4351 | /*
* Copyright 2017 GLodi
*
* 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 giuliolodi.gitnav.ui.stargazerlist
import giuliolodi.gitnav.data.DataManager
import giuliolodi.gitnav.ui.base.BasePresenter
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.CompositeDisposable
import io.reactivex.schedulers.Schedulers
import org.eclipse.egit.github.core.User
import timber.log.Timber
import javax.inject.Inject
/**
* Created by giulio on 25/08/2017.
*/
class StargazerListPresenter<V: StargazerListContract.View> : BasePresenter<V>, StargazerListContract.Presenter<V> {
private val TAG = "StargazerListPresenter"
private var mStargazerList: MutableList<User> = mutableListOf()
private var mRepoOwner: String? = null
private var mRepoName: String? = null
private var PAGE_N: Int = 1
private var ITEMS_PER_PAGE: Int = 20
private var LOADING: Boolean = false
private var LOADING_LIST: Boolean = false
private var NO_SHOWING: Boolean = false
@Inject
constructor(mCompositeDisposable: CompositeDisposable, mDataManager: DataManager) : super(mCompositeDisposable, mDataManager)
override fun subscribe(isNetworkAvailable: Boolean, repoOwner: String?, repoName: String?) {
mRepoOwner = repoOwner
mRepoName = repoName
if (!mStargazerList.isEmpty()) getView().showStargazerList(mStargazerList)
else if (NO_SHOWING) getView().showNoStargazers()
else if (LOADING) getView().showLoading()
else {
if (isNetworkAvailable) {
LOADING = true
getView().showLoading()
if (mRepoOwner != null && mRepoName != null) loadStargazerList()
}
else {
getView().showNoConnectionError()
getView().hideLoading()
LOADING = false
}
}
}
private fun loadStargazerList() {
getCompositeDisposable().add(getDataManager().pageStargazers(mRepoOwner!!, mRepoName!!, PAGE_N, ITEMS_PER_PAGE)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(
{ stargazerList ->
getView().hideLoading()
getView().hideListLoading()
mStargazerList.addAll(stargazerList)
getView().showStargazerList(stargazerList)
if (PAGE_N == 1 && stargazerList.isEmpty()) {
getView().showNoStargazers()
NO_SHOWING = true
}
PAGE_N += 1
LOADING = false
LOADING_LIST = false
},
{ throwable ->
throwable?.localizedMessage?.let { getView().showError(it) }
getView().hideLoading()
getView().hideListLoading()
Timber.e(throwable)
LOADING = false
LOADING_LIST = false
}
))
}
override fun onLastItemVisible(isNetworkAvailable: Boolean, dy: Int) {
if (LOADING_LIST)
return
else if (isNetworkAvailable) {
LOADING_LIST = true
getView().showListLoading()
if (mRepoOwner != null && mRepoName != null) loadStargazerList()
}
else if (dy > 0) {
getView().showNoConnectionError()
getView().hideLoading()
}
}
override fun onUserClick(username: String) {
getView().intentToUserActivity(username)
}
} | apache-2.0 | e797b65b1b406ac9433cb540b068b7e0 | 37.175439 | 129 | 0.584234 | 5.088889 | false | false | false | false |
jiaminglu/kotlin-native | backend.native/tests/datagen/literals/strdedup1.kt | 1 | 134 | fun main(args : Array<String>) {
val str1 = "Hello"
val str2 = "Hello"
println(str1 == str2)
println(str1 === str2)
}
| apache-2.0 | c70d5c84090e7ea259b78bcbb46e4a52 | 21.333333 | 32 | 0.567164 | 2.851064 | false | false | false | false |
Bios-Marcel/ServerBrowser | src/main/kotlin/com/msc/serverbrowser/gui/controllers/implementations/VersionChangeController.kt | 1 | 7983 | package com.msc.serverbrowser.gui.controllers.implementations
import com.msc.serverbrowser.Client
import com.msc.serverbrowser.data.insallationcandidates.InstallationCandidate
import com.msc.serverbrowser.data.insallationcandidates.Installer
import com.msc.serverbrowser.gui.View
import com.msc.serverbrowser.gui.controllers.interfaces.ViewController
import com.msc.serverbrowser.util.samp.GTAController
import javafx.application.Platform
import javafx.collections.FXCollections
import javafx.collections.ObservableList
import javafx.fxml.FXML
import javafx.scene.control.Button
import javafx.scene.control.Label
import javafx.scene.control.Separator
import javafx.scene.layout.HBox
import javafx.scene.layout.Priority
import javafx.scene.layout.VBox
import java.text.MessageFormat
import java.util.HashMap
import java.util.Optional
/**
* @since 02.07.2017
*/
class VersionChangeController(val client: Client) : ViewController {
private val installText = Client.getString("install")
private val installedText = Client.getString("installed")
private val installingText = Client.getString("installing")
private val sampVersion = Client.getString("sampVersion")
private val buttons = HashMap<InstallationCandidate, Button>()
@FXML
private lateinit var buttonContainer: VBox
override fun initialize() {
createAndSetupButtons()
updateButtonStates()
}
/**
* Will create a [HBox] for every [InstallationCandidate], said [HBox] will
* contain a [Label] and a [Button].
*/
private fun createAndSetupButtons() {
for (candidate in INSTALLATION_CANDIDATES) {
val versionContainer = HBox()
if (!buttonContainer.children.isEmpty()) {
buttonContainer.children.add(Separator())
}
versionContainer.styleClass.add("installEntry")
val title = Label(MessageFormat.format(sampVersion, candidate.name))
title.styleClass.add("installLabel")
title.maxWidth = java.lang.Double.MAX_VALUE
val installButton = Button(installText)
installButton.setOnAction { installSamp(installButton, candidate) }
installButton.styleClass.add("installButton")
buttons[candidate] = installButton
versionContainer.children.add(title)
versionContainer.children.add(installButton)
buttonContainer.children.add(versionContainer)
HBox.setHgrow(title, Priority.ALWAYS)
}
}
/**
*
*
* Triggers the installation of the chosen [InstallationCandidate].
*
*
* @param button the [Button] which was clicked.
* @param toInstall [InstallationCandidate] which will be installed
*/
private fun installSamp(button: Button, toInstall: InstallationCandidate) {
if (GTAController.gtaPath != null) {
val installedVersion = GTAController.installedVersion
if (!installedVersion.isPresent || installedVersion.get() != toInstall) {
setAllButtonsDisabled(true)
button.text = installingText
GTAController.killGTA()
GTAController.killSAMP()
//Installing in a thread in order to keep the app responsive.
Thread {
Installer.installViaInstallationCandidate(toInstall)
finishInstalling()
}.start()
}
} else {
client.selectSampPathTextField()
}
}
/**
* Decides which buttons will be enabled and what text every button will have, depending on if
* an installation is going on and what is currently installed.
*/
private fun updateButtonStates() {
val installedVersion = GTAController.installedVersion
val ongoingInstallation = currentlyInstalling.isPresent
for ((buttonVersion, button) in buttons) {
if (installedVersion.isPresent && installedVersion.get() === buttonVersion) {
button.text = installedText
button.isDisable = true
} else if (ongoingInstallation && buttonVersion === currentlyInstalling.get()) {
button.text = installingText
button.isDisable = true
} else {
button.text = installText
button.isDisable = ongoingInstallation
}
}
}
private fun setAllButtonsDisabled(disabled: Boolean) {
buttons.forEach { _, value -> value.isDisable = disabled }
}
override fun onClose() {
// Do nothing
}
private fun finishInstalling() {
currentlyInstalling = Optional.empty()
Platform.runLater { client.reloadViewIfLoaded(View.VERSION_CHANGER) }
}
companion object {
private var currentlyInstalling = Optional.empty<InstallationCandidate>()
/**
* Contains all available Installation candidates
*/
val INSTALLATION_CANDIDATES: ObservableList<InstallationCandidate> = FXCollections.observableArrayList<InstallationCandidate>()
//Adding all usable InstallationCandidates
//TODO but this could probably be made in a more desirable way
init {
INSTALLATION_CANDIDATES
.add(InstallationCandidate("BCCDB297464BD382625635BE25585DF07A8FA6668BC0015650708E3EB4FFCD4B", "0.3.DL R1", "http://forum.sa-mp.com/files/03DL/sa-mp-0.3.DL-R1-install.exe", false, true, "FDDBEF743914D6A4A8D9B9895F219864BBB238A447BF36B8A8D652E303D78ACB"))
INSTALLATION_CANDIDATES
.add(InstallationCandidate("65ACB8C9CB0D6723BB9D151BA182A02EC6F7766E2225E66EB51FF1CA95454B43", "0.3.8-RC4-4", "http://forum.sa-mp.com/files/038RC/sa-mp-0.3.8-RC4-4-install.exe", false, true, "69D590121ACA9CB04E71355405B9DC2CEBA681AD940AA43AC1F274129918ABB5"))
INSTALLATION_CANDIDATES
.add(InstallationCandidate("DE07A850590A43D83A40F9251741C07D3D0D74A217D5A09CB498A32982E8315B", "0.3.7 R2", "http://files.sa-mp.com/sa-mp-0.3.7-R2-install.exe", false, true, "8F37CC4E7B4E1201C52B981E4DDF70D30937E5AD1F699EC6FC43ED006FE9FD58"))
INSTALLATION_CANDIDATES
.add(InstallationCandidate("0382C4468E00BEDFE0188EA819BF333A332A4F0D36E6FC07B11B79F4B6D93E6A", "0.3z R2", "http://files.sa-mp.com/sa-mp-0.3z-R2-install.exe", false, true, "2DD1BEB2FB1630A44CE5C47B80685E984D3166F8D93EE5F98E35CC072541919E"))
INSTALLATION_CANDIDATES
.add(InstallationCandidate("23B630CC5C922EE4AA4EF9E93ED5F7F3F9137ACA32D5BCAD6A0C0728D4A17CC6", "0.3x R2", "http://files.sa-mp.com/sa-mp-0.3x-R2-install.exe", false, true, "F75929EC22DF9492219D226C2BDFCDDB5C4351AE71F4B36589B337B10F4656CD"))
INSTALLATION_CANDIDATES
.add(InstallationCandidate("54E1494661962302C8166B1B747D8ED86C69F26FA3E0C5456C129F998883B410", "0.3e", "http://files.sa-mp.com/sa-mp-0.3e-install.exe", false, true, "83C4145E36DF63AF40877969C2D9F97A4B9AF780DB4EF7C0E82861780BF59D5C"))
INSTALLATION_CANDIDATES
.add(InstallationCandidate("D97D6D4750512653B157EDEBC7D5960A4FD7B1E55E04A9ACD86687900A9804BC", "0.3d R2", "http://files.sa-mp.com/sa-mp-0.3d-R2-install.exe", false, true, "FFE1B66DAB76FF300C8563451106B130054E01671CEFDEBE709AD8DC0D3A319A"))
INSTALLATION_CANDIDATES
.add(InstallationCandidate("6A584102E655202871D2158B2659C5B5581AB48ECFB21D330861484AE0CB3043", "0.3c R3", "http://files.sa-mp.com/sa-mp-0.3c-R3-install.exe", false, true, "8CCD7A22B3BF24F00EC32F55AE28CA8F50C48B03504C98BD4FAC3EF661163B4C"))
INSTALLATION_CANDIDATES
.add(InstallationCandidate("23901473FB98F9781B68913F907F3B7A88D9D96BBF686CC65AD1505E400BE942", "0.3a", "http://files.sa-mp.com/sa-mp-0.3a-install.exe", false, true, "690FFF2E9433FF36788BF4F4EA9D8C601EB42471FD1210FE1E0CFFC4F54D7D9D"))
}
}
} | mpl-2.0 | 944d05a91e36451874fdf05c206f0be1 | 45.690058 | 279 | 0.69435 | 3.52606 | false | false | false | false |
Heiner1/AndroidAPS | automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerLocation.kt | 1 | 5249 | package info.nightscout.androidaps.plugins.general.automation.triggers
import android.location.Location
import android.widget.LinearLayout
import com.google.common.base.Optional
import dagger.android.HasAndroidInjector
import info.nightscout.androidaps.automation.R
import info.nightscout.shared.logging.LTag
import info.nightscout.androidaps.plugins.general.automation.elements.*
import info.nightscout.androidaps.utils.JsonHelper
import org.json.JSONObject
import java.text.DecimalFormat
class TriggerLocation(injector: HasAndroidInjector) : Trigger(injector) {
var latitude = InputDouble(0.0, -90.0, +90.0, 0.000001, DecimalFormat("0.000000"))
var longitude = InputDouble(0.0, -180.0, +180.0, 0.000001, DecimalFormat("0.000000"))
var distance = InputDouble(200.0, 0.0, 100000.0, 10.0, DecimalFormat("0"))
var modeSelected = InputLocationMode(rh)
var name: InputString = InputString()
var lastMode = InputLocationMode.Mode.INSIDE
private val buttonAction = Runnable {
locationDataContainer.lastLocation?.let {
latitude.setValue(it.latitude)
longitude.setValue(it.longitude)
aapsLogger.debug(LTag.AUTOMATION, String.format("Grabbed location: %f %f", latitude.value, longitude.value))
}
}
private constructor(injector: HasAndroidInjector, triggerLocation: TriggerLocation) : this(injector) {
latitude = InputDouble(triggerLocation.latitude)
longitude = InputDouble(triggerLocation.longitude)
distance = InputDouble(triggerLocation.distance)
modeSelected = InputLocationMode(rh, triggerLocation.modeSelected.value)
if (modeSelected.value == InputLocationMode.Mode.GOING_OUT)
lastMode = InputLocationMode.Mode.OUTSIDE
name = triggerLocation.name
}
@Synchronized override fun shouldRun(): Boolean {
val location: Location = locationDataContainer.lastLocation ?: return false
val a = Location("Trigger")
a.latitude = latitude.value
a.longitude = longitude.value
val calculatedDistance = location.distanceTo(a).toDouble()
if (modeSelected.value == InputLocationMode.Mode.INSIDE && calculatedDistance <= distance.value ||
modeSelected.value == InputLocationMode.Mode.OUTSIDE && calculatedDistance > distance.value ||
modeSelected.value == InputLocationMode.Mode.GOING_IN && calculatedDistance <= distance.value && lastMode == InputLocationMode.Mode.OUTSIDE ||
modeSelected.value == InputLocationMode.Mode.GOING_OUT && calculatedDistance > distance.value && lastMode == InputLocationMode.Mode.INSIDE) {
aapsLogger.debug(LTag.AUTOMATION, "Ready for execution: " + friendlyDescription())
lastMode = currentMode(calculatedDistance)
return true
}
lastMode = currentMode(calculatedDistance) // current mode will be last mode for the next check
aapsLogger.debug(LTag.AUTOMATION, "NOT ready for execution: " + friendlyDescription())
return false
}
override fun dataJSON(): JSONObject =
JSONObject()
.put("latitude", latitude.value)
.put("longitude", longitude.value)
.put("distance", distance.value)
.put("name", name.value)
.put("mode", modeSelected.value)
override fun fromJSON(data: String): Trigger {
val d = JSONObject(data)
latitude.value = JsonHelper.safeGetDouble(d, "latitude")
longitude.value = JsonHelper.safeGetDouble(d, "longitude")
distance.value = JsonHelper.safeGetDouble(d, "distance")
name.value = JsonHelper.safeGetString(d, "name")!!
modeSelected.value = InputLocationMode.Mode.valueOf(JsonHelper.safeGetString(d, "mode")!!)
if (modeSelected.value == InputLocationMode.Mode.GOING_OUT) lastMode = InputLocationMode.Mode.OUTSIDE
return this
}
override fun friendlyName(): Int = R.string.location
override fun friendlyDescription(): String =
rh.gs(R.string.locationis, rh.gs(modeSelected.value.stringRes), " " + name.value)
override fun icon(): Optional<Int> = Optional.of(R.drawable.ic_location_on)
override fun duplicate(): Trigger = TriggerLocation(injector, this)
override fun generateDialog(root: LinearLayout) {
LayoutBuilder()
.add(StaticLabel(rh, R.string.location, this))
.add(LabelWithElement(rh, rh.gs(R.string.name_short), "", name))
.add(LabelWithElement(rh, rh.gs(R.string.latitude_short), "", latitude))
.add(LabelWithElement(rh, rh.gs(R.string.longitude_short), "", longitude))
.add(LabelWithElement(rh, rh.gs(R.string.distance_short), "", distance))
.add(LabelWithElement(rh, rh.gs(R.string.location_mode), "", modeSelected))
.maybeAdd(InputButton(rh.gs(R.string.currentlocation), buttonAction), locationDataContainer.lastLocation != null)
.build(root)
}
// Method to return the actual mode based on the current distance
fun currentMode(currentDistance: Double): InputLocationMode.Mode {
return if (currentDistance <= distance.value) InputLocationMode.Mode.INSIDE else InputLocationMode.Mode.OUTSIDE
}
} | agpl-3.0 | bb29c92c92724c1854e68bbf4cbc0d26 | 49.480769 | 154 | 0.697466 | 4.381469 | false | false | false | false |
Adventech/sabbath-school-android-2 | features/media/src/main/kotlin/app/ss/media/playback/ui/nowPlaying/components/CoverImage.kt | 1 | 4115 | /*
* Copyright (c) 2021. Adventech <[email protected]>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package app.ss.media.playback.ui.nowPlaying.components
import androidx.compose.animation.core.animateDpAsState
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.runtime.Composable
import androidx.compose.runtime.SideEffect
import androidx.compose.runtime.getValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.DpSize
import androidx.compose.ui.unit.dp
import app.ss.design.compose.extensions.modifier.asPlaceholder
import app.ss.design.compose.theme.Dimens
import app.ss.design.compose.widget.content.ContentBox
import app.ss.design.compose.widget.image.RemoteImage
import app.ss.media.playback.ui.spec.CoverImageSpec
import coil.size.Scale
private interface Sizes {
val width: Dp
val height: Dp
}
private enum class CoverOrientation(val key: String) : Sizes {
SQUARE("square") {
override val width: Dp = 276.dp
override val height: Dp = 276.dp
},
PORTRAIT("portrait") {
override val width: Dp = 187.dp
override val height: Dp = 276.dp
};
companion object {
private val map = values().associateBy(CoverOrientation::key)
fun fromKey(type: String) = map[type]
}
}
@Composable
internal fun CoverImage(
spec: CoverImageSpec,
modifier: Modifier = Modifier,
boxState: BoxState = BoxState.Expanded,
heightCallback: (DpSize) -> Unit
) {
val orientation = CoverOrientation.fromKey(spec.imageRatio) ?: CoverOrientation.PORTRAIT
val collapsed = boxState == BoxState.Collapsed
val width = if (collapsed) orientation.width / 2 else orientation.width
val height = if (collapsed) orientation.height / 2 else orientation.height
val animatedWidth by animateDpAsState(width)
val animatedHeight by animateDpAsState(height)
val scale = when (orientation) {
CoverOrientation.SQUARE -> Scale.FILL
CoverOrientation.PORTRAIT -> Scale.FIT
}
val placeholder: @Composable () -> Unit = {
Spacer(
modifier = Modifier
.fillMaxSize()
.asPlaceholder(visible = true)
)
}
ContentBox(
content = RemoteImage(
data = spec.image,
contentDescription = spec.title,
scale = scale,
loading = placeholder,
error = placeholder
),
modifier = modifier
.size(
width = animatedWidth,
height = animatedHeight
)
.padding(Dimens.grid_1)
.clip(RoundedCornerShape(CoverCornerRadius))
)
SideEffect {
heightCallback(DpSize(animatedWidth, animatedHeight))
}
}
private val CoverCornerRadius = 6.dp
| mit | d9fa5277580543c209e7286b0e8e3298 | 34.474138 | 92 | 0.7113 | 4.396368 | false | false | false | false |
KeenenCharles/AndroidUnplash | androidunsplash/src/main/java/com/keenencharles/unsplash/Unsplash.kt | 1 | 3989 | package com.keenencharles.unsplash
import android.content.Context
import android.net.Uri
import androidx.browser.customtabs.CustomTabsIntent
import com.keenencharles.unsplash.api.*
import com.keenencharles.unsplash.api.endpoints.*
import com.keenencharles.unsplash.models.Token
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
@JvmSuppressWildcards
class Unsplash(private var clientID: String, private var token: String? = null) {
lateinit var photos: PhotoAPI
lateinit var collections: CollectionAPI
lateinit var users: UserAPI
lateinit var stats: StatsAPI
private lateinit var authApiService: AuthEndpointInterface
private val TAG = "AndroidUnsplash"
init {
createServices(clientID, token)
}
private fun createServices(clientId: String, token: String?) {
val retrofit = createRetrofitClient(clientId, token)
val handler = UnsplashResponseHandler()
photos = PhotoAPI(retrofit.create(PhotosEndpointInterface::class.java), handler)
collections =
CollectionAPI(retrofit.create(CollectionsEndpointInterface::class.java), handler)
users = UserAPI(retrofit.create(UserEndpointInterface::class.java), handler)
stats = StatsAPI(retrofit.create(StatsEndpointInterface::class.java), handler)
authApiService = retrofit.create(AuthEndpointInterface::class.java)
}
fun authorize(
context: Context,
redirectURI: String,
scopeList: List<Scope>
) {
var scopes = StringBuilder()
for (scope in scopeList) {
scopes.append(scope.scope).append("+")
}
scopes = scopes.deleteCharAt(scopes.length - 1)
val url =
"https://unsplash.com/oauth/authorize?client_id=$clientID&redirect_uri=$redirectURI&response_type=code&scope=$scopes"
val builder = CustomTabsIntent.Builder()
val customTabsIntent = builder.build()
customTabsIntent.launchUrl(context, Uri.parse(url))
}
fun getToken(
clientSecret: String,
redirectURI: String,
code: String,
onComplete: (Token) -> Unit,
onError: (String) -> Unit
) {
val call = authApiService.getToken(
"https://unsplash.com/oauth/token",
clientID,
clientSecret,
redirectURI,
code,
"authorization_code"
)
call.enqueue(UnsplashCallback(onComplete, onError))
}
suspend fun getToken(
clientSecret: String,
redirectURI: String,
code: String
): UnsplashResource<Token> {
val responseHandler = UnsplashResponseHandler()
return try {
val res = authApiService.getTokenSuspend(
"https://unsplash.com/oauth/token",
clientID,
clientSecret,
redirectURI,
code,
"authorization_code"
)
responseHandler.handleSuccess(res)
} catch (e: Exception) {
responseHandler.handleException(e)
}
}
fun setToken(token: String) {
this.token = token
createServices(clientID, token)
}
private fun createRetrofitClient(clientID: String, token: String?): Retrofit {
val builder = Retrofit.Builder()
val headerInterceptor = HeaderInterceptor(clientID, token)
val client = OkHttpClient.Builder()
.addInterceptor(headerInterceptor)
if (BuildConfig.DEBUG) {
val logging = HttpLoggingInterceptor()
logging.level = HttpLoggingInterceptor.Level.BODY
client.addInterceptor(logging)
}
return builder
.baseUrl("https://api.unsplash.com/")
.addConverterFactory(GsonConverterFactory.create())
.client(client.build())
.build()
}
}
| mit | 90a11a108a6d8606e59118e6bdbe7ede | 30.409449 | 129 | 0.64377 | 4.88848 | false | false | false | false |
Maccimo/intellij-community | platform/platform-impl/src/com/intellij/openapi/editor/toolbar/floating/TransparentComponentAnimator.kt | 2 | 4606 | // Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.openapi.editor.toolbar.floating
import com.intellij.openapi.Disposable
import com.intellij.openapi.observable.util.whenDisposed
import com.intellij.openapi.ui.isComponentUnderMouse
import com.intellij.util.ui.TimerUtil
import com.intellij.util.ui.UIUtil.invokeLaterIfNeeded
import org.jetbrains.annotations.ApiStatus
import java.util.concurrent.atomic.AtomicBoolean
import java.util.concurrent.atomic.AtomicReference
@Suppress("SameParameterValue")
@ApiStatus.Internal
class TransparentComponentAnimator(
private val component: TransparentComponent,
parentDisposable: Disposable
) {
private val isDisposed = AtomicBoolean()
private val executor = ExecutorWithThrottling(THROTTLING_DELAY)
private val clk = TimerUtil.createNamedTimer("CLK", CLK_DELAY)
private val state = AtomicReference<State>(State.Invisible)
private fun startTimerIfNeeded() {
if (!isDisposed.get() && !clk.isRunning) {
clk.start()
}
}
private fun stopTimerIfNeeded() {
if (clk.isRunning) {
clk.stop()
}
}
fun scheduleShow() = executor.executeOrSkip {
state.updateAndGet(::nextShowingState)
startTimerIfNeeded()
}
fun scheduleHide() {
state.updateAndGet(::nextHidingState)
startTimerIfNeeded()
}
private fun updateState() {
val state = state.updateAndGet(::nextState)
if (state is State.Invisible ||
state is State.Visible && !component.autoHideable) {
stopTimerIfNeeded()
}
updateComponent(state)
}
private fun updateComponent(state: State) {
invokeLaterIfNeeded {
component.opacity = getOpacity(state)
when (isVisible(state)) {
true -> component.showComponent()
else -> component.hideComponent()
}
component.component.repaint()
}
}
private fun nextShowingState(state: State): State {
return when (state) {
is State.Invisible -> State.Showing(0)
is State.Visible -> State.Visible(0)
is State.Hiding -> State.Showing(SHOWING_COUNT - SHOWING_COUNT * state.count / HIDING_COUNT)
is State.Showing -> state
}
}
private fun nextHidingState(state: State): State {
return when (state) {
is State.Invisible -> State.Invisible
is State.Visible -> State.Hiding(0)
is State.Hiding -> state
is State.Showing -> State.Hiding(HIDING_COUNT - HIDING_COUNT * state.count / SHOWING_COUNT)
}
}
private fun nextState(state: State): State {
return when (state) {
is State.Invisible -> State.Invisible
is State.Visible -> when {
!component.autoHideable -> State.Visible(0)
component.isComponentUnderMouse() -> State.Visible(0)
state.count >= RETENTION_COUNT -> State.Hiding(0)
else -> State.Visible(state.count + 1)
}
is State.Hiding -> when {
state.count >= HIDING_COUNT -> State.Invisible
else -> State.Hiding(state.count + 1)
}
is State.Showing -> when {
state.count >= SHOWING_COUNT -> State.Visible(0)
else -> State.Showing(state.count + 1)
}
}
}
private fun TransparentComponent.isComponentUnderMouse(): Boolean {
return component.parent?.isComponentUnderMouse() == true
}
private fun getOpacity(state: State): Float {
return when (state) {
is State.Invisible -> 0.0f
is State.Visible -> 1.0f
is State.Hiding -> 1.0f - getOpacity(state.count, HIDING_COUNT)
is State.Showing -> getOpacity(state.count, SHOWING_COUNT)
}
}
private fun getOpacity(count: Int, maxCount: Int): Float {
return maxOf(0.0f, minOf(1.0f, count / maxCount.toFloat()))
}
private fun isVisible(state: State): Boolean {
return state !is State.Invisible
}
init {
clk.isRepeats = true
clk.addActionListener { updateState() }
parentDisposable.whenDisposed { isDisposed.set(true) }
parentDisposable.whenDisposed { stopTimerIfNeeded() }
}
private sealed interface State {
object Invisible : State
data class Visible(val count: Int) : State
data class Hiding(val count: Int) : State
data class Showing(val count: Int) : State
}
companion object {
private const val CLK_FREQUENCY = 60
private const val CLK_DELAY = 1000 / CLK_FREQUENCY
private const val RETENTION_COUNT = 1500 / CLK_DELAY
private const val SHOWING_COUNT = 500 / CLK_DELAY
private const val HIDING_COUNT = 1000 / CLK_DELAY
private const val THROTTLING_DELAY = 1000
}
} | apache-2.0 | db5677084e0c3b8ff50e63d422e49c99 | 29.919463 | 140 | 0.685845 | 4.047452 | false | false | false | false |
K0zka/finder4j | finder4j-backtrack-examples/src/main/kotlin/com/github/k0zka/finder4j/backtrack/examples/sudoku/SudokuState.kt | 1 | 949 | package com.github.k0zka.finder4j.backtrack.examples.sudoku
import com.github.k0zka.finder4j.backtrack.State
class SudokuState(internal val sudoku: Array<ShortArray>) : State {
override val complete: Boolean
get() {
for (row in sudoku) {
for (num in row) {
if (num == notSet) {
return false
}
}
}
return true
}
init {
if (sudoku.size != sudokuRowSize.toInt() && sudoku[0].size != sudokuRowSize.toInt()) {
throw IllegalArgumentException("Requires " + sudokuRowSize
+ " * " + sudokuRowSize + " array")
}
}
override fun toString(): String {
val str = StringBuilder()
for (row in sudoku) {
for (num in row) {
str.append(num)
str.append(' ')
}
str.append('\n')
}
return str.toString()
}
companion object {
val notSet = (-1).toShort()
internal val sudokuGridSize: Short = 3
internal val sudokuRowSize = (sudokuGridSize * sudokuGridSize).toShort()
}
}
| apache-2.0 | ae124b823b7fa664f7268dbbc3200086 | 20.568182 | 88 | 0.635406 | 3.184564 | false | false | false | false |
android/nowinandroid | feature/topic/src/main/java/com/google/samples/apps/nowinandroid/feature/topic/TopicScreen.kt | 1 | 9938 | /*
* 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
*
* 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.samples.apps.nowinandroid.feature.topic
import androidx.annotation.VisibleForTesting
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.WindowInsets
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.safeDrawing
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.windowInsetsBottomHeight
import androidx.compose.foundation.layout.windowInsetsTopHeight
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.LazyListScope
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.ColorFilter
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.lifecycle.compose.ExperimentalLifecycleComposeApi
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import coil.compose.AsyncImage
import com.google.samples.apps.nowinandroid.core.designsystem.component.NiaBackground
import com.google.samples.apps.nowinandroid.core.designsystem.component.NiaFilterChip
import com.google.samples.apps.nowinandroid.core.designsystem.component.NiaLoadingWheel
import com.google.samples.apps.nowinandroid.core.designsystem.icon.NiaIcons
import com.google.samples.apps.nowinandroid.core.designsystem.theme.NiaTheme
import com.google.samples.apps.nowinandroid.core.domain.model.FollowableTopic
import com.google.samples.apps.nowinandroid.core.domain.model.SaveableNewsResource
import com.google.samples.apps.nowinandroid.core.model.data.previewNewsResources
import com.google.samples.apps.nowinandroid.core.model.data.previewTopics
import com.google.samples.apps.nowinandroid.core.ui.DevicePreviews
import com.google.samples.apps.nowinandroid.core.ui.TrackScrollJank
import com.google.samples.apps.nowinandroid.core.ui.newsResourceCardItems
import com.google.samples.apps.nowinandroid.feature.topic.R.string
import com.google.samples.apps.nowinandroid.feature.topic.TopicUiState.Loading
@OptIn(ExperimentalLifecycleComposeApi::class)
@Composable
internal fun TopicRoute(
onBackClick: () -> Unit,
modifier: Modifier = Modifier,
viewModel: TopicViewModel = hiltViewModel(),
) {
val topicUiState: TopicUiState by viewModel.topicUiState.collectAsStateWithLifecycle()
val newsUiState: NewsUiState by viewModel.newUiState.collectAsStateWithLifecycle()
TopicScreen(
topicUiState = topicUiState,
newsUiState = newsUiState,
modifier = modifier,
onBackClick = onBackClick,
onFollowClick = viewModel::followTopicToggle,
onBookmarkChanged = viewModel::bookmarkNews,
)
}
@VisibleForTesting
@Composable
internal fun TopicScreen(
topicUiState: TopicUiState,
newsUiState: NewsUiState,
onBackClick: () -> Unit,
onFollowClick: (Boolean) -> Unit,
onBookmarkChanged: (String, Boolean) -> Unit,
modifier: Modifier = Modifier,
) {
val state = rememberLazyListState()
TrackScrollJank(scrollableState = state, stateName = "topic:screen")
LazyColumn(
state = state,
modifier = modifier,
horizontalAlignment = Alignment.CenterHorizontally
) {
item {
Spacer(Modifier.windowInsetsTopHeight(WindowInsets.safeDrawing))
}
when (topicUiState) {
Loading -> item {
NiaLoadingWheel(
modifier = modifier,
contentDesc = stringResource(id = string.topic_loading),
)
}
TopicUiState.Error -> TODO()
is TopicUiState.Success -> {
item {
TopicToolbar(
onBackClick = onBackClick,
onFollowClick = onFollowClick,
uiState = topicUiState.followableTopic,
)
}
TopicBody(
name = topicUiState.followableTopic.topic.name,
description = topicUiState.followableTopic.topic.longDescription,
news = newsUiState,
imageUrl = topicUiState.followableTopic.topic.imageUrl,
onBookmarkChanged = onBookmarkChanged
)
}
}
item {
Spacer(Modifier.windowInsetsBottomHeight(WindowInsets.safeDrawing))
}
}
}
private fun LazyListScope.TopicBody(
name: String,
description: String,
news: NewsUiState,
imageUrl: String,
onBookmarkChanged: (String, Boolean) -> Unit
) {
// TODO: Show icon if available
item {
TopicHeader(name, description, imageUrl)
}
TopicCards(news, onBookmarkChanged)
}
@Composable
private fun TopicHeader(name: String, description: String, imageUrl: String) {
Column(
modifier = Modifier.padding(horizontal = 24.dp)
) {
AsyncImage(
model = imageUrl,
contentDescription = null,
colorFilter = ColorFilter.tint(MaterialTheme.colorScheme.primary),
modifier = Modifier
.align(Alignment.CenterHorizontally)
.size(216.dp)
.padding(bottom = 12.dp)
)
Text(name, style = MaterialTheme.typography.displayMedium)
if (description.isNotEmpty()) {
Text(
description,
modifier = Modifier.padding(top = 24.dp),
style = MaterialTheme.typography.bodyLarge
)
}
}
}
private fun LazyListScope.TopicCards(
news: NewsUiState,
onBookmarkChanged: (String, Boolean) -> Unit
) {
when (news) {
is NewsUiState.Success -> {
newsResourceCardItems(
items = news.news,
newsResourceMapper = { it.newsResource },
isBookmarkedMapper = { it.isSaved },
onToggleBookmark = { onBookmarkChanged(it.newsResource.id, !it.isSaved) },
itemModifier = Modifier.padding(24.dp)
)
}
is NewsUiState.Loading -> item {
NiaLoadingWheel(contentDesc = "Loading news") // TODO
}
else -> item {
Text("Error") // TODO
}
}
}
@Preview
@Composable
private fun TopicBodyPreview() {
NiaTheme {
LazyColumn {
TopicBody(
"Jetpack Compose", "Lorem ipsum maximum",
NewsUiState.Success(emptyList()), "", { _, _ -> }
)
}
}
}
@Composable
private fun TopicToolbar(
uiState: FollowableTopic,
modifier: Modifier = Modifier,
onBackClick: () -> Unit = {},
onFollowClick: (Boolean) -> Unit = {},
) {
Row(
horizontalArrangement = Arrangement.SpaceBetween,
verticalAlignment = Alignment.CenterVertically,
modifier = modifier
.fillMaxWidth()
.padding(bottom = 32.dp)
) {
IconButton(onClick = { onBackClick() }) {
Icon(
imageVector = NiaIcons.ArrowBack,
contentDescription = stringResource(
id = com.google.samples.apps.nowinandroid.core.ui.R.string.back
)
)
}
val selected = uiState.isFollowed
NiaFilterChip(
selected = selected,
onSelectedChange = onFollowClick,
modifier = Modifier.padding(end = 24.dp)
) {
if (selected) {
Text("FOLLOWING")
} else {
Text("NOT FOLLOWING")
}
}
}
}
@DevicePreviews
@Composable
fun TopicScreenPopulated() {
NiaTheme {
NiaBackground {
TopicScreen(
topicUiState = TopicUiState.Success(FollowableTopic(previewTopics[0], false)),
newsUiState = NewsUiState.Success(
previewNewsResources.mapIndexed { index, newsResource ->
SaveableNewsResource(
newsResource = newsResource,
isSaved = index % 2 == 0,
)
}
),
onBackClick = {},
onFollowClick = {},
onBookmarkChanged = { _, _ -> },
)
}
}
}
@DevicePreviews
@Composable
fun TopicScreenLoading() {
NiaTheme {
NiaBackground {
TopicScreen(
topicUiState = TopicUiState.Loading,
newsUiState = NewsUiState.Loading,
onBackClick = {},
onFollowClick = {},
onBookmarkChanged = { _, _ -> },
)
}
}
}
| apache-2.0 | dd4011828e387652bb0fe1ec76548a5c | 33.387543 | 94 | 0.646106 | 4.876349 | false | false | false | false |
failex234/FastHub | app/src/main/java/com/fastaccess/ui/modules/search/SearchUserActivity.kt | 1 | 3655 | package com.fastaccess.ui.modules.search
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.text.Editable
import android.view.View
import android.widget.CheckBox
import butterknife.BindView
import butterknife.OnClick
import butterknife.OnEditorAction
import butterknife.OnTextChanged
import com.evernote.android.state.State
import com.fastaccess.R
import com.fastaccess.helper.AnimHelper
import com.fastaccess.helper.AppHelper
import com.fastaccess.helper.InputHelper
import com.fastaccess.ui.base.BaseActivity
import com.fastaccess.ui.base.mvp.BaseMvp
import com.fastaccess.ui.base.mvp.presenter.BasePresenter
import com.fastaccess.ui.modules.search.repos.SearchReposFragment
import com.fastaccess.ui.widgets.FontAutoCompleteEditText
class SearchUserActivity : BaseActivity<BaseMvp.FAView, BasePresenter<BaseMvp.FAView>>() {
@BindView(R.id.forkCheckBox) lateinit var forkCheckBox: CheckBox
@BindView(R.id.clear) lateinit var clear: View
@BindView(R.id.searchEditText) lateinit var searchEditText: FontAutoCompleteEditText
@State var username = ""
@State var searchTerm = ""
@OnTextChanged(value = R.id.searchEditText, callback = OnTextChanged.Callback.AFTER_TEXT_CHANGED)
fun onTextChange(str: Editable) {
searchTerm = str.toString()
if (searchTerm.isEmpty()) {
AnimHelper.animateVisibility(clear, false)
} else {
AnimHelper.animateVisibility(clear, true)
}
}
@OnClick(R.id.search) fun onSearchClicked() {
searchTerm = searchEditText.text.toString()
makeSearch()
}
@OnClick(R.id.forkCheckBox) fun checkBoxClicked() {
onSearchClicked()
}
@OnEditorAction(R.id.searchEditText) fun onEditor(): Boolean {
onSearchClicked()
return true
}
@OnClick(R.id.clear) internal fun onClear(view: View) {
if (view.id == R.id.clear) {
searchEditText.setText("")
}
}
override fun layout(): Int = R.layout.activity_search_user
override fun isTransparent(): Boolean = false
override fun canBack(): Boolean = true
override fun providePresenter(): BasePresenter<BaseMvp.FAView> = BasePresenter()
override fun isSecured(): Boolean = false
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
if (savedInstanceState == null) {
val args = intent.extras
username = args.getString(USERNAME)
if (InputHelper.isEmpty(username)) {
finish()
return
}
searchTerm = args.getString(SEARCH_TERM)
supportFragmentManager.beginTransaction()
.replace(R.id.containerFragment, SearchReposFragment.newInstance(), "SearchReposFragment")
.commit()
}
searchEditText.setText(searchTerm)
onSearchClicked()
}
private fun makeSearch() {
val query = "user:$username $searchTerm fork:${forkCheckBox.isChecked}"
getFragment()?.onQueueSearch(query)
}
private fun getFragment() = AppHelper.getFragmentByTag(supportFragmentManager, "SearchReposFragment") as? SearchReposFragment?
companion object {
val USERNAME = "username"
val SEARCH_TERM = "search"
fun getIntent(context: Context, username: String, searchTerm: String?): Intent {
val intent = Intent(context, SearchUserActivity::class.java)
intent.putExtra(USERNAME, username)
intent.putExtra(SEARCH_TERM, searchTerm)
return intent
}
}
}
| gpl-3.0 | 18e506b65c3d9b00ad679e02f8c4ce5d | 32.53211 | 130 | 0.686731 | 4.650127 | false | false | false | false |
siarhei-luskanau/android-iot-doorbell | di/di_singleton/src/main/kotlin/siarhei/luskanau/iot/doorbell/di/DiHolderImpl.kt | 1 | 1338 | package siarhei.luskanau.iot.doorbell.di
import android.app.Application
import android.content.Context
import androidx.fragment.app.FragmentActivity
import androidx.fragment.app.FragmentFactory
import androidx.work.WorkerFactory
import siarhei.luskanau.iot.doorbell.workmanager.DefaultWorkerFactory
class DiHolderImpl(context: Context) : DiHolder {
private val appModules by lazy {
AppModules(context = context)
}
override fun onAppCreate(application: Application) {
appModules.scheduleWorkManagerService.startUptimeNotifications()
appModules.appBackgroundServices.startServices()
}
override fun onAppTrimMemory(application: Application) = Unit
override fun getFragmentFactory(fragmentActivity: FragmentActivity): FragmentFactory =
AppFragmentFactory(
fragmentActivity = fragmentActivity,
appModules = appModules
)
override fun provideWorkerFactory(): WorkerFactory =
DefaultWorkerFactory(
thisDeviceRepository = { appModules.thisDeviceRepository },
doorbellRepository = { appModules.doorbellRepository },
cameraRepository = { appModules.cameraRepository },
uptimeRepository = { appModules.uptimeRepository },
imageRepository = { appModules.imageRepository }
)
}
| mit | 7ed510fce0f12f8e1efb48bc58af53bc | 35.162162 | 90 | 0.734679 | 5.373494 | false | false | false | false |
ACRA/acra | acra-core/src/main/java/org/acra/plugins/ServicePluginLoader.kt | 1 | 2340 | /*
* Copyright (c) 2018
*
* 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.acra.plugins
import org.acra.config.CoreConfiguration
import org.acra.log.debug
import org.acra.log.error
import java.util.*
/**
* Utility to load [Plugin]s
*
* @author F43nd1r
* @since 18.04.18
*/
class ServicePluginLoader : PluginLoader {
override fun <T : Plugin> load(clazz: Class<T>): List<T> = loadInternal(clazz) { true }
override fun <T : Plugin> loadEnabled(config: CoreConfiguration, clazz: Class<T>): List<T> = loadInternal(clazz) { it.enabled(config) }
private fun <T : Plugin> loadInternal(clazz: Class<T>, shouldLoadPredicate: (T) -> Boolean): List<T> {
val plugins: MutableList<T> = ArrayList()
val serviceLoader = ServiceLoader.load(clazz, javaClass.classLoader)
debug { "ServicePluginLoader loading services from ServiceLoader : $serviceLoader" }
val iterator: Iterator<T> = serviceLoader.iterator()
while (true) {
try {
if (!iterator.hasNext()) {
break
}
} catch (e: ServiceConfigurationError) {
error(e) { "Broken ServiceLoader for ${clazz.simpleName}" }
break
}
try {
val plugin = iterator.next()
if (shouldLoadPredicate.invoke(plugin)) {
debug { "Loaded ${clazz.simpleName} of type ${plugin.javaClass.name}" }
plugins.add(plugin)
} else {
debug { "Ignoring disabled ${clazz.simpleName} of type ${plugin.javaClass.simpleName}" }
}
} catch (e: ServiceConfigurationError) {
error(e) { "Unable to load ${clazz.simpleName}" }
}
}
return plugins
}
} | apache-2.0 | 77313d3cd722f7dbf9ba9494310bb021 | 36.758065 | 139 | 0.61453 | 4.309392 | false | true | false | false |
siarhei-luskanau/android-iot-doorbell | ui/ui_common/src/main/kotlin/siarhei/luskanau/iot/doorbell/ui/common/PagingItems.kt | 1 | 1258 | package siarhei.luskanau.iot.doorbell.ui.common
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.wrapContentHeight
import androidx.compose.material.Card
import androidx.compose.material.CircularProgressIndicator
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.unit.dp
@Composable
@Suppress("FunctionNaming")
fun LoadingItem() {
Box(
modifier = Modifier
.fillMaxWidth()
.wrapContentHeight(),
contentAlignment = Alignment.Center
) {
CircularProgressIndicator()
}
}
@Composable
@Suppress("FunctionNaming")
fun ErrorItem(text: String) {
Card(
elevation = 2.dp,
modifier = Modifier
.padding(2.dp)
.fillMaxWidth()
.wrapContentHeight()
) {
Text(
text = text,
color = Color.Red,
style = MaterialTheme.typography.h5
)
}
}
| mit | afb0e8aabc2fcb770b459a7b439a457d | 26.347826 | 59 | 0.704293 | 4.608059 | false | false | false | false |
GunoH/intellij-community | uast/uast-java/src/org/jetbrains/uast/java/declarations/JavaUFile.kt | 8 | 1687 | // 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.uast.java
import com.intellij.psi.PsiComment
import com.intellij.psi.PsiJavaFile
import com.intellij.psi.PsiRecursiveElementWalkingVisitor
import org.jetbrains.annotations.ApiStatus
import org.jetbrains.uast.*
import org.jetbrains.uast.java.internal.JavaUElementWithComments
@ApiStatus.Internal
class JavaUFile(
override val sourcePsi: PsiJavaFile,
override val languagePlugin: UastLanguagePlugin
) : UFile, UElement, JavaUElementWithComments {
override val packageName: String
get() = sourcePsi.packageName
override val imports: List<UImportStatement> by lz {
sourcePsi.importList?.allImportStatements?.map { JavaUImportStatement(it, this) } ?: listOf()
}
override val implicitImports: List<String>
get() = sourcePsi.implicitlyImportedPackages.toList()
override val uAnnotations: List<UAnnotation>
get() = sourcePsi.packageStatement?.annotationList?.annotations?.map { JavaUAnnotation(it, this) } ?: emptyList()
override val classes: List<UClass> by lz { sourcePsi.classes.map { JavaUClass.create(it, this) } }
override val allCommentsInFile: ArrayList<UComment> by lz {
val comments = ArrayList<UComment>(0)
sourcePsi.accept(object : PsiRecursiveElementWalkingVisitor() {
override fun visitComment(comment: PsiComment) {
comments += UComment(comment, this@JavaUFile)
}
})
comments
}
override fun equals(other: Any?): Boolean = (other as? JavaUFile)?.sourcePsi == sourcePsi
@Suppress("OverridingDeprecatedMember")
override val psi
get() = sourcePsi
}
| apache-2.0 | a64076a797de789eeed0582e0ed2bcdd | 34.893617 | 120 | 0.758151 | 4.584239 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/jvm-debugger/test/test/org/jetbrains/kotlin/idea/debugger/test/preference/DebuggerPreferences.kt | 4 | 1903 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.debugger.test.preference
import com.intellij.openapi.project.Project
import org.jetbrains.kotlin.idea.test.InTextDirectivesUtils
class DebuggerPreferences(val project: Project, fileContents: String) {
private val values: Map<String, Any?>
init {
val values = HashMap<String, Any?>()
for (key in DebuggerPreferenceKeys.values) {
val list = findValues(fileContents, key.name).takeIf { it.isNotEmpty() } ?: continue
fun errorValue(): Nothing = error("Error value for key ${key.name}")
val convertedValue: Any = when (key.type) {
java.lang.Boolean::class.java -> list.singleOrNull()?.toBoolean() ?: errorValue()
String::class.java -> list.singleOrNull() ?: errorValue()
java.lang.Integer::class.java -> list.singleOrNull()?.toIntOrNull() ?: errorValue()
List::class.java -> list
else -> error("Cannot find a converter for type ${key.type}")
}
values[key.name] = convertedValue
}
this.values = values
}
private fun findValues(fileContents: String, key: String): List<String> {
val list: List<String> = InTextDirectivesUtils.findLinesWithPrefixesRemoved(fileContents, "// $key: ")
if (list.isNotEmpty()) {
return list
}
if (InTextDirectivesUtils.findLinesWithPrefixesRemoved(fileContents, true, false, "// $key").isNotEmpty()) {
return listOf("true")
}
return emptyList()
}
operator fun <T : Any> get(key: DebuggerPreferenceKey<T>): T {
@Suppress("UNCHECKED_CAST")
return values[key.name] as T? ?: key.defaultValue
}
} | apache-2.0 | 91990741c56f07bd748a1181187fc1de | 39.510638 | 158 | 0.632685 | 4.563549 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/compiler-plugins/noarg/common/src/org/jetbrains/kotlin/idea/compilerPlugin/noarg/NoArgUltraLightClassModifierExtension.kt | 4 | 3161 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.compilerPlugin.noarg
import com.intellij.openapi.project.Project
import org.jetbrains.kotlin.idea.compilerPlugin.CachedAnnotationNames
import org.jetbrains.kotlin.idea.compilerPlugin.getAnnotationNames
import org.jetbrains.kotlin.asJava.UltraLightClassModifierExtension
import org.jetbrains.kotlin.asJava.classes.KtUltraLightClass
import org.jetbrains.kotlin.asJava.classes.createGeneratedMethodFromDescriptor
import org.jetbrains.kotlin.asJava.elements.KtLightMethod
import org.jetbrains.kotlin.descriptors.ClassDescriptor
import org.jetbrains.kotlin.descriptors.DeclarationDescriptor
import org.jetbrains.kotlin.extensions.AnnotationBasedExtension
import org.jetbrains.kotlin.noarg.AbstractNoArgExpressionCodegenExtension
import org.jetbrains.kotlin.noarg.AbstractNoArgExpressionCodegenExtension.Companion.isZeroParameterConstructor
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.util.isAnnotated
import org.jetbrains.kotlin.util.isOrdinaryClass
class NoArgUltraLightClassModifierExtension(project: Project) :
AnnotationBasedExtension,
UltraLightClassModifierExtension {
private val cachedAnnotationsNames = CachedAnnotationNames(project, NO_ARG_ANNOTATION_OPTION_PREFIX)
override fun getAnnotationFqNames(modifierListOwner: KtModifierListOwner?): List<String> =
cachedAnnotationsNames.getAnnotationNames(modifierListOwner)
private fun isSuitableDeclaration(declaration: KtDeclaration): Boolean {
if (getAnnotationFqNames(declaration).isEmpty()) return false
if (!declaration.isOrdinaryClass || declaration !is KtClassOrObject) return false
if (declaration.allConstructors.isEmpty()) return false
if (declaration.allConstructors.any { it.getValueParameters().isEmpty() }) return false
if (declaration.superTypeListEntries.isEmpty() && !declaration.isAnnotated) return false
return true
}
override fun interceptMethodsBuilding(
declaration: KtDeclaration,
descriptor: Lazy<DeclarationDescriptor?>,
containingDeclaration: KtUltraLightClass,
methodsList: MutableList<KtLightMethod>
) {
val parentClass = containingDeclaration as? KtUltraLightClass ?: return
if (methodsList.any { it.isConstructor && it.parameters.isEmpty() }) return
if (!isSuitableDeclaration(declaration)) return
val descriptorValue = descriptor.value ?: return
val classDescriptor = (descriptorValue as? ClassDescriptor)
?: descriptorValue.containingDeclaration as? ClassDescriptor
?: return
if (!classDescriptor.hasSpecialAnnotation(declaration)) return
if (classDescriptor.constructors.any { isZeroParameterConstructor(it) }) return
val constructorDescriptor = AbstractNoArgExpressionCodegenExtension.createNoArgConstructorDescriptor(classDescriptor)
methodsList.add(parentClass.createGeneratedMethodFromDescriptor(constructorDescriptor))
}
} | apache-2.0 | 8f3b6751cb4bb2a2dc3f743fba5061d4 | 44.171429 | 158 | 0.79342 | 5.339527 | false | false | false | false |
GunoH/intellij-community | java/java-impl/src/com/intellij/codeInsight/daemon/impl/JavaInheritorsCodeVisionProvider.kt | 3 | 3155 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.codeInsight.daemon.impl
import com.intellij.codeInsight.codeVision.CodeVisionRelativeOrdering
import com.intellij.codeInsight.hints.codeVision.InheritorsCodeVisionProvider
import com.intellij.java.JavaBundle
import com.intellij.lang.java.JavaLanguage
import com.intellij.openapi.editor.Editor
import com.intellij.pom.java.LanguageLevel
import com.intellij.psi.*
import com.intellij.psi.util.PsiUtil
import java.awt.event.MouseEvent
class JavaInheritorsCodeVisionProvider : InheritorsCodeVisionProvider() {
companion object {
const val ID = "java.inheritors"
}
override fun acceptsFile(file: PsiFile): Boolean = file.language == JavaLanguage.INSTANCE
override fun acceptsElement(element: PsiElement): Boolean =
element is PsiClass && element !is PsiTypeParameter || element is PsiMethod
override fun getHint(element: PsiElement, file: PsiFile): String? {
if (element is PsiClass && element !is PsiTypeParameter) {
val inheritors = JavaTelescope.collectInheritingClasses(element)
if (inheritors > 0) {
val isInterface: Boolean = element.isInterface
return if (isInterface) JavaBundle.message("code.vision.implementations.hint", inheritors)
else JavaBundle.message("code.vision.inheritors.hint", inheritors)
}
}
else if (element is PsiMethod) {
val overrides = JavaTelescope.collectOverridingMethods(element)
if (overrides > 0) {
val isAbstractMethod = isAbstractMethod(element)
return if (isAbstractMethod) JavaBundle.message("code.vision.implementations.hint", overrides)
else JavaBundle.message("code.vision.overrides.hint", overrides)
}
}
return null
}
override fun logClickToFUS(element: PsiElement) {
val location = if (element is PsiClass) JavaCodeVisionUsageCollector.CLASS_LOCATION else JavaCodeVisionUsageCollector.METHOD_LOCATION
JavaCodeVisionUsageCollector.IMPLEMENTATION_CLICKED_EVENT_ID.log(element.project, location)
}
override fun handleClick(editor: Editor, element: PsiElement, event: MouseEvent?) {
val markerType = if (element is PsiClass) MarkerType.SUBCLASSED_CLASS else MarkerType.OVERRIDDEN_METHOD
val navigationHandler = markerType.navigationHandler
if (element is PsiNameIdentifierOwner) {
navigationHandler.navigate(event, element.nameIdentifier)
}
}
override val relativeOrderings: List<CodeVisionRelativeOrdering>
get() = emptyList()
override val id: String
get() = ID
private fun isAbstractMethod(method: PsiMethod): Boolean {
if (method.hasModifierProperty(PsiModifier.ABSTRACT)) {
return true
}
val aClass = method.containingClass
return aClass != null && aClass.isInterface && !isDefaultMethod(aClass, method)
}
private fun isDefaultMethod(aClass: PsiClass, method: PsiMethod): Boolean {
return method.hasModifierProperty(PsiModifier.DEFAULT) &&
PsiUtil.getLanguageLevel(aClass).isAtLeast(LanguageLevel.JDK_1_8)
}
} | apache-2.0 | 8cfdabe357932987452f1268866c0b5c | 41.648649 | 158 | 0.757528 | 4.730135 | false | false | false | false |
jimandreas/BottomNavigationView-plus-LeakCanary | app/src/main/java/com/jimandreas/android/designlibdemo/SettingsActivity.kt | 2 | 3074 | /*
* Copyright (c) 2016 Ha Duy Trung
* Copyright 2017 Jim Andreas
*
* 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.content.Intent
import android.os.Bundle
import android.os.Handler
import android.support.design.widget.BottomNavigationView
import android.support.design.widget.CollapsingToolbarLayout
import android.support.v4.app.Fragment
import android.support.v7.app.AppCompatDelegate
import android.widget.ImageView
import androidx.os.postDelayed
import com.bumptech.glide.Glide
import com.jimandreas.android.base.BottomNavActivity
class SettingsActivity : BottomNavActivity(), SettingsFragment.RestartCallback {
private lateinit var ctl: CollapsingToolbarLayout
private lateinit var bottomNavigationView : BottomNavigationView
private lateinit var backdrop_image: ImageView
override val activityMenuID: Int
get() = R.id.action_settings
override val contentViewId: Int
get() = R.layout.activity_settings
override fun doRestart() {
Handler().postDelayed(200) {
recreate()
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
// setContentView(R.layout.activity_settings);
ctl = findViewById(R.id.collapsing_toolbar)
bottomNavigationView = findViewById(R.id.bottom_navigation)
backdrop_image = findViewById(R.id.backdrop_settings_image)
ctl.title = resources.getString(R.string.text_settings)
loadBackdrop()
if (savedInstanceState == null) {
val args = Bundle()
supportFragmentManager
.beginTransaction()
.add(R.id.settings_container,
Fragment.instantiate(this, SettingsFragment::class.java.name, args),
SettingsFragment::class.java.name)
.commit()
}
}
internal fun setNightMode(@AppCompatDelegate.NightMode nightMode: Int) {
AppCompatDelegate.setDefaultNightMode(nightMode)
}
private fun loadBackdrop() {
// val imageView: ImageView = findViewById(R.id.backdrop_settings_image)
Glide.with(this)
.load(R.drawable.settings_backdrop)
.centerCrop()
.into(backdrop_image)
}
override fun onBackPressed() {
val intent = Intent(this, MainActivityKotlin::class.java)
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
startActivity(intent)
}
} | apache-2.0 | 6bd2f9686ed42a1f3a00ed7aea6d1df8 | 33.166667 | 96 | 0.68933 | 4.765891 | false | false | false | false |
ktorio/ktor | ktor-utils/common/src/io/ktor/util/pipeline/SuspendFunctionGun.kt | 1 | 5326 | /*
* 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.util.pipeline
import io.ktor.util.CoroutineStackFrame
import io.ktor.util.StackTraceElement
import io.ktor.utils.io.*
import kotlinx.coroutines.*
import kotlin.coroutines.*
import kotlin.coroutines.intrinsics.*
internal class SuspendFunctionGun<TSubject : Any, TContext : Any>(
initial: TSubject,
context: TContext,
private val blocks: List<PipelineInterceptorFunction<TSubject, TContext>>
) : PipelineContext<TSubject, TContext>(context) {
override val coroutineContext: CoroutineContext get() = continuation.context
// this is impossible to inline because of property name clash
// between PipelineContext.context and Continuation.context
private val continuation: Continuation<Unit> = object : Continuation<Unit>, CoroutineStackFrame {
override val callerFrame: CoroutineStackFrame? get() = peekContinuation() as? CoroutineStackFrame
var currentIndex: Int = Int.MIN_VALUE
override fun getStackTraceElement(): StackTraceElement? = null
private fun peekContinuation(): Continuation<*>? {
if (currentIndex == Int.MIN_VALUE) currentIndex = lastSuspensionIndex
if (currentIndex < 0) {
currentIndex = Int.MIN_VALUE
return null
}
// this is only invoked by debug agent during job state probes
// lastPeekedIndex is non-volatile intentionally
// and the list of continuations is not synchronized too
// so this is not guaranteed to work properly (may produce incorrect trace),
// but the only we care is to not crash here
// and simply return StackWalkingFailedFrame on any unfortunate accident
try {
val result = suspensions[currentIndex] ?: return StackWalkingFailedFrame
currentIndex -= 1
return result
} catch (_: Throwable) {
return StackWalkingFailedFrame
}
}
override val context: CoroutineContext
get() = suspensions[lastSuspensionIndex]?.context ?: error("Not started")
override fun resumeWith(result: Result<Unit>) {
if (result.isFailure) {
resumeRootWith(Result.failure(result.exceptionOrNull()!!))
return
}
loop(false)
}
}
override var subject: TSubject = initial
private val suspensions: Array<Continuation<TSubject>?> = arrayOfNulls(blocks.size)
private var lastSuspensionIndex: Int = -1
private var index = 0
override fun finish() {
index = blocks.size
}
override suspend fun proceed(): TSubject = suspendCoroutineUninterceptedOrReturn { continuation ->
if (index == blocks.size) return@suspendCoroutineUninterceptedOrReturn subject
addContinuation(continuation)
if (loop(true)) {
discardLastRootContinuation()
return@suspendCoroutineUninterceptedOrReturn subject
}
COROUTINE_SUSPENDED
}
override suspend fun proceedWith(subject: TSubject): TSubject {
this.subject = subject
return proceed()
}
override suspend fun execute(initial: TSubject): TSubject {
index = 0
if (index == blocks.size) return initial
subject = initial
if (lastSuspensionIndex >= 0) throw IllegalStateException("Already started")
return proceed()
}
/**
* @return `true` if it is possible to return result immediately
*/
private fun loop(direct: Boolean): Boolean {
do {
val currentIndex = index // it is important to read index every time
if (currentIndex == blocks.size) {
if (!direct) {
resumeRootWith(Result.success(subject))
return false
}
return true
}
index = currentIndex + 1 // it is important to increase it before function invocation
val next = blocks[currentIndex]
try {
val result = next(this, subject, continuation)
if (result === COROUTINE_SUSPENDED) return false
} catch (cause: Throwable) {
resumeRootWith(Result.failure(cause))
return false
}
} while (true)
}
private fun resumeRootWith(result: Result<TSubject>) {
if (lastSuspensionIndex < 0) error("No more continuations to resume")
val next = suspensions[lastSuspensionIndex]!!
suspensions[lastSuspensionIndex--] = null
if (!result.isFailure) {
next.resumeWith(result)
} else {
val exception = recoverStackTraceBridge(result.exceptionOrNull()!!, next)
next.resumeWithException(exception)
}
}
private fun discardLastRootContinuation() {
if (lastSuspensionIndex < 0) throw IllegalStateException("No more continuations to resume")
suspensions[lastSuspensionIndex--] = null
}
private fun addContinuation(continuation: Continuation<TSubject>) {
suspensions[++lastSuspensionIndex] = continuation
}
}
| apache-2.0 | c32ffeeb34bf69e002f1e8b1d8f955a3 | 33.810458 | 118 | 0.632933 | 5.358149 | false | false | false | false |
marius-m/wt4 | app/src/main/java/lt/markmerkk/widgets/settings/AccountSettingsOauthWidget.kt | 1 | 11513 | package lt.markmerkk.widgets.settings
import com.google.common.eventbus.EventBus
import com.jfoenix.controls.JFXButton
import com.jfoenix.controls.JFXSpinner
import com.jfoenix.controls.JFXTextArea
import com.jfoenix.svg.SVGGlyph
import io.sentry.Attachment
import io.sentry.Scope
import io.sentry.Sentry
import javafx.geometry.Pos
import javafx.scene.Parent
import javafx.scene.control.Label
import javafx.scene.control.ScrollPane
import javafx.scene.layout.*
import javafx.scene.paint.Color
import javafx.scene.web.WebView
import lt.markmerkk.*
import lt.markmerkk.events.EventSnackBarMessage
import lt.markmerkk.interactors.AuthService
import lt.markmerkk.interactors.JiraBasicApi
import lt.markmerkk.ui_2.views.jfxButton
import lt.markmerkk.ui_2.views.jfxSpinner
import lt.markmerkk.ui_2.views.jfxTextArea
import org.slf4j.LoggerFactory
import rx.Observable
import rx.observables.JavaFxObservable
import tornadofx.*
import java.io.File
import javax.inject.Inject
// todo incomplete display of behaviour
class AccountSettingsOauthWidget : Fragment() {
@Inject lateinit var graphics: Graphics<SVGGlyph>
@Inject lateinit var schedulerProvider: SchedulerProvider
@Inject lateinit var jiraAuthInteractor: AuthService.AuthInteractor
@Inject lateinit var userSettings: UserSettings
@Inject lateinit var strings: Strings
@Inject lateinit var eventBus: EventBus
@Inject lateinit var jiraClientProvider: JiraClientProvider
@Inject lateinit var appConfig: Config
@Inject lateinit var jiraBasicApi: JiraBasicApi
@Inject lateinit var autoSyncWatcher: AutoSyncWatcher2
@Inject lateinit var timeProvider: TimeProvider
private lateinit var viewWebview: WebView
private lateinit var viewButtonStatus: JFXButton
private lateinit var viewButtonSetupConnection: JFXButton
private lateinit var viewLabelStatus: Label
private lateinit var viewProgress: JFXSpinner
private lateinit var viewTextOutput: JFXTextArea
private lateinit var viewContainerLogs: BorderPane
private lateinit var viewContainerSetup: VBox
private lateinit var viewContainerSetupStatus: VBox
private lateinit var viewContainerSetupWebview: VBox
private lateinit var logFile: File
init {
Main.component().inject(this)
}
private lateinit var authorizator: OAuthAuthorizator
private lateinit var authWebviewPresenter: AuthWebviewPresenter
private lateinit var logTailer: LogTailer
override val root: Parent = borderpane {
addClass(Styles.dialogContainer)
top {
hbox(spacing = 10, alignment = Pos.TOP_LEFT) {
label("Account settings") {
addClass(Styles.dialogHeader)
}
viewProgress = jfxSpinner {
style {
padding = box(all = 4.px)
}
val boxDimen = 42.0
minWidth = boxDimen
maxWidth = boxDimen
minHeight = boxDimen
maxHeight = boxDimen
hide()
}
}
}
center {
borderpane {
minWidth = 650.0
minHeight = 450.0
center {
stackpane {
viewContainerSetup = vbox(spacing = 4, alignment = Pos.CENTER) {
viewContainerSetupStatus = vbox(spacing = 4, alignment = Pos.CENTER) {
viewButtonStatus = jfxButton {
setOnAction { authorizator.checkAuth() }
}
viewLabelStatus = label {
alignment = Pos.CENTER
isWrapText = true
}
viewButtonSetupConnection = jfxButton("Set-up new connection".toUpperCase()) {
addClass(Styles.dialogButtonAction)
setOnAction { authorizator.setupAuthStep1() }
}
}
viewContainerSetupWebview = vbox {
viewWebview = webview { }
}
}
viewContainerLogs = borderpane {
center {
viewTextOutput = jfxTextArea {
style {
fontSize = 8.pt
fontFamily = "monospaced"
hBarPolicy = ScrollPane.ScrollBarPolicy.ALWAYS
vBarPolicy = ScrollPane.ScrollBarPolicy.ALWAYS
}
isEditable = false
isWrapText = false
}
}
}
}
}
}
}
bottom {
hbox(alignment = Pos.CENTER_RIGHT, spacing = 4) {
addClass(Styles.dialogContainerActionsButtons)
jfxButton("Send report".toUpperCase()) {
setOnAction {
sendReport()
eventBus.post(EventSnackBarMessage("Thank you for the report!"))
close()
}
}
jfxButton("Show logs".toUpperCase()) {
setOnAction { toggleAdvanced() }
}
jfxButton("Close".toUpperCase()) {
setOnAction {
close()
}
}
}
}
}
override fun onDock() {
super.onDock()
this.logFile = File(appConfig.basePath(), "${File.separator}logs${File.separator}app.log")
authorizator = OAuthAuthorizator(
view = object : OAuthAuthorizator.View {
override fun accountReady() {
autoSyncWatcher.markForShortCycleUpdate()
}
override fun renderView(authViewModel: AuthViewModel) {
viewContainerSetupStatus.showIf(authViewModel.showContainerStatus)
viewContainerSetupWebview.showIf(authViewModel.showContainerWebview)
viewButtonSetupConnection.showIf(authViewModel.showButtonSetupNew)
viewButtonStatus.graphic = when (authViewModel.showStatusEmoticon) {
AuthViewModel.StatusEmoticon.HAPPY -> graphics.from(Glyph.EMOTICON_COOL, Color.BLACK, 64.0)
AuthViewModel.StatusEmoticon.NEUTRAL -> graphics.from(Glyph.EMOTICON_NEUTRAL, Color.BLACK, 64.0)
AuthViewModel.StatusEmoticon.SAD -> graphics.from(Glyph.EMOTICON_DEAD, Color.BLACK, 64.0)
}
viewLabelStatus.text = authViewModel.textStatus
}
override fun loadAuthWeb(url: String) {
viewWebview.engine.load(url)
}
override fun resetWeb() {
// Cookie reset does not work, as it scrambles the login flow
// Source: https://stackoverflow.com/questions/23409138/clear-the-session-cache-cookie-in-the-javafx-webview
// java.net.CookieHandler.setDefault(java.net.CookieManager())
viewWebview.engine.loadContent("<html></html>")
}
override fun showProgress() {
viewProgress.show()
}
override fun hideProgress() {
viewProgress.hide()
}
},
oAuthInteractor = OAuthInteractor(userSettings),
jiraClientProvider = jiraClientProvider,
jiraApi = jiraBasicApi,
userSettings = userSettings,
ioScheduler = schedulerProvider.io(),
uiScheduler = schedulerProvider.ui()
)
authWebviewPresenter = AuthWebviewPresenter(
view = object : AuthWebviewPresenter.View {
override fun onAccessToken(accessTokenKey: String) {
authorizator.setupAuthStep2(accessTokenKey)
}
override fun showProgress() {
viewProgress.show()
}
override fun hideProgress() {
viewProgress.hide()
}
},
authResultParser = AuthResultParser()
)
viewContainerSetup.show()
viewContainerLogs.hide()
logTailer = LogTailer(
logTailerLister,
schedulerProvider.io(),
schedulerProvider.ui()
)
logTailer.onAttach()
authorizator.onAttach()
authWebviewPresenter.onAttach()
authWebviewPresenter.attachRunning(JavaFxObservable.valuesOf(viewWebview.engine.loadWorker.runningProperty()))
val wvDocumentProperty = JavaFxObservable.valuesOf(viewWebview.engine.documentProperty())
.flatMap {
if (it != null) {
val documentUri: String = it.documentURI ?: ""
Observable.just(AuthWebviewPresenter.DocumentContent(documentUri, it.documentElement.textContent))
} else {
Observable.empty()
}
}
authWebviewPresenter.attachDocumentProperty(wvDocumentProperty)
autoSyncWatcher.changeUpdateLock(isInLock = true, lockProcessName = "AccountSettingsOauthWidget")
}
override fun onUndock() {
autoSyncWatcher.changeUpdateLock(isInLock = false, lockProcessName = "")
authWebviewPresenter.onDetach()
authorizator.onDetach()
logTailer.onDetach()
viewTextOutput.clear()
super.onUndock()
}
private fun toggleAdvanced() {
if (viewContainerLogs.isVisible) {
viewContainerLogs.hide()
viewContainerSetup.show()
logTailer.clear()
} else {
viewContainerLogs.show()
viewContainerSetup.hide()
this.logFile = File(appConfig.basePath(), "${File.separator}logs${File.separator}app.log")
logTailer.tail(logFile)
}
}
private fun sendReport() {
val attachment = Attachment(logFile.absolutePath)
Sentry.withScope { scope: Scope ->
scope.addAttachment(attachment)
Sentry.captureMessage("Sentry report (${timeProvider.now()})");
}
}
//region Logs
private val logTailerLister = object : LogTailer.Listener {
override fun onLogUpdate(logAsString: String) {
viewTextOutput.appendText("$logAsString\n")
}
override fun onClearLog() {
viewTextOutput.clear()
}
}
//endregion
//region Listeners
//endregion
companion object {
private val logger = LoggerFactory.getLogger(Tags.JIRA)!!
}
} | apache-2.0 | 7b749ca174276ee958b25b85ea7ccec4 | 37.898649 | 132 | 0.547555 | 5.725012 | false | false | false | false |
onnerby/musikcube | src/musikdroid/app/src/main/java/io/casey/musikcube/remote/service/playback/impl/streaming/db/OfflineDb.kt | 1 | 4050 | package io.casey.musikcube.remote.service.playback.impl.streaming.db
import androidx.room.Database
import androidx.room.RoomDatabase
import io.casey.musikcube.remote.Application
import io.casey.musikcube.remote.injection.DaggerDataComponent
import io.casey.musikcube.remote.service.playback.impl.remote.Metadata
import io.casey.musikcube.remote.service.playback.impl.streaming.StreamProxy
import io.casey.musikcube.remote.service.websocket.Messages
import io.casey.musikcube.remote.service.websocket.SocketMessage
import io.casey.musikcube.remote.service.websocket.WebSocketService
import io.reactivex.Single
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import org.json.JSONArray
import org.json.JSONObject
import java.util.*
import javax.inject.Inject
@Database(entities = [OfflineTrack::class], version = 1)
abstract class OfflineDb : RoomDatabase() {
@Inject lateinit var wss: WebSocketService
@Inject lateinit var streamProxy: StreamProxy
init {
DaggerDataComponent.builder()
.appComponent(Application.appComponent)
.build().inject(this)
wss.addInterceptor{ message, responder ->
var result = false
if (Messages.Request.QueryTracksByCategory.matches(message.name)) {
val category = message.getStringOption(Messages.Key.CATEGORY)
if (Metadata.Category.OFFLINE == category) {
queryTracks(message, responder)
result = true
}
}
result
}
prune()
}
abstract fun trackDao(): OfflineTrackDao
fun prune() {
@Suppress("unused")
Single.fromCallable {
val uris = trackDao().queryUris()
val toDelete = ArrayList<String>()
uris.forEach {
if (!streamProxy.isCached(it)) {
toDelete.add(it)
}
}
if (toDelete.size > 0) {
trackDao().deleteByUri(toDelete)
}
true
}
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe({ }, { })
}
private fun queryTracks(message: SocketMessage, responder: WebSocketService.Responder) {
Single.fromCallable {
val dao = trackDao()
val countOnly = message.getBooleanOption(Messages.Key.COUNT_ONLY, false)
val filter = message.getStringOption(Messages.Key.FILTER, "")
val tracks = JSONArray()
val options = JSONObject()
if (countOnly) {
val count = if (filter.isEmpty()) dao.countTracks() else dao.countTracks(filter)
options.put(Messages.Key.COUNT, count)
}
else {
val offset = message.getIntOption(Messages.Key.OFFSET, -1)
val limit = message.getIntOption(Messages.Key.LIMIT, -1)
val offlineTracks: List<OfflineTrack> =
if (filter.isEmpty()) {
if (offset == -1 || limit == -1)
dao.queryTracks() else dao.queryTracks(limit, offset)
}
else {
if (offset == -1 || limit == -1)
dao.queryTracks(filter) else dao.queryTracks(filter, limit, offset)
}
for (track in offlineTracks) {
tracks.put(track.toJSONObject())
}
options.put(Messages.Key.OFFSET, offset)
options.put(Messages.Key.LIMIT, limit)
}
options.put(Messages.Key.DATA, tracks)
val response = SocketMessage.Builder
.respondTo(message).withOptions(options).build()
responder.respond(response)
true
}
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe()
}
}
| bsd-3-clause | fb44f431a12640c35c641a0f75627f7b | 33.033613 | 96 | 0.590123 | 4.850299 | false | false | false | false |
inorichi/mangafeed | app/src/main/java/eu/kanade/tachiyomi/source/online/ParsedHttpSource.kt | 2 | 6552 | package eu.kanade.tachiyomi.source.online
import eu.kanade.tachiyomi.source.model.MangasPage
import eu.kanade.tachiyomi.source.model.Page
import eu.kanade.tachiyomi.source.model.SChapter
import eu.kanade.tachiyomi.source.model.SManga
import eu.kanade.tachiyomi.util.asJsoup
import okhttp3.Response
import org.jsoup.nodes.Document
import org.jsoup.nodes.Element
/**
* A simple implementation for sources from a website using Jsoup, an HTML parser.
*/
abstract class ParsedHttpSource : HttpSource() {
/**
* Parses the response from the site and returns a [MangasPage] object.
*
* @param response the response from the site.
*/
override fun popularMangaParse(response: Response): MangasPage {
val document = response.asJsoup()
val mangas = document.select(popularMangaSelector()).map { element ->
popularMangaFromElement(element)
}
val hasNextPage = popularMangaNextPageSelector()?.let { selector ->
document.select(selector).first()
} != null
return MangasPage(mangas, hasNextPage)
}
/**
* Returns the Jsoup selector that returns a list of [Element] corresponding to each manga.
*/
protected abstract fun popularMangaSelector(): String
/**
* Returns a manga from the given [element]. Most sites only show the title and the url, it's
* totally fine to fill only those two values.
*
* @param element an element obtained from [popularMangaSelector].
*/
protected abstract fun popularMangaFromElement(element: Element): SManga
/**
* Returns the Jsoup selector that returns the <a> tag linking to the next page, or null if
* there's no next page.
*/
protected abstract fun popularMangaNextPageSelector(): String?
/**
* Parses the response from the site and returns a [MangasPage] object.
*
* @param response the response from the site.
*/
override fun searchMangaParse(response: Response): MangasPage {
val document = response.asJsoup()
val mangas = document.select(searchMangaSelector()).map { element ->
searchMangaFromElement(element)
}
val hasNextPage = searchMangaNextPageSelector()?.let { selector ->
document.select(selector).first()
} != null
return MangasPage(mangas, hasNextPage)
}
/**
* Returns the Jsoup selector that returns a list of [Element] corresponding to each manga.
*/
protected abstract fun searchMangaSelector(): String
/**
* Returns a manga from the given [element]. Most sites only show the title and the url, it's
* totally fine to fill only those two values.
*
* @param element an element obtained from [searchMangaSelector].
*/
protected abstract fun searchMangaFromElement(element: Element): SManga
/**
* Returns the Jsoup selector that returns the <a> tag linking to the next page, or null if
* there's no next page.
*/
protected abstract fun searchMangaNextPageSelector(): String?
/**
* Parses the response from the site and returns a [MangasPage] object.
*
* @param response the response from the site.
*/
override fun latestUpdatesParse(response: Response): MangasPage {
val document = response.asJsoup()
val mangas = document.select(latestUpdatesSelector()).map { element ->
latestUpdatesFromElement(element)
}
val hasNextPage = latestUpdatesNextPageSelector()?.let { selector ->
document.select(selector).first()
} != null
return MangasPage(mangas, hasNextPage)
}
/**
* Returns the Jsoup selector that returns a list of [Element] corresponding to each manga.
*/
protected abstract fun latestUpdatesSelector(): String
/**
* Returns a manga from the given [element]. Most sites only show the title and the url, it's
* totally fine to fill only those two values.
*
* @param element an element obtained from [latestUpdatesSelector].
*/
protected abstract fun latestUpdatesFromElement(element: Element): SManga
/**
* Returns the Jsoup selector that returns the <a> tag linking to the next page, or null if
* there's no next page.
*/
protected abstract fun latestUpdatesNextPageSelector(): String?
/**
* Parses the response from the site and returns the details of a manga.
*
* @param response the response from the site.
*/
override fun mangaDetailsParse(response: Response): SManga {
return mangaDetailsParse(response.asJsoup())
}
/**
* Returns the details of the manga from the given [document].
*
* @param document the parsed document.
*/
protected abstract fun mangaDetailsParse(document: Document): SManga
/**
* Parses the response from the site and returns a list of chapters.
*
* @param response the response from the site.
*/
override fun chapterListParse(response: Response): List<SChapter> {
val document = response.asJsoup()
return document.select(chapterListSelector()).map { chapterFromElement(it) }
}
/**
* Returns the Jsoup selector that returns a list of [Element] corresponding to each chapter.
*/
protected abstract fun chapterListSelector(): String
/**
* Returns a chapter from the given element.
*
* @param element an element obtained from [chapterListSelector].
*/
protected abstract fun chapterFromElement(element: Element): SChapter
/**
* Parses the response from the site and returns the page list.
*
* @param response the response from the site.
*/
override fun pageListParse(response: Response): List<Page> {
return pageListParse(response.asJsoup())
}
/**
* Returns a page list from the given document.
*
* @param document the parsed document.
*/
protected abstract fun pageListParse(document: Document): List<Page>
/**
* Parse the response from the site and returns the absolute url to the source image.
*
* @param response the response from the site.
*/
override fun imageUrlParse(response: Response): String {
return imageUrlParse(response.asJsoup())
}
/**
* Returns the absolute url to the source image from the document.
*
* @param document the parsed document.
*/
protected abstract fun imageUrlParse(document: Document): String
}
| apache-2.0 | dc506ddd5d5aa6f42c152e378a7ebe17 | 31.76 | 97 | 0.667277 | 5.08301 | false | false | false | false |
iSoron/uhabits | uhabits-android/src/main/java/org/isoron/uhabits/activities/common/views/RingView.kt | 1 | 7755 | /*
* Copyright (C) 2016-2021 Álinson Santos Xavier <[email protected]>
*
* This file is part of Loop Habit Tracker.
*
* Loop Habit Tracker 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.
*
* Loop Habit Tracker 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 org.isoron.uhabits.activities.common.views
import android.content.Context
import android.graphics.Bitmap
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.graphics.PorterDuff
import android.graphics.PorterDuffXfermode
import android.graphics.RectF
import android.text.TextPaint
import android.util.AttributeSet
import android.view.View
import org.isoron.uhabits.R
import org.isoron.uhabits.utils.AttributeSetUtils.getAttribute
import org.isoron.uhabits.utils.AttributeSetUtils.getBooleanAttribute
import org.isoron.uhabits.utils.AttributeSetUtils.getColorAttribute
import org.isoron.uhabits.utils.AttributeSetUtils.getFloatAttribute
import org.isoron.uhabits.utils.ColorUtils.setAlpha
import org.isoron.uhabits.utils.InterfaceUtils.dpToPixels
import org.isoron.uhabits.utils.InterfaceUtils.getDimension
import org.isoron.uhabits.utils.InterfaceUtils.getFontAwesome
import org.isoron.uhabits.utils.InterfaceUtils.spToPixels
import org.isoron.uhabits.utils.PaletteUtils.getAndroidTestColor
import org.isoron.uhabits.utils.StyledResources
import kotlin.math.max
import kotlin.math.min
import kotlin.math.roundToLong
class RingView : View {
private var color: Int
private var precision: Float
private var percentage: Float
private var diameter = 1
private var thickness: Float
private var rect: RectF? = null
private var pRing: TextPaint? = null
private var backgroundColor: Int? = null
private var inactiveColor: Int? = null
private var em = 0f
private var text: String?
private var textSize: Float
private var enableFontAwesome = false
private var internalDrawingCache: Bitmap? = null
private var cacheCanvas: Canvas? = null
private var isTransparencyEnabled = false
constructor(context: Context?) : super(context) {
percentage = 0.0f
precision = 0.01f
color = getAndroidTestColor(0)
thickness = dpToPixels(getContext(), 2f)
text = ""
textSize = getDimension(context!!, R.dimen.smallTextSize)
init()
}
constructor(ctx: Context?, attrs: AttributeSet?) : super(ctx, attrs) {
percentage = getFloatAttribute(ctx!!, attrs!!, "percentage", 0f)
precision = getFloatAttribute(ctx, attrs, "precision", 0.01f)
color = getColorAttribute(ctx, attrs, "color", 0)!!
backgroundColor = getColorAttribute(ctx, attrs, "backgroundColor", null)
inactiveColor = getColorAttribute(ctx, attrs, "inactiveColor", null)
thickness = getFloatAttribute(ctx, attrs, "thickness", 0f)
thickness = dpToPixels(ctx, thickness)
val defaultTextSize = getDimension(ctx, R.dimen.smallTextSize)
textSize = getFloatAttribute(ctx, attrs, "textSize", defaultTextSize)
textSize = spToPixels(ctx, textSize)
text = getAttribute(ctx, attrs, "text", "")
enableFontAwesome = getBooleanAttribute(ctx, attrs, "enableFontAwesome", false)
init()
}
override fun setBackgroundColor(backgroundColor: Int) {
this.backgroundColor = backgroundColor
invalidate()
}
fun setColor(color: Int) {
this.color = color
invalidate()
}
fun getColor(): Int {
return color
}
fun setIsTransparencyEnabled(isTransparencyEnabled: Boolean) {
this.isTransparencyEnabled = isTransparencyEnabled
}
fun setPercentage(percentage: Float) {
this.percentage = percentage
invalidate()
}
fun setPrecision(precision: Float) {
this.precision = precision
invalidate()
}
fun setText(text: String?) {
this.text = text
invalidate()
}
fun setTextSize(textSize: Float) {
this.textSize = textSize
}
fun setThickness(thickness: Float) {
this.thickness = thickness
invalidate()
}
override fun onDraw(canvas: Canvas) {
super.onDraw(canvas)
val activeCanvas: Canvas?
if (isTransparencyEnabled) {
if (internalDrawingCache == null) reallocateCache()
activeCanvas = cacheCanvas
internalDrawingCache!!.eraseColor(Color.TRANSPARENT)
} else {
activeCanvas = canvas
}
pRing!!.color = color
rect!![0f, 0f, diameter.toFloat()] = diameter.toFloat()
val angle = 360 * (percentage / precision).roundToLong() * precision
activeCanvas!!.drawArc(rect!!, -90f, angle, true, pRing!!)
pRing!!.color = inactiveColor!!
activeCanvas.drawArc(rect!!, angle - 90, 360 - angle, true, pRing!!)
if (thickness > 0) {
if (isTransparencyEnabled) pRing!!.xfermode = XFERMODE_CLEAR else pRing!!.color =
backgroundColor!!
rect!!.inset(thickness, thickness)
activeCanvas.drawArc(rect!!, 0f, 360f, true, pRing!!)
pRing!!.xfermode = null
pRing!!.color = color
pRing!!.textSize = textSize
if (enableFontAwesome) pRing!!.typeface = getFontAwesome(context)
activeCanvas.drawText(
text!!,
rect!!.centerX(),
rect!!.centerY() + 0.4f * em,
pRing!!
)
}
if (activeCanvas !== canvas) canvas.drawBitmap(internalDrawingCache!!, 0f, 0f, null)
}
override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec)
val width = MeasureSpec.getSize(widthMeasureSpec)
val height = MeasureSpec.getSize(heightMeasureSpec)
diameter = max(1, min(height, width))
pRing!!.textSize = textSize
em = pRing!!.measureText("M")
setMeasuredDimension(diameter, diameter)
}
override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
super.onSizeChanged(w, h, oldw, oldh)
if (isTransparencyEnabled) reallocateCache()
}
private fun init() {
pRing = TextPaint()
pRing!!.isAntiAlias = true
pRing!!.color = color
pRing!!.textAlign = Paint.Align.CENTER
val res = StyledResources(context)
if (backgroundColor == null) backgroundColor = res.getColor(R.attr.cardBgColor)
if (inactiveColor == null) inactiveColor = res.getColor(R.attr.contrast100)
inactiveColor = setAlpha(inactiveColor!!, 0.1f)
rect = RectF()
}
private fun reallocateCache() {
if (internalDrawingCache != null) internalDrawingCache!!.recycle()
val newDrawingCache = Bitmap.createBitmap(diameter, diameter, Bitmap.Config.ARGB_8888)
internalDrawingCache = newDrawingCache
cacheCanvas = Canvas(newDrawingCache)
}
fun getPercentage(): Float {
return percentage
}
fun getPrecision(): Float {
return precision
}
companion object {
val XFERMODE_CLEAR = PorterDuffXfermode(PorterDuff.Mode.CLEAR)
}
}
| gpl-3.0 | 86a726d11a291383d5c40aa794ee431c | 35.233645 | 94 | 0.674491 | 4.50029 | false | false | false | false |
cascheberg/Signal-Android | app/src/main/java/org/thoughtcrime/securesms/components/settings/conversation/preferences/ButtonStripPreference.kt | 2 | 4435 | package org.thoughtcrime.securesms.components.settings.conversation.preferences
import android.view.View
import android.widget.ImageView
import android.widget.TextView
import androidx.appcompat.content.res.AppCompatResources
import org.thoughtcrime.securesms.R
import org.thoughtcrime.securesms.components.settings.DSLSettingsIcon
import org.thoughtcrime.securesms.components.settings.PreferenceModel
import org.thoughtcrime.securesms.util.MappingAdapter
import org.thoughtcrime.securesms.util.MappingViewHolder
import org.thoughtcrime.securesms.util.visible
/**
* Renders a configurable strip of buttons
*/
object ButtonStripPreference {
fun register(adapter: MappingAdapter) {
adapter.registerFactory(Model::class.java, MappingAdapter.LayoutFactory(::ViewHolder, R.layout.conversation_settings_button_strip))
}
class Model(
val state: State,
val background: DSLSettingsIcon? = null,
val onMessageClick: () -> Unit = {},
val onVideoClick: () -> Unit = {},
val onAudioClick: () -> Unit = {},
val onMuteClick: () -> Unit = {},
val onSearchClick: () -> Unit = {}
) : PreferenceModel<Model>() {
override fun areContentsTheSame(newItem: Model): Boolean {
return super.areContentsTheSame(newItem) && state == newItem.state
}
override fun areItemsTheSame(newItem: Model): Boolean {
return true
}
}
class ViewHolder(itemView: View) : MappingViewHolder<Model>(itemView) {
private val message: View = itemView.findViewById(R.id.message)
private val messageLabel: View = itemView.findViewById(R.id.message_label)
private val videoCall: View = itemView.findViewById(R.id.start_video)
private val videoLabel: View = itemView.findViewById(R.id.start_video_label)
private val audioCall: ImageView = itemView.findViewById(R.id.start_audio)
private val audioLabel: TextView = itemView.findViewById(R.id.start_audio_label)
private val mute: ImageView = itemView.findViewById(R.id.mute)
private val muteLabel: TextView = itemView.findViewById(R.id.mute_label)
private val search: View = itemView.findViewById(R.id.search)
private val searchLabel: View = itemView.findViewById(R.id.search_label)
override fun bind(model: Model) {
message.visible = model.state.isMessageAvailable
messageLabel.visible = model.state.isMessageAvailable
videoCall.visible = model.state.isVideoAvailable
videoLabel.visible = model.state.isVideoAvailable
audioCall.visible = model.state.isAudioAvailable
audioLabel.visible = model.state.isAudioAvailable
mute.visible = model.state.isMuteAvailable
muteLabel.visible = model.state.isMuteAvailable
search.visible = model.state.isSearchAvailable
searchLabel.visible = model.state.isSearchAvailable
if (model.state.isAudioSecure) {
audioLabel.setText(R.string.ConversationSettingsFragment__audio)
audioCall.setImageDrawable(AppCompatResources.getDrawable(context, R.drawable.ic_phone_right_24))
} else {
audioLabel.setText(R.string.ConversationSettingsFragment__call)
audioCall.setImageDrawable(AppCompatResources.getDrawable(context, R.drawable.ic_phone_right_unlock_primary_accent_24))
}
if (model.state.isMuted) {
mute.setImageDrawable(AppCompatResources.getDrawable(context, R.drawable.ic_bell_disabled_24))
muteLabel.setText(R.string.ConversationSettingsFragment__muted)
} else {
mute.setImageDrawable(AppCompatResources.getDrawable(context, R.drawable.ic_bell_24))
muteLabel.setText(R.string.ConversationSettingsFragment__mute)
}
if (model.background != null) {
listOf(message, videoCall, audioCall, mute, search).forEach {
it.background = model.background.resolve(context)
}
}
message.setOnClickListener { model.onMessageClick() }
videoCall.setOnClickListener { model.onVideoClick() }
audioCall.setOnClickListener { model.onAudioClick() }
mute.setOnClickListener { model.onMuteClick() }
search.setOnClickListener { model.onSearchClick() }
}
}
data class State(
val isMessageAvailable: Boolean = false,
val isVideoAvailable: Boolean = false,
val isAudioAvailable: Boolean = false,
val isMuteAvailable: Boolean = false,
val isSearchAvailable: Boolean = false,
val isAudioSecure: Boolean = false,
val isMuted: Boolean = false,
)
}
| gpl-3.0 | 15b479c1a723f25ff117e094e1a3cb24 | 41.238095 | 135 | 0.736189 | 4.408549 | false | false | false | false |
dahlstrom-g/intellij-community | platform/platform-impl/src/com/intellij/openapi/project/impl/ProjectManagerExImpl.kt | 2 | 23691 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
@file:Suppress("ReplaceNegatedIsEmptyWithIsNotEmpty")
package com.intellij.openapi.project.impl
import com.intellij.conversion.ConversionResult
import com.intellij.conversion.ConversionService
import com.intellij.diagnostic.Activity
import com.intellij.diagnostic.ActivityCategory
import com.intellij.diagnostic.StartUpMeasurer
import com.intellij.diagnostic.opentelemetry.TraceManager
import com.intellij.diagnostic.runActivity
import com.intellij.diagnostic.telemetry.useWithScope
import com.intellij.featureStatistics.fusCollectors.LifecycleUsageTriggerCollector
import com.intellij.ide.*
import com.intellij.ide.impl.*
import com.intellij.ide.lightEdit.LightEditCompatible
import com.intellij.ide.startup.impl.StartupManagerImpl
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.application.ModalityState
import com.intellij.openapi.application.PathManager
import com.intellij.openapi.components.ComponentManagerEx
import com.intellij.openapi.components.StorageScheme
import com.intellij.openapi.components.service
import com.intellij.openapi.module.Module
import com.intellij.openapi.module.ModuleManager
import com.intellij.openapi.progress.ProcessCanceledException
import com.intellij.openapi.progress.ProgressIndicator
import com.intellij.openapi.progress.ProgressManager
import com.intellij.openapi.project.*
import com.intellij.openapi.startup.StartupManager
import com.intellij.openapi.ui.Messages
import com.intellij.openapi.util.NlsSafe
import com.intellij.openapi.util.SystemInfoRt
import com.intellij.openapi.util.io.FileUtil
import com.intellij.openapi.wm.IdeFocusManager
import com.intellij.openapi.wm.WindowManager
import com.intellij.openapi.wm.impl.WindowManagerImpl
import com.intellij.openapi.wm.impl.welcomeScreen.WelcomeFrame
import com.intellij.platform.PlatformProjectOpenProcessor
import com.intellij.platform.PlatformProjectOpenProcessor.Companion.isLoadedFromCacheButHasNoModules
import com.intellij.project.ProjectStoreOwner
import com.intellij.projectImport.ProjectAttachProcessor
import com.intellij.projectImport.ProjectOpenedCallback
import com.intellij.ui.IdeUICustomization
import com.intellij.util.ModalityUiUtil
import com.intellij.util.ThreeState
import com.intellij.util.io.delete
import com.intellij.util.io.exists
import io.opentelemetry.api.common.AttributeKey
import io.opentelemetry.context.Context
import org.jetbrains.annotations.ApiStatus
import org.jetbrains.annotations.TestOnly
import java.awt.event.InvocationEvent
import java.io.IOException
import java.nio.file.*
import java.util.concurrent.CompletableFuture
import java.util.concurrent.TimeUnit
@ApiStatus.Internal
open class ProjectManagerExImpl : ProjectManagerImpl() {
final override fun createProject(name: String?, path: String): Project? {
return newProject(toCanonicalName(path), OpenProjectTask(isNewProject = true, runConfigurators = false, projectName = name))
}
final override fun newProject(projectName: String?, path: String, useDefaultProjectAsTemplate: Boolean, isDummy: Boolean): Project? {
return newProject(toCanonicalName(path), OpenProjectTask(isNewProject = true,
useDefaultProjectAsTemplate = useDefaultProjectAsTemplate,
projectName = projectName))
}
final override fun loadAndOpenProject(originalFilePath: String): Project? {
return openProject(toCanonicalName(originalFilePath), OpenProjectTask())
}
final override fun openProject(projectStoreBaseDir: Path, options: OpenProjectTask): Project? {
return openProjectAsync(projectStoreBaseDir, options).get(30, TimeUnit.MINUTES)
}
final override fun openProjectAsync(projectStoreBaseDir: Path, options: OpenProjectTask): CompletableFuture<Project?> {
if (LOG.isDebugEnabled && !ApplicationManager.getApplication().isUnitTestMode) {
LOG.debug("open project: $options", Exception())
}
if (options.project != null && isProjectOpened(options.project as Project)) {
return CompletableFuture.completedFuture(null)
}
if (!checkTrustedState(projectStoreBaseDir)) {
return CompletableFuture.completedFuture(null)
}
val activity = StartUpMeasurer.startActivity("project opening preparation")
if (!options.forceOpenInNewFrame) {
val openProjects = openProjects
if (!openProjects.isEmpty()) {
var projectToClose = options.projectToClose
if (projectToClose == null) {
// if several projects are opened, ask to reuse not last opened project frame, but last focused (to avoid focus switching)
val lastFocusedFrame = IdeFocusManager.getGlobalInstance().lastFocusedFrame
projectToClose = lastFocusedFrame?.project
if (projectToClose == null || projectToClose is LightEditCompatible) {
projectToClose = openProjects.last()
}
}
// this null assertion is required to overcome bug in new version of KT compiler: KT-40034
@Suppress("UNNECESSARY_NOT_NULL_ASSERTION")
if (checkExistingProjectOnOpen(projectToClose!!, options.callback, projectStoreBaseDir, options.projectName)) {
return CompletableFuture.completedFuture(null)
}
}
}
return doOpenAsync(options, projectStoreBaseDir, activity)
}
private fun doOpenAsync(options: OpenProjectTask,
projectStoreBaseDir: Path,
activity: Activity): CompletableFuture<Project?> {
val frameAllocator = if (ApplicationManager.getApplication().isHeadlessEnvironment) {
ProjectFrameAllocator(options)
}
else {
ProjectUiFrameAllocator(options, projectStoreBaseDir)
}
val disableAutoSaveToken = SaveAndSyncHandler.getInstance().disableAutoSave()
return frameAllocator.run { indicator ->
activity.end()
val result: PrepareProjectResult
if (options.project == null) {
result = prepareProject(options, projectStoreBaseDir) ?: return@run null
}
else {
result = PrepareProjectResult(options.project as Project, null)
}
val project = result.project
if (!addToOpened(project)) {
return@run null
}
if (!checkOldTrustedStateAndMigrate(project, projectStoreBaseDir)) {
handleProjectOpenCancelOrFailure(project)
return@run null
}
frameAllocator.projectLoaded(project)
try {
openProject(project, indicator, isRunStartUpActivitiesEnabled(project)).join()
}
catch (e: ProcessCanceledException) {
handleProjectOpenCancelOrFailure(project)
return@run null
}
result
}
.handle { result, error ->
disableAutoSaveToken.finish()
if (error != null) {
throw error
}
if (result == null) {
frameAllocator.projectNotLoaded(error = null)
if (options.showWelcomeScreen) {
WelcomeFrame.showIfNoProjectOpened()
}
return@handle null
}
val project = result.project
if (options.callback != null) {
options.callback!!.projectOpened(project, result.module ?: ModuleManager.getInstance(project).modules[0])
}
project
}
}
private fun handleProjectOpenCancelOrFailure(project: Project) {
val app = ApplicationManager.getApplication()
app.invokeAndWait {
closeProject(project, /* saveProject = */false, /* dispose = */true, /* checkCanClose = */false)
}
app.messageBus.syncPublisher(AppLifecycleListener.TOPIC).projectOpenFailed()
}
/**
* Checks if the project path is trusted, and shows the Trust Project dialog if needed.
*
* @return true if we should proceed with project opening, false if the process of project opening should be canceled.
*/
private fun checkTrustedState(projectStoreBaseDir: Path): Boolean {
val trustedPaths = TrustedPaths.getInstance()
val trustedState = trustedPaths.getProjectPathTrustedState(projectStoreBaseDir)
if (trustedState != ThreeState.UNSURE) {
// the trusted state of this project path is already known => proceed with opening
return true
}
if (isProjectImplicitlyTrusted(projectStoreBaseDir)) {
return true
}
// check if the project trusted state could be known from the previous IDE version
val metaInfo = (RecentProjectsManager.getInstance() as RecentProjectsManagerBase).getProjectMetaInfo(projectStoreBaseDir)
val projectId = metaInfo?.projectWorkspaceId
val productWorkspaceFile = PathManager.getConfigDir().resolve("workspace").resolve("$projectId.xml")
if (projectId != null && productWorkspaceFile.exists()) {
// this project is in recent projects => it was opened on this computer before
// => most probably we already asked about its trusted state before
// the only exception is: the project stayed in the UNKNOWN state in the previous version because it didn't utilize any dangerous features
// in this case we will ask since no UNKNOWN state is allowed, but on a later stage, when we'll be able to look into the project-wide storage
return true
}
return confirmOpeningAndSetProjectTrustedStateIfNeeded(projectStoreBaseDir)
}
/**
* Checks if the project was trusted using the previous API.
* Migrates the setting to the new API, shows the Trust Project dialog if needed.
*
* @return true if we should proceed with project opening, false if the process of project opening should be canceled.
*/
private fun checkOldTrustedStateAndMigrate(project: Project, projectStoreBaseDir: Path): Boolean {
val trustedPaths = TrustedPaths.getInstance()
val trustedState = trustedPaths.getProjectPathTrustedState(projectStoreBaseDir)
if (trustedState != ThreeState.UNSURE) {
return true
}
@Suppress("DEPRECATION")
val previousTrustedState = project.service<TrustedProjectSettings>().trustedState
if (previousTrustedState != ThreeState.UNSURE) {
// we were asking about this project in the previous IDE version => migrate
trustedPaths.setProjectPathTrusted(projectStoreBaseDir, previousTrustedState.toBoolean())
return true
}
return confirmOpeningAndSetProjectTrustedStateIfNeeded(projectStoreBaseDir)
}
override fun openProject(project: Project): Boolean {
val store = if (project is ProjectStoreOwner) (project as ProjectStoreOwner).componentStore else null
if (store != null) {
val projectFilePath = if (store.storageScheme == StorageScheme.DIRECTORY_BASED) store.directoryStorePath!! else store.projectFilePath
for (p in openProjects) {
if (ProjectUtil.isSameProject(projectFilePath, p)) {
ModalityUiUtil.invokeLaterIfNeeded(ModalityState.NON_MODAL
) { ProjectUtil.focusProjectWindow(p, false) }
return false
}
}
}
if (!addToOpened(project)) {
return false
}
val app = ApplicationManager.getApplication()
if (!app.isUnitTestMode && app.isDispatchThread) {
LOG.warn("Do not open project in EDT")
}
try {
openProject(project, ProgressManager.getInstance().progressIndicator, isRunStartUpActivitiesEnabled(project)).join()
}
catch (e: ProcessCanceledException) {
app.invokeAndWait { closeProject(project, /* saveProject = */false, /* dispose = */true, /* checkCanClose = */false) }
app.messageBus.syncPublisher(AppLifecycleListener.TOPIC).projectOpenFailed()
if (!app.isUnitTestMode) {
WelcomeFrame.showIfNoProjectOpened()
}
return false
}
return true
}
override fun newProject(projectFile: Path, options: OpenProjectTask): Project? {
removeProjectConfigurationAndCaches(projectFile)
val project = instantiateProject(projectFile, options)
try {
val template = if (options.useDefaultProjectAsTemplate) defaultProject else null
initProject(projectFile, project, options.isRefreshVfsNeeded, options.preloadServices, template,
ProgressManager.getInstance().progressIndicator)
project.setTrusted(true)
return project
}
catch (t: Throwable) {
handleErrorOnNewProject(t)
return null
}
}
protected open fun handleErrorOnNewProject(t: Throwable) {
LOG.warn(t)
try {
val errorMessage = message(t)
ApplicationManager.getApplication().invokeAndWait {
Messages.showErrorDialog(errorMessage, ProjectBundle.message("project.load.default.error"))
}
}
catch (e: NoClassDefFoundError) {
// error icon not loaded
LOG.info(e)
}
}
protected open fun instantiateProject(projectStoreBaseDir: Path, options: OpenProjectTask): ProjectImpl {
val activity = StartUpMeasurer.startActivity("project instantiation")
val project = ProjectExImpl(projectStoreBaseDir, options.projectName)
activity.end()
options.beforeInit?.invoke(project)
return project
}
private fun prepareProject(options: OpenProjectTask, projectStoreBaseDir: Path): PrepareProjectResult? {
val project: Project?
val indicator = ProgressManager.getInstance().progressIndicator
if (options.isNewProject) {
removeProjectConfigurationAndCaches(projectStoreBaseDir)
project = instantiateProject(projectStoreBaseDir, options)
val template = if (options.useDefaultProjectAsTemplate) defaultProject else null
initProject(projectStoreBaseDir, project, options.isRefreshVfsNeeded, options.preloadServices, template, indicator)
}
else {
var conversionResult: ConversionResult? = null
if (options.runConversionBeforeOpen) {
val conversionService = ConversionService.getInstance()
if (conversionService != null) {
indicator?.text = IdeUICustomization.getInstance().projectMessage("progress.text.project.checking.configuration")
conversionResult = runActivity("project conversion") {
conversionService.convert(projectStoreBaseDir)
}
if (conversionResult.openingIsCanceled()) {
return null
}
indicator?.text = ""
}
}
project = instantiateProject(projectStoreBaseDir, options)
// template as null here because it is not a new project
initProject(projectStoreBaseDir, project, options.isRefreshVfsNeeded, options.preloadServices, null, indicator)
if (conversionResult != null && !conversionResult.conversionNotNeeded()) {
StartupManager.getInstance(project).runAfterOpened {
conversionResult.postStartupActivity(project)
}
}
}
project.putUserData(PlatformProjectOpenProcessor.PROJECT_NEWLY_OPENED, options.isNewProject)
if (options.beforeOpen != null && !options.beforeOpen!!(project)) {
return null
}
if (options.runConfigurators && (options.isNewProject || ModuleManager.getInstance(project).modules.isEmpty()) ||
project.isLoadedFromCacheButHasNoModules()) {
val module = PlatformProjectOpenProcessor.runDirectoryProjectConfigurators(projectStoreBaseDir, project,
options.isProjectCreatedWithWizard)
options.preparedToOpen?.invoke(module)
return PrepareProjectResult(project, module)
}
return PrepareProjectResult(project, module = null)
}
protected open fun isRunStartUpActivitiesEnabled(project: Project): Boolean = true
private fun checkExistingProjectOnOpen(projectToClose: Project,
callback: ProjectOpenedCallback?,
projectDir: Path?,
projectName: String?): Boolean {
val settings = GeneralSettings.getInstance()
val isValidProject = projectDir != null && ProjectUtil.isValidProjectPath(projectDir)
var result = false
// modality per thread, it means that we cannot use invokeLater, because after getting result from EDT, we MUST continue execution
// in ORIGINAL thread
ApplicationManager.getApplication().invokeAndWait task@{
if (projectDir != null && ProjectAttachProcessor.canAttachToProject() &&
(!isValidProject || settings.confirmOpenNewProject == GeneralSettings.OPEN_PROJECT_ASK)) {
val exitCode = ProjectUtil.confirmOpenOrAttachProject()
if (exitCode == -1) {
result = true
return@task
}
else if (exitCode == GeneralSettings.OPEN_PROJECT_SAME_WINDOW) {
if (!closeAndDisposeKeepingFrame(projectToClose)) {
result = true
return@task
}
}
else if (exitCode == GeneralSettings.OPEN_PROJECT_SAME_WINDOW_ATTACH) {
if (PlatformProjectOpenProcessor.attachToProject(projectToClose, projectDir, callback)) {
result = true
return@task
}
}
// process all pending events that can interrupt focus flow
// todo this can be removed after taming the focus beast
IdeEventQueue.getInstance().flushQueue()
}
else {
val mode = GeneralSettings.getInstance().confirmOpenNewProject
if (mode == GeneralSettings.OPEN_PROJECT_SAME_WINDOW_ATTACH) {
if (projectDir != null && PlatformProjectOpenProcessor.attachToProject(projectToClose, projectDir, callback)) {
result = true
return@task
}
}
val projectNameValue = projectName ?: projectDir?.fileName?.toString() ?: projectDir?.toString()
val exitCode = ProjectUtil.confirmOpenNewProject(false, projectNameValue)
if (exitCode == GeneralSettings.OPEN_PROJECT_SAME_WINDOW) {
if (!closeAndDisposeKeepingFrame(projectToClose)) {
result = true
return@task
}
}
else if (exitCode != GeneralSettings.OPEN_PROJECT_NEW_WINDOW) {
// not in a new window
result = true
return@task
}
}
result = false
}
return result
}
private fun closeAndDisposeKeepingFrame(project: Project): Boolean {
return (WindowManager.getInstance() as WindowManagerImpl).runWithFrameReuseEnabled { closeAndDispose(project) }
}
}
private val tracer by lazy { TraceManager.getTracer("projectManager") }
@NlsSafe
private fun message(e: Throwable): String {
var message = e.message ?: e.localizedMessage
if (message != null) {
return message
}
message = e.toString()
val causeMessage = message(e.cause ?: return message)
return "$message (cause: $causeMessage)"
}
private inline fun executeInEdtWithProgress(indicator: ProgressIndicator?, crossinline task: () -> Unit) {
var pce: ProcessCanceledException? = null
ApplicationManager.getApplication().invokeAndWait {
try {
if (indicator == null) {
task()
}
else {
ProgressManager.getInstance().executeProcessUnderProgress({ task() }, indicator)
}
}
catch (e: ProcessCanceledException) {
pce = e
}
}
pce?.let { throw it }
}
private fun openProject(project: Project, indicator: ProgressIndicator?, runStartUpActivities: Boolean): CompletableFuture<*> {
val waitEdtActivity = StartUpMeasurer.startActivity("placing calling projectOpened on event queue")
if (indicator != null) {
indicator.text = if (ApplicationManager.getApplication().isInternal) "Waiting on event queue..." // NON-NLS (internal mode)
else ProjectBundle.message("project.preparing.workspace")
indicator.isIndeterminate = true
}
tracer.spanBuilder("open project")
.setAttribute(AttributeKey.stringKey("project"), project.name)
.useWithScope {
val traceContext = Context.current()
// invokeLater cannot be used for now
executeInEdtWithProgress(indicator) {
waitEdtActivity.end()
indicator?.checkCanceled()
if (indicator != null && ApplicationManager.getApplication().isInternal) {
indicator.text = "Running project opened tasks..." // NON-NLS (internal mode)
}
ProjectManagerImpl.LOG.debug("projectOpened")
val activity = StartUpMeasurer.startActivity("project opened callbacks")
runActivity("projectOpened event executing") {
tracer.spanBuilder("execute projectOpened handlers").setParent(traceContext).useWithScope {
ApplicationManager.getApplication().messageBus.syncPublisher(ProjectManager.TOPIC).projectOpened(project)
}
}
@Suppress("DEPRECATION")
(project as ComponentManagerEx)
.processInitializedComponents(com.intellij.openapi.components.ProjectComponent::class.java) { component, pluginDescriptor ->
indicator?.checkCanceled()
try {
val componentActivity = StartUpMeasurer.startActivity(component.javaClass.name, ActivityCategory.PROJECT_OPEN_HANDLER,
pluginDescriptor.pluginId.idString)
component.projectOpened()
componentActivity.end()
}
catch (e: ProcessCanceledException) {
throw e
}
catch (e: Throwable) {
ProjectManagerImpl.LOG.error(e)
}
}
activity.end()
}
ProjectImpl.ourClassesAreLoaded = true
if (runStartUpActivities) {
tracer.spanBuilder("StartupManager.projectOpened").useWithScope {
(StartupManager.getInstance(project) as StartupManagerImpl).projectOpened(indicator)
}
}
LifecycleUsageTriggerCollector.onProjectOpened(project)
return CompletableFuture.completedFuture(null)
}
}
// allow `invokeAndWait` inside startup activities
@TestOnly
internal fun waitAndProcessInvocationEventsInIdeEventQueue(startupManager: StartupManagerImpl) {
ApplicationManager.getApplication().assertIsDispatchThread()
val eventQueue = IdeEventQueue.getInstance()
if (startupManager.postStartupActivityPassed()) {
ApplicationManager.getApplication().invokeLater {}
}
else {
// make sure eventQueue.nextEvent will unblock
startupManager.registerPostStartupActivity(DumbAwareRunnable { ApplicationManager.getApplication().invokeLater{ } })
}
while (true) {
val event = eventQueue.nextEvent
if (event is InvocationEvent) {
eventQueue.dispatchEvent(event)
}
if (startupManager.postStartupActivityPassed() && eventQueue.peekEvent() == null) {
break
}
}
}
private data class PrepareProjectResult(val project: Project, val module: Module?)
private fun toCanonicalName(filePath: String): Path {
val file = Paths.get(filePath)
try {
if (SystemInfoRt.isWindows && FileUtil.containsWindowsShortName(filePath)) {
return file.toRealPath(LinkOption.NOFOLLOW_LINKS)
}
}
catch (ignore: InvalidPathException) {
}
catch (e: IOException) {
// OK. File does not yet exist, so its canonical path will be equal to its original path.
}
return file
}
private fun removeProjectConfigurationAndCaches(projectFile: Path) {
try {
if (Files.isRegularFile(projectFile)) {
Files.deleteIfExists(projectFile)
}
else {
Files.newDirectoryStream(projectFile.resolve(Project.DIRECTORY_STORE_FOLDER)).use { directoryStream ->
for (file in directoryStream) {
file!!.delete()
}
}
}
}
catch (ignored: IOException) {
}
try {
getProjectDataPathRoot(projectFile).delete()
}
catch (ignored: IOException) {
}
}
| apache-2.0 | 0a34c18c712ed7a026bee24e468323fc | 38.485 | 147 | 0.707737 | 5.341826 | false | false | false | false |
cdietze/klay | tripleklay/src/main/kotlin/tripleklay/sound/SoundBoard.kt | 1 | 9464 | package tripleklay.sound
import euklid.f.MathUtil
import klay.core.Clock
import klay.core.Platform
import klay.core.Sound
import react.Signal
import react.Value
import tripleklay.util.Interpolator
/**
* Manages sound clips (sfx) and loops (music). Allows for master volume adjustment, and applying
* adjusted volume to currently playing loops. The expected usage pattern is to create a separate
* sound board for every collection of sounds that share a single volume control. For example, one
* might create one board for SFX and one board for music so that each could be volume controlled
* (and disabled) separately.
*/
class SoundBoard
/** Creates a sound board which will play sounds via `plat` and connect to `paint`
* to receive per-frame updates. */
(
/** The platform on which this sound board is operating. */
val plat: Platform, paint: Signal<Clock>) {
/** Controls the volume of this sound board. */
var volume: Value<Float> = object : Value<Float>(1f) {
override fun updateAndNotifyIf(value: Float): Float {
return super.updateAndNotifyIf(MathUtil.clamp(value, 0f, 1f))
}
}
/** Controls whether this sound board is muted. When muted, no sounds will play. */
var muted = Value(false)
init {
paint.connect({ clock: Clock ->
update(clock.dt)
})
volume.connect({ volume: Float ->
for (active in _active) active.updateVolume(volume)
})
muted.connect({ muted: Boolean ->
for (active in _active) active.fadeForMute(muted)
})
}
/**
* Creates and returns a clip with the supplied path. This clip will contain its own copy of
* the sound data at the specified path, and thus should be retained by the caller if it will
* be used multiple times before being released. Once all references to this clip are released,
* it will be garbage collected and its sound data unloaded.
*/
fun getClip(path: String): Clip {
return object : ClipImpl() {
override fun path(): String {
return path
}
}
}
/**
* Creates and returns a loop with the supplied path. The loop will contain its own copy of the
* sound data at the specified path, and thus should be retained by the caller if it will be
* used multiple times before being released. Once all references to this loop are released, it
* will be garbage collected and its sound data unloaded.
*/
fun getLoop(path: String): Loop {
return object : LoopImpl() {
override fun path(): String {
return path
}
}
}
protected fun shouldPlay(): Boolean {
return !muted.get() && volume.get() > 0
}
protected fun update(delta: Int) {
// update any active faders
var ii = 0
var ll = _faders.size
while (ii < ll) {
if (_faders[ii].update(delta)) {
_faders.removeAt(ii--)
ll--
}
ii++
}
}
protected abstract inner class ClipImpl : LazySound(), Clip {
override fun preload() {
if (shouldPlay()) prepareSound()
}
override fun play() {
if (shouldPlay()) prepareSound().play()
}
override fun fadeIn(fadeMillis: Float) {
if (shouldPlay()) startFadeIn(fadeMillis)
}
override fun fadeOut(fadeMillis: Float) {
if (shouldPlay()) startFadeOut(fadeMillis)
}
override fun stop() {
if (isPlaying) sound!!.stop()
}
override fun asSound(): Sound {
return object : Sound() {
override fun play(): Boolean {
[email protected]()
return true
}
override fun stop() {
[email protected]()
}
}
}
override fun toString(): String {
return "clip:" + sound!!
}
override fun loadSound(path: String): Sound {
return plat.assets.getSound(path)
}
}
protected abstract inner class LoopImpl : LazySound(), Loop {
fun fadeForMute(muted: Boolean) {
if (muted)
startFadeOut(FADE_DURATION)
else
startFadeIn(FADE_DURATION)
}
override fun play() {
if (!_active.add(this)) return
if (shouldPlay() && !isPlaying) prepareSound().play()
}
override fun fadeIn(fadeMillis: Float) {
if (_active.add(this) && shouldPlay()) startFadeIn(fadeMillis)
}
override fun fadeOut(fadeMillis: Float) {
if (_active.remove(this) && shouldPlay()) startFadeOut(fadeMillis)
}
override fun stop() {
if (_active.remove(this) && isPlaying) sound!!.stop()
}
override fun toString(): String {
return "loop:" + sound!!
}
override fun prepareSound(): Sound {
val sound = super.prepareSound()
sound.setLooping(true)
return sound
}
override fun fadeOutComplete() {
sound!!.release()
sound = null
}
override fun loadSound(path: String): Sound {
return plat.assets.getMusic(path)
}
}
protected abstract inner class LazySound : Playable {
var sound: Sound? = null
override val isPlaying: Boolean
get() = if (sound == null) false else sound!!.isPlaying
override fun setVolume(volume: Float) {
_volume = volume
updateVolume([email protected]())
}
override fun volume(): Float {
return _volume
}
override fun release() {
if (sound != null) {
if (sound!!.isPlaying) sound!!.stop()
sound!!.release()
sound = null
}
}
override fun hashCode(): Int {
return path().hashCode()
}
override fun equals(other: Any?): Boolean {
return if (other === this)
true
else
other != null && other::class == this::class &&
path() == (other as LazySound).path()
}
fun updateVolume(volume: Float) {
if (isPlaying) {
val effectiveVolume = volume * _volume
if (effectiveVolume > 0)
sound!!.setVolume(effectiveVolume)
else
sound!!.stop()
}
}
protected fun startFadeIn(fadeMillis: Float) {
cancelFaders()
if (!isPlaying) prepareSound().play()
sound!!.setVolume(0f) // start at zero, fade in from there
_faders.add(object : Fader() {
override fun update(delta: Int): Boolean {
_elapsed += delta
val vol = Interpolator.Companion.LINEAR.apply(0f, _range, _elapsed.toFloat(), fadeMillis)
updateVolume(vol)
return vol >= _range // we're done when the volume hits the target
}
override fun cancel() {}
protected val _range = volume.get()
protected var _elapsed: Int = 0
})
}
protected fun startFadeOut(fadeMillis: Float) {
cancelFaders()
if (isPlaying)
_faders.add(object : Fader() {
override fun update(delta: Int): Boolean {
_elapsed += delta
val vol = Interpolator.Companion.LINEAR.apply(_start, -_start, _elapsed.toFloat(), fadeMillis)
updateVolume(vol)
if (vol > 0)
return false
else { // we're done when the volume hits zero
fadeOutComplete()
return true
}
}
override fun cancel() {
updateVolume(0f)
fadeOutComplete()
}
protected val _start = volume.get()
protected var _elapsed: Int = 0
})
}
protected fun cancelFaders() {
for (fader in _faders) {
fader.cancel()
}
_faders.clear()
}
protected open fun prepareSound(): Sound {
if (sound == null) {
sound = loadSound(path())
sound!!.prepare()
}
sound!!.setVolume(volume.get() * _volume)
return sound!!
}
protected open fun fadeOutComplete() {}
protected abstract fun loadSound(path: String): Sound
protected abstract fun path(): String
protected var _volume = 1f
}
protected abstract inner class Fader {
abstract fun update(delta: Int): Boolean
abstract fun cancel()
}
protected val _active: MutableSet<LoopImpl> = HashSet()
protected val _faders: MutableList<Fader> = ArrayList()
companion object {
protected val FADE_DURATION = 1000f
}
}
| apache-2.0 | a254adbd9bcb1f2d844b0791140307df | 30.029508 | 118 | 0.525254 | 4.936881 | false | false | false | false |
spotify/heroic | heroic-component/src/main/java/com/spotify/heroic/QueryDateRange.kt | 1 | 2579 | /*
* Copyright (c) 2019 Spotify AB.
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package com.spotify.heroic
import com.fasterxml.jackson.annotation.JsonCreator
import com.fasterxml.jackson.annotation.JsonIgnore
import com.fasterxml.jackson.annotation.JsonSubTypes
import com.fasterxml.jackson.annotation.JsonTypeInfo
import com.spotify.heroic.common.DateRange
import com.spotify.heroic.common.Duration
import com.spotify.heroic.common.TimeUtils
import java.util.concurrent.TimeUnit
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "type")
@JsonSubTypes(
JsonSubTypes.Type(QueryDateRange.Absolute::class, name = "absolute"),
JsonSubTypes.Type(QueryDateRange.Relative::class, name = "relative")
)
interface QueryDateRange {
fun buildDateRange(now: Long): DateRange
fun toDSL(): String
@JsonIgnore fun isEmpty(): Boolean
data class Absolute(val start: Long, val end: Long): QueryDateRange {
override fun buildDateRange(now: Long): DateRange = DateRange(start, end)
override fun toDSL(): String = "($start, $end)"
override fun isEmpty(): Boolean = end - start <= 0
}
data class Relative(val unit: TimeUnit, val value: Long): QueryDateRange {
@JsonCreator
constructor(unit: String, value: Long):
this(TimeUtils.parseTimeUnit(unit).orElse(DEFAULT_UNIT), value)
override fun buildDateRange(now: Long): DateRange = DateRange(start(now, value), now)
override fun isEmpty(): Boolean = value <= 0
override fun toDSL(): String = "($value${Duration.unitSuffix(unit)})"
fun start(now: Long, value: Long): Long = now - TimeUnit.MILLISECONDS.convert(value, unit)
companion object {
@JvmField val DEFAULT_UNIT = TimeUnit.DAYS
}
}
}
| apache-2.0 | 4aa3a3cf00be139d4b5c26a25ec8e1bb | 36.926471 | 98 | 0.721598 | 4.319933 | false | false | false | false |
tateisu/SubwayTooter | app/src/main/java/jp/juggler/subwaytooter/action/Action_Status.kt | 1 | 21106 | package jp.juggler.subwaytooter.action
import android.content.Intent
import androidx.appcompat.app.AlertDialog
import jp.juggler.subwaytooter.ActMain
import jp.juggler.subwaytooter.R
import jp.juggler.subwaytooter.actmain.addColumn
import jp.juggler.subwaytooter.actmain.reloadAccountSetting
import jp.juggler.subwaytooter.actmain.showColumnMatchAccount
import jp.juggler.subwaytooter.api.*
import jp.juggler.subwaytooter.api.entity.EntityId
import jp.juggler.subwaytooter.api.entity.TootScheduled
import jp.juggler.subwaytooter.api.entity.TootStatus
import jp.juggler.subwaytooter.column.*
import jp.juggler.subwaytooter.dialog.ActionsDialog
import jp.juggler.subwaytooter.dialog.DlgConfirm.confirm
import jp.juggler.subwaytooter.dialog.pickAccount
import jp.juggler.subwaytooter.table.AcctColor
import jp.juggler.subwaytooter.table.SavedAccount
import jp.juggler.subwaytooter.util.emptyCallback
import jp.juggler.util.*
import kotlinx.coroutines.CancellationException
import okhttp3.Request
fun ActMain.clickStatusDelete(
accessInfo: SavedAccount,
status: TootStatus?,
) {
status ?: return
AlertDialog.Builder(this)
.setMessage(getString(R.string.confirm_delete_status))
.setNegativeButton(R.string.cancel, null)
.setPositiveButton(R.string.ok) { _, _ -> statusDelete(accessInfo, status.id) }
.show()
}
fun ActMain.clickBookmark(accessInfo: SavedAccount, status: TootStatus, willToast: Boolean) {
if (accessInfo.isPseudo) {
bookmarkFromAnotherAccount(accessInfo, status)
} else {
// トグル動作
val bSet = !status.bookmarked
bookmark(
accessInfo,
status,
CrossAccountMode.SameAccount,
bSet = bSet,
callback = when {
!willToast -> emptyCallback
// 簡略表示なら結果をトースト表示
bSet -> bookmarkCompleteCallback
else -> unbookmarkCompleteCallback
},
)
}
}
fun ActMain.clickFavourite(accessInfo: SavedAccount, status: TootStatus, willToast: Boolean) {
if (accessInfo.isPseudo) {
favouriteFromAnotherAccount(accessInfo, status)
} else {
// トグル動作
val bSet = !status.favourited
favourite(
accessInfo,
status,
CrossAccountMode.SameAccount,
bSet = bSet,
callback = when {
!willToast -> emptyCallback
// 簡略表示なら結果をトースト表示
bSet -> favouriteCompleteCallback
else -> unfavouriteCompleteCallback
},
)
}
}
fun ActMain.clickScheduledToot(accessInfo: SavedAccount, item: TootScheduled, column: Column) {
ActionsDialog()
.addAction(getString(R.string.edit)) {
scheduledPostEdit(accessInfo, item)
}
.addAction(getString(R.string.delete)) {
launchAndShowError {
scheduledPostDelete(accessInfo, item)
column.onScheduleDeleted(item)
showToast(false, R.string.scheduled_post_deleted)
}
}
.show(this)
}
fun ActMain.launchActText(intent: Intent) = arActText.launch(intent)
///////////////////////////////////////////////////////////////
// お気に入りの非同期処理
fun ActMain.favourite(
accessInfo: SavedAccount,
statusArg: TootStatus,
crossAccountMode: CrossAccountMode,
callback: () -> Unit,
bSet: Boolean = true,
) {
launchAndShowError {
if (appState.isBusyFav(accessInfo, statusArg)) {
showToast(false, R.string.wait_previous_operation)
return@launchAndShowError
}
// 必要なら確認を出す
if (accessInfo.isMastodon) {
confirm(
getString(
when (bSet) {
true -> R.string.confirm_favourite_from
else -> R.string.confirm_unfavourite_from
},
AcctColor.getNickname(accessInfo)
),
when (bSet) {
true -> accessInfo.confirm_favourite
else -> accessInfo.confirm_unfavourite
}
) { newConfirmEnabled ->
when (bSet) {
true -> accessInfo.confirm_favourite = newConfirmEnabled
else -> accessInfo.confirm_unfavourite = newConfirmEnabled
}
accessInfo.saveSetting()
reloadAccountSetting(accessInfo)
}
}
//
appState.setBusyFav(accessInfo, statusArg)
// ファボ表示を更新中にする
showColumnMatchAccount(accessInfo)
var resultStatus: TootStatus? = null
val result = runApiTask(
accessInfo,
progressStyle = ApiTask.PROGRESS_NONE
) { client ->
val targetStatus = if (crossAccountMode.isRemote) {
val (result, status) = client.syncStatus(accessInfo, statusArg)
status ?: return@runApiTask result
if (status.favourited) {
return@runApiTask TootApiResult(getString(R.string.already_favourited))
}
status
} else {
statusArg
}
if (accessInfo.isMisskey) {
client.request(
if (bSet) {
"/api/notes/favorites/create"
} else {
"/api/notes/favorites/delete"
},
accessInfo.putMisskeyApiToken().apply {
put("noteId", targetStatus.id.toString())
}
.toPostRequestBuilder()
)?.also { result ->
// 正常レスポンスは 204 no content
// 既にお気に入り済みならエラー文字列に "already favorited" が返る
if (result.response?.code == 204 ||
result.error?.contains("already favorited") == true ||
result.error?.contains("already not favorited") == true
) {
// 成功した
resultStatus = targetStatus.apply { favourited = bSet }
}
}
} else {
client.request(
"/api/v1/statuses/${targetStatus.id}/${if (bSet) "favourite" else "unfavourite"}",
"".toFormRequestBody().toPost()
)?.also { result ->
resultStatus = TootParser(this, accessInfo).status(result.jsonObject)
}
}
}
appState.resetBusyFav(accessInfo, statusArg)
if (result != null) {
when (val newStatus = resultStatus) {
null -> showToast(true, result.error)
else -> {
val oldCount = statusArg.favourites_count
val newCount = newStatus.favourites_count
if (oldCount != null && newCount != null) {
if (accessInfo.isMisskey) {
newStatus.favourited = bSet
}
if (bSet && newStatus.favourited && newCount <= oldCount) {
// 星をつけたのにカウントが上がらないのは違和感あるので、表示をいじる
newStatus.favourites_count = oldCount + 1L
} else if (!bSet && !newStatus.favourited && newCount >= oldCount) {
// 星を外したのにカウントが下がらないのは違和感あるので、表示をいじる
// 0未満にはならない
newStatus.favourites_count =
if (oldCount < 1L) 0L else oldCount - 1L
}
}
for (column in appState.columnList) {
column.findStatus(
accessInfo.apDomain,
newStatus.id
) { account, status ->
// 同タンス別アカウントでもカウントは変化する
status.favourites_count = newStatus.favourites_count
// 同アカウントならfav状態を変化させる
if (accessInfo == account) {
status.favourited = newStatus.favourited
}
true
}
}
callback()
}
}
}
// 結果に関わらず、更新中状態から復帰させる
showColumnMatchAccount(accessInfo)
}
}
// アカウントを選んでお気に入り
fun ActMain.favouriteFromAnotherAccount(
timelineAccount: SavedAccount,
status: TootStatus?,
) {
status ?: return
launchMain {
pickAccount(
bAllowPseudo = false,
bAuto = false,
message = getString(R.string.account_picker_favourite),
accountListArg = accountListNonPseudo(timelineAccount.apDomain)
)?.let { action_account ->
favourite(
action_account,
status,
calcCrossAccountMode(timelineAccount, action_account),
callback = favouriteCompleteCallback
)
}
}
}
////////////////////////////////////////////////////////////////
// お気に入りの非同期処理
fun ActMain.bookmark(
accessInfo: SavedAccount,
statusArg: TootStatus,
crossAccountMode: CrossAccountMode,
callback: () -> Unit,
bSet: Boolean = true,
) {
if (appState.isBusyFav(accessInfo, statusArg)) {
showToast(false, R.string.wait_previous_operation)
return
}
if (accessInfo.isMisskey) {
showToast(false, R.string.misskey_account_not_supported)
return
}
launchAndShowError {
// 必要なら確認を出す
// ブックマークは解除する時だけ確認する
if (!bSet) {
confirm(
getString(
R.string.confirm_unbookmark_from,
AcctColor.getNickname(accessInfo)
),
accessInfo.confirm_unbookmark
) { newConfirmEnabled ->
accessInfo.confirm_unbookmark = newConfirmEnabled
accessInfo.saveSetting()
reloadAccountSetting(accessInfo)
}
}
//
appState.setBusyBookmark(accessInfo, statusArg)
// ファボ表示を更新中にする
showColumnMatchAccount(accessInfo)
var resultStatus: TootStatus? = null
val result = runApiTask(accessInfo, progressStyle = ApiTask.PROGRESS_NONE) { client ->
val targetStatus = if (crossAccountMode.isRemote) {
val (result, status) = client.syncStatus(accessInfo, statusArg)
status ?: return@runApiTask result
if (status.bookmarked) {
return@runApiTask TootApiResult(getString(R.string.already_bookmarked))
}
status
} else {
statusArg
}
client.request(
"/api/v1/statuses/${targetStatus.id}/${if (bSet) "bookmark" else "unbookmark"}",
"".toFormRequestBody().toPost()
)?.also { result ->
resultStatus = TootParser(this, accessInfo).status(result.jsonObject)
}
}
appState.resetBusyBookmark(accessInfo, statusArg)
if (result != null) {
when (val newStatus = resultStatus) {
null -> showToast(true, result.error)
else -> {
for (column in appState.columnList) {
column.findStatus(
accessInfo.apDomain,
newStatus.id
) { account, status ->
// 同アカウントならブックマーク状態を伝播する
if (accessInfo == account) {
status.bookmarked = newStatus.bookmarked
}
true
}
}
callback()
}
}
}
// 結果に関わらず、更新中状態から復帰させる
showColumnMatchAccount(accessInfo)
}
}
// アカウントを選んでブックマーク
fun ActMain.bookmarkFromAnotherAccount(
timelineAccount: SavedAccount,
status: TootStatus?,
) {
status ?: return
launchMain {
pickAccount(
bAllowPseudo = false,
bAuto = false,
message = getString(R.string.account_picker_bookmark),
accountListArg = accountListNonPseudo(timelineAccount.apDomain)
)?.let { action_account ->
bookmark(
action_account,
status,
calcCrossAccountMode(timelineAccount, action_account),
callback = bookmarkCompleteCallback
)
}
}
}
///////////////////////////////////////////////////////////////
fun ActMain.statusDelete(
accessInfo: SavedAccount,
statusId: EntityId,
) {
launchMain {
runApiTask(accessInfo) { client ->
if (accessInfo.isMisskey) {
client.request(
"/api/notes/delete",
accessInfo.putMisskeyApiToken().apply {
put("noteId", statusId)
}
.toPostRequestBuilder()
)
// 204 no content
} else {
client.request(
"/api/v1/statuses/$statusId",
Request.Builder().delete()
)
}
}?.let { result ->
if (result.jsonObject != null) {
showToast(false, R.string.delete_succeeded)
for (column in appState.columnList) {
column.onStatusRemoved(accessInfo.apDomain, statusId)
}
} else {
showToast(false, result.error)
}
}
}
}
////////////////////////////////////////
// profile pin
fun ActMain.statusPin(
accessInfo: SavedAccount,
status: TootStatus?,
bSet: Boolean,
) {
status ?: return
launchMain {
var resultStatus: TootStatus? = null
runApiTask(
accessInfo,
progressPrefix = getString(R.string.profile_pin_progress)
) { client ->
client.request(
"/api/v1/statuses/${status.id}/${if (bSet) "pin" else "unpin"}",
"".toFormRequestBody().toPost()
)?.also { result ->
resultStatus = TootParser(this, accessInfo).status(result.jsonObject)
}
}?.let { result ->
when (val newStatus = resultStatus) {
null -> showToast(true, result.error)
else -> {
for (column in appState.columnList) {
if (accessInfo == column.accessInfo) {
column.findStatus(
accessInfo.apDomain,
newStatus.id
) { _, status ->
status.pinned = bSet
true
}
}
}
showColumnMatchAccount(accessInfo)
}
}
}
}
}
// 投稿画面を開く。初期テキストを指定する
fun ActMain.statusRedraft(
accessInfo: SavedAccount,
status: TootStatus?,
) {
status ?: return
completionHelper.closeAcctPopup()
when {
accessInfo.isMisskey ->
openActPostImpl(
accessInfo.db_id,
redraftStatus = status,
replyStatus = status.reply
)
status.in_reply_to_id == null ->
openActPostImpl(
accessInfo.db_id,
redraftStatus = status
)
else -> launchMain {
var resultStatus: TootStatus? = null
runApiTask(accessInfo) { client ->
client.request("/api/v1/statuses/${status.in_reply_to_id}")
?.also { resultStatus = TootParser(this, accessInfo).status(it.jsonObject) }
}?.let { result ->
when (val replyStatus = resultStatus) {
null -> showToast(
true,
"${getString(R.string.cant_sync_toot)} : ${result.error ?: "(no information)"}"
)
else -> openActPostImpl(
accessInfo.db_id,
redraftStatus = status,
replyStatus = replyStatus
)
}
}
}
}
}
// 投稿画面を開く。初期テキストを指定する
fun ActMain.statusEdit(
accessInfo: SavedAccount,
status: TootStatus?,
) {
status ?: return
completionHelper.closeAcctPopup()
when {
accessInfo.isMisskey ->
openActPostImpl(
accessInfo.db_id,
editStatus = status,
replyStatus = status.reply
)
status.in_reply_to_id == null ->
openActPostImpl(
accessInfo.db_id,
editStatus = status
)
else -> launchMain {
var resultStatus: TootStatus? = null
runApiTask(accessInfo) { client ->
client.request("/api/v1/statuses/${status.in_reply_to_id}")
?.also { resultStatus = TootParser(this, accessInfo).status(it.jsonObject) }
}?.let { result ->
when (val replyStatus = resultStatus) {
null -> showToast(
true,
"${getString(R.string.cant_sync_toot)} : ${result.error ?: "(no information)"}"
)
else -> openActPostImpl(
accessInfo.db_id,
editStatus = status,
replyStatus = replyStatus
)
}
}
}
}
}
suspend fun ActMain.scheduledPostDelete(
accessInfo: SavedAccount,
item: TootScheduled,
bConfirmed: Boolean = false,
) {
if (!bConfirmed) {
confirm(R.string.scheduled_status_delete_confirm)
}
val result = runApiTask(accessInfo) { client ->
client.request(
"/api/v1/scheduled_statuses/${item.id}",
Request.Builder().delete()
)
} ?: throw CancellationException("scheduledPostDelete cancelled.")
result.error?.notEmpty()?.let { error(it) }
}
fun ActMain.scheduledPostEdit(
accessInfo: SavedAccount,
item: TootScheduled,
) {
launchMain {
var resultStatus: TootStatus? = null
runApiTask(accessInfo) { client ->
val replyStatusId = item.inReplyToId ?: return@runApiTask TootApiResult()
client.request("/api/v1/statuses/$replyStatusId")?.also { result ->
resultStatus = TootParser(this, accessInfo).status(result.jsonObject)
}
}?.let { result ->
when (val error = result.error) {
null -> openActPostImpl(
accessInfo.db_id,
scheduledStatus = item,
replyStatus = resultStatus
)
else -> showToast(true, error)
}
}
}
}
// アカウントを選んでタイムラインカラムを追加
fun ActMain.openStatusHistory(
pos: Int,
accessInfo: SavedAccount,
status: TootStatus,
) {
addColumn(pos, accessInfo, ColumnType.STATUS_HISTORY, status.id, status.json)
}
| apache-2.0 | fb5214a7e5963147aea910099924f601 | 31.737105 | 103 | 0.490333 | 4.930934 | false | false | false | false |
sreich/ore-infinium | core/src/com/ore/infinium/components/LightComponent.kt | 1 | 1801 | /**
MIT License
Copyright (c) 2016 Shaun Reich <[email protected]>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
package com.ore.infinium.components
import com.artemis.Component
import com.ore.infinium.systems.server.TileLightingSystem.Companion.MAX_TILE_LIGHT_LEVEL
import com.ore.infinium.util.ExtendedComponent
class LightComponent : Component(), ExtendedComponent<LightComponent> {
var radius = 0
set(value) {
assert(value <= MAX_TILE_LIGHT_LEVEL) {
"out of range light level ($value/$MAX_TILE_LIGHT_LEVEL) given for light component"
}
field = value
}
override fun copyFrom(other: LightComponent) {
this.radius = other.radius
}
override fun canCombineWith(other: LightComponent) =
radius == other.radius
}
| mit | 57cc0b4e21c88befd9de6a4103b7875c | 37.319149 | 99 | 0.749028 | 4.4801 | false | false | false | false |
zbeboy/ISY | src/main/java/top/zbeboy/isy/web/data/building/BuildingController.kt | 1 | 9909 | package top.zbeboy.isy.web.data.building
import org.springframework.stereotype.Controller
import org.springframework.ui.ModelMap
import org.springframework.util.ObjectUtils
import org.springframework.util.StringUtils
import org.springframework.validation.BindingResult
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RequestMethod
import org.springframework.web.bind.annotation.RequestParam
import org.springframework.web.bind.annotation.ResponseBody
import top.zbeboy.isy.domain.tables.pojos.Building
import top.zbeboy.isy.service.data.BuildingService
import top.zbeboy.isy.web.bean.data.building.BuildingBean
import top.zbeboy.isy.web.common.MethodControllerCommon
import top.zbeboy.isy.web.common.PageParamControllerCommon
import top.zbeboy.isy.web.util.AjaxUtils
import top.zbeboy.isy.web.util.DataTablesUtils
import top.zbeboy.isy.web.util.SmallPropsUtils
import top.zbeboy.isy.web.vo.data.building.BuildingVo
import java.util.*
import javax.annotation.Resource
import javax.servlet.http.HttpServletRequest
import javax.validation.Valid
/**
* Created by zbeboy 2017-12-07 .
**/
@Controller
open class BuildingController {
@Resource
open lateinit var buildingService: BuildingService
@Resource
open lateinit var methodControllerCommon: MethodControllerCommon
@Resource
open lateinit var pageParamControllerCommon: PageParamControllerCommon
/**
* 通过院id获取全部楼
*
* @param collegeId 院id
* @return 院下全部楼
*/
@RequestMapping(value = ["/user/buildings"], method = [(RequestMethod.POST)])
@ResponseBody
fun buildings(@RequestParam("collegeId") collegeId: Int): AjaxUtils<Building> {
val ajaxUtils = AjaxUtils.of<Building>()
val buildings = ArrayList<Building>()
val isDel: Byte = 0
val building = Building(0, "请选择楼", isDel, 0)
buildings.add(building)
val buildingRecords = buildingService.findByCollegeIdAndIsDel(collegeId, isDel)
buildingRecords.mapTo(buildings) { Building(it.buildingId, it.buildingName, it.buildingIsDel, it.collegeId) }
return ajaxUtils.success().msg("获取楼数据成功!").listData(buildings)
}
/**
* 楼数据
*
* @return 楼数据页面
*/
@RequestMapping(value = ["/web/menu/data/building"], method = [(RequestMethod.GET)])
fun buildingData(): String {
return "web/data/building/building_data::#page-wrapper"
}
/**
* datatables ajax查询数据
*
* @param request 请求
* @return datatables数据
*/
@RequestMapping(value = ["/web/data/building/data"], method = [(RequestMethod.GET)])
@ResponseBody
fun buildingDatas(request: HttpServletRequest): DataTablesUtils<BuildingBean> {
// 前台数据标题 注:要和前台标题顺序一致,获取order用
val headers = ArrayList<String>()
headers.add("select")
headers.add("building_id")
headers.add("school_name")
headers.add("college_name")
headers.add("building_name")
headers.add("building_is_del")
headers.add("operator")
val dataTablesUtils = DataTablesUtils<BuildingBean>(request, headers)
val records = buildingService.findAllByPage(dataTablesUtils)
var buildingBeens: List<BuildingBean> = ArrayList()
if (!ObjectUtils.isEmpty(records) && records.isNotEmpty) {
buildingBeens = records.into(BuildingBean::class.java)
}
dataTablesUtils.data = buildingBeens
dataTablesUtils.setiTotalRecords(buildingService.countAll().toLong())
dataTablesUtils.setiTotalDisplayRecords(buildingService.countByCondition(dataTablesUtils).toLong())
return dataTablesUtils
}
/**
* 楼数据添加
*
* @return 添加页面
*/
@RequestMapping(value = ["/web/data/building/add"], method = [(RequestMethod.GET)])
fun buildingAdd(modelMap: ModelMap): String {
pageParamControllerCommon.currentUserRoleNameAndCollegeIdNoAdminPageParam(modelMap)
return "web/data/building/building_add::#page-wrapper"
}
/**
* 楼数据编辑
*
* @param id 楼id
* @param modelMap 页面对象
* @return 编辑页面
*/
@RequestMapping(value = ["/web/data/building/edit"], method = [(RequestMethod.GET)])
fun buildingEdit(@RequestParam("id") id: Int, modelMap: ModelMap): String {
val record = buildingService.findByIdRelation(id)
return if (record.isPresent) {
val buildingBean = record.get().into(BuildingBean::class.java)
modelMap.addAttribute("building", buildingBean)
modelMap.addAttribute("collegeId", buildingBean.collegeId)
pageParamControllerCommon.currentUserRoleNamePageParam(modelMap)
"web/data/building/building_edit::#page-wrapper"
} else {
methodControllerCommon.showTip(modelMap, "未查询到相关楼信息")
}
}
/**
* 保存时检验楼名是否重复
*
* @param name 楼名
* @param collegeId 院id
* @return true 合格 false 不合格
*/
@RequestMapping(value = ["/web/data/building/save/valid"], method = [(RequestMethod.POST)])
@ResponseBody
fun saveValid(@RequestParam("buildingName") name: String, @RequestParam(value = "collegeId") collegeId: Int): AjaxUtils<*> {
val buildingName = StringUtils.trimWhitespace(name)
if (StringUtils.hasLength(buildingName)) {
val buildingRecords = buildingService.findByBuildingNameAndCollegeId(buildingName, collegeId)
return if (ObjectUtils.isEmpty(buildingRecords)) {
AjaxUtils.of<Any>().success().msg("楼名不存在")
} else {
AjaxUtils.of<Any>().fail().msg("楼名已存在")
}
}
return AjaxUtils.of<Any>().fail().msg("缺失必要参数")
}
/**
* 检验编辑时楼名重复
*
* @param id 楼id
* @param name 楼名
* @param collegeId 院id
* @return true 合格 false 不合格
*/
@RequestMapping(value = ["/web/data/building/update/valid"], method = [(RequestMethod.POST)])
@ResponseBody
fun updateValid(@RequestParam("buildingId") id: Int, @RequestParam("buildingName") name: String, @RequestParam(value = "collegeId") collegeId: Int): AjaxUtils<*> {
val buildingName = StringUtils.trimWhitespace(name)
if (StringUtils.hasLength(buildingName)) {
val buildingRecords = buildingService.findByBuildingNameAndCollegeIdNeBuildingId(buildingName, id, collegeId)
return if (buildingRecords.isEmpty()) {
AjaxUtils.of<Any>().success().msg("楼名不重复")
} else {
AjaxUtils.of<Any>().fail().msg("楼名重复")
}
}
return AjaxUtils.of<Any>().fail().msg("缺失必要参数")
}
/**
* 保存楼信息
*
* @param buildingVo 楼
* @param bindingResult 检验
* @return true 保存成功 false 保存失败
*/
@RequestMapping(value = ["/web/data/building/save"], method = [(RequestMethod.POST)])
@ResponseBody
fun buildingSave(@Valid buildingVo: BuildingVo, bindingResult: BindingResult): AjaxUtils<*> {
if (!bindingResult.hasErrors()) {
val building = Building()
building.buildingIsDel = if (!ObjectUtils.isEmpty(buildingVo.buildingIsDel) && buildingVo.buildingIsDel == 1.toByte()) {
1
} else {
0
}
building.buildingName = StringUtils.trimWhitespace(buildingVo.buildingName!!)
building.collegeId = buildingVo.collegeId
buildingService.save(building)
return AjaxUtils.of<Any>().success().msg("保存成功")
}
return AjaxUtils.of<Any>().fail().msg("填写信息错误,请检查")
}
/**
* 保存楼更改
*
* @param buildingVo 楼
* @param bindingResult 检验
* @return true 更改成功 false 更改失败
*/
@RequestMapping(value = ["/web/data/building/update"], method = [(RequestMethod.POST)])
@ResponseBody
fun buildingUpdate(@Valid buildingVo: BuildingVo, bindingResult: BindingResult): AjaxUtils<*> {
if (!bindingResult.hasErrors() && !ObjectUtils.isEmpty(buildingVo.buildingId)) {
val building = buildingService.findById(buildingVo.buildingId!!)
if (!ObjectUtils.isEmpty(building)) {
building.buildingIsDel = if (!ObjectUtils.isEmpty(buildingVo.buildingIsDel) && buildingVo.buildingIsDel == 1.toByte()) {
1
} else {
0
}
building.buildingName = StringUtils.trimWhitespace(buildingVo.buildingName!!)
building.collegeId = buildingVo.collegeId
buildingService.update(building)
return AjaxUtils.of<Any>().success().msg("更改成功")
}
}
return AjaxUtils.of<Any>().fail().msg("更改失败")
}
/**
* 批量更改楼状态
*
* @param buildingIds 楼ids
* @param isDel is_del
* @return true注销成功
*/
@RequestMapping(value = ["/web/data/building/update/del"], method = [(RequestMethod.POST)])
@ResponseBody
fun buildingUpdateDel(buildingIds: String, isDel: Byte?): AjaxUtils<*> {
if (StringUtils.hasLength(buildingIds) && SmallPropsUtils.StringIdsIsNumber(buildingIds)) {
buildingService.updateIsDel(SmallPropsUtils.StringIdsToList(buildingIds), isDel)
return AjaxUtils.of<Any>().success().msg("更改楼状态成功")
}
return AjaxUtils.of<Any>().fail().msg("更改楼状态失败")
}
} | mit | e2975bbecb9384533acff7f54876cc00 | 37.457143 | 167 | 0.650356 | 4.309698 | false | false | false | false |
ranmocy/rCaltrain | android/app/src/main/java/me/ranmocy/rcaltrain/ui/StationListAdapter.kt | 1 | 2043 | package me.ranmocy.rcaltrain.ui
import android.content.Context
import android.database.DataSetObserver
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.BaseAdapter
import android.widget.ListAdapter
import android.widget.TextView
import me.ranmocy.rcaltrain.R
import java.util.*
/** Station list adapter. */
class StationListAdapter(context: Context) : BaseAdapter(), ListAdapter {
private val stationNames = ArrayList<String>()
private val observers = ArrayList<DataSetObserver>()
private val layoutInflater: LayoutInflater = LayoutInflater.from(context)
fun setData(data: List<String>) {
stationNames.clear()
stationNames.addAll(data)
notifyDataSetChanged()
}
fun getData(): List<String> {
return stationNames
}
override fun areAllItemsEnabled(): Boolean {
return true
}
override fun isEnabled(position: Int): Boolean {
return true
}
override fun registerDataSetObserver(observer: DataSetObserver) {
observers.add(observer)
}
override fun unregisterDataSetObserver(observer: DataSetObserver) {
observers.remove(observer)
}
override fun getCount(): Int {
return stationNames.size
}
override fun getItem(position: Int): String {
return stationNames[position]
}
override fun getItemId(position: Int): Long {
return position.toLong()
}
override fun hasStableIds(): Boolean {
return false
}
override fun getView(position: Int, convertView: View?, parent: ViewGroup): View {
val view = convertView ?: layoutInflater.inflate(R.layout.station_item, parent, false)
(view as TextView).text = getItem(position)
return view
}
override fun getItemViewType(position: Int): Int {
return 0
}
override fun getViewTypeCount(): Int {
return 1
}
override fun isEmpty(): Boolean {
return stationNames.isEmpty()
}
}
| mit | c9be372f45b24ad6e2cc11ea6d9a4083 | 24.5375 | 94 | 0.683798 | 4.68578 | false | false | false | false |
Jire/Overwatcheat | src/main/kotlin/org/jire/overwatcheat/nativelib/interception/InterceptionStroke.kt | 1 | 1298 | /*
* Free, open-source undetected color cheat for Overwatch!
* Copyright (C) 2017 Thomas G. Nappo
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.jire.overwatcheat.nativelib.interception
import com.sun.jna.Structure
import com.sun.jna.Structure.FieldOrder
@FieldOrder("code", "state", "flags", "rolling", "x", "y", "information")
class InterceptionStroke(
@JvmField var code: Short = 0,
@JvmField var state: Short = 0,
@JvmField var information: Short = 0,
@JvmField var rolling: Short = 0,
@JvmField var x: Int = 0,
@JvmField var y: Int = 0,
@JvmField var flags: Short = 0,
var isInjected: Boolean = false
) : Structure() | agpl-3.0 | bf5f19f5e56afdb67fdc703d19f48bd3 | 37.205882 | 78 | 0.717257 | 3.851632 | false | false | false | false |
peruukki/SimpleCurrencyConverter | app/src/main/java/com/peruukki/simplecurrencyconverter/db/ConverterContract.kt | 1 | 610 | package com.peruukki.simplecurrencyconverter.db
import android.net.Uri
import android.provider.BaseColumns
object ConverterContract {
private val CONTENT_AUTHORITY = "com.peruukki.simplecurrencyconverter"
@JvmField
val BASE_CONTENT_URI = Uri.parse("content://$CONTENT_AUTHORITY")
class ConversionRateEntry : BaseColumns {
companion object {
const val TABLE_NAME = "conversionRates"
const val COLUMN_FIXED_CURRENCY = "fixed"
const val COLUMN_VARIABLE_CURRENCY = "variable"
const val COLUMN_CONVERSION_RATE = "rate"
}
}
}
| mit | 5a4455e3e9bc66311c2820e1160310ff | 26.727273 | 74 | 0.683607 | 4.692308 | false | false | false | false |
akhbulatov/wordkeeper | app/src/main/java/com/akhbulatov/wordkeeper/data/global/local/database/wordcategory/WordCategoryDbModel.kt | 1 | 377 | package com.akhbulatov.wordkeeper.data.global.local.database.wordcategory
import androidx.room.ColumnInfo
import androidx.room.Entity
import androidx.room.PrimaryKey
@Entity(tableName = "categories")
data class WordCategoryDbModel(
@ColumnInfo(name = "name") val name: String
) {
@PrimaryKey(autoGenerate = true)
@ColumnInfo(name = "_id")
var id: Long = 0
}
| apache-2.0 | 910e6e51635dd5a77614e045ee977ad1 | 24.133333 | 73 | 0.745358 | 3.846939 | false | false | false | false |
paplorinc/intellij-community | platform/vcs-impl/src/com/intellij/openapi/vcs/changes/ui/ChangeInfoCalculator.kt | 6 | 1617 | // 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.vcs.changes.Change
private val MODIFIED_FILTER = { it: Change -> it.type == Change.Type.MODIFICATION || it.type == Change.Type.MOVED }
private val NEW_FILTER = { it: Change -> it.type == Change.Type.NEW }
private val DELETED_FILTER = { it: Change -> it.type == Change.Type.DELETED }
class ChangeInfoCalculator : CommitLegendPanel.InfoCalculator {
private var myDisplayedChanges = emptyList<Change>()
private var myIncludedChanges = emptyList<Change>()
override val new get() = myDisplayedChanges.count(NEW_FILTER)
override val modified get() = myDisplayedChanges.count(MODIFIED_FILTER)
override val deleted get() = myDisplayedChanges.count(DELETED_FILTER)
override var unversioned: Int = 0
private set
override val includedNew get() = myIncludedChanges.count(NEW_FILTER)
override val includedModified get() = myIncludedChanges.count(MODIFIED_FILTER)
override val includedDeleted get() = myIncludedChanges.count(DELETED_FILTER)
override var includedUnversioned: Int = 0
private set
@JvmOverloads
fun update(displayedChanges: List<Change>,
includedChanges: List<Change>,
unversionedFilesCount: Int = 0,
includedUnversionedFilesCount: Int = 0) {
myDisplayedChanges = displayedChanges
myIncludedChanges = includedChanges
unversioned = unversionedFilesCount
includedUnversioned = includedUnversionedFilesCount
}
}
| apache-2.0 | 80803dc4175c656d698aaee4041c3e39 | 43.916667 | 140 | 0.750773 | 4.358491 | false | false | false | false |
fedepaol/BikeSharing | app/src/main/java/com/whiterabbit/pisabike/screens/list/StationsListPresenterImpl.kt | 1 | 4044 | package com.whiterabbit.pisabike.screens.list
import android.location.Location
import com.whiterabbit.pisabike.model.Station
import com.whiterabbit.pisabike.schedule.SchedulersProvider
import com.whiterabbit.pisabike.storage.BikesProvider
import pl.charmas.android.reactivelocation.ReactiveLocationProvider
import rx.Observable
import rx.subscriptions.CompositeSubscription
import java.util.concurrent.TimeUnit
import kotlin.comparisons.compareBy
class StationsListPresenterImpl(val provider : BikesProvider,
val schedulers : SchedulersProvider,
val locationProvider : ReactiveLocationProvider) : StationsListPresenter {
var data : ListData? = null
lateinit var subscription : CompositeSubscription
var view : StationsListView? = null
data class ListData(var list : List<Station>,
var location : Location)
override fun attachToView(v: StationsListView) {
view = v
subscription = CompositeSubscription()
val sub = allStationsObservable().subscribe { d -> data = d
onStationsUpdate(d.list) }
subscription.add(sub)
val sub1 = v.getStationSelectedObservable().subscribeOn(schedulers.provideMainThreadScheduler())
.observeOn(schedulers.provideMainThreadScheduler())
.subscribe { s -> view?.displayStationOnMap(s)}
subscription.add(sub1)
val sub2 = v.preferredToggledObservable()
.subscribeOn(schedulers.provideBackgroundScheduler())
.flatMap { station -> provider.changePreferredStatus(station.name, !station.isFavourite) }
.observeOn(schedulers.provideBackgroundScheduler())
.subscribe({} ,
{_ : Throwable -> run {} })
subscription.add(sub2)
}
fun filterStation(s : Station, t : String) : Boolean {
if (t.equals("")) {
return true
}
val lowerName = s.name.toLowerCase()
val lowerAddress = s.name.toLowerCase()
val lowerText = t.toLowerCase()
return lowerName.contains(lowerText) || lowerAddress.contains(lowerText)
}
private fun allStationsObservable() : Observable<ListData> {
val stationsObservable = provider.stationsObservables
val textObservable = Observable.just("")
.concatWith(view?.searchStationObservable()?.debounce(400, TimeUnit.MILLISECONDS))
val filteredStations : Observable<List<Station>>
if (textObservable != null) {
filteredStations = Observable.combineLatest(stationsObservable,
textObservable,
{ s: List<Station>, t: String -> Pair(s, t) })
.map { (first, second) -> first.filter { s -> filterStation(s, second) } }
} else {
filteredStations = Observable.just(emptyList())
}
return Observable.combineLatest(locationProvider.lastKnownLocation.take(1),
filteredStations,
{ l: Location, stations: List<Station> ->
ListData(stations, l)
})
}
override fun detachFromView() {
subscription.unsubscribe()
view = null
}
fun onStationsUpdate(stations : List<Station>) {
val toDisplay = stations.sortedBy { it.getDistanceFrom(data?.location) }
view?.displayStations(toDisplay, data?.location)
}
override fun onSearchButtonPressed() {
view?.displaySearchBar(true)
view?.displaySearchFab(false)
}
override fun onSearchEnabled(enabled: Boolean) {
if (!enabled) {
view?.displaySearchBar(false)
view?.displaySearchFab(true)
}
}
}
| gpl-3.0 | c44d40de96e514014f4e53ffad04776a | 37.884615 | 111 | 0.59545 | 5.399199 | false | false | false | false |
RuneSuite/client | plugins-dev/src/main/java/org/runestar/client/plugins/dev/PrayerDebug.kt | 1 | 1031 | package org.runestar.client.plugins.dev
import org.runestar.client.api.plugins.DisposablePlugin
import org.runestar.client.api.Fonts
import org.runestar.client.api.game.EnumId
import org.runestar.client.api.game.live.Canvas
import org.runestar.client.api.game.live.Enums
import org.runestar.client.api.game.live.Prayers
import org.runestar.client.api.plugins.PluginSettings
import java.awt.Color
class PrayerDebug : DisposablePlugin<PluginSettings>() {
override val defaultSettings = PluginSettings()
override fun onStart() {
add(Canvas.repaints.subscribe { g ->
val x = 5
var y = 40
g.font = Fonts.PLAIN_12
g.color = Color.WHITE
val strings = ArrayList<String>()
val prayers = Enums[EnumId.PRAYER_NAMES].keys
prayers.filter { Prayers.enabled[it] }.mapTo(strings) { Prayers.name(it) }
strings.forEach { s ->
g.drawString(s, x, y)
y += g.font.size + 5
}
})
}
} | mit | f372ea51feabc9e2a3b6714ebfd7fc05 | 32.290323 | 86 | 0.645005 | 3.790441 | false | false | false | false |
dkhmelenko/draw2fashion | app/src/main/java/org/hackzurich2017/draw2fashion/PickupFragment.kt | 1 | 8233 | package org.hackzurich2017.draw2fashion
import android.Manifest
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Bundle
import android.os.Environment
import android.provider.MediaStore
import android.support.v4.app.ActivityCompat
import android.support.v4.app.Fragment
import android.support.v4.content.ContextCompat
import android.support.v4.content.FileProvider
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import kotlinx.android.synthetic.main.activity_main_alternative.*
import org.hackzurich2017.draw2fashion.draw2fashion.R
import java.io.*
import java.text.SimpleDateFormat
import java.util.*
/**
* A simple [Fragment] subclass.
* Activities that contain this fragment must implement the
* [PickupFragment.OnFragmentInteractionListener] interface
* to handle interaction events.
* Use the [PickupFragment.newInstance] factory method to
* create an instance of this fragment.
*/
class PickupFragment : Fragment() {
private val CAMERA_REQUEST_CODE = 1
private var listener: OnFragmentInteractionListener? = null
var currentPhotoPath: String? = null
override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?,
savedInstanceState: Bundle?): View? {
// Inflate the layout for this fragment
return inflater!!.inflate(R.layout.activity_main_alternative, container, false)
}
override fun onViewCreated(view: View?, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
takeImage.setOnClickListener { takePicture() }
openGalery.setOnClickListener { pickFromGalery() }
}
override fun onAttach(context: Context?) {
super.onAttach(context)
if (context is OnFragmentInteractionListener) {
listener = context
} else {
throw RuntimeException(context!!.toString() + " must implement OnFragmentInteractionListener")
}
}
override fun onDetach() {
super.onDetach()
listener = null
}
private fun takePicture() {
if (ContextCompat.checkSelfPermission(activity, Manifest.permission.CAMERA)
!= PackageManager.PERMISSION_GRANTED) {
// Should we show an explanation?
if (ActivityCompat.shouldShowRequestPermissionRationale(activity,
Manifest.permission.CAMERA)) {
Toast.makeText(activity, "Enable camera permission first", Toast.LENGTH_SHORT).show()
} else {
ActivityCompat.requestPermissions(activity,
arrayOf(Manifest.permission.CAMERA), CAMERA_REQUEST_CODE);
}
} else {
doStartTakePicture()
}
}
private fun doStartTakePicture() {
val takePictureIntent = Intent(MediaStore.ACTION_IMAGE_CAPTURE);
// Ensure that there's a camera activity to handle the intent
if (takePictureIntent.resolveActivity(activity.packageManager) != null) {
// Create the File where the photo should go
var photoFile: File? = null
try {
photoFile = createImageFile();
} catch (e: IOException) {
e.printStackTrace()
}
// Continue only if the File was successfully created
if (photoFile != null) {
val photoURI = FileProvider.getUriForFile(activity, "com.example.android.fileprovider",
photoFile)
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI)
startActivityForResult(takePictureIntent, 0)
}
}
}
private fun copyFile(uri: Uri): File {
var out: OutputStream?
val timeStamp = SimpleDateFormat("yyyyMMdd_HHmmss").format(Date());
val imageFileName = "JPEG_" + timeStamp + "_";
val storageDir = activity.getExternalFilesDir(Environment.DIRECTORY_PICTURES);
val image = File.createTempFile(
imageFileName,
".jpg",
storageDir
)
out = FileOutputStream(image);
val iStream = activity.contentResolver.openInputStream(uri)
val inputData = getBytes(iStream)
out.write(inputData);
out.close()
currentPhotoPath = image.getAbsolutePath();
return image
}
fun getBytes(inputStream: InputStream): ByteArray {
val byteBuffer = ByteArrayOutputStream()
val bufferSize = 1024
val buffer = ByteArray(bufferSize)
var len = 0
while (len != -1) {
len = inputStream.read(buffer)
if (len == -1) {
break
}
byteBuffer.write(buffer, 0, len)
}
return byteBuffer.toByteArray()
}
private fun pickFromGalery() {
val pickPhoto = Intent(Intent.ACTION_PICK,
MediaStore.Images.Media.EXTERNAL_CONTENT_URI)
startActivityForResult(pickPhoto, 1)//one can be replaced with any action code
}
override fun onRequestPermissionsResult(requestCode: Int,
permissions: Array<String>, grantResults: IntArray) {
when (requestCode) {
CAMERA_REQUEST_CODE -> {
// If request is cancelled, the result arrays are empty.
if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
doStartTakePicture()
} else {
Toast.makeText(activity, "Enable camera permission first", Toast.LENGTH_SHORT).show()
}
return
}
}
}
private fun createImageFile(): File {
// Create an image file name
val timeStamp = SimpleDateFormat("yyyyMMdd_HHmmss").format(Date());
val imageFileName = "JPEG_" + timeStamp + "_";
val storageDir = activity.getExternalFilesDir(Environment.DIRECTORY_PICTURES);
val image = File.createTempFile(
imageFileName,
".jpg",
storageDir
)
// Save a file: path for use with ACTION_VIEW intents
currentPhotoPath = image.getAbsolutePath();
return image;
}
override fun onActivityResult(requestCode: Int, resultCode: Int, imageReturnedIntent: Intent?) {
super.onActivityResult(requestCode, resultCode, imageReturnedIntent)
when (requestCode) {
0 -> if (resultCode == Activity.RESULT_OK) {
emptyView.visibility = View.GONE
val f = File(currentPhotoPath)
imageView.setImageURI(Uri.fromFile(f))
goToProducts()
}
1 -> if (resultCode == Activity.RESULT_OK) {
emptyView.visibility = View.GONE
val selectedImage = imageReturnedIntent?.data
imageView.setImageURI(selectedImage)
copyFile(selectedImage!!)
goToProducts()
}
}
}
private fun goToProducts() {
val intent = Intent(activity, ProductsActivity::class.java)
intent.putExtra(PRODUCTS_FILE_PATH, currentPhotoPath)
startActivity(intent)
}
/**
* This interface must be implemented by activities that contain this
* fragment to allow an interaction in this fragment to be communicated
* to the activity and potentially other fragments contained in that
* activity.
*
*
* See the Android Training lesson [Communicating with Other Fragments](http://developer.android.com/training/basics/fragments/communicating.html) for more information.
*/
interface OnFragmentInteractionListener {
fun onPickupAction(uri: Uri)
}
companion object {
fun newInstance(): PickupFragment {
val fragment = PickupFragment()
val args = Bundle()
fragment.arguments = args
return fragment
}
}
}// Required empty public constructor
| apache-2.0 | 8cc1e94bcc809443666de308a9b93534 | 33.020661 | 172 | 0.627353 | 5.297941 | false | false | false | false |
JetBrains/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/ReplaceAssociateFunctionInspection.kt | 1 | 10973 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.inspections
import com.intellij.codeInspection.LocalQuickFix
import com.intellij.codeInspection.ProblemDescriptor
import com.intellij.codeInspection.ProblemHighlightType
import com.intellij.codeInspection.ProblemHighlightType.GENERIC_ERROR_OR_WARNING
import com.intellij.codeInspection.ProblemHighlightType.INFORMATION
import com.intellij.codeInspection.ProblemsHolder
import com.intellij.openapi.project.Project
import org.jetbrains.kotlin.builtins.KotlinBuiltIns
import org.jetbrains.kotlin.config.LanguageVersion
import org.jetbrains.kotlin.descriptors.ValueParameterDescriptor
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.base.projectStructure.languageVersionSettings
import org.jetbrains.kotlin.idea.caches.resolve.analyze
import org.jetbrains.kotlin.idea.core.getLastLambdaExpression
import org.jetbrains.kotlin.idea.inspections.AssociateFunction.*
import org.jetbrains.kotlin.idea.intentions.callExpression
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.allChildren
import org.jetbrains.kotlin.psi.psiUtil.anyDescendantOfType
import org.jetbrains.kotlin.psi.psiUtil.getStrictParentOfType
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.calls.util.getResolvedCall
import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameSafe
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
import org.jetbrains.kotlin.idea.codeinsight.api.classic.inspections.AbstractKotlinInspection
class ReplaceAssociateFunctionInspection : AbstractKotlinInspection() {
companion object {
private val associateFunctionNames = listOf("associate", "associateTo")
private val associateFqNames = listOf(FqName("kotlin.collections.associate"), FqName("kotlin.sequences.associate"))
private val associateToFqNames = listOf(FqName("kotlin.collections.associateTo"), FqName("kotlin.sequences.associateTo"))
fun getAssociateFunctionAndProblemHighlightType(
dotQualifiedExpression: KtDotQualifiedExpression,
context: BindingContext = dotQualifiedExpression.analyze(BodyResolveMode.PARTIAL)
): Pair<AssociateFunction, ProblemHighlightType>? {
val callExpression = dotQualifiedExpression.callExpression ?: return null
val lambda = callExpression.lambda() ?: return null
if (lambda.valueParameters.size > 1) return null
val functionLiteral = lambda.functionLiteral
if (functionLiteral.anyDescendantOfType<KtReturnExpression> { it.labelQualifier != null }) return null
val lastStatement = functionLiteral.lastStatement() ?: return null
val (keySelector, valueTransform) = lastStatement.pair(context) ?: return null
val lambdaParameter = context[BindingContext.FUNCTION, functionLiteral]?.valueParameters?.singleOrNull() ?: return null
return when {
keySelector.isReferenceTo(lambdaParameter, context) -> {
val receiver =
dotQualifiedExpression.receiverExpression.getResolvedCall(context)?.resultingDescriptor?.returnType ?: return null
if ((KotlinBuiltIns.isArray(receiver) || KotlinBuiltIns.isPrimitiveArray(receiver)) &&
dotQualifiedExpression.languageVersionSettings.languageVersion < LanguageVersion.KOTLIN_1_4
) return null
ASSOCIATE_WITH to GENERIC_ERROR_OR_WARNING
}
valueTransform.isReferenceTo(lambdaParameter, context) ->
ASSOCIATE_BY to GENERIC_ERROR_OR_WARNING
else -> {
if (functionLiteral.bodyExpression?.statements?.size != 1) return null
ASSOCIATE_BY_KEY_AND_VALUE to INFORMATION
}
}
}
private fun KtExpression.isReferenceTo(descriptor: ValueParameterDescriptor, context: BindingContext): Boolean {
return (this as? KtNameReferenceExpression)?.getResolvedCall(context)?.resultingDescriptor == descriptor
}
}
override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean) = dotQualifiedExpressionVisitor(fun(dotQualifiedExpression) {
if (dotQualifiedExpression.languageVersionSettings.languageVersion < LanguageVersion.KOTLIN_1_3) return
val callExpression = dotQualifiedExpression.callExpression ?: return
val calleeExpression = callExpression.calleeExpression ?: return
if (calleeExpression.text !in associateFunctionNames) return
val context = dotQualifiedExpression.analyze(BodyResolveMode.PARTIAL)
val fqName = callExpression.getResolvedCall(context)?.resultingDescriptor?.fqNameSafe ?: return
val isAssociate = fqName in associateFqNames
val isAssociateTo = fqName in associateToFqNames
if (!isAssociate && !isAssociateTo) return
val (associateFunction, highlightType) = getAssociateFunctionAndProblemHighlightType(dotQualifiedExpression, context) ?: return
holder.registerProblemWithoutOfflineInformation(
calleeExpression,
KotlinBundle.message("replace.0.with.1", calleeExpression.text, associateFunction.name(isAssociateTo)),
isOnTheFly,
highlightType,
ReplaceAssociateFunctionFix(associateFunction, isAssociateTo)
)
})
}
class ReplaceAssociateFunctionFix(private val function: AssociateFunction, private val hasDestination: Boolean) : LocalQuickFix {
private val functionName = function.name(hasDestination)
override fun getName() = KotlinBundle.message("replace.with.0", functionName)
override fun getFamilyName() = name
override fun applyFix(project: Project, descriptor: ProblemDescriptor) {
val dotQualifiedExpression = descriptor.psiElement.getStrictParentOfType<KtDotQualifiedExpression>() ?: return
val receiverExpression = dotQualifiedExpression.receiverExpression
val callExpression = dotQualifiedExpression.callExpression ?: return
val lambda = callExpression.lambda() ?: return
val lastStatement = lambda.functionLiteral.lastStatement() ?: return
val (keySelector, valueTransform) = lastStatement.pair() ?: return
val psiFactory = KtPsiFactory(project)
if (function == ASSOCIATE_BY_KEY_AND_VALUE) {
val destination = if (hasDestination) {
callExpression.valueArguments.firstOrNull()?.getArgumentExpression() ?: return
} else {
null
}
val newExpression = psiFactory.buildExpression {
appendExpression(receiverExpression)
appendFixedText(".")
appendFixedText(functionName)
appendFixedText("(")
if (destination != null) {
appendExpression(destination)
appendFixedText(",")
}
appendLambda(lambda, keySelector)
appendFixedText(",")
appendLambda(lambda, valueTransform)
appendFixedText(")")
}
dotQualifiedExpression.replace(newExpression)
} else {
lastStatement.replace(if (function == ASSOCIATE_WITH) valueTransform else keySelector)
val newExpression = psiFactory.buildExpression {
appendExpression(receiverExpression)
appendFixedText(".")
appendFixedText(functionName)
val valueArgumentList = callExpression.valueArgumentList
if (valueArgumentList != null) {
appendValueArgumentList(valueArgumentList)
}
if (callExpression.lambdaArguments.isNotEmpty()) {
appendLambda(lambda)
}
}
dotQualifiedExpression.replace(newExpression)
}
}
private fun BuilderByPattern<KtExpression>.appendLambda(lambda: KtLambdaExpression, body: KtExpression? = null) {
appendFixedText("{")
lambda.valueParameters.firstOrNull()?.nameAsName?.also {
appendName(it)
appendFixedText("->")
}
if (body != null) {
appendExpression(body)
} else {
lambda.bodyExpression?.allChildren?.let(this::appendChildRange)
}
appendFixedText("}")
}
private fun BuilderByPattern<KtExpression>.appendValueArgumentList(valueArgumentList: KtValueArgumentList) {
appendFixedText("(")
valueArgumentList.arguments.forEachIndexed { index, argument ->
if (index > 0) appendFixedText(",")
appendExpression(argument.getArgumentExpression())
}
appendFixedText(")")
}
companion object {
fun replaceLastStatementForAssociateFunction(callExpression: KtCallExpression, function: AssociateFunction) {
val lastStatement = callExpression.lambda()?.functionLiteral?.lastStatement() ?: return
val (keySelector, valueTransform) = lastStatement.pair() ?: return
lastStatement.replace(if (function == ASSOCIATE_WITH) valueTransform else keySelector)
}
}
}
enum class AssociateFunction(val functionName: String) {
ASSOCIATE_WITH("associateWith"), ASSOCIATE_BY("associateBy"), ASSOCIATE_BY_KEY_AND_VALUE("associateBy");
fun name(hasDestination: Boolean): String {
return if (hasDestination) "${functionName}To" else functionName
}
}
private fun KtCallExpression.lambda(): KtLambdaExpression? {
return lambdaArguments.singleOrNull()?.getArgumentExpression() as? KtLambdaExpression ?: getLastLambdaExpression()
}
private fun KtFunctionLiteral.lastStatement(): KtExpression? {
return bodyExpression?.statements?.lastOrNull()
}
private fun KtExpression.pair(context: BindingContext = analyze(BodyResolveMode.PARTIAL)): Pair<KtExpression, KtExpression>? {
return when (this) {
is KtBinaryExpression -> {
if (operationReference.text != "to") return null
val left = left ?: return null
val right = right ?: return null
left to right
}
is KtCallExpression -> {
if (calleeExpression?.text != "Pair") return null
if (valueArguments.size != 2) return null
if (getResolvedCall(context)?.resultingDescriptor?.containingDeclaration?.fqNameSafe != FqName("kotlin.Pair")) return null
val first = valueArguments[0]?.getArgumentExpression() ?: return null
val second = valueArguments[1]?.getArgumentExpression() ?: return null
first to second
}
else -> return null
}
} | apache-2.0 | 49ba91a6181d4b28c03e8cff213265fa | 48.881818 | 158 | 0.694796 | 5.986361 | false | false | false | false |
allotria/intellij-community | plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/annotator/checkers/ImmutableOptionsAnnotationChecker.kt | 4 | 2176 | // Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.plugins.groovy.annotator.checkers
import com.intellij.codeInsight.AnnotationUtil
import com.intellij.lang.annotation.AnnotationHolder
import com.intellij.lang.annotation.HighlightSeverity
import com.intellij.psi.PsiModifier
import com.intellij.psi.util.PsiTreeUtil
import org.jetbrains.plugins.groovy.GroovyBundle
import org.jetbrains.plugins.groovy.lang.psi.api.auxiliary.modifiers.annotation.GrAnnotation
import org.jetbrains.plugins.groovy.lang.psi.api.auxiliary.modifiers.annotation.GrAnnotationArrayInitializer
import org.jetbrains.plugins.groovy.lang.psi.api.statements.GrField
import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.literals.GrLiteral
import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.GrTypeDefinition
import org.jetbrains.plugins.groovy.transformations.immutable.GROOVY_TRANSFORM_IMMUTABLE_OPTIONS
import org.jetbrains.plugins.groovy.transformations.immutable.KNOWN_IMMUTABLES_OPTION
class ImmutableOptionsAnnotationChecker : CustomAnnotationChecker() {
override fun checkArgumentList(holder: AnnotationHolder, annotation: GrAnnotation): Boolean {
if (GROOVY_TRANSFORM_IMMUTABLE_OPTIONS != annotation.qualifiedName) return false
val containingClass = PsiTreeUtil.getParentOfType(annotation, GrTypeDefinition::class.java) ?: return false
val immutableFieldsList = AnnotationUtil.findDeclaredAttribute(annotation, KNOWN_IMMUTABLES_OPTION)?.value ?: return false
val fields = (immutableFieldsList as? GrAnnotationArrayInitializer)?.initializers ?: return false
for (literal in fields.filterIsInstance<GrLiteral>()) {
val value = literal.value as? String ?: continue
val field = containingClass.findCodeFieldByName(value, false) as? GrField
if (field == null || !field.isProperty || field.hasModifierProperty(PsiModifier.STATIC)) {
holder.newAnnotation(HighlightSeverity.ERROR, GroovyBundle.message("immutable.options.property.not.exist", value)).range(literal).create()
}
}
return false
}
} | apache-2.0 | 509710d5db45b94e3724953c88396378 | 63.029412 | 146 | 0.81296 | 4.600423 | false | false | false | false |
genonbeta/TrebleShot | app/src/main/java/org/monora/uprotocol/client/android/content/ImageStore.kt | 1 | 5981 | /*
* Copyright (C) 2021 Veli Tasalı
*
* 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.monora.uprotocol.client.android.content
import android.content.ContentUris
import android.content.Context
import android.net.Uri
import android.os.Parcelable
import android.provider.MediaStore.Images.Media
import dagger.hilt.android.qualifiers.ApplicationContext
import kotlinx.parcelize.IgnoredOnParcel
import kotlinx.parcelize.Parcelize
import javax.inject.Inject
class ImageStore @Inject constructor(
@ApplicationContext private val context: Context,
) {
fun getBuckets(): List<ImageBucket> {
try {
context.contentResolver.query(
Media.EXTERNAL_CONTENT_URI,
arrayOf(
Media.BUCKET_ID,
Media.BUCKET_DISPLAY_NAME,
Media._ID,
Media.DATE_MODIFIED,
),
null,
null,
"${Media.DATE_MODIFIED} DESC"
)?.use {
if (it.moveToFirst()) {
val idIndex = it.getColumnIndex(Media._ID)
val bucketIdIndex = it.getColumnIndex(Media.BUCKET_ID)
val bucketDisplayNameIndex = it.getColumnIndex(Media.BUCKET_DISPLAY_NAME)
val dateModifiedIndex = it.getColumnIndex(Media.DATE_MODIFIED)
val buckets = mutableMapOf<Long, ImageBucket>()
do {
try {
val bucketId = it.getLong(bucketIdIndex)
if (buckets.containsKey(bucketId)) continue
buckets[bucketId] = ImageBucket(
bucketId,
it.getString(bucketDisplayNameIndex),
it.getLong(dateModifiedIndex),
ContentUris.withAppendedId(Media.EXTERNAL_CONTENT_URI, it.getLong(idIndex))
)
} catch (e: Throwable) {
e.printStackTrace()
}
} while (it.moveToNext())
val result = buckets.values.toMutableList()
result.sortBy { bucket -> bucket.name }
return result
}
}
} catch (e: Throwable) {
e.printStackTrace()
}
return emptyList()
}
fun getImages(bucket: ImageBucket): List<Image> {
try {
context.contentResolver.query(
Media.EXTERNAL_CONTENT_URI,
arrayOf(
Media._ID,
Media.TITLE,
Media.DISPLAY_NAME,
Media.SIZE,
Media.MIME_TYPE,
Media.DATE_MODIFIED,
Media.BUCKET_ID
),
"${Media.BUCKET_ID} = ?",
arrayOf(bucket.id.toString()),
"${Media.DATE_MODIFIED} DESC"
)?.use {
if (it.moveToFirst()) {
val idIndex = it.getColumnIndex(Media._ID)
val titleIndex = it.getColumnIndex(Media.TITLE)
val displayNameIndex = it.getColumnIndex(Media.DISPLAY_NAME)
val sizeIndex = it.getColumnIndex(Media.SIZE)
val mimeTypeIndex = it.getColumnIndex(Media.MIME_TYPE)
val dateModifiedIndex = it.getColumnIndex(Media.DATE_MODIFIED)
val list = ArrayList<Image>(it.count)
do {
try {
val id = it.getLong(idIndex)
val title = it.getString(titleIndex)
val displayName = it.getString(displayNameIndex) ?: title
list.add(
Image(
id,
title,
displayName,
it.getLong(sizeIndex),
it.getString(mimeTypeIndex),
it.getLong(dateModifiedIndex),
ContentUris.withAppendedId(Media.EXTERNAL_CONTENT_URI, id)
)
)
} catch (e: Throwable) {
e.printStackTrace()
}
} while (it.moveToNext())
return list
}
}
} catch (e: Throwable) {
e.printStackTrace()
}
return emptyList()
}
}
@Parcelize
data class ImageBucket(
val id: Long,
val name: String,
val dateModified: Long,
val thumbnailUri: Uri,
) : Parcelable
@Parcelize
data class Image(
val id: Long,
val title: String,
val displayName: String,
val size: Long,
val mimeType: String,
val dateModified: Long,
val uri: Uri,
) : Parcelable {
@IgnoredOnParcel
var isSelected = false
override fun equals(other: Any?): Boolean {
return other is Image && uri == other.uri
}
}
| gpl-2.0 | efeb63cb2a92d30a807c4621905d091b | 34.384615 | 107 | 0.504682 | 5.436364 | false | false | false | false |
leafclick/intellij-community | platform/platform-impl/src/com/intellij/openapi/project/projectLoader.kt | 1 | 4435 | // Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.openapi.project
import com.intellij.diagnostic.Activity
import com.intellij.diagnostic.PluginException
import com.intellij.diagnostic.StartUpMeasurer
import com.intellij.diagnostic.StartUpMeasurer.Activities
import com.intellij.ide.plugins.IdeaPluginDescriptorImpl
import com.intellij.ide.plugins.PluginManagerCore
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.extensions.impl.ExtensionPointImpl
import com.intellij.openapi.extensions.impl.ExtensionsAreaImpl
import com.intellij.openapi.progress.ProcessCanceledException
import com.intellij.openapi.project.impl.ProjectImpl
import com.intellij.openapi.project.impl.ProjectLifecycleListener
import org.jetbrains.annotations.ApiStatus
// Code maybe located in a ProjectImpl, but it is not possible due to non-technical reasons to convert ProjectImpl into modern language.
// Wrap into class as it is not possible to use internal modifier for top-level functions from Java (but we have to reduce scope).
@ApiStatus.Internal
internal class ProjectLoadHelper {
companion object {
@JvmStatic
fun registerComponents(project: ProjectImpl) {
var activity = createActivity(project) { "project ${Activities.REGISTER_COMPONENTS_SUFFIX}" }
// at this point of time plugins are already loaded by application - no need to pass indicator to getLoadedPlugins call
@Suppress("UNCHECKED_CAST")
project.registerComponents(PluginManagerCore.getLoadedPlugins() as List<IdeaPluginDescriptorImpl>, notifyListeners = false)
activity = activity?.endAndStart("projectComponentRegistered")
runHandler(ProjectServiceContainerCustomizer.getEp()) {
it.serviceRegistered(project)
}
activity?.end()
}
@JvmStatic
fun notifyThatComponentCreated(project: ProjectImpl) {
var activity = createActivity(project) { "projectComponentCreated event handling" }
val app = ApplicationManager.getApplication()
@Suppress("DEPRECATION")
app.messageBus.syncPublisher(ProjectLifecycleListener.TOPIC).projectComponentsInitialized(project)
activity = activity?.endAndStart("projectComponentCreated")
runHandler((app.extensionArea as ExtensionsAreaImpl).getExtensionPoint<ProjectServiceContainerInitializedListener>("com.intellij.projectServiceContainerInitializedListener")) {
it.serviceCreated(project)
}
activity?.end()
}
}
}
private val LOG = logger<ProjectImpl>()
private inline fun createActivity(project: ProjectImpl, message: () -> String): Activity? {
return if (project.isDefault || !StartUpMeasurer.isEnabled()) null else StartUpMeasurer.startActivity(message())
}
private inline fun <T : Any> runHandler(ep: ExtensionPointImpl<T>, crossinline executor: (T) -> Unit) {
ep.processWithPluginDescriptor { handler, pluginDescriptor ->
if (pluginDescriptor.pluginId != PluginManagerCore.CORE_ID) {
LOG.error(PluginException("Plugin $pluginDescriptor is not approved to add ${ep.name}", pluginDescriptor.pluginId))
}
try {
executor(handler)
}
catch (e: ProcessCanceledException) {
throw e
}
catch (e: Throwable) {
LOG.error(PluginException(e, pluginDescriptor.pluginId))
}
}
}
/**
* Usage requires IJ Platform team approval (including plugin into white-list).
*/
@ApiStatus.Internal
interface ProjectServiceContainerCustomizer {
companion object {
@JvmStatic
fun getEp(): ExtensionPointImpl<ProjectServiceContainerCustomizer> {
return (ApplicationManager.getApplication().extensionArea as ExtensionsAreaImpl)
.getExtensionPoint("com.intellij.projectServiceContainerCustomizer")
}
}
/**
* Invoked after implementation classes for project's components were determined (and loaded),
* but before components are instantiated.
*/
fun serviceRegistered(project: Project)
}
/**
* Usage requires IJ Platform team approval (including plugin into white-list).
*/
@ApiStatus.Internal
interface ProjectServiceContainerInitializedListener {
/**
* Invoked after implementation classes for project's components were determined (and loaded),
* but before components are instantiated.
*/
fun serviceCreated(project: Project)
} | apache-2.0 | ced9efa7e3d4c55d1a2064cf6e2044d7 | 40.074074 | 182 | 0.769109 | 4.955307 | false | false | false | false |
leafclick/intellij-community | platform/platform-impl/src/com/intellij/credentialStore/credentialPromt.kt | 1 | 4985 | // Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
@file:JvmName("CredentialPromptDialog")
package com.intellij.credentialStore
import com.intellij.ide.passwordSafe.PasswordSafe
import com.intellij.openapi.application.ModalityState
import com.intellij.openapi.application.invokeAndWaitIfNeeded
import com.intellij.openapi.project.Project
import com.intellij.ui.AppIcon
import com.intellij.ui.UIBundle
import com.intellij.ui.components.CheckBox
import com.intellij.ui.components.dialog
import com.intellij.ui.layout.*
import com.intellij.util.text.nullize
import javax.swing.JCheckBox
import javax.swing.JPasswordField
import javax.swing.text.BadLocationException
import javax.swing.text.Segment
/**
* @param project The context project (might be null)
* @param dialogTitle The dialog title
* @param passwordFieldLabel The password field label, describing a resource, for which password is asked
* @param resetPassword if true, the old password is removed from database and new password will be asked.
* @param error The error to show in the dialog
* @return null if dialog was cancelled or password (stored in database or a entered by user)
*/
@JvmOverloads
fun askPassword(project: Project?,
dialogTitle: String,
passwordFieldLabel: String,
attributes: CredentialAttributes,
resetPassword: Boolean = false,
error: String? = null): String? {
return askCredentials(project, dialogTitle, passwordFieldLabel, attributes,
isResetPassword = resetPassword,
error = error,
isCheckExistingBeforeDialog = true)?.credentials?.getPasswordAsString()?.nullize()
}
@JvmOverloads
fun askCredentials(project: Project?,
dialogTitle: String,
passwordFieldLabel: String,
attributes: CredentialAttributes,
isSaveOnOk: Boolean = true,
isCheckExistingBeforeDialog: Boolean = false,
isResetPassword: Boolean = false,
error: String? = null): CredentialRequestResult? {
val store = PasswordSafe.instance
if (isResetPassword) {
store.set(attributes, null)
}
else if (isCheckExistingBeforeDialog) {
store.get(attributes)?.let {
return CredentialRequestResult(it, false)
}
}
return invokeAndWaitIfNeeded(ModalityState.any()) {
val passwordField = JPasswordField()
val rememberCheckBox = RememberCheckBoxState.createCheckBox(toolTip = "The password will be stored between application sessions.")
val panel = panel {
row { label(if (passwordFieldLabel.endsWith(":")) passwordFieldLabel else "$passwordFieldLabel:") }
row { passwordField() }
row { rememberCheckBox() }
}
AppIcon.getInstance().requestAttention(project, true)
if (!dialog(dialogTitle, project = project, panel = panel, focusedComponent = passwordField, errorText = error).showAndGet()) {
return@invokeAndWaitIfNeeded null
}
RememberCheckBoxState.update(rememberCheckBox)
val credentials = Credentials(attributes.userName, passwordField.getTrimmedChars())
if (isSaveOnOk && rememberCheckBox.isSelected) {
store.set(attributes, credentials)
credentials.getPasswordAsString()
}
// for memory only store isRemember is true, because false doesn't matter
return@invokeAndWaitIfNeeded CredentialRequestResult(credentials, isRemember = rememberCheckBox.isSelected)
}
}
data class CredentialRequestResult(val credentials: Credentials, val isRemember: Boolean)
object RememberCheckBoxState {
val isSelected: Boolean
get() = PasswordSafe.instance.isRememberPasswordByDefault
@JvmStatic
fun update(component: JCheckBox) {
PasswordSafe.instance.isRememberPasswordByDefault = component.isSelected
}
fun createCheckBox(toolTip: String?): JCheckBox {
return CheckBox(
UIBundle.message("auth.remember.cb"),
selected = isSelected,
toolTip = toolTip
)
}
}
// do not trim trailing whitespace
fun JPasswordField.getTrimmedChars(): CharArray? {
val doc = document
val size = doc.length
if (size == 0) {
return null
}
val segment = Segment()
try {
doc.getText(0, size, segment)
}
catch (e: BadLocationException) {
return null
}
val chars = segment.array
var startOffset = segment.offset
while (Character.isWhitespace(chars[startOffset])) {
startOffset++
}
// exclusive
var endIndex = segment.count
while (endIndex > startOffset && Character.isWhitespace(chars[endIndex - 1])) {
endIndex--
}
if (startOffset >= endIndex) {
return null
}
else if (startOffset == 0 && endIndex == chars.size) {
return chars
}
val result = chars.copyOfRange(startOffset, endIndex)
chars.fill(0.toChar(), segment.offset, segment.count)
return result
} | apache-2.0 | 1db21b767ce26229bfd5f63334b0336e | 33.386207 | 140 | 0.709529 | 4.738593 | false | false | false | false |
Raizlabs/DBFlow | processor/src/main/kotlin/com/dbflow5/processor/definition/BaseDefinition.kt | 1 | 5844 | package com.dbflow5.processor.definition
import com.dbflow5.processor.ClassNames
import com.dbflow5.processor.DBFlowProcessor
import com.dbflow5.processor.ProcessorManager
import com.dbflow5.processor.utils.hasJavaX
import com.dbflow5.processor.utils.toClassName
import com.dbflow5.processor.utils.toTypeElement
import com.grosner.kpoet.S
import com.grosner.kpoet.`@`
import com.grosner.kpoet.`public final class`
import com.grosner.kpoet.extends
import com.grosner.kpoet.implements
import com.grosner.kpoet.javadoc
import com.grosner.kpoet.typeName
import com.squareup.javapoet.ClassName
import com.squareup.javapoet.ParameterizedTypeName
import com.squareup.javapoet.TypeName
import com.squareup.javapoet.TypeSpec
import javax.lang.model.element.Element
import javax.lang.model.element.ExecutableElement
import javax.lang.model.element.TypeElement
/**
* Description: Holds onto a common-set of fields and provides a common-set of methods to output class files.
*/
abstract class BaseDefinition(
/**
* Original definition element.
*/
val element: Element,
/**
* Optional [TypeElement]. if the [element] passed in is a type.
*/
val typeElement: TypeElement?,
/**
* The resolved [TypeName] for this definition. It may be a return type if [ExecutableElement],
*
*/
val elementTypeName: TypeName?,
val manager: ProcessorManager,
val packageName: String) : TypeDefinition {
/**
* The [ClassName] referring to the type of the definition. This excludes primitives.
*/
var elementClassName: ClassName? = null
var outputClassName: ClassName? = null
private set
/**
* Unqualified name of the [element]. Useful for names of methods, fields, or short type names.
*/
val elementName: String = element.simpleName.toString()
constructor(element: ExecutableElement, processorManager: ProcessorManager) : this(
manager = processorManager,
packageName = processorManager.elements.getPackageOf(element)?.qualifiedName?.toString()
?: "",
element = element,
typeElement = null,
elementTypeName = try {
element.asType().typeName
} catch (i: IllegalArgumentException) {
// unexpected TypeMirror (usually a List). Cannot use for TypeName.
null
}
) {
elementClassName = if (elementTypeName?.isPrimitive == true) null else element.toClassName(manager)
}
constructor(element: Element, processorManager: ProcessorManager,
packageName: String = processorManager.elements.getPackageOf(element)?.qualifiedName?.toString()
?: "") : this(
manager = processorManager,
element = element,
packageName = packageName,
typeElement = element as? TypeElement ?: element.toTypeElement(),
elementTypeName = try {
when (element) {
is ExecutableElement -> element.returnType
else -> element.asType()
}.typeName
} catch (i: IllegalArgumentException) {
processorManager.logError("Found illegal type: ${element.asType()} for ${element.simpleName}")
processorManager.logError("Exception here: $i")
null
}
) {
elementTypeName?.let {
if (!it.isPrimitive) elementClassName = element.toClassName(processorManager)
}
}
constructor(element: TypeElement, processorManager: ProcessorManager) : this(
manager = processorManager,
element = element,
typeElement = element,
packageName = processorManager.elements.getPackageOf(element)?.qualifiedName?.toString()
?: "",
elementTypeName = element.asType().typeName
) {
elementClassName = element.toClassName(processorManager)
}
protected fun setOutputClassName(postfix: String) {
val outputName: String
val elementClassName = elementClassName
if (elementClassName == null) {
when (elementTypeName) {
is ClassName -> outputName = elementTypeName.simpleName()
is ParameterizedTypeName -> {
outputName = elementTypeName.rawType.simpleName()
this.elementClassName = elementTypeName.rawType
}
else -> outputName = elementTypeName.toString()
}
} else {
outputName = elementClassName.simpleName()
}
outputClassName = ClassName.get(packageName, outputName + postfix)
}
protected fun setOutputClassNameFull(fullName: String) {
outputClassName = ClassName.get(packageName, fullName)
}
override val typeSpec: TypeSpec
get() {
if (outputClassName == null) {
manager.logError("$elementTypeName's is missing an outputClassName. Database was " +
"${(this as? EntityDefinition)?.associationalBehavior?.databaseTypeName}")
}
return `public final class`(outputClassName?.simpleName() ?: "") {
if (hasJavaX()) {
addAnnotation(`@`(ClassNames.GENERATED) {
this["value"] = DBFlowProcessor::class.java.canonicalName.toString().S
}.build())
}
extendsClass?.let { extends(it) }
implementsClasses.forEach { implements(it) }
javadoc("This is generated code. Please do not modify")
onWriteDefinition(this)
this
}
}
protected open val extendsClass: TypeName?
get() = null
protected val implementsClasses: Array<TypeName>
get() = arrayOf()
open fun onWriteDefinition(typeBuilder: TypeSpec.Builder) {
}
}
| mit | e80991489af992acf20c1ab8831e4d3d | 34.852761 | 112 | 0.640999 | 5.046632 | false | false | false | false |
rpradal/octo-poker-planning | app/src/main/kotlin/com/octo/mob/planningpoker/list/MainActivity.kt | 1 | 4473 | package com.octo.mob.planningpoker.list
import android.os.Bundle
import android.support.v4.app.ActivityOptionsCompat
import android.support.v4.content.ContextCompat
import android.support.v7.app.AppCompatActivity
import android.support.v7.widget.GridLayoutManager
import android.view.Menu
import android.view.MenuItem
import android.view.MenuItem.SHOW_AS_ACTION_NEVER
import android.widget.ImageView
import com.google.firebase.analytics.FirebaseAnalytics
import com.octo.mob.planningpoker.BuildConfig
import com.octo.mob.planningpoker.R
import com.octo.mob.planningpoker.detail.DetailActivity
import com.octo.mob.planningpoker.list.model.Card
import com.octo.mob.planningpoker.list.model.CardDeck
import com.octo.mob.planningpoker.transversal.AnalyticsSender
import com.octo.mob.planningpoker.transversal.AnalyticsSenderImpl
import kotlinx.android.synthetic.main.activity_main.*
import org.jetbrains.anko.email
class MainActivity : AppCompatActivity() {
companion object {
val GRID_COLUMN_NUMBER = 3
}
private var currentCardType = CardDeck.FIBONACCI
private val cardsAdapter = CardsAdapter(SelectedCardListener())
private lateinit var analyticsSender: AnalyticsSender
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
cardsRecyclerView.layoutManager = GridLayoutManager(this, GRID_COLUMN_NUMBER)
cardsRecyclerView.adapter = cardsAdapter
cardsAdapter.setCards(currentCardType.resourceList)
analyticsSender = AnalyticsSenderImpl(FirebaseAnalytics.getInstance(this), this)
}
override fun onCreateOptionsMenu(menu: Menu?): Boolean {
val sortIcon = ContextCompat.getDrawable(this, R.drawable.ic_view_agenda_white_24dp)
val sortSubMenu = menu?.addSubMenu(Menu.NONE, Menu.NONE, Menu.NONE, R.string.selected_card_transition_name)?.setIcon(sortIcon)
sortSubMenu?.item?.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM)
sortSubMenu?.add(Menu.NONE, R.id.menu_fibonacci, Menu.NONE, R.string.fibonacci_cards)
sortSubMenu?.add(Menu.NONE, R.id.menu_tshirt, Menu.NONE, R.string.tshirt_cards)
menu?.add(Menu.NONE, R.id.menu_feedback, Menu.NONE, R.string.send_feedback)?.setShowAsAction(SHOW_AS_ACTION_NEVER)
return true
}
override fun onPrepareOptionsMenu(menu: Menu?): Boolean {
val fibonacciMenu = menu?.findItem(R.id.menu_fibonacci)
if (currentCardType == CardDeck.FIBONACCI) {
fibonacciMenu?.icon = ContextCompat.getDrawable(this, R.drawable.ic_done_black_24dp)
} else {
fibonacciMenu?.icon = null
}
val tshirtSizeMenu = menu?.findItem(R.id.menu_tshirt)
if (currentCardType == CardDeck.TSHIRT) {
tshirtSizeMenu?.icon = ContextCompat.getDrawable(this, R.drawable.ic_done_black_24dp)
} else {
tshirtSizeMenu?.icon = null
}
return super.onPrepareOptionsMenu(menu)
}
override fun onOptionsItemSelected(item: MenuItem?): Boolean {
when (item?.itemId) {
R.id.menu_tshirt ->
currentCardType = CardDeck.TSHIRT
R.id.menu_fibonacci ->
currentCardType = CardDeck.FIBONACCI
R.id.menu_feedback -> {
analyticsSender.onSendFeedBack()
sendFeedbackEmail()
return true
}
else -> return super.onOptionsItemSelected(item)
}
cardsAdapter.setCards(currentCardType.resourceList)
analyticsSender.onCardDeckChanged(currentCardType)
invalidateOptionsMenu()
return true
}
private fun sendFeedbackEmail() {
val email = getString(R.string.app_feedback_recipient_email)
val subject = getString(R.string.app_feedback_subject_pattern, BuildConfig.VERSION_NAME, BuildConfig.VERSION_CODE)
email(email, subject)
}
inner class SelectedCardListener : CardClickListener {
override fun onClick(card: Card, clickedView: ImageView) {
val transitionName = getString(R.string.selected_card_transition_name)
val options = ActivityOptionsCompat.makeSceneTransitionAnimation(this@MainActivity, clickedView, transitionName)
analyticsSender.onCardSelected(card)
startActivity(DetailActivity.getIntent(this@MainActivity, card.resource), options.toBundle())
}
}
}
| apache-2.0 | 7a38035e852800d2008b5df77c5e9dd7 | 39.663636 | 134 | 0.713168 | 4.305101 | false | false | false | false |
JuliusKunze/kotlin-native | performance/src/main/kotlin/org/jetbrains/ring/ClassListBenchmark.kt | 2 | 3347 | /*
* Copyright 2010-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.ring
open class ClassListBenchmark {
private var _data: ArrayList<Value>? = null
val data: ArrayList<Value>
get() = _data!!
fun setup() {
val list = ArrayList<Value>(BENCHMARK_SIZE)
for (n in classValues(BENCHMARK_SIZE))
list.add(n)
_data = list
}
//Benchmark
fun copy(): List<Value> {
return data.toList()
}
//Benchmark
fun copyManual(): List<Value> {
val list = ArrayList<Value>(data.size)
for (item in data) {
list.add(item)
}
return list
}
//Benchmark
fun filterAndCount(): Int {
return data.filter { filterLoad(it) }.count()
}
//Benchmark
fun filterAndCountWithLambda(): Int {
return data.filter { it.value % 2 == 0 }.count()
}
//Benchmark
fun filterWithLambda(): List<Value> {
return data.filter { it.value % 2 == 0 }
}
//Benchmark
fun mapWithLambda(): List<String> {
return data.map { it.toString() }
}
//Benchmark
fun countWithLambda(): Int {
return data.count { it.value % 2 == 0 }
}
//Benchmark
fun filterAndMapWithLambda(): List<String> {
return data.filter { it.value % 2 == 0 }.map { it.toString() }
}
//Benchmark
fun filterAndMapWithLambdaAsSequence(): List<String> {
return data.asSequence().filter { it.value % 2 == 0 }.map { it.toString() }.toList()
}
//Benchmark
fun filterAndMap(): List<String> {
return data.filter { filterLoad(it) }.map { mapLoad(it) }
}
//Benchmark
fun filterAndMapManual(): ArrayList<String> {
val list = ArrayList<String>()
for (it in data) {
if (filterLoad(it)) {
val value = mapLoad(it)
list.add(value)
}
}
return list
}
//Benchmark
fun filter(): List<Value> {
return data.filter { filterLoad(it) }
}
//Benchmark
fun filterManual(): List<Value> {
val list = ArrayList<Value>()
for (it in data) {
if (filterLoad(it))
list.add(it)
}
return list
}
//Benchmark
fun countFilteredManual(): Int {
var count = 0
for (it in data) {
if (filterLoad(it))
count++
}
return count
}
//Benchmark
fun countFiltered(): Int {
return data.count { filterLoad(it) }
}
//Benchmark
// fun countFilteredLocal(): Int {
// return data.cnt { filterLoad(it) }
// }
//Benchmark
fun reduce(): Int {
return data.fold(0) { acc, it -> if (filterLoad(it)) acc + 1 else acc }
}
}
| apache-2.0 | 05ba9cdd38cb9864ddb51a2a2ab6b9b7 | 23.610294 | 92 | 0.56588 | 4.061893 | false | false | false | false |
salRoid/Filmy | app/src/main/java/tech/salroid/filmy/ui/fragment/SearchFragment.kt | 1 | 3538 | package tech.salroid.filmy.ui.fragment
import android.content.Context
import android.content.Intent
import android.content.res.Configuration
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.inputmethod.InputMethodManager
import androidx.fragment.app.Fragment
import androidx.preference.PreferenceManager
import androidx.recyclerview.widget.GridLayoutManager
import tech.salroid.filmy.ui.activities.MovieDetailsActivity
import tech.salroid.filmy.ui.adapters.SearchResultAdapter
import tech.salroid.filmy.data.local.model.SearchResult
import tech.salroid.filmy.databinding.FragmentSearchBinding
class SearchFragment : Fragment() {
private var _binding: FragmentSearchBinding? = null
private val binding get() = _binding!!
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View {
_binding = FragmentSearchBinding.inflate(inflater, container, false)
val view = binding.root
val sp = PreferenceManager.getDefaultSharedPreferences(requireContext())
//val nightMode = sp.getBoolean("dark", false)
when (activity?.resources?.configuration?.orientation) {
Configuration.ORIENTATION_PORTRAIT -> {
val gridLayoutManager = GridLayoutManager(
context,
3,
)
binding.searchResultsRecycler.layoutManager = gridLayoutManager
}
else -> {
val gridLayoutManager = GridLayoutManager(
context,
5,
)
binding.searchResultsRecycler.layoutManager = gridLayoutManager
}
}
return view
}
private fun itemClicked(searchData: SearchResult, position: Int) {
Intent(activity, MovieDetailsActivity::class.java).run {
putExtra("network_applicable", true)
putExtra("title", searchData.originalTitle)
putExtra("id", searchData.id.toString())
putExtra("activity", false)
startActivity(this)
}
}
fun getSearchedResult(query: String) {
/* NetworkUtil.searchMovies(finalQuery, { searchResultResponse ->
searchResultResponse?.let {
showSearchResults(it.results)
}
}, {
})*/
}
fun showSearchResults(results: List<SearchResult>) {
val adapter = SearchResultAdapter(results) { searchData, position ->
itemClicked(searchData, position)
}
binding.searchResultsRecycler.adapter = adapter
hideProgress()
hideSoftKeyboard()
}
fun showProgress() {
binding.breathingProgress.visibility = View.VISIBLE
binding.searchResultsRecycler.visibility = View.INVISIBLE
}
private fun hideProgress() {
binding.breathingProgress.visibility = View.INVISIBLE
binding.searchResultsRecycler.visibility = View.VISIBLE
}
private fun hideSoftKeyboard() {
if (activity != null && activity?.currentFocus != null) {
val inputMethodManager =
activity?.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
inputMethodManager.hideSoftInputFromWindow(activity?.currentFocus?.windowToken, 0)
}
}
override fun onDestroyView() {
super.onDestroyView()
_binding = null
}
} | apache-2.0 | 4df91258c5c72ceb5d7993a659a2e869 | 32.074766 | 94 | 0.656586 | 5.459877 | false | false | false | false |
AndroidX/androidx | compose/ui/ui/src/skikoMain/kotlin/androidx/compose/ui/platform/SkiaBasedOwner.skiko.kt | 3 | 19058 | /*
* 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("DEPRECATION")
package androidx.compose.ui.platform
import androidx.compose.runtime.collection.mutableVectorOf
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.compose.ui.DefaultPointerButtons
import androidx.compose.ui.ExperimentalComposeUiApi
import androidx.compose.ui.InternalComposeUiApi
import androidx.compose.ui.PrimaryPressedPointerButtons
import androidx.compose.ui.autofill.Autofill
import androidx.compose.ui.autofill.AutofillTree
import androidx.compose.ui.focus.FocusDirection
import androidx.compose.ui.focus.FocusDirection.Companion.In
import androidx.compose.ui.focus.FocusDirection.Companion.Next
import androidx.compose.ui.focus.FocusDirection.Companion.Out
import androidx.compose.ui.focus.FocusDirection.Companion.Previous
import androidx.compose.ui.focus.FocusManager
import androidx.compose.ui.focus.FocusManagerImpl
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.graphics.Canvas
import androidx.compose.ui.graphics.asComposeCanvas
import androidx.compose.ui.input.InputModeManager
import androidx.compose.ui.input.InputModeManagerImpl
import androidx.compose.ui.input.InputMode.Companion.Keyboard
import androidx.compose.ui.input.key.Key.Companion.Back
import androidx.compose.ui.input.key.Key.Companion.DirectionCenter
import androidx.compose.ui.input.key.Key.Companion.Tab
import androidx.compose.ui.input.key.KeyEvent
import androidx.compose.ui.input.key.KeyEventType.Companion.KeyDown
import androidx.compose.ui.input.key.KeyInputModifier
import androidx.compose.ui.input.key.isShiftPressed
import androidx.compose.ui.input.key.key
import androidx.compose.ui.input.key.type
import androidx.compose.ui.input.pointer.PointerEventType
import androidx.compose.ui.input.pointer.PointerIcon
import androidx.compose.ui.input.pointer.PointerIconDefaults
import androidx.compose.ui.input.pointer.PointerIconService
import androidx.compose.ui.input.pointer.PointerInputEvent
import androidx.compose.ui.input.pointer.PointerInputEventProcessor
import androidx.compose.ui.input.pointer.PositionCalculator
import androidx.compose.ui.input.pointer.ProcessResult
import androidx.compose.ui.input.pointer.TestPointerInputEventData
import androidx.compose.ui.layout.RootMeasurePolicy
import androidx.compose.ui.modifier.ModifierLocalManager
import androidx.compose.ui.node.InternalCoreApi
import androidx.compose.ui.node.LayoutNode
import androidx.compose.ui.node.LayoutNodeDrawScope
import androidx.compose.ui.node.MeasureAndLayoutDelegate
import androidx.compose.ui.node.Owner
import androidx.compose.ui.node.OwnerSnapshotObserver
import androidx.compose.ui.node.RootForTest
import androidx.compose.ui.semantics.SemanticsModifierCore
import androidx.compose.ui.semantics.SemanticsOwner
import androidx.compose.ui.text.input.TextInputService
import androidx.compose.ui.text.font.createFontFamilyResolver
import androidx.compose.ui.text.platform.FontLoader
import androidx.compose.ui.unit.Constraints
import androidx.compose.ui.unit.Density
import androidx.compose.ui.unit.IntSize
import androidx.compose.ui.unit.IntOffset
import androidx.compose.ui.unit.IntRect
import androidx.compose.ui.unit.LayoutDirection
import androidx.compose.ui.input.pointer.PointerKeyboardModifiers
private typealias Command = () -> Unit
@OptIn(
ExperimentalComposeUiApi::class,
InternalCoreApi::class,
InternalComposeUiApi::class
)
internal class SkiaBasedOwner(
private val platformInputService: PlatformInput,
private val component: PlatformComponent,
density: Density = Density(1f, 1f),
val isPopup: Boolean = false,
val isFocusable: Boolean = true,
val onDismissRequest: (() -> Unit)? = null,
private val onPreviewKeyEvent: (KeyEvent) -> Boolean = { false },
private val onKeyEvent: (KeyEvent) -> Boolean = { false },
) : Owner, RootForTest, SkiaRootForTest, PositionCalculator {
internal fun isHovered(point: Offset): Boolean {
val intOffset = IntOffset(point.x.toInt(), point.y.toInt())
return bounds.contains(intOffset)
}
internal var accessibilityController: AccessibilityController? = null
internal var bounds by mutableStateOf(IntRect.Zero)
override var density by mutableStateOf(density)
// TODO(demin): support RTL
override val layoutDirection: LayoutDirection = LayoutDirection.Ltr
override val sharedDrawScope = LayoutNodeDrawScope()
private val semanticsModifier = SemanticsModifierCore(
mergeDescendants = false,
clearAndSetSemantics = false,
properties = {}
)
private val _focusManager: FocusManagerImpl = FocusManagerImpl().apply {
// TODO(demin): support RTL [onRtlPropertiesChanged]
layoutDirection = LayoutDirection.Ltr
}
override val focusManager: FocusManager
get() = _focusManager
// TODO: Set the input mode. For now we don't support touch mode, (always in Key mode).
private val _inputModeManager = InputModeManagerImpl(
initialInputMode = Keyboard,
onRequestInputModeChange = {
// TODO: Change the input mode programmatically. For now we just return true if the
// requested input mode is Keyboard mode.
it == Keyboard
}
)
override val inputModeManager: InputModeManager
get() = _inputModeManager
override val modifierLocalManager: ModifierLocalManager = ModifierLocalManager(this)
// TODO: set/clear _windowInfo.isWindowFocused when the window gains/loses focus.
private val _windowInfo: WindowInfoImpl = WindowInfoImpl()
override val windowInfo: WindowInfo
get() = _windowInfo
// TODO(b/177931787) : Consider creating a KeyInputManager like we have for FocusManager so
// that this common logic can be used by all owners.
private val keyInputModifier: KeyInputModifier = KeyInputModifier(
onKeyEvent = {
val focusDirection = getFocusDirection(it)
if (focusDirection == null || it.type != KeyDown) return@KeyInputModifier false
// Consume the key event if we moved focus.
focusManager.moveFocus(focusDirection)
},
onPreviewKeyEvent = null
)
@Suppress("unused") // to be used in JB fork (not all prerequisite changes added yet)
internal fun setCurrentKeyboardModifiers(modifiers: PointerKeyboardModifiers) {
_windowInfo.keyboardModifiers = modifiers
}
var constraints: Constraints = Constraints()
set(value) {
field = value
if (!isPopup) {
this.bounds = IntRect(
IntOffset(bounds.left, bounds.top),
IntSize(constraints.maxWidth, constraints.maxHeight)
)
}
}
override val root = LayoutNode().also {
it.measurePolicy = RootMeasurePolicy
it.modifier = semanticsModifier
.then(_focusManager.modifier)
.then(keyInputModifier)
.then(
KeyInputModifier(
onKeyEvent = onKeyEvent,
onPreviewKeyEvent = onPreviewKeyEvent
)
)
}
override val rootForTest = this
override val snapshotObserver = OwnerSnapshotObserver { command ->
onDispatchCommand?.invoke(command)
}
private val pointerInputEventProcessor = PointerInputEventProcessor(root)
private val measureAndLayoutDelegate = MeasureAndLayoutDelegate(root)
private val endApplyChangesListeners = mutableVectorOf<(() -> Unit)?>()
init {
snapshotObserver.startObserving()
root.attach(this)
_focusManager.takeFocus()
}
fun dispose() {
snapshotObserver.stopObserving()
// we don't need to call root.detach() because root will be garbage collected
}
override val textInputService = TextInputService(platformInputService)
@Deprecated(
"fontLoader is deprecated, use fontFamilyResolver",
replaceWith = ReplaceWith("fontFamilyResolver")
)
override val fontLoader = FontLoader()
override val fontFamilyResolver = createFontFamilyResolver()
override val hapticFeedBack = DefaultHapticFeedback()
override val clipboardManager = PlatformClipboardManager()
override val accessibilityManager = DefaultAccessibilityManager()
override val textToolbar = DefaultTextToolbar()
override val semanticsOwner: SemanticsOwner = SemanticsOwner(root)
override val autofillTree = AutofillTree()
override val autofill: Autofill? get() = null
override val viewConfiguration: ViewConfiguration = DefaultViewConfiguration(density)
override fun sendKeyEvent(keyEvent: KeyEvent): Boolean =
sendKeyEvent(platformInputService, keyInputModifier, keyEvent)
override var showLayoutBounds = false
override fun requestFocus() = true
override fun onAttach(node: LayoutNode) = Unit
override fun onDetach(node: LayoutNode) {
measureAndLayoutDelegate.onNodeDetached(node)
snapshotObserver.clear(node)
needClearObservations = true
}
override val measureIteration: Long get() = measureAndLayoutDelegate.measureIteration
private var needLayout = true
private var needDraw = true
val needRender get() = needLayout || needDraw || needSendSyntheticEvents
var onNeedRender: (() -> Unit)? = null
var onDispatchCommand: ((Command) -> Unit)? = null
fun render(canvas: org.jetbrains.skia.Canvas) {
needLayout = false
measureAndLayout()
sendSyntheticEvents()
needDraw = false
draw(canvas)
clearInvalidObservations()
}
private var needClearObservations = false
private fun clearInvalidObservations() {
if (needClearObservations) {
snapshotObserver.clearInvalidObservations()
needClearObservations = false
}
}
private fun requestLayout() {
needLayout = true
needDraw = true
onNeedRender?.invoke()
}
private fun requestDraw() {
needDraw = true
onNeedRender?.invoke()
}
var contentSize = IntSize.Zero
private set
override fun measureAndLayout(sendPointerUpdate: Boolean) {
measureAndLayoutDelegate.updateRootConstraints(constraints)
if (
measureAndLayoutDelegate.measureAndLayout(
scheduleSyntheticEvents.takeIf { sendPointerUpdate }
)
) {
requestDraw()
}
measureAndLayoutDelegate.dispatchOnPositionedCallbacks()
// Don't use mainOwner.root.width here, as it strictly coerced by [constraints]
contentSize = IntSize(
root.children.maxOfOrNull { it.outerCoordinator.measuredWidth } ?: 0,
root.children.maxOfOrNull { it.outerCoordinator.measuredHeight } ?: 0,
)
}
override fun measureAndLayout(layoutNode: LayoutNode, constraints: Constraints) {
measureAndLayoutDelegate.measureAndLayout(layoutNode, constraints)
measureAndLayoutDelegate.dispatchOnPositionedCallbacks()
}
override fun forceMeasureTheSubtree(layoutNode: LayoutNode) {
measureAndLayoutDelegate.forceMeasureTheSubtree(layoutNode)
}
override fun onRequestMeasure(
layoutNode: LayoutNode,
affectsLookahead: Boolean,
forceRequest: Boolean
) {
if (affectsLookahead) {
if (measureAndLayoutDelegate.requestLookaheadRemeasure(layoutNode, forceRequest)) {
requestLayout()
}
} else if (measureAndLayoutDelegate.requestRemeasure(layoutNode, forceRequest)) {
requestLayout()
}
}
override fun onRequestRelayout(
layoutNode: LayoutNode,
affectsLookahead: Boolean,
forceRequest: Boolean
) {
if (affectsLookahead) {
if (measureAndLayoutDelegate.requestLookaheadRelayout(layoutNode, forceRequest)) {
requestLayout()
}
} else if (measureAndLayoutDelegate.requestRelayout(layoutNode, forceRequest)) {
requestLayout()
}
}
override fun requestOnPositionedCallback(layoutNode: LayoutNode) {
measureAndLayoutDelegate.requestOnPositionedCallback(layoutNode)
requestLayout()
}
override fun createLayer(
drawBlock: (Canvas) -> Unit,
invalidateParentLayer: () -> Unit
) = SkiaLayer(
density,
invalidateParentLayer = {
invalidateParentLayer()
requestDraw()
},
drawBlock = drawBlock,
onDestroy = { needClearObservations = true }
)
override fun onSemanticsChange() {
accessibilityController?.onSemanticsChange()
}
override fun onLayoutChange(layoutNode: LayoutNode) {
accessibilityController?.onLayoutChange(layoutNode)
}
override fun getFocusDirection(keyEvent: KeyEvent): FocusDirection? {
return when (keyEvent.key) {
Tab -> if (keyEvent.isShiftPressed) Previous else Next
DirectionCenter -> In
Back -> Out
else -> null
}
}
override fun calculatePositionInWindow(localPosition: Offset): Offset = localPosition
override fun calculateLocalPosition(positionInWindow: Offset): Offset = positionInWindow
override fun localToScreen(localPosition: Offset): Offset = localPosition
override fun screenToLocal(positionOnScreen: Offset): Offset = positionOnScreen
fun draw(canvas: org.jetbrains.skia.Canvas) {
root.draw(canvas.asComposeCanvas())
}
private var desiredPointerIcon: PointerIcon? = null
private var needSendSyntheticEvents = false
private var lastPointerEvent: PointerInputEvent? = null
private val scheduleSyntheticEvents: () -> Unit = {
// we can't send event synchronously, as we can have call of `measureAndLayout`
// inside the event handler. So we can have a situation when we call event handler inside
// event handler. And that can lead to unpredictable behaviour.
// Nature of synthetic events doesn't require that they should be fired
// synchronously on layout change.
needSendSyntheticEvents = true
onNeedRender?.invoke()
}
// TODO(demin) should we repeat all events, or only which are make sense?
// For example, touch Move after touch Release doesn't make sense,
// and an application can handle it in a wrong way
// Desktop doesn't support touch at the moment, but when it will, we should resolve this.
private fun sendSyntheticEvents() {
if (needSendSyntheticEvents) {
needSendSyntheticEvents = false
val lastPointerEvent = lastPointerEvent
if (lastPointerEvent != null) {
doProcessPointerInput(
PointerInputEvent(
PointerEventType.Move,
lastPointerEvent.uptime,
lastPointerEvent.pointers,
lastPointerEvent.buttons,
lastPointerEvent.keyboardModifiers,
lastPointerEvent.mouseEvent
)
)
}
}
}
internal fun processPointerInput(event: PointerInputEvent): ProcessResult {
measureAndLayout()
sendSyntheticEvents()
desiredPointerIcon = null
lastPointerEvent = event
return doProcessPointerInput(event)
}
private fun doProcessPointerInput(event: PointerInputEvent): ProcessResult {
return pointerInputEventProcessor.process(
event,
this,
isInBounds = event.pointers.all {
it.position.x in 0f..root.width.toFloat() &&
it.position.y in 0f..root.height.toFloat()
}
).also {
if (it.dispatchedToAPointerInputModifier) {
setPointerIcon(component, desiredPointerIcon)
}
}
}
override fun processPointerInput(timeMillis: Long, pointers: List<TestPointerInputEventData>) {
val isPressed = pointers.any { it.down }
processPointerInput(
PointerInputEvent(
PointerEventType.Unknown,
timeMillis,
pointers.map { it.toPointerInputEventData() },
if (isPressed) PrimaryPressedPointerButtons else DefaultPointerButtons
)
)
}
override fun onEndApplyChanges() {
// Listeners can add more items to the list and we want to ensure that they
// are executed after being added, so loop until the list is empty
while (endApplyChangesListeners.isNotEmpty()) {
val size = endApplyChangesListeners.size
for (i in 0 until size) {
val listener = endApplyChangesListeners[i]
// null out the item so that if the listener is re-added then we execute it again.
endApplyChangesListeners[i] = null
listener?.invoke()
}
// Remove all the items that were visited. Removing items shifts all items after
// to the front of the list, so removing in a chunk is cheaper than removing one-by-one
endApplyChangesListeners.removeRange(0, size)
}
}
override fun registerOnEndApplyChangesListener(listener: () -> Unit) {
if (listener !in endApplyChangesListeners) {
endApplyChangesListeners += listener
}
}
override fun registerOnLayoutCompletedListener(listener: Owner.OnLayoutCompletedListener) {
measureAndLayoutDelegate.registerOnLayoutCompletedListener(listener)
requestLayout()
}
override val pointerIconService: PointerIconService =
object : PointerIconService {
override var current: PointerIcon
get() = desiredPointerIcon ?: PointerIconDefaults.Default
set(value) {
desiredPointerIcon = value
}
}
}
internal expect fun sendKeyEvent(
platformInputService: PlatformInput,
keyInputModifier: KeyInputModifier,
keyEvent: KeyEvent
): Boolean
internal expect fun setPointerIcon(
containerCursor: PlatformComponentWithCursor?,
icon: PointerIcon?
)
| apache-2.0 | efdd0efe7698431d5931f7ef73afbaf0 | 35.791506 | 99 | 0.695089 | 5.051153 | false | false | false | false |
pyamsoft/padlock | padlock-service/src/main/java/com/pyamsoft/padlock/service/LockServiceInteractorImpl.kt | 1 | 14428 | /*
* Copyright 2019 Peter Kenji Yamanaka
*
* 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.pyamsoft.padlock.service
import android.content.Context
import androidx.annotation.CheckResult
import com.pyamsoft.padlock.api.database.EntryQueryDao
import com.pyamsoft.padlock.api.lockscreen.LockPassed
import com.pyamsoft.padlock.api.packagemanager.PackageActivityManager
import com.pyamsoft.padlock.api.packagemanager.PackageApplicationManager
import com.pyamsoft.padlock.api.preferences.MasterPinPreferences
import com.pyamsoft.padlock.api.preferences.ServicePreferences
import com.pyamsoft.padlock.api.service.JobSchedulerCompat
import com.pyamsoft.padlock.api.service.LockServiceInteractor
import com.pyamsoft.padlock.api.service.LockServiceInteractor.ForegroundEvent
import com.pyamsoft.padlock.api.service.LockServiceInteractor.ProcessedEventPayload
import com.pyamsoft.padlock.api.service.LockServiceInteractor.ServiceState
import com.pyamsoft.padlock.api.service.LockServiceInteractor.ServiceState.DISABLED
import com.pyamsoft.padlock.api.service.LockServiceInteractor.ServiceState.ENABLED
import com.pyamsoft.padlock.api.service.LockServiceInteractor.ServiceState.PAUSED
import com.pyamsoft.padlock.api.service.LockServiceInteractor.ServiceState.PERMISSION
import com.pyamsoft.padlock.api.service.ScreenStateObserver
import com.pyamsoft.padlock.api.service.UsageEventProvider
import com.pyamsoft.padlock.model.Excludes
import com.pyamsoft.padlock.model.db.PadLockDbModels
import com.pyamsoft.padlock.model.db.PadLockEntryModel
import com.pyamsoft.padlock.model.service.ServicePauseState
import com.pyamsoft.padlock.model.service.ServicePauseState.STARTED
import com.pyamsoft.padlock.service.device.UsagePermissionChecker
import com.pyamsoft.pydroid.core.optional.Optional
import com.pyamsoft.pydroid.core.optional.Optional.Present
import com.pyamsoft.pydroid.core.optional.asOptional
import com.pyamsoft.pydroid.core.threads.Enforcer
import io.reactivex.Flowable
import io.reactivex.Maybe
import io.reactivex.MaybeTransformer
import io.reactivex.Observable
import io.reactivex.ObservableEmitter
import io.reactivex.Single
import io.reactivex.SingleTransformer
import timber.log.Timber
import java.util.concurrent.TimeUnit
import java.util.concurrent.TimeUnit.MILLISECONDS
import javax.inject.Inject
internal class LockServiceInteractorImpl @Inject internal constructor(
private val enforcer: Enforcer,
private val context: Context,
private val screenStateObserver: ScreenStateObserver,
private val usageEventProvider: UsageEventProvider,
private val lockPassed: LockPassed,
private val jobSchedulerCompat: JobSchedulerCompat,
private val packageActivityManager: PackageActivityManager,
private val packageApplicationManager: PackageApplicationManager,
private val queryDao: EntryQueryDao,
private val pinPreferences: MasterPinPreferences,
private val servicePreferences: ServicePreferences
) : LockServiceInteractor {
private var activePackageName = ""
private var activeClassName = ""
private var lastForegroundEvent = ForegroundEvent.EMPTY
override fun init() {
reset()
}
override fun cleanup() {
Timber.d("Cleanup LockService")
jobSchedulerCompat.cancelAll()
reset()
}
private fun reset() {
resetState()
// Also reset last foreground
lastForegroundEvent = ForegroundEvent.EMPTY
}
override fun setPauseState(paused: ServicePauseState) {
servicePreferences.setPaused(paused)
}
@CheckResult
private fun decideServiceEnabledState(): ServiceState {
if (servicePreferences.getPaused() != STARTED) {
Timber.d("Service is paused")
return PAUSED
} else if (UsagePermissionChecker.hasPermission(context)) {
if (pinPreferences.getMasterPassword().isNullOrEmpty()) {
Timber.d("Service is disabled")
return DISABLED
} else {
Timber.d("Service is enabled")
return ENABLED
}
} else {
Timber.d("Service lacks permission")
return PERMISSION
}
}
override fun observeServiceState(): Observable<ServiceState> {
return Observable.defer<ServiceState> {
enforcer.assertNotOnMainThread()
return@defer Observable.create { emitter ->
val usageWatcher = usageEventProvider.watchPermission {
Timber.d("Usage permission changed")
emit(emitter, decideServiceEnabledState())
}
val pausedState = servicePreferences.watchPausedState {
Timber.d("Paused changed")
emit(emitter, decideServiceEnabledState())
}
val masterPinPresence = pinPreferences.watchPinPresence {
Timber.d("Pin presence changed")
emit(emitter, decideServiceEnabledState())
}
emitter.setCancellable {
usageWatcher.stopWatching()
pausedState.stopWatching()
masterPinPresence.stopWatching()
}
enforcer.assertNotOnMainThread()
Timber.d("Watching service state")
// Don't emit an event here or we receive double pause events
}
}
}
override fun isServiceEnabled(): Single<ServiceState> {
return Single.fromCallable {
enforcer.assertNotOnMainThread()
return@fromCallable decideServiceEnabledState()
}
}
override fun clearMatchingForegroundEvent(
packageName: String,
className: String
) {
val event = ForegroundEvent(packageName, className)
Timber.d("Received foreground event: $event")
if (lastForegroundEvent == event) {
Timber.d("LockScreen reported last foreground event was cleared.")
lastForegroundEvent = ForegroundEvent.EMPTY
}
}
private fun resetState() {
Timber.i("Reset name state")
activeClassName = ""
activePackageName = ""
}
private fun <T : Any> emit(
emitter: ObservableEmitter<T>,
value: T
) {
if (!emitter.isDisposed) {
emitter.onNext(value)
}
}
override fun observeScreenState(): Observable<Boolean> {
return Observable.defer<Boolean> {
enforcer.assertNotOnMainThread()
return@defer Observable.create { emitter ->
emitter.setCancellable {
screenStateObserver.unregister()
}
// Observe screen state changes
screenStateObserver.register {
emit(emitter, it)
}
// Start with screen as ON
enforcer.assertNotOnMainThread()
emit(emitter, true)
}
}
}
/**
* Take care to avoid any calls to logging methods as it will run every 200 ms and flood
*/
override fun listenForForegroundEvents(): Flowable<ForegroundEvent> {
return Flowable.interval(LISTEN_INTERVAL_MILLIS, MILLISECONDS)
.map {
enforcer.assertNotOnMainThread()
val now = System.currentTimeMillis()
// Watch from a period of time before this exact millisecond
val beginTime = now - QUERY_SPAN_MILLIS
// End the query in the future - this will make sure that any
// delays caused by threading or whatnot will be handled and
// seems to speed up responsiveness.
val endTime = now + QUERY_FUTURE_OFFSET_MILLIS
return@map usageEventProvider.queryEvents(beginTime, endTime)
.asOptional()
}
.onErrorReturn {
Timber.e(it, "Error while querying usage events")
return@onErrorReturn Optional.ofNullable(null)
}
.onBackpressureDrop()
.map {
if (it is Present) {
return@map it.value.createForegroundEvent { packageName, className ->
ForegroundEvent(packageName, className)
}
.asOptional()
}
return@map Optional.ofNullable(null)
}
.filter { it is Present }
.map { it as Present }
.map { it.value }
.filter { !Excludes.isLockScreen(it.packageName, it.className) }
.filter { !Excludes.isPackageExcluded(it.packageName) }
.filter { !Excludes.isClassExcluded(it.className) }
.filter { it != lastForegroundEvent }
.filter { !ForegroundEvent.isEmpty(it) }
.doOnNext { lastForegroundEvent = it }
.onErrorReturn {
Timber.e(it, "Error listening to foreground events")
return@onErrorReturn ForegroundEvent.EMPTY
}
}
override fun ifActiveMatching(
packageName: String,
className: String
): Maybe<Unit> {
return Single.fromCallable {
enforcer.assertNotOnMainThread()
Timber.d(
"Check against current window values: %s, %s", activePackageName,
activeClassName
)
// We can replace the actual passed classname with the stored classname because:
// either it is equal to the passed name or the passed name is PACKAGE
// which will respond to any class name
return@fromCallable (activePackageName == packageName)
&& (activeClassName == className || className == PadLockDbModels.PACKAGE_ACTIVITY_NAME)
}
.filter { it }
.map { Unit }
}
@CheckResult
private fun prepareLockScreen(
packageName: String,
activityName: String
): MaybeTransformer<Boolean, PadLockEntryModel> {
return MaybeTransformer { source ->
return@MaybeTransformer source.flatMap {
enforcer.assertNotOnMainThread()
Timber.d("Get locked with package: %s, class: %s", packageName, activityName)
return@flatMap queryDao.queryWithPackageActivityName(packageName, activityName)
.filter { !PadLockDbModels.isEmpty(it) }
}
}
}
@CheckResult
private fun filterOutInvalidEntries(): MaybeTransformer<PadLockEntryModel, PadLockEntryModel> {
return MaybeTransformer { source ->
return@MaybeTransformer source.filter {
enforcer.assertNotOnMainThread()
val ignoreUntilTime: Long = it.ignoreUntilTime()
val currentTime: Long = System.currentTimeMillis()
Timber.d("Ignore until time: %d", ignoreUntilTime)
Timber.d("Current time: %d", currentTime)
return@filter currentTime >= ignoreUntilTime
}
.filter {
if (PadLockDbModels.PACKAGE_ACTIVITY_NAME == it.activityName() && it.whitelist()) {
throw RuntimeException("PACKAGE entry: ${it.packageName()} cannot be whitelisted")
}
Timber.d("Filter out whitelisted packages")
return@filter !it.whitelist()
}
}
}
@CheckResult
private fun getEntry(
packageName: String,
activityName: String
): SingleTransformer<Boolean, PadLockEntryModel> {
return SingleTransformer { source ->
return@SingleTransformer source.filter {
enforcer.assertNotOnMainThread()
return@filter it
}
.compose(prepareLockScreen(packageName, activityName))
.compose(filterOutInvalidEntries())
.toSingle(PadLockDbModels.EMPTY)
}
}
@CheckResult
private fun serviceEnabled(): Maybe<Boolean> {
return Maybe.defer {
enforcer.assertNotOnMainThread()
return@defer isServiceEnabled()
.map { it == ENABLED }
.filter {
enforcer.assertNotOnMainThread()
if (!it) {
Timber.e("Service is not user enabled, ignore event")
resetState()
}
return@filter it
}
}
}
@CheckResult
private fun isEventFromActivity(
packageName: String,
className: String
): MaybeTransformer<Boolean, Boolean> {
return MaybeTransformer { source ->
return@MaybeTransformer source.isEmpty
.filter {
enforcer.assertNotOnMainThread()
return@filter !it
}
.flatMap {
enforcer.assertNotOnMainThread()
Timber.d("Check event from activity: %s %s", packageName, className)
return@flatMap packageActivityManager.isValidActivity(packageName, className)
.doOnSuccess {
if (!it) {
Timber.w("Event not caused by activity.")
Timber.w("P: %s, C: %s", packageName, className)
Timber.w("Ignore")
}
}
.filter { it }
}
}
}
override fun processEvent(
forced: Boolean,
packageName: String,
className: String
): Single<ProcessedEventPayload> {
val windowEventObservable: Single<Boolean> = serviceEnabled()
.compose(isEventFromActivity(packageName, className))
.doOnSuccess {
activePackageName = packageName
activeClassName = className
}
.toSingle(false)
return windowEventObservable.map {
enforcer.assertNotOnMainThread()
if (!it && !forced) {
Timber.e("Failed to pass window checking")
return@map false
} else {
if (forced) {
Timber.d("Pass filter via forced recheck")
}
return@map true
}
}
.compose(getEntry(packageName, className))
.doOnSuccess {
if (!PadLockDbModels.isEmpty(it)) {
lockPassed.remove(it.packageName(), it.activityName())
}
}
// Load the application info for the valid model so we can grab the icon id
.flatMap { model ->
enforcer.assertNotOnMainThread()
return@flatMap packageApplicationManager.getApplicationInfo(packageName)
.map { it.icon }
.map { ProcessedEventPayload(model, it) }
}
.onErrorReturn {
Timber.e(it, "Error getting padlock entry")
return@onErrorReturn ProcessedEventPayload(PadLockDbModels.EMPTY, 0)
}
}
companion object {
private const val LISTEN_INTERVAL_MILLIS = 400L
private val QUERY_SPAN_MILLIS = TimeUnit.SECONDS.toMillis(5L)
private val QUERY_FUTURE_OFFSET_MILLIS = TimeUnit.SECONDS.toMillis(5L)
}
}
| apache-2.0 | 9cf86cbf5a08819526f961a15a8a449d | 33.352381 | 97 | 0.680621 | 4.78382 | false | false | false | false |
smmribeiro/intellij-community | plugins/github/src/org/jetbrains/plugins/github/api/data/pullrequest/GHPullRequestReviewThread.kt | 2 | 1251 | // Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.plugins.github.api.data.pullrequest
import com.fasterxml.jackson.annotation.JsonProperty
import com.intellij.collaboration.api.dto.GraphQLFragment
import com.intellij.diff.util.Side
import org.jetbrains.plugins.github.api.data.GHNode
import org.jetbrains.plugins.github.api.data.GHNodes
@GraphQLFragment("/graphql/fragment/pullRequestReviewThread.graphql")
class GHPullRequestReviewThread(id: String,
val isResolved: Boolean,
val line: Int,
val startLine: Int?,
@JsonProperty("diffSide") val side: Side,
@JsonProperty("comments") comments: GHNodes<GHPullRequestReviewComment>)
: GHNode(id) {
val comments = comments.nodes
private val root = comments.nodes.first()
val state = root.state
val commit = root.commit
val originalCommit = root.originalCommit
val createdAt = root.createdAt
val diffHunk = root.diffHunk
val reviewId = root.reviewId
val isOutdated = root.position == null
val path = root.path
} | apache-2.0 | 4b4c0156e893199735360532448edea6 | 42.172414 | 140 | 0.686651 | 4.516245 | false | false | false | false |
smmribeiro/intellij-community | platform/vcs-impl/src/com/intellij/openapi/vcs/changes/committed/CommittedChangesFilterComponent.kt | 12 | 4350 | // Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.openapi.vcs.changes.committed
import com.intellij.openapi.Disposable
import com.intellij.openapi.ui.ComponentValidator
import com.intellij.openapi.ui.ValidationInfo
import com.intellij.openapi.vcs.VcsBundle.message
import com.intellij.openapi.vcs.versionBrowser.CommittedChangeList
import com.intellij.ui.FilterComponent
import com.intellij.ui.LightColors
import com.intellij.ui.components.JBCheckBox
import com.intellij.util.containers.ContainerUtil.createLockFreeCopyOnWriteList
import com.intellij.util.ui.UIUtil.getTextFieldBackground
import java.awt.BorderLayout
import java.awt.event.ItemListener
import java.util.function.Supplier
import java.util.regex.PatternSyntaxException
import javax.swing.JComponent
import javax.swing.event.ChangeEvent
import javax.swing.event.ChangeListener
private typealias CommittedChangeListPredicate = (CommittedChangeList) -> Boolean
private val TEXT_FILTER_KEY = CommittedChangesFilterKey("text", CommittedChangesFilterPriority.TEXT)
class CommittedChangesFilterComponent :
FilterComponent("COMMITTED_CHANGES_FILTER_HISTORY", 20),
ChangeListFilteringStrategy,
Disposable {
private val listeners = createLockFreeCopyOnWriteList<ChangeListener>()
private val regexCheckBox = JBCheckBox(message("committed.changes.regex.title")).apply {
model.addItemListener(ItemListener { filter() })
}
private val regexValidator = ComponentValidator(this)
.withValidator(Supplier { validateRegex() })
.installOn(textEditor)
private var regex: Regex? = null
init {
add(regexCheckBox, BorderLayout.EAST)
}
private fun hasValidationErrors(): Boolean = regexValidator.validationInfo != null
private fun validateRegex(): ValidationInfo? {
if (!regexCheckBox.isSelected) return null
regex = null
val value = filter.takeUnless { it.isNullOrEmpty() } ?: return null
return try {
regex = Regex(value)
null
}
catch (e: PatternSyntaxException) {
ValidationInfo(message("changes.please.enter.a.valid.regex"), textEditor)
}
}
override fun filter() {
regexValidator.revalidate()
val event = ChangeEvent(this)
listeners.forEach { it.stateChanged(event) }
}
override fun getKey(): CommittedChangesFilterKey = TEXT_FILTER_KEY
override fun getFilterUI(): JComponent? = null
override fun addChangeListener(listener: ChangeListener) {
listeners += listener
}
override fun removeChangeListener(listener: ChangeListener) {
listeners -= listener
}
override fun setFilterBase(changeLists: List<CommittedChangeList>) = Unit
override fun resetFilterBase() = Unit
override fun appendFilterBase(changeLists: List<CommittedChangeList>) = Unit
override fun filterChangeLists(changeLists: List<CommittedChangeList>): List<CommittedChangeList> {
val result = doFilter(changeLists)
textEditor.background = if (result.isEmpty() && changeLists.isNotEmpty()) LightColors.RED else getTextFieldBackground()
return result
}
private fun doFilter(changeLists: List<CommittedChangeList>): List<CommittedChangeList> {
if (hasValidationErrors()) return emptyList()
val predicate = createFilterPredicate() ?: return changeLists
return changeLists.filter(predicate)
}
private fun createFilterPredicate(): CommittedChangeListPredicate? =
if (regexCheckBox.isSelected) regex?.let { RegexPredicate(it) }
else filter.takeUnless { it.isNullOrBlank() }?.let { WordPredicate(it) }
}
private class RegexPredicate(private val regex: Regex) : CommittedChangeListPredicate {
override fun invoke(changeList: CommittedChangeList): Boolean =
regex.containsMatchIn(changeList.comment.orEmpty()) ||
regex.containsMatchIn(changeList.committerName.orEmpty()) ||
regex.containsMatchIn(changeList.number.toString())
}
private class WordPredicate(filter: String) : CommittedChangeListPredicate {
private val filterWords = filter.split(" ")
override fun invoke(changeList: CommittedChangeList): Boolean =
filterWords.any { word ->
changeList.comment.orEmpty().contains(word, true) ||
changeList.committerName.orEmpty().contains(word, true) ||
changeList.number.toString().contains(word)
}
} | apache-2.0 | 67664295de6900659075c30cb508747c | 34.958678 | 140 | 0.770575 | 4.7593 | false | false | false | false |
smmribeiro/intellij-community | plugins/settings-sync/src/com/intellij/settingsSync/SettingsSyncSettings.kt | 1 | 2744 | package com.intellij.settingsSync
import com.intellij.openapi.Disposable
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.components.*
import com.intellij.settingsSync.SettingsSyncSettings.Companion.FILE_SPEC
import com.intellij.util.EventDispatcher
import java.util.*
@State(name = "SettingsSyncSettings", storages = [Storage(FILE_SPEC)])
internal class SettingsSyncSettings : SimplePersistentStateComponent<SettingsSyncSettings.SettingsSyncSettingsState>(
SettingsSyncSettingsState()) {
companion object {
fun getInstance() = ApplicationManager.getApplication().getService(SettingsSyncSettings::class.java)
const val FILE_SPEC = "settingsSync.xml"
}
private val evenDispatcher = EventDispatcher.create(Listener::class.java)
var syncEnabled
get() = state.syncEnabled
set(value) {
state.syncEnabled = value
evenDispatcher.multicaster.settingsChanged()
}
fun isCategoryEnabled(category: SettingsCategory) = !state.disabledCategories.contains(category)
fun setCategoryEnabled(category: SettingsCategory, isEnabled: Boolean) {
if (isEnabled) {
state.disabledCategories.remove(category)
}
else {
if (!state.disabledCategories.contains(category)) {
state.disabledCategories.add(category)
state.disabledCategories.sort()
}
}
}
fun isSubcategoryEnabled(category: SettingsCategory, subcategoryId: String): Boolean {
val disabled = state.disabledSubcategories[category]
return disabled == null || !disabled.contains(subcategoryId)
}
fun setSubcategoryEnabled(category: SettingsCategory, subcategoryId: String, isEnabled: Boolean) {
val disabledList = state.disabledSubcategories[category]
if (isEnabled) {
if (disabledList != null) {
disabledList.remove(subcategoryId)
if (disabledList.isEmpty()) {
state.disabledSubcategories.remove(category)
}
}
}
else {
if (disabledList == null) {
val newList = ArrayList<String>()
newList.add(subcategoryId)
state.disabledSubcategories.put(category, newList)
}
else {
if (!disabledList.contains(subcategoryId)) {
disabledList.add(subcategoryId)
Collections.sort(disabledList)
}
}
}
}
class SettingsSyncSettingsState : BaseState() {
var syncEnabled by property(false)
var disabledCategories by list<SettingsCategory>()
var disabledSubcategories by map<SettingsCategory, ArrayList<String>>()
}
interface Listener : EventListener {
fun settingsChanged()
}
fun addListener(listener: Listener, disposable: Disposable) {
evenDispatcher.addListener(listener, disposable)
}
} | apache-2.0 | c05784e9e149519477c211b4d1715d2a | 30.551724 | 117 | 0.722668 | 4.805604 | false | false | false | false |
smmribeiro/intellij-community | plugins/grazie/src/main/kotlin/com/intellij/grazie/ide/inspection/grammar/quickfix/GrazieReplaceTypoQuickFix.kt | 1 | 6111 | // Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.grazie.ide.inspection.grammar.quickfix
import com.intellij.codeInsight.daemon.impl.UpdateHighlightersUtil
import com.intellij.codeInsight.intention.FileModifier
import com.intellij.codeInsight.intention.HighPriorityAction
import com.intellij.codeInsight.intention.IntentionAction
import com.intellij.codeInsight.intention.choice.ChoiceTitleIntentionAction
import com.intellij.codeInsight.intention.choice.ChoiceVariantIntentionAction
import com.intellij.codeInspection.LocalQuickFix
import com.intellij.codeInspection.util.IntentionFamilyName
import com.intellij.codeInspection.util.IntentionName
import com.intellij.grazie.GrazieBundle
import com.intellij.grazie.ide.fus.GrazieFUSCounter
import com.intellij.grazie.ide.ui.components.dsl.msg
import com.intellij.grazie.text.Rule
import com.intellij.grazie.text.TextProblem
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.NlsSafe
import com.intellij.openapi.util.TextRange
import com.intellij.psi.PsiFile
import com.intellij.psi.SmartPointerManager
import com.intellij.psi.SmartPsiFileRange
import kotlin.math.min
object GrazieReplaceTypoQuickFix {
private class ReplaceTypoTitleAction(@IntentionFamilyName family: String, @IntentionName title: String) : ChoiceTitleIntentionAction(family, title),
HighPriorityAction {
override fun compareTo(other: IntentionAction): Int {
if (other is GrazieCustomFixWrapper) return -1
return super.compareTo(other)
}
}
private class ChangeToVariantAction(
private val rule: Rule,
override val index: Int,
@IntentionFamilyName private val family: String,
@NlsSafe private val suggestion: String,
private val replacement: String,
private val underlineRanges: List<SmartPsiFileRange>,
private val replacementRange: SmartPsiFileRange,
)
: ChoiceVariantIntentionAction(), HighPriorityAction {
override fun getName(): String {
if (suggestion.isEmpty()) return msg("grazie.grammar.quickfix.remove.typo.tooltip")
if (suggestion[0].isWhitespace() || suggestion.last().isWhitespace()) return "'$suggestion'"
return suggestion
}
override fun getTooltipText(): String = if (suggestion.isNotEmpty()) {
msg("grazie.grammar.quickfix.replace.typo.tooltip", suggestion)
} else {
msg("grazie.grammar.quickfix.remove.typo.tooltip")
}
override fun getFamilyName(): String = family
override fun isAvailable(project: Project, editor: Editor?, file: PsiFile): Boolean = replacementRange.range != null
override fun getFileModifierForPreview(target: PsiFile): FileModifier = this
override fun applyFix(project: Project, file: PsiFile, editor: Editor?) {
GrazieFUSCounter.quickFixInvoked(rule, project, "accept.suggestion")
val replacementRange = this.replacementRange.range ?: return
val document = file.viewProvider.document ?: return
underlineRanges.forEach { underline ->
underline.range?.let { UpdateHighlightersUtil.removeHighlightersWithExactRange(document, project, it) }
}
document.replaceString(replacementRange.startOffset, replacementRange.endOffset, replacement)
}
override fun startInWriteAction(): Boolean = true
override fun compareTo(other: IntentionAction): Int {
if (other is GrazieCustomFixWrapper) return -1
return super.compareTo(other)
}
}
@Deprecated(message = "use getReplacementFixes(problem, underlineRanges)")
@Suppress("UNUSED_PARAMETER", "DeprecatedCallableAddReplaceWith")
fun getReplacementFixes(problem: TextProblem, underlineRanges: List<SmartPsiFileRange>, file: PsiFile): List<LocalQuickFix> {
return getReplacementFixes(problem, underlineRanges)
}
@JvmStatic
fun getReplacementFixes(problem: TextProblem, underlineRanges: List<SmartPsiFileRange>): List<LocalQuickFix> {
val replacementRange = problem.replacementRange
val replacedText = replacementRange.subSequence(problem.text)
val file = problem.text.containingFile
val spm = SmartPointerManager.getInstance(file.project)
@Suppress("HardCodedStringLiteral") val familyName: @IntentionFamilyName String = familyName(problem)
val result = arrayListOf<LocalQuickFix>(ReplaceTypoTitleAction(familyName, problem.shortMessage))
problem.corrections.forEachIndexed { index, suggestion ->
val commonPrefix = commonPrefixLength(suggestion, replacedText)
val commonSuffix =
min(commonSuffixLength(suggestion, replacedText), min(suggestion.length, replacementRange.length) - commonPrefix)
val localRange = TextRange(replacementRange.startOffset + commonPrefix, replacementRange.endOffset - commonSuffix)
val replacement = suggestion.substring(commonPrefix, suggestion.length - commonSuffix)
result.add(ChangeToVariantAction(
problem.rule, index, familyName, suggestion, replacement, underlineRanges,
spm.createSmartPsiFileRangePointer(file, problem.text.textRangeToFile(localRange))))
}
return result
}
fun familyName(problem: TextProblem): @IntentionFamilyName String =
GrazieBundle.message("grazie.grammar.quickfix.replace.typo.text", problem.shortMessage)
// custom common prefix/suffix calculation to honor cases when the text is separated by a synthetic \n,
// but LT suggests a space instead (https://github.com/languagetool-org/languagetool/issues/5297)
private fun commonPrefixLength(s1: CharSequence, s2: CharSequence): Int {
val minLength = min(s1.length, s2.length)
var i = 0
while (i < minLength && charsMatch(s1[i], s2[i])) i++
return i
}
private fun commonSuffixLength(s1: CharSequence, s2: CharSequence): Int {
val minLength = min(s1.length, s2.length)
var i = 0
while (i < minLength && charsMatch(s1[s1.length - i - 1], s2[s2.length - i - 1])) i++
return i
}
private fun charsMatch(c1: Char, c2: Char) = c1 == c2 || c1 == ' ' && c2 == '\n'
}
| apache-2.0 | ee08e9f7f038a0d5b3da566536fbc61d | 44.947368 | 150 | 0.763868 | 4.598194 | false | false | false | false |
kickstarter/android-oss | app/src/main/java/com/kickstarter/viewmodels/UpdateCardViewHolderViewModel.kt | 1 | 6875 | package com.kickstarter.viewmodels
import android.util.Pair
import androidx.annotation.NonNull
import com.kickstarter.libs.ActivityViewModel
import com.kickstarter.libs.Environment
import com.kickstarter.libs.rx.transformers.Transformers
import com.kickstarter.libs.rx.transformers.Transformers.takeWhen
import com.kickstarter.libs.utils.extensions.isNullOrZero
import com.kickstarter.libs.utils.extensions.negate
import com.kickstarter.libs.utils.extensions.userIsCreator
import com.kickstarter.models.Project
import com.kickstarter.models.Update
import com.kickstarter.ui.viewholders.UpdateCardViewHolder
import org.joda.time.DateTime
import rx.Observable
import rx.subjects.BehaviorSubject
import rx.subjects.PublishSubject
interface UpdateCardViewHolderViewModel {
interface Inputs {
/** Configure with the current [Project] and [Update]. */
fun configureWith(project: Project, update: Update)
/** Call when the user clicks on an [Update]. */
fun updateClicked()
}
interface Outputs {
/** Emits a boolean determining if the backers only container should be visible. */
fun backersOnlyContainerIsVisible(): Observable<Boolean>
/** Emits a truncated version of the [Update]'s body. */
fun blurb(): Observable<String>
/** Emits the number of comments of the [Update]. */
fun commentsCount(): Observable<Int>
/** Emits a boolean determining if the comments count container should be visible. */
fun commentsCountIsGone(): Observable<Boolean>
/** Emits the number of likes of the [Update]. */
fun likesCount(): Observable<Int>
/** Emits a boolean determining if the likes count container should be visible. */
fun likesCountIsGone(): Observable<Boolean>
/** Emits the publish timestamp of the [Update]. */
fun publishDate(): Observable<DateTime>
/** Emits the sequence of the [Update]. */
fun sequence(): Observable<Int>
/** Emits when the [UpdateCardViewHolder.Delegate] should start the [com.kickstarter.ui.activities.UpdateActivity]. */
fun showUpdateDetails(): Observable<Update>
/** Emits the title of the [Update]. */
fun title(): Observable<String>
}
class ViewModel(@NonNull environment: Environment) : ActivityViewModel<UpdateCardViewHolder>(environment), Inputs, Outputs {
private val projectAndUpdate = PublishSubject.create<Pair<Project, Update>>()
private val updateClicked = PublishSubject.create<Void>()
private val backersOnlyContainerIsVisible = BehaviorSubject.create<Boolean>()
private val blurb = BehaviorSubject.create<String>()
private val commentsCount = BehaviorSubject.create<Int>()
private val commentsCountIsGone = BehaviorSubject.create<Boolean>()
private val likesCount = BehaviorSubject.create<Int>()
private val likesCountIsGone = BehaviorSubject.create<Boolean>()
private val publishDate = BehaviorSubject.create<DateTime>()
private val sequence = BehaviorSubject.create<Int>()
private val showUpdateDetails = PublishSubject.create<Update>()
private val title = BehaviorSubject.create<String>()
private val currentUser = requireNotNull(environment.currentUser())
val inputs: Inputs = this
val outputs: Outputs = this
init {
val update = this.projectAndUpdate
.map { it.second }
val project = this.projectAndUpdate
.map { it.first }
val isCreator = Observable.combineLatest(this.currentUser.observable(), project) { user, project ->
Pair(user, project)
}.map { it.second.userIsCreator(it.first) }
this.projectAndUpdate
.compose<Pair<Pair<Project, Update>, Boolean>>(Transformers.combineLatestPair(isCreator))
.map {
when {
it.first.first.isBacking() || it.second -> false
else -> (it.first.second.isPublic() ?: false).negate()
}
}
.compose(bindToLifecycle())
.subscribe(this.backersOnlyContainerIsVisible)
update
.map { it.truncatedBody() }
.compose(bindToLifecycle())
.subscribe(this.blurb)
update
.map { it.commentsCount() }
.filter { it != null }
.compose(bindToLifecycle())
.subscribe(this.commentsCount)
update
.map { it.commentsCount() }
.map { it.isNullOrZero() }
.compose(bindToLifecycle())
.subscribe(this.commentsCountIsGone)
update
.map { it.likesCount() }
.filter { it != null }
.compose(bindToLifecycle())
.subscribe(this.likesCount)
update
.map { it.likesCount() }
.map { it.isNullOrZero() }
.compose(bindToLifecycle())
.subscribe(this.likesCountIsGone)
update
.map { it.publishedAt() }
.compose(bindToLifecycle())
.subscribe(this.publishDate)
update
.map { it.sequence() }
.compose(bindToLifecycle())
.subscribe(this.sequence)
update
.map { it.title() }
.compose(bindToLifecycle())
.subscribe(this.title)
update
.compose<Update>(takeWhen(this.updateClicked))
.compose(bindToLifecycle())
.subscribe(this.showUpdateDetails)
}
override fun configureWith(project: Project, update: Update) {
this.projectAndUpdate.onNext(Pair.create(project, update))
}
override fun updateClicked() {
this.updateClicked.onNext(null)
}
override fun backersOnlyContainerIsVisible(): Observable<Boolean> = this.backersOnlyContainerIsVisible
override fun blurb(): Observable<String> = this.blurb
override fun commentsCount(): Observable<Int> = this.commentsCount
override fun commentsCountIsGone(): Observable<Boolean> = this.commentsCountIsGone
override fun likesCount(): Observable<Int> = this.likesCount
override fun likesCountIsGone(): Observable<Boolean> = this.likesCountIsGone
override fun publishDate(): Observable<DateTime> = this.publishDate
override fun sequence(): Observable<Int> = this.sequence
override fun showUpdateDetails(): Observable<Update> = this.showUpdateDetails
override fun title(): Observable<String> = this.title
}
}
| apache-2.0 | be4f72a6c993ce9dabf6d6ff1769115e | 36.774725 | 128 | 0.624873 | 5.232116 | false | false | false | false |
tensorflow/examples | lite/examples/image_classification/android/app/src/main/java/org/tensorflow/lite/examples/imageclassification/fragments/PermissionsFragment.kt | 1 | 2826 | /*
* Copyright 2022 The TensorFlow Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.tensorflow.lite.examples.imageclassification.fragments
import android.Manifest
import android.content.Context
import android.content.pm.PackageManager
import android.os.Bundle
import android.widget.Toast
import androidx.activity.result.contract.ActivityResultContracts
import androidx.core.content.ContextCompat
import androidx.fragment.app.Fragment
import androidx.lifecycle.lifecycleScope
import androidx.navigation.Navigation
import org.tensorflow.lite.examples.imageclassification.R
private val PERMISSIONS_REQUIRED = arrayOf(Manifest.permission.CAMERA)
class PermissionsFragment : Fragment() {
private val requestPermissionLauncher =
registerForActivityResult(
ActivityResultContracts.RequestPermission()
) { isGranted: Boolean ->
if (isGranted) {
Toast.makeText(context, "Permission request granted", Toast.LENGTH_LONG).show()
navigateToCamera()
} else {
Toast.makeText(context, "Permission request denied", Toast.LENGTH_LONG).show()
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
when {
ContextCompat.checkSelfPermission(
requireContext(),
Manifest.permission.CAMERA
) == PackageManager.PERMISSION_GRANTED -> {
navigateToCamera()
}
else -> {
requestPermissionLauncher.launch(
Manifest.permission.CAMERA
)
}
}
}
private fun navigateToCamera() {
lifecycleScope.launchWhenStarted {
Navigation.findNavController(requireActivity(), R.id.fragment_container).navigate(
PermissionsFragmentDirections.actionPermissionsToCamera()
)
}
}
companion object {
/** Convenience method used to check if all permissions required by this app are granted */
fun hasPermissions(context: Context) = PERMISSIONS_REQUIRED.all {
ContextCompat.checkSelfPermission(context, it) == PackageManager.PERMISSION_GRANTED
}
}
}
| apache-2.0 | 29b55e288828ab82623afe9bd9936152 | 34.772152 | 99 | 0.678344 | 5.292135 | false | false | false | false |
nuxusr/walkman | okreplay-junit/src/main/kotlin/okreplay/CharMatcher.kt | 1 | 8166 | /*
* Copyright (C) 2010 The Guava 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 okreplay
import java.util.BitSet
import okreplay.Util.checkArgument
import okreplay.Util.checkNotNull
import okreplay.Util.checkPositionIndex
// Constructors
/**
* Constructor for use by subclasses. When subclassing, you may want to override
* `toString()` to provide a useful description.
*/
internal abstract class CharMatcher : Predicate<Char> {
// Abstract methods
/** Determines a true or false value for the given character. */
abstract fun matches(c: Char): Boolean
// Non-static factories
/** Returns a matcher that matches any character matched by both this matcher and `other`. */
open fun and(other: CharMatcher): CharMatcher {
return And(this, other)
}
/** Returns a matcher that matches any character matched by either this matcher or `other`. */
open fun or(other: CharMatcher): CharMatcher {
return Or(this, other)
}
/** Sets bits in `table` matched by this matcher. */
internal open fun setBits(table: BitSet) {
var c = Character.MAX_VALUE.toInt()
while (c >= Character.MIN_VALUE.toInt()) {
if (matches(c.toChar())) {
table.set(c)
}
c--
}
}
// Text processing routines
/**
* Returns the index of the first matching character in a character sequence, starting from a
* given position, or `-1` if no character matches after that position.
*
* The default implementation iterates over the sequence in forward order, beginning at `start`,
* calling [.matches] for each character.
* @param sequence the character sequence to examine
* *
* @param start the first index to examine; must be nonnegative and no greater than `sequence.length()`
* *
* @return the index of the first matching character, guaranteed to be no less than `start`,
* * or `-1` if no character matches
* *
* @throws IndexOutOfBoundsException if start is negative or greater than `sequence.length()`
*/
open fun indexIn(sequence: CharSequence, start: Int): Int {
val length = sequence.length
checkPositionIndex(start, length)
return (start..length - 1).firstOrNull { matches(sequence[it]) } ?: -1
}
@Deprecated("Provided only to satisfy the Predicate interface; use matches instead.")
override fun apply(character: Char?): Boolean {
return matches(character!!)
}
/**
* Returns a string representation of this `CharMatcher`, such as
* `CharMatcher.or(WHITESPACE, JAVA_DIGIT)`.
*/
override fun toString(): String {
return super.toString()
}
// Fast matchers
/** A matcher for which precomputation will not yield any significant benefit. */
internal abstract class FastMatcher : CharMatcher()
/** [FastMatcher] which overrides `toString()` with a custom name. */
internal abstract class NamedFastMatcher(description: String) : FastMatcher() {
private val description: String = checkNotNull(description)
override fun toString(): String {
return description
}
}
// Static constant implementation classes
/** Implementation of [.none]. */
private class None private constructor() : NamedFastMatcher("CharMatcher.none()") {
override fun matches(c: Char): Boolean {
return false
}
override fun indexIn(sequence: CharSequence, start: Int): Int {
val length = sequence.length
checkPositionIndex(start, length)
return -1
}
override fun and(other: CharMatcher): CharMatcher {
checkNotNull(other)
return this
}
override fun or(other: CharMatcher): CharMatcher {
return checkNotNull(other)
}
companion object {
internal val INSTANCE = None()
}
}
// Non-static factory implementation classes
/** Implementation of [.and]. */
private class And internal constructor(
a: CharMatcher, b: CharMatcher,
internal val first: CharMatcher = checkNotNull(a)) : CharMatcher() {
internal val second: CharMatcher = checkNotNull(b)
override fun matches(c: Char): Boolean {
return first.matches(c) && second.matches(c)
}
override fun setBits(table: BitSet) {
val tmp1 = BitSet()
first.setBits(tmp1)
val tmp2 = BitSet()
second.setBits(tmp2)
tmp1.and(tmp2)
table.or(tmp1)
}
override fun toString(): String {
return "CharMatcher.and($first, $second)"
}
}
/** Implementation of [.or]. */
private class Or internal constructor(a: CharMatcher, b: CharMatcher) : CharMatcher() {
internal val first: CharMatcher = checkNotNull(a)
internal val second: CharMatcher = checkNotNull(b)
override fun setBits(table: BitSet) {
first.setBits(table)
second.setBits(table)
}
override fun matches(c: Char): Boolean {
return first.matches(c) || second.matches(c)
}
override fun toString(): String {
return "CharMatcher.or($first, $second)"
}
}
// Static factory implementations
/** Implementation of [.is]. */
private class Is internal constructor(private val match: Char) : FastMatcher() {
override fun matches(c: Char): Boolean {
return c == match
}
override fun and(other: CharMatcher): CharMatcher {
return if (other.matches(match)) this else none()
}
override fun or(other: CharMatcher): CharMatcher {
return if (other.matches(match)) other else super.or(other)
}
override fun setBits(table: BitSet) {
table.set(match.toInt())
}
override fun toString(): String {
return "CharMatcher.is('" + showCharacter(match) + "')"
}
}
/** Implementation of [.inRange]. */
private class InRange internal constructor(
private val startInclusive: Char,
private val endInclusive: Char) : FastMatcher() {
init {
checkArgument(endInclusive >= startInclusive)
}
override fun matches(c: Char): Boolean {
return c in startInclusive..endInclusive
}
override fun setBits(table: BitSet) {
table.set(startInclusive.toInt(), endInclusive.toInt() + 1)
}
override fun toString(): String {
return "CharMatcher.inRange('${showCharacter(startInclusive)}', '${showCharacter(endInclusive)}')"
}
}
companion object {
// Constant matcher factory methods
/**
* Matches no characters.
* @since 19.0 (since 1.0 as constant `NONE`)
*/
fun none(): CharMatcher {
return None.INSTANCE
}
// Static factories
/**
* Returns a `char` matcher that matches only one specified character.
*/
fun `is`(match: Char): CharMatcher {
return Is(match)
}
/**
* Returns a `char` matcher that matches any character in a given range (both endpoints are
* inclusive). For example, to match any lowercase letter of the English alphabet, use
* `CharMatcher.inRange('a', 'z')`.
* @throws IllegalArgumentException if `endInclusive < startInclusive`
*/
fun inRange(startInclusive: Char, endInclusive: Char): CharMatcher {
return InRange(startInclusive, endInclusive)
}
/**
* Returns the Java Unicode escape sequence for the given character, in the form "\u12AB" where
* "12AB" is the four hexadecimal digits representing the 16 bits of the UTF-16 character.
*/
private fun showCharacter(c: Char): String {
var c = c
val hex = "0123456789ABCDEF"
val tmp = charArrayOf('\\', 'u', '\u0000', '\u0000', '\u0000', '\u0000')
for (i in 0..3) {
tmp[5 - i] = hex[c.toInt() and 0xF]
c = (c.toInt() shr 4).toChar()
}
return String(tmp)
}
}
}
| apache-2.0 | b46227b7b7b3c2d1191d800c7df25bd5 | 28.164286 | 105 | 0.662626 | 4.266458 | false | false | false | false |
moko256/twicalico | app/src/main/java/com/github/moko256/twitlatte/view/EditTextsDialogShower.kt | 1 | 4465 | /*
* Copyright 2015-2019 The twitlatte 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.moko256.twitlatte.view
import android.content.Context
import android.content.DialogInterface
import android.text.Editable
import android.text.TextWatcher
import android.widget.EditText
import android.widget.LinearLayout
import android.widget.LinearLayout.VERTICAL
import androidx.appcompat.app.AlertDialog
import io.reactivex.Completable
import io.reactivex.subjects.CompletableSubject
fun createEditTextsDialog(
context: Context,
title: String?,
cancellable: Boolean,
cancelCallback: DialogInterface.OnCancelListener?,
vararg contents: DialogContent
): Completable {
val result = CompletableSubject.create()
val dialog = AlertDialog.Builder(context)
.setTitle(title)
.setPositiveButton(android.R.string.ok) { _, _ -> result.onComplete() }
.apply {
if (cancellable) {
setNegativeButton(android.R.string.cancel) { dialog, _ ->
cancelCallback?.onCancel(dialog)
}
}
setCancelable(cancellable)
setOnCancelListener(cancelCallback)
}
.create()
val views: List<EditText> = contents
.map {
val editText = EditText(context)
editText.hint = it.hint
editText.inputType = it.type
editText.setText(it.initValue)
editText.setSelection(it.initValue.length)
editText.addTextChangedListener(object : TextWatcher {
override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {}
override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {
it.callback(s.toString())
}
override fun afterTextChanged(s: Editable) {}
})
editText
}
var firstEnabled = false
dialog.setView(
views.singleOrNull()?.also {
firstEnabled = it.text.isNotEmpty()
it.addTextChangedListener(object : TextWatcher {
override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {}
override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
dialog.getButton(DialogInterface.BUTTON_POSITIVE).isEnabled = s?.isNotEmpty() == true
}
override fun afterTextChanged(s: Editable?) {}
})
} ?: LinearLayout(context).apply {
orientation = VERTICAL
firstEnabled = views.map { it.text.isNotEmpty() }.all { it }
val listener = object : TextWatcher {
override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {}
override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
dialog.getButton(DialogInterface.BUTTON_POSITIVE).isEnabled =
views.map { it.text.isNotEmpty() }.all { it }
}
override fun afterTextChanged(s: Editable?) {}
}
views.forEach { editText ->
editText.addTextChangedListener(listener)
addView(editText)
}
}
)
dialog.show()
dialog.getButton(DialogInterface.BUTTON_POSITIVE).isEnabled = firstEnabled
return result.doOnDispose {
dialog.setOnDismissListener(null)
dialog.dismiss()
}
}
class DialogContent(
val hint: String,
val initValue: String,
val type: Int,
val callback: (String) -> Unit
) | apache-2.0 | adf52880bbc2d82f15cfefb536904c1a | 34.728 | 109 | 0.591713 | 5.216121 | false | false | false | false |
980f/droid | app/src/main/kotlin/pers/hal42/droid/DroidSampler.kt | 1 | 3453 | package pers.hal42.droid
import android.graphics.Color
import android.os.Bundle
import pers.hal42.android.EasyActivity
import pers.hal42.android.NumberEditor
import pers.hal42.android.PolitePeriodicTimer
import pers.hal42.android.ViewFormatter
import kotlin.reflect.KMutableProperty
import kotlin.reflect.KMutableProperty1
import kotlin.reflect.KProperty
class DroidSampler : EasyActivity(3) {
internal val myView: ViewFormatter by lazy { makeText(-1) }
internal val timing: PolitePeriodicTimer = PolitePeriodicTimer(1000)//once a second and startup stopped as we aren't init'd
// internal var sets: List<TimerSet>? = null
internal val currentSet: TimerSet = TimerSet()
internal var tremain: Int = 0
internal var running: Boolean = false
private fun doubleProp(prop:KMutableProperty<Int> ){
prop.setter.call (this,2+prop.getter.call(this))
}
private fun updateTimeview() {
if (running) {
myView.cls()
--tremain
if (tremain > 0) {
myView.format("{0}", tremain)
} else if (tremain < 0) {
if (tremain < -currentSet.totalTime()) {
myView.format("Over >{0}!", currentSet.totalTime())
running = false
} else {
myView.format("Over {0}!", -tremain)
}
} else {
myView.format("Time's UP!")
}
setColor(currentSet.colorForTimeRemaining(tremain))
}
}
private fun setColor(color: Int) {
myView.setBackgroundColor(color)
}
private fun testTimer() {
tremain = currentSet.totalTime()
running = true
timing.resume()
}
/** */
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
makeColorButton("Greenish", Color.GREEN)
makeColorButton("Yellowish", Color.YELLOW)
// makeColorButton("Redish", Color.RED)
makeLauncher(NumberEditor.Connection("Reddish", "set red time", true, false, { currentSet.red.toFloat() }, { value -> currentSet.red = value.toInt() }))
makeButton(-1, "Start Timer") { testTimer() }
myView.printf("Toast Timer") //this reference to myView creates it so must occur in an appropriate place to set its screen position.
//we will eventually make this more dynamic
// window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
myView.view.keepScreenOn = true
timing.tasklist.add { updateTimeview() }
myView.printf("\n local arg ${tremain}")
var prop=DroidSampler::tremain
doubleProp(prop)
myView.printf("\n local arg ${tremain}")
}
/** a button that when pressed sets the background of the text area to the given @param colorcode */
private fun makeColorButton(colorname: String, colorcode: Int) {
makeButton(colorname) { myView.setBackgroundColor(colorcode) }
}
/**
* a triplet of parameters, how long each of the three phases lasts.
* e.g. 5 minutes green, 2 minutes yellow, 30 seconds red. Total time 7.5 minutes.
*/
class TimerSet(var green: Int = 5, var yellow: Int = 2, var red: Int = 1) {
fun totalTime(): Int {
return green + yellow + red
}
fun colorForTimeRemaining(tremain: Int): Int {
if (tremain < 0) {
return Color.LTGRAY
} else if (tremain < red) {
return Color.RED
} else if (tremain < yellow + red) {
return Color.YELLOW
} else if (tremain < green + yellow + red) {
return Color.GREEN
} else {
return Color.MAGENTA
}
}
}
}
| mit | 78f91d9cd16f2aa10480aee6f1f6ab91 | 29.289474 | 156 | 0.667535 | 3.906109 | false | false | false | false |
ncoe/rosetta | Random_Latin_Squares/Kotlin/src/RLS.kt | 1 | 1203 | typealias matrix = MutableList<MutableList<Int>>
fun printSquare(latin: matrix) {
for (row in latin) {
println(row)
}
println()
}
fun latinSquare(n: Int) {
if (n <= 0) {
println("[]")
return
}
val latin = MutableList(n) { MutableList(n) { it } }
// first row
latin[0].shuffle()
// middle row(s)
for (i in 1 until n - 1) {
var shuffled = false
shuffling@
while (!shuffled) {
latin[i].shuffle()
for (k in 0 until i) {
for (j in 0 until n) {
if (latin[k][j] == latin[i][j]) {
continue@shuffling
}
}
}
shuffled = true
}
}
// last row
for (j in 0 until n) {
val used = MutableList(n) { false }
for (i in 0 until n - 1) {
used[latin[i][j]] = true
}
for (k in 0 until n) {
if (!used[k]) {
latin[n - 1][j] = k
break
}
}
}
printSquare(latin)
}
fun main() {
latinSquare(5)
latinSquare(5)
latinSquare(10) // for good measure
}
| mit | c230a460b37db79db4a3a0a16cdbc928 | 19.741379 | 56 | 0.425603 | 3.759375 | false | false | false | false |
dpisarenko/econsim-tr01 | src/test/java/cc/altruix/econsimtr01/AbstractAccountantTests.kt | 1 | 2975 | /*
* Copyright 2012-2016 Dmitri Pisarenko
*
* WWW: http://altruix.cc
* E-Mail: [email protected]
* Skype: dp118m (voice calls must be scheduled in advance)
*
* Physical address:
*
* 4-i Rostovskii pereulok 2/1/20
* 119121 Moscow
* Russian Federation
*
* This file is part of econsim-tr01.
*
* econsim-tr01 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.
*
* econsim-tr01 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 econsim-tr01. If not, see <http://www.gnu.org/licenses/>.
*
*/
package cc.altruix.econsimtr01
import org.joda.time.DateTime
import org.junit.Test
import org.mockito.Mockito
/**
* @author Dmitri Pisarenko ([email protected])
* @version $Id$
* @since 1.0
*/
class AbstractAccountantTests {
open class TestAccountant(logTarget:StringBuilder,
agents:List<IAgent>,
resources:List<PlResource>)
: AbstractAccountant(logTarget, agents, resources) {
override fun measure(time: DateTime, agents: List<IAgent>) {
}
}
@Test
fun writeResourceDataCallsConvertToPrologString() {
val logTarget = StringBuilder()
val agents = emptyList<IAgent>()
val txt =
"People, who were exposed to Stacy's writings 6 times"
val resource = PlResource(
"r11-pc2",
txt,
"People")
val out = Mockito.spy(
TestAccountant(
logTarget,
agents,
listOf(resource)
)
)
Mockito.doReturn("foo").`when`(out).convertToPrologString(txt)
// Run method under test
out.writeResourceData()
// Verify
Mockito.verify(out).convertToPrologString(txt)
logTarget.toString().shouldBe("resource(r11-pc2, \"foo\", \"People\")" +
".\n")
}
@Test
fun convertToPrologStringEscapesApostrophes() {
val txt =
"People, who were exposed to Stacy's writings 6 times"
val out = TestAccountant(
StringBuilder(),
emptyList<IAgent>(),
emptyList<PlResource>()
)
// Run method under test
val act = out.convertToPrologString(txt)
// Verify
act.shouldBe("People, who were exposed to Stacy''s writings 6 times")
}
}
| gpl-3.0 | c1194877a9504c5b6116a305267415ec | 31.055556 | 80 | 0.580168 | 4.500756 | false | true | false | false |
siosio/intellij-community | plugins/kotlin/j2k/new/src/org/jetbrains/kotlin/nj2k/conversions/AssignmentExpressionUnfoldingConversion.kt | 2 | 7426 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.nj2k.conversions
import org.jetbrains.kotlin.nj2k.NewJ2kConverterContext
import org.jetbrains.kotlin.nj2k.parenthesizeIfBinaryExpression
import org.jetbrains.kotlin.nj2k.tree.*
import org.jetbrains.kotlin.utils.addToStdlib.safeAs
class AssignmentExpressionUnfoldingConversion(context: NewJ2kConverterContext) : RecursiveApplicableConversionBase(context) {
override fun applyToElement(element: JKTreeElement): JKTreeElement {
val unfolded = when (element) {
is JKBlock -> element.convertAssignments()
is JKExpressionStatement -> element.convertAssignments()
is JKJavaAssignmentExpression -> element.convertAssignments()
else -> null
} ?: return recurse(element)
return recurse(unfolded)
}
private fun JKBlock.convertAssignments(): JKBlock? {
val hasAssignments = statements.any { it.containsAssignment() }
if (!hasAssignments) return null
val newStatements = mutableListOf<JKStatement>()
for (statement in statements) {
when {
statement is JKExpressionStatement && statement.expression is JKJavaAssignmentExpression -> {
val assignment = statement.expression as JKJavaAssignmentExpression
newStatements += assignment
.unfoldToStatementsList(assignmentTarget = null)
.withFormattingFrom(statement)
}
statement is JKDeclarationStatement && statement.containsAssignment() -> {
val variable = statement.declaredStatements.single() as JKVariable
val assignment = variable.initializer as JKJavaAssignmentExpression
newStatements += assignment
.unfoldToStatementsList(variable.detached(statement))
.withFormattingFrom(statement)
}
else -> {
newStatements += statement
}
}
}
statements = newStatements
return this
}
private fun JKExpressionStatement.convertAssignments(): JKStatement? {
val assignment = expression as? JKJavaAssignmentExpression ?: return null
return when {
canBeConvertedToBlock() && assignment.expression is JKJavaAssignmentExpression ->
JKBlockStatement(JKBlockImpl(assignment.unfoldToStatementsList(assignmentTarget = null)))
else -> createKtAssignmentStatement(
assignment::field.detached(),
assignment::expression.detached(),
assignment.operator
)
}.withFormattingFrom(this)
}
private fun JKExpressionStatement.canBeConvertedToBlock() = when (val parent = parent) {
is JKLoopStatement -> parent.body == this
is JKIfElseStatement -> parent.thenBranch == this || parent.elseBranch == this
is JKJavaSwitchCase -> true
else -> false
}
private fun JKJavaAssignmentExpression.convertAssignments() =
unfoldToExpressionsChain().withFormattingFrom(this)
private fun JKDeclarationStatement.containsAssignment() =
declaredStatements.singleOrNull()?.safeAs<JKVariable>()?.initializer is JKJavaAssignmentExpression
private fun JKStatement.containsAssignment() = when (this) {
is JKExpressionStatement -> expression is JKJavaAssignmentExpression
is JKDeclarationStatement -> containsAssignment()
else -> false
}
private fun JKJavaAssignmentExpression.unfold() = generateSequence(this) { assignment ->
assignment.expression as? JKJavaAssignmentExpression
}.toList().asReversed()
private fun JKJavaAssignmentExpression.unfoldToExpressionsChain(): JKExpression {
val links = unfold()
val first = links.first()
return links.subList(1, links.size)
.fold(first.toExpressionChainLink(first::expression.detached())) { state, assignment ->
assignment.toExpressionChainLink(state)
}
}
private fun JKJavaAssignmentExpression.unfoldToStatementsList(assignmentTarget: JKVariable?): List<JKStatement> {
val links = unfold()
val first = links.first()
val statements = links.subList(1, links.size)
.foldIndexed(listOf(first.toDeclarationChainLink(first::expression.detached()))) { index, list, assignment ->
list + assignment.toDeclarationChainLink(links[index].field.copyTreeAndDetach())
}
return when (assignmentTarget) {
null -> statements
else -> {
assignmentTarget.initializer = statements.last().field.copyTreeAndDetach()
statements + JKDeclarationStatement(listOf(assignmentTarget))
}
}
}
private fun JKJavaAssignmentExpression.toExpressionChainLink(receiver: JKExpression): JKExpression {
val assignment = createKtAssignmentStatement(
this::field.detached(),
JKKtItExpression(operator.returnType),
operator
).withFormattingFrom(this)
return when {
operator.isSimpleToken() ->
JKAssignmentChainAlsoLink(receiver, assignment, field.copyTreeAndDetach())
else ->
JKAssignmentChainLetLink(receiver, assignment, field.copyTreeAndDetach())
}
}
private fun JKJavaAssignmentExpression.toDeclarationChainLink(expression: JKExpression) =
createKtAssignmentStatement(this::field.detached(), expression, this.operator)
.withFormattingFrom(this)
private fun createKtAssignmentStatement(
field: JKExpression,
expression: JKExpression,
operator: JKOperator
) = when {
operator.isOnlyJavaToken() ->
JKKtAssignmentStatement(
field,
JKBinaryExpression(
field.copyTreeAndDetach(),
expression.parenthesizeIfBinaryExpression(),
JKKtOperatorImpl(
onlyJavaAssignTokensToKotlinOnes[operator.token]!!,
operator.returnType
)
),
JKOperatorToken.EQ
)
else -> JKKtAssignmentStatement(field, expression, operator.token)
}
private fun JKOperator.isSimpleToken() = when {
isOnlyJavaToken() -> false
token == JKOperatorToken.PLUSEQ
|| token == JKOperatorToken.MINUSEQ
|| token == JKOperatorToken.MULTEQ
|| token == JKOperatorToken.DIVEQ -> false
else -> true
}
private fun JKOperator.isOnlyJavaToken() = token in onlyJavaAssignTokensToKotlinOnes
companion object {
private val onlyJavaAssignTokensToKotlinOnes = mapOf(
JKOperatorToken.ANDEQ to JKOperatorToken.AND,
JKOperatorToken.OREQ to JKOperatorToken.OR,
JKOperatorToken.XOREQ to JKOperatorToken.XOR,
JKOperatorToken.LTLTEQ to JKOperatorToken.SHL,
JKOperatorToken.GTGTEQ to JKOperatorToken.SHR,
JKOperatorToken.GTGTGTEQ to JKOperatorToken.USHR
)
}
} | apache-2.0 | 9346ced4a6881914563530e86e871358 | 41.930636 | 158 | 0.645166 | 6.183181 | false | false | false | false |
loxal/FreeEthereum | free-ethereum-core/src/test/java/org/ethereum/jsontestsuite/GitHubVMTest.kt | 1 | 7507 | /*
* The MIT License (MIT)
*
* Copyright 2017 Alexander Orlov <[email protected]>. All rights reserved.
* Copyright (c) [2016] [ <ether.camp> ]
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
*/
package org.ethereum.jsontestsuite
import org.ethereum.config.SystemProperties
import org.ethereum.config.net.MainNetConfig
import org.ethereum.jsontestsuite.suite.JSONReader
import org.ethereum.jsontestsuite.suite.JSONReader.getFileNamesForTreeSha
import org.json.simple.parser.ParseException
import org.junit.After
import org.junit.FixMethodOrder
import org.junit.Ignore
import org.junit.Test
import org.junit.runners.MethodSorters
import java.util.*
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
class GitHubVMTest {
//SHACOMMIT of tested commit, ethereum/tests.git
private val shacommit = "289b3e4524786618c7ec253b516bc8e76350f947"
@After
fun recover() {
SystemProperties.getDefault()!!.blockchainConfig = MainNetConfig()
}
@Ignore
@Test
@Throws(ParseException::class)
fun runSingle() {
val json = JSONReader.loadJSONFromCommit("VMTests/vmEnvironmentalInfoTest.json", shacommit)
GitHubJSONTestSuite.runGitHubJsonVMTest(json, "ExtCodeSizeAddressInputTooBigRightMyAddress")
}
@Test
@Throws(ParseException::class)
fun testArithmeticFromGitHub() {
val excluded = HashSet<String>()
// TODO: these are excluded due to bad wrapping behavior in ADDMOD/DataWord.add
val json = JSONReader.loadJSONFromCommit("VMTests/vmArithmeticTest.json", shacommit)
//String json = JSONReader.getTestBlobForTreeSha(shacommit, "vmArithmeticTest.json");
GitHubJSONTestSuite.runGitHubJsonVMTest(json, excluded)
}
@Test // testing full suite
@Throws(ParseException::class)
fun testBitwiseLogicOperationFromGitHub() {
val excluded = HashSet<String>()
val json = JSONReader.loadJSONFromCommit("VMTests/vmBitwiseLogicOperationTest.json", shacommit)
GitHubJSONTestSuite.runGitHubJsonVMTest(json, excluded)
}
@Test // testing full suite
@Throws(ParseException::class)
fun testBlockInfoFromGitHub() {
val excluded = HashSet<String>()
val json = JSONReader.loadJSONFromCommit("VMTests/vmBlockInfoTest.json", shacommit)
GitHubJSONTestSuite.runGitHubJsonVMTest(json, excluded)
}
@Ignore
@Test // testing full suite
@Throws(ParseException::class)
fun testEnvironmentalInfoFromGitHub() {
val excluded = HashSet<String>()
val json = JSONReader.loadJSONFromCommit("VMTests/vmEnvironmentalInfoTest.json", shacommit)
GitHubJSONTestSuite.runGitHubJsonVMTest(json, excluded)
}
@Test // testing full suite
@Throws(ParseException::class)
fun testIOandFlowOperationsFromGitHub() {
val excluded = HashSet<String>()
val json = JSONReader.loadJSONFromCommit("VMTests/vmIOandFlowOperationsTest.json", shacommit)
GitHubJSONTestSuite.runGitHubJsonVMTest(json, excluded)
}
@Ignore //FIXME - 60M - need new fast downloader
@Test
@Throws(ParseException::class)
fun testvmInputLimitsTest1FromGitHub() {
val excluded = HashSet<String>()
val json = JSONReader.loadJSONFromCommit("VMTests/vmInputLimits1.json", shacommit)
GitHubJSONTestSuite.runGitHubJsonVMTest(json, excluded)
}
@Ignore //FIXME - 50M - need to handle large filesizes
@Test
@Throws(ParseException::class)
fun testvmInputLimitsTest2FromGitHub() {
val excluded = HashSet<String>()
val json = JSONReader.loadJSONFromCommit("VMTests/vmInputLimits2.json", shacommit)
GitHubJSONTestSuite.runGitHubJsonVMTest(json, excluded)
}
@Ignore //FIXME - 20M - possibly provide percentage indicator
@Test
@Throws(ParseException::class)
fun testvmInputLimitsLightTestFromGitHub() {
val excluded = HashSet<String>()
val json = JSONReader.loadJSONFromCommit("VMTests/vmInputLimitsLight.json", shacommit)
GitHubJSONTestSuite.runGitHubJsonVMTest(json, excluded)
}
@Test // testing full suite
@Throws(ParseException::class)
fun testVMLogGitHub() {
val excluded = HashSet<String>()
val json = JSONReader.loadJSONFromCommit("VMTests/vmLogTest.json", shacommit)
GitHubJSONTestSuite.runGitHubJsonVMTest(json, excluded)
}
@Test // testing full suite
@Throws(ParseException::class)
fun testPerformanceFromGitHub() {
val excluded = HashSet<String>()
val json = JSONReader.loadJSONFromCommit("VMTests/vmPerformanceTest.json", shacommit)
GitHubJSONTestSuite.runGitHubJsonVMTest(json, excluded)
}
@Test // testing full suite
@Throws(ParseException::class)
fun testPushDupSwapFromGitHub() {
val excluded = HashSet<String>()
val json = JSONReader.loadJSONFromCommit("VMTests/vmPushDupSwapTest.json", shacommit)
GitHubJSONTestSuite.runGitHubJsonVMTest(json, excluded)
}
@Test // testing full suite
@Throws(ParseException::class)
fun testShaFromGitHub() {
val excluded = HashSet<String>()
val json = JSONReader.loadJSONFromCommit("VMTests/vmSha3Test.json", shacommit)
GitHubJSONTestSuite.runGitHubJsonVMTest(json, excluded)
}
@Test // testing full suite
@Throws(ParseException::class)
fun testvmSystemOperationsTestGitHub() {
val excluded = HashSet<String>()
val json = JSONReader.loadJSONFromCommit("VMTests/vmSystemOperationsTest.json", shacommit)
GitHubJSONTestSuite.runGitHubJsonVMTest(json, excluded)
}
@Test // testing full suite
@Throws(ParseException::class)
fun testVMGitHub() {
val excluded = HashSet<String>()
val json = JSONReader.loadJSONFromCommit("VMTests/vmtests.json", shacommit)
GitHubJSONTestSuite.runGitHubJsonVMTest(json, excluded)
}
@Test // testing full suite
@Throws(ParseException::class)
fun testRandomVMGitHub() {
val shacommit = "c5eafb85390eee59b838a93ae31bc16a5fd4f7b1"
val fileNames = getFileNamesForTreeSha(shacommit)
val excludedFiles = listOf("")
for (fileName in fileNames) {
if (excludedFiles.contains(fileName)) continue
println("Running: " + fileName)
val json = JSONReader.loadJSON("VMTests//RandomTests/" + fileName)
GitHubJSONTestSuite.runGitHubJsonVMTest(json)
}
}
}
| mit | 4668e3da43470c3f1184e3dced347af1 | 37.30102 | 103 | 0.719329 | 4.079891 | false | true | false | false |
jwren/intellij-community | platform/execution/src/com/intellij/execution/runToolbar/RunToolbarProcess.kt | 5 | 2016 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.execution.runToolbar
import com.intellij.application.options.RegistryManager
import com.intellij.openapi.extensions.ExtensionPointName
import com.intellij.ui.JBColor
import org.jetbrains.annotations.Nls
import javax.swing.Icon
interface RunToolbarProcess {
companion object {
const val RUN_WIDGET_MORE_ACTION_GROUP = "RunToolbarMoreActionGroup"
const val RUN_WIDGET_GROUP = "RunToolbarProcessActionGroup"
const val RUN_WIDGET_MAIN_GROUP = "RunToolbarProcessMainActionGroup"
const val ACTIVE_STATE_BUTTONS_COUNT = 3
@JvmStatic
val isAvailable: Boolean
get() = RegistryManager.getInstance().`is`("ide.widget.toolbar")
@JvmStatic
val isSettingsAvailable: Boolean
get() = RegistryManager.getInstance().`is`("ide.widget.toolbar.is.settings.available") && isAvailable
val logNeeded: Boolean
get() = RegistryManager.getInstance().`is`("ide.widget.toolbar.logging")
@JvmStatic
val isExperimentalUpdatingEnabled: Boolean
get() = RegistryManager.getInstance().`is`("ide.widget.toolbar.experimentalUpdating")
val EP_NAME: ExtensionPointName<RunToolbarProcess> = ExtensionPointName("com.intellij.runToolbarProcess")
@JvmStatic
fun getProcesses(): List<RunToolbarProcess> = EP_NAME.extensionList
@JvmStatic
fun getProcessesByExecutorId(executorId: String): List<RunToolbarProcess> {
return getProcesses().filter { it.executorId == executorId }.toList()
}
}
val ID: String
val executorId: String
val name: @Nls String
val shortName: @Nls String
val actionId: String
fun getMainActionId(): String = "main$actionId"
val moreActionSubGroupName: String
val showInBar: Boolean
fun isTemporaryProcess(): Boolean = false
fun rerunAvailable(): Boolean = false
fun getStopIcon(): Icon? = null
val pillColor: JBColor
} | apache-2.0 | f19806331bb260741a833af2f0e18803 | 32.065574 | 158 | 0.749008 | 4.540541 | false | false | false | false |
jwren/intellij-community | platform/platform-impl/src/com/intellij/ide/plugins/HeadlessPluginsInstaller.kt | 4 | 1796 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.ide.plugins
import com.intellij.openapi.application.ApplicationStarter
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.extensions.PluginId
import com.intellij.openapi.updateSettings.impl.pluginsAdvertisement.installAndEnable
import com.intellij.util.io.URLUtil
import kotlin.system.exitProcess
internal class HeadlessPluginsInstaller : ApplicationStarter {
@Suppress("SSBasedInspection")
private val LOG = logger<HeadlessPluginsInstaller>()
override fun getCommandName(): String = "installPlugins"
override fun getRequiredModality(): Int = ApplicationStarter.NOT_IN_EDT
override fun main(args: List<String>) {
try {
val pluginIds = LinkedHashSet<PluginId>()
val customRepositories = LinkedHashSet<String>()
for (i in 1 until args.size) {
val arg = args[i]
when {
arg.contains(URLUtil.SCHEME_SEPARATOR) -> customRepositories += arg
else -> pluginIds += PluginId.getId(arg)
}
}
if (customRepositories.isNotEmpty()) {
val hosts = System.getProperty("idea.plugin.hosts")
val newHosts = customRepositories.joinToString(separator = ";", prefix = if (hosts.isNullOrBlank()) "" else "${hosts};")
System.setProperty("idea.plugin.hosts", newHosts)
println("plugin hosts: ${newHosts}")
LOG.info("plugin hosts: ${newHosts}")
}
println("installing: ${pluginIds}")
LOG.info("installing: ${pluginIds}")
installAndEnable(null, pluginIds) {}
exitProcess(0)
}
catch (t: Throwable) {
LOG.error(t)
exitProcess(1)
}
}
}
| apache-2.0 | a89a6a078241e367d7f7992fdfd115fb | 35.653061 | 158 | 0.695434 | 4.412776 | false | false | false | false |
GunoH/intellij-community | platform/platform-impl/src/com/intellij/openapi/wm/impl/headertoolbar/ProjectWidget.kt | 1 | 8349 | // 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.openapi.wm.impl.headertoolbar
import com.intellij.ide.*
import com.intellij.ide.impl.ProjectUtilCore
import com.intellij.ide.plugins.newui.ListPluginComponent
import com.intellij.openapi.actionSystem.*
import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.popup.JBPopupFactory
import com.intellij.openapi.ui.popup.ListPopup
import com.intellij.openapi.ui.popup.ListPopupStep
import com.intellij.openapi.ui.popup.ListSeparator
import com.intellij.openapi.ui.popup.util.PopupUtil
import com.intellij.openapi.util.Key
import com.intellij.openapi.util.io.FileUtil
import com.intellij.openapi.wm.impl.ToolbarComboWidget
import com.intellij.ui.GroupHeaderSeparator
import com.intellij.ui.components.panels.NonOpaquePanel
import com.intellij.ui.dsl.builder.AlignY
import com.intellij.ui.dsl.builder.EmptySpacingConfiguration
import com.intellij.ui.dsl.builder.panel
import com.intellij.ui.dsl.gridLayout.JBGaps
import com.intellij.ui.popup.PopupFactoryImpl
import com.intellij.ui.popup.list.ListPopupModel
import com.intellij.ui.popup.list.SelectablePanel
import com.intellij.ui.popup.util.PopupImplUtil
import com.intellij.util.PathUtil
import com.intellij.util.ui.JBFont
import com.intellij.util.ui.JBUI
import com.intellij.util.ui.NamedColorUtil
import com.intellij.util.ui.UIUtil
import com.intellij.util.ui.accessibility.AccessibleContextUtil
import java.awt.BorderLayout
import java.awt.Component
import java.awt.event.InputEvent
import java.util.function.Function
import javax.swing.*
private const val MAX_RECENT_COUNT = 100
internal val projectKey = Key.create<Project>("project-widget-project")
internal class ProjectWidget(private val presentation: Presentation) : ToolbarComboWidget() {
private val project: Project?
get() = presentation.getClientProperty(projectKey)
init {
presentation.addPropertyChangeListener { updateWidget() }
}
override fun updateWidget() {
text = presentation.text
toolTipText = presentation.description
}
override fun doExpand(e: InputEvent?) {
val dataContext = DataManager.getInstance().getDataContext(this)
val anActionEvent = AnActionEvent.createFromInputEvent(e, ActionPlaces.PROJECT_WIDGET_POPUP, null, dataContext)
val step = createStep(createActionGroup(anActionEvent))
val widgetRenderer = ProjectWidgetRenderer()
val renderer = Function<ListCellRenderer<Any>, ListCellRenderer<out Any>> { base ->
ListCellRenderer<PopupFactoryImpl.ActionItem> { list, value, index, isSelected, cellHasFocus ->
val action = (value as PopupFactoryImpl.ActionItem).action
if (action is ReopenProjectAction) {
widgetRenderer.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus)
}
else {
base.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus)
}
}
}
project?.let { createPopup(it, step, renderer) }?.showUnderneathOf(this)
}
private fun createPopup(it: Project, step: ListPopupStep<Any>, renderer: Function<ListCellRenderer<Any>, ListCellRenderer<out Any>>): ListPopup {
val res = JBPopupFactory.getInstance().createListPopup(it, step, renderer)
PopupImplUtil.setPopupToggleButton(res, this)
res.setRequestFocus(false)
return res
}
private fun createActionGroup(initEvent: AnActionEvent): ActionGroup {
val res = DefaultActionGroup()
val group = ActionManager.getInstance().getAction("ProjectWidget.Actions") as ActionGroup
res.addAll(group.getChildren(initEvent).asList())
val openProjects = ProjectUtilCore.getOpenProjects()
val actionsMap: Map<Boolean, List<AnAction>> = RecentProjectListActionProvider.getInstance().getActions().take(MAX_RECENT_COUNT).groupBy(createSelector(openProjects))
actionsMap[true]?.let {
res.addSeparator(IdeBundle.message("project.widget.open.projects"))
res.addAll(it)
}
actionsMap[false]?.let {
res.addSeparator(IdeBundle.message("project.widget.recent.projects"))
res.addAll(it)
}
return res
}
private fun createSelector(openProjects: Array<Project>): (AnAction) -> Boolean {
val paths = openProjects.map { it.basePath }
return { action -> (action as? ReopenProjectAction)?.projectPath in paths }
}
private fun createStep(actionGroup: ActionGroup): ListPopupStep<Any> {
val context = DataManager.getInstance().getDataContext(this)
return JBPopupFactory.getInstance().createActionsStep(actionGroup, context, ActionPlaces.PROJECT_WIDGET_POPUP, false, false,
null, this, false, 0, false)
}
private class ProjectWidgetRenderer : ListCellRenderer<PopupFactoryImpl.ActionItem> {
override fun getListCellRendererComponent(list: JList<out PopupFactoryImpl.ActionItem>?,
value: PopupFactoryImpl.ActionItem?,
index: Int,
isSelected: Boolean,
cellHasFocus: Boolean): Component {
return createRecentProjectPane(value as PopupFactoryImpl.ActionItem, isSelected, getSeparator(list, value), index == 0)
}
private fun getSeparator(list: JList<out PopupFactoryImpl.ActionItem>?, value: PopupFactoryImpl.ActionItem?): ListSeparator? {
val model = list?.model as? ListPopupModel<*> ?: return null
val hasSeparator = model.isSeparatorAboveOf(value)
if (!hasSeparator) return null
return ListSeparator(model.getCaptionAboveOf(value))
}
private fun createRecentProjectPane(value: PopupFactoryImpl.ActionItem, isSelected: Boolean, separator: ListSeparator?, hideLine: Boolean): JComponent {
val action = value.action as ReopenProjectAction
val projectPath = action.projectPath
lateinit var nameLbl: JLabel
lateinit var pathLbl: JLabel
val content = panel {
customizeSpacingConfiguration(EmptySpacingConfiguration()) {
row {
icon(RecentProjectsManagerBase.getInstanceEx().getProjectIcon(projectPath, true))
.align(AlignY.TOP)
.customize(JBGaps(right = 8))
panel {
row {
nameLbl = label(action.projectNameToDisplay ?: "")
.customize(JBGaps(bottom = 4))
.applyToComponent {
foreground = if (isSelected) NamedColorUtil.getListSelectionForeground(true) else UIUtil.getListForeground()
}.component
}
row {
pathLbl = label(FileUtil.getLocationRelativeToUserHome(PathUtil.toSystemDependentName(projectPath), false))
.applyToComponent {
font = JBFont.smallOrNewUiMedium()
foreground = UIUtil.getLabelInfoForeground()
}.component
}
}
}
}
}.apply {
border = JBUI.Borders.empty(8, 0)
isOpaque = false
}
val result = SelectablePanel.wrap(content, JBUI.CurrentTheme.Popup.BACKGROUND)
PopupUtil.configListRendererFlexibleHeight(result)
if (isSelected) {
result.selectionColor = ListPluginComponent.SELECTION_COLOR
}
AccessibleContextUtil.setCombinedName(result, nameLbl, " - ", pathLbl)
AccessibleContextUtil.setCombinedDescription(result, nameLbl, " - ", pathLbl)
if (separator == null) {
return result
}
val res = NonOpaquePanel(BorderLayout())
res.border = JBUI.Borders.empty()
res.add(createSeparator(separator, hideLine), BorderLayout.NORTH)
res.add(result, BorderLayout.CENTER)
return res
}
private fun createSeparator(separator: ListSeparator, hideLine: Boolean): JComponent {
val res = GroupHeaderSeparator(JBUI.CurrentTheme.Popup.separatorLabelInsets())
res.caption = separator.text
res.setHideLine(hideLine)
val panel = JPanel(BorderLayout())
panel.border = JBUI.Borders.empty()
panel.isOpaque = true
panel.background = JBUI.CurrentTheme.Popup.BACKGROUND
panel.add(res)
return panel
}
}
}
| apache-2.0 | 59a7d62cec5b7c487110b56f02685f1c | 39.726829 | 170 | 0.704156 | 4.823224 | false | false | false | false |
GunoH/intellij-community | platform/workspaceModel/jps/tests/testSrc/com/intellij/workspaceModel/ide/StoreSnapshotsAnalyzer.kt | 2 | 3483 | // Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.workspaceModel.ide
import com.intellij.workspaceModel.storage.EntitySource
import com.intellij.workspaceModel.storage.bridgeEntities.ModuleEntity
import com.intellij.workspaceModel.storage.impl.EntityStorageSerializerImpl
import com.intellij.workspaceModel.storage.impl.MatchedEntitySource
import com.intellij.workspaceModel.storage.impl.SimpleEntityTypesResolver
import com.intellij.workspaceModel.storage.impl.url.VirtualFileUrlManagerImpl
import com.intellij.workspaceModel.storage.toBuilder
import java.io.File
import kotlin.system.exitProcess
/**
* This is a boilerplate code for analyzing state of entity stores that were received as attachments to exceptions
*/
fun main(args: Array<String>) {
if (args.size != 1) {
println("Usage: com.intellij.workspaceModel.ide.StoreSnapshotsAnalyzerKt <path to directory with storage files>")
exitProcess(1)
}
val file = File(args[0])
if (!file.exists()) {
throw IllegalArgumentException("$file doesn't exist")
}
if (file.isFile) {
val serializer = EntityStorageSerializerImpl(SimpleEntityTypesResolver, VirtualFileUrlManagerImpl())
val storage = file.inputStream().use {
serializer.deserializeCache(it).getOrThrow()
}
// Set a breakpoint and check
println("Cache loaded: ${storage!!.entities(ModuleEntity::class.java).toList().size} modules")
return
}
val leftFile = file.resolve("Left_Store")
val rightFile = file.resolve("Right_Store")
val rightDiffLogFile = file.resolve("Right_Diff_Log")
val converterFile = file.resolve("ClassToIntConverter")
val resFile = file.resolve("Res_Store")
val serializer = EntityStorageSerializerImpl(SimpleEntityTypesResolver, VirtualFileUrlManagerImpl())
serializer.deserializeClassToIntConverter(converterFile.inputStream())
val resStore = serializer.deserializeCache(resFile.inputStream()).getOrThrow()!!
val leftStore = serializer.deserializeCache(leftFile.inputStream()).getOrThrow() ?: throw IllegalArgumentException("Cannot load cache")
if (file.resolve("Replace_By_Source").exists()) {
val rightStore = serializer.deserializeCache(rightFile.inputStream()).getOrThrow()!!
val allEntitySources = leftStore.entitiesBySource { true }.map { it.key }.toHashSet()
allEntitySources.addAll(rightStore.entitiesBySource { true }.map { it.key })
val pattern = if (file.resolve("Report_Wrapped").exists()) {
matchedPattern()
}
else {
val sortedSources = allEntitySources.sortedBy { it.toString() }
patternFilter(file.resolve("Replace_By_Source").readText(), sortedSources)
}
val expectedResult = leftStore.toBuilder()
expectedResult.replaceBySource(pattern, rightStore)
// Set a breakpoint and check
println("storage loaded")
}
else {
val rightStore = serializer.deserializeCacheAndDiffLog(rightFile.inputStream(), rightDiffLogFile.inputStream())!!
val expectedResult = leftStore.toBuilder()
expectedResult.addDiff(rightStore)
// Set a breakpoint and check
println("storage loaded")
}
}
fun patternFilter(pattern: String, sortedSources: List<EntitySource>): (EntitySource) -> Boolean {
return {
val idx = sortedSources.indexOf(it)
pattern[idx] == '1'
}
}
fun matchedPattern(): (EntitySource) -> Boolean {
return {
it is MatchedEntitySource
}
}
| apache-2.0 | 6fdb91913c741697dd3785ca1e7b0e74 | 36.053191 | 140 | 0.751077 | 4.494194 | false | false | false | false |
jwren/intellij-community | plugins/kotlin/analysis/src/org/jetbrains/kotlin/idea/caches/resolve/IDEKotlinAsJavaSupport.kt | 1 | 11408 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.caches.resolve
import com.intellij.openapi.project.Project
import com.intellij.psi.*
import com.intellij.psi.search.GlobalSearchScope
import com.intellij.util.SmartList
import org.jetbrains.kotlin.analysis.decompiled.light.classes.DecompiledLightClassesFactory
import org.jetbrains.kotlin.analysis.decompiled.light.classes.DecompiledLightClassesFactory.getLightClassForDecompiledClassOrObject
import org.jetbrains.kotlin.analysis.decompiled.light.classes.KtLightClassForDecompiledDeclaration
import org.jetbrains.kotlin.analysis.decompiler.psi.file.KtClsFile
import org.jetbrains.kotlin.asJava.KotlinAsJavaSupport
import org.jetbrains.kotlin.asJava.classes.*
import org.jetbrains.kotlin.config.JvmAnalysisFlags
import org.jetbrains.kotlin.fileClasses.javaFileFacadeFqName
import org.jetbrains.kotlin.idea.caches.lightClasses.platformMutabilityWrapper
import org.jetbrains.kotlin.idea.caches.project.*
import org.jetbrains.kotlin.idea.caches.project.IdeaModuleInfo
import org.jetbrains.kotlin.idea.decompiler.navigation.SourceNavigationHelper
import org.jetbrains.kotlin.idea.project.getLanguageVersionSettings
import org.jetbrains.kotlin.idea.project.platform
import org.jetbrains.kotlin.idea.stubindex.*
import org.jetbrains.kotlin.idea.util.ProjectRootsUtil
import org.jetbrains.kotlin.idea.util.application.runReadAction
import org.jetbrains.kotlin.idea.util.application.withPsiAttachment
import org.jetbrains.kotlin.idea.util.runReadActionInSmartMode
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.platform.jvm.JvmPlatforms
import org.jetbrains.kotlin.platform.jvm.isJvm
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.resolve.scopes.MemberScope
open class IDEKotlinAsJavaSupport(private val project: Project) : KotlinAsJavaSupport() {
private val psiManager: PsiManager = PsiManager.getInstance(project)
private val languageVersionSettings = project.getLanguageVersionSettings()
override fun getFacadeNames(packageFqName: FqName, scope: GlobalSearchScope): Collection<String> {
val facadeFilesInPackage = project.runReadActionInSmartMode {
KotlinFileFacadeClassByPackageIndex.get(packageFqName.asString(), project, scope)
}
return facadeFilesInPackage.map { it.javaFileFacadeFqName.shortName().asString() }.toSet()
}
override fun getFacadeClassesInPackage(packageFqName: FqName, scope: GlobalSearchScope): Collection<PsiClass> {
val facadeFilesInPackage = runReadAction {
KotlinFileFacadeClassByPackageIndex.get(packageFqName.asString(), project, scope).platformSourcesFirst()
}
val groupedByFqNameAndModuleInfo = facadeFilesInPackage.groupBy {
Pair(it.javaFileFacadeFqName, it.getModuleInfoPreferringJvmPlatform())
}
return groupedByFqNameAndModuleInfo.flatMap {
val (key, files) = it
val (fqName, moduleInfo) = key
createLightClassForFileFacade(fqName, files, moduleInfo)
}
}
override fun findClassOrObjectDeclarations(fqName: FqName, searchScope: GlobalSearchScope): Collection<KtClassOrObject> {
return project.runReadActionInSmartMode {
KotlinFullClassNameIndex.get(
fqName.asString(),
project,
KotlinSourceFilterScope.sourceAndClassFiles(searchScope, project)
)
}
}
override fun findFilesForPackage(fqName: FqName, searchScope: GlobalSearchScope): Collection<KtFile> {
return project.runReadActionInSmartMode {
PackageIndexUtil.findFilesWithExactPackage(
fqName,
KotlinSourceFilterScope.sourceAndClassFiles(
searchScope,
project
),
project
)
}
}
override fun findClassOrObjectDeclarationsInPackage(
packageFqName: FqName,
searchScope: GlobalSearchScope
): Collection<KtClassOrObject> {
return KotlinTopLevelClassByPackageIndex.get(
packageFqName.asString(), project,
KotlinSourceFilterScope.sourceAndClassFiles(searchScope, project)
)
}
override fun packageExists(fqName: FqName, scope: GlobalSearchScope): Boolean {
return PackageIndexUtil.packageExists(
fqName,
KotlinSourceFilterScope.sourceAndClassFiles(
scope,
project
)
)
}
override fun getSubPackages(fqn: FqName, scope: GlobalSearchScope): Collection<FqName> {
return PackageIndexUtil.getSubPackageFqNames(
fqn,
KotlinSourceFilterScope.sourceAndClassFiles(
scope,
project
),
MemberScope.ALL_NAME_FILTER
)
}
private val recursiveGuard = ThreadLocal<Boolean>()
private inline fun <T> guardedRun(body: () -> T): T? {
if (recursiveGuard.get() == true) return null
return try {
recursiveGuard.set(true)
body()
} finally {
recursiveGuard.set(false)
}
}
override fun getLightClass(classOrObject: KtClassOrObject): KtLightClass? {
if (!classOrObject.isValid) {
return null
}
val virtualFile = classOrObject.containingFile.virtualFile
if (virtualFile != null) {
when {
ProjectRootsUtil.isProjectSourceFile(project, virtualFile) ->
return KtLightClassForSourceDeclaration.create(
classOrObject,
languageVersionSettings.getFlag(JvmAnalysisFlags.jvmDefaultMode)
)
ProjectRootsUtil.isLibraryClassFile(project, virtualFile) ->
return getLightClassForDecompiledClassOrObject(classOrObject, project)
ProjectRootsUtil.isLibrarySourceFile(project, virtualFile) ->
return guardedRun {
SourceNavigationHelper.getOriginalClass(classOrObject) as? KtLightClass
}
}
}
if ((classOrObject.containingFile as? KtFile)?.analysisContext != null ||
classOrObject.containingFile.originalFile.virtualFile != null
) {
// explicit request to create light class from dummy.kt
return KtLightClassForSourceDeclaration.create(classOrObject, languageVersionSettings.getFlag(JvmAnalysisFlags.jvmDefaultMode))
}
return null
}
override fun getLightClassForScript(script: KtScript): KtLightClass? {
if (!script.isValid) {
return null
}
return KtLightClassForScript.create(script)
}
override fun getFacadeClasses(facadeFqName: FqName, scope: GlobalSearchScope): Collection<PsiClass> {
val filesByModule = findFilesForFacade(facadeFqName, scope).groupBy(PsiElement::getModuleInfoPreferringJvmPlatform)
return filesByModule.flatMap {
createLightClassForFileFacade(facadeFqName, it.value, it.key)
}
}
override fun getScriptClasses(scriptFqName: FqName, scope: GlobalSearchScope): Collection<PsiClass> {
return KotlinScriptFqnIndex.get(scriptFqName.asString(), project, scope).mapNotNull {
getLightClassForScript(it)
}
}
override fun getKotlinInternalClasses(fqName: FqName, scope: GlobalSearchScope): Collection<PsiClass> {
if (fqName.isRoot) return emptyList()
val packageParts = findPackageParts(fqName, scope)
val platformWrapper = findPlatformWrapper(fqName, scope)
return if (platformWrapper != null) packageParts + platformWrapper else packageParts
}
private fun findPackageParts(fqName: FqName, scope: GlobalSearchScope): List<KtLightClassForDecompiledDeclaration> {
val facadeKtFiles = StaticFacadeIndexUtil.getMultifileClassForPart(fqName, scope, project)
val partShortName = fqName.shortName().asString()
val partClassFileShortName = "$partShortName.class"
return facadeKtFiles.mapNotNull { facadeKtFile ->
if (facadeKtFile is KtClsFile) {
val partClassFile = facadeKtFile.virtualFile.parent.findChild(partClassFileShortName) ?: return@mapNotNull null
val javaClsClass = DecompiledLightClassesFactory.createClsJavaClassFromVirtualFile(facadeKtFile, partClassFile, null, project) ?: return@mapNotNull null
KtLightClassForDecompiledDeclaration(javaClsClass, javaClsClass.parent, facadeKtFile, null)
} else {
// TODO should we build light classes for parts from source?
null
}
}
}
private fun findPlatformWrapper(fqName: FqName, scope: GlobalSearchScope): PsiClass? {
return platformMutabilityWrapper(fqName) {
JavaPsiFacade.getInstance(
project
).findClass(it, scope)
}
}
private fun createLightClassForFileFacade(
facadeFqName: FqName,
facadeFiles: List<KtFile>,
moduleInfo: IdeaModuleInfo
): List<PsiClass> = SmartList<PsiClass>().apply {
tryCreateFacadesForSourceFiles(moduleInfo, facadeFqName)?.let { sourcesFacade ->
add(sourcesFacade)
}
facadeFiles.filterIsInstance<KtClsFile>().mapNotNullTo(this) {
DecompiledLightClassesFactory.createLightClassForDecompiledKotlinFile(it, project)
}
}
private fun tryCreateFacadesForSourceFiles(moduleInfo: IdeaModuleInfo, facadeFqName: FqName): PsiClass? {
if (moduleInfo !is ModuleSourceInfo && moduleInfo !is PlatformModuleInfo) return null
return KtLightClassForFacadeImpl.createForFacade(psiManager, facadeFqName, moduleInfo.contentScope())
}
override fun findFilesForFacade(facadeFqName: FqName, scope: GlobalSearchScope): Collection<KtFile> {
return runReadAction {
KotlinFileFacadeFqNameIndex.get(facadeFqName.asString(), project, scope).platformSourcesFirst()
}
}
override fun getFakeLightClass(classOrObject: KtClassOrObject): KtFakeLightClass =
KtDescriptorBasedFakeLightClass(classOrObject)
override fun createFacadeForSyntheticFile(facadeClassFqName: FqName, file: KtFile): PsiClass =
KtLightClassForFacadeImpl.createForSyntheticFile(facadeClassFqName, file)
// NOTE: this is a hacky solution to the following problem:
// when building this light class resolver will be built by the first file in the list
// (we could assume that files are in the same module before)
// thus we need to ensure that resolver will be built by the file from platform part of the module
// (resolver built by a file from the common part will have no knowledge of the platform part)
// the actual of order of files that resolver receives is controlled by *findFilesForFacade* method
private fun Collection<KtFile>.platformSourcesFirst() = sortedByDescending { it.platform.isJvm() }
}
internal fun PsiElement.getModuleInfoPreferringJvmPlatform(): IdeaModuleInfo {
return getPlatformModuleInfo(JvmPlatforms.unspecifiedJvmPlatform) ?: getModuleInfo()
}
| apache-2.0 | 8172ae3063753aa5f8026d9b884c0bef | 43.5625 | 168 | 0.70696 | 5.545941 | false | false | false | false |
stefanmedack/cccTV | app/src/main/java/de/stefanmedack/ccctv/util/RxExtensions.kt | 1 | 805 | package de.stefanmedack.ccctv.util
import io.reactivex.*
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
fun <T> Single<T>.applySchedulers(): Single<T> = subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
fun <T> Flowable<T>.applySchedulers(): Flowable<T> = subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
fun <T> Observable<T>.applySchedulers(): Observable<T> = subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
fun Completable.applySchedulers(): Completable = subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
fun <T> createFlowable(strategy: BackpressureStrategy, onSubscribe: (Emitter<T>) -> Unit): Flowable<T>
= Flowable.create(onSubscribe, strategy) | apache-2.0 | 3c1bd49cd274fa349d97f8a08a030206 | 49.375 | 127 | 0.786335 | 4.472222 | false | false | false | false |
GunoH/intellij-community | platform/platform-api/src/com/intellij/ide/actions/CollapseAllAction.kt | 3 | 1854 | // 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.ide.actions
import com.intellij.ide.TreeExpander
import com.intellij.openapi.actionSystem.ActionPlaces
import com.intellij.openapi.actionSystem.ActionUpdateThread
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.actionSystem.IdeActions.ACTION_COLLAPSE_ALL
import com.intellij.openapi.actionSystem.PlatformDataKeys
import com.intellij.openapi.actionSystem.PlatformDataKeys.TREE_EXPANDER
import com.intellij.openapi.actionSystem.ex.ActionUtil.copyFrom
import com.intellij.openapi.project.DumbAwareAction
import com.intellij.ui.ExperimentalUI
class CollapseAllAction : DumbAwareAction {
private val getTreeExpander: (AnActionEvent) -> TreeExpander?
constructor() : super() {
getTreeExpander = { it.getData(TREE_EXPANDER) }
}
constructor(getExpander: (AnActionEvent) -> TreeExpander?) : super() {
getTreeExpander = getExpander
copyFrom(this, ACTION_COLLAPSE_ALL)
}
override fun actionPerformed(event: AnActionEvent) {
val expander = getTreeExpander(event) ?: return
if (expander.canCollapse()) expander.collapseAll()
}
override fun getActionUpdateThread() = ActionUpdateThread.EDT
override fun update(event: AnActionEvent) {
val expander = getTreeExpander(event)
val hideIfMissing = event.getData(PlatformDataKeys.TREE_EXPANDER_HIDE_ACTIONS_IF_NO_EXPANDER) ?: false
event.presentation.isVisible = expander == null && !hideIfMissing ||
expander != null && expander.isCollapseAllVisible
event.presentation.isEnabled = expander != null && expander.canCollapse()
if (ExperimentalUI.isNewUI() && ActionPlaces.isPopupPlace(event.place)) {
event.presentation.icon = null
}
}
}
| apache-2.0 | 552a78b71ca30e754df6a967fc8bf453 | 41.136364 | 120 | 0.764833 | 4.658291 | false | false | false | false |
smmribeiro/intellij-community | plugins/kotlin/fir-low-level-api/src/org/jetbrains/kotlin/idea/fir/low/level/api/file/builder/ModuleFileCache.kt | 2 | 3484 | /*
* Copyright 2010-2020 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlin.idea.fir.low.level.api.file.builder
import org.jetbrains.kotlin.fir.FirSession
import org.jetbrains.kotlin.fir.declarations.FirClassLikeDeclaration
import org.jetbrains.kotlin.fir.declarations.FirDeclaration
import org.jetbrains.kotlin.fir.declarations.FirFile
import org.jetbrains.kotlin.fir.psi
import org.jetbrains.kotlin.fir.render
import org.jetbrains.kotlin.fir.symbols.CallableId
import org.jetbrains.kotlin.fir.symbols.impl.FirCallableSymbol
import org.jetbrains.kotlin.name.ClassId
import org.jetbrains.kotlin.psi.KtFile
import java.util.*
import java.util.concurrent.ConcurrentHashMap
import java.util.concurrent.locks.ReentrantLock
import java.util.concurrent.locks.ReentrantReadWriteLock
import org.jetbrains.kotlin.idea.fir.low.level.api.annotations.ThreadSafe
import kotlin.concurrent.withLock
/**
* Caches mapping [KtFile] -> [FirFile] of module [moduleInfo]
*/
@ThreadSafe
internal abstract class ModuleFileCache {
abstract val session: FirSession
/**
* Maps [ClassId] to corresponding classifiers
* If classifier with required [ClassId] is not found in given module then map contains [Optional.EMPTY]
*/
abstract val classifierByClassId: ConcurrentHashMap<ClassId, Optional<FirClassLikeDeclaration<*>>>
/**
* Maps [CallableId] to corresponding callable
* If callable with required [CallableId]] is not found in given module then map contains emptyList
*/
abstract val callableByCallableId: ConcurrentHashMap<CallableId, List<FirCallableSymbol<*>>>
/**
* @return [FirFile] by [file] if it was previously built or runs [createValue] otherwise
* The [createValue] is run under the lock so [createValue] is executed at most once for each [KtFile]
*/
abstract fun fileCached(file: KtFile, createValue: () -> FirFile): FirFile
abstract fun getContainerFirFile(declaration: FirDeclaration): FirFile?
abstract fun getCachedFirFile(ktFile: KtFile): FirFile?
abstract val firFileLockProvider: LockProvider<FirFile>
inline fun <D : FirDeclaration, R> withReadLockOn(declaration: D, action: (D) -> R): R {
val file = getContainerFirFile(declaration)
?: error("No fir file found for\n${declaration.render()}")
return firFileLockProvider.withReadLock(file) { action(declaration) }
}
}
internal class ModuleFileCacheImpl(override val session: FirSession) : ModuleFileCache() {
private val ktFileToFirFile = ConcurrentHashMap<KtFile, FirFile>()
override val classifierByClassId: ConcurrentHashMap<ClassId, Optional<FirClassLikeDeclaration<*>>> = ConcurrentHashMap()
override val callableByCallableId: ConcurrentHashMap<CallableId, List<FirCallableSymbol<*>>> = ConcurrentHashMap()
override fun fileCached(file: KtFile, createValue: () -> FirFile): FirFile =
ktFileToFirFile.computeIfAbsent(file) { createValue() }
override fun getCachedFirFile(ktFile: KtFile): FirFile? = ktFileToFirFile[ktFile]
override fun getContainerFirFile(declaration: FirDeclaration): FirFile? {
val ktFile = declaration.psi?.containingFile as? KtFile ?: return null
return getCachedFirFile(ktFile)
}
override val firFileLockProvider: LockProvider<FirFile> = LockProvider()
}
| apache-2.0 | 59dc9da2733d0cea325a980cbfce4e3d | 42.55 | 124 | 0.761194 | 4.449553 | false | false | false | false |
Fotoapparat/Fotoapparat | fotoapparat/src/main/java/io/fotoapparat/preview/PreviewStream.kt | 1 | 3442 | @file:Suppress("DEPRECATION")
package io.fotoapparat.preview
import android.graphics.ImageFormat
import android.hardware.Camera
import io.fotoapparat.hardware.frameProcessingExecutor
import io.fotoapparat.hardware.orientation.Orientation
import io.fotoapparat.parameter.Resolution
import io.fotoapparat.util.FrameProcessor
import java.util.*
/**
* Preview stream of Camera.
*/
internal class PreviewStream(private val camera: Camera) {
private val frameProcessors = LinkedHashSet<FrameProcessor>()
private var previewResolution: Resolution? = null
/**
* CW orientation.
*/
var frameOrientation: Orientation = Orientation.Vertical.Portrait
/**
* Clears all processors.
*/
private fun clearProcessors() {
synchronized(frameProcessors) {
frameProcessors.clear()
}
}
/**
* Registers new processor. If processor was already added before, does nothing.
*/
private fun addProcessor(processor: FrameProcessor) {
synchronized(frameProcessors) {
frameProcessors.add(processor)
}
}
/**
* Starts preview stream. After preview is started frame processors will start receiving frames.
*/
private fun start() {
camera.addFrameToBuffer()
camera.setPreviewCallbackWithBuffer { data, _ -> dispatchFrameOnBackgroundThread(data) }
}
/**
* Stops preview stream.
*/
private fun stop() {
camera.setPreviewCallbackWithBuffer(null)
}
/**
* Updates the frame processor safely.
*/
fun updateProcessorSafely(frameProcessor: FrameProcessor?) {
clearProcessors()
if (frameProcessor == null) {
stop()
} else {
addProcessor(frameProcessor)
start()
}
}
private fun Camera.addFrameToBuffer() {
addCallbackBuffer(parameters.allocateBuffer())
}
private fun Camera.Parameters.allocateBuffer(): ByteArray {
ensureNv21Format()
previewResolution = Resolution(
previewSize.width,
previewSize.height
)
return ByteArray(previewSize.bytesPerFrame())
}
private fun dispatchFrameOnBackgroundThread(data: ByteArray) {
frameProcessingExecutor.execute {
synchronized(frameProcessors) {
dispatchFrame(data)
}
}
}
private fun dispatchFrame(image: ByteArray) {
val previewResolution = ensurePreviewSizeAvailable()
val frame = Frame(
size = previewResolution,
image = image,
rotation = frameOrientation.degrees
)
frameProcessors.forEach {
it.invoke(frame)
}
returnFrameToBuffer(frame)
}
private fun ensurePreviewSizeAvailable(): Resolution =
previewResolution
?: throw IllegalStateException("previewSize is null. Frame was not added?")
private fun returnFrameToBuffer(frame: Frame) {
camera.addCallbackBuffer(
frame.image
)
}
}
private fun Camera.Size.bytesPerFrame(): Int =
width * height * ImageFormat.getBitsPerPixel(ImageFormat.NV21) / 8
private fun Camera.Parameters.ensureNv21Format() {
if (previewFormat != ImageFormat.NV21) {
throw UnsupportedOperationException("Only NV21 preview format is supported")
}
}
| apache-2.0 | 2c833236c60bcdacd8ee681b26d268f6 | 25.075758 | 100 | 0.639454 | 5.144993 | false | false | false | false |
smmribeiro/intellij-community | platform/vcs-log/impl/src/com/intellij/vcs/log/history/VcsLogFileHistoryProviderImpl.kt | 1 | 8514 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.vcs.log.history
import com.google.common.util.concurrent.SettableFuture
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.registry.Registry
import com.intellij.openapi.vcs.FilePath
import com.intellij.openapi.vcs.VcsBundle
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.ui.content.TabGroupId
import com.intellij.vcs.log.*
import com.intellij.vcs.log.data.VcsLogData
import com.intellij.vcs.log.data.VcsLogStorage
import com.intellij.vcs.log.impl.*
import com.intellij.vcs.log.impl.VcsLogTabLocation.Companion.findLogUi
import com.intellij.vcs.log.statistics.VcsLogUsageTriggerCollector
import com.intellij.vcs.log.ui.MainVcsLogUi
import com.intellij.vcs.log.ui.VcsLogUiEx
import com.intellij.vcs.log.util.VcsLogUtil
import com.intellij.vcs.log.util.VcsLogUtil.jumpToRow
import com.intellij.vcs.log.visible.VisiblePack
import com.intellij.vcs.log.visible.filters.VcsLogFilterObject
import com.intellij.vcs.log.visible.filters.matches
import com.intellij.vcsUtil.VcsUtil
import java.util.function.Function
class VcsLogFileHistoryProviderImpl(project: Project) : VcsLogFileHistoryProvider {
private val providers = listOf(VcsLogSingleFileHistoryProvider(project), VcsLogDirectoryHistoryProvider(project))
override fun canShowFileHistory(paths: Collection<FilePath>, revisionNumber: String?): Boolean {
return providers.any { it.canShowFileHistory(paths, revisionNumber) }
}
override fun showFileHistory(paths: Collection<FilePath>, revisionNumber: String?) {
providers.firstOrNull { it.canShowFileHistory(paths, revisionNumber) }?.showFileHistory(paths, revisionNumber)
}
}
private class VcsLogDirectoryHistoryProvider(private val project: Project) : VcsLogFileHistoryProvider {
override fun canShowFileHistory(paths: Collection<FilePath>, revisionNumber: String?): Boolean {
if (!Registry.`is`("vcs.history.show.directory.history.in.log")) return false
val dataManager = VcsProjectLog.getInstance(project).dataManager ?: return false
return createPathsFilter(project, dataManager, paths) != null
}
override fun showFileHistory(paths: Collection<FilePath>, revisionNumber: String?) {
val hash = revisionNumber?.let { HashImpl.build(it) }
val root = VcsLogUtil.getActualRoot(project, paths.first())!!
triggerFileHistoryUsage(project, paths, hash)
val logManager = VcsProjectLog.getInstance(project).logManager!!
val pathsFilter = createPathsFilter(project, logManager.dataManager, paths)!!
val hashFilter = createHashFilter(hash, root)
var ui = logManager.findLogUi(VcsLogTabLocation.TOOL_WINDOW, MainVcsLogUi::class.java, true) { logUi ->
matches(logUi.filterUi.filters, pathsFilter, hashFilter)
}
val firstTime = ui == null
if (firstTime) {
val filters = VcsLogFilterObject.collection(pathsFilter, hashFilter)
ui = VcsProjectLog.getInstance(project).openLogTab(filters) ?: return
ui.properties.set(MainVcsLogUiProperties.SHOW_ONLY_AFFECTED_CHANGES, true)
}
selectRowWhenOpen(logManager, hash, root, ui!!, firstTime)
}
companion object {
private fun createPathsFilter(project: Project, dataManager: VcsLogData, paths: Collection<FilePath>): VcsLogFilter? {
val forRootFilter = mutableSetOf<VirtualFile>()
val forPathsFilter = mutableListOf<FilePath>()
for (path in paths) {
val root = VcsLogUtil.getActualRoot(project, path)
if (root == null) return null
if (!dataManager.roots.contains(root) ||
!VcsLogProperties.SUPPORTS_LOG_DIRECTORY_HISTORY.getOrDefault(dataManager.getLogProvider(root))) return null
val correctedPath = getCorrectedPath(project, path, root, false)
if (!correctedPath.isDirectory) return null
if (path.virtualFile == root) {
forRootFilter.add(root)
}
else {
forPathsFilter.add(correctedPath)
}
if (forPathsFilter.isNotEmpty() && forRootFilter.isNotEmpty()) return null
}
if (forPathsFilter.isNotEmpty()) return VcsLogFilterObject.fromPaths(forPathsFilter)
return VcsLogFilterObject.fromRoots(forRootFilter)
}
private fun createHashFilter(hash: Hash?, root: VirtualFile): VcsLogFilter {
if (hash == null) {
return VcsLogFilterObject.fromBranch(VcsLogUtil.HEAD)
}
return VcsLogFilterObject.fromCommit(CommitId(hash, root))
}
private fun matches(filters: VcsLogFilterCollection, pathsFilter: VcsLogFilter, hashFilter: VcsLogFilter): Boolean {
if (!filters.matches(hashFilter.key, pathsFilter.key)) {
return false
}
return filters.get(pathsFilter.key) == pathsFilter && filters.get(hashFilter.key) == hashFilter
}
}
}
private class VcsLogSingleFileHistoryProvider(private val project: Project) : VcsLogFileHistoryProvider {
private val tabGroupId: TabGroupId = TabGroupId("History", VcsBundle.messagePointer("file.history.tab.name"), false)
override fun canShowFileHistory(paths: Collection<FilePath>, revisionNumber: String?): Boolean {
if (!isNewHistoryEnabled() || paths.size != 1) return false
val root = VcsLogUtil.getActualRoot(project, paths.single()) ?: return false
val correctedPath = getCorrectedPath(project, paths.single(), root, revisionNumber != null)
if (correctedPath.isDirectory) return false
val dataManager = VcsProjectLog.getInstance(project).dataManager ?: return false
if (dataManager.logProviders[root]?.diffHandler == null) return false
return dataManager.index.isIndexingEnabled(root) || Registry.`is`("vcs.force.new.history")
}
override fun showFileHistory(paths: Collection<FilePath>, revisionNumber: String?) {
if (paths.size != 1) return
val root = VcsLogUtil.getActualRoot(project, paths.first())!!
val path = getCorrectedPath(project, paths.single(), root, revisionNumber != null)
if (path.isDirectory) return
val hash = revisionNumber?.let { HashImpl.build(it) }
triggerFileHistoryUsage(project, paths, hash)
val logManager = VcsProjectLog.getInstance(project).logManager!!
var fileHistoryUi = logManager.findLogUi(VcsLogTabLocation.TOOL_WINDOW, FileHistoryUi::class.java, true) { ui -> ui.matches(path, hash) }
val firstTime = fileHistoryUi == null
if (firstTime) {
val suffix = if (hash != null) " (" + hash.toShortString() + ")" else ""
fileHistoryUi = VcsLogContentUtil.openLogTab(project, logManager, tabGroupId, Function { path.name + suffix },
FileHistoryUiFactory(path, root, hash), true)
}
selectRowWhenOpen(logManager, hash, root, fileHistoryUi!!, firstTime)
}
}
fun isNewHistoryEnabled() = Registry.`is`("vcs.new.history")
private fun selectRowWhenOpen(logManager: VcsLogManager, hash: Hash?, root: VirtualFile, ui: VcsLogUiEx, firstTime: Boolean) {
if (hash != null) {
ui.jumpToNearestCommit(logManager.dataManager.storage, hash, root, true)
}
else if (firstTime) {
jumpToRow(ui, 0, true)
}
}
private fun VcsLogUiEx.jumpToNearestCommit(storage: VcsLogStorage, hash: Hash, root: VirtualFile, silently: Boolean) {
jumpTo(hash, { visiblePack: VisiblePack, h: Hash? ->
if (!storage.containsCommit(CommitId(h!!, root))) return@jumpTo VcsLogUiEx.COMMIT_NOT_FOUND
val commitIndex: Int = storage.getCommitIndex(h, root)
var rowIndex = visiblePack.visibleGraph.getVisibleRowIndex(commitIndex)
if (rowIndex == null) {
rowIndex = findVisibleAncestorRow(commitIndex, visiblePack)
}
rowIndex ?: VcsLogUiEx.COMMIT_DOES_NOT_MATCH
}, SettableFuture.create(), silently, true)
}
private fun getCorrectedPath(project: Project, path: FilePath, root: VirtualFile,
isRevisionHistory: Boolean): FilePath {
var correctedPath = path
if (root != VcsUtil.getVcsRootFor(project, correctedPath) && correctedPath.isDirectory) {
correctedPath = VcsUtil.getFilePath(correctedPath.path, false)
}
if (!isRevisionHistory) {
return VcsUtil.getLastCommitPath(project, correctedPath)
}
return correctedPath
}
private fun triggerFileHistoryUsage(project: Project, paths: Collection<FilePath>, hash: Hash?) {
val kind = if (paths.size > 1) "multiple" else if (paths.first().isDirectory) "folder" else "file"
VcsLogUsageTriggerCollector.triggerFileHistoryUsage(project, kind, hash != null)
} | apache-2.0 | e9a92e176eeb89669f22652d266e3106 | 43.581152 | 158 | 0.743951 | 4.64738 | false | false | false | false |
ThiagoGarciaAlves/intellij-community | plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/resolve/imports/StarImport.kt | 3 | 1412 | // Copyright 2000-2017 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.plugins.groovy.lang.resolve.imports
import com.intellij.psi.JavaPsiFacade
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiPackage
import com.intellij.psi.ResolveState
import com.intellij.psi.scope.PsiScopeProcessor
import org.jetbrains.plugins.groovy.lang.psi.GroovyFileBase
import org.jetbrains.plugins.groovy.lang.resolve.isNonAnnotationResolve
import org.jetbrains.plugins.groovy.lang.resolve.shouldProcessClasses
data class StarImport(val packageFqn: String) : GroovyStarImport {
override val fqn: String get() = packageFqn
override fun resolveImport(file: GroovyFileBase): PsiPackage? {
val facade = JavaPsiFacade.getInstance(file.project)
return facade.findPackage(packageFqn)
}
override fun processDeclarations(processor: PsiScopeProcessor, state: ResolveState, place: PsiElement, file: GroovyFileBase): Boolean {
if (processor.isNonAnnotationResolve()) return true
if (!processor.shouldProcessClasses()) return true
val pckg = resolveImport(file) ?: return true
return pckg.processDeclarations(processor, state, null, place)
}
override fun isUnnecessary(imports: GroovyFileImports): Boolean = this in defaultStarImportsSet
override fun toString(): String = "import $packageFqn.*"
}
| apache-2.0 | 8cf2d69e0dc1f417c66694216ddf8b94 | 43.125 | 140 | 0.796742 | 4.440252 | false | false | false | false |
TimePath/data-examiner | src/main/kotlin/com/timepath/util/Properties.kt | 1 | 1754 | package com.timepath.util
import java.beans.PropertyChangeSupport
import java.beans.PropertyVetoException
import java.beans.VetoableChangeSupport
import kotlin.properties.ReadWriteProperty
import kotlin.reflect.KMutableProperty
public class BeanProperty<T>(initialValue: T,
val pcs: PropertyChangeSupport,
val vcs: VetoableChangeSupport) : ReadWriteProperty<Any?, T> {
private var value = initialValue
public override fun get(thisRef: Any?, desc: PropertyMetadata) = value
public override fun set(thisRef: Any?, desc: PropertyMetadata, value: T) {
val old = this.value
if (old == value) return
vcs.fireVetoableChange(desc.name, old, value)
this.value = value
pcs.firePropertyChange(desc.name, old, value)
}
}
public inline fun <R> KMutableProperty<R>.observe(pcs: PropertyChangeSupport,
@inlineOptions(InlineOption.ONLY_LOCAL_RETURN)
function: (old: R, new: R) -> Unit) {
pcs.addPropertyChangeListener(this.name) {
@suppress("UNCHECKED_CAST")
function(it.getOldValue() as R, it.getNewValue() as R)
}
}
public inline fun <R> KMutableProperty<R>.observe(vcs: VetoableChangeSupport,
@inlineOptions(InlineOption.ONLY_LOCAL_RETURN)
function: (old: R, new: R) -> String?) {
vcs.addVetoableChangeListener(this.name) {
@suppress("UNCHECKED_CAST")
function(it.getOldValue() as R, it.getNewValue() as R)?.let { e ->
throw PropertyVetoException("${this.name}: ${e}", it)
}
}
}
| artistic-2.0 | 35253678fc556776f6f10b996621c684 | 39.790698 | 96 | 0.603193 | 4.544041 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.