repo_name
stringlengths 7
81
| path
stringlengths 6
242
| copies
stringclasses 55
values | size
stringlengths 2
6
| content
stringlengths 55
737k
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 5.44
99.8
| line_max
int64 15
979
| alpha_frac
float64 0.3
0.91
| ratio
float64 2
9.93
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
smmribeiro/intellij-community | plugins/kotlin/idea/tests/testData/refactoring/extractFunction/controlFlow/outputValues/tooManyOutputValues.kt | 9 | 506 | // WITH_STDLIB
// PARAM_TYPES: kotlin.Int
// PARAM_TYPES: kotlin.Int
// PARAM_TYPES: kotlin.Int
// PARAM_DESCRIPTOR: value-parameter a: kotlin.Int defined in foo
// PARAM_DESCRIPTOR: var b: kotlin.Int defined in foo
// PARAM_DESCRIPTOR: var c: kotlin.Int defined in foo
// SIBLING:
fun foo(a: Int): Int {
var b: Int = 1
var c: Int = 1
var d: Int = 1
var e: Int = 1
<selection>b += a
c -= a
d += c
e -= d
println(b)
println(c)</selection>
return b + c + d + e
} | apache-2.0 | 19169b2017b7bb0856d425125aa0590a | 21.043478 | 65 | 0.596838 | 3.123457 | false | false | false | false |
smmribeiro/intellij-community | plugins/completion-ml-ranking/src/com/intellij/completion/ml/features/MLCompletionWeigher.kt | 6 | 1925 | // 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.completion.ml.features
import com.intellij.codeInsight.completion.CompletionLocation
import com.intellij.codeInsight.completion.CompletionWeigher
import com.intellij.codeInsight.completion.ml.ElementFeatureProvider
import com.intellij.codeInsight.completion.ml.MLFeatureValue
import com.intellij.codeInsight.lookup.LookupElement
import com.intellij.completion.ml.storage.LookupStorage
class MLCompletionWeigher : CompletionWeigher() {
override fun weigh(element: LookupElement, location: CompletionLocation): Comparable<*> {
val storage: LookupStorage = LookupStorage.get(location.completionParameters) ?: return DummyComparable.EMPTY
if (!storage.shouldComputeFeatures()) return DummyComparable.EMPTY
val result = mutableMapOf<String, MLFeatureValue>()
val contextFeatures = storage.contextProvidersResult()
for (provider in ElementFeatureProvider.forLanguage(storage.language)) {
val name = provider.name
val features = storage.performanceTracker.trackElementFeaturesCalculation(name) {
provider.calculateFeatures(element, location, contextFeatures)
}
for ((featureName, featureValue) in features) {
result["${name}_$featureName"] = featureValue
}
}
return if (result.isEmpty()) DummyComparable.EMPTY else DummyComparable(result)
}
internal class DummyComparable(values: Map<String, MLFeatureValue>) : Comparable<Any> {
val mlFeatures = values.mapValues { MLFeaturesUtil.getRawValue(it.value) }
override fun compareTo(other: Any): Int = 0
override fun toString(): String {
return mlFeatures.entries.joinToString(",", "[", "]", transform = { "${it.key}=${it.value}" })
}
companion object {
val EMPTY = DummyComparable(emptyMap())
}
}
} | apache-2.0 | 084cf7c60bfdb540f718329ca572bc3b | 41.8 | 140 | 0.752727 | 4.741379 | false | false | false | false |
smmribeiro/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/RedundantSamConstructorInspection.kt | 1 | 13732 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.inspections
import com.intellij.codeInsight.FileModificationService
import com.intellij.codeInspection.*
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiElementVisitor
import org.jetbrains.kotlin.codegen.SamCodegenUtil
import org.jetbrains.kotlin.config.LanguageFeature
import org.jetbrains.kotlin.idea.FrontendInternals
import org.jetbrains.kotlin.idea.KotlinBundle
import org.jetbrains.kotlin.idea.caches.resolve.analyze
import org.jetbrains.kotlin.idea.caches.resolve.getResolutionFacade
import org.jetbrains.kotlin.idea.project.languageVersionSettings
import org.jetbrains.kotlin.idea.resolve.frontendService
import org.jetbrains.kotlin.idea.util.getResolutionScope
import org.jetbrains.kotlin.idea.util.safeAnalyzeNonSourceRootCode
import org.jetbrains.kotlin.name.Name
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.anyDescendantOfType
import org.jetbrains.kotlin.psi.psiUtil.getElementTextWithContext
import org.jetbrains.kotlin.psi.psiUtil.getQualifiedExpressionForSelector
import org.jetbrains.kotlin.psi.psiUtil.getQualifiedExpressionForSelectorOrThis
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.BindingTraceContext
import org.jetbrains.kotlin.resolve.bindingContextUtil.getDataFlowInfoBefore
import org.jetbrains.kotlin.resolve.calls.CallResolver
import org.jetbrains.kotlin.resolve.calls.callUtil.getParameterForArgument
import org.jetbrains.kotlin.resolve.calls.callUtil.getResolvedCall
import org.jetbrains.kotlin.resolve.calls.model.isReallySuccess
import org.jetbrains.kotlin.resolve.calls.tower.NewResolvedCallImpl
import org.jetbrains.kotlin.resolve.calls.util.DelegatingCall
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
import org.jetbrains.kotlin.resolve.sam.SamConstructorDescriptor
import org.jetbrains.kotlin.resolve.sam.SamConversionOracle
import org.jetbrains.kotlin.resolve.sam.SamConversionResolver
import org.jetbrains.kotlin.resolve.sam.getFunctionTypeForPossibleSamType
import org.jetbrains.kotlin.types.TypeUtils
import org.jetbrains.kotlin.types.isNullable
import org.jetbrains.kotlin.types.typeUtil.makeNotNullable
import org.jetbrains.kotlin.utils.keysToMapExceptNulls
class RedundantSamConstructorInspection : AbstractKotlinInspection() {
override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean, session: LocalInspectionToolSession): PsiElementVisitor {
return callExpressionVisitor(fun(expression) {
if (expression.valueArguments.isEmpty()) return
val samConstructorCalls = samConstructorCallsToBeConverted(expression)
if (samConstructorCalls.isEmpty()) return
val single = samConstructorCalls.singleOrNull()
if (single != null) {
val calleeExpression = single.calleeExpression ?: return
val problemDescriptor = holder.manager.createProblemDescriptor(
single.getQualifiedExpressionForSelector()?.receiverExpression ?: calleeExpression,
single.typeArgumentList ?: calleeExpression,
KotlinBundle.message("redundant.sam.constructor"),
ProblemHighlightType.LIKE_UNUSED_SYMBOL,
isOnTheFly,
createQuickFix(single)
)
holder.registerProblem(problemDescriptor)
} else {
val problemDescriptor = holder.manager.createProblemDescriptor(
expression.valueArgumentList!!,
KotlinBundle.message("redundant.sam.constructors"),
createQuickFix(samConstructorCalls),
ProblemHighlightType.GENERIC_ERROR_OR_WARNING,
isOnTheFly
)
holder.registerProblem(problemDescriptor)
}
})
}
private fun createQuickFix(expression: KtCallExpression): LocalQuickFix {
return object : LocalQuickFix {
override fun getName() = KotlinBundle.message("remove.redundant.sam.constructor")
override fun getFamilyName() = name
override fun applyFix(project: Project, descriptor: ProblemDescriptor) {
if (!FileModificationService.getInstance().preparePsiElementForWrite(expression)) return
replaceSamConstructorCall(expression)
}
}
}
private fun createQuickFix(expressions: Collection<KtCallExpression>): LocalQuickFix {
return object : LocalQuickFix {
override fun getName() = KotlinBundle.message("remove.redundant.sam.constructors")
override fun getFamilyName() = name
override fun applyFix(project: Project, descriptor: ProblemDescriptor) {
for (callExpression in expressions) {
if (!FileModificationService.getInstance().preparePsiElementForWrite(callExpression)) return
replaceSamConstructorCall(callExpression)
}
}
}
}
companion object {
fun replaceSamConstructorCall(callExpression: KtCallExpression): KtLambdaExpression {
val functionalArgument = callExpression.samConstructorValueArgument()?.getArgumentExpression()
?: throw AssertionError("SAM-constructor should have a FunctionLiteralExpression as single argument: ${callExpression.getElementTextWithContext()}")
return callExpression.getQualifiedExpressionForSelectorOrThis().replace(functionalArgument) as KtLambdaExpression
}
private fun canBeReplaced(
parentCall: KtCallExpression,
samConstructorCallArgumentMap: Map<KtValueArgument, KtCallExpression>
): Boolean {
val context = parentCall.analyze(BodyResolveMode.PARTIAL)
val calleeExpression = parentCall.calleeExpression ?: return false
val scope = calleeExpression.getResolutionScope(context, calleeExpression.getResolutionFacade())
val originalCall = parentCall.getResolvedCall(context) ?: return false
val dataFlow = context.getDataFlowInfoBefore(parentCall)
@OptIn(FrontendInternals::class)
val callResolver = parentCall.getResolutionFacade().frontendService<CallResolver>()
val newCall = CallWithConvertedArguments(originalCall.call, samConstructorCallArgumentMap)
val qualifiedExpression = parentCall.getQualifiedExpressionForSelectorOrThis()
val expectedType = context[BindingContext.EXPECTED_EXPRESSION_TYPE, qualifiedExpression] ?: TypeUtils.NO_EXPECTED_TYPE
val resolutionResults =
callResolver.resolveFunctionCall(BindingTraceContext(), scope, newCall, expectedType, dataFlow, false, null)
if (!resolutionResults.isSuccess) return false
val generatingAdditionalSamCandidateIsDisabled =
parentCall.languageVersionSettings.supportsFeature(LanguageFeature.SamConversionPerArgument) ||
parentCall.languageVersionSettings.supportsFeature(LanguageFeature.ProhibitVarargAsArrayAfterSamArgument)
val samAdapterOriginalDescriptor =
if (generatingAdditionalSamCandidateIsDisabled && resolutionResults.resultingCall is NewResolvedCallImpl<*>) {
resolutionResults.resultingDescriptor
} else {
SamCodegenUtil.getOriginalIfSamAdapter(resolutionResults.resultingDescriptor) ?: return false
}
return samAdapterOriginalDescriptor.original == originalCall.resultingDescriptor.original
}
private class CallWithConvertedArguments(
original: Call,
callArgumentMapToConvert: Map<KtValueArgument, KtCallExpression>,
) : DelegatingCall(original) {
private val newArguments: List<ValueArgument>
init {
val factory = KtPsiFactory(callElement)
newArguments = original.valueArguments.map { argument ->
val call = callArgumentMapToConvert[argument]
val newExpression = call?.samConstructorValueArgument()?.getArgumentExpression() ?: return@map argument
factory.createArgument(newExpression, argument.getArgumentName()?.asName, reformat = false)
}
}
override fun getValueArguments() = newArguments
}
@OptIn(FrontendInternals::class)
fun samConstructorCallsToBeConverted(functionCall: KtCallExpression): Collection<KtCallExpression> {
val valueArguments = functionCall.valueArguments
if (valueArguments.none { canBeSamConstructorCall(it) }) return emptyList()
val resolutionFacade = functionCall.getResolutionFacade()
val oracle = resolutionFacade.frontendService<SamConversionOracle>()
val resolver = resolutionFacade.frontendService<SamConversionResolver>()
val bindingContext = functionCall.safeAnalyzeNonSourceRootCode(resolutionFacade, BodyResolveMode.PARTIAL)
val functionResolvedCall = functionCall.getResolvedCall(bindingContext) ?: return emptyList()
if (!functionResolvedCall.isReallySuccess()) return emptyList()
/**
* Checks that SAM conversion for [arg] and [call] in the argument position is possible
* and does not loose any information.
*
* We want to do as many cheap checks as possible before actually trying to resolve substituted call in [canBeReplaced].
*
* Several cases where we do not want the conversion:
*
* - Expected argument type is inferred from the argument; for example when the expected type is `T`, and SAM constructor
* helps to deduce it.
* - Expected argument type is a base type for the actual argument type; for example when expected type is `Any`, and removing
* SAM constructor will lead to passing object of different type.
*/
fun samConversionIsPossible(arg: KtValueArgument, call: KtCallExpression): Boolean {
val samConstructor =
call.getResolvedCall(bindingContext)?.resultingDescriptor?.original as? SamConstructorDescriptor ?: return false
// we suppose that SAM constructors return type is always not nullable
val samConstructorReturnType = samConstructor.returnType?.unwrap()?.takeUnless { it.isNullable() } ?: return false
// we take original parameter descriptor to get type parameter instead of inferred type (e.g. `T` instead of `Runnable`)
val originalParameterDescriptor = functionResolvedCall.getParameterForArgument(arg)?.original ?: return false
val expectedNotNullableType = originalParameterDescriptor.type.makeNotNullable().unwrap()
if (resolver.getFunctionTypeForPossibleSamType(expectedNotNullableType, oracle) == null) return false
return samConstructorReturnType.constructor == expectedNotNullableType.constructor
}
val argumentsWithSamConstructors = valueArguments.keysToMapExceptNulls { arg ->
arg.toCallExpression()?.takeIf { call -> samConversionIsPossible(arg, call) }
}
val haveToConvertAllArguments = !functionCall.languageVersionSettings.supportsFeature(LanguageFeature.SamConversionPerArgument)
val argumentsThatCanBeConverted = if (haveToConvertAllArguments) {
argumentsWithSamConstructors.takeIf { it.values.none(::containsLabeledReturnPreventingConversion) }.orEmpty()
} else {
argumentsWithSamConstructors.filterValues { !containsLabeledReturnPreventingConversion(it) }
}
return when {
argumentsThatCanBeConverted.isEmpty() -> emptyList()
!canBeReplaced(functionCall, argumentsThatCanBeConverted) -> emptyList()
else -> argumentsThatCanBeConverted.values
}
}
private fun canBeSamConstructorCall(argument: KtValueArgument) = argument.toCallExpression()?.samConstructorValueArgument() != null
private fun KtCallExpression.samConstructorValueArgument(): KtValueArgument? {
return valueArguments.singleOrNull()?.takeIf { it.getArgumentExpression() is KtLambdaExpression }
}
private fun ValueArgument.toCallExpression(): KtCallExpression? {
val argumentExpression = getArgumentExpression()
return (if (argumentExpression is KtDotQualifiedExpression)
argumentExpression.selectorExpression
else
argumentExpression) as? KtCallExpression
}
private fun containsLabeledReturnPreventingConversion(it: KtCallExpression): Boolean {
val samValueArgument = it.samConstructorValueArgument()
val samConstructorName = (it.calleeExpression as? KtSimpleNameExpression)?.getReferencedNameAsName()
return samValueArgument == null ||
samConstructorName == null ||
samValueArgument.hasLabeledReturnPreventingConversion(samConstructorName)
}
private fun KtValueArgument.hasLabeledReturnPreventingConversion(samConstructorName: Name) =
anyDescendantOfType<KtReturnExpression> { it.getLabelNameAsName() == samConstructorName }
}
}
| apache-2.0 | ce5d5db868b05ddd1828376de5760d90 | 53.492063 | 164 | 0.707472 | 6.127622 | false | false | false | false |
mapzen/eraser-map | app/src/main/kotlin/com/mapzen/erasermap/view/InstructionGroup.kt | 1 | 3841 | package com.mapzen.erasermap.view
import android.content.Context
import android.graphics.Color
import android.graphics.Typeface
import android.text.SpannableString
import android.text.style.StyleSpan
import com.mapzen.erasermap.R
import com.mapzen.valhalla.Instruction
import com.mapzen.valhalla.TransitInfo
import com.mapzen.valhalla.TransitStop
import com.mapzen.valhalla.TravelMode
import com.mapzen.valhalla.TravelType
import java.util.ArrayList
import java.util.regex.Pattern
class InstructionGroup(val travelType: TravelType, val travelMode: TravelMode,
val instructions: ArrayList<Instruction>) {
val totalDistance: Int by lazy { calculateTotalDistance() }
val totalTime: Int by lazy { calculateTotalTime() }
private var firstStationName: String? = null
private var numberOfStops: String? = null
private var transitInstruction: SpannableString? = null
val transitColor: Int by lazy { calculateTransitColor() }
private fun calculateTotalDistance(): Int {
var total = 0
for(instruction in instructions) {
total+= instruction.distance
}
return total
}
private fun calculateTotalTime(): Int {
var total = 0
for(instruction in instructions) {
total+= instruction.getTime()
}
return total
}
fun firstStationName(context: Context, instruction: Instruction): String? {
if (firstStationName == null) {
val transitStop = instruction.getTransitInfo()?.getTransitStops()?.get(0)
if (transitStop != null) {
val builder = StringBuilder()
builder.append(transitStop?.getName())
builder.append(" ")
builder.append(context.getString(R.string.station))
firstStationName = builder.toString()
}
}
return firstStationName
}
fun numberOfStops(context: Context, instruction: Instruction): String? {
if (numberOfStops == null) {
val stops = instruction.getTransitInfo()?.getTransitStops()
if (stops != null) {
val numStops = stops?.size - 1
val builder = StringBuilder()
builder.append(numStops)
builder.append(" ")
builder.append(context.getString(R.string.stops))
builder.append(context.getString(R.string.comma))
numberOfStops = builder.toString()
}
}
return numberOfStops
}
fun transitInstructionSpannable(context: Context, instruction: Instruction): SpannableString? {
if (transitInstruction == null) {
var turnInstruction = instruction.getHumanTurnInstruction()
val pattern = Pattern.compile("\\([0-9]+ stops\\)")
val matcher = pattern.matcher(turnInstruction)
turnInstruction = matcher.replaceAll("")
val transitStops = instruction.getTransitInfo()?.getTransitStops() as ArrayList<TransitStop>
val departureTime = transitStops[0].getDepartureDateTime().substring(11, 16)
turnInstruction += " "
turnInstruction += context.getString(R.string.transit_time, departureTime)
val spannableString = SpannableString(turnInstruction)
val transitInfo = instruction.getTransitInfo() as TransitInfo
val shortnameLoc = spannableString.indexOf(transitInfo.getShortName(), 0, true)
val headsignLoc = spannableString.indexOf(transitInfo.getHeadsign(), 0 , true)
spannableString.setSpan(StyleSpan(Typeface.BOLD), shortnameLoc,
shortnameLoc + transitInfo.getShortName().length, 0)
spannableString.setSpan(StyleSpan(Typeface.BOLD), headsignLoc,
headsignLoc + transitInfo.getHeadsign().length, 0)
transitInstruction = spannableString
}
return transitInstruction
}
fun calculateTransitColor(): Int {
val instruction = instructions[0]
try {
return Color.parseColor(instruction.getTransitInfoColorHex())
} catch(e : IllegalArgumentException) {
return R.color.mz_white
}
}
}
| gpl-3.0 | 7951fc4036f08639d16c44cae249e9af | 35.235849 | 98 | 0.715699 | 4.48715 | false | false | false | false |
dreampany/framework | frame/src/main/kotlin/com/dreampany/vision/ui/fragment/LiveTextOcrFragment.kt | 1 | 6347 | package com.dreampany.vision.ui.fragment
import android.os.Bundle
import android.view.Menu
import android.view.MenuInflater
import android.view.MenuItem
import android.widget.TextView
import androidx.appcompat.widget.AppCompatCheckBox
import androidx.appcompat.widget.AppCompatTextView
import com.afollestad.assent.Permission
import com.afollestad.assent.runWithPermissions
import com.dreampany.framework.R
import com.dreampany.framework.data.model.Task
import com.dreampany.framework.databinding.FragmentLiveTextOcrBinding
import com.dreampany.framework.misc.ActivityScope
import com.dreampany.framework.ui.fragment.BaseMenuFragment
import com.dreampany.framework.util.*
import com.dreampany.vision.ml.CameraSource
import com.dreampany.vision.ml.CameraSourcePreview
import com.dreampany.vision.ml.GraphicOverlay
import com.dreampany.vision.ml.ocr.TextRecognitionProcessor
import com.google.android.gms.common.annotation.KeepName
import com.klinker.android.link_builder.Link
import timber.log.Timber
import java.io.IOException
import javax.inject.Inject
/**
* Created by Roman-372 on 7/18/2019
* Copyright (c) 2019 bjit. All rights reserved.
* [email protected]
* Last modified $file.lastModified
*/
@KeepName
@ActivityScope
class LiveTextOcrFragment @Inject constructor() : BaseMenuFragment() {
private lateinit var bind: FragmentLiveTextOcrBinding
private var source: CameraSource? = null
private lateinit var preview: CameraSourcePreview
private lateinit var overlay: GraphicOverlay
private lateinit var viewText: AppCompatTextView
private lateinit var viewCheck: AppCompatCheckBox
private val texts = StringBuilder()
private val words = mutableListOf<String>()
override fun getLayoutId(): Int {
return R.layout.fragment_live_text_ocr
}
override fun getMenuId(): Int {
return R.menu.menu_live_text_ocr
}
override fun onMenuCreated(menu: Menu, inflater: MenuInflater) {
val checkItem = menu.findItem(R.id.item_auto_collection)
val clearItem = menu.findItem(R.id.item_clear)
val doneItem = menu.findItem(R.id.item_done)
MenuTint.colorMenuItem(
ColorUtil.getColor(context!!, R.color.material_white), null,
clearItem, doneItem
)
viewCheck = checkItem.actionView as AppCompatCheckBox
viewCheck.setOnCheckedChangeListener { buttonView, isChecked ->
val text =
if (isChecked) "All text collection is enabled" else "All text collection is disabled"
context?.run {
NotifyUtil.shortToast(this, text)
}
}
}
override fun onStartUi(state: Bundle?) {
initView()
runWithPermissions(Permission.CAMERA, Permission.WRITE_EXTERNAL_STORAGE) {
createCameraSource()
}
}
override fun onStopUi() {
source?.release()
}
override fun onResume() {
super.onResume()
startCameraSource()
}
override fun onPause() {
preview.stop()
super.onPause()
}
override fun hasBackPressed(): Boolean {
done()
return false
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
if (item.itemId == R.id.item_clear) {
clear()
return true
}
if (item.itemId == R.id.item_done) {
done()
return true
}
return super.onOptionsItemSelected(item)
}
private fun initView() {
setTitle(TextUtil.getString(context, R.string.detected_words, 0))
bind = super.binding as FragmentLiveTextOcrBinding
preview = bind.preview
overlay = bind.overlay
viewText = bind.viewText
}
private fun createCameraSource() {
if (source == null) {
source = CameraSource(getParent(), overlay)
}
source?.setMachineLearningFrameProcessor(TextRecognitionProcessor(TextRecognitionProcessor.Callback {
this.updateTitle(
it
)
}))
}
private fun startCameraSource() {
if (source != null) {
try {
if (preview == null) {
Timber.d("resume: Preview is null")
}
if (overlay == null) {
Timber.d("resume: graphOverlay is null")
}
preview.start(source, overlay)
} catch (e: IOException) {
Timber.e(e, "Unable to start camera source.")
source?.release()
source = null
}
}
}
private fun updateTitle(text: String) {
if (!viewCheck.isChecked) {
this.words.clear()
}
val words = TextUtil.getWords(text)
for (word in words) {
if (!this.words.contains(word)) {
this.words.add(word)
viewText.append(word + DataUtil.SPACE)
}
}
// val result = DataUtil.joinString(this.words, DataUtil.SPACE)
setSpan(viewText, this.words)
setTitle(TextUtil.getString(context, R.string.detected_words, this.words.size))
}
private fun setSpan(view: TextView, words: List<String>) {
if (words.isNullOrEmpty()) {
return
}
TextUtil.setSpan(
view,
words,
R.color.material_white,
R.color.material_white,
object : Link.OnClickListener {
override fun onClick(clickedText: String) {
onClickOnText(clickedText)
}
},
object : Link.OnLongClickListener {
override fun onLongClick(clickedText: String) {
onLongClickOnText(clickedText)
}
}
)
}
private fun onClickOnText(text: String) {
Timber.v("Clicked Word %s", text)
}
private fun onLongClickOnText(text: String) {
Timber.v("Clicked Word %s", text)
}
private fun clear() {
setTitle(TextUtil.getString(context, R.string.detected_words, 0))
// textView.text = null
texts.setLength(0)
}
private fun done() {
getCurrentTask<Task<*>>(false)!!.extra = texts.toString()
forResult()
}
} | apache-2.0 | b258b17a7c022258654ff2e766a837ce | 29.373206 | 109 | 0.619505 | 4.595945 | false | false | false | false |
mikepenz/MaterialDrawer | materialdrawer/src/main/java/com/mikepenz/materialdrawer/widget/MiniDrawerSliderView.kt | 1 | 13810 | package com.mikepenz.materialdrawer.widget
import android.content.Context
import android.util.AttributeSet
import android.view.View
import android.view.ViewGroup
import android.widget.LinearLayout
import androidx.core.view.ViewCompat
import androidx.drawerlayout.widget.DrawerLayout
import androidx.recyclerview.widget.DefaultItemAnimator
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.mikepenz.fastadapter.FastAdapter
import com.mikepenz.fastadapter.IAdapter
import com.mikepenz.fastadapter.adapters.ItemAdapter
import com.mikepenz.fastadapter.select.SelectExtension
import com.mikepenz.materialdrawer.R
import com.mikepenz.materialdrawer.interfaces.ICrossfader
import com.mikepenz.materialdrawer.model.*
import com.mikepenz.materialdrawer.model.interfaces.IDrawerItem
import com.mikepenz.materialdrawer.model.interfaces.withEnabled
import com.mikepenz.materialdrawer.model.utils.hiddenInMiniDrawer
import com.mikepenz.materialdrawer.util.getDrawerItem
/**
* This view is a simple drop in view for the [DrawerLayout] or as companion to a [MaterialDrawerSliderView] offering a convenient API to provide a nice and flexible mini slider view following
* the material design guidelines v2.
*/
open class MiniDrawerSliderView @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = R.attr.materialDrawerStyle) : LinearLayout(context, attrs, defStyleAttr) {
/**
* get the RecyclerView of this MiniDrawer
*
* @return
*/
val recyclerView: RecyclerView
/**
* get the FastAdapter of this MiniDrawer
*
* @return
*/
val adapter: FastAdapter<IDrawerItem<*>>
/**
* get the ItemAdapter of this MiniDrawer
*
* @return
*/
val itemAdapter: ItemAdapter<IDrawerItem<*>>
val selectExtension: SelectExtension<IDrawerItem<*>>
/**
* get the Drawer used to fill this MiniDrawer
*
* @return
*/
var drawer: MaterialDrawerSliderView? = null
set(value) {
field = value
if (field?.miniDrawer != this) {
field?.miniDrawer = this
}
createItems()
}
/**
* get the AccountHeader used to fill the this MiniDrawer
*
* @return
*/
val accountHeader: AccountHeaderView?
get() = drawer?.accountHeader
/**
* get the Crossfader used for this MiniDrawer
*
* @return
*/
var crossFader: ICrossfader? = null
var innerShadow = false
set(value) {
field = value
updateInnerShadow()
}
var inRTL = false
set(value) {
field = value
updateInnerShadow()
}
var includeSecondaryDrawerItems = false
set(value) {
field = value
createItems()
}
var enableSelectedMiniDrawerItemBackground = false
set(value) {
field = value
createItems()
}
var enableProfileClick = true
set(value) {
field = value
createItems()
}
private var onMiniDrawerItemClickListener: ((view: View?, position: Int, drawerItem: IDrawerItem<*>, type: Int) -> Boolean)? = null
private var onMiniDrawerItemOnClickListener: ((v: View?, adapter: IAdapter<IDrawerItem<*>>, item: IDrawerItem<*>, position: Int) -> Boolean)? = null
set(value) {
field = value
if (value == null) {
createItems()
} else {
adapter.onClickListener = value
}
}
private var onMiniDrawerItemLongClickListener: ((v: View, adapter: IAdapter<IDrawerItem<*>>, item: IDrawerItem<*>, position: Int) -> Boolean)? = null
set(value) {
field = value
adapter.onLongClickListener = value
}
/**
* returns always the original drawerItems and not the switched content
*
* @return
*/
private val drawerItems: List<IDrawerItem<*>>
get() = drawer?.itemAdapter?.adapterItems ?: ArrayList()
init {
val a = context.obtainStyledAttributes(attrs, R.styleable.MaterialDrawerSliderView, defStyleAttr, R.style.Widget_MaterialDrawerStyle)
background = a.getDrawable(R.styleable.MaterialDrawerSliderView_materialDrawerBackground)
a.recycle()
updateInnerShadow()
//create and append recyclerView
recyclerView = RecyclerView(context)
addView(recyclerView, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)
//set the itemAnimator
recyclerView.itemAnimator = DefaultItemAnimator()
//some style improvements on older devices
recyclerView.setFadingEdgeLength(0)
//set the drawing cache background to the same color as the slider to improve performance
recyclerView.clipToPadding = false
//additional stuff
recyclerView.layoutManager = LinearLayoutManager(context)
//adapter
itemAdapter = ItemAdapter()
adapter = FastAdapter.with(itemAdapter)
selectExtension = adapter.getOrCreateExtension(SelectExtension::class.java)!! // definitely not null
selectExtension.isSelectable = true
selectExtension.allowDeselection = false
recyclerView.adapter = adapter
// set the insets
ViewCompat.setOnApplyWindowInsetsListener(this) { v, insets ->
recyclerView.setPadding(recyclerView.paddingLeft, insets.systemWindowInsetTop, recyclerView.paddingRight, insets.systemWindowInsetBottom)
insets
}
//set the adapter with the items
createItems()
}
private fun updateInnerShadow() {
if (innerShadow) {
if (!inRTL) {
setBackgroundResource(R.drawable.material_drawer_shadow_left)
} else {
setBackgroundResource(R.drawable.material_drawer_shadow_right)
}
} else {
background = null
}
}
/**
* call this method to trigger the onProfileClick on the MiniDrawer
*/
fun onProfileClick() {
//crossfade if we are cross faded
crossFader?.let {
if (it.isCrossfaded) {
it.crossfade()
}
}
//update the current profile
accountHeader?.let {
val profile = it.activeProfile
if (profile is IDrawerItem<*>) {
generateMiniDrawerItem(profile as IDrawerItem<*>)?.let { item ->
itemAdapter.set(0, item)
}
}
}
}
/**
* call this method to trigger the onItemClick on the MiniDrawer
*
* @param selectedDrawerItem
* @return
*/
fun onItemClick(selectedDrawerItem: IDrawerItem<*>): Boolean {
//We only need to clear if the new item is selectable
return if (selectedDrawerItem.isSelectable) {
// crossfade if we are cross faded
crossFader?.let {
if (drawer?.closeOnClick == true && it.isCrossfaded) {
it.crossfade()
}
}
// update everything
if (selectedDrawerItem.hiddenInMiniDrawer) {
selectExtension.deselect()
} else {
setSelection(selectedDrawerItem.identifier)
}
false
} else {
true
}
}
/**
* set the selection of the MiniDrawer
*
* @param identifier the identifier of the item which should be selected (-1 for none)
*/
fun setSelection(identifier: Long) {
if (identifier == -1L) {
selectExtension.deselect()
return
}
val count = adapter.itemCount
for (i in 0 until count) {
val item = adapter.getItem(i)
if (item?.identifier == identifier && !item.isSelected) {
selectExtension.deselect()
selectExtension.select(i)
}
}
}
/**
* update a MiniDrawerItem (after updating the main Drawer) via its identifier
*
* @param identifier the identifier of the item which was updated
*/
fun updateItem(identifier: Long) {
if (drawer != null && identifier != -1L) {
drawerItems.getDrawerItem(identifier)?.let { drawerItem ->
for (i in 0 until itemAdapter.adapterItems.size) {
if (itemAdapter.adapterItems[i].identifier == drawerItem.identifier) {
val miniDrawerItem = generateMiniDrawerItem(drawerItem)
if (miniDrawerItem != null) {
itemAdapter[i] = miniDrawerItem
}
}
}
}
}
}
/**
* creates the items for the MiniDrawer
*/
open fun createItems() {
itemAdapter.clear()
var profileOffset = 0
accountHeader?.let { accountHeader ->
val profile = accountHeader.activeProfile
if (profile is IDrawerItem<*>) {
generateMiniDrawerItem(profile as IDrawerItem<*>)?.let {
itemAdapter.add(it)
}
profileOffset = 1
}
}
var select = -1
if (drawer != null) {
//migrate to miniDrawerItems
val length = drawerItems.size
var position = 0
for (i in 0 until length) {
val miniDrawerItem = generateMiniDrawerItem(drawerItems[i])
if (miniDrawerItem != null) {
if (miniDrawerItem.isSelected) {
select = position
}
itemAdapter.add(miniDrawerItem)
position += 1
}
}
if (select >= 0) {
//+1 because of the profile
selectExtension.select(select + profileOffset)
}
}
//listener
if (this.onMiniDrawerItemOnClickListener != null) {
adapter.onClickListener = this.onMiniDrawerItemOnClickListener
} else {
adapter.onClickListener = { v: View?, _: IAdapter<IDrawerItem<*>>, item: IDrawerItem<*>, position: Int ->
val type = getMiniDrawerType(item)
//if a listener is defined and we consume the event return
if (onMiniDrawerItemClickListener?.invoke(v, position, item, type) == true) {
false
} else {
if (type == ITEM) {
//fire the onClickListener also if the specific drawerItem is not Selectable
if (item.isSelectable) {
//make sure we are on the original drawerItemList
accountHeader?.let {
if (it.selectionListShown) {
it.toggleSelectionList()
}
}
val drawerItem = drawer?.getDrawerItem(item.identifier)
if (drawerItem != null && !drawerItem.isSelected) {
//set the selection
drawer?.selectExtension?.deselect()
drawer?.setSelection(item.identifier, true)
}
} else if (drawer?.onDrawerItemClickListener != null) {
drawerItems.getDrawerItem(item.identifier)?.let {
//get the original `DrawerItem` from the Drawer as this one will contain all information
drawer?.onDrawerItemClickListener?.invoke(v, it, position)
}
}
} else if (type == PROFILE) {
accountHeader?.let {
if (!it.selectionListShown) {
it.toggleSelectionList()
}
}
crossFader?.crossfade()
}
false
}
}
}
adapter.onLongClickListener = onMiniDrawerItemLongClickListener
recyclerView.scrollToPosition(0)
}
/**
* generates a MiniDrawerItem from a IDrawerItem
*
* @param drawerItem
* @return
*/
open fun generateMiniDrawerItem(drawerItem: IDrawerItem<*>): IDrawerItem<*>? {
return when (drawerItem) {
is SecondaryDrawerItem -> if (includeSecondaryDrawerItems && !drawerItem.hiddenInMiniDrawer) MiniDrawerItem(drawerItem).withEnableSelectedBackground(enableSelectedMiniDrawerItemBackground).withSelectedBackgroundAnimated(false) else null
is PrimaryDrawerItem -> if (!drawerItem.hiddenInMiniDrawer) MiniDrawerItem(drawerItem).withEnableSelectedBackground(enableSelectedMiniDrawerItemBackground).withSelectedBackgroundAnimated(false) else null
is ProfileDrawerItem -> MiniProfileDrawerItem(drawerItem).apply { withEnabled(enableProfileClick) }
else -> null
}
}
/**
* gets the type of a IDrawerItem
*
* @param drawerItem
* @return
*/
open fun getMiniDrawerType(drawerItem: IDrawerItem<*>): Int {
if (drawerItem is MiniProfileDrawerItem) {
return PROFILE
} else if (drawerItem is MiniDrawerItem) {
return ITEM
}
return -1
}
companion object {
val PROFILE = 1
val ITEM = 2
}
}
| apache-2.0 | 4513756a43724ecc1424056211bcf1d8 | 33.698492 | 248 | 0.574728 | 5.396639 | false | false | false | false |
quran/quran_android | feature/downloadmanager/src/main/kotlin/com/quran/mobile/feature/downloadmanager/ui/sheikhdownload/SheikhSuraInfoList.kt | 2 | 1324 | package com.quran.mobile.feature.downloadmanager.ui.sheikhdownload
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import com.quran.mobile.feature.downloadmanager.model.sheikhdownload.SheikhUiModel
import com.quran.mobile.feature.downloadmanager.model.sheikhdownload.SuraForQari
import com.quran.page.common.data.QuranNaming
@Composable
fun SheikhSuraInfoList(
sheikhUiModel: SheikhUiModel,
currentSelection: List<SuraForQari>,
quranNaming: QuranNaming,
onSuraClicked: ((SuraForQari) -> Unit),
onSelectionStarted: ((SuraForQari) -> Unit)
) {
Column(modifier = Modifier.verticalScroll(rememberScrollState())) {
sheikhUiModel.suraUiModel.forEach { suraUiModel ->
val isSuraSelected = currentSelection.any { it.sura == suraUiModel.sura }
SheikhSuraRow(
sheikhSuraUiModel = suraUiModel,
isSelected = isSuraSelected,
quranNaming = quranNaming,
onSuraClicked = { clickedSura -> onSuraClicked(clickedSura) },
onSuraLongClicked = { clickedSura ->
if (currentSelection.isEmpty()) {
onSelectionStarted(clickedSura)
}
}
)
}
}
}
| gpl-3.0 | 20fdc33b6d4ae6d0ac1b6c0557d5e662 | 35.777778 | 82 | 0.75 | 4.28479 | false | false | false | false |
Zubnix/westmalle | compositor/src/main/kotlin/org/westford/nativ/libdrm/DrmEventContext.kt | 3 | 1263 | /*
* Westford Wayland Compositor.
* Copyright (C) 2016 Erik De Rijcke
*
* 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.westford.nativ.libdrm
import org.freedesktop.jaccall.CType
import org.freedesktop.jaccall.Field
import org.freedesktop.jaccall.Struct
@Struct(Field(name = "version",
type = CType.INT),
Field(name = "vblank_handler",
type = CType.POINTER,
dataType = vblank_handler::class),
Field(name = "page_flip_handler",
type = CType.POINTER,
dataType = page_flip_handler::class)) class DrmEventContext : Struct_DrmEventContext()
| apache-2.0 | 74fc547ccf9c80f10ab565f9669c37b9 | 39.741935 | 100 | 0.703088 | 4.22408 | false | false | false | false |
foresterre/mal | kotlin/src/mal/step7_quote.kt | 14 | 5341 | package mal
import java.util.*
fun read(input: String?): MalType = read_str(input)
fun eval(_ast: MalType, _env: Env): MalType {
var ast = _ast
var env = _env
while (true) {
if (ast is MalList) {
if (ast.count() == 0) return ast
when ((ast.first() as? MalSymbol)?.value) {
"def!" -> return env.set(ast.nth(1) as MalSymbol, eval(ast.nth(2), env))
"let*" -> {
val childEnv = Env(env)
val bindings = ast.nth(1) as? ISeq ?: throw MalException("expected sequence as the first parameter to let*")
val it = bindings.seq().iterator()
while (it.hasNext()) {
val key = it.next()
if (!it.hasNext()) throw MalException("odd number of binding elements in let*")
childEnv.set(key as MalSymbol, eval(it.next(), childEnv))
}
env = childEnv
ast = ast.nth(2)
}
"fn*" -> return fn_STAR(ast, env)
"do" -> {
eval_ast(ast.slice(1, ast.count() - 1), env)
ast = ast.seq().last()
}
"if" -> {
val check = eval(ast.nth(1), env)
if (check !== NIL && check !== FALSE) {
ast = ast.nth(2)
} else if (ast.count() > 3) {
ast = ast.nth(3)
} else return NIL
}
"quote" -> return ast.nth(1)
"quasiquote" -> ast = quasiquote(ast.nth(1))
else -> {
val evaluated = eval_ast(ast, env) as ISeq
val firstEval = evaluated.first()
when (firstEval) {
is MalFnFunction -> {
ast = firstEval.ast
env = Env(firstEval.env, firstEval.params, evaluated.rest().seq())
}
is MalFunction -> return firstEval.apply(evaluated.rest())
else -> throw MalException("cannot execute non-function")
}
}
}
} else return eval_ast(ast, env)
}
}
fun eval_ast(ast: MalType, env: Env): MalType =
when (ast) {
is MalSymbol -> env.get(ast)
is MalList -> ast.elements.fold(MalList(), { a, b -> a.conj_BANG(eval(b, env)); a })
is MalVector -> ast.elements.fold(MalVector(), { a, b -> a.conj_BANG(eval(b, env)); a })
is MalHashMap -> ast.elements.entries.fold(MalHashMap(), { a, b -> a.assoc_BANG(b.key, eval(b.value, env)); a })
else -> ast
}
private fun fn_STAR(ast: MalList, env: Env): MalType {
val binds = ast.nth(1) as? ISeq ?: throw MalException("fn* requires a binding list as first parameter")
val params = binds.seq().filterIsInstance<MalSymbol>()
val body = ast.nth(2)
return MalFnFunction(body, params, env, { s: ISeq -> eval(body, Env(env, params, s.seq())) })
}
private fun is_pair(ast: MalType): Boolean = ast is ISeq && ast.seq().any()
private fun quasiquote(ast: MalType): MalType {
if (!is_pair(ast)) {
val quoted = MalList()
quoted.conj_BANG(MalSymbol("quote"))
quoted.conj_BANG(ast)
return quoted
}
val seq = ast as ISeq
var first = seq.first()
if ((first as? MalSymbol)?.value == "unquote") {
return seq.nth(1)
}
if (is_pair(first) && ((first as ISeq).first() as? MalSymbol)?.value == "splice-unquote") {
val spliced = MalList()
spliced.conj_BANG(MalSymbol("concat"))
spliced.conj_BANG(first.nth(1))
spliced.conj_BANG(quasiquote(MalList(seq.seq().drop(1).toCollection(LinkedList<MalType>()))))
return spliced
}
val consed = MalList()
consed.conj_BANG(MalSymbol("cons"))
consed.conj_BANG(quasiquote(ast.first()))
consed.conj_BANG(quasiquote(MalList(seq.seq().drop(1).toCollection(LinkedList<MalType>()))))
return consed
}
fun print(result: MalType) = pr_str(result, print_readably = true)
fun rep(input: String, env: Env): String =
print(eval(read(input), env))
fun main(args: Array<String>) {
val repl_env = Env()
ns.forEach({ it -> repl_env.set(it.key, it.value) })
repl_env.set(MalSymbol("*ARGV*"), MalList(args.drop(1).map({ it -> MalString(it) }).toCollection(LinkedList<MalType>())))
repl_env.set(MalSymbol("eval"), MalFunction({ a: ISeq -> eval(a.first(), repl_env) }))
rep("(def! not (fn* (a) (if a false true)))", repl_env)
rep("(def! load-file (fn* (f) (eval (read-string (str \"(do \" (slurp f) \")\")))))", repl_env)
if (args.any()) {
rep("(load-file \"${args[0]}\")", repl_env)
return
}
while (true) {
val input = readline("user> ")
try {
println(rep(input, repl_env))
} catch (e: EofException) {
break
} catch (e: MalContinue) {
} catch (e: MalException) {
println("Error: " + e.message)
} catch (t: Throwable) {
println("Uncaught " + t + ": " + t.message)
t.printStackTrace()
}
}
}
| mpl-2.0 | baaad8565ce0823fd22e69a147fcd96d | 35.087838 | 128 | 0.501779 | 3.92432 | false | false | false | false |
xiprox/Dinner-Menu | app/src/main/kotlin/tr/xip/dinnermenu/model/Menu.kt | 1 | 1182 | package tr.xip.dinnermenu.model
import android.os.Parcel
import android.os.Parcelable
class Menu : Parcelable {
var month: Int? = null
var year: Int? = null
var days: MutableList<Day>? = null
constructor(month: Int?, year: Int?, days: MutableList<Day>?) {
this.month = month
this.year = year
this.days = days
}
constructor(source: Parcel) {
month = source.readInt()
year = source.readInt()
source.readList(days, Day::class.java.classLoader)
}
override fun writeToParcel(dest: Parcel, flags: Int) {
dest.writeInt(month ?: 0)
dest.writeInt(year ?: 0)
dest.writeList(days)
}
override fun describeContents(): Int = 0
override fun toString(): String{
return "Menu(month=$month, year=$year, days=$days)"
}
companion object {
@JvmField
val CREATOR = object : Parcelable.Creator<Menu> {
override fun createFromParcel(`in`: Parcel): Menu {
return Menu(`in`)
}
override fun newArray(size: Int): Array<Menu?> {
return arrayOfNulls(size)
}
}
}
} | gpl-3.0 | f24197619b8dedfef576ab74e1f7f2b2 | 24.170213 | 67 | 0.576142 | 4.267148 | false | false | false | false |
gradle/gradle | subprojects/configuration-cache/src/main/kotlin/org/gradle/configurationcache/ConfigurationCacheBuildOperations.kt | 3 | 2223 | /*
* Copyright 2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gradle.configurationcache
import org.gradle.internal.configurationcache.ConfigurationCacheLoadBuildOperationType
import org.gradle.internal.configurationcache.ConfigurationCacheStoreBuildOperationType
import org.gradle.internal.operations.BuildOperationContext
import org.gradle.internal.operations.BuildOperationDescriptor
import org.gradle.internal.operations.BuildOperationExecutor
import org.gradle.internal.operations.CallableBuildOperation
internal
fun <T : Any> BuildOperationExecutor.withLoadOperation(block: () -> T) =
withOperation("Load configuration cache state", block, LoadDetails, LoadResult)
internal
fun BuildOperationExecutor.withStoreOperation(cacheKey: String, block: () -> Unit) =
withOperation("Store configuration cache state $cacheKey", block, StoreDetails, StoreResult)
private
object LoadDetails : ConfigurationCacheLoadBuildOperationType.Details
private
object LoadResult : ConfigurationCacheLoadBuildOperationType.Result
private
object StoreDetails : ConfigurationCacheStoreBuildOperationType.Details
private
object StoreResult : ConfigurationCacheStoreBuildOperationType.Result
private
fun <T : Any, D : Any, R : Any> BuildOperationExecutor.withOperation(displayName: String, block: () -> T, details: D, result: R): T =
call(object : CallableBuildOperation<T> {
override fun description(): BuildOperationDescriptor.Builder =
BuildOperationDescriptor.displayName(displayName).details(details)
override fun call(context: BuildOperationContext): T =
block().also { context.setResult(result) }
})
| apache-2.0 | 82ed482aa373b9fa95182237443018c4 | 35.442623 | 133 | 0.787674 | 4.719745 | false | true | false | false |
elect86/modern-jogl-examples | src/main/kotlin/main/tut09/scaleAndLighting.kt | 2 | 6858 | package main.tut09
import com.jogamp.newt.event.KeyEvent
import com.jogamp.newt.event.MouseEvent
import com.jogamp.opengl.GL2ES3.*
import com.jogamp.opengl.GL3
import com.jogamp.opengl.GL3.GL_DEPTH_CLAMP
import glNext.*
import glm.f
import glm.mat.Mat4
import glm.quat.Quat
import glm.vec._3.Vec3
import glm.vec._4.Vec4
import main.framework.Framework
import main.framework.Semantic
import main.framework.component.Mesh
import uno.buffer.destroy
import uno.buffer.intBufferBig
import uno.glm.MatrixStack
import uno.glsl.programOf
import uno.mousePole.*
/**
* Created by GBarbieri on 23.03.2017.
*/
fun main(args: Array<String>) {
ScaleAndLighting_().setup("Tutorial 09 - Scale and Lighting")
}
class ScaleAndLighting_ : Framework() {
lateinit var whiteDiffuseColor: ProgramData
lateinit var vertexDiffuseColor: ProgramData
lateinit var cylinder: Mesh
lateinit var plane: Mesh
val projectionUniformBuffer = intBufferBig(1)
val lightDirection = Vec4(0.866f, 0.5f, 0.0f, 0.0f)
var scaleCylinder = false
var doInverseTranspose = true
val initialViewData = ViewData(
Vec3(0.0f, 0.5f, 0.0f),
Quat(0.92387953f, 0.3826834f, 0.0f, 0.0f),
5.0f,
0.0f)
val viewScale = ViewScale(
3.0f, 20.0f,
1.5f, 0.5f,
0.0f, 0.0f, //No camera movement.
90.0f / 250.0f)
val viewPole = ViewPole(initialViewData, viewScale, MouseEvent.BUTTON1)
val initialObjectData = ObjectData(
Vec3(0.0f, 0.5f, 0.0f),
Quat(1.0f, 0.0f, 0.0f, 0.0f))
val objectPole = ObjectPole(initialObjectData, 90.0f / 250.0f, MouseEvent.BUTTON3, viewPole)
override fun init(gl: GL3) = with(gl) {
initializeProgram(gl)
cylinder = Mesh(gl, javaClass, "tut09/UnitCylinder.xml")
plane = Mesh(gl, javaClass, "tut09/LargePlane.xml")
glEnable(GL_CULL_FACE)
glCullFace(GL_BACK)
glFrontFace(GL_CW)
glEnable(GL_DEPTH_TEST)
glDepthMask(true)
glDepthFunc(GL_LEQUAL)
glDepthRangef(0.0f, 1.0f)
glEnable(GL_DEPTH_CLAMP)
glGenBuffer(projectionUniformBuffer)
glBindBuffer(GL_UNIFORM_BUFFER, projectionUniformBuffer)
glBufferData(GL_UNIFORM_BUFFER, Mat4.SIZE, GL_DYNAMIC_DRAW)
//Bind the static buffers.
glBindBufferRange(GL_UNIFORM_BUFFER, Semantic.Uniform.PROJECTION, projectionUniformBuffer, 0, Mat4.SIZE)
glBindBuffer(GL_UNIFORM_BUFFER)
}
fun initializeProgram(gl: GL3) {
whiteDiffuseColor = ProgramData(gl, "dir-vertex-lighting-PN.vert", "color-passthrough.frag")
vertexDiffuseColor = ProgramData(gl, "dir-vertex-lighting-PCN.vert", "color-passthrough.frag")
}
override fun display(gl: GL3) = with(gl) {
glClearBufferf(GL_COLOR, 0)
glClearBufferf(GL_DEPTH)
val modelMatrix = MatrixStack().setMatrix(viewPole.calcMatrix())
val lightDirCameraSpace = modelMatrix.top() * lightDirection
glUseProgram(whiteDiffuseColor.theProgram)
glUniform3f(whiteDiffuseColor.dirToLightUnif, lightDirCameraSpace)
glUseProgram(vertexDiffuseColor.theProgram)
glUniform3f(vertexDiffuseColor.dirToLightUnif, lightDirCameraSpace)
glUseProgram()
modelMatrix run {
//Render the ground plane.
run {
glUseProgram(whiteDiffuseColor.theProgram)
glUniformMatrix4f(whiteDiffuseColor.modelToCameraMatrixUnif, top())
glUniformMatrix3f(whiteDiffuseColor.normalModelToCameraMatrixUnif, top())
glUniform4f(whiteDiffuseColor.lightIntensityUnif, 1.0f)
plane.render(gl)
glUseProgram()
}
//Render the Cylinder
run {
applyMatrix(objectPole.calcMatrix())
if (scaleCylinder)
scale(1.0f, 1.0f, 0.2f)
glUseProgram(vertexDiffuseColor.theProgram)
glUniformMatrix4f(vertexDiffuseColor.modelToCameraMatrixUnif, top())
val normMatrix = top().toMat3()
if (doInverseTranspose)
normMatrix.inverse_().transpose_()
glUniformMatrix3f(vertexDiffuseColor.normalModelToCameraMatrixUnif, normMatrix)
glUniform4f(vertexDiffuseColor.lightIntensityUnif, 1.0f)
cylinder.render(gl, "lit-color")
glUseProgram()
}
}
}
override fun reshape(gl: GL3, w: Int, h: Int) = with(gl) {
val zNear = 1.0f
val zFar = 1_000f
val perspMatrix = MatrixStack()
perspMatrix.perspective(45.0f, w.f / h, zNear, zFar)
glBindBuffer(GL_UNIFORM_BUFFER, projectionUniformBuffer)
glBufferSubData(GL_UNIFORM_BUFFER, perspMatrix.top())
glBindBuffer(GL_UNIFORM_BUFFER)
glViewport(w, h)
}
override fun mousePressed(e: MouseEvent) {
viewPole.mousePressed(e)
objectPole.mousePressed(e)
}
override fun mouseDragged(e: MouseEvent) {
viewPole.mouseDragged(e)
objectPole.mouseDragged(e)
}
override fun mouseReleased(e: MouseEvent) {
viewPole.mouseReleased(e)
objectPole.mouseReleased(e)
}
override fun mouseWheelMoved(e: MouseEvent) {
viewPole.mouseWheel(e)
}
override fun keyPressed(e: KeyEvent) {
when (e.keyCode) {
KeyEvent.VK_ESCAPE -> quit()
KeyEvent.VK_SPACE -> scaleCylinder = !scaleCylinder
KeyEvent.VK_T -> {
doInverseTranspose = !doInverseTranspose
println(if (doInverseTranspose) "Doing Inverse Transpose." else "Bad Lighting.")
}
}
}
override fun end(gl: GL3) = with(gl) {
glDeleteProgram(vertexDiffuseColor.theProgram)
glDeleteProgram(whiteDiffuseColor.theProgram)
glDeleteBuffers(1, projectionUniformBuffer)
cylinder.dispose(gl)
plane.dispose(gl)
projectionUniformBuffer.destroy()
}
inner class ProgramData(gl: GL3, vertex: String, fragment: String) {
val theProgram = programOf(gl, javaClass, "tut09", vertex, fragment)
val dirToLightUnif = gl.glGetUniformLocation(theProgram, "dirToLight")
val lightIntensityUnif = gl.glGetUniformLocation(theProgram, "lightIntensity")
val modelToCameraMatrixUnif = gl.glGetUniformLocation(theProgram, "modelToCameraMatrix")
val normalModelToCameraMatrixUnif = gl.glGetUniformLocation(theProgram, "normalModelToCameraMatrix")
init {
gl.glUniformBlockBinding(
theProgram,
gl.glGetUniformBlockIndex(theProgram, "Projection"),
Semantic.Uniform.PROJECTION)
}
}
} | mit | 9bf78594bde30376798d59e0a4cc3bc1 | 29.083333 | 112 | 0.643482 | 4.118919 | false | false | false | false |
coil-kt/coil | coil-base/src/test/java/coil/disk/FaultyFileSystem.kt | 1 | 2675 | /*
* Copyright (C) 2011 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 coil.disk
import java.io.IOException
import okio.Buffer
import okio.FileSystem
import okio.ForwardingFileSystem
import okio.ForwardingSink
import okio.Path
import okio.Sink
class FaultyFileSystem(delegate: FileSystem) : ForwardingFileSystem(delegate) {
private val writeFaults = mutableSetOf<Path>()
private val deleteFaults = mutableSetOf<Path>()
private val renameFaults = mutableSetOf<Path>()
fun setFaultyWrite(file: Path, faulty: Boolean) {
if (faulty) {
writeFaults += file
} else {
writeFaults -= file
}
}
fun setFaultyDelete(file: Path, faulty: Boolean) {
if (faulty) {
deleteFaults += file
} else {
deleteFaults -= file
}
}
fun setFaultyRename(file: Path, faulty: Boolean) {
if (faulty) {
renameFaults += file
} else {
renameFaults -= file
}
}
override fun atomicMove(source: Path, target: Path) {
if (source in renameFaults || target in renameFaults) throw IOException("boom!")
super.atomicMove(source, target)
}
override fun delete(path: Path, mustExist: Boolean) {
if (path in deleteFaults) throw IOException("boom!")
super.delete(path, mustExist)
}
override fun deleteRecursively(fileOrDirectory: Path, mustExist: Boolean) {
if (fileOrDirectory in deleteFaults) throw IOException("boom!")
super.deleteRecursively(fileOrDirectory, mustExist)
}
override fun appendingSink(file: Path, mustExist: Boolean): Sink =
FaultySink(super.appendingSink(file, mustExist), file)
override fun sink(file: Path, mustCreate: Boolean): Sink =
FaultySink(super.sink(file, mustCreate), file)
inner class FaultySink(sink: Sink, private val file: Path) : ForwardingSink(sink) {
override fun write(source: Buffer, byteCount: Long) {
if (file in writeFaults) throw IOException("boom!")
super.write(source, byteCount)
}
}
}
| apache-2.0 | b901e667099c2650264c3ccc32b538e4 | 31.228916 | 88 | 0.665794 | 4.588336 | false | false | false | false |
saru95/DSA | Kotlin/MaxHeap.kt | 1 | 2811 | import javafx.util.Pair
import java.util.ArrayList
class MaxHeap<T : Comparable<T>> {
private var heap: ArrayList<T>? = null
val isEmpty: Boolean
get() = heap!!.size() <= 1
val max: T
@Throws(EmptyHeapException::class)
get() {
if (heap!!.size() <= 1) {
throw EmptyHeapException("getMax")
}
return heap!!.get(1)
}
constructor() {
heap = ArrayList<T>(32)
heap!!.add(null)
}
private constructor(array: Array<T>?) {
heap = ArrayList<T>(2)
heap!!.add(null)
if (array == null || array.size < 1) {
return
}
heap!!.ensureCapacity(array.size + 2)
for (i in array.indices) {
heap!!.add(array[i])
}
for (i in heap!!.size() / 2 downTo 1) {
bubbleDown(i)
}
}
fun insert(element: T) {
heap!!.add(element)
bubbleUp(heap!!.size() - 1)
}
@Throws(EmptyHeapException::class)
fun extractMax() {
if (heap!!.size() <= 1) {
throw EmptyHeapException("extractMax")
}
heap!!.set(1, heap!!.get(heap!!.size() - 1))
heap!!.remove(heap!!.size() - 1)
bubbleDown(1)
}
private fun bubbleUp(n: Int) {
if (n > 1) {
val parent = heap!!.get(n shr 1)
if (parent.compareTo(heap!!.get(n)) === -1) {
heap!!.set(n shr 1, heap!!.get(n))
heap!!.set(n, parent)
bubbleUp(n shr 1)
}
}
}
private fun bubbleDown(n: Int) {
if ((n shl 1) + 1 < heap!!.size() || n shl 1 < heap!!.size()) {
val son = getSonWithUpperKey(n)
if (son.getValue().compareTo(heap!!.get(n)) === 1) {
heap!!.set(son.getKey(), heap!!.get(n))
heap!!.set(n, son.getValue())
bubbleDown(son.getKey())
}
}
}
private fun getSonWithUpperKey(n: Int): Pair<Integer, T> {
val leftSonIndex = n shl 1
val rightSonIndex = leftSonIndex + 1
if (rightSonIndex >= heap!!.size()) {
return Pair<Integer, T>(leftSonIndex, heap!!.get(leftSonIndex))
}
val leftSon = heap!!.get(leftSonIndex)
val rightSon = heap!!.get(rightSonIndex)
return if (leftSon.compareTo(rightSon) > 0) {
Pair<Integer, T>(leftSonIndex, leftSon)
} else Pair<Integer, T>(rightSonIndex, rightSon)
}
companion object {
fun <E : Comparable<E>> makeHeap(array: Array<E>): MaxHeap<E> {
return MaxHeap(array)
}
}
}
internal class EmptyHeapException(action: String) : Exception("Heap is empty. Cannot perform action '".concat(action).concat("'."))
| mit | 8d525a8d765e549f269d43b1346d6934 | 23.876106 | 131 | 0.501245 | 3.758021 | false | false | false | false |
LorittaBot/Loritta | discord/loritta-bot-common/src/main/kotlin/net/perfectdreams/loritta/morenitta/commands/vanilla/fun/AvaliarWaifuCommand.kt | 1 | 4545 | package net.perfectdreams.loritta.morenitta.commands.vanilla.`fun`
import net.perfectdreams.loritta.morenitta.commands.AbstractCommand
import net.perfectdreams.loritta.morenitta.commands.CommandContext
import net.perfectdreams.loritta.morenitta.utils.Constants
import net.perfectdreams.loritta.morenitta.utils.stripCodeMarks
import net.perfectdreams.loritta.morenitta.messages.LorittaReply
import net.perfectdreams.loritta.common.locale.BaseLocale
import net.perfectdreams.loritta.common.locale.LocaleKeyData
import net.perfectdreams.loritta.common.utils.Emotes
import net.perfectdreams.loritta.morenitta.utils.OutdatedCommandUtils
import java.util.*
import net.perfectdreams.loritta.morenitta.LorittaBot
class AvaliarWaifuCommand(loritta: LorittaBot) : AbstractCommand(loritta, "ratewaifu", listOf("avaliarwaifu", "ratemywaifu", "ratewaifu", "avaliarminhawaifu", "notawaifu"), net.perfectdreams.loritta.common.commands.CommandCategory.FUN) {
companion object {
private const val LOCALE_PREFIX = "commands.command.ratewaifu"
}
override fun getDescriptionKey() = LocaleKeyData("$LOCALE_PREFIX.description")
override fun getExamplesKey() = LocaleKeyData("$LOCALE_PREFIX.examples")
// TODO: Fix Usage
override suspend fun run(context: CommandContext, locale: BaseLocale) {
OutdatedCommandUtils.sendOutdatedCommandMessage(context, locale, "rate waifu")
if (context.args.isNotEmpty()) {
var waifu = context.args.joinToString(separator = " ") // Vamos juntar tudo em uma string
val user = context.getUserAt(0)
if (user != null) {
waifu = user.name
}
val waifuLowerCase = waifu.toLowerCase()
val random = SplittableRandom(Calendar.getInstance(TimeZone.getTimeZone(Constants.LORITTA_TIMEZONE)).get(Calendar.DAY_OF_YEAR) + waifuLowerCase.hashCode().toLong()) // Usar um RANDOM sempre com a mesma seed
val nota = random.nextInt(0, 11)
val scoreReason = context.locale.getList("$LOCALE_PREFIX.note${nota}").random()
var reason = when (nota) {
10 -> "$scoreReason ${Emotes.LORI_WOW}"
9 -> "$scoreReason ${Emotes.LORI_HEART}"
8 -> "$scoreReason ${Emotes.LORI_PAT}"
7 -> "$scoreReason ${Emotes.LORI_SMILE}"
3 -> "$scoreReason ${Emotes.LORI_SHRUG}"
2 -> "$scoreReason ${Emotes.LORI_HMPF}"
1 -> "$scoreReason ${Emotes.LORI_RAGE}"
else -> scoreReason
}
var strNota = nota.toString()
if (waifuLowerCase == "loritta") {
strNota = "∞"
reason = "${context.locale.getList("$LOCALE_PREFIX.noteLoritta").random()} ${Emotes.LORI_YAY}"
}
if (waifuLowerCase == "pollux") {
strNota = "10"
reason = context.locale.getList("$LOCALE_PREFIX.notePollux").random()
}
if (waifuLowerCase == "pantufa") {
strNota = "10"
reason = context.locale.getList("$LOCALE_PREFIX.notePantufa").random() + " ${Emotes.LORI_HEART}"
}
if (waifuLowerCase == "tatsumaki") {
strNota = "10"
reason = context.locale.getList("$LOCALE_PREFIX.noteTatsumaki").random()
}
if (waifuLowerCase == "mee6") {
strNota = "10"
reason = context.locale.getList("$LOCALE_PREFIX.noteMee6").random()
}
if (waifuLowerCase == "mantaro") {
strNota = "10"
reason = context.locale.getList("$LOCALE_PREFIX.noteMantaro").random()
}
if (waifuLowerCase == "dyno") {
strNota = "10"
reason = context.locale.getList("$LOCALE_PREFIX.noteDyno").random()
}
if (waifuLowerCase == "mudae") {
strNota = "10"
reason = context.locale.getList("$LOCALE_PREFIX.noteMudae").random()
}
if (waifuLowerCase == "nadeko") {
strNota = "10"
reason = context.locale.getList("$LOCALE_PREFIX.noteNadeko").random()
}
if (waifuLowerCase == "unbelievaboat") {
strNota = "10"
reason = context.locale.getList("$LOCALE_PREFIX.noteUnbelievaBoat").random()
}
if (waifuLowerCase == "chino kafuu") {
strNota = "10"
reason = context.locale.getList("$LOCALE_PREFIX.noteChinoKafuu").random()
}
if (waifuLowerCase == "groovy") {
strNota = "10"
reason = context.locale.getList("$LOCALE_PREFIX.noteGroovy").random()
}
if (waifuLowerCase == "lorita" || waifuLowerCase == "lorrita") {
strNota = "-∞"
reason = "${context.locale.getList("$LOCALE_PREFIX.noteLorrita").random()} ${Emotes.LORI_HMPF}"
}
context.reply(
LorittaReply(
message = context.locale["$LOCALE_PREFIX.result", strNota, waifu.stripCodeMarks(), reason],
prefix = "\uD83E\uDD14"
)
)
} else {
this.explain(context)
}
}
}
| agpl-3.0 | a2877fe614c5a0efb07109407d820065 | 37.811966 | 237 | 0.685972 | 3.257532 | false | false | false | false |
JustinMullin/drifter-kotlin | src/main/kotlin/xyz/jmullin/drifter/gdx/FloatFrameBuffer.kt | 1 | 1192 | package xyz.jmullin.drifter.gdx
import com.badlogic.gdx.Application.ApplicationType
import com.badlogic.gdx.Gdx
import com.badlogic.gdx.graphics.Texture
import com.badlogic.gdx.graphics.Texture.TextureFilter
import com.badlogic.gdx.graphics.Texture.TextureWrap
import com.badlogic.gdx.graphics.glutils.FrameBuffer
/** This is a [FrameBuffer] variant backed by a float texture. */
class FloatFrameBuffer(width: Int, height: Int, hasDepth: Boolean) : FrameBuffer(null, width, height, hasDepth) {
override fun createTexture(attachmentSpec: FrameBufferTextureAttachmentSpec?): Texture {
val data = FloatTextureData(width, height)
val result = Texture(data)
if (Gdx.app.type == ApplicationType.Desktop || Gdx.app.type == ApplicationType.Applet)
result.setFilter(TextureFilter.Linear, TextureFilter.Linear)
else
// no filtering for float textures in OpenGL ES
result.setFilter(TextureFilter.Nearest, TextureFilter.Nearest)
result.setWrap(TextureWrap.ClampToEdge, TextureWrap.ClampToEdge)
return result
}
override fun disposeColorTexture(colorTexture: Texture) {
colorTexture.dispose()
}
}
| mit | 0380576604686c22724e84f6019aad1c | 41.571429 | 113 | 0.743289 | 4.431227 | false | false | false | false |
danrien/projectBlue | projectBlueWater/src/test/java/com/lasthopesoftware/bluewater/client/playback/engine/GivenAHaltedPlaylistEngine/AndAPlaylistIsPreparing/WhenATrackIsSwitchedTwice.kt | 1 | 2689 | package com.lasthopesoftware.bluewater.client.playback.engine.GivenAHaltedPlaylistEngine.AndAPlaylistIsPreparing
import com.lasthopesoftware.bluewater.client.browsing.items.media.files.ServiceFile
import com.lasthopesoftware.bluewater.client.browsing.library.access.PassThroughLibraryStorage
import com.lasthopesoftware.bluewater.client.browsing.library.access.PassThroughSpecificLibraryProvider
import com.lasthopesoftware.bluewater.client.browsing.library.repository.Library
import com.lasthopesoftware.bluewater.client.playback.engine.PlaybackEngine.Companion.createEngine
import com.lasthopesoftware.bluewater.client.playback.engine.bootstrap.PlaylistPlaybackBootstrapper
import com.lasthopesoftware.bluewater.client.playback.engine.preparation.PreparedPlaybackQueueResourceManagement
import com.lasthopesoftware.bluewater.client.playback.file.preparation.FakeDeferredPlayableFilePreparationSourceProvider
import com.lasthopesoftware.bluewater.client.playback.file.preparation.queues.CompletingFileQueueProvider
import com.lasthopesoftware.bluewater.client.playback.view.nowplaying.storage.NowPlayingRepository
import com.lasthopesoftware.bluewater.client.playback.volume.PlaylistVolumeManager
import com.lasthopesoftware.bluewater.shared.promises.extensions.toFuture
import org.assertj.core.api.Assertions.assertThat
import org.joda.time.Duration
import org.junit.Test
class WhenATrackIsSwitchedTwice {
companion object {
private val nextSwitchedFile by lazy {
val fakePlaybackPreparerProvider = FakeDeferredPlayableFilePreparationSourceProvider()
val library = Library()
library.setId(1)
val libraryProvider = PassThroughSpecificLibraryProvider(library)
val libraryStorage = PassThroughLibraryStorage()
val playbackEngine = createEngine(
PreparedPlaybackQueueResourceManagement(
fakePlaybackPreparerProvider
) { 1 }, listOf(CompletingFileQueueProvider()),
NowPlayingRepository(libraryProvider, libraryStorage),
PlaylistPlaybackBootstrapper(PlaylistVolumeManager(1.0f)))
.toFuture()
.get()
playbackEngine
?.startPlaylist(
listOf(
ServiceFile(1),
ServiceFile(2),
ServiceFile(3),
ServiceFile(4),
ServiceFile(5)
), 0, Duration.ZERO
)
fakePlaybackPreparerProvider.deferredResolution.resolve()
playbackEngine?.changePosition(3, Duration.ZERO)?.toFuture()
val futurePlaylist = playbackEngine?.changePosition(4, Duration.ZERO)?.toFuture()
fakePlaybackPreparerProvider.deferredResolution.resolve()
futurePlaylist?.get()
}
}
@Test
fun thenTheNextFileChangeIsTheSwitchedToTheCorrectTrackPosition() {
assertThat(nextSwitchedFile?.playlistPosition).isEqualTo(4)
}
}
| lgpl-3.0 | 53e2791966425102770e7796d636e9b5 | 43.816667 | 120 | 0.829676 | 4.684669 | false | false | false | false |
carlphilipp/chicago-commutes | android-app/src/main/kotlin/fr/cph/chicago/core/model/BikeStation.kt | 1 | 2465 | /**
* Copyright 2021 Carl-Philipp Harmant
*
*
* 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 fr.cph.chicago.core.model
import android.os.Parcel
import android.os.Parcelable
import org.apache.commons.lang3.StringUtils
class BikeStation(
id: String,
name: String,
val availableDocks: Int,
val availableBikes: Int,
val latitude: Double,
val longitude: Double,
val address: String
) : Parcelable, Station(id, name) {
companion object {
fun buildUnknownStation(): BikeStation {
return buildDefaultBikeStationWithName("Unknown")
}
fun buildDefaultBikeStationWithName(name: String, id: String = StringUtils.EMPTY): BikeStation {
return BikeStation(id, name, -1, -1, 0.0, 0.0, StringUtils.EMPTY)
}
@JvmField
val CREATOR: Parcelable.Creator<BikeStation> = object : Parcelable.Creator<BikeStation> {
override fun createFromParcel(source: Parcel): BikeStation {
return BikeStation(source)
}
override fun newArray(size: Int): Array<BikeStation?> {
return arrayOfNulls(size)
}
}
}
private constructor(source: Parcel) : this(
id = source.readString() ?: StringUtils.EMPTY,
name = source.readString() ?: StringUtils.EMPTY,
availableDocks = source.readInt(),
availableBikes = source.readInt(),
latitude = source.readDouble(),
longitude = source.readDouble(),
address = source.readString() ?: StringUtils.EMPTY
)
override fun describeContents(): Int {
return 0
}
override fun writeToParcel(dest: Parcel, flags: Int) {
dest.writeString(id)
dest.writeString(name)
dest.writeInt(availableDocks)
dest.writeInt(availableBikes)
dest.writeDouble(latitude)
dest.writeDouble(longitude)
dest.writeString(address)
}
}
| apache-2.0 | e3c43f6680470543d89b3a32cc4827ac | 29.8125 | 104 | 0.658012 | 4.386121 | false | false | false | false |
JLLeitschuh/ktlint-gradle | plugin/src/main/kotlin/org/jlleitschuh/gradle/ktlint/tasks/GenerateReportsTask.kt | 1 | 7449 | package org.jlleitschuh.gradle.ktlint.tasks
import net.swiftzer.semver.SemVer
import org.gradle.api.DefaultTask
import org.gradle.api.GradleException
import org.gradle.api.file.ConfigurableFileCollection
import org.gradle.api.file.DirectoryProperty
import org.gradle.api.file.ProjectLayout
import org.gradle.api.file.RegularFileProperty
import org.gradle.api.model.ObjectFactory
import org.gradle.api.provider.Property
import org.gradle.api.provider.SetProperty
import org.gradle.api.tasks.CacheableTask
import org.gradle.api.tasks.Classpath
import org.gradle.api.tasks.Input
import org.gradle.api.tasks.InputFile
import org.gradle.api.tasks.Optional
import org.gradle.api.tasks.OutputDirectory
import org.gradle.api.tasks.PathSensitive
import org.gradle.api.tasks.PathSensitivity
import org.gradle.api.tasks.TaskAction
import org.gradle.workers.WorkerExecutor
import org.jlleitschuh.gradle.ktlint.reporter.ReporterType
import org.jlleitschuh.gradle.ktlint.worker.ConsoleReportWorkAction
import org.jlleitschuh.gradle.ktlint.worker.GenerateReportsWorkAction
import org.jlleitschuh.gradle.ktlint.worker.LoadReportersWorkAction
import java.io.File
import java.io.FileInputStream
import java.io.ObjectInputStream
import javax.inject.Inject
/**
* Generates reports and prints errors into Gradle console.
*
* This will actually fail the build in case some non-corrected lint issues.
*/
@CacheableTask
abstract class GenerateReportsTask @Inject constructor(
private val workerExecutor: WorkerExecutor,
private val projectLayout: ProjectLayout,
objectFactory: ObjectFactory
) : DefaultTask() {
@get:Classpath
internal abstract val ktLintClasspath: ConfigurableFileCollection
@get:Classpath
internal abstract val reportersClasspath: ConfigurableFileCollection
@get:PathSensitive(PathSensitivity.RELATIVE)
@get:InputFile
internal abstract val loadedReporterProviders: RegularFileProperty
@get:PathSensitive(PathSensitivity.RELATIVE)
@get:InputFile
internal abstract val loadedReporters: RegularFileProperty
@get:PathSensitive(PathSensitivity.RELATIVE)
@get:InputFile
internal abstract val discoveredErrors: RegularFileProperty
@get:Input
internal abstract val reportsName: Property<String>
@get:Input
internal abstract val enabledReporters: SetProperty<ReporterType>
@get:Input
internal abstract val outputToConsole: Property<Boolean>
@get:Input
internal abstract val coloredOutput: Property<Boolean>
@get:Input
internal abstract val outputColorName: Property<String>
@get:Input
internal abstract val ignoreFailures: Property<Boolean>
@get:Input
internal abstract val verbose: Property<Boolean>
@get:Input
internal abstract val ktLintVersion: Property<String>
@get:Input
internal abstract val relative: Property<Boolean>
@get:PathSensitive(PathSensitivity.RELATIVE)
@get:InputFile
@get:Optional
internal abstract val baseline: RegularFileProperty
init {
// Workaround for https://github.com/gradle/gradle/issues/2919
onlyIf {
val errorsFile = (it as GenerateReportsTask).discoveredErrors.asFile.get()
errorsFile.exists()
}
}
/**
* Reports output directory.
*
* Default is "build/reports/ktlint/${taskName}/".
*/
@Suppress("UnstableApiUsage")
@get:OutputDirectory
val reportsOutputDirectory: DirectoryProperty = objectFactory
.directoryProperty()
.convention(
reportsName.flatMap {
projectLayout
.buildDirectory
.dir("reports${File.separator}ktlint${File.separator}$it")
}
)
@Suppress("UnstableApiUsage")
@TaskAction
fun generateReports() {
checkBaselineSupportedKtLintVersion()
// Classloader isolation is enough here as we just want to use some classes from KtLint classpath
// to get errors and generate files/console reports. No KtLint main object is initialized/used in this case.
val queue = workerExecutor.classLoaderIsolation { spec ->
spec.classpath.from(ktLintClasspath, reportersClasspath)
}
val loadedReporters = loadLoadedReporters()
.associateWith {
reportsOutputDirectory.file("${reportsName.get()}.${it.fileExtension}")
}
loadedReporters.forEach { (loadedReporter, reporterOutput) ->
queue.submit(GenerateReportsWorkAction::class.java) { param ->
param.discoveredErrorsFile.set(discoveredErrors)
param.loadedReporterProviders.set(loadedReporterProviders)
param.reporterId.set(loadedReporter.reporterId)
param.reporterOutput.set(reporterOutput)
param.reporterOptions.set(generateReporterOptions(loadedReporter))
param.ktLintVersion.set(ktLintVersion)
param.baseline.set(baseline)
param.projectDirectory.set(projectLayout.projectDirectory)
if (relative.get()) {
param.filePathsRelativeTo.set(project.rootDir)
}
}
}
queue.submit(ConsoleReportWorkAction::class.java) { param ->
param.discoveredErrors.set(discoveredErrors)
param.outputToConsole.set(outputToConsole)
param.ignoreFailures.set(ignoreFailures)
param.verbose.set(verbose)
param.generatedReportsPaths.from(loadedReporters.values)
param.ktLintVersion.set(ktLintVersion)
param.baseline.set(baseline)
param.projectDirectory.set(projectLayout.projectDirectory)
}
}
private fun loadLoadedReporters() = ObjectInputStream(
FileInputStream(loadedReporters.asFile.get())
).use {
@Suppress("UNCHECKED_CAST")
it.readObject() as List<LoadReportersWorkAction.LoadedReporter>
}
private fun generateReporterOptions(
loadedReporter: LoadReportersWorkAction.LoadedReporter
): Map<String, String> {
val options = mutableMapOf(
"verbose" to verbose.get().toString(),
"color" to coloredOutput.get().toString()
)
if (outputColorName.get().isNotBlank()) {
options["color_name"] = outputColorName.get()
} else {
// Same default as in the KtLint CLI
options["color_name"] = "DARK_GRAY"
}
options.putAll(loadedReporter.reporterOptions)
return options.toMap()
}
private fun checkBaselineSupportedKtLintVersion() {
if (baseline.isPresent && SemVer.parse(ktLintVersion.get()) < SemVer(0, 41, 0)) {
throw GradleException("Baseline support is only enabled for KtLint versions 0.41.0+.")
}
}
internal enum class LintType(
val suffix: String
) {
CHECK("Check"), FORMAT("Format")
}
internal companion object {
internal fun generateNameForSourceSets(
sourceSetName: String,
lintType: LintType
): String = "ktlint${sourceSetName.capitalize()}SourceSet${lintType.suffix}"
internal fun generateNameForKotlinScripts(
lintType: LintType
): String = "ktlintKotlinScript${lintType.suffix}"
const val DESCRIPTION = "Generates reports and prints errors into Gradle console."
}
}
| mit | 83ffa99d41e740c0e271482ffbf266c0 | 34.471429 | 116 | 0.697409 | 4.73855 | false | false | false | false |
JetBrains/resharper-unity | rider/src/main/kotlin/com/jetbrains/rider/plugins/unity/workspace/UnityWorkspaceModelUpdater.kt | 1 | 2724 | @file:Suppress("UnstableApiUsage")
package com.jetbrains.rider.plugins.unity.workspace
import com.intellij.openapi.project.Project
import com.intellij.util.application
import com.intellij.workspaceModel.ide.WorkspaceModel
import com.intellij.workspaceModel.ide.getInstance
import com.intellij.workspaceModel.storage.MutableEntityStorage
import com.intellij.workspaceModel.storage.bridgeEntities.addContentRootEntityWithCustomEntitySource
import com.intellij.workspaceModel.storage.impl.url.toVirtualFileUrl
import com.intellij.workspaceModel.storage.url.VirtualFileUrl
import com.intellij.workspaceModel.storage.url.VirtualFileUrlManager
import com.jetbrains.rider.plugins.unity.isUnityProject
import com.jetbrains.rider.projectView.solutionDirectory
import com.jetbrains.rider.projectView.workspace.RiderEntitySource
import com.jetbrains.rider.projectView.workspace.getOrCreateRiderModuleEntity
class UnityWorkspaceModelUpdater(private val project: Project) {
init {
application.invokeLater {
if (project.isDisposed)
return@invokeLater
if (project.isUnityProject()) {
rebuildWorkspaceModel()
}
}
}
@Suppress("UnstableApiUsage")
private fun rebuildWorkspaceModel() {
application.assertIsDispatchThread()
if (!project.isUnityProject()) return
val builder = MutableEntityStorage.create()
val virtualFileUrlManager = VirtualFileUrlManager.getInstance(project)
val packagesModuleEntity = builder.getOrCreateRiderModuleEntity()
// TODO: WORKSPACEMODEL
// We want to include list of special files (by extensions comes from unity editor)
// in the content model. It is better to do it on backed via backend PackageManager
val excludedUrls = emptyList<VirtualFileUrl>()
val excludedPatterns = UNITY_EXCLUDED_PATTERNS
builder.addContentRootEntityWithCustomEntitySource(
project.solutionDirectory.resolve("Packages").toVirtualFileUrl(virtualFileUrlManager),
excludedUrls,
excludedPatterns,
packagesModuleEntity,
RiderUnityEntitySource)
builder.addContentRootEntityWithCustomEntitySource(
project.solutionDirectory.resolve("ProjectSettings").toVirtualFileUrl(virtualFileUrlManager),
excludedUrls,
excludedPatterns,
packagesModuleEntity,
RiderUnityEntitySource)
application.runWriteAction {
WorkspaceModel.getInstance(project).updateProjectModel { x -> x.replaceBySource({ it is RiderUnityEntitySource }, builder) }
}
}
object RiderUnityEntitySource : RiderEntitySource
} | apache-2.0 | c0e813ea10412e97ee495ad9fad66db8 | 39.073529 | 136 | 0.743392 | 5.734737 | false | false | false | false |
Ph1b/MaterialAudiobookPlayer | scanner/src/main/kotlin/de/ph1b/audiobook/scanner/FileRecognition.kt | 1 | 966 | package de.ph1b.audiobook.scanner
import java.io.FileFilter
/**
* Class containing methods for recognizing different file types by their file ending.
*/
object FileRecognition {
private val imageTypes = listOf("jpg", "jpeg", "png", "bmp")
private val audioTypes = arrayOf(
"3gp",
"aac",
"awb",
"flac",
"imy",
"m4a",
"m4b",
"mid",
"mka",
"mkv",
"mp3",
"mp3package",
"mp4",
"opus",
"mxmf",
"oga",
"ogg",
"ota",
"rtttl",
"rtx",
"wav",
"webm",
"wma",
"xmf"
)
val imageFilter = FileFilter {
val extension = it.extension.lowercase()
extension in imageTypes
}
val musicFilter = FileFilter {
val extension = it.extension.lowercase()
extension in audioTypes
}
val folderAndMusicFilter = FileFilter {
if (it.isDirectory) {
true
} else {
val extension = it.extension.lowercase()
extension in audioTypes
}
}
}
| lgpl-3.0 | b3eaecc8940f0b5faecac93e988973e5 | 16.25 | 86 | 0.576605 | 3.437722 | false | false | false | false |
Deletescape-Media/Lawnchair | quickstep/src/com/android/quickstep/views/TaskMenuViewWithArrow.kt | 2 | 12331 | /*
* Copyright (C) 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.quickstep.views
import android.animation.AnimatorSet
import android.animation.ObjectAnimator
import android.content.Context
import android.graphics.Rect
import android.graphics.drawable.ShapeDrawable
import android.graphics.drawable.shapes.RectShape
import android.util.AttributeSet
import android.view.Gravity
import android.view.MotionEvent
import android.view.View
import android.view.ViewGroup
import android.widget.FrameLayout
import android.widget.LinearLayout
import com.android.launcher3.BaseDraggingActivity
import com.android.launcher3.DeviceProfile
import com.android.launcher3.InsettableFrameLayout
import com.android.launcher3.R
import com.android.launcher3.popup.ArrowPopup
import com.android.launcher3.popup.RoundedArrowDrawable
import com.android.launcher3.popup.SystemShortcut
import com.android.launcher3.util.Themes
import com.android.quickstep.KtR
import com.android.quickstep.TaskOverlayFactory
import com.android.quickstep.views.TaskView.TaskIdAttributeContainer
class TaskMenuViewWithArrow<T : BaseDraggingActivity> : ArrowPopup<T> {
companion object {
const val TAG = "TaskMenuViewWithArrow"
fun showForTask(
taskContainer: TaskIdAttributeContainer,
alignSecondRow: Boolean = false
): Boolean {
val activity = BaseDraggingActivity
.fromContext<BaseDraggingActivity>(taskContainer.taskView.context)
val taskMenuViewWithArrow = activity.layoutInflater
.inflate(
KtR.layout.task_menu_with_arrow,
activity.dragLayer,
false
) as TaskMenuViewWithArrow<*>
return taskMenuViewWithArrow.populateAndShowForTask(taskContainer, alignSecondRow)
}
}
constructor(context: Context) : super(context)
constructor(context: Context, attrs: AttributeSet) : super(context, attrs)
constructor(context: Context, attrs: AttributeSet, defStyleAttr: Int) : super(
context,
attrs,
defStyleAttr
)
init {
clipToOutline = true
shouldScaleArrow = true
// This synchronizes the arrow and menu to open at the same time
OPEN_CHILD_FADE_START_DELAY = OPEN_FADE_START_DELAY
OPEN_CHILD_FADE_DURATION = OPEN_FADE_DURATION
CLOSE_FADE_START_DELAY = CLOSE_CHILD_FADE_START_DELAY
CLOSE_FADE_DURATION = CLOSE_CHILD_FADE_DURATION
}
private var alignSecondRow: Boolean = false
private val extraSpaceForSecondRowAlignment: Int
get() = if (alignSecondRow) optionMeasuredHeight else 0
private val menuWidth = context.resources.getDimensionPixelSize(R.dimen.task_menu_width_grid)
private lateinit var taskView: TaskView
private lateinit var optionLayout: LinearLayout
private lateinit var taskContainer: TaskIdAttributeContainer
private var optionMeasuredHeight = 0
private val arrowHorizontalPadding: Int
get() = if (taskView.isFocusedTask)
resources.getDimensionPixelSize(KtR.dimen.task_menu_horizontal_padding)
else
0
private var iconView: IconView? = null
private var scrim: View? = null
private val scrimAlpha = 0.8f
override fun isOfType(type: Int): Boolean = type and TYPE_TASK_MENU != 0
override fun getTargetObjectLocation(outPos: Rect?) {
popupContainer.getDescendantRectRelativeToSelf(taskContainer.iconView, outPos)
}
override fun onControllerInterceptTouchEvent(ev: MotionEvent?): Boolean {
if (ev?.action == MotionEvent.ACTION_DOWN) {
if (!popupContainer.isEventOverView(this, ev)) {
close(true)
return true
}
}
return false
}
override fun onFinishInflate() {
super.onFinishInflate()
optionLayout = findViewById(KtR.id.menu_option_layout)
}
private fun populateAndShowForTask(
taskContainer: TaskIdAttributeContainer,
alignSecondRow: Boolean
): Boolean {
if (isAttachedToWindow) {
return false
}
taskView = taskContainer.taskView
this.taskContainer = taskContainer
this.alignSecondRow = alignSecondRow
if (!populateMenu()) return false
addScrim()
show()
return true
}
private fun addScrim() {
scrim = View(context).apply {
layoutParams = FrameLayout.LayoutParams(
FrameLayout.LayoutParams.MATCH_PARENT,
FrameLayout.LayoutParams.MATCH_PARENT
)
setBackgroundColor(Themes.getAttrColor(context, R.attr.overviewScrimColor))
alpha = 0f
}
popupContainer.addView(scrim)
}
/** @return true if successfully able to populate task view menu, false otherwise
*/
private fun populateMenu(): Boolean {
// Icon may not be loaded
if (taskContainer.task.icon == null) return false
addMenuOptions()
return true
}
private fun addMenuOptions() {
// Add the options
TaskOverlayFactory
.getEnabledShortcuts(taskView, mActivityContext.deviceProfile, taskContainer)
.forEach { this.addMenuOption(it) }
// Add the spaces between items
val divider = ShapeDrawable(RectShape())
divider.paint.color = resources.getColor(android.R.color.transparent)
val dividerSpacing = resources.getDimension(KtR.dimen.task_menu_spacing).toInt()
optionLayout.showDividers = SHOW_DIVIDER_MIDDLE
// Set the orientation, which makes the menu show
val recentsView: RecentsView<*, *> = mActivityContext.getOverviewPanel()
val orientationHandler = recentsView.pagedOrientationHandler
val deviceProfile: DeviceProfile = mActivityContext.deviceProfile
orientationHandler.setTaskOptionsMenuLayoutOrientation(
deviceProfile,
optionLayout,
dividerSpacing,
divider
)
}
private fun addMenuOption(menuOption: SystemShortcut<*>) {
val menuOptionView = mActivityContext.layoutInflater.inflate(
KtR.layout.task_view_menu_option, this, false
) as LinearLayout
menuOption.setIconAndLabelFor(
menuOptionView.findViewById(R.id.icon),
menuOptionView.findViewById(R.id.text)
)
val lp = menuOptionView.layoutParams as LayoutParams
lp.width = menuWidth
menuOptionView.setOnClickListener { view: View? -> menuOption.onClick(view) }
optionLayout.addView(menuOptionView)
}
override fun assignMarginsAndBackgrounds(viewGroup: ViewGroup) {
assignMarginsAndBackgrounds(
this,
Themes.getAttrColor(context, com.android.internal.R.attr.colorSurface)
)
}
override fun onCreateOpenAnimation(anim: AnimatorSet) {
scrim?.let {
anim.play(
ObjectAnimator.ofFloat(it, View.ALPHA, 0f, scrimAlpha)
.setDuration(OPEN_DURATION.toLong())
)
}
}
override fun onCreateCloseAnimation(anim: AnimatorSet) {
scrim?.let {
anim.play(
ObjectAnimator.ofFloat(it, View.ALPHA, scrimAlpha, 0f)
.setDuration(CLOSE_DURATION.toLong())
)
}
}
override fun closeComplete() {
super.closeComplete()
popupContainer.removeView(scrim)
popupContainer.removeView(iconView)
}
/**
* Copy the iconView from taskView to dragLayer so it can stay on top of the scrim.
* It needs to be called after [getTargetObjectLocation] because [mTempRect] needs to be
* populated.
*/
private fun copyIconToDragLayer(insets: Rect) {
iconView = IconView(context).apply {
layoutParams = FrameLayout.LayoutParams(
taskContainer.iconView.width,
taskContainer.iconView.height
)
x = mTempRect.left.toFloat() - insets.left
y = mTempRect.top.toFloat() - insets.top
drawable = taskContainer.iconView.drawable
setDrawableSize(
taskContainer.iconView.drawableWidth,
taskContainer.iconView.drawableHeight
)
}
popupContainer.addView(iconView)
}
/**
* Orients this container to the left or right of the given icon, aligning with the first option
* or second.
*
* These are the preferred orientations, in order (RTL prefers right-aligned over left):
* - Right and first option aligned
* - Right and second option aligned
* - Left and first option aligned
* - Left and second option aligned
*
* So we always align right if there is enough horizontal space
*/
override fun orientAboutObject() {
measure(MeasureSpec.UNSPECIFIED, MeasureSpec.UNSPECIFIED)
// Needed for offsets later
optionMeasuredHeight = optionLayout.getChildAt(0).measuredHeight
val extraHorizontalSpace = (mArrowHeight + mArrowOffsetVertical + arrowHorizontalPadding)
val widthWithArrow = measuredWidth + paddingLeft + paddingRight + extraHorizontalSpace
getTargetObjectLocation(mTempRect)
val dragLayer: InsettableFrameLayout = popupContainer
val insets = dragLayer.insets
copyIconToDragLayer(insets)
// Put this menu to the right of the icon if there is space,
// which means the arrow is left aligned with the menu
val rightAlignedMenuStartX = mTempRect.left - widthWithArrow
val leftAlignedMenuStartX = mTempRect.right + extraHorizontalSpace
mIsLeftAligned = if (mIsRtl) {
rightAlignedMenuStartX + insets.left < 0
} else {
leftAlignedMenuStartX + (widthWithArrow - extraHorizontalSpace) + insets.left <
dragLayer.width - insets.right
}
var menuStartX = if (mIsLeftAligned) leftAlignedMenuStartX else rightAlignedMenuStartX
// Offset y so that the arrow and row are center-aligned with the original icon.
val iconHeight = mTempRect.height()
val yOffset = (optionMeasuredHeight - iconHeight) / 2
var menuStartY = mTempRect.top - yOffset - extraSpaceForSecondRowAlignment
// Insets are added later, so subtract them now.
menuStartX -= insets.left
menuStartY -= insets.top
x = menuStartX.toFloat()
y = menuStartY.toFloat()
val lp = layoutParams as FrameLayout.LayoutParams
val arrowLp = mArrow.layoutParams as FrameLayout.LayoutParams
lp.gravity = Gravity.TOP
arrowLp.gravity = lp.gravity
}
override fun addArrow() {
popupContainer.addView(mArrow)
mArrow.x = getArrowX()
mArrow.y = y + (optionMeasuredHeight / 2) - (mArrowHeight / 2) +
extraSpaceForSecondRowAlignment
updateArrowColor()
// This is inverted (x = height, y = width) because the arrow is rotated
mArrow.pivotX = if (mIsLeftAligned) 0f else mArrowHeight.toFloat()
mArrow.pivotY = 0f
}
private fun getArrowX(): Float {
return if (mIsLeftAligned)
x - mArrowHeight
else
x + measuredWidth + mArrowOffsetVertical
}
override fun updateArrowColor() {
mArrow.background = RoundedArrowDrawable(
mArrowWidth.toFloat(),
mArrowHeight.toFloat(),
mArrowPointRadius.toFloat(),
mIsLeftAligned,
mArrowColor
)
elevation = mElevation
mArrow.elevation = mElevation
}
} | gpl-3.0 | 533e7e45fda42315e214c142aec4d3dd | 34.848837 | 100 | 0.664747 | 4.731773 | false | false | false | false |
Deletescape-Media/Lawnchair | lawnchair/src/app/lawnchair/ui/preferences/components/SwitchPreference.kt | 1 | 3050 | /*
* Copyright 2021, Lawnchair
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package app.lawnchair.ui.preferences.components
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.*
import androidx.compose.material3.Switch
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import app.lawnchair.preferences.PreferenceAdapter
import app.lawnchair.ui.theme.dividerColor
import app.lawnchair.ui.util.addIf
@Composable
fun SwitchPreference(
adapter: PreferenceAdapter<Boolean>,
label: String,
description: String? = null,
onClick: (() -> Unit)? = null,
enabled: Boolean = true,
) {
val checked = adapter.state.value
SwitchPreference(
checked = checked,
onCheckedChange = adapter::onChange,
label = label,
description = description,
onClick = onClick,
enabled = enabled,
)
}
@Composable
fun SwitchPreference(
checked: Boolean,
onCheckedChange: (Boolean) -> Unit,
label: String,
description: String? = null,
onClick: (() -> Unit)? = null,
enabled: Boolean = true,
) {
PreferenceTemplate(
modifier = Modifier.clickable(enabled = enabled) {
if (onClick != null) {
onClick()
} else {
onCheckedChange(!checked)
}
},
contentModifier = Modifier
.fillMaxHeight()
.padding(vertical = 16.dp)
.padding(start = 16.dp),
title = { Text(text = label) },
description = { description?.let { Text(text = it) } },
endWidget = {
if (onClick != null) {
Spacer(
modifier = Modifier
.height(32.dp)
.width(1.dp)
.fillMaxHeight()
.background(dividerColor())
)
}
Switch(
modifier = Modifier
.addIf(onClick != null) {
clickable(enabled = enabled) { onCheckedChange(!checked) }
}
.padding(all = 16.dp)
.height(24.dp),
checked = checked,
onCheckedChange = null,
enabled = enabled,
)
},
enabled = enabled,
applyPaddings = false
)
}
| gpl-3.0 | 32d0454eb289f5ef1857c182b055edc3 | 30.122449 | 82 | 0.588197 | 4.736025 | false | false | false | false |
inorichi/tachiyomi | app/src/main/java/eu/kanade/tachiyomi/extension/model/Extension.kt | 1 | 1596 | package eu.kanade.tachiyomi.extension.model
import eu.kanade.tachiyomi.source.Source
sealed class Extension {
abstract val name: String
abstract val pkgName: String
abstract val versionName: String
abstract val versionCode: Long
abstract val lang: String?
abstract val isNsfw: Boolean
data class Installed(
override val name: String,
override val pkgName: String,
override val versionName: String,
override val versionCode: Long,
override val lang: String,
override val isNsfw: Boolean,
val pkgFactory: String?,
val sources: List<Source>,
val hasUpdate: Boolean = false,
val isObsolete: Boolean = false,
val isUnofficial: Boolean = false
) : Extension()
data class Available(
override val name: String,
override val pkgName: String,
override val versionName: String,
override val versionCode: Long,
override val lang: String,
override val isNsfw: Boolean,
val sources: List<AvailableExtensionSources>,
val apkName: String,
val iconUrl: String
) : Extension()
data class Untrusted(
override val name: String,
override val pkgName: String,
override val versionName: String,
override val versionCode: Long,
val signatureHash: String,
override val lang: String? = null,
override val isNsfw: Boolean = false
) : Extension()
}
data class AvailableExtensionSources(
val name: String,
val id: Long,
val baseUrl: String
)
| apache-2.0 | b69ab60ca43342b0faf51b382d4488ca | 28.018182 | 53 | 0.651003 | 4.910769 | false | false | false | false |
googlemaps/android-samples | ApiDemos/kotlin/app/src/gms/java/com/example/kotlindemos/StreetViewPanoramaOptionsDemoActivity.kt | 1 | 4251 | // 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
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.example.kotlindemos
import android.os.Bundle
import android.view.View
import android.widget.CheckBox
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.google.android.gms.maps.StreetViewPanorama
import com.google.android.gms.maps.SupportStreetViewPanoramaFragment
import com.google.android.gms.maps.model.LatLng
import com.google.android.gms.maps.model.StreetViewSource
/**
* This shows how to create an activity with static streetview (all options have been switched off)
*/
class StreetViewPanoramaOptionsDemoActivity : AppCompatActivity() {
private var streetViewPanorama: StreetViewPanorama? = null
private lateinit var streetNameCheckbox: CheckBox
private lateinit var navigationCheckbox: CheckBox
private lateinit var zoomCheckbox: CheckBox
private lateinit var panningCheckbox: CheckBox
private lateinit var outdoorCheckbox: CheckBox
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.street_view_panorama_options_demo)
streetNameCheckbox = findViewById(R.id.streetnames)
navigationCheckbox = findViewById(R.id.navigation)
zoomCheckbox = findViewById(R.id.zoom)
panningCheckbox = findViewById(R.id.panning)
outdoorCheckbox = findViewById(R.id.outdoor)
val streetViewPanoramaFragment =
supportFragmentManager.findFragmentById(R.id.streetviewpanorama) as SupportStreetViewPanoramaFragment?
streetViewPanoramaFragment?.getStreetViewPanoramaAsync { panorama: StreetViewPanorama ->
streetViewPanorama = panorama
panorama.isStreetNamesEnabled = streetNameCheckbox.isChecked()
panorama.isUserNavigationEnabled = navigationCheckbox.isChecked()
panorama.isZoomGesturesEnabled = zoomCheckbox.isChecked()
panorama.isPanningGesturesEnabled = panningCheckbox.isChecked()
// Only set the panorama to SAN_FRAN on startup (when no panoramas have been
// loaded which is when the savedInstanceState is null).
savedInstanceState ?: setPosition()
}
}
private fun setPosition() {
streetViewPanorama?.setPosition(
SAN_FRAN,
RADIUS,
if (outdoorCheckbox.isChecked) StreetViewSource.OUTDOOR else StreetViewSource.DEFAULT
)
}
private fun checkReady(): Boolean {
if (streetViewPanorama == null) {
Toast.makeText(this, R.string.map_not_ready, Toast.LENGTH_SHORT).show()
return false
}
return true
}
fun onStreetNamesToggled(view: View?) {
if (!checkReady()) {
return
}
streetViewPanorama?.isStreetNamesEnabled = streetNameCheckbox.isChecked
}
fun onNavigationToggled(view: View?) {
if (!checkReady()) {
return
}
streetViewPanorama?.isUserNavigationEnabled = navigationCheckbox.isChecked
}
fun onZoomToggled(view: View?) {
if (!checkReady()) {
return
}
streetViewPanorama?.isZoomGesturesEnabled = zoomCheckbox.isChecked
}
fun onPanningToggled(view: View?) {
if (!checkReady()) {
return
}
streetViewPanorama?.isPanningGesturesEnabled = panningCheckbox.isChecked
}
fun onOutdoorToggled(view: View?) {
if (!checkReady()) {
return
}
setPosition()
}
companion object {
// Cole St, San Fran
private val SAN_FRAN = LatLng(37.765927, -122.449972)
private const val RADIUS = 20
}
} | apache-2.0 | 85c0f555a2b1ba3f47a803fe682ef284 | 35.34188 | 114 | 0.693249 | 4.875 | false | false | false | false |
tinypass/piano-sdk-for-android | show-custom-form/src/main/java/io/piano/android/showform/ShowFormJs.kt | 1 | 2039 | package io.piano.android.showform
import android.view.View
import android.webkit.JavascriptInterface
import android.webkit.WebView
import androidx.annotation.UiThread
import io.piano.android.composer.Composer
import io.piano.android.showhelper.BaseJsInterface
import timber.log.Timber
import kotlin.properties.Delegates
class ShowFormJs(
private val formName: String,
private val trackingId: String,
internal var loginCallback: () -> Unit = {}
) : BaseJsInterface() {
internal var token: String by Delegates.observable("") { _, oldValue, newValue ->
if (isReady && oldValue != newValue)
updateToken()
}
private var isReady: Boolean = false
internal fun init(dialogFragment: ShowFormDialogFragment?, webView: WebView?, loginCallback: () -> Unit) {
super.init(dialogFragment, webView)
this.loginCallback = loginCallback
}
private fun updateToken() {
executeJavascript(
"""PianoIDMobileSDK.messageCallback('{"event":"setToken","params":"$token"}')""",
200
)
}
@JavascriptInterface
fun postMessage(data: String) {
ShowFormController.eventAdapter.fromJson(data)?.apply {
when (event) {
"formSend" -> {
Composer.getInstance().trackCustomFormSubmission(formName, trackingId)
close()
}
"formSkip" -> close()
"stateReady" -> {
isReady = true
Composer.getInstance().trackCustomFormImpression(formName, trackingId)
updateToken()
}
"tokenRejected" -> loginCallback.invoke()
}
} ?: Timber.d("Can't parse $data")
}
@UiThread
fun close() {
Composer.getInstance().trackCloseEvent(trackingId)
fragment?.dismissAllowingStateLoss()
?: webView?.apply {
visibility = View.GONE
loadUrl("about:blank")
}
}
}
| apache-2.0 | 4d36f8512f76aa2386ca5d494c445f18 | 31.365079 | 110 | 0.598823 | 4.925121 | false | false | false | false |
googleapis/gax-kotlin | kgax-grpc/src/main/kotlin/com/google/api/kgax/grpc/LongRunningCall.kt | 1 | 2967 | /*
* Copyright 2018 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.api.kgax.grpc
import com.google.common.util.concurrent.ListenableFuture
import com.google.longrunning.GetOperationRequest
import com.google.longrunning.Operation
import com.google.longrunning.OperationsClientStub
import com.google.protobuf.Message
import io.grpc.Status
import io.grpc.stub.AbstractStub
import kotlinx.coroutines.Deferred
import kotlinx.coroutines.async
import kotlinx.coroutines.coroutineScope
/** Resolves long running operations. */
class LongRunningCall<T : Message>(
private val stub: GrpcClientStub<OperationsClientStub>,
deferred: Deferred<Operation>,
responseType: Class<T>
) : LongRunningCallBase<T, Operation>(deferred, responseType) {
override suspend fun nextOperation(op: Operation) = stub.execute {
it.getOperation(
GetOperationRequest.newBuilder()
.setName(operation!!.name)
.build()
)
}
override fun isOperationDone(op: Operation) = op.done
override fun parse(operation: Operation, type: Class<T>): T {
if (operation.error == null || operation.error.code == Status.Code.OK.value()) {
return operation.response.unpack(type)
}
throw RuntimeException("Operation completed with error: ${operation.error.code}\n details: ${operation.error.message}")
}
}
/**
* Execute a long running operation. For example:
*
* ```
* val response = stub.executeLongRunning(MyLongRunningResponse::class.java) {
* it.myLongRunningMethod(...)
* }
* print("${response.body}")
* ```
*
* The [method] lambda should perform a future method call on the stub given as the
* first parameter. The result along with any additional information, such as
* [ResponseMetadata], will be returned as a [LongRunningCall]. The [type] given
* must match the return type of the Operation.
*
* An optional [context] can be supplied to enable arbitrary retry strategies.
*/
suspend fun <RespT : Message, T : AbstractStub<T>> GrpcClientStub<T>.executeLongRunning(
type: Class<RespT>,
context: String = "",
method: (T) -> ListenableFuture<Operation>
): LongRunningCall<RespT> = coroutineScope {
val operationsStub = GrpcClientStub(OperationsClientStub(stubWithContext().channel), options)
val deferred = async { execute(context, method) }
LongRunningCall(operationsStub, deferred, type)
}
| apache-2.0 | b17c23f3ed8fb150a0d9c5287d251c72 | 35.62963 | 127 | 0.72329 | 4.226496 | false | false | false | false |
eugeis/ee-schkola | ee-schkola/src-gen/main/kotlin/ee/schkola/finance/FinanceApiBase.kt | 1 | 1763 | package ee.schkola.finance
import ee.schkola.SchkolaBase
import ee.schkola.person.Profile
import java.util.*
open class Expense : SchkolaBase {
val purpose: ExpensePurpose
val amount: Float
val profile: Profile
val date: Date
constructor(id: String = "", purpose: ExpensePurpose = ExpensePurpose(), amount: Float = 0f,
profile: Profile = Profile(), date: Date = Date()) : super(id) {
this.purpose = purpose
this.amount = amount
this.profile = profile
this.date = date
}
companion object {
val EMPTY = Expense()
}
}
open class ExpensePurpose : SchkolaBase {
val name: String
val description: String
constructor(id: String = "", name: String = "", description: String = "") : super(id) {
this.name = name
this.description = description
}
companion object {
val EMPTY = ExpensePurpose()
}
}
open class Fee : SchkolaBase {
val student: Profile
val amount: Float
val kind: FeeKind
val date: Date
constructor(id: String = "", student: Profile = Profile(), amount: Float = 0f, kind: FeeKind = FeeKind(),
date: Date = Date()) : super(id) {
this.student = student
this.amount = amount
this.kind = kind
this.date = date
}
companion object {
val EMPTY = Fee()
}
}
open class FeeKind : SchkolaBase {
val name: String
val amount: Float
val description: String
constructor(id: String = "", name: String = "", amount: Float = 0f, description: String = "") : super(id) {
this.name = name
this.amount = amount
this.description = description
}
companion object {
val EMPTY = FeeKind()
}
}
| apache-2.0 | 5a6f2e9d7b7ca04ac784ecdf2d3bb969 | 19.988095 | 111 | 0.599546 | 3.988688 | false | false | false | false |
AllanWang/Frost-for-Facebook | app/src/main/kotlin/com/pitchedapps/frost/views/Keywords.kt | 1 | 4684 | /*
* Copyright 2018 Allan Wang
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.pitchedapps.frost.views
import android.content.Context
import android.graphics.drawable.Drawable
import android.util.AttributeSet
import android.view.View
import android.widget.ImageView
import androidx.appcompat.widget.AppCompatEditText
import androidx.appcompat.widget.AppCompatTextView
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import ca.allanwang.kau.utils.bindView
import ca.allanwang.kau.utils.string
import ca.allanwang.kau.utils.tint
import ca.allanwang.kau.utils.toDrawable
import com.mikepenz.fastadapter.FastAdapter
import com.mikepenz.fastadapter.adapters.FastItemAdapter
import com.mikepenz.fastadapter.items.AbstractItem
import com.mikepenz.fastadapter.listeners.ClickEventHook
import com.mikepenz.iconics.typeface.IIcon
import com.mikepenz.iconics.typeface.library.googlematerial.GoogleMaterial
import com.pitchedapps.frost.R
import com.pitchedapps.frost.injectors.ThemeProvider
import com.pitchedapps.frost.prefs.Prefs
import dagger.hilt.android.AndroidEntryPoint
import javax.inject.Inject
/** Created by Allan Wang on 2017-06-19. */
@AndroidEntryPoint
class Keywords
@JvmOverloads
constructor(context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0) :
ConstraintLayout(context, attrs, defStyleAttr) {
@Inject lateinit var prefs: Prefs
@Inject lateinit var themeProvider: ThemeProvider
val editText: AppCompatEditText by bindView(R.id.edit_text)
val addIcon: ImageView by bindView(R.id.add_icon)
val recycler: RecyclerView by bindView(R.id.recycler)
val adapter = FastItemAdapter<KeywordItem>()
init {
inflate(context, R.layout.view_keywords, this)
editText.tint(themeProvider.textColor)
addIcon.setImageDrawable(GoogleMaterial.Icon.gmd_add.keywordDrawable(context, themeProvider))
addIcon.setOnClickListener {
if (editText.text.isNullOrEmpty()) editText.error = context.string(R.string.empty_keyword)
else {
adapter.add(0, KeywordItem(editText.text.toString(), themeProvider))
editText.text?.clear()
}
}
adapter.add(prefs.notificationKeywords.map { KeywordItem(it, themeProvider) })
recycler.layoutManager = LinearLayoutManager(context)
recycler.adapter = adapter
adapter.addEventHook(
object : ClickEventHook<KeywordItem>() {
override fun onBind(viewHolder: RecyclerView.ViewHolder): View? =
(viewHolder as? KeywordItem.ViewHolder)?.delete
override fun onClick(
v: View,
position: Int,
fastAdapter: FastAdapter<KeywordItem>,
item: KeywordItem
) {
adapter.remove(position)
}
}
)
}
fun save() {
prefs.notificationKeywords = adapter.adapterItems.mapTo(mutableSetOf()) { it.keyword }
}
}
private fun IIcon.keywordDrawable(context: Context, themeProvider: ThemeProvider): Drawable =
toDrawable(context, 20, themeProvider.textColor)
class KeywordItem(val keyword: String, private val themeProvider: ThemeProvider) :
AbstractItem<KeywordItem.ViewHolder>() {
override fun getViewHolder(v: View): ViewHolder = ViewHolder(v, themeProvider)
override val layoutRes: Int
get() = R.layout.item_keyword
override val type: Int
get() = R.id.item_keyword
override fun bindView(holder: ViewHolder, payloads: List<Any>) {
super.bindView(holder, payloads)
holder.text.text = keyword
}
override fun unbindView(holder: ViewHolder) {
super.unbindView(holder)
holder.text.text = null
}
class ViewHolder(v: View, themeProvider: ThemeProvider) : RecyclerView.ViewHolder(v) {
val text: AppCompatTextView by bindView(R.id.keyword_text)
val delete: ImageView by bindView(R.id.keyword_delete)
init {
text.setTextColor(themeProvider.textColor)
delete.setImageDrawable(
GoogleMaterial.Icon.gmd_delete.keywordDrawable(itemView.context, themeProvider)
)
}
}
}
| gpl-3.0 | 0bb5eb03462cbd6b1d183f8f594fa07a | 34.218045 | 97 | 0.754697 | 4.333025 | false | false | false | false |
ronaldsmartin/20twenty20 | app/src/main/java/com/itsronald/twenty2020/settings/injection/SettingsModule.kt | 1 | 2265 | package com.itsronald.twenty2020.settings.injection
import android.support.design.widget.Snackbar
import com.f2prateek.rx.preferences.RxSharedPreferences
import com.itsronald.twenty2020.R
import com.itsronald.twenty2020.base.Activity
import com.itsronald.twenty2020.data.ResourceRepository
import com.itsronald.twenty2020.settings.SettingsContract
import com.itsronald.twenty2020.settings.SettingsPresenter
import com.itsronald.twenty2020.settings.SnackbarPermissionListener
import com.karumi.dexter.listener.single.PermissionListener
import com.karumi.dexter.listener.single.SnackbarOnDeniedPermissionListener
import dagger.Module
import dagger.Provides
import timber.log.Timber
@Module
class SettingsModule(private val view: SettingsContract.SettingsView) {
@Provides @Activity
fun provideSettingsView(): SettingsContract.SettingsView = view
@Provides @Activity
fun providePresenter(resources: ResourceRepository,
preferences: RxSharedPreferences): SettingsContract.Presenter =
SettingsPresenter(view, resources, preferences)
@Provides @Activity
fun provideSnackbarOnDeniedPermissionsListener(callback: Snackbar.Callback)
: SnackbarOnDeniedPermissionListener =
SnackbarOnDeniedPermissionListener.Builder
.with(view.contentView, R.string.location_permission_rationale)
.withOpenSettingsButton(R.string.settings)
.withCallback(callback)
.build()
@Provides @Activity
fun providePermissionsDeniedCallback(): Snackbar.Callback = object : Snackbar.Callback() {
override fun onShown(snackbar: Snackbar) {
super.onShown(snackbar)
// If the Snackbar is shown, the permission was denied.
// Un-check the setting that requires the permission.
Timber.w("Permission request was denied. Disabling automatic night mode.")
view.setPreferenceChecked(
prefKeyID = R.string.pref_key_display_location_based_night_mode,
checked = false
)
}
}
@Provides @Activity
fun providePermissionsListener(listener: SnackbarPermissionListener): PermissionListener = listener
} | gpl-3.0 | 16d766012c840cd24c2e5cd8f3b5ed8d | 40.962963 | 103 | 0.729801 | 5.022173 | false | false | false | false |
vsch/idea-multimarkdown | src/main/java/com/vladsch/md/nav/settings/api/MdExtendableSettingsImpl.kt | 1 | 4979 | // Copyright (c) 2015-2020 Vladimir Schneider <[email protected]> Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.vladsch.md.nav.settings.api
import com.vladsch.flexmark.util.data.DataKey
import com.vladsch.flexmark.util.data.MutableDataSet
import com.vladsch.md.nav.settings.TagItemHolder
import com.vladsch.md.nav.settings.UnwrappedSettings
class MdExtendableSettingsImpl : MdExtendableSettings, MdSettingsExtensionsHolder {
private val myExtensions = MutableDataSet()
private var myContainer: MdExtendableSettings = this
private val myExtensionPoints = LinkedHashMap<DataKey<out MdSettingsExtension<*>>, MdSettingsExtensionProvider<*>>()
private val myPendingExtensionNotifications = LinkedHashSet<DataKey<out MdSettingsExtension<*>>>()
companion object {
val settingsExtensionProviders: Array<MdSettingsExtensionProvider<*>> get() = MdSettingsExtensionProvider.EXTENSIONS.value
}
override fun initializeExtensions(container: MdExtendableSettings) {
myContainer = container
for (extensionProvider in settingsExtensionProviders) {
if (extensionProvider.isAvailableIn(container)) {
myExtensionPoints[extensionProvider.getKey()] = extensionProvider
}
}
}
override fun getExtensionPoints(): Collection<MdSettingsExtensionProvider<*>> {
return myExtensionPoints.values
}
override fun <T : MdSettingsExtension<T>> hasExtension(key: DataKey<T>): Boolean {
return myExtensions.contains(key)
}
override fun <T : MdSettingsExtension<T>> hasExtensionPoint(key: DataKey<T>): Boolean {
return myExtensionPoints.contains(key)
}
override fun <T : MdSettingsExtension<T>> notifySettingsChanged(key: DataKey<T>) {
key.get(myExtensions).notifySettingsChanged()
}
override fun <T : MdSettingsExtension<T>> pendingSettingsChanged(key: DataKey<T>) {
myPendingExtensionNotifications.add(key)
}
override fun notifyPendingSettingsChanged() {
myPendingExtensionNotifications.forEach {
it.get(myExtensions).notifySettingsChanged()
}
}
override fun getExtensions(): MutableDataSet = myExtensions
override fun getExtensionKeys(): Set<DataKey<MdSettingsExtension<*>>> {
@Suppress("UNCHECKED_CAST")
return myExtensionPoints.keys as Set<DataKey<MdSettingsExtension<*>>>
}
override fun getContainedExtensionKeys(): Set<DataKey<MdSettingsExtension<*>>> {
return myExtensions.keys.filterIsInstance<DataKey<MdSettingsExtension<*>>>().toSet()
}
fun <T : MdExtendableSettings> copyFrom(other: T) {
other.extensionKeys.forEach { key ->
if (!other.containedExtensionKeys.contains(key)) extensions.remove(key)
else key.get(extensions).copyFrom(other.extensions)
}
}
fun addItems(tagItemHolder: TagItemHolder): TagItemHolder {
extensionKeys.forEach { key ->
val extensionProvider = myExtensionPoints[key] ?: return@forEach
val savedBy = extensionProvider.isSavedBy(myContainer)
val loadedBy = extensionProvider.isLoadedBy(myContainer)
if (savedBy || loadedBy) {
key.get(myExtensions).addItems(!savedBy, tagItemHolder)
}
}
return tagItemHolder
}
fun addUnwrappedItems(tagItemHolder: TagItemHolder): TagItemHolder {
return addUnwrappedItems(myContainer, tagItemHolder)
}
override fun validateLoadedSettings() {
extensionKeys.forEach { key ->
val extension = key.get(myExtensions)
extension.validateLoadedSettings()
}
}
override fun addUnwrappedItems(container: Any, tagItemHolder: TagItemHolder): TagItemHolder {
extensionKeys.forEach { key ->
val extensionProvider = myExtensionPoints[key] ?: return@forEach
val savedBy = extensionProvider.isSavedBy(container)
val loadedBy = extensionProvider.isLoadedBy(container)
if (savedBy || loadedBy) {
val settings = key.get(myExtensions)
tagItemHolder.addItems(UnwrappedSettings<MdSettingsExtension<*>>(!savedBy, settings))
if (settings is MdExtendableSettings) {
settings.addUnwrappedItems(container, tagItemHolder)
}
}
}
return tagItemHolder
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other !is MdExtendableSettings) return false
extensionKeys.forEach {
if (it.get(myExtensions) != it.get(other.extensions)) return false
}
return true
}
override fun hashCode(): Int {
var result = 0
extensionKeys.forEach { result += 31 * result + it.get(myExtensions).hashCode() }
return result
}
}
| apache-2.0 | 64ef3ea7622ac97d308359b5b83978a8 | 37.596899 | 177 | 0.680257 | 4.959163 | false | false | false | false |
Fitbit/MvRx | todomvrx/src/main/java/com/airbnb/mvrx/todomvrx/util/SimpleCountingIdlingResource.kt | 1 | 2508 | /*
* Copyright 2017, The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.airbnb.mvrx.todomvrx.util
import androidx.test.espresso.IdlingResource
import java.util.concurrent.atomic.AtomicInteger
/**
* An simple counter implementation of [IdlingResource] that determines idleness by
* maintaining an internal counter. When the counter is 0 - it is considered to be idle, when it is
* non-zero it is not idle. This is very similar to the way a [java.util.concurrent.Semaphore]
* behaves.
*
*
* This class can then be used to wrap up operations that while in progress should block tests from
* accessing the UI.
*/
class SimpleCountingIdlingResource(private val resourceName: String) : IdlingResource {
private val counter = AtomicInteger(0)
// written from main thread, read from any thread.
@Volatile
private var resourceCallback: IdlingResource.ResourceCallback? = null
override fun getName() = resourceName
override fun isIdleNow() = counter.get() == 0
override fun registerIdleTransitionCallback(resourceCallback: IdlingResource.ResourceCallback) {
this.resourceCallback = resourceCallback
}
/**
* Increments the count of in-flight transactions to the resource being monitored.
*/
fun increment() {
counter.getAndIncrement()
}
/**
* Decrements the count of in-flight transactions to the resource being monitored.
* If this operation results in the counter falling below 0 - an exception is raised.
*
* @throws IllegalStateException if the counter is below 0.
*/
fun decrement() {
val counterVal = counter.decrementAndGet()
if (counterVal == 0) {
// we've gone from non-zero to zero. That means we're idle now! Tell espresso.
resourceCallback?.onTransitionToIdle()
} else if (counterVal < 0) {
throw IllegalArgumentException("Counter has been corrupted!")
}
}
}
| apache-2.0 | 944def020d6801b33e2451cae69cd27a | 34.828571 | 100 | 0.710925 | 4.679104 | false | false | false | false |
opengl-8080/kotlin-lifegame | src/main/kotlin/gl8080/lifegame/web/resource/GameResource.kt | 1 | 2027 | package gl8080.lifegame.web.resource
import gl8080.lifegame.application.NextStepService
import gl8080.lifegame.application.RegisterGameService
import gl8080.lifegame.application.RemoveGameService
import gl8080.lifegame.application.SearchGameService
import gl8080.lifegame.util.Maps
import javax.enterprise.context.ApplicationScoped
import javax.inject.Inject
import javax.ws.rs.*
import javax.ws.rs.core.MediaType
import javax.ws.rs.core.Response
import javax.ws.rs.core.UriBuilder
@Path("/game")
@ApplicationScoped
open class GameResource {
@Inject
lateinit private var registerService: RegisterGameService
@Inject
lateinit private var searchServie: SearchGameService
@Inject
lateinit private var nextService: NextStepService
@Inject
lateinit private var removeService: RemoveGameService
@POST
open fun register(@QueryParam("game-definition-id") gameDefinitionId: Long): Response {
val game = this.registerService.register(gameDefinitionId)
val id = game.getId()
val uri = UriBuilder
.fromResource(GameResource::class.java)
.path(GameResource::class.java, "search")
.build(id)
return Response
.created(uri)
.entity(Maps.map("id", id))
.build()
}
@GET
@Path("/{id}")
@Produces(MediaType.APPLICATION_JSON)
open fun search(@PathParam("id") id: Long): LifeGameDto {
val game = this.searchServie.search(id)
return LifeGameDto.of(game)
}
@POST
@Path("/{id}")
@Produces(MediaType.APPLICATION_JSON)
open fun next(@PathParam("id") id: Long): LifeGameDto {
val game = this.nextService.next(id)
return LifeGameDto.of(game)
}
@DELETE
@Path("/{id}")
open fun remove(@PathParam("id") id: Long): Response {
this.removeService.remove(id)
return Response.ok().build()
}
} | mit | 6f7610e39370138b3948b35ef6e2d0a0 | 29.215385 | 91 | 0.648249 | 4.119919 | false | false | false | false |
googlecodelabs/android-paging | basic/start/app/src/main/java/com/example/android/codelabs/paging/data/ArticleRepository.kt | 1 | 1378 | /*
* Copyright 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.android.codelabs.paging.data
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.flowOf
import java.time.LocalDateTime
private val firstArticleCreatedTime = LocalDateTime.now()
/**
* Repository class that mimics fetching [Article] instances from an asynchronous source.
*/
class ArticleRepository {
/**
* Exposed singular stream of [Article] instances
*/
val articleStream: Flow<List<Article>> = flowOf(
(0..500).map { number ->
Article(
id = number,
title = "Article $number",
description = "This describes article $number",
created = firstArticleCreatedTime.minusDays(number.toLong())
)
}
)
}
| apache-2.0 | e3ac9c28eb346b6b394b111c74f520d1 | 31.809524 | 89 | 0.685051 | 4.474026 | false | false | false | false |
infinum/android_dbinspector | dbinspector/src/main/kotlin/com/infinum/dbinspector/data/sources/local/cursor/shared/CursorSource.kt | 1 | 5853 | package com.infinum.dbinspector.data.sources.local.cursor.shared
import android.database.Cursor
import androidx.core.database.getBlobOrNull
import androidx.core.database.getFloatOrNull
import androidx.core.database.getIntOrNull
import androidx.core.database.getStringOrNull
import com.infinum.dbinspector.data.models.local.cursor.exceptions.CursorException
import com.infinum.dbinspector.data.models.local.cursor.exceptions.QueryException
import com.infinum.dbinspector.data.models.local.cursor.input.Query
import com.infinum.dbinspector.data.models.local.cursor.output.Field
import com.infinum.dbinspector.data.models.local.cursor.output.FieldType
import com.infinum.dbinspector.data.models.local.cursor.output.QueryResult
import com.infinum.dbinspector.data.models.local.cursor.output.Row
import com.infinum.dbinspector.data.models.local.proto.output.SettingsEntity
import com.infinum.dbinspector.data.sources.memory.pagination.Paginator
import com.infinum.dbinspector.extensions.lowercase
import kotlin.coroutines.resume
import kotlin.coroutines.resumeWithException
import kotlinx.coroutines.CancellableContinuation
internal open class CursorSource {
fun collectRows(
query: Query,
paginator: Paginator,
settings: SettingsEntity?,
filterPredicate: ((Field) -> Boolean) = { false },
continuation: CancellableContinuation<QueryResult>
) {
if (query.database?.isOpen == true) {
runQuery(query)?.use { cursor ->
paginator.setPageCount(
cursor.count,
query.pageSize
)
val boundary = paginator.boundary(
query.page,
query.pageSize,
cursor.count
)
val count = paginator.count(
boundary.startRow,
boundary.endRow,
cursor.count,
cursor.columnCount
)
val rows = iterateRowsInTable(cursor, boundary, settings, filterPredicate)
continuation.resume(
QueryResult(
rows = rows,
nextPage = paginator.nextPage(query.page),
beforeCount = count.beforeCount,
afterCount = count.afterCount
)
)
} ?: continuation.resumeWithException(CursorException())
} else {
continuation.resumeWithException(QueryException())
}
}
internal fun runQuery(query: Query): Cursor? =
query.database?.rawQuery(
query.statement,
null
)
private fun iterateRowsInTable(
cursor: Cursor,
boundary: Paginator.Boundary,
settings: SettingsEntity?,
filterPredicate: (Field) -> Boolean
): List<Row> =
if (cursor.moveToPosition(boundary.startRow)) {
(boundary.startRow until boundary.endRow).map { row ->
Row(
position = row,
fields = iterateFieldsInRow(
cursor,
settings ?: SettingsEntity.getDefaultInstance(),
filterPredicate
)
).also {
cursor.moveToNext()
}
}
} else {
listOf()
}
private fun iterateFieldsInRow(
cursor: Cursor,
settings: SettingsEntity,
filterPredicate: (Field) -> Boolean
): List<Field> =
(0 until cursor.columnCount).map { column ->
when (val type = FieldType(cursor.getType(column))) {
FieldType.NULL -> Field(
type = type,
text = FieldType.NULL.name.lowercase(),
linesCount = if (settings.linesLimit) settings.linesCount else Int.MAX_VALUE,
truncate = settings.truncateMode,
blobPreview = settings.blobPreview
)
FieldType.INTEGER -> Field(
type = type,
text = cursor.getIntOrNull(column)?.toString()
?: FieldType.NULL.name.lowercase(),
linesCount = if (settings.linesLimit) settings.linesCount else Int.MAX_VALUE,
truncate = settings.truncateMode,
blobPreview = settings.blobPreview
)
FieldType.FLOAT -> Field(
type = type,
text = cursor.getFloatOrNull(column)?.toString()
?: FieldType.NULL.name.lowercase(),
linesCount = if (settings.linesLimit) settings.linesCount else Int.MAX_VALUE,
truncate = settings.truncateMode,
blobPreview = settings.blobPreview
)
FieldType.STRING -> Field(
type = type,
text = cursor.getStringOrNull(column)
?: FieldType.NULL.name.lowercase(),
linesCount = if (settings.linesLimit) settings.linesCount else Int.MAX_VALUE,
truncate = settings.truncateMode,
blobPreview = settings.blobPreview
)
FieldType.BLOB -> Field(
type = type,
text = FieldType.NULL.name.lowercase(),
blob = cursor.getBlobOrNull(column),
linesCount = if (settings.linesLimit) settings.linesCount else Int.MAX_VALUE,
truncate = settings.truncateMode,
blobPreview = settings.blobPreview
)
}
}
.filterNot(filterPredicate)
}
| apache-2.0 | a1c13b24a16b9462dafbebbf7ecb4a44 | 39.365517 | 97 | 0.55903 | 5.542614 | false | false | false | false |
tokenbrowser/token-android-client | app/src/main/java/com/toshi/view/activity/AddCustomTokenActivity.kt | 1 | 6462 | /*
* Copyright (c) 2017. Toshi Inc
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.toshi.view.activity
import android.app.Activity
import android.arch.lifecycle.Observer
import android.content.Intent
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.view.MotionEvent
import com.toshi.R
import com.toshi.crypto.util.isPaymentAddressValid
import com.toshi.extensions.getViewModel
import com.toshi.extensions.isVisible
import com.toshi.extensions.safeToInt
import com.toshi.extensions.startActivityForResult
import com.toshi.extensions.toast
import com.toshi.model.network.token.CustomERCToken
import com.toshi.util.KeyboardUtil
import com.toshi.util.QrCodeHandler
import com.toshi.util.ScannerResultType
import com.toshi.view.adapter.listeners.TextChangedListener
import com.toshi.viewModel.AddCustomTokenViewModel
import kotlinx.android.synthetic.main.activity_add_custom_token.addTokenBtn
import kotlinx.android.synthetic.main.activity_add_custom_token.contractAddress
import kotlinx.android.synthetic.main.activity_add_custom_token.decimals
import kotlinx.android.synthetic.main.activity_add_custom_token.loadingOverlay
import kotlinx.android.synthetic.main.activity_add_custom_token.name
import kotlinx.android.synthetic.main.activity_add_custom_token.symbol
import kotlinx.android.synthetic.main.activity_chat.closeButton
class AddCustomTokenActivity : AppCompatActivity() {
companion object {
private const val PAYMENT_SCAN_REQUEST_CODE = 200
}
private lateinit var viewModel: AddCustomTokenViewModel
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_add_custom_token)
init()
}
private fun init() {
initViewModel()
initClickListeners()
initScannerClickListener()
initTextListeners()
initObservers()
}
private fun initViewModel() {
viewModel = getViewModel()
}
private fun initClickListeners() {
addTokenBtn.setOnClickListener { handleAddTokenBtnClicked() }
closeButton.setOnClickListener { hideKeyboardAndFinish() }
}
private fun handleAddTokenBtnClicked() {
KeyboardUtil.hideKeyboard(contractAddress)
viewModel.addCustomToken(buildCustomERCToken())
}
private fun buildCustomERCToken(): CustomERCToken {
val contractAddress: String = contractAddress.text.toString()
val name = name.text.toString()
val symbol = symbol.text.toString()
val decimals = decimals.text.toString().safeToInt()
return CustomERCToken(
contractAddress = contractAddress,
name = name,
symbol = symbol,
decimals = decimals
)
}
private fun hideKeyboardAndFinish() {
KeyboardUtil.hideKeyboard(contractAddress)
finish()
}
private fun initScannerClickListener() {
contractAddress.setOnTouchListener { _, event ->
if (event.action == MotionEvent.ACTION_UP) {
val rightDrawable = 2
val widthOfRightDrawable = contractAddress.compoundDrawables[rightDrawable].bounds.width()
if (event.rawX >= (contractAddress.right - widthOfRightDrawable)) {
startScanQrActivity()
return@setOnTouchListener true
}
}
return@setOnTouchListener false
}
}
private fun startScanQrActivity() = startActivityForResult<ScannerActivity>(PAYMENT_SCAN_REQUEST_CODE) {
putExtra(ScannerActivity.SCANNER_RESULT_TYPE, ScannerResultType.PAYMENT_ADDRESS)
}
private fun initTextListeners() {
contractAddress.addTextChangedListener(textListener)
name.addTextChangedListener(textListener)
symbol.addTextChangedListener(textListener)
decimals.addTextChangedListener(textListener)
}
private val textListener = object : TextChangedListener() {
override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
val isInputValid = isInputValid()
if (isInputValid) enableAddBtn()
else disableAddBtn()
}
}
private fun isInputValid(): Boolean {
val isContractAddressValid = isPaymentAddressValid(contractAddress.text.toString())
val isNameValid = name.text.isNotEmpty()
val isSymbolValid = symbol.text.isNotEmpty()
val isDecimalsValid = decimals.text.isNotEmpty()
return isContractAddressValid && isNameValid && isSymbolValid && isDecimalsValid
}
private fun enableAddBtn() {
addTokenBtn.isClickable = true
addTokenBtn.setBackgroundResource(R.drawable.background_with_radius_primary_color)
}
private fun disableAddBtn() {
addTokenBtn.isClickable = false
addTokenBtn.setBackgroundResource(R.drawable.background_with_radius_disabled)
}
private fun initObservers() {
viewModel.isLoading.observe(this, Observer {
if (it != null) loadingOverlay.isVisible(it)
})
viewModel.error.observe(this, Observer {
if (it != null) toast(it)
})
viewModel.success.observe(this, Observer {
if (it != null) toast(R.string.add_custom_token_success)
})
}
override fun onActivityResult(requestCode: Int, resultCode: Int, resultIntent: Intent?) {
super.onActivityResult(requestCode, resultCode, resultIntent)
if (requestCode != PAYMENT_SCAN_REQUEST_CODE || resultCode != Activity.RESULT_OK || resultIntent == null) return
val paymentAddress = resultIntent.getStringExtra(QrCodeHandler.ACTIVITY_RESULT)
contractAddress.setText(paymentAddress)
}
} | gpl-3.0 | 770e9183a110e3f6076219396d09e861 | 37.017647 | 120 | 0.703497 | 4.709913 | false | false | false | false |
fossasia/open-event-android | app/src/main/java/org/fossasia/openevent/general/auth/ProfileViewModel.kt | 1 | 5214 | package org.fossasia.openevent.general.auth
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import io.reactivex.disposables.CompositeDisposable
import io.reactivex.rxkotlin.plusAssign
import org.fossasia.openevent.general.R
import org.fossasia.openevent.general.common.SingleLiveEvent
import org.fossasia.openevent.general.data.Resource
import org.fossasia.openevent.general.utils.extensions.withDefaultSchedulers
import timber.log.Timber
class ProfileViewModel(
private val authService: AuthService,
private val resource: Resource
) : ViewModel() {
private val compositeDisposable = CompositeDisposable()
private val mutableProgress = MutableLiveData<Boolean>()
val progress: LiveData<Boolean> = mutableProgress
private val mutableUser = MutableLiveData<User>()
val user: LiveData<User> = mutableUser
private val mutableMessage = SingleLiveEvent<String>()
val message: SingleLiveEvent<String> = mutableMessage
private val mutableUpdatedUser = MutableLiveData<User>()
val updatedUser: LiveData<User> = mutableUpdatedUser
private val mutableUpdatedPassword = MutableLiveData<String>()
val updatedPassword: LiveData<String> = mutableUpdatedPassword
private val mutableAccountDeleted = MutableLiveData<Boolean>()
val accountDeleted: LiveData<Boolean> = mutableAccountDeleted
fun isLoggedIn() = authService.isLoggedIn()
fun logout() {
compositeDisposable += authService.logout()
.withDefaultSchedulers()
.subscribe({
Timber.d("Logged out!")
}) {
Timber.e(it, "Failure Logging out!")
}
}
fun deleteProfile() {
compositeDisposable += authService.deleteProfile()
.withDefaultSchedulers()
.doOnSubscribe {
mutableProgress.value = true
}.doFinally {
mutableProgress.value = false
}.subscribe({
mutableAccountDeleted.value = true
mutableMessage.value = resource.getString(R.string.success_deleting_account_message)
logout()
}, {
mutableAccountDeleted.value = false
mutableMessage.value = resource.getString(R.string.error_deleting_account_message)
})
}
fun changePassword(oldPassword: String, newPassword: String) {
compositeDisposable += authService.changePassword(oldPassword, newPassword)
.withDefaultSchedulers()
.subscribe({
if (it.passwordChanged) {
mutableMessage.value = resource.getString(R.string.change_password_success_message)
mutableUpdatedPassword.value = newPassword
}
}, {
if (it.message.toString() == "HTTP 400 BAD REQUEST")
mutableMessage.value = resource.getString(R.string.incorrect_old_password_message)
else mutableMessage.value = resource.getString(R.string.change_password_fail_message)
})
}
fun getProfile() {
compositeDisposable += authService.getProfile()
.withDefaultSchedulers()
.doOnSubscribe {
mutableProgress.value = true
}.doFinally {
mutableProgress.value = false
}.subscribe({ user ->
Timber.d("Response Success")
this.mutableUser.value = user
}) {
Timber.e(it, "Failure")
mutableMessage.value = resource.getString(R.string.failure)
}
}
fun syncProfile() {
compositeDisposable += authService.syncProfile()
.withDefaultSchedulers()
.subscribe({ user ->
Timber.d("Response Success")
this.mutableUpdatedUser.value = user
}) {
Timber.e(it, "Failure")
}
}
fun resendVerificationEmail(email: String) {
compositeDisposable += authService.resendVerificationEmail(email)
.withDefaultSchedulers()
.doOnSubscribe {
mutableProgress.value = true
}.doFinally {
mutableProgress.value = false
}.subscribe({
mutableMessage.value = it.message
}) {
Timber.e(it, "Failure")
mutableMessage.value = resource.getString(R.string.failure)
}
}
fun verifyProfile(token: String) {
compositeDisposable += authService.verifyEmail(token)
.withDefaultSchedulers()
.doOnSubscribe {
mutableProgress.value = true
}.doFinally {
mutableProgress.value = false
}.subscribe({
mutableMessage.value = it.message
syncProfile()
}) {
Timber.e(it, "Error in verifying email")
mutableMessage.value = resource.getString(R.string.verification_error_message)
}
}
override fun onCleared() {
super.onCleared()
compositeDisposable.clear()
}
}
| apache-2.0 | 217b19c90baf2518ac3b2129bdd3013c | 36.242857 | 103 | 0.612006 | 5.588424 | false | false | false | false |
LanternPowered/LanternServer | src/main/kotlin/org/lanternpowered/server/inventory/container/layout/RootDonkeyContainerLayout.kt | 1 | 5377 | /*
* Lantern
*
* Copyright (c) LanternPowered <https://www.lanternpowered.org>
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* This work is licensed under the terms of the MIT License (MIT). For
* a copy, see 'LICENSE.txt' or <https://opensource.org/licenses/MIT>.
*/
package org.lanternpowered.server.inventory.container.layout
import org.lanternpowered.api.entity.Entity
import org.lanternpowered.api.item.inventory.container.layout.ContainerSlot
import org.lanternpowered.api.item.inventory.container.layout.DonkeyContainerLayout
import org.lanternpowered.api.item.inventory.container.layout.GridContainerLayout
import org.lanternpowered.api.key.minecraftKey
import org.lanternpowered.api.text.translatableTextOf
import org.lanternpowered.server.entity.LanternEntity
import org.lanternpowered.server.network.entity.EntityProtocolTypes
import org.lanternpowered.server.network.entity.parameter.MutableParameterList
import org.lanternpowered.server.network.entity.vanilla.EntityNetworkIDs
import org.lanternpowered.server.network.entity.vanilla.EntityParameters
import org.lanternpowered.server.network.packet.Packet
import org.lanternpowered.server.network.value.PackedAngle
import org.lanternpowered.server.network.vanilla.packet.type.play.DestroyEntitiesPacket
import org.lanternpowered.server.network.vanilla.packet.type.play.EntityMetadataPacket
import org.lanternpowered.server.network.vanilla.packet.type.play.OpenHorseWindowPacket
import org.lanternpowered.server.network.vanilla.packet.type.play.SpawnMobPacket
import org.spongepowered.math.vector.Vector3d
import java.util.UUID
class RootDonkeyContainerLayout(val hasChest: Boolean) : LanternTopBottomContainerLayout<DonkeyContainerLayout>(
title = TITLE, slotFlags = if (hasChest) ALL_INVENTORY_FLAGS_WITH_CHEST else ALL_INVENTORY_FLAGS
) {
companion object {
private val TITLE = translatableTextOf("entity.minecraft.donkey")
private val EQUIPMENT_INVENTORY_FLAGS = intArrayOf(
Flags.REVERSE_SHIFT_INSERTION + Flags.POSSIBLY_DISABLED_SHIFT_INSERTION // Saddle slot
)
const val CHEST_WIDTH = 5
const val CHEST_HEIGHT = 3
private val CHEST_INVENTORY_FLAGS = IntArray(CHEST_WIDTH * CHEST_HEIGHT) { Flags.REVERSE_SHIFT_INSERTION }
private val TOP_INVENTORY_FLAGS = EQUIPMENT_INVENTORY_FLAGS + CHEST_INVENTORY_FLAGS
private val ALL_INVENTORY_FLAGS_WITH_CHEST = TOP_INVENTORY_FLAGS + MAIN_INVENTORY_FLAGS
private val ALL_INVENTORY_FLAGS = EQUIPMENT_INVENTORY_FLAGS + MAIN_INVENTORY_FLAGS
private val DONKEY_NETWORK_TYPE = EntityNetworkIDs.REGISTRY.require(minecraftKey("donkey"))
}
var entity: Entity? = null
override fun serverSlotIndexToClient(index: Int): Int {
if (index == 0)
return 0
// Insert client armor slot index
return index + 1
}
override fun clientSlotIndexToServer(index: Int): Int {
if (index == 0)
return 0
// Remove client armor slot index
return index - 1
}
// TODO: Changes to the entity must be tracked, because the entity
// may not even be visible to the given player at a given time,
// in that case we need to make it visible.
override fun createOpenPackets(data: ContainerData): List<Packet> {
val entity = this.entity
if (entity != null) {
entity as LanternEntity
val protocolType = entity.protocolType
if (protocolType == EntityProtocolTypes.DONKEY) {
val entityId = entity.world.entityProtocolManager.getProtocolId(entity)
return listOf(OpenHorseWindowPacket(data.containerId, TOP_INVENTORY_FLAGS.size + 1, entityId))
}
}
val entityId = Int.MAX_VALUE
// No entity was found, so create a fake one
val parameters = MutableParameterList()
parameters.add(EntityParameters.Base.FLAGS, EntityParameters.Base.Flags.IS_INVISIBLE.toByte())
parameters.add(EntityParameters.ChestedHorse.HAS_CHEST, this.hasChest)
val packets = mutableListOf<Packet>()
packets += SpawnMobPacket(entityId, UUID.randomUUID(), DONKEY_NETWORK_TYPE,
Vector3d.ZERO, PackedAngle.Zero, PackedAngle.Zero, PackedAngle.Zero, Vector3d.ZERO)
packets += EntityMetadataPacket(entityId, parameters)
packets += OpenHorseWindowPacket(data.containerId, TOP_INVENTORY_FLAGS.size + 1, entityId)
packets += DestroyEntitiesPacket(entityId)
return packets
}
override val top: DonkeyContainerLayout = SubDonkeyContainerLayout(0, TOP_INVENTORY_FLAGS.size, this)
}
private class SubDonkeyContainerLayout(
offset: Int, size: Int, private val root: RootDonkeyContainerLayout
) : SubContainerLayout(offset, size, root), DonkeyContainerLayout {
override var entity: Entity?
get() = this.root.entity
set(value) { this.root.entity = value }
override val saddle: ContainerSlot get() = this[0]
override val chest: GridContainerLayout =
if (this.root.hasChest) {
SubGridContainerLayout(1, RootDonkeyContainerLayout.CHEST_WIDTH, RootDonkeyContainerLayout.CHEST_HEIGHT, this.root)
} else {
SubGridContainerLayout(1, 0, 0, this.root)
}
}
| mit | 0a99d976fc5bd9ed32ea1ca5a32a9262 | 42.016 | 131 | 0.725683 | 4.308494 | false | false | false | false |
Kotlin/kotlinx.serialization | core/jvmTest/src/kotlinx/serialization/SerializeFlatTest.kt | 1 | 9175 | /*
* Copyright 2017-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license.
*/
package kotlinx.serialization
import kotlinx.serialization.descriptors.*
import kotlinx.serialization.encoding.*
import kotlinx.serialization.modules.*
import org.junit.Test
import kotlin.test.*
// Serializable data class
@Serializable
data class Data(
val value1: String,
val value2: Int
)
// Serializable data class with explicit companion object
@Serializable
data class DataExplicit(
val value1: String,
val value2: Int
) {
companion object
}
// Regular (non-data) class with var properties
@Serializable
class Reg {
var value1: String = ""
var value2: Int = 0
}
// Specify serializable names
@Serializable
data class Names(
@SerialName("value1")
val custom1: String,
@SerialName("value2")
val custom2: Int
)
// Custom serializer
@Serializable(with= CustomSerializer::class)
data class Custom(
val _value1: String,
val _value2: Int
)
@Suppress("NAME_SHADOWING")
object CustomSerializer : KSerializer<Custom> {
override val descriptor = object : SerialDescriptor {
override val serialName = "kotlinx.serialization.Custom"
override val kind: SerialKind = StructureKind.CLASS
override val elementsCount: Int get() = 2
override fun getElementName(index: Int) = when(index) {
0 -> "value1"
1 -> "value2"
else -> ""
}
override fun getElementIndex(name: String) = when(name) {
"value1" -> 0
"value2" -> 1
else -> -1
}
override fun getElementAnnotations(index: Int): List<Annotation> = emptyList()
override fun getElementDescriptor(index: Int): SerialDescriptor = fail("Should not be called")
override fun isElementOptional(index: Int): Boolean = false
}
override fun serialize(encoder: Encoder, value: Custom) {
val encoder = encoder.beginStructure(descriptor)
encoder.encodeStringElement(descriptor, 0, value._value1)
encoder.encodeIntElement(descriptor, 1, value._value2)
encoder.endStructure(descriptor)
}
override fun deserialize(decoder: Decoder): Custom {
val decoder = decoder.beginStructure(descriptor)
if (decoder.decodeElementIndex(descriptor) != 0) throw java.lang.IllegalStateException()
val value1 = decoder.decodeStringElement(descriptor, 0)
if (decoder.decodeElementIndex(descriptor) != 1) throw java.lang.IllegalStateException()
val value2 = decoder.decodeIntElement(descriptor, 1)
if (decoder.decodeElementIndex(descriptor) != CompositeDecoder.DECODE_DONE) throw java.lang.IllegalStateException()
decoder.endStructure(descriptor)
return Custom(value1, value2)
}
}
// External serializer
// not Serializable !!!
data class ExternalData(
val value1: String,
val value2: Int
)
@Serializer(forClass= ExternalData::class)
object ExternalSerializer
// --------- tests and utils ---------
class SerializeFlatTest() {
@Test
fun testData() {
val out = Out("Data")
out.encodeSerializableValue(serializer(), Data("s1", 42))
out.done()
val inp = Inp("Data")
val data = inp.decodeSerializableValue(serializer<Data>())
inp.done()
assert(data.value1 == "s1" && data.value2 == 42)
}
@Test
fun testDataExplicit() {
val out = Out("DataExplicit")
out.encodeSerializableValue(serializer(), DataExplicit("s1", 42))
out.done()
val inp = Inp("DataExplicit")
val data = inp.decodeSerializableValue(serializer<DataExplicit>())
inp.done()
assert(data.value1 == "s1" && data.value2 == 42)
}
@Test
fun testReg() {
val out = Out("Reg")
val reg = Reg()
reg.value1 = "s1"
reg.value2 = 42
out.encodeSerializableValue(serializer(), reg)
out.done()
val inp = Inp("Reg")
val data = inp.decodeSerializableValue(serializer<Reg>())
inp.done()
assert(data.value1 == "s1" && data.value2 == 42)
}
@Test
fun testNames() {
val out = Out("Names")
out.encodeSerializableValue(serializer(), Names("s1", 42))
out.done()
val inp = Inp("Names")
val data = inp.decodeSerializableValue(serializer<Names>())
inp.done()
assert(data.custom1 == "s1" && data.custom2 == 42)
}
@Test
fun testCustom() {
val out = Out("Custom")
out.encodeSerializableValue(CustomSerializer, Custom("s1", 42))
out.done()
val inp = Inp("Custom")
val data = inp.decodeSerializableValue(CustomSerializer)
inp.done()
assert(data._value1 == "s1" && data._value2 == 42)
}
@Test
fun testExternalData() {
val out = Out("ExternalData")
out.encodeSerializableValue(ExternalSerializer, ExternalData("s1", 42))
out.done()
val inp = Inp("ExternalData")
val data = inp.decodeSerializableValue(ExternalSerializer)
inp.done()
assert(data.value1 == "s1" && data.value2 == 42)
}
companion object {
fun fail(msg: String): Nothing = throw RuntimeException(msg)
fun checkDesc(name: String, desc: SerialDescriptor) {
if (desc.serialName != "kotlinx.serialization." + name) fail("checkDesc name $desc")
if (desc.kind != StructureKind.CLASS) fail("checkDesc kind ${desc.kind}")
if (desc.getElementName(0) != "value1") fail("checkDesc[0] $desc")
if (desc.getElementName(1) != "value2") fail("checkDesc[1] $desc")
}
}
class Out(private val name: String) : AbstractEncoder() {
var step = 0
override val serializersModule: SerializersModule = EmptySerializersModule()
override fun beginStructure(
descriptor: SerialDescriptor
): CompositeEncoder {
checkDesc(name, descriptor)
if (step == 0) step++ else fail("@$step: beginStructure($descriptor)")
return this
}
override fun encodeElement(descriptor: SerialDescriptor, index: Int): Boolean {
checkDesc(name, descriptor)
when (step) {
1 -> if (index == 0) {
step++
return true
}
3 -> if (index == 1) {
step++
return true
}
}
fail("@$step: encodeElement($descriptor, $index)")
}
override fun encodeString(value: String) {
when (step) {
2 -> if (value == "s1") {
step++
return
}
}
fail("@$step: encodeString($value)")
}
override fun encodeInt(value: Int) {
when (step) {
4 -> if (value == 42) {
step++
return
}
}
fail("@$step: decodeInt($value)")
}
override fun endStructure(descriptor: SerialDescriptor) {
checkDesc(name, descriptor)
if (step == 5) step++ else fail("@$step: endStructure($descriptor)")
}
fun done() {
if (step != 6) fail("@$step: OUT FAIL")
}
}
class Inp(private val name: String) : AbstractDecoder() {
var step = 0
override val serializersModule: SerializersModule = EmptySerializersModule()
override fun beginStructure(descriptor: SerialDescriptor): CompositeDecoder {
checkDesc(name, descriptor)
if (step == 0) step++ else fail("@$step: beginStructure($descriptor)")
return this
}
override fun decodeElementIndex(descriptor: SerialDescriptor): Int {
checkDesc(name, descriptor)
when (step) {
1 -> {
step++
return 0
}
3 -> {
step++
return 1
}
5 -> {
step++
return -1
}
}
fail("@$step: decodeElementIndex($descriptor)")
}
override fun decodeString(): String {
when (step) {
2 -> {
step++
return "s1"
}
}
fail("@$step: decodeString()")
}
override fun decodeInt(): Int {
when (step) {
4 -> {
step++
return 42
}
}
fail("@$step: decodeInt()")
}
override fun endStructure(descriptor: SerialDescriptor) {
checkDesc(name, descriptor)
if (step == 6) step++ else fail("@$step: endStructure($descriptor)")
}
fun done() {
if (step != 7) fail("@$step: INP FAIL")
}
}
}
| apache-2.0 | c5c4bf05fd2c3b0448b02af9c89ce0c0 | 28.126984 | 123 | 0.551717 | 4.557874 | false | true | false | false |
LanternPowered/LanternServer | src/main/kotlin/org/lanternpowered/api/data/Key.kt | 1 | 2610 | /*
* Lantern
*
* Copyright (c) LanternPowered <https://www.lanternpowered.org>
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* This work is licensed under the terms of the MIT License (MIT). For
* a copy, see 'LICENSE.txt' or <https://opensource.org/licenses/MIT>.
*/
package org.lanternpowered.api.data
import org.lanternpowered.api.key.NamespacedKey
import org.lanternpowered.api.util.type.typeTokenOf
import org.lanternpowered.api.registry.builderOf
import org.lanternpowered.api.registry.CatalogBuilder
import org.lanternpowered.api.util.type.TypeToken
import org.spongepowered.api.data.value.Value
typealias Key<V> = org.spongepowered.api.data.Key<V>
/**
* Constructs a new [Key] with the given [NamespacedKey] and value [TypeToken].
*/
fun <V : Value<*>> valueKeyOf(key: NamespacedKey, valueType: TypeToken<V>, fn: KeyBuilder<V>.() -> Unit = {}): Key<V> =
builderOf<KeyBuilder<V>>().key(key).type(valueType).requireExplicitRegistration().apply(fn).build()
/**
* Constructs a new [Key] with the given [NamespacedKey] and value type [V].
*/
inline fun <reified V : Value<*>> valueKeyOf(key: NamespacedKey, fn: KeyBuilder<V>.() -> Unit = {}): Key<V> =
builderOf<KeyBuilder<V>>().key(key).type(typeTokenOf<V>()).requireExplicitRegistration().apply(fn).build()
@Target(AnnotationTarget.TYPE, AnnotationTarget.CLASS)
@DslMarker
annotation class KeyBuilderDsl
/**
* A builder class for [Key]s.
*/
@KeyBuilderDsl
interface KeyBuilder<V : Value<*>> : CatalogBuilder<Key<V>, KeyBuilder<V>> {
/**
* Starter method for the builder. This defines the generics for the
* builder itself to provide the properly generified [Key].
*
* @param token The type token, preferably an anonymous
* @param <T> The element type of the Key
* @param <B> The base value type of the key
* @return This builder, generified
*/
fun <N : Value<*>> type(token: TypeToken<N>): KeyBuilder<N>
/**
* Sets the comparator of the bounded value [Key].
*/
fun <V : Value<E>, E : Any> KeyBuilder<V>.comparator(
comparator: @KeyBuilderDsl Comparator<in E>): KeyBuilder<V>
/**
* Sets the comparator of the bounded value [Key].
*/
fun <V : Value<E>, E : Any> KeyBuilder<V>.includesTester(
tester: @KeyBuilderDsl (E, E) -> Boolean): KeyBuilder<V>
/**
* Enables the requirement that the key is registered explicitly on a value collection.
*
* @return This builder, for chaining
*/
fun requireExplicitRegistration(): KeyBuilder<V>
}
| mit | f2eab2b7f318233479334545c3c2fe89 | 34.753425 | 119 | 0.684291 | 3.777135 | false | false | false | false |
SimonVT/cathode | cathode-common/src/main/java/net/simonvt/cathode/common/database/cursor.kt | 1 | 1153 | package net.simonvt.cathode.common.database
import android.database.Cursor
fun Cursor.getBlob(column: String): ByteArray = getBlob(this.getColumnIndexOrThrow(column))
fun Cursor.getDouble(column: String): Double = getDouble(this.getColumnIndexOrThrow(column))
fun Cursor.getFloat(column: String): Float = getFloat(this.getColumnIndexOrThrow(column))
fun Cursor.getInt(column: String): Int = getInt(getColumnIndexOrThrow(column))
fun Cursor.getLong(column: String): Long = getLong(getColumnIndexOrThrow(column))
fun Cursor.getLongOrNull(column: String): Long? {
val index = getColumnIndex(column)
if (index == -1 || isNull(index)) {
return null
}
return getLong(column)
}
fun Cursor.getString(column: String): String = getString(this.getColumnIndexOrThrow(column))
fun Cursor.getStringOrNull(column: String): String? {
val index = getColumnIndex(column)
if (index == -1 || isNull(index)) {
return null
}
return getString(column)
}
fun Cursor.getBoolean(column: String): Boolean = getInt(column) == 1
inline fun Cursor.forEach(action: (Cursor) -> Unit) {
moveToPosition(-1)
while (moveToNext()) {
action(this)
}
}
| apache-2.0 | 1f7c13a75078f9da5f41453be6595376 | 31.027778 | 92 | 0.743278 | 4.017422 | false | false | false | false |
zhufucdev/PCtoPE | app/src/main/java/com/zhufucdev/pctope/utils/JsonFormatTool.kt | 1 | 4751 | package com.zhufucdev.pctope.utils
/**
* 该类提供格式化JSON字符串的方法。
* 该类的方法formatJson将JSON字符串格式化,方便查看JSON数据。
*
* 例如:
*
* JSON字符串:["yht","xzj","zwy"]
*
* 格式化为:
*
* [
*
* "yht",
*
* "xzj",
*
* "zwy"
*
* ]
*
*
* 使用算法如下:
*
* 对输入字符串,追个字符的遍历
*
* 1、获取当前字符。
*
* 2、如果当前字符是前方括号、前花括号做如下处理:
*
* (1)如果前面还有字符,并且字符为“:”,打印:换行和缩进字符字符串。
*
* (2)打印:当前字符。
*
* (3)前方括号、前花括号,的后面必须换行。打印:换行。
*
* (4)每出现一次前方括号、前花括号;缩进次数增加一次。打印:新行缩进。
*
* (5)进行下一次循环。
*
* 3、如果当前字符是后方括号、后花括号做如下处理:
*
* (1)后方括号、后花括号,的前面必须换行。打印:换行。
*
* (2)每出现一次后方括号、后花括号;缩进次数减少一次。打印:缩进。
*
* (3)打印:当前字符。
*
* (4)如果当前字符后面还有字符,并且字符不为“,”,打印:换行。
*
* (5)继续下一次循环。
*
* 4、如果当前字符是逗号。逗号后面换行,并缩进,不改变缩进次数。
*
* 5、打印:当前字符。
*
* @author yanghaitao
* @version [版本号, 2014年9月29日]
*/
class JsonFormatTool {
/**
* 返回格式化JSON字符串。
*
* @param json 未格式化的JSON字符串。
* @return 格式化的JSON字符串。
*/
fun formatJson(json: String): String {
val result = StringBuffer()
val length = json.length
var number = 0
var key: Char = 0.toChar()
//遍历输入字符串。
for (i in 0..length - 1) {
//1、获取当前字符。
key = json[i]
//2、如果当前字符是前方括号、前花括号做如下处理:
if (key == '[' || key == '{') {
//(1)如果前面还有字符,并且字符为“:”,打印:换行和缩进字符字符串。
if (i - 1 > 0 && json[i - 1] == ':') {
result.append('\n')
result.append(indent(number))
}
//(2)打印:当前字符。
result.append(key)
//(3)前方括号、前花括号,的后面必须换行。打印:换行。
result.append('\n')
//(4)每出现一次前方括号、前花括号;缩进次数增加一次。打印:新行缩进。
number++
result.append(indent(number))
//(5)进行下一次循环。
continue
}
//3、如果当前字符是后方括号、后花括号做如下处理:
if (key == ']' || key == '}') {
//(1)后方括号、后花括号,的前面必须换行。打印:换行。
result.append('\n')
//(2)每出现一次后方括号、后花括号;缩进次数减少一次。打印:缩进。
number--
result.append(indent(number))
//(3)打印:当前字符。
result.append(key)
//(4)如果当前字符后面还有字符,并且字符不为“,”,打印:换行。
if (i + 1 < length && json[i + 1] != ',') {
result.append('\n')
}
//(5)继续下一次循环。
continue
}
//4、如果当前字符是逗号。逗号后面换行,并缩进,不改变缩进次数。
if (key == ',') {
result.append(key)
result.append('\n')
result.append(indent(number))
continue
}
//5、打印:当前字符。
result.append(key)
}
return result.toString()
}
/**
* 返回指定次数的缩进字符串。每一次缩进三个空格,即SPACE。
*
* @param number 缩进次数。
* @return 指定缩进次数的字符串。
*/
private fun indent(number: Int): String {
val result = StringBuffer()
for (i in 0..number - 1) {
result.append(SPACE)
}
return result.toString()
}
companion object {
/**
* 单位缩进字符串。
*/
private val SPACE = " "
}
} | gpl-3.0 | dae1d401245543f8fbc357ad68a51560 | 18.974843 | 59 | 0.439685 | 2.639235 | false | false | false | false |
hellenxu/AndroidAdvanced | CrashCases/app/src/main/java/six/ca/crashcases/fragment/data/MemoryDataSource.kt | 1 | 1919 | package six.ca.crashcases.fragment.data
import android.app.ActivityManager
import android.content.Context
import android.util.LruCache
import kotlin.math.roundToInt
/**
* @author hellenxu
* @date 2021-01-18
* Copyright 2021 Six. All rights reserved.
*/
object MemoryDataSource {
private var cachePercentage = 0.1
// private var m = 1024 * 1024f
private val lruCache: LruCache<String, String>
init {
val runtime = Runtime.getRuntime()
// val maxMemory = runtime.maxMemory() / m
// val freeMemory = runtime.freeMemory() / m
// val totalMemory = runtime.totalMemory() / m
// val actManager = appCtx.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
// println("xxl-memory11: per-app-memory-normal= ${actManager.memoryClass}; per-app-memory-large= ${actManager.largeMemoryClass}")
//
// val memoryInfo = ActivityManager.MemoryInfo()
// actManager.getMemoryInfo(memoryInfo)
// println("xxl-memory22: total= ${memoryInfo.totalMem / m}; available= ${memoryInfo.availMem / m}")
val availableMemory = runtime.maxMemory() - runtime.totalMemory() + runtime.freeMemory()
val cacheSize = availableMemory * cachePercentage
println("xxl-cache-size: $cacheSize")
lruCache = object: LruCache<String, String>(cacheSize.roundToInt()) {
override fun sizeOf(key: String?, value: String): Int {
val tmp = value.toByteArray().size
println("xxl-byte-array-size: $tmp")
return tmp
}
}
}
fun putCache(key: String, value: String) {
println("xxl-cache-put: $key; $value")
if (key.isBlank() || value.isBlank()) {
return
}
lruCache.put(key, value)
}
fun getCache(key: String): String? {
println("xxl-cache-get: $key")
return lruCache.get(key)
}
} | apache-2.0 | e2512d606092e4eda7a139fab0f724c3 | 29 | 137 | 0.632621 | 4.065678 | false | false | false | false |
mopsalarm/Pr0 | app/src/main/java/com/pr0gramm/app/ui/InterstitialAdler.kt | 1 | 2062 | package com.pr0gramm.app.ui
import android.app.Activity
import android.os.Handler
import android.os.Looper
import com.google.android.gms.ads.FullScreenContentCallback
import com.google.android.gms.ads.MobileAds
import com.google.android.gms.ads.interstitial.InterstitialAd
import com.pr0gramm.app.Logger
import com.pr0gramm.app.services.Track
import com.pr0gramm.app.util.Holder
import com.pr0gramm.app.util.di.injector
class InterstitialAdler(private val activity: Activity) {
private val logger = Logger("InterstitialAdler")
private val adService: AdService = activity.injector.instance()
private val handler = Handler(Looper.getMainLooper())
private var holder: Holder<InterstitialAd?> = adService.buildInterstitialAd(activity)
private val ad: InterstitialAd?
get() = holder.valueOrNull
fun runWithAd(block: () -> Unit) {
val ad = this.ad ?: return block()
if (!adService.shouldShowInterstitialAd()) {
logger.debug { "Ad is not loaded or not activated." }
return block()
}
adService.interstitialAdWasShown()
// schedule a handler in case the ad can not be shown
val onAdNotShown = Runnable {
logger.warn { "Watchdog timer hit, ad was not shown after calling 'show'." }
Track.adEvent("i_watchdog")
block()
}
// set watchdog timer for 1 second.
handler.postDelayed(onAdNotShown, 1000)
// show app
ad.setImmersiveMode(false)
// again, apply muted, just to be on the sure side
MobileAds.setAppVolume(0f)
MobileAds.setAppMuted(true)
ad.show(activity)
ad.fullScreenContentCallback = object : FullScreenContentCallback() {
override fun onAdShowedFullScreenContent() {
handler.removeCallbacks(onAdNotShown)
block()
// load a new ad
holder = adService.buildInterstitialAd(activity)
}
}
// always run block
block()
}
}
| mit | f55d1308e635e8968a16da1bb144be8b | 30.723077 | 89 | 0.655674 | 4.405983 | false | false | false | false |
i7c/cfm | server/recorder/src/main/kotlin/org/rliz/cfm/recorder/mbs/api/MbsRecordingViewRes.kt | 1 | 387 | package org.rliz.cfm.recorder.mbs.api
import java.util.UUID
data class MbsRecordingViewRes(
val id: UUID? = null,
val name: String? = null,
val length: Long? = null,
val artists: List<String> = emptyList()
)
data class MbsRecordingViewListRes(
val elements: List<MbsRecordingViewRes> = emptyList()
) {
fun toIdMap() = elements.map { it.id!! to it }.toMap()
}
| gpl-3.0 | 197031b712e67eea4d20d6c897861401 | 21.764706 | 58 | 0.677003 | 3.279661 | false | false | false | false |
FHannes/intellij-community | platform/credential-store/src/CredentialStoreWrapper.kt | 11 | 5187 | /*
* Copyright 2000-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.credentialStore
import com.intellij.ide.passwordSafe.PasswordStorage
import com.intellij.notification.NotificationGroup
import com.intellij.notification.NotificationType
import com.intellij.notification.SingletonNotificationManager
import com.intellij.openapi.application.ApplicationNamesInfo
import com.intellij.openapi.application.ex.ApplicationInfoEx
import com.intellij.openapi.diagnostic.runAndLogException
import com.intellij.openapi.util.SystemInfo
import com.intellij.util.SystemProperties
import com.intellij.util.concurrency.QueueProcessor
private val nullCredentials = Credentials("\u0000", OneTimeString("\u0000"))
private val NOTIFICATION_MANAGER by lazy {
// we use name "Password Safe" instead of "Credentials Store" because it was named so previously (and no much sense to rename it)
SingletonNotificationManager(NotificationGroup.balloonGroup("Password Safe"), NotificationType.WARNING, null)
}
private class CredentialStoreWrapper(private val store: CredentialStore) : PasswordStorage {
private val fallbackStore = lazy { KeePassCredentialStore(memoryOnly = true) }
private val queueProcessor = QueueProcessor<() -> Unit>({ it() })
private val postponedCredentials = KeePassCredentialStore(memoryOnly = true)
override fun get(attributes: CredentialAttributes): Credentials? {
postponedCredentials.get(attributes)?.let {
return if (it == nullCredentials) null else it
}
var store = if (fallbackStore.isInitialized()) fallbackStore.value else store
val requestor = attributes.requestor
val userName = attributes.userName
try {
val value = store.get(attributes)
if (value != null || requestor == null || userName == null) {
return value
}
}
catch (e: UnsatisfiedLinkError) {
store = fallbackStore.value
notifyUnsatisfiedLinkError(e)
return store.get(attributes)
}
catch (e: Throwable) {
LOG.error(e)
return null
}
LOG.runAndLogException {
fun setNew(oldKey: CredentialAttributes): Credentials? {
return store.get(oldKey)?.let {
set(oldKey, null)
// https://youtrack.jetbrains.com/issue/IDEA-160341
set(attributes, Credentials(userName, it.password?.clone(false, true)))
Credentials(userName, it.password)
}
}
// try old key - as hash
setNew(toOldKey(requestor, userName))?.let { return it }
val appInfo = ApplicationInfoEx.getInstanceEx()
if (appInfo.isEAP || appInfo.build.isSnapshot) {
setNew(CredentialAttributes(SERVICE_NAME_PREFIX, "${requestor.name}/$userName"))?.let { return it }
}
}
return null
}
override fun set(attributes: CredentialAttributes, credentials: Credentials?) {
fun doSave() {
var store = if (fallbackStore.isInitialized()) fallbackStore.value else store
try {
store.set(attributes, credentials)
}
catch (e: UnsatisfiedLinkError) {
store = fallbackStore.value
notifyUnsatisfiedLinkError(e)
store.set(attributes, credentials)
}
catch (e: Throwable) {
LOG.error(e)
}
postponedCredentials.set(attributes, null)
}
LOG.runAndLogException {
if (fallbackStore.isInitialized()) {
fallbackStore.value.set(attributes, credentials)
}
else {
postponedCredentials.set(attributes, credentials ?: nullCredentials)
queueProcessor.add { doSave() }
}
}
}
}
private fun notifyUnsatisfiedLinkError(e: UnsatisfiedLinkError) {
LOG.error(e)
var message = "Credentials are remembered until ${ApplicationNamesInfo.getInstance().fullProductName} is closed."
if (SystemInfo.isLinux) {
message += "\nPlease install required package libsecret-1-0: sudo apt-get install libsecret-1-0 gnome-keyring"
}
NOTIFICATION_MANAGER.notify("Cannot Access Native Keychain", message)
}
private class MacOsCredentialStoreFactory : CredentialStoreFactory {
override fun create(): PasswordStorage? {
if (isMacOsCredentialStoreSupported && SystemProperties.getBooleanProperty("use.mac.keychain", true)) {
return CredentialStoreWrapper(KeyChainCredentialStore())
}
return null
}
}
private class LinuxSecretCredentialStoreFactory : CredentialStoreFactory {
override fun create(): PasswordStorage? {
if (SystemInfo.isLinux && SystemProperties.getBooleanProperty("use.linux.keychain", true)) {
return CredentialStoreWrapper(SecretCredentialStore("com.intellij.credentialStore.Credential"))
}
return null
}
} | apache-2.0 | a09f0e25b333cbadab20a1b7b4d1e5bc | 35.027778 | 131 | 0.721612 | 4.63125 | false | false | false | false |
AgileVentures/MetPlus_resumeCruncher | core/src/main/kotlin/org/metplus/cruncher/rating/CrunchJobProcess.kt | 1 | 1466 | package org.metplus.cruncher.rating
import org.metplus.cruncher.job.Job
import org.metplus.cruncher.job.JobsRepository
import org.slf4j.LoggerFactory
open class CrunchJobProcess(
private val allCrunchers: CruncherList,
private val jobRepository: JobsRepository) : ProcessCruncher<Job>() {
private val logger = LoggerFactory.getLogger(CrunchJobProcess::class.java)
override fun process(work: Job) {
logger.trace("process({})", work)
val titleMetaData: MutableMap<String, CruncherMetaData> = work.titleMetaData.toMutableMap()
val descriptionMetaData: MutableMap<String, CruncherMetaData> = work.descriptionMetaData.toMutableMap()
allCrunchers.getCrunchers().forEach {
try {
titleMetaData[it.getCruncherName()] = it.crunch(work.title)
} catch (exp: Exception) {
logger.warn("Error crunching the title of job: ${work.id}: $exp")
exp.printStackTrace()
}
try {
descriptionMetaData[it.getCruncherName()] = it.crunch(work.description)
} catch (exp: Exception) {
logger.warn("Error crunching the description of job: ${work.id}: $exp")
exp.printStackTrace()
}
}
jobRepository.save(work.copy(titleMetaData = titleMetaData, descriptionMetaData = descriptionMetaData))
logger.debug("Job [$work] processed successfully")
}
} | gpl-3.0 | bf26669761f640cc2aa8b5d8377f2235 | 42.147059 | 111 | 0.653479 | 4.510769 | false | false | false | false |
clappr/clappr-android | clappr/src/test/kotlin/io/clappr/player/playback/VideoResolutionChangeListenerTest.kt | 1 | 1276 | package io.clappr.player.playback
import androidx.test.core.app.ApplicationProvider
import io.clappr.player.base.BaseObject
import io.clappr.player.base.Options
import io.clappr.player.components.Playback
import io.clappr.player.playback.ExoPlayerPlayback.Companion.supportsSource
import org.junit.Assert.*
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
@RunWith(RobolectricTestRunner::class)
class VideoResolutionChangeListenerTest {
@Before
fun setUp() {
BaseObject.applicationContext = ApplicationProvider.getApplicationContext()
}
@Test
fun `should trigger VIDEO_RESOLUTION_CHANGED on playback`() {
val playback = DummyPlayback()
val listener = VideoResolutionChangeListener(playback)
var width = 0
var height = 0
playback.on("didUpdateVideoResolution") {
width = it?.getInt("width") ?: 0
height = it?.getInt("height") ?: 0
}
listener.onVideoSizeChanged(null, 1280, 720, 0, 0.0f)
assertEquals(1280, width)
assertEquals(720, height)
}
class DummyPlayback : Playback("some-source", null, Options(), "ExoPlayerVideoSizeListenerTestPlayback", supportsSource)
} | bsd-3-clause | ef94f5706daf0b4e71ad136b74fde355 | 30.146341 | 124 | 0.722571 | 4.477193 | false | true | false | false |
ken-kentan/student-portal-plus | app/src/main/java/jp/kentan/studentportalplus/view/widget/CustomTabsTextView.kt | 1 | 2551 | package jp.kentan.studentportalplus.view.widget
import android.content.Context
import android.util.AttributeSet
import androidx.appcompat.widget.AppCompatTextView
import androidx.core.text.parseAsHtml
import jp.kentan.studentportalplus.R
import jp.kentan.studentportalplus.view.text.LinkTransformationMethod
import java.util.regex.Pattern
class CustomTabsTextView @JvmOverloads constructor(
context: Context,
attrs: AttributeSet? = null,
defStyleAttr: Int = android.R.attr.textViewStyle
) : AppCompatTextView(context, attrs, defStyleAttr) {
private companion object {
/**
* Support custom SPAN class
* https://portal.student.kit.ac.jp/css/common/wb_common.css
*/
val HTML_TAGS by lazy(LazyThreadSafetyMode.NONE) {
mapOf<Pattern, String>(
Pattern.compile("<span class=\"col_red\">(.*?)</span>") to "<font color=\"#ff0000\">\$1</font>",
Pattern.compile("<span class=\"col_green\">(.*?)</span>") to "<font color=\"#008000\">\$1</font>",
Pattern.compile("<span class=\"col_blue\">(.*?)</span>") to "<font color=\"#0000ff\">\$1</font>",
Pattern.compile("<span class=\"col_orange\">(.*?)</span>") to "<font color=\"#ffa500\">\$1</font>",
Pattern.compile("<span class=\"col_white\">(.*?)</span>") to "<font color=\"#ffffff\">\$1</font>",
Pattern.compile("<span class=\"col_black\">(.*?)</span>") to "<font color=\"#000000\">\$1</font>",
Pattern.compile("<span class=\"col_gray\">(.*?)</span>") to "<font color=\"#999999\">\$1</font>",
Pattern.compile("<a href=\"(.*?)\"(.*?)\">(.*?)</a>") to "\$3( \$1 )",
Pattern.compile("<span class=\"u_line\">(.*?)</span>") to "<u>\$1</u>",
Pattern.compile("([A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}?)") to " \$1 "
)
}
}
init {
context.obtainStyledAttributes(attrs, R.styleable.CustomTabsTextView, defStyleAttr, 0).apply {
setHtml(getString(R.styleable.CustomTabsTextView_html))
recycle()
}
transformationMethod = LinkTransformationMethod(context)
}
fun setHtml(html: String?) {
var htmlText = html ?: run {
text = null
return
}
HTML_TAGS.forEach { (pattern, span) ->
htmlText = pattern.matcher(htmlText).replaceAll(span)
}
text = htmlText.parseAsHtml()
}
} | gpl-3.0 | 9c9cb9622f57b1e59bf95e7bd569027e | 41.533333 | 119 | 0.562525 | 4.049206 | false | false | false | false |
dafi/photoshelf | core/src/main/java/com/ternaryop/photoshelf/util/ListExt.kt | 1 | 512 | package com.ternaryop.photoshelf.util
fun <T> List<T>.near(startIndex: Int, distance: Int): List<T> {
val leftLower = 0.coerceAtLeast(startIndex - distance)
val leftUpper = startIndex - 1
val sublist = mutableListOf<T>()
for (i in leftLower..leftUpper) {
sublist.add(this[i])
}
val rightLower = startIndex + 1
val rightUpper = (startIndex + distance).coerceAtMost(size - 1)
for (i in rightLower..rightUpper) {
sublist.add(this[i])
}
return sublist
}
| mit | 15c1e4cc42486eda5f02c2867d0521cf | 23.380952 | 67 | 0.646484 | 3.710145 | false | false | false | false |
noripi/querydsl-sample | src/main/kotlin/io/github/noripi/querydsl_sample/db/QueryDslSample.kt | 1 | 2839 | /**
* The MIT License (MIT)
*
* Copyright (c) 2017 Noriyuki Ishida
*
* 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 io.github.noripi.querydsl_sample.db
import com.mysql.jdbc.jdbc2.optional.MysqlDataSource
import com.querydsl.core.Tuple
import com.querydsl.sql.Configuration
import com.querydsl.sql.MySQLTemplates
import com.querydsl.sql.SQLQueryFactory
import io.github.noripi.querydsl_sample.extension.COLUMNS
import io.github.noripi.querydsl_sample.extension.INSERT_INTO
import io.github.noripi.querydsl_sample.extension.ON_DUPLICATE_KEY_UPDATE
import io.github.noripi.querydsl_sample.extension.VALUES
import io.github.noripi.querydsl_sample.obj.Restaurant
import io.github.noripi.querydsl_sample.query.QRestaurant
private val r = QRestaurant("r")
object QueryDslSample {
private val factory = SQLQueryFactory(Configuration(MySQLTemplates()),
MysqlDataSource().apply {
this.setUrl("jdbc:mysql://localhost:3306/test")
this.setUser(DB_USER)
this.setPassword(DB_PASS)
})
fun getRestaurant(id: Int): Restaurant? {
val result: Tuple? = factory.select(r.restaurantId, r.restaurantName)
.from(r)
.where(r.restaurantId.eq(id))
.limit(1)
.fetchOne()
return result?.toRestaurant()
}
fun insertOrReplaceRestaurant(id: Int, name: String) {
(factory
INSERT_INTO r
COLUMNS arrayOf(r.restaurantId, r.restaurantName)
VALUES arrayOf(id, name)
ON_DUPLICATE_KEY_UPDATE r.restaurantName.eq(name)
).execute()
}
}
private fun Tuple.toRestaurant(): Restaurant = Restaurant(
id = this.get(r.restaurantId)!!,
name = this.get(r.restaurantName)!!
) | mit | 1b66f05047801d74cca5e208c57e6d6d | 39 | 80 | 0.706235 | 4.126453 | false | false | false | false |
chibatching/Kotpref | kotpref/src/test/java/com/chibatching/kotpref/pref/BooleanPrefTest.kt | 1 | 2252 | package com.chibatching.kotpref.pref
import android.content.Context
import com.chibatching.kotpref.R
import com.google.common.truth.Truth.assertThat
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.ParameterizedRobolectricTestRunner
import java.util.Arrays
@RunWith(ParameterizedRobolectricTestRunner::class)
internal class BooleanPrefTest(commitAllProperties: Boolean) : BasePrefTest(commitAllProperties) {
companion object {
@JvmStatic
@ParameterizedRobolectricTestRunner.Parameters(name = "commitAllProperties = {0}")
fun data(): Collection<Array<out Any>> {
return Arrays.asList(arrayOf(false), arrayOf(true))
}
}
@Test
fun booleanPrefDefaultIsFalse() {
assertThat(example.testBoolean).isEqualTo(false)
}
@Test
fun setValueToPreference() {
example.testBoolean = false
assertThat(example.testBoolean)
.isEqualTo(false)
assertThat(example.testBoolean)
.isEqualTo(examplePref.getBoolean("testBoolean", false))
}
@Test
fun customDefaultValue() {
assertThat(customExample.testBoolean).isEqualTo(true)
}
@Test
fun useCustomPreferenceKey() {
customExample.testBoolean = false
assertThat(customExample.testBoolean)
.isEqualTo(false)
assertThat(customExample.testBoolean)
.isEqualTo(
customPref.getBoolean(
context.getString(R.string.test_custom_boolean),
false
)
)
}
@Test
fun readFromOtherPreferenceInstance() {
val otherPreference =
context.getSharedPreferences(example.kotprefName, Context.MODE_PRIVATE)
example.testBoolean = true
assertThat(otherPreference.getBoolean("testBoolean", false))
.isTrue()
}
@Test
fun writeFromOtherPreferenceInstance() {
val otherPreference =
context.getSharedPreferences(example.kotprefName, Context.MODE_PRIVATE)
example.testBoolean
otherPreference.edit()
.putBoolean("testBoolean", true)
.commit()
assertThat(example.testBoolean).isTrue()
}
}
| apache-2.0 | 52952ac3245928941b5835b2f5b9551b | 27.871795 | 98 | 0.659414 | 5.083521 | false | true | false | false |
rsiebert/TVHClient | app/src/main/java/org/tvheadend/tvhclient/ui/common/MenuDialogs.kt | 1 | 10159 | package org.tvheadend.tvhclient.ui.common
import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.databinding.DataBindingUtil
import androidx.databinding.ViewDataBinding
import androidx.preference.PreferenceManager
import androidx.recyclerview.widget.RecyclerView
import com.afollestad.materialdialogs.MaterialDialog
import com.afollestad.materialdialogs.callbacks.onDismiss
import com.afollestad.materialdialogs.list.customListAdapter
import com.afollestad.materialdialogs.list.listItemsSingleChoice
import org.tvheadend.data.entity.ChannelTag
import org.tvheadend.tvhclient.BR
import org.tvheadend.tvhclient.R
import org.tvheadend.tvhclient.databinding.GenreColorListAdapterBinding
import org.tvheadend.tvhclient.ui.common.interfaces.ChannelTagIdsSelectedInterface
import org.tvheadend.tvhclient.ui.common.interfaces.ChannelTimeSelectedInterface
import timber.log.Timber
import java.text.SimpleDateFormat
import java.util.*
fun showChannelTagSelectionDialog(context: Context, channelTags: MutableList<ChannelTag>, channelCount: Int, callback: ChannelTagIdsSelectedInterface): Boolean {
val isMultipleChoice = PreferenceManager.getDefaultSharedPreferences(context).getBoolean("multiple_channel_tags_enabled",
context.resources.getBoolean(R.bool.pref_default_multiple_channel_tags_enabled))
// Create a default tag (All channels)
if (!isMultipleChoice) {
val tag = ChannelTag()
tag.tagId = 0
tag.tagName = context.getString(R.string.all_channels)
tag.channelCount = channelCount
var allChannelsSelected = true
for (channelTag in channelTags) {
if (channelTag.isSelected) {
allChannelsSelected = false
break
}
}
tag.isSelected = allChannelsSelected
channelTags.add(0, tag)
}
val adapter = ChannelTagSelectionAdapter(channelTags, isMultipleChoice)
// Show the dialog that shows all available channel tags. When the
// user has selected a tag, restart the loader to loadRecordingById the updated channel list
val dialog: MaterialDialog = MaterialDialog(context)
.title(R.string.filter_channel_list)
.customListAdapter(adapter)
if (isMultipleChoice) {
dialog.title(R.string.select_multiple_channel_tags)
.positiveButton(R.string.save) { callback.onChannelTagIdsSelected(adapter.selectedTagIds) }
} else {
dialog.onDismiss { callback.onChannelTagIdsSelected(adapter.selectedTagIds) }
}
adapter.setCallback(dialog)
dialog.show()
return true
}
class ChannelTagSelectionAdapter(private val channelTagList: List<ChannelTag>, private val isMultiChoice: Boolean) : RecyclerView.Adapter<ChannelTagSelectionAdapter.ViewHolder>() {
private val selectedChannelTagIds: MutableSet<Int>
private lateinit var dialog: MaterialDialog
internal val selectedTagIds: Set<Int>
get() = selectedChannelTagIds
init {
this.selectedChannelTagIds = HashSet()
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val layoutInflater = LayoutInflater.from(parent.context)
val binding = DataBindingUtil.inflate<ViewDataBinding>(layoutInflater, viewType, parent, false)
val sharedPreferences = PreferenceManager.getDefaultSharedPreferences(parent.context)
val showChannelTagIcons = sharedPreferences.getBoolean("channel_tag_icons_enabled",
parent.context.resources.getBoolean(R.bool.pref_default_channel_tag_icons_enabled))
return ViewHolder(binding, showChannelTagIcons, this)
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
if (channelTagList.size > position) {
val channelTag = channelTagList[position]
holder.bind(channelTag, position)
if (channelTag.isSelected) {
selectedChannelTagIds.add(channelTag.tagId)
}
}
}
override fun getItemCount(): Int {
return channelTagList.size
}
override fun getItemViewType(position: Int): Int {
return if (isMultiChoice) R.layout.channeltag_list_multiple_choice_adapter else R.layout.channeltag_list_single_choice_adapter
}
fun setCallback(dialog: MaterialDialog) {
this.dialog = dialog
}
fun onChecked(@Suppress("UNUSED_PARAMETER") view: View, position: Int, isChecked: Boolean) {
val tagId = channelTagList[position].tagId
if (isChecked) {
selectedChannelTagIds.add(tagId)
} else {
selectedChannelTagIds.remove(tagId)
}
}
fun onSelected(position: Int) {
val tagId = channelTagList[position].tagId
selectedChannelTagIds.clear()
if (position != 0) {
selectedChannelTagIds.add(tagId)
}
dialog.dismiss()
}
class ViewHolder(private val binding: ViewDataBinding, private val showChannelTagIcons: Boolean, private val callback: ChannelTagSelectionAdapter) : RecyclerView.ViewHolder(binding.root) {
fun bind(channelTag: ChannelTag, position: Int) {
binding.setVariable(BR.channelTag, channelTag)
binding.setVariable(BR.position, position)
binding.setVariable(BR.callback, callback)
binding.setVariable(BR.showChannelTagIcons, showChannelTagIcons)
}
}
}
/**
* Prepares a dialog that shows the available genre colors and the names. In
* here the data for the adapter is created and the dialog prepared which
* can be shown later.
*/
fun showGenreColorDialog(context: Context): Boolean {
val adapter = GenreColorListAdapter(context.resources.getStringArray(R.array.pr_content_type0))
MaterialDialog(context).show {
title(R.string.genre_color_list)
customListAdapter(adapter)
}
return true
}
class GenreColorListAdapter internal constructor(private val contentInfo: Array<String>) : RecyclerView.Adapter<GenreColorListAdapter.ViewHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val layoutInflater = LayoutInflater.from(parent.context)
val itemBinding = GenreColorListAdapterBinding.inflate(layoutInflater, parent, false)
return ViewHolder(itemBinding)
}
override fun getItemCount(): Int {
return contentInfo.size
}
/**
* Applies the values to the available layout items
*/
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
holder.bind((position + 1) * 16, contentInfo[position])
}
// Provide a reference to the views for each data item
// Complex data items may need more than one view per item, and
// you provide access to all the views for a data item in a view holder
class ViewHolder(private val binding: GenreColorListAdapterBinding) : RecyclerView.ViewHolder(binding.root) {
fun bind(contentType: Int, contentName: String) {
binding.contentType = contentType
binding.contentName = contentName
}
}
}
fun showProgramTimeframeSelectionDialog(context: Context, currentSelection: Int, intervalInHours: Int, maxIntervalsToShow: Int, callback: ChannelTimeSelectedInterface?): MaterialDialog {
val startDateFormat = SimpleDateFormat("dd.MM.yyyy - HH:00", Locale.US)
val endDateFormat = SimpleDateFormat("HH:00", Locale.US)
val times = ArrayList<String>()
times.add(context.getString(R.string.current_time))
// Set the time that shall be shown next in the dialog. This is the
// current time plus the value of the intervalInHours in milliseconds
var timeInMillis = System.currentTimeMillis() + 1000 * 60 * 60 * intervalInHours
// Add the date and time to the list. Remove Increase the time in
// milliseconds for each iteration by the defined intervalInHours
for (i in 1 until maxIntervalsToShow) {
val startTime = startDateFormat.format(timeInMillis)
timeInMillis += (1000 * 60 * 60 * intervalInHours).toLong()
val endTime = endDateFormat.format(timeInMillis)
times.add("$startTime - $endTime")
}
val dialog = MaterialDialog(context)
dialog.show {
title(R.string.select_time)
listItemsSingleChoice(items = times, initialSelection = currentSelection) { _, index, _ ->
callback?.onTimeSelected(index)
}
}
return dialog
}
fun showChannelSortOrderSelectionDialog(context: Context): Boolean {
val channelSortOrder = Integer.valueOf(PreferenceManager.getDefaultSharedPreferences(context).getString("channel_sort_order", context.resources.getString(R.string.pref_default_channel_sort_order))!!)
MaterialDialog(context).show {
title(R.string.pref_sort_channels)
listItemsSingleChoice(R.array.pref_sort_channels_names, initialSelection = channelSortOrder) { _, index, _ ->
Timber.d("New selected channel sort order changed from $channelSortOrder to $index")
val editor = PreferenceManager.getDefaultSharedPreferences(context).edit()
editor.putString("channel_sort_order", index.toString())
editor.apply()
}
}
return false
}
fun showCompletedRecordingSortOrderSelectionDialog(context: Context): Boolean {
val sortOrder = Integer.valueOf(PreferenceManager.getDefaultSharedPreferences(context).getString("completed_recording_sort_order", context.resources.getString(R.string.pref_default_completed_recording_sort_order))!!)
MaterialDialog(context).show {
title(R.string.pref_sort_completed_recordings)
listItemsSingleChoice(R.array.pref_sort_completed_recordings_names, initialSelection = sortOrder) { _, index, _ ->
Timber.d("New selected completed recording sort order changed from $sortOrder to $index")
val editor = PreferenceManager.getDefaultSharedPreferences(context).edit()
editor.putString("completed_recording_sort_order", index.toString())
editor.apply()
}
}
return false
} | gpl-3.0 | d199cd45ade835a2c4236b6b7e804499 | 40.133603 | 220 | 0.717689 | 4.744979 | false | false | false | false |
mibac138/ArgParser | binder/src/main/kotlin/com/github/mibac138/argparser/binder/SyntaxGeneratorContainer.kt | 1 | 3142 | /*
* Copyright (c) 2017 Michał Bączkowski
*
* 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.github.mibac138.argparser.binder
import com.github.mibac138.argparser.syntax.dsl.SyntaxElementDSL
import org.jetbrains.annotations.Contract
import kotlin.reflect.KParameter
/**
* Syntax generator consisting of other generators. Does nothing on it's own.
* When running [generate] it invokes all of the added [generators].
*/
class SyntaxGeneratorContainer() : SyntaxGenerator {
private val generators = mutableListOf<SyntaxGenerator>()
constructor(generators: Iterable<SyntaxGenerator>) : this() {
this.generators += generators
}
constructor(vararg generators: SyntaxGenerator) : this() {
this.generators += generators
}
fun clear()
= this.generators.clear()
override fun generate(dsl: SyntaxElementDSL, param: KParameter) {
for (generator in generators)
generator.generate(dsl, param)
}
@Contract(pure = true)
@JvmName("concat")
operator fun plus(generator: SyntaxGenerator): SyntaxGeneratorContainer
= SyntaxGeneratorContainer(this, generator)
@Contract(pure = true)
@JvmName("deconcat") /* https://english.stackexchange.com/a/53821/251410 */
operator fun minus(generator: SyntaxGenerator): SyntaxGeneratorContainer
= SyntaxGeneratorContainer(generators.except(generator))
@JvmName("add")
operator fun plusAssign(generator: SyntaxGenerator) {
this.generators.add(generator)
}
@JvmName("addAll")
operator fun plusAssign(generators: Iterable<SyntaxGenerator>) {
this.generators.addAll(generators)
}
@JvmName("remove")
operator fun minusAssign(generator: SyntaxGenerator) {
this.generators.remove(generator)
}
@JvmName("removeAll")
operator fun minusAssign(generators: Iterable<SyntaxGenerator>) {
this.generators.removeAll(generators)
}
private fun <T> List<T>.except(element: T): List<T>
= this.filterTo(ArrayList(((size - 1) / 0.75).toInt()), { it != element })
} | mit | ceffb53065d96b26775596bdb7c19795 | 36.392857 | 86 | 0.717834 | 4.563953 | false | false | false | false |
isuPatches/WiseFy | wisefy/src/main/java/com/isupatches/wisefy/WiseFyPrechecks.kt | 1 | 22520 | /*
* Copyright 2019 Patches Klinefelter
*
* 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.isupatches.wisefy
import android.Manifest.permission.ACCESS_FINE_LOCATION
import androidx.annotation.RequiresPermission
import com.isupatches.wisefy.constants.DEFAULT_PRECHECK_RETURN_CODE
import com.isupatches.wisefy.constants.MISSING_PARAMETER
import com.isupatches.wisefy.constants.NETWORK_ALREADY_CONFIGURED
import com.isupatches.wisefy.constants.WiseFyCode
import com.isupatches.wisefy.search.WiseFySearch
/**
* A helper class with methods to determine if the necessary requirements are met to preform operations.
*
* @see [WiseFyPrechecks]
* @see [WiseFySearch]
*
* @author Patches
* @since 3.0
*/
internal class WiseFyPrechecksImpl private constructor(
private val wisefySearch: WiseFySearch
) : WiseFyPrechecks {
/**
* Used internally to make sure perquisites for adding a network as a saved configuration are met.
*
* @param ssid The ssid param from [com.isupatches.wisefy.WiseFy.addOpenNetwork]
*
* @return PrecheckResult - [DEFAULT_PRECHECK_RESULT] or a [PrecheckResult] with an error code.
*
* @see [checkAddNetworkPrerequisites]
* @see [com.isupatches.wisefy.WiseFy.addOpenNetwork]
*
* @author Patches
* @since 3.0
*/
@RequiresPermission(ACCESS_FINE_LOCATION)
override fun addNetworkPrechecks(ssid: String?): PrecheckResult =
checkAddNetworkPrerequisites(ssid)
/**
* Used internally to make sure perquisites for adding a network as a saved configuration are met.
*
* @param ssid The ssid param from [com.isupatches.wisefy.WiseFy.addWEPNetwork] or
* [com.isupatches.wisefy.WiseFy.addWPA2Network]
* @param password The password from [com.isupatches.wisefy.WiseFy.addWEPNetwork] or
* [com.isupatches.wisefy.WiseFy.addWPA2Network]
*
* @return PrecheckResult - [DEFAULT_PRECHECK_RESULT] or a [PrecheckResult] with an error code.
*
* @see [checkAddNetworkPrerequisites]
* @see [com.isupatches.wisefy.WiseFy.addWEPNetwork]
* @see [com.isupatches.wisefy.WiseFy.addWPA2Network]
*
* @author Patches
* @since 3.0
*/
@RequiresPermission(ACCESS_FINE_LOCATION)
override fun addNetworkPrechecks(ssid: String?, password: String?): PrecheckResult =
checkAddNetworkPrerequisites(ssid, password)
/**
* Used internally to make sure perquisites for connecting to a network are met.
*
* @param ssidToConnectTo The ssidToConnectTo param from [com.isupatches.wisefy.WiseFy.connectToNetwork]
*
* @return PrecheckResult - [DEFAULT_PRECHECK_RESULT] or a [PrecheckResult] with an error code.
*
* @see [checkForParam]
* @see [com.isupatches.wisefy.WiseFy.connectToNetwork]
*
* @author Patches
* @since 3.0
*/
override fun connectToNetworkPrechecks(ssidToConnectTo: String?): PrecheckResult =
checkForParam(ssidToConnectTo)
/**
* Used internally to make sure perquisites for disabling wifi on the device are met.
*
* @return PrecheckResult - [DEFAULT_PRECHECK_RESULT]
*
* @see [com.isupatches.wisefy.WiseFy.disableWifi]
* @see [DEFAULT_PRECHECK_RESULT]
*
* @author Patches
* @since 3.0
*/
override fun disableWifiChecks() = DEFAULT_PRECHECK_RESULT
/**
* Used internally to make sure perquisites for disconnecting a device from it's current network are met.
*
* @return PrecheckResult - [DEFAULT_PRECHECK_RESULT]
*
* @see [com.isupatches.wisefy.WiseFy.disconnectFromCurrentNetwork]
* @see [DEFAULT_PRECHECK_RESULT]
*
* @author Patches
* @since 3.0
*/
override fun disconnectFromCurrentNetworkChecks() = DEFAULT_PRECHECK_RESULT
/**
* Used internally to make sure perquisites for enabling wifi on the device are met.
*
* @return PrecheckResult - [DEFAULT_PRECHECK_RESULT]
*
* @see [com.isupatches.wisefy.WiseFy.enableWifi]
* @see [DEFAULT_PRECHECK_RESULT]
*
* @author Patches
* @since 3.0
*/
override fun enableWifiChecks() = DEFAULT_PRECHECK_RESULT
/**
* Used internally to make sure perquisites for getting the device's current network are met.
*
* @return PrecheckResult - [DEFAULT_PRECHECK_RESULT]
*
* @see [com.isupatches.wisefy.WiseFy.getCurrentNetworkInfo]
* @see [DEFAULT_PRECHECK_RESULT]
*
* @author Patches
* @since 3.0
*/
override fun getCurrentNetworkChecks() = DEFAULT_PRECHECK_RESULT
/**
* Used internally to make sure perquisites for getting the device's current network info are met.
*
* @return PrecheckResult - [DEFAULT_PRECHECK_RESULT]
*
* @see [com.isupatches.wisefy.WiseFy.getCurrentNetworkInfo]
* @see [DEFAULT_PRECHECK_RESULT]
*
* @author Patches
* @since 3.0
*/
override fun getCurrentNetworkInfoChecks() = DEFAULT_PRECHECK_RESULT
/**
* Used internally to make sure perquisites for getting the frequency of the current network are met.
*
* @return PrecheckResult - [DEFAULT_PRECHECK_RESULT]
*
* @see [com.isupatches.wisefy.WiseFy.getFrequency]
* @see [DEFAULT_PRECHECK_RESULT]
*
* @author Patches
* @since 4.1
*/
override fun getFrequencyChecks() = DEFAULT_PRECHECK_RESULT
/**
* Used internally to make sure perquisites for getting the ip of the device are met.
*
* @return PrecheckResult - [DEFAULT_PRECHECK_RESULT]
*
* @see [com.isupatches.wisefy.WiseFy.getIP]
* @see [DEFAULT_PRECHECK_RESULT]
*
* @author Patches
* @since 3.0
*/
override fun getIPChecks() = DEFAULT_PRECHECK_RESULT
/**
* Used internally to make sure perquisites for getting nearby access points are met.
*
* @return PrecheckResult - [DEFAULT_PRECHECK_RESULT]
*
* @see [com.isupatches.wisefy.WiseFy.getNearbyAccessPoints]
* @see [DEFAULT_PRECHECK_RESULT]
*
* @author Patches
* @since 3.0
*/
override fun getNearbyAccessPointsChecks() = DEFAULT_PRECHECK_RESULT
/**
* Used internally to make sure perquisites for getting the RSSI of a network matching a given regex are met.
*
* @param regexForSSID The regexForSSID param from [com.isupatches.wisefy.WiseFy.getRSSI]
*
* @return PrecheckResult - [DEFAULT_PRECHECK_RESULT] or a [PrecheckResult] with an error code.
*
* @see [checkForParam]
* @see [com.isupatches.wisefy.WiseFy.getRSSI]
*
* @author Patches
* @since 3.0
*/
override fun getRSSIChecks(regexForSSID: String?): PrecheckResult =
checkForParam(regexForSSID)
/**
* Used internally to make sure perquisites for searching for a saved network on a device are met.
*
* @param regexForSSID The regexForSSID param from [com.isupatches.wisefy.WiseFy.searchForSavedNetwork]
*
* @return PrecheckResult - [DEFAULT_PRECHECK_RESULT] or a [PrecheckResult] with an error code.
*
* @see [checkForParam]
* @see [com.isupatches.wisefy.WiseFy.searchForSavedNetwork]
*
* @author Patches
* @since 3.0
*/
override fun getSavedNetworkChecks(regexForSSID: String?): PrecheckResult =
checkForParam(regexForSSID)
/**
* Used internally to make sure perquisites for getting a saved network on a device are met.
*
* @return PrecheckResult - [DEFAULT_PRECHECK_RESULT]
*
* @see [com.isupatches.wisefy.WiseFy.getSavedNetworks]
* @see [DEFAULT_PRECHECK_RESULT]
*
* @author Patches
* @since 3.0
*/
override fun getSavedNetworksChecks() = DEFAULT_PRECHECK_RESULT
/**
* Used internally to make sure perquisites for getting the saved networks on a device are met.
*
* @param regexForSSID The regexForSSID param from [com.isupatches.wisefy.WiseFy.getSavedNetworks]
*
* @return PrecheckResult - [DEFAULT_PRECHECK_RESULT] or a [PrecheckResult] with an error code.
*
* @see [checkForParam]
* @see [com.isupatches.wisefy.WiseFy.getSavedNetworks]
*
* @author Patches
* @since 3.0
*/
override fun getSavedNetworksChecks(regexForSSID: String?): PrecheckResult =
checkForParam(regexForSSID)
/**
* Used internally to make sure perquisites for checking if the device is connected to
* a mobile network are met.
*
* @return PrecheckResult - [DEFAULT_PRECHECK_RESULT]
*
* @see [com.isupatches.wisefy.WiseFy.isDeviceConnectedToMobileNetwork]
* @see [DEFAULT_PRECHECK_RESULT]
*
* @author Patches
* @since 3.0
*/
override fun isDeviceConnectedToMobileNetworkChecks() = DEFAULT_PRECHECK_RESULT
/**
* Used internally to make sure perquisites for checking if the device is connected to
* a mobile or wifi network are met.
*
* @return PrecheckResult - [DEFAULT_PRECHECK_RESULT]
*
* @see [com.isupatches.wisefy.WiseFy.isDeviceConnectedToMobileOrWifiNetwork]
* @see [DEFAULT_PRECHECK_RESULT]
*
* @author Patches
* @since 3.0
*/
override fun isDeviceConnectedToMobileOrWifiNetworkChecks() = DEFAULT_PRECHECK_RESULT
/**
* Used internally to make sure perquisites for checking if the device is connected to
* a specific SSID are met.
*
* @param ssid The ssid param from [com.isupatches.wisefy.WiseFy.isDeviceConnectedToSSID]
*
* @return PrecheckResult - [DEFAULT_PRECHECK_RESULT] or a [PrecheckResult] with an error code.
*
* @see [checkForParam]
* @see [com.isupatches.wisefy.WiseFy.isDeviceConnectedToSSID]
*
* @author Patches
* @since 3.0
*/
override fun isDeviceConnectedToSSIDChecks(ssid: String?): PrecheckResult =
checkForParam(ssid)
/**
* Used internally to make sure perquisites for checking if the device is connected to
* a wifi network are met.
*
* @return PrecheckResult - [DEFAULT_PRECHECK_RESULT]
*
* @see [com.isupatches.wisefy.WiseFy.isDeviceConnectedToWifiNetwork]
* @see [DEFAULT_PRECHECK_RESULT]
*
* @author Patches
* @since 3.0
*/
override fun isDeviceConnectedToWifiNetworkChecks() = DEFAULT_PRECHECK_RESULT
/**
* Used internally to make sure prerequisites for seeing if a device is roaming are met.
*
* @return PrecheckResult - [DEFAULT_PRECHECK_RESULT]
*
* @see [com.isupatches.wisefy.WiseFy.isDeviceRoaming]
* @see [DEFAULT_PRECHECK_RESULT]
*
* @author Patches
* @since 3.0
*/
override fun isDeviceRoamingChecks() = DEFAULT_PRECHECK_RESULT
/**
* Used internally to make sure prerequisites for seeing if a network is a saved configuration
* are met.
*
* @return PrecheckResult - [DEFAULT_PRECHECK_RESULT]
*
* @see [com.isupatches.wisefy.WiseFy.isNetworkSaved]
* @see [DEFAULT_PRECHECK_RESULT]
*
* @author Patches
* @since 3.0
*/
override fun isNetworkSavedChecks() = DEFAULT_PRECHECK_RESULT
/**
* Used internally to make sure prerequisites for enabling wifi are met.
*
* @return PrecheckResult - [DEFAULT_PRECHECK_RESULT]
*
* @see [com.isupatches.wisefy.WiseFy.isWifiEnabled]
* @see [DEFAULT_PRECHECK_RESULT]
*
* @author Patches
* @since 3.0
*/
override fun isWifiEnabledChecks() = DEFAULT_PRECHECK_RESULT
/**
* Used internally to make sure prerequisites for removing a network are met.
*
* @param ssidToRemove The regexForSsid param from [com.isupatches.wisefy.WiseFy.removeNetwork]
*
* @return PrecheckResult - [DEFAULT_PRECHECK_RESULT] or a [PrecheckResult] with an error code.
*
* @see [checkForParam]
* @see [com.isupatches.wisefy.WiseFy.removeNetwork]
*
* @author Patches
* @since 3.0
*/
override fun removeNetworkCheck(ssidToRemove: String?): PrecheckResult =
checkForParam(ssidToRemove)
/**
* Used internally to make sure prerequisites for searching for an individual access point
* are met.
*
* @param regexForSSID The regexForSsid param from [com.isupatches.wisefy.WiseFy.searchForAccessPoint]
*
* @return PrecheckResult - [DEFAULT_PRECHECK_RESULT] or a [PrecheckResult] with an error code.
*
* @see [checkForParam]
* @see [com.isupatches.wisefy.WiseFy.searchForAccessPoint]
*
* @author Patches
* @since 3.0
*/
override fun searchForAccessPointChecks(regexForSSID: String?): PrecheckResult =
checkForParam(regexForSSID)
/**
* Used internally to make sure prerequisites for searching for access points are met.
*
* @param regexForSSID The regexForSsid param from [com.isupatches.wisefy.WiseFy.searchForAccessPoints]
*
* @return PrecheckResult - [DEFAULT_PRECHECK_RESULT] or a [PrecheckResult] with an error code.
*
* @see [checkForParam]
* @see [com.isupatches.wisefy.WiseFy.searchForAccessPoints]
*
* @author Patches
* @since 3.0
*/
override fun searchForAccessPointsChecks(regexForSSID: String?): PrecheckResult =
checkForParam(regexForSSID)
/**
* Used internally to make sure prerequisites for searching for an individual saved network
* are met.
*
* @param regexForSSID The regexForSsid param from [com.isupatches.wisefy.WiseFy.searchForSavedNetwork]
*
* @return PrecheckResult - [DEFAULT_PRECHECK_RESULT] or a [PrecheckResult] with an error code.
*
* @see [checkForParam]
* @see [com.isupatches.wisefy.WiseFy.searchForSavedNetwork]
*
* @author Patches
* @since 4.0
*/
override fun searchForSavedNetworkChecks(regexForSSID: String?): PrecheckResult =
checkForParam(regexForSSID)
/**
* Used internally to make sure prerequisites for searching for saved networks are met.
*
* @param regexForSSID The regexForSsid param from [com.isupatches.wisefy.WiseFy.searchForSavedNetworks]
*
* @return PrecheckResult - [DEFAULT_PRECHECK_RESULT] or a [PrecheckResult] with an error code.
*
* @see [checkForParam]
* @see [com.isupatches.wisefy.WiseFy.searchForSavedNetworks]
*
* @author Patches
* @since 4.0
*/
override fun searchForSavedNetworksChecks(regexForSSID: String?): PrecheckResult =
checkForParam(regexForSSID)
/**
* Used internally to make sure prerequisites for searching for an individual SSID are met.
*
* @param regexForSSID The regexForSsid param from [com.isupatches.wisefy.WiseFy.searchForSSID]
*
* @return PrecheckResult - [DEFAULT_PRECHECK_RESULT] or a [PrecheckResult] with an error code.
*
* @see [checkForParam]
* @see [com.isupatches.wisefy.WiseFy.searchForSSID]
*
* @author Patches
* @since 3.0
*/
override fun searchForSSIDChecks(regexForSSID: String?): PrecheckResult =
checkForParam(regexForSSID)
/**
* Used internally to make sure prerequisites for searching for SSIDs are met.
*
* @param regexForSSID The regexForSsid param from [com.isupatches.wisefy.WiseFy.searchForSSIDs]
*
* @return PrecheckResult - [DEFAULT_PRECHECK_RESULT] or a [PrecheckResult] with an error code.
*
* @see [checkForParam]
* @see [com.isupatches.wisefy.WiseFy.searchForSSIDs]
*
* @author Patches
* @since 3.0
*/
override fun searchForSSIDsChecks(regexForSSID: String?): PrecheckResult =
checkForParam(regexForSSID)
/*
* HELPERS
*/
/**
* Used internally as an abstracted layer that check if a necessary param is not empty.
*
* @param param The param to check if it's empty
*
* @return PrecheckResult - [DEFAULT_PRECHECK_RESULT] or a [PrecheckResult] with an error code.
*
* @see [DEFAULT_PRECHECK_RESULT]
* @see [MISSING_PARAMETER]
* @see [PrecheckResult]
*
* @author Patches
* @since 3.0
*/
private fun checkForParam(param: String?): PrecheckResult =
if (param.isNullOrEmpty()) {
PrecheckResult(code = MISSING_PARAMETER)
} else {
DEFAULT_PRECHECK_RESULT
}
/**
* Used internally as an abstracted layer that checks if all of the prerequisites for adding
* a network are met. f.e. ssid is not null or empty, network is not already saved, etc.
*
* @param ssid The ssid of the network to add
*
* @return PrecheckResult - [DEFAULT_PRECHECK_RESULT] or a [PrecheckResult] with an error code.
*
* @see [DEFAULT_PRECHECK_RESULT]
* @see [MISSING_PARAMETER]
* @see [NETWORK_ALREADY_CONFIGURED]
* @see [PrecheckResult]
*
* @author Patches
* @since 3.0
*/
@RequiresPermission(ACCESS_FINE_LOCATION)
private fun checkAddNetworkPrerequisites(ssid: String?): PrecheckResult =
when {
ssid.isNullOrEmpty() -> PrecheckResult(code = MISSING_PARAMETER)
wisefySearch.isNetworkASavedConfiguration(ssid) -> {
PrecheckResult(code = NETWORK_ALREADY_CONFIGURED)
}
else -> DEFAULT_PRECHECK_RESULT
}
/**
* Used internally as an abstracted layer that checks if all of the prerequisites for adding
* a network are met. f.e. ssid and password are not null or empty, network is not already saved, etc.
*
* @param ssid The ssid of the network to add
* @param password The password of the network to add
*
* @return PrecheckResult - [DEFAULT_PRECHECK_RESULT] or a [PrecheckResult] with an error code.
*
* @see [DEFAULT_PRECHECK_RESULT]
* @see [MISSING_PARAMETER]
* @see [NETWORK_ALREADY_CONFIGURED]
* @see [PrecheckResult]
*
* @author Patches
* @since 3.0
*/
@RequiresPermission(ACCESS_FINE_LOCATION)
private fun checkAddNetworkPrerequisites(ssid: String?, password: String?): PrecheckResult =
when {
ssid.isNullOrEmpty() || password.isNullOrEmpty() -> {
PrecheckResult(code = MISSING_PARAMETER)
}
wisefySearch.isNetworkASavedConfiguration(ssid) -> {
PrecheckResult(code = NETWORK_ALREADY_CONFIGURED)
}
else -> DEFAULT_PRECHECK_RESULT
}
internal companion object {
fun create(wisefySearch: WiseFySearch): WiseFyPrechecks = WiseFyPrechecksImpl(wisefySearch)
}
}
/**
* An interface with methods that relate to checking that prerequisites are met before
* continuing with a WiseFy operation.
*
* @see [WiseFyPrechecksImpl]
*
* Updates
* - 01/04/2020: Refined permissions
*
* @author Patches
* @since 3.0
*/
internal interface WiseFyPrechecks {
@RequiresPermission(ACCESS_FINE_LOCATION)
fun addNetworkPrechecks(ssid: String?): PrecheckResult
@RequiresPermission(ACCESS_FINE_LOCATION)
fun addNetworkPrechecks(ssid: String?, password: String?): PrecheckResult
fun connectToNetworkPrechecks(ssidToConnectTo: String?): PrecheckResult
fun disableWifiChecks(): PrecheckResult
fun disconnectFromCurrentNetworkChecks(): PrecheckResult
fun enableWifiChecks(): PrecheckResult
fun getCurrentNetworkChecks(): PrecheckResult
fun getCurrentNetworkInfoChecks(): PrecheckResult
fun getFrequencyChecks(): PrecheckResult
fun getIPChecks(): PrecheckResult
fun getNearbyAccessPointsChecks(): PrecheckResult
fun getRSSIChecks(regexForSSID: String?): PrecheckResult
fun getSavedNetworkChecks(regexForSSID: String?): PrecheckResult
fun getSavedNetworksChecks(regexForSSID: String?): PrecheckResult
fun getSavedNetworksChecks(): PrecheckResult
fun isDeviceConnectedToMobileNetworkChecks(): PrecheckResult
fun isDeviceConnectedToMobileOrWifiNetworkChecks(): PrecheckResult
fun isDeviceConnectedToSSIDChecks(ssid: String?): PrecheckResult
fun isDeviceConnectedToWifiNetworkChecks(): PrecheckResult
fun isDeviceRoamingChecks(): PrecheckResult
fun isNetworkSavedChecks(): PrecheckResult
fun isWifiEnabledChecks(): PrecheckResult
fun removeNetworkCheck(ssidToRemove: String?): PrecheckResult
fun searchForAccessPointChecks(regexForSSID: String?): PrecheckResult
fun searchForAccessPointsChecks(regexForSSID: String?): PrecheckResult
fun searchForSavedNetworkChecks(regexForSSID: String?): PrecheckResult
fun searchForSavedNetworksChecks(regexForSSID: String?): PrecheckResult
fun searchForSSIDChecks(regexForSSID: String?): PrecheckResult
fun searchForSSIDsChecks(regexForSSID: String?): PrecheckResult
}
/**
* A return from WiseFyPrechecks that includes a relevant detail code.
*
* @param code The return code from prechecks (f.e. [DEFAULT_PRECHECK_RETURN_CODE] or
* an error code such as [MISSING_PARAMETER]. This code will also be used by the extension
* functions [passed] and [failed].
*
* @see [failed]
* @see [passed]
* @see [WiseFyCode]
*
* @author Patches
* @since 3.0
*/
internal data class PrecheckResult(@WiseFyCode val code: Int)
/**
* An extension function to determine if prerequisites for an operation are NOT met.
*
* @see [PrecheckResult]
*
* @author Patches
* @since 3.0
*/
internal fun PrecheckResult.failed(): Boolean = code < DEFAULT_PRECHECK_RETURN_CODE
/**
* An extension function to determine if prerequisites for an operation ARE met.
*
* @see [PrecheckResult]
*
* @author Patches
* @since 3.0
*/
internal fun PrecheckResult.passed(): Boolean = code >= DEFAULT_PRECHECK_RETURN_CODE
/**
* A default result to return that denotes a success and that prerequisites for an operation are met.
*
* @see [PrecheckResult]
*
* @author Patches
* @since 3.0
*/
internal val DEFAULT_PRECHECK_RESULT = PrecheckResult(code = DEFAULT_PRECHECK_RETURN_CODE)
| apache-2.0 | 6046ac5eed39eb235abbe4d14221521c | 32.362963 | 113 | 0.679174 | 4.34246 | false | false | false | false |
Egorand/kotlin-playground | src/me/egorand/kotlin/playground/misc/Casts.kt | 1 | 1491 | /*
* Copyright 2016 Egor Andreevici
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package me.egorand.kotlin.playground.misc
fun printObj(obj: Any) {
when (obj) {
is Int -> println(obj + 1)
is String -> println(obj.length)
is IntArray -> println(obj.sum())
}
}
fun main(args: Array<String>) {
val obj = "Hello world!"
if (obj !is String) {
println("Not a String")
} else {
// compiler is smart enough to cast the obj to String for us,
// so we can safely call length() without explicit casting
println(obj.length)
}
// smart casts work in right hand side of || and &&
if (obj is String && obj.length > 5) println(obj.first())
printObj(obj)
val nullable = null
// val nullableStr = nullable as String // unsafe cast, will throw exception!
val nullableStr1 = nullable as String?
println(nullableStr1)
val nullableStr2 = nullable as? String
println(nullableStr2)
} | apache-2.0 | d8e0a55a2ed77d50bad09c7b9018205a | 29.44898 | 81 | 0.671362 | 3.793893 | false | false | false | false |
BilledTrain380/sporttag-psa | app/shared/src/main/kotlin/ch/schulealtendorf/psa/shared/rulebook/BallThrowingRuleSet.kt | 1 | 2711 | /*
* Copyright (c) 2019 by Nicolas Märchy
*
* This file is part of Sporttag PSA.
*
* Sporttag PSA 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.
*
* Sporttag PSA 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 Sporttag PSA. If not, see <http://www.gnu.org/licenses/>.
*
* Diese Datei ist Teil von Sporttag PSA.
*
* Sporttag PSA ist Freie Software: Sie können es unter den Bedingungen
* der GNU General Public License, wie von der Free Software Foundation,
* Version 3 der Lizenz oder (nach Ihrer Wahl) jeder späteren
* veröffentlichten Version, weiterverbreiten und/oder modifizieren.
*
* Sporttag PSA wird in der Hoffnung, dass es nützlich sein wird, aber
* OHNE JEDE GEWÄHRLEISTUNG, bereitgestellt; sogar ohne die implizite
* Gewährleistung der MARKTFÄHIGKEIT oder EIGNUNG FÜR EINEN BESTIMMTEN ZWECK.
* Siehe die GNU General Public License für weitere Details.
*
* Sie sollten eine Kopie der GNU General Public License zusammen mit diesem
* Programm erhalten haben. Wenn nicht, siehe <http://www.gnu.org/licenses/>.
*
*
*/
package ch.schulealtendorf.psa.shared.rulebook
import ch.schulealtendorf.psa.dto.participation.GenderDto
import ch.schulealtendorf.psa.dto.participation.athletics.BALLWURF
import ch.schulealtendorf.psa.shared.rulebook.rules.RuleSet
/**
* Defines all the rules that can be applied to a ball throwing.
*
* @author nmaerchy
* @version 1.0.0
*/
class BallThrowingRuleSet : RuleSet<FormulaModel, Int>() {
/**
* @return true if the rules of this rule set can be used, otherwise false
*/
override val whenever: (FormulaModel) -> Boolean = { it.discipline == BALLWURF }
init {
addRule(
object : FormulaRule() {
override val formula: (Double) -> Int = { (22 * ((((it * 100) - 500) / 100) pow 0.9)).toInt() }
override val whenever: (FormulaModel) -> Boolean = { it.gender == GenderDto.FEMALE }
}
)
addRule(
object : FormulaRule() {
override val formula: (Double) -> Int = { (18 * ((((it * 100) - 800) / 100) pow 0.9)).toInt() }
override val whenever: (FormulaModel) -> Boolean = { it.gender == GenderDto.MALE }
}
)
}
}
| gpl-3.0 | 756b1a97e6d66537b382296d7309bdf9 | 35.5 | 111 | 0.68197 | 4.220313 | false | false | false | false |
mihmuh/IntelliJConsole | Konsole/src/com/intellij/idekonsole/KSettings.kt | 1 | 1582 | package com.intellij.idekonsole
import com.intellij.openapi.components.PersistentStateComponent
import com.intellij.openapi.components.ServiceManager
import com.intellij.openapi.components.State
import com.intellij.openapi.components.Storage
import java.awt.Color
import java.util.*
@State(name = "IDEKonsole", storages = arrayOf(Storage("/ide_konsole.xml")))
internal class KSettings : PersistentStateComponent<KSettings.Data> {
companion object {
val instance: KSettings
get() = ServiceManager.getService(KSettings::class.java)
val LIB_NAME = "Z_SECRET_LIB"
val MODULE_NAME = "Z_SECRET_MODULE"
val SRC_DIR = "com/intellij/idekonsole/runtime/";
val PSI_STUBS = "PsiClassReferences.kt"
val JAVA_TOKEN_STUBS = "JavaTokenReferences.kt"
val CONSOLE_FILE_PATH = SRC_DIR + "Test.kt";
val BACKGROUND_COLOR = Color.LIGHT_GRAY
val SEARCH_TIME = 100L
val TIME_LIMIT = 1000L
val MAX_USAGES = 1000
}
var data = Data()
override fun loadState(value: Data) {
data = value
}
override fun getState(): Data = data
fun getConsoleHistory() = ConsoleHistory(data.CONSOLE_HISTORY)
class ConsoleHistory(list: MutableList<String>) : MutableList<String> by list {
val myList = list
fun smartAppend(string: String) {
remove(string)
add(string)
while (size > 50) {
myList.removeAt(0)
}
}
}
class Data {
var CONSOLE_HISTORY = ArrayList<String>()
}
} | gpl-3.0 | c8a0fbe299685180e71decbe771b149c | 27.781818 | 83 | 0.645386 | 4.152231 | false | false | false | false |
Undin/intellij-rust | src/test/kotlin/org/rust/ide/inspections/typecheck/ConvertToTyUsingTraitMethodFixTestBase.kt | 3 | 1821 | /*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.ide.inspections.typecheck
import org.rust.ProjectDescriptor
import org.rust.WithStdlibRustProjectDescriptor
import org.rust.ide.inspections.RsInspectionsTestBase
import org.rust.ide.inspections.RsTypeCheckInspection
@ProjectDescriptor(WithStdlibRustProjectDescriptor::class)
abstract class ConvertToTyUsingTraitMethodFixTestBase(
isExpectedMut: Boolean, private val trait: String, private val method: String, protected val imports: String = ""
) : RsInspectionsTestBase(RsTypeCheckInspection::class) {
private val ref = if (isExpectedMut) "&mut " else "&"
private val fixName = "Convert to ${ref}A using `$trait` trait"
fun `test Trait with A subs is impl for B`() = checkFixByText(fixName, """
$imports
struct A;
struct B;
impl $trait<A> for B { fn $method(&self) -> ${ref}A { ${ref}A } }
fn main () {
let a: ${ref}A = <error>B<caret></error>;
}
""", """
$imports
struct A;
struct B;
impl $trait<A> for B { fn $method(&self) -> ${ref}A { ${ref}A } }
fn main () {
let a: ${ref}A = B.$method();
}
""")
fun `test Trait with C subs is impl for B`() = checkFixIsUnavailable(fixName, """
$imports
struct A;
struct B;
struct C;
impl $trait<C> for B { fn $method(&self) -> ${ref}C { ${ref}C; } }
fn main () {
let a: ${ref}A = <error>B<caret></error>;
}
""")
fun `test Trait is not impl for B`() = checkFixIsUnavailable(fixName, """
struct A;
struct B;
fn main () {
let a: ${ref}A = <error>B<caret></error>;
}
""")
}
| mit | 88dae72b16c6cc33f9dd1b77f73d5dc3 | 26.590909 | 117 | 0.582647 | 3.891026 | false | true | false | false |
Undin/intellij-rust | src/main/kotlin/org/rust/lang/core/dfa/borrowck/gatherLoans/GatherMoves.kt | 3 | 3628 | /*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.lang.core.dfa.borrowck.gatherLoans
import org.rust.lang.core.dfa.Categorization.*
import org.rust.lang.core.dfa.Cmt
import org.rust.lang.core.dfa.MoveReason
import org.rust.lang.core.dfa.MoveReason.*
import org.rust.lang.core.dfa.MutateMode
import org.rust.lang.core.dfa.borrowck.*
import org.rust.lang.core.psi.RsPat
import org.rust.lang.core.psi.RsPatBinding
import org.rust.lang.core.psi.RsPatIdent
import org.rust.lang.core.psi.ext.RsElement
import org.rust.lang.core.psi.ext.RsStructOrEnumItemElement
import org.rust.lang.core.types.ty.Ty
import org.rust.lang.core.types.ty.TyAdt
import org.rust.lang.core.types.ty.TySlice
import org.rust.lang.core.types.ty.isBox
class GatherMoveContext(private val bccx: BorrowCheckContext, private val moveData: MoveData) {
data class GatherMoveInfo(
val element: RsElement,
val kind: MoveKind,
val cmt: Cmt,
val movePlace: MovePlace? = null
)
fun gatherDeclaration(binding: RsPatBinding, variableType: Ty) {
val loanPath = LoanPath(LoanPathKind.Var(binding), variableType, binding)
moveData.addMove(loanPath, binding, MoveKind.Declared)
}
fun gatherMoveFromExpr(element: RsElement, cmt: Cmt, moveReason: MoveReason) {
val kind = when (moveReason) {
DirectRefMove, PatBindingMove -> MoveKind.MoveExpr
CaptureMove -> MoveKind.Captured
}
val moveInfo = GatherMoveInfo(element, kind, cmt)
gatherMove(moveInfo)
}
fun gatherMoveFromPat(movePat: RsPat, cmt: Cmt) {
val patMovePlace = (movePat as? RsPatIdent)?.let { MovePlace(movePat.patBinding) }
val moveInfo = GatherMoveInfo(movePat, MoveKind.MovePat, cmt, patMovePlace)
gatherMove(moveInfo)
}
private fun gatherMove(moveInfo: GatherMoveInfo) {
val move = getIllegalMoveOrigin(moveInfo.cmt)
if (move != null) {
bccx.reportMoveError(move)
} else {
val loanPath = LoanPath.computeFor(moveInfo.cmt) ?: return
moveData.addMove(loanPath, moveInfo.element, moveInfo.kind)
}
}
fun gatherAssignment(loanPath: LoanPath, assign: RsElement, assignee: RsElement, mode: MutateMode) {
moveData.addAssignment(loanPath, assign, assignee, mode)
}
private fun getIllegalMoveOrigin(cmt: Cmt): Cmt? {
return when (val category = cmt.category) {
is Rvalue, is Local -> null
is Deref -> if (category.cmt.ty.isBox) null else cmt
is StaticItem -> cmt
is Interior.Field, is Interior.Pattern -> {
val base = (category as Interior).cmt
when (base.ty) {
is TyAdt -> if (base.ty.item.hasDestructor) cmt else getIllegalMoveOrigin(base)
is TySlice -> cmt
else -> getIllegalMoveOrigin(base)
}
}
is Interior.Index -> cmt
is Downcast -> {
val base = category.cmt
when (base.ty) {
is TyAdt -> if (base.ty.item.hasDestructor) cmt else getIllegalMoveOrigin(base)
is TySlice -> cmt
else -> getIllegalMoveOrigin(base)
}
}
null -> null
}
}
}
// TODO: use ImplLookup
@Suppress("unused")
val RsStructOrEnumItemElement.hasDestructor: Boolean get() = false
val Ty.isAdtWithDestructor: Boolean get() = this is TyAdt && this.item.hasDestructor
| mit | c62c8104a389e2ca74333c81d2632d58 | 33.884615 | 104 | 0.64333 | 3.686992 | false | false | false | false |
Gh0u1L5/WechatMagician | app/src/main/kotlin/com/gh0u1l5/wechatmagician/backend/storage/list/BaseList.kt | 1 | 675 | package com.gh0u1l5.wechatmagician.backend.storage.list
import java.util.*
import java.util.concurrent.ConcurrentHashMap
open class BaseList<T> {
protected val data: MutableSet<T> = Collections.newSetFromMap(ConcurrentHashMap())
fun toList() = data.toList()
fun forEach(action: (T) -> Unit) = data.forEach(action)
open operator fun contains(value: Any?): Boolean = value in data
open operator fun plusAssign(value: T) { data += value }
open operator fun plusAssign(values: Iterable<T>) { data += values }
open operator fun minusAssign(value: T) { data -= value }
open operator fun minusAssign(values: Iterable<T>) { data -= values }
} | gpl-3.0 | 7d241b9dd31fcfeb839e5cab843d8fe6 | 29.727273 | 86 | 0.708148 | 4.017857 | false | false | false | false |
McGars/basekitk | basekitk/src/main/kotlin/com/mcgars/basekitk/features/recycler2/BaseRecycleViewDelegateController.kt | 1 | 6374 | package com.mcgars.basekitk.features.recycler2
import android.os.Bundle
import androidx.annotation.CallSuper
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import android.view.View
import com.bluelinelabs.conductor.Controller
import com.mcgars.basekitk.R
import com.mcgars.basekitk.features.base.BaseViewController
import com.mcgars.basekitk.features.decorators.DecoratorListener
import com.mcgars.basekitk.tools.find
import com.mcgars.basekitk.tools.gone
import com.mcgars.basekitk.tools.visible
import java.lang.RuntimeException
/**
* Created by Владимир on 22.09.2015.
*/
abstract class BaseRecycleViewDelegateController(args: Bundle? = null) : BaseViewController(args) {
var recyclerView: RecyclerView? = null
private set
protected var visibleThreshold = 5
private var hasMoreItems: Boolean = false
private var isLoading: Boolean = false
private var adapter: RecyclerView.Adapter<*>? = null
protected var page = DEFAULT_FIRST_PAGE
/**
* If user on the first page, then all list will be cleared when new data arrived
*/
var clearOnFirstPage = true
private var loadingScroll: RecyclerView.OnScrollListener = object : RecyclerView.OnScrollListener() {
override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
val linearLayoutManager = recyclerView.layoutManager as? LinearLayoutManager ?: return
val totalItemCount = linearLayoutManager.itemCount
val lastVisibleItem = linearLayoutManager.findLastVisibleItemPosition()
if (!isLoading && hasMoreItems && totalItemCount <= (lastVisibleItem + visibleThreshold)) {
page++
isLoading = true
loadData(page)
}
}
}
init {
addDecorator(object : DecoratorListener() {
override fun postCreateView(controller: Controller, view: View) {
recyclerView = view.find(R.id.recycleView)
recyclerView?.layoutManager = initLayoutManager()
initLoading()
}
})
}
override fun getLayoutId() = R.layout.basekit_view_recycler
/**
* Drop page to default
*/
fun setDefaultPage() {
page = DEFAULT_FIRST_PAGE
}
fun isFirstPage(): Boolean = page == DEFAULT_FIRST_PAGE
fun getAdapter() = adapter
protected open fun initLayoutManager() = LinearLayoutManager(activity)
/**
* Load more items when list scrolls to end
*/
protected fun initLoading() {
recyclerView?.addOnScrollListener(loadingScroll)
}
/**
* Call when [adapter] is null, in first init
*/
abstract fun getAdapter(list: MutableList<*>): RecyclerView.Adapter<*>
/**
* Calls when list scrolls to end
*/
abstract fun loadData(page: Int)
/**
* Indicate have more items and when list scrolls to end call [loadData]
*/
@CallSuper
open fun hasMoreItems(has: Boolean) {
isLoading = false
hasMoreItems = has
if (adapter is KitAdapter<*>) {
showAdapterLoader((adapter as KitAdapter<Any>).getDelegates())
}
}
/**
* TODO через стратегию переделать
*/
protected fun prepareData(
list: List<Any>,
diffUtil: (oldItems: List<Any>, newItems: List<Any>) -> DiffUtil.Callback
) {
if (adapter == null) {
adapter = getAdapter(mutableListOf<Any>()).also {
setAdapter(it)
}
}
if (list.isEmpty()) {
(adapter as? KitAdapter<Any>)?.clear()
} else {
(adapter as? KitAdapter<Any>)?.set(list, diffUtil)
?: throw RuntimeException("Use KitAdapter only")
}
}
/**
* You must call this when data is ready to show for UI
* TODO через стратегию переделать
*/
protected fun prepareData(
list: List<Any>,
hasmore: Boolean = false,
customNotify: ((RecyclerView.Adapter<*>) -> Unit)? = null
) {
if (activity == null)
return
if (clearOnFirstPage && page == DEFAULT_FIRST_PAGE) {
(adapter as? KitAdapter<*>)?.clear()
}
if (adapter == null) {
recyclerView?.gone()
adapter = getAdapter(list as MutableList<*>).also {
setAdapter(it)
}
recyclerView?.visible()
} else {
when {
customNotify != null -> customNotify.invoke(adapter!!)
list.isNotEmpty() -> (adapter as KitAdapter<Any>).addItems(list)
else -> adapter?.notifyDataSetChanged()
}
}
hasMoreItems(hasmore)
}
/**
* Use this only if you need recreate adapter
*/
protected fun destroyAdapter() {
adapter = null
}
protected fun removeItem(position: Int) {
if (adapter is KitAdapter<*>) {
(adapter as KitAdapter<*>).removeItemByPosition(position)
}
}
protected fun removeItem(item: Any) {
(adapter is KitAdapter<*>).let {
(adapter as KitAdapter<Any>).removeItem(item)
}
}
protected fun addItem(item: Any) {
(adapter is KitAdapter<*>).let {
(adapter as KitAdapter<Any>).addItem(item)
}
}
protected fun addItem(position: Int, item: Any) {
(adapter is KitAdapter<*>).let {
(adapter as KitAdapter<Any>).addItem(position, item)
}
}
private fun setAdapter(adapter: RecyclerView.Adapter<*>) {
recyclerView?.adapter = adapter
}
/*
* Try show pagination loader
*/
private fun showAdapterLoader(delegates: List<AdapterDelegate<Any>>?) {
delegates?.forEach {
if (it is AdapterViewLoader<*>) {
it.showLoader(hasMoreItems)
}
}
}
override fun onDestroyView(view: View) {
super.onDestroyView(view)
// When we go to another page and back to this page list disappears, fix this
adapter = null
}
companion object {
var DEFAULT_FIRST_PAGE = 0
var LIMIT = 10
}
}
| apache-2.0 | 3f0fffe8d78734c50e74de7339f9395a | 28.115207 | 105 | 0.604938 | 4.789992 | false | false | false | false |
charleskorn/batect | app/src/unitTest/kotlin/batect/ui/fancy/CleanupProgressDisplayLineSpec.kt | 1 | 32115 | /*
Copyright 2017-2020 Charles Korn.
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 batect.ui.fancy
import batect.config.Container
import batect.docker.DockerContainer
import batect.docker.DockerNetwork
import batect.execution.model.events.ContainerCreatedEvent
import batect.execution.model.events.ContainerRemovedEvent
import batect.execution.model.events.TaskNetworkCreatedEvent
import batect.execution.model.events.TaskNetworkDeletedEvent
import batect.execution.model.events.TemporaryDirectoryCreatedEvent
import batect.execution.model.events.TemporaryDirectoryDeletedEvent
import batect.execution.model.events.TemporaryFileCreatedEvent
import batect.execution.model.events.TemporaryFileDeletedEvent
import batect.testutils.createForEachTest
import batect.testutils.equivalentTo
import batect.testutils.imageSourceDoesNotMatter
import batect.testutils.on
import batect.testutils.runForEachTest
import batect.ui.text.Text
import com.natpryce.hamkrest.assertion.assertThat
import org.spekframework.spek2.Spek
import org.spekframework.spek2.style.specification.describe
import java.nio.file.Paths
object CleanupProgressDisplayLineSpec : Spek({
describe("a cleanup progress display line") {
val cleanupDisplay by createForEachTest { CleanupProgressDisplayLine() }
describe("printing cleanup progress to the console") {
on("when there is nothing to clean up") {
val output by runForEachTest { cleanupDisplay.print() }
it("prints that clean up is complete") {
assertThat(output, equivalentTo(Text.white("Clean up: done")))
}
}
describe("when there is only the network to clean up") {
beforeEachTest {
cleanupDisplay.onEventPosted(TaskNetworkCreatedEvent(DockerNetwork("some-network")))
}
on("and the network hasn't been removed yet") {
val output by runForEachTest { cleanupDisplay.print() }
it("prints that the network still needs to be cleaned up") {
assertThat(output, equivalentTo(Text.white("Cleaning up: removing task network...")))
}
}
on("and the network has been removed") {
beforeEachTest { cleanupDisplay.onEventPosted(TaskNetworkDeletedEvent) }
val output by runForEachTest { cleanupDisplay.print() }
it("prints that clean up is complete") {
assertThat(output, equivalentTo(Text.white("Clean up: done")))
}
}
}
describe("when there is a container and the network to clean up") {
val container = Container("some-container", imageSourceDoesNotMatter())
beforeEachTest {
cleanupDisplay.onEventPosted(TaskNetworkCreatedEvent(DockerNetwork("some-network")))
cleanupDisplay.onEventPosted(ContainerCreatedEvent(container, DockerContainer("some-container-id")))
}
on("and the container hasn't been removed yet") {
val output by runForEachTest { cleanupDisplay.print() }
it("prints that the container still needs to be cleaned up") {
assertThat(output, equivalentTo(Text.white(Text("Cleaning up: 1 container (") + Text.bold("some-container") + Text(") left to remove..."))))
}
}
on("and the container has been removed") {
beforeEachTest { cleanupDisplay.onEventPosted(ContainerRemovedEvent(container)) }
val output by runForEachTest { cleanupDisplay.print() }
it("prints that the network still needs to be cleaned up") {
assertThat(output, equivalentTo(Text.white("Cleaning up: removing task network...")))
}
}
on("and the network has been removed") {
beforeEachTest {
cleanupDisplay.onEventPosted(ContainerRemovedEvent(container))
cleanupDisplay.onEventPosted(TaskNetworkDeletedEvent)
}
val output by runForEachTest { cleanupDisplay.print() }
it("prints that clean up is complete") {
assertThat(output, equivalentTo(Text.white("Clean up: done")))
}
}
}
describe("when there is a container, a temporary file and the network to clean up") {
val container = Container("some-container", imageSourceDoesNotMatter())
val filePath = Paths.get("some-file")
beforeEachTest {
cleanupDisplay.onEventPosted(TaskNetworkCreatedEvent(DockerNetwork("some-network")))
cleanupDisplay.onEventPosted(ContainerCreatedEvent(container, DockerContainer("some-container-id")))
cleanupDisplay.onEventPosted(TemporaryFileCreatedEvent(container, filePath))
}
on("and the container hasn't been removed yet") {
val output by runForEachTest { cleanupDisplay.print() }
it("prints that the container still needs to be cleaned up") {
assertThat(output, equivalentTo(Text.white(Text("Cleaning up: 1 container (") + Text.bold("some-container") + Text(") left to remove..."))))
}
}
on("and the container has been removed") {
beforeEachTest { cleanupDisplay.onEventPosted(ContainerRemovedEvent(container)) }
val output by runForEachTest { cleanupDisplay.print() }
it("prints that the network and file still needs to be cleaned up") {
assertThat(output, equivalentTo(Text.white("Cleaning up: removing task network and 1 temporary file...")))
}
}
on("and the network has been removed") {
beforeEachTest {
cleanupDisplay.onEventPosted(ContainerRemovedEvent(container))
cleanupDisplay.onEventPosted(TaskNetworkDeletedEvent)
}
val output by runForEachTest { cleanupDisplay.print() }
it("prints that the file still needs to be cleaned up") {
assertThat(output, equivalentTo(Text.white("Cleaning up: removing 1 temporary file...")))
}
}
on("and the temporary file has been removed") {
beforeEachTest {
cleanupDisplay.onEventPosted(ContainerRemovedEvent(container))
cleanupDisplay.onEventPosted(TemporaryFileDeletedEvent(filePath))
}
val output by runForEachTest { cleanupDisplay.print() }
it("prints that the network still needs to be cleaned up") {
assertThat(output, equivalentTo(Text.white("Cleaning up: removing task network...")))
}
}
on("and both the network and the temporary file has been removed") {
beforeEachTest {
cleanupDisplay.onEventPosted(ContainerRemovedEvent(container))
cleanupDisplay.onEventPosted(TemporaryFileDeletedEvent(filePath))
cleanupDisplay.onEventPosted(TaskNetworkDeletedEvent)
}
val output by runForEachTest { cleanupDisplay.print() }
it("prints that clean up is complete") {
assertThat(output, equivalentTo(Text.white("Clean up: done")))
}
}
}
describe("when there is a container, a temporary directory and the network to clean up") {
val container = Container("some-container", imageSourceDoesNotMatter())
val directoryPath = Paths.get("some-directory")
beforeEachTest {
cleanupDisplay.onEventPosted(TaskNetworkCreatedEvent(DockerNetwork("some-network")))
cleanupDisplay.onEventPosted(ContainerCreatedEvent(container, DockerContainer("some-container-id")))
cleanupDisplay.onEventPosted(TemporaryDirectoryCreatedEvent(container, directoryPath))
}
on("and the container hasn't been removed yet") {
val output by runForEachTest { cleanupDisplay.print() }
it("prints that the container still needs to be cleaned up") {
assertThat(output, equivalentTo(Text.white(Text("Cleaning up: 1 container (") + Text.bold("some-container") + Text(") left to remove..."))))
}
}
on("and the container has been removed") {
beforeEachTest { cleanupDisplay.onEventPosted(ContainerRemovedEvent(container)) }
val output by runForEachTest { cleanupDisplay.print() }
it("prints that the network and directory still needs to be cleaned up") {
assertThat(output, equivalentTo(Text.white("Cleaning up: removing task network and 1 temporary directory...")))
}
}
on("and the network has been removed") {
beforeEachTest {
cleanupDisplay.onEventPosted(ContainerRemovedEvent(container))
cleanupDisplay.onEventPosted(TaskNetworkDeletedEvent)
}
val output by runForEachTest { cleanupDisplay.print() }
it("prints that the directory still needs to be cleaned up") {
assertThat(output, equivalentTo(Text.white("Cleaning up: removing 1 temporary directory...")))
}
}
on("and the temporary directory has been removed") {
beforeEachTest {
cleanupDisplay.onEventPosted(ContainerRemovedEvent(container))
cleanupDisplay.onEventPosted(TemporaryDirectoryDeletedEvent(directoryPath))
}
val output by runForEachTest { cleanupDisplay.print() }
it("prints that the network still needs to be cleaned up") {
assertThat(output, equivalentTo(Text.white("Cleaning up: removing task network...")))
}
}
on("and both the network and the temporary directory has been removed") {
beforeEachTest {
cleanupDisplay.onEventPosted(ContainerRemovedEvent(container))
cleanupDisplay.onEventPosted(TemporaryDirectoryDeletedEvent(directoryPath))
cleanupDisplay.onEventPosted(TaskNetworkDeletedEvent)
}
val output by runForEachTest { cleanupDisplay.print() }
it("prints that clean up is complete") {
assertThat(output, equivalentTo(Text.white("Clean up: done")))
}
}
}
describe("when there is a container, two temporary files and the network to clean up") {
val container = Container("some-container", imageSourceDoesNotMatter())
val file1Path = Paths.get("file-1")
val file2Path = Paths.get("file-2")
beforeEachTest {
cleanupDisplay.onEventPosted(TaskNetworkCreatedEvent(DockerNetwork("some-network")))
cleanupDisplay.onEventPosted(ContainerCreatedEvent(container, DockerContainer("some-container-id")))
cleanupDisplay.onEventPosted(TemporaryFileCreatedEvent(container, file1Path))
cleanupDisplay.onEventPosted(TemporaryFileCreatedEvent(container, file2Path))
}
on("and the container hasn't been removed yet") {
val output by runForEachTest { cleanupDisplay.print() }
it("prints that the container still needs to be cleaned up") {
assertThat(output, equivalentTo(Text.white(Text("Cleaning up: 1 container (") + Text.bold("some-container") + Text(") left to remove..."))))
}
}
on("and the container has been removed") {
beforeEachTest {
cleanupDisplay.onEventPosted(ContainerRemovedEvent(container))
}
val output by runForEachTest { cleanupDisplay.print() }
it("prints that the network and both files still need to be cleaned up") {
assertThat(output, equivalentTo(Text.white("Cleaning up: removing task network and 2 temporary files...")))
}
}
on("and the network has been removed") {
beforeEachTest {
cleanupDisplay.onEventPosted(ContainerRemovedEvent(container))
cleanupDisplay.onEventPosted(TaskNetworkDeletedEvent)
}
val output by runForEachTest { cleanupDisplay.print() }
it("prints that the files still needs to be cleaned up") {
assertThat(output, equivalentTo(Text.white("Cleaning up: removing 2 temporary files...")))
}
}
on("and the network and one of the temporary files have been removed") {
beforeEachTest {
cleanupDisplay.onEventPosted(ContainerRemovedEvent(container))
cleanupDisplay.onEventPosted(TemporaryFileDeletedEvent(file1Path))
cleanupDisplay.onEventPosted(TaskNetworkDeletedEvent)
}
val output by runForEachTest { cleanupDisplay.print() }
it("prints that the files still needs to be cleaned up") {
assertThat(output, equivalentTo(Text.white("Cleaning up: removing 1 temporary file...")))
}
}
on("and the both temporary files have been removed") {
beforeEachTest {
cleanupDisplay.onEventPosted(ContainerRemovedEvent(container))
cleanupDisplay.onEventPosted(TemporaryFileDeletedEvent(file1Path))
cleanupDisplay.onEventPosted(TemporaryFileDeletedEvent(file2Path))
}
val output by runForEachTest { cleanupDisplay.print() }
it("prints that the network still needs to be cleaned up") {
assertThat(output, equivalentTo(Text.white("Cleaning up: removing task network...")))
}
}
on("and both the network and the temporary files has been removed") {
beforeEachTest {
cleanupDisplay.onEventPosted(ContainerRemovedEvent(container))
cleanupDisplay.onEventPosted(TemporaryFileDeletedEvent(file1Path))
cleanupDisplay.onEventPosted(TemporaryFileDeletedEvent(file2Path))
cleanupDisplay.onEventPosted(TaskNetworkDeletedEvent)
}
val output by runForEachTest { cleanupDisplay.print() }
it("prints that clean up is complete") {
assertThat(output, equivalentTo(Text.white("Clean up: done")))
}
}
}
describe("when there is a container, two temporary directories and the network to clean up") {
val container = Container("some-container", imageSourceDoesNotMatter())
val directory1Path = Paths.get("directory-1")
val directory2Path = Paths.get("directory-2")
beforeEachTest {
cleanupDisplay.onEventPosted(TaskNetworkCreatedEvent(DockerNetwork("some-network")))
cleanupDisplay.onEventPosted(ContainerCreatedEvent(container, DockerContainer("some-container-id")))
cleanupDisplay.onEventPosted(TemporaryDirectoryCreatedEvent(container, directory1Path))
cleanupDisplay.onEventPosted(TemporaryDirectoryCreatedEvent(container, directory2Path))
}
on("and the container hasn't been removed yet") {
val output by runForEachTest { cleanupDisplay.print() }
it("prints that the container still needs to be cleaned up") {
assertThat(output, equivalentTo(Text.white(Text("Cleaning up: 1 container (") + Text.bold("some-container") + Text(") left to remove..."))))
}
}
on("and the container has been removed") {
beforeEachTest { cleanupDisplay.onEventPosted(ContainerRemovedEvent(container)) }
val output by runForEachTest { cleanupDisplay.print() }
it("prints that the network and both directories still need to be cleaned up") {
assertThat(output, equivalentTo(Text.white("Cleaning up: removing task network and 2 temporary directories...")))
}
}
on("and the network has been removed") {
beforeEachTest {
cleanupDisplay.onEventPosted(ContainerRemovedEvent(container))
cleanupDisplay.onEventPosted(TaskNetworkDeletedEvent)
}
val output by runForEachTest { cleanupDisplay.print() }
it("prints that the directories still needs to be cleaned up") {
assertThat(output, equivalentTo(Text.white("Cleaning up: removing 2 temporary directories...")))
}
}
on("and the network and one of the temporary directories have been removed") {
beforeEachTest {
cleanupDisplay.onEventPosted(ContainerRemovedEvent(container))
cleanupDisplay.onEventPosted(TemporaryDirectoryDeletedEvent(directory1Path))
cleanupDisplay.onEventPosted(TaskNetworkDeletedEvent)
}
val output by runForEachTest { cleanupDisplay.print() }
it("prints that the directories still needs to be cleaned up") {
assertThat(output, equivalentTo(Text.white("Cleaning up: removing 1 temporary directory...")))
}
}
on("and both temporary directories have been removed") {
beforeEachTest {
cleanupDisplay.onEventPosted(ContainerRemovedEvent(container))
cleanupDisplay.onEventPosted(TemporaryDirectoryDeletedEvent(directory1Path))
cleanupDisplay.onEventPosted(TemporaryDirectoryDeletedEvent(directory2Path))
}
val output by runForEachTest { cleanupDisplay.print() }
it("prints that the network still needs to be cleaned up") {
assertThat(output, equivalentTo(Text.white("Cleaning up: removing task network...")))
}
}
on("and both the network and the temporary directories have been removed") {
beforeEachTest {
cleanupDisplay.onEventPosted(ContainerRemovedEvent(container))
cleanupDisplay.onEventPosted(TemporaryDirectoryDeletedEvent(directory1Path))
cleanupDisplay.onEventPosted(TemporaryDirectoryDeletedEvent(directory2Path))
cleanupDisplay.onEventPosted(TaskNetworkDeletedEvent)
}
val output by runForEachTest { cleanupDisplay.print() }
it("prints that clean up is complete") {
assertThat(output, equivalentTo(Text.white("Clean up: done")))
}
}
}
describe("when there is a container, a temporary file, a temporary directory and the network to clean up") {
val container = Container("some-container", imageSourceDoesNotMatter())
val filePath = Paths.get("some-file")
val directoryPath = Paths.get("some-directory")
beforeEachTest {
cleanupDisplay.onEventPosted(TaskNetworkCreatedEvent(DockerNetwork("some-network")))
cleanupDisplay.onEventPosted(ContainerCreatedEvent(container, DockerContainer("some-container-id")))
cleanupDisplay.onEventPosted(TemporaryFileCreatedEvent(container, filePath))
cleanupDisplay.onEventPosted(TemporaryDirectoryCreatedEvent(container, directoryPath))
}
on("and the container hasn't been removed yet") {
val output by runForEachTest { cleanupDisplay.print() }
it("prints that the container still needs to be cleaned up") {
assertThat(output, equivalentTo(Text.white(Text("Cleaning up: 1 container (") + Text.bold("some-container") + Text(") left to remove..."))))
}
}
on("and the container has been removed") {
beforeEachTest {
cleanupDisplay.onEventPosted(ContainerRemovedEvent(container))
}
val output by runForEachTest { cleanupDisplay.print() }
it("prints that the network and both directories still need to be cleaned up") {
assertThat(output, equivalentTo(Text.white("Cleaning up: removing task network, 1 temporary file and 1 temporary directory...")))
}
}
on("and the network has been removed") {
beforeEachTest {
cleanupDisplay.onEventPosted(ContainerRemovedEvent(container))
cleanupDisplay.onEventPosted(TaskNetworkDeletedEvent)
}
val output by runForEachTest { cleanupDisplay.print() }
it("prints that the directories still needs to be cleaned up") {
assertThat(output, equivalentTo(Text.white("Cleaning up: removing 1 temporary file and 1 temporary directory...")))
}
}
on("and the network and the temporary file have been removed") {
beforeEachTest {
cleanupDisplay.onEventPosted(ContainerRemovedEvent(container))
cleanupDisplay.onEventPosted(TemporaryFileDeletedEvent(filePath))
cleanupDisplay.onEventPosted(TaskNetworkDeletedEvent)
}
val output by runForEachTest { cleanupDisplay.print() }
it("prints that the directory still needs to be cleaned up") {
assertThat(output, equivalentTo(Text.white("Cleaning up: removing 1 temporary directory...")))
}
}
on("and the network and the temporary directory have been removed") {
beforeEachTest {
cleanupDisplay.onEventPosted(ContainerRemovedEvent(container))
cleanupDisplay.onEventPosted(TemporaryDirectoryDeletedEvent(directoryPath))
cleanupDisplay.onEventPosted(TaskNetworkDeletedEvent)
}
val output by runForEachTest { cleanupDisplay.print() }
it("prints that the file still needs to be cleaned up") {
assertThat(output, equivalentTo(Text.white("Cleaning up: removing 1 temporary file...")))
}
}
on("and the temporary file and temporary directory have been removed") {
beforeEachTest {
cleanupDisplay.onEventPosted(ContainerRemovedEvent(container))
cleanupDisplay.onEventPosted(TemporaryFileDeletedEvent(filePath))
cleanupDisplay.onEventPosted(TemporaryDirectoryDeletedEvent(directoryPath))
}
val output by runForEachTest { cleanupDisplay.print() }
it("prints that the network still needs to be cleaned up") {
assertThat(output, equivalentTo(Text.white("Cleaning up: removing task network...")))
}
}
on("and both the network, the temporary file and the temporary directory have been removed") {
beforeEachTest {
cleanupDisplay.onEventPosted(ContainerRemovedEvent(container))
cleanupDisplay.onEventPosted(TemporaryFileDeletedEvent(filePath))
cleanupDisplay.onEventPosted(TemporaryDirectoryDeletedEvent(directoryPath))
cleanupDisplay.onEventPosted(TaskNetworkDeletedEvent)
}
val output by runForEachTest { cleanupDisplay.print() }
it("prints that clean up is complete") {
assertThat(output, equivalentTo(Text.white("Clean up: done")))
}
}
}
describe("when there are two containers and the network to clean up") {
val container1 = Container("container-1", imageSourceDoesNotMatter())
val container2 = Container("container-2", imageSourceDoesNotMatter())
beforeEachTest {
cleanupDisplay.onEventPosted(TaskNetworkCreatedEvent(DockerNetwork("some-network")))
cleanupDisplay.onEventPosted(ContainerCreatedEvent(container1, DockerContainer("container-1-id")))
cleanupDisplay.onEventPosted(ContainerCreatedEvent(container2, DockerContainer("container-2-id")))
}
on("and neither container has been removed yet") {
val output by runForEachTest { cleanupDisplay.print() }
it("prints that both of the containers still need to be cleaned up") {
assertThat(output, equivalentTo(Text.white(Text("Cleaning up: 2 containers (") + Text.bold("container-1") + Text(" and ") + Text.bold("container-2") + Text(") left to remove..."))))
}
}
on("and one container has been removed") {
beforeEachTest { cleanupDisplay.onEventPosted(ContainerRemovedEvent(container1)) }
val output by runForEachTest { cleanupDisplay.print() }
it("prints that the other container still needs to be cleaned up") {
assertThat(output, equivalentTo(Text.white(Text("Cleaning up: 1 container (") + Text.bold("container-2") + Text(") left to remove..."))))
}
}
on("and the network has been removed") {
beforeEachTest {
cleanupDisplay.onEventPosted(ContainerRemovedEvent(container1))
cleanupDisplay.onEventPosted(ContainerRemovedEvent(container2))
cleanupDisplay.onEventPosted(TaskNetworkDeletedEvent)
}
val output by runForEachTest { cleanupDisplay.print() }
it("prints that clean up is complete") {
assertThat(output, equivalentTo(Text.white("Clean up: done")))
}
}
}
describe("when there are three containers and the network to clean up") {
val container1 = Container("container-1", imageSourceDoesNotMatter())
val container2 = Container("container-2", imageSourceDoesNotMatter())
val container3 = Container("container-3", imageSourceDoesNotMatter())
beforeEachTest {
cleanupDisplay.onEventPosted(TaskNetworkCreatedEvent(DockerNetwork("some-network")))
cleanupDisplay.onEventPosted(ContainerCreatedEvent(container1, DockerContainer("container-1-id")))
cleanupDisplay.onEventPosted(ContainerCreatedEvent(container2, DockerContainer("container-2-id")))
cleanupDisplay.onEventPosted(ContainerCreatedEvent(container3, DockerContainer("container-3-id")))
}
on("and none of the containers have been removed yet") {
val output by runForEachTest { cleanupDisplay.print() }
it("prints that all of the containers still need to be cleaned up") {
assertThat(output, equivalentTo(Text.white(Text("Cleaning up: 3 containers (") + Text.bold("container-1") + Text(", ") + Text.bold("container-2") + Text(" and ") + Text.bold("container-3") + Text(") left to remove..."))))
}
}
}
describe("when there are four containers and the network to clean up") {
val container1 = Container("container-1", imageSourceDoesNotMatter())
val container2 = Container("container-2", imageSourceDoesNotMatter())
val container3 = Container("container-3", imageSourceDoesNotMatter())
val container4 = Container("container-4", imageSourceDoesNotMatter())
beforeEachTest {
cleanupDisplay.onEventPosted(TaskNetworkCreatedEvent(DockerNetwork("some-network")))
cleanupDisplay.onEventPosted(ContainerCreatedEvent(container1, DockerContainer("container-1-id")))
cleanupDisplay.onEventPosted(ContainerCreatedEvent(container2, DockerContainer("container-2-id")))
cleanupDisplay.onEventPosted(ContainerCreatedEvent(container3, DockerContainer("container-3-id")))
cleanupDisplay.onEventPosted(ContainerCreatedEvent(container4, DockerContainer("container-4-id")))
}
on("and none of the containers have been removed yet") {
val output by runForEachTest { cleanupDisplay.print() }
it("prints that all of the containers still need to be cleaned up") {
assertThat(
output,
equivalentTo(Text.white(Text("Cleaning up: 4 containers (") + Text.bold("container-1") + Text(", ") + Text.bold("container-2") + Text(", ") + Text.bold("container-3") + Text(" and ") + Text.bold("container-4") + Text(") left to remove...")))
)
}
}
}
}
}
})
| apache-2.0 | 1b4dc57379a82d4eb40a53f47a51a151 | 50.301917 | 269 | 0.575121 | 6.33807 | false | true | false | false |
codebutler/odyssey | retrograde-app-shared/src/main/java/com/codebutler/retrograde/lib/game/display/gl/GlGameDisplay.kt | 1 | 2491 | /*
* GameGlSurfaceView.kt
*
* Copyright (C) 2017 Retrograde Project
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.codebutler.retrograde.lib.game.display.gl
import android.content.Context
import android.graphics.Bitmap
import android.opengl.GLSurfaceView
import android.view.Choreographer
import androidx.lifecycle.LifecycleOwner
import com.codebutler.retrograde.lib.game.display.FpsCalculator
import com.codebutler.retrograde.lib.game.display.GameDisplay
class GlGameDisplay(context: Context) :
GameDisplay,
Choreographer.FrameCallback {
private val glSurfaceView = GLSurfaceView(context)
private val fpsCalculator = FpsCalculator()
private val renderer: GlRenderer2d
init {
// Create an OpenGL ES 2.0 context.
glSurfaceView.setEGLContextClientVersion(2)
// Set the Renderer for drawing on the GLSurfaceView
renderer = GlRenderer2d()
glSurfaceView.setRenderer(renderer)
// Render the view only when there is a change in the drawing data
glSurfaceView.renderMode = GLSurfaceView.RENDERMODE_WHEN_DIRTY
renderer.callback = {
fpsCalculator.update()
}
}
override val view = glSurfaceView
override val fps: Long
get() = fpsCalculator.fps
override fun update(bitmap: Bitmap) {
renderer.setBitmap(bitmap)
}
override fun onResume(owner: LifecycleOwner) {
Choreographer.getInstance().postFrameCallback(this)
}
override fun onPause(owner: LifecycleOwner) {
Choreographer.getInstance().removeFrameCallback(this)
}
override fun onDestroy(owner: LifecycleOwner) {
Choreographer.getInstance().removeFrameCallback(this)
}
override fun doFrame(frameTimeNanos: Long) {
Choreographer.getInstance().postFrameCallback(this)
view.requestRender()
}
}
| gpl-3.0 | 22295f7b814ada2e3cf73b919103259d | 30.531646 | 74 | 0.720594 | 4.595941 | false | false | false | false |
bibaev/stream-debugger-plugin | src/main/java/com/intellij/debugger/streams/trace/dsl/impl/CodeBlockBase.kt | 1 | 3445 | /*
* Copyright 2000-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.debugger.streams.trace.dsl.impl
import com.intellij.debugger.streams.trace.dsl.*
/**
* @author Vitaliy.Bibaev
*/
abstract class CodeBlockBase(private val myFactory: StatementFactory) : CompositeCodeBlock {
private val myStatements: MutableList<Convertable> = mutableListOf()
override val size: Int
get() = myStatements.size
override fun Statement.unaryPlus() {
myStatements.add(this)
}
override fun statement(statement: () -> Statement) {
myStatements.add(statement.invoke())
}
override fun declare(variable: Variable, isMutable: Boolean): Variable =
declare(myFactory.createVariableDeclaration(variable, isMutable))
override fun declare(variable: Variable, init: Expression, isMutable: Boolean): Variable =
declare(myFactory.createVariableDeclaration(variable, init, isMutable))
override fun declare(declaration: VariableDeclaration): Variable {
addStatement(declaration)
return declaration.variable
}
override fun forLoop(initialization: VariableDeclaration, condition: Expression, afterThought: Expression, init: ForLoopBody.() -> Unit) {
val loopBody = myFactory.createEmptyForLoopBody(initialization.variable)
loopBody.init()
addStatement(myFactory.createForLoop(initialization, condition, afterThought, loopBody))
}
override fun tryBlock(init: CodeBlock.() -> Unit): TryBlock {
val codeBlock = myFactory.createEmptyCodeBlock()
codeBlock.init()
val tryBlock = myFactory.createTryBlock(codeBlock)
myStatements.add(tryBlock)
return tryBlock
}
override fun ifBranch(condition: Expression, init: CodeBlock.() -> Unit): IfBranch {
val ifBody = myFactory.createEmptyCodeBlock()
ifBody.init()
val branch = myFactory.createIfBranch(condition, ifBody)
addStatement(branch)
return branch
}
override fun call(receiver: Expression, methodName: String, vararg args: Expression): Expression {
val call = receiver.call(methodName, *args)
addStatement(call)
return call
}
override fun forEachLoop(iterateVariable: Variable, collection: Expression, init: ForLoopBody.() -> Unit) {
val loopBody = myFactory.createEmptyForLoopBody(iterateVariable)
loopBody.init()
addStatement(myFactory.createForEachLoop(iterateVariable, collection, loopBody))
}
override fun scope(init: CodeBlock.() -> Unit) {
val codeBlock = myFactory.createEmptyCodeBlock()
codeBlock.init()
addStatement(myFactory.createScope(codeBlock))
}
override fun Variable.assign(expression: Expression) {
val assignmentStatement = myFactory.createAssignmentStatement(this, expression)
addStatement(assignmentStatement)
}
override fun addStatement(statement: Convertable) {
myStatements += statement
}
override fun getStatements(): List<Convertable> = ArrayList(myStatements)
} | apache-2.0 | 80b7e0d17e943a94046bfc6c9db0c044 | 34.525773 | 140 | 0.749492 | 4.491525 | false | false | false | false |
qikh/mini-block-chain | src/main/kotlin/mbc/util/CryptoUtil.kt | 1 | 4481 | package mbc.util
import mbc.core.Block
import mbc.core.Transaction
import mbc.trie.Trie
import org.spongycastle.crypto.params.ECDomainParameters
import org.spongycastle.jcajce.provider.asymmetric.ec.BCECPrivateKey
import org.spongycastle.jce.ECNamedCurveTable
import org.spongycastle.jce.provider.BouncyCastleProvider
import org.spongycastle.jce.spec.ECPublicKeySpec
import java.security.*
import java.security.Security.insertProviderAt
import java.security.interfaces.ECPublicKey
import java.security.spec.ECGenParameterSpec
import java.security.spec.PKCS8EncodedKeySpec
import java.security.spec.X509EncodedKeySpec
/**
* 密码学工具类。
*/
class CryptoUtil {
companion object {
init {
insertProviderAt(BouncyCastleProvider(), 1)
}
/**
* 根据公钥(public key)推算出账户地址,使用以太坊的算法,先KECCAK-256计算哈希值(32位),取后20位作为账户地址。
* 比特币地址算法:http://www.infoq.com/cn/articles/bitcoin-and-block-chain-part03
* 以太坊地址算法:http://ethereum.stackexchange.com/questions/3542/how-are-ethereum-addresses-generated
*/
fun generateAddress(publicKey: PublicKey): ByteArray {
val digest = MessageDigest.getInstance("KECCAK-256", "SC")
digest.update(publicKey.encoded)
val hash = digest.digest()
return hash.drop(12).toByteArray()
}
/**
* 生成公私钥对,使用以太坊的ECDSA算法(secp256k1)。
*/
fun generateKeyPair(): KeyPair? {
val gen = KeyPairGenerator.getInstance("EC", "SC")
gen.initialize(ECGenParameterSpec("secp256k1"), SecureRandom())
val keyPair = gen.generateKeyPair()
return keyPair
}
/**
* 发送方用私钥对交易Transaction进行签名。
*/
fun signTransaction(trx: Transaction, privateKey: PrivateKey): ByteArray {
val signer = Signature.getInstance("SHA256withECDSA")
signer.initSign(privateKey)
val msgToSign = CodecUtil.encodeTransactionWithoutSignatureToAsn1(trx).encoded
signer.update(msgToSign)
return signer.sign()
}
/**
* 验证交易Transaction签名的有效性。
*/
fun verifyTransactionSignature(trx: Transaction, signature: ByteArray): Boolean {
val signer = Signature.getInstance("SHA256withECDSA")
signer.initVerify(trx.publicKey)
signer.update(CodecUtil.encodeTransactionWithoutSignatureToAsn1(trx).encoded)
return signer.verify(signature)
}
/**
* 运算区块的哈希值。
*/
fun hashBlock(block: Block): ByteArray {
val digest = MessageDigest.getInstance("KECCAK-256", "SC")
digest.update(block.encode())
return digest.digest()
}
/**
* 计算Merkle Root Hash
*/
fun merkleRoot(transactions: List<Transaction>): ByteArray {
val trxTrie = Trie<Transaction>()
for (i in 0 until transactions.size) {
trxTrie.put(i.toString(), transactions[i])
}
return trxTrie.root?.hash() ?: ByteArray(0)
}
/**
* SHA-256
*/
fun sha256(msg: ByteArray): ByteArray {
val digest = MessageDigest.getInstance("SHA-256", "SC")
digest.update(msg)
val hash = digest.digest()
return hash
}
/**
* SHA3
*/
fun sha3(msg: ByteArray): ByteArray {
return sha256((msg))
}
fun deserializePrivateKey(bytes: ByteArray): PrivateKey {
val kf = KeyFactory.getInstance("EC", "SC")
return kf.generatePrivate(PKCS8EncodedKeySpec(bytes))
}
fun deserializePublicKey(bytes: ByteArray): PublicKey {
val kf = KeyFactory.getInstance("EC", "SC")
return kf.generatePublic(X509EncodedKeySpec(bytes))
}
/**
* 从PrivateKey计算出PublicKey,参考了以太坊的代码和http://stackoverflow.com/questions/26159149/how-can-i-default-a-publickey-object-from-ec-public-key-bytes
*/
fun generatePublicKey(privateKey: PrivateKey): PublicKey? {
val spec = ECNamedCurveTable.getParameterSpec("secp256k1")
val kf = KeyFactory.getInstance("EC", "SC")
val curve = ECDomainParameters(spec.curve, spec.g, spec.n, spec.h)
if (privateKey is BCECPrivateKey) {
val d = privateKey.d
val point = curve.g.multiply(d)
val pubKeySpec = ECPublicKeySpec(point, spec)
val publicKey = kf.generatePublic(pubKeySpec) as ECPublicKey
return publicKey
} else {
return null
}
}
}
}
| apache-2.0 | b91e7fad791e6f55e544ac03ede2955c | 28.326389 | 146 | 0.681269 | 3.723986 | false | false | false | false |
minecraft-dev/MinecraftDev | src/main/kotlin/platform/mixin/action/GenerateAccessorAction.kt | 1 | 2722 | /*
* Minecraft Dev for IntelliJ
*
* https://minecraftdev.org
*
* Copyright (c) 2022 minecraft-dev
*
* MIT License
*/
package com.demonwav.mcdev.platform.mixin.action
import com.intellij.codeInsight.FileModificationService
import com.intellij.codeInsight.generation.actions.BaseGenerateAction
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.command.CommandProcessor
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.editor.EditorModificationUtil
import com.intellij.openapi.editor.actionSystem.DocCommandGroupId
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiFile
import com.intellij.psi.PsiJavaFile
import com.intellij.psi.util.PsiUtilBase
class GenerateAccessorAction : BaseGenerateAction(GenerateAccessorHandler()) {
/**
* Copied from [com.intellij.codeInsight.actions.CodeInsightAction.actionPerformedImpl]
* except that it calls the [GenerateAccessorHandler.customInvoke] method instead of the normal one
*/
override fun actionPerformedImpl(project: Project, editor: Editor?) {
if (editor == null) {
return
}
val psiFile = PsiUtilBase.getPsiFileInEditor(editor, project) ?: return
val handler = this.handler as GenerateAccessorHandler
val elementToMakeWritable = handler.getElementToMakeWritable(psiFile)
if (elementToMakeWritable != null) {
if (!EditorModificationUtil.checkModificationAllowed(editor) ||
!FileModificationService.getInstance().preparePsiElementsForWrite(elementToMakeWritable)
) {
return
}
}
CommandProcessor.getInstance().executeCommand(
project,
{
val action = Runnable {
if (ApplicationManager.getApplication().isHeadlessEnvironment ||
editor.contentComponent.isShowing
) {
handler.customInvoke(project, editor, psiFile)
}
}
if (handler.startInWriteAction()) {
ApplicationManager.getApplication().runWriteAction(action)
} else {
action.run()
}
},
commandName,
DocCommandGroupId.noneGroupId(editor.document),
editor.document
)
}
override fun isValidForFile(project: Project, editor: Editor, file: PsiFile): Boolean {
if (file !is PsiJavaFile) {
return false
}
val targetClass = getTargetClass(editor, file)
return targetClass != null && isValidForClass(targetClass)
}
}
| mit | 9fc9c9cbaf2d1145ed2d43d2b95603b1 | 35.293333 | 104 | 0.653564 | 5.337255 | false | false | false | false |
InfiniteSoul/ProxerAndroid | src/main/kotlin/me/proxer/app/notification/AccountNotifications.kt | 1 | 4192 | package me.proxer.app.notification
import android.app.Notification
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import androidx.core.app.NotificationCompat
import androidx.core.app.NotificationManagerCompat
import androidx.core.content.ContextCompat
import androidx.core.text.parseAsHtml
import me.proxer.app.R
import me.proxer.app.util.NotificationUtils.PROFILE_CHANNEL
import me.proxer.app.util.data.StorageHelper
import me.proxer.app.util.extension.ProxerNotification
import me.proxer.app.util.extension.androidUri
import me.proxer.app.util.extension.getQuantityString
import me.proxer.app.util.extension.safeInject
import me.proxer.app.util.extension.toInstantBP
import org.koin.core.KoinComponent
/**
* @author Ruben Gees
*/
object AccountNotifications : KoinComponent {
private const val ID = 759_234_852
private val storageHelper by safeInject<StorageHelper>()
fun showOrUpdate(context: Context, notifications: Collection<ProxerNotification>) {
when (val notification = buildNotification(context, notifications)) {
null -> NotificationManagerCompat.from(context).cancel(ID)
else -> NotificationManagerCompat.from(context).notify(ID, notification)
}
}
fun cancel(context: Context) = NotificationManagerCompat.from(context).cancel(ID)
private fun buildNotification(context: Context, notifications: Collection<ProxerNotification>): Notification? {
if (notifications.isEmpty()) {
return null
}
val builder = NotificationCompat.Builder(context, PROFILE_CHANNEL)
val notificationAmount = context.getQuantityString(R.plurals.notification_account_amount, notifications.size)
val title = context.getString(R.string.notification_account_title)
val style: NotificationCompat.Style
val intent: PendingIntent
val content: CharSequence
when (notifications.size) {
1 -> {
content = notifications.first().text.parseAsHtml()
intent = PendingIntent.getActivity(
context, ID,
Intent(Intent.ACTION_VIEW, notifications.first().contentLink.androidUri()),
PendingIntent.FLAG_UPDATE_CURRENT
)
style = NotificationCompat.BigTextStyle(builder)
.bigText(content)
.setBigContentTitle(title)
.setSummaryText(notificationAmount)
}
else -> {
content = notificationAmount
intent = PendingIntent.getActivity(
context, ID,
NotificationActivity.getIntent(context),
PendingIntent.FLAG_UPDATE_CURRENT
)
style = NotificationCompat.InboxStyle().also {
notifications.forEach { notification ->
it.addLine(notification.text.parseAsHtml())
}
it.setBigContentTitle(title)
it.setSummaryText(notificationAmount)
}
}
}
val shouldAlert = notifications
.maxBy { it.date }
?.date?.toInstantBP()
?.isAfter(storageHelper.lastNotificationsDate)
?: true
return builder.setAutoCancel(true)
.setSmallIcon(R.drawable.ic_stat_proxer)
.setContentTitle(title)
.setContentText(content)
.setContentIntent(intent)
.addAction(
R.drawable.ic_stat_check, context.getString(R.string.notification_account_read_action),
AccountNotificationReadReceiver.getPendingIntent(context)
)
.setDefaults(if (shouldAlert) Notification.DEFAULT_ALL else 0)
.setColor(ContextCompat.getColor(context, R.color.primary))
.setPriority(NotificationCompat.PRIORITY_DEFAULT)
.setCategory(NotificationCompat.CATEGORY_SOCIAL)
.setNumber(notifications.size)
.setOnlyAlertOnce(true)
.setStyle(style)
.build()
}
}
| gpl-3.0 | 5458e6fd8726de6cba06a6e4ded23b20 | 37.109091 | 117 | 0.643368 | 5.292929 | false | false | false | false |
kenrube/Fantlab-client | app/src/main/kotlin/ru/fantlab/android/ui/adapter/viewholder/ForumsParentViewHolder.kt | 2 | 1482 | package ru.fantlab.android.ui.adapter.viewholder
import android.view.View
import android.widget.ImageView
import android.widget.TextView
import androidx.core.view.isVisible
import androidx.recyclerview.widget.RecyclerView
import kotlinx.android.synthetic.main.forums_parent_row_item.view.*
import ru.fantlab.android.R
import ru.fantlab.android.data.dao.model.ForumsTreeParent
import ru.fantlab.android.ui.widgets.treeview.TreeNode
import ru.fantlab.android.ui.widgets.treeview.TreeViewAdapter
import ru.fantlab.android.ui.widgets.treeview.TreeViewBinder
class ForumsParentViewHolder : TreeViewBinder<ForumsParentViewHolder.ViewHolder>() {
override val layoutId: Int = R.layout.forums_parent_row_item
override fun provideViewHolder(itemView: View): ViewHolder = ViewHolder(itemView)
override fun bindView(
holder: RecyclerView.ViewHolder, position: Int, node: TreeNode<*>, onTreeNodeListener: TreeViewAdapter.OnTreeNodeListener?
) {
(holder as ViewHolder).expandButton.rotation = 0f
holder.expandButton.setImageResource(R.drawable.ic_arrow_right)
val rotateDegree = if (node.isExpand) 90f else 0f
holder.expandButton.rotation = rotateDegree
val parentNode = node.content as ForumsTreeParent?
holder.title.text = parentNode!!.title
holder.expandButton.isVisible = !node.isLeaf
}
class ViewHolder(rootView: View) : TreeViewBinder.ViewHolder(rootView) {
val expandButton: ImageView = rootView.expandButton
var title: TextView = rootView.forumTitle
}
}
| gpl-3.0 | e561a85e70d3f7a4c515fa07b1862750 | 39.054054 | 125 | 0.811741 | 3.859375 | false | false | false | false |
kenrube/Fantlab-client | app/src/main/kotlin/ru/fantlab/android/ui/adapter/viewholder/SearchEditionsViewHolder.kt | 2 | 1891 | package ru.fantlab.android.ui.adapter.viewholder
import android.net.Uri
import android.view.View
import android.view.ViewGroup
import kotlinx.android.synthetic.main.search_editions_row_item.view.*
import ru.fantlab.android.R
import ru.fantlab.android.data.dao.model.SearchEdition
import ru.fantlab.android.provider.scheme.LinkParserHelper.HOST_DATA
import ru.fantlab.android.provider.scheme.LinkParserHelper.PROTOCOL_HTTPS
import ru.fantlab.android.ui.widgets.CoverLayout
import ru.fantlab.android.ui.widgets.FontTextView
import ru.fantlab.android.ui.widgets.recyclerview.BaseRecyclerAdapter
import ru.fantlab.android.ui.widgets.recyclerview.BaseViewHolder
class SearchEditionsViewHolder(itemView: View, adapter: BaseRecyclerAdapter<SearchEdition, SearchEditionsViewHolder>)
: BaseViewHolder<SearchEdition>(itemView, adapter) {
override fun bind(edition: SearchEdition) {
itemView.coverLayout.setUrl(Uri.Builder().scheme(PROTOCOL_HTTPS)
.authority(HOST_DATA)
.appendPath("images")
.appendPath("editions")
.appendPath("big")
.appendPath(edition.id.toString())
.toString())
if (edition.authors.isNotEmpty()) {
itemView.authors.text = edition.authors.replace(ANY_CHARACTERS_IN_BRACKETS_REGEX, "")
itemView.authors.visibility = View.VISIBLE
} else {
itemView.authors.visibility = View.GONE
}
itemView.title.text = edition.name.replace(ANY_CHARACTERS_IN_BRACKETS_REGEX, "")
if (edition.year.isNotEmpty()) {
itemView.year.text = edition.year
} else {
itemView.year.visibility = View.GONE
}
}
companion object {
private val ANY_CHARACTERS_IN_BRACKETS_REGEX = "\\[.*?]".toRegex()
fun newInstance(
viewGroup: ViewGroup,
adapter: BaseRecyclerAdapter<SearchEdition, SearchEditionsViewHolder>
): SearchEditionsViewHolder =
SearchEditionsViewHolder(getView(viewGroup, R.layout.search_editions_row_item), adapter)
}
} | gpl-3.0 | 928387e7da03fee352648bb1e55484b2 | 33.4 | 117 | 0.77578 | 3.759443 | false | false | false | false |
ohmae/DmsExplorer | mobile/src/debug/java/net/mm2d/dmsexplorer/DebugApp.kt | 1 | 3717 | /*
* Copyright (c) 2019 大前良介 (OHMAE Ryosuke)
*
* This software is released under the MIT License.
* http://opensource.org/licenses/MIT
*/
package net.mm2d.dmsexplorer
import android.os.Build
import android.os.StrictMode
import android.os.StrictMode.ThreadPolicy
import android.os.StrictMode.VmPolicy
import android.util.Log
import com.facebook.flipper.android.AndroidFlipperClient
import com.facebook.flipper.android.utils.FlipperUtils
import com.facebook.flipper.plugins.crashreporter.CrashReporterPlugin
import com.facebook.flipper.plugins.databases.DatabasesFlipperPlugin
import com.facebook.flipper.plugins.inspector.DescriptorMapping
import com.facebook.flipper.plugins.inspector.InspectorFlipperPlugin
import com.facebook.flipper.plugins.leakcanary2.FlipperLeakListener
import com.facebook.flipper.plugins.leakcanary2.LeakCanary2FlipperPlugin
import com.facebook.flipper.plugins.navigation.NavigationFlipperPlugin
import com.facebook.flipper.plugins.network.NetworkFlipperPlugin
import com.facebook.flipper.plugins.sharedpreferences.SharedPreferencesFlipperPlugin
import com.facebook.soloader.SoLoader
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import leakcanary.LeakCanary
import net.mm2d.log.DefaultSender
import net.mm2d.log.Logger
@Suppress("unused")
class DebugApp : App() {
override fun initializeOverrideWhenDebug() {
setUpLogger()
setUpStrictMode()
setUpFlipper()
}
private fun setUpLogger() {
Logger.setLogLevel(Logger.DEBUG)
Logger.setSender(DefaultSender.create { level, tag, message ->
GlobalScope.launch(Dispatchers.Main) {
message.split("\n").forEach {
Log.println(level, tag, it)
}
}
})
DefaultSender.appendThread(true)
}
private fun setUpStrictMode() {
StrictMode.setThreadPolicy(makeThreadPolicy())
StrictMode.setVmPolicy(makeVmPolicy())
}
private fun makeThreadPolicy(): ThreadPolicy = ThreadPolicy.Builder().apply {
detectAll()
penaltyLog()
penaltyDeathOnNetwork()
}.build()
private fun makeVmPolicy(): VmPolicy = VmPolicy.Builder().apply {
penaltyLog()
detectActivityLeaks()
detectLeakedClosableObjects()
detectLeakedRegistrationObjects()
detectFileUriExposure()
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
detectCleartextNetwork()
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
penaltyDeathOnFileUriExposure()
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
detectContentUriWithoutPermission()
//detectUntaggedSockets()
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
detectCredentialProtectedWhileLocked()
}
}.build()
private fun setUpFlipper() {
LeakCanary.config = LeakCanary.config.copy(
onHeapAnalyzedListener = FlipperLeakListener()
)
SoLoader.init(this, false)
if (!FlipperUtils.shouldEnableFlipper(this)) return
val client = AndroidFlipperClient.getInstance(this)
client.addPlugin(InspectorFlipperPlugin(this, DescriptorMapping.withDefaults()))
client.addPlugin(NavigationFlipperPlugin.getInstance())
client.addPlugin(NetworkFlipperPlugin())
client.addPlugin(DatabasesFlipperPlugin(this))
client.addPlugin(SharedPreferencesFlipperPlugin(this))
client.addPlugin(LeakCanary2FlipperPlugin())
client.addPlugin(CrashReporterPlugin.getInstance())
client.start()
}
}
| mit | 389727b2c97dcf465d59566371803e1e | 35.362745 | 88 | 0.713939 | 4.590347 | false | false | false | false |
JavaEden/Orchid | OrchidTest/src/test/kotlin/com/eden/orchid/impl/themes/assets/TestAssetDownloading.kt | 2 | 7796 | package com.eden.orchid.impl.themes.assets
import com.eden.orchid.strikt.asExpected
import com.eden.orchid.strikt.htmlBodyMatches
import com.eden.orchid.strikt.htmlHeadMatches
import com.eden.orchid.strikt.pageWasNotRendered
import com.eden.orchid.strikt.pageWasRendered
import com.eden.orchid.testhelpers.OrchidIntegrationTest
import kotlinx.html.div
import kotlinx.html.link
import kotlinx.html.script
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.DisplayName
import org.junit.jupiter.api.Test
import strikt.assertions.isEqualTo
class TestAssetDownloading : OrchidIntegrationTest(
TestAssetsModule()
) {
@BeforeEach
fun setUp() {
TestAssetsModule.addNormalAssetsToTest(this)
flag("logLevel", "FATAL")
}
@Test
@DisplayName("Test external assets not downloaded in dev environment")
fun test01() {
flag("environment", "dev")
configObject(
"site",
"""
|{
| "theme": "${TestAssetTheme.KEY}"
|}
""".trimMargin()
)
configObject(
"allPages",
"""
|{
| "components": [
| {"type": "pageContent", "noWrapper": false}
| ],
| "extraCss": [
| "https://copper-leaf.github.io/test-downloadable-assets/assets/css/style.css"
| ],
| "extraJs": [
| "https://copper-leaf.github.io/test-downloadable-assets/assets/js/scripts.js"
| ]
|}
""".trimMargin()
)
execute()
.asExpected()
.pageWasRendered("/test/asset/page-one/index.html") {
htmlHeadMatches("head link[rel=stylesheet]") {
link(href="http://orchid.test/TestAssetTheme/1e240/${TestAssetTheme.CSS}", rel="stylesheet", type="text/css") { }
link(href="http://orchid.test/${TestAssetPage.CSS}", rel="stylesheet", type="text/css") { }
link(href="https://copper-leaf.github.io/test-downloadable-assets/assets/css/style.css", rel="stylesheet", type="text/css") { }
}
htmlBodyMatches {
div("component component-pageContent component-order-0") {}
script(src="http://orchid.test/TestAssetTheme/1e240/${TestAssetTheme.JS}") { }
script(src="http://orchid.test/${TestAssetPage.JS}") { }
script(src="https://copper-leaf.github.io/test-downloadable-assets/assets/js/scripts.js") { }
}
}
.pageWasNotRendered("/test-downloadable-assets/assets/css/style.css")
.pageWasNotRendered("/test-downloadable-assets/assets/js/scripts.js")
}
@Test
@DisplayName("Test external assets are downloaded in prod environment")
fun test02() {
flag("environment", "prod")
configObject(
"site",
"""
|{
| "theme": "${TestAssetTheme.KEY}"
|}
""".trimMargin()
)
configObject(
"allPages",
"""
|{
| "components": [
| {"type": "pageContent", "noWrapper": false}
| ],
| "extraCss": [
| "https://copper-leaf.github.io/test-downloadable-assets/assets/css/style.css"
| ],
| "extraJs": [
| "https://copper-leaf.github.io/test-downloadable-assets/assets/js/scripts.js"
| ]
|}
""".trimMargin()
)
execute()
.asExpected()
.pageWasRendered("/test/asset/page-one/index.html") {
htmlHeadMatches("head link[rel=stylesheet]") {
link(href="http://orchid.test/TestAssetTheme/1e240/${TestAssetTheme.CSS}", rel="stylesheet", type="text/css") { }
link(href="http://orchid.test/${TestAssetPage.CSS}", rel="stylesheet", type="text/css") { }
link(href="http://orchid.test/test-downloadable-assets/assets/css/style.css", rel="stylesheet", type="text/css") { }
}
htmlBodyMatches {
div("component component-pageContent component-order-0") {}
script(src="http://orchid.test/TestAssetTheme/1e240/${TestAssetTheme.JS}") { }
script(src="http://orchid.test/${TestAssetPage.JS}") { }
script(src="http://orchid.test/test-downloadable-assets/assets/js/scripts.js") { }
}
}
.pageWasRendered("/test-downloadable-assets/assets/css/style.css") {
get { content.replace("\\s+".toRegex(), "") }
.isEqualTo(
"""
|.extra-css {
| color: blue;
|}
""".trimMargin().replace("\\s+".toRegex(), "")
)
}
.pageWasRendered("/test-downloadable-assets/assets/js/scripts.js") {
get { content.replace("\\s+".toRegex(), "") }
.isEqualTo(
"""
|fun js() {
| console.log("js");
|}
""".trimMargin().replace("\\s+".toRegex(), "")
)
}
}
@Test
@DisplayName("Test external assets are not downloaded in prod environment when `download` is set to `false`")
fun test03() {
flag("environment", "prod")
configObject(
"site",
"""
|{
| "theme": "${TestAssetTheme.KEY}"
|}
""".trimMargin()
)
configObject(
"allPages",
"""
|{
| "components": [
| {"type": "pageContent", "noWrapper": false}
| ],
| "extraCss": [
| {
| "asset": "https://copper-leaf.github.io/test-downloadable-assets/assets/css/style.css",
| "download": false
| }
| ],
| "extraJs": [
| {
| "asset": "https://copper-leaf.github.io/test-downloadable-assets/assets/js/scripts.js",
| "download": false
| }
| ]
|}
""".trimMargin()
)
execute()
.asExpected()
.pageWasRendered("/test/asset/page-one/index.html") {
htmlHeadMatches("head link[rel=stylesheet]") {
link(href="http://orchid.test/TestAssetTheme/1e240/${TestAssetTheme.CSS}", rel="stylesheet", type="text/css") { }
link(href="http://orchid.test/${TestAssetPage.CSS}", rel="stylesheet", type="text/css") { }
link(href="https://copper-leaf.github.io/test-downloadable-assets/assets/css/style.css", rel="stylesheet", type="text/css") { }
}
htmlBodyMatches {
div("component component-pageContent component-order-0") {}
script(src="http://orchid.test/TestAssetTheme/1e240/${TestAssetTheme.JS}") { }
script(src="http://orchid.test/${TestAssetPage.JS}") { }
script(src="https://copper-leaf.github.io/test-downloadable-assets/assets/js/scripts.js") { }
}
}
.pageWasNotRendered("/test-downloadable-assets/assets/css/style.css")
.pageWasNotRendered("/test-downloadable-assets/assets/js/scripts.js")
}
}
| lgpl-3.0 | 19b2b10004b2c20cfc02cd6323a62b90 | 38.979487 | 147 | 0.496024 | 4.483036 | false | true | false | false |
rhdunn/xquery-intellij-plugin | src/lang-xquery/main/uk/co/reecedunn/intellij/plugin/xquery/psi/impl/xquery/XQueryVersionDeclPsiImpl.kt | 1 | 3196 | /*
* Copyright (C) 2016-2021 Reece H. Dunn
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package uk.co.reecedunn.intellij.plugin.xquery.psi.impl.xquery
import com.intellij.extapi.psi.ASTWrapperPsiElement
import com.intellij.lang.ASTNode
import com.intellij.psi.PsiElement
import com.intellij.psi.impl.source.tree.PsiErrorElementImpl
import com.intellij.psi.tree.TokenSet
import uk.co.reecedunn.intellij.plugin.xdm.types.XsStringValue
import uk.co.reecedunn.intellij.plugin.xpath.ast.xpath.XPathComment
import uk.co.reecedunn.intellij.plugin.xpath.parser.XPathElementType
import uk.co.reecedunn.intellij.plugin.xpm.lang.validation.XpmSyntaxValidationElement
import uk.co.reecedunn.intellij.plugin.xquery.ast.xquery.XQueryVersionDecl
import uk.co.reecedunn.intellij.plugin.xquery.lexer.XQueryTokenType
import xqt.platform.intellij.xpath.XPathTokenProvider
import xqt.platform.xml.lexer.tokens.KeywordTokenType
class XQueryVersionDeclPsiImpl(node: ASTNode) :
ASTWrapperPsiElement(node),
XQueryVersionDecl,
XpmSyntaxValidationElement {
// region XQueryVersionDecl
override val version: XsStringValue?
get() = getStringValueAfterKeyword(XQueryTokenType.K_VERSION)
override val encoding: XsStringValue?
get() = getStringValueAfterKeyword(XQueryTokenType.K_ENCODING)
private fun getStringValueAfterKeyword(type: KeywordTokenType): XsStringValue? {
for (child in node.getChildren(STRINGS)) {
var previous = child.treePrev
while (previous.elementType === XPathTokenProvider.S.elementType || previous.psi is XPathComment) {
previous = previous.treePrev
}
if (previous.elementType === type) {
return child.psi as XsStringValue
} else if (previous is PsiErrorElementImpl) {
if (previous.firstChildNode.elementType === type) {
return child.psi as XsStringValue
}
}
}
return null
}
companion object {
private val STRINGS = TokenSet.create(XPathElementType.STRING_LITERAL)
}
// endregion
// region XpmSyntaxValidationElement
override val conformanceElement: PsiElement
get() {
val encoding = node.findChildByType(XQueryTokenType.K_ENCODING) ?: return firstChild
var previous = encoding.treePrev
while (previous.elementType === XPathTokenProvider.S.elementType || previous.psi is XPathComment) {
previous = previous.treePrev
}
return if (previous.elementType === XQueryTokenType.K_XQUERY) encoding.psi else firstChild
}
// endregion
}
| apache-2.0 | e40eabb0fb2e1d40fd8bc87792351658 | 37.97561 | 111 | 0.715582 | 4.686217 | false | false | false | false |
westnordost/StreetComplete | app/src/main/java/de/westnordost/streetcomplete/quests/diet_type/AddKosher.kt | 1 | 1314 | package de.westnordost.streetcomplete.quests.diet_type
import de.westnordost.streetcomplete.R
import de.westnordost.streetcomplete.data.meta.updateWithCheckDate
import de.westnordost.streetcomplete.data.osm.changes.StringMapChangesBuilder
import de.westnordost.streetcomplete.data.osm.osmquest.OsmFilterQuestType
class AddKosher : OsmFilterQuestType<DietAvailability>() {
override val elementFilter = """
nodes, ways with
(
amenity ~ restaurant|cafe|fast_food|ice_cream
or shop ~ butcher|supermarket|ice_cream
)
and name and (
!diet:kosher
or diet:kosher != only and diet:kosher older today -4 years
)
"""
override val commitMessage = "Add kosher status"
override val wikiLink = "Key:diet:kosher"
override val icon = R.drawable.ic_quest_kosher
override val defaultDisabledMessage = R.string.default_disabled_msg_go_inside_regional_warning
override fun getTitle(tags: Map<String, String>) = R.string.quest_dietType_kosher_name_title
override fun createForm() = AddDietTypeForm.create(R.string.quest_dietType_explanation_kosher)
override fun applyAnswerTo(answer: DietAvailability, changes: StringMapChangesBuilder) {
changes.updateWithCheckDate("diet:kosher", answer.osmValue)
}
}
| gpl-3.0 | 8e55b525b9e2606aa2be6489b0d9833e | 38.818182 | 98 | 0.733638 | 4.23871 | false | false | false | false |
StepicOrg/stepic-android | app/src/main/java/org/stepik/android/domain/profile_activities/interactor/ProfileActivitiesInteractor.kt | 2 | 1451 | package org.stepik.android.domain.profile_activities.interactor
import io.reactivex.Single
import org.stepik.android.domain.profile_activities.model.ProfileActivitiesData
import org.stepik.android.domain.user_activity.repository.UserActivityRepository
import org.stepik.android.model.user.UserActivity
import ru.nobird.android.domain.rx.first
import javax.inject.Inject
import kotlin.math.max
class ProfileActivitiesInteractor
@Inject
constructor(
private val userActivityRepository: UserActivityRepository
) {
fun getProfileActivities(userId: Long): Single<ProfileActivitiesData> =
userActivityRepository
.getUserActivities(userId)
.first()
.map(::mapToProfileActivities)
private fun mapToProfileActivities(userActivity: UserActivity): ProfileActivitiesData {
var streak = 0
var maxStreak = 0
var buffer = 0
for (i in 0..userActivity.pins.size) {
val pin = userActivity.pins.getOrElse(i) { 0 }
if (pin > 0) {
buffer++
} else {
maxStreak = max(maxStreak, buffer)
if (buffer == i || buffer == i - 1) { // first is solved today, second not solved
streak = buffer
}
buffer = 0
}
}
return ProfileActivitiesData(userActivity.pins, streak, maxStreak, isSolvedToday = userActivity.pins[0] > 0)
}
} | apache-2.0 | ee268e2a7040fd4ef27a353fc482abbb | 33.571429 | 116 | 0.654721 | 4.562893 | false | false | false | false |
pkleimann/livingdoc | livingdoc-engine/src/main/kotlin/org/livingdoc/engine/execution/examples/scenarios/matching/Alignment.kt | 3 | 12858 | package org.livingdoc.engine.execution.examples.scenarios.matching
import java.lang.Math.min
/**
* An alignment of a scenario step with a `StepTemplate`. Aligning a scenario step with a template allows us to check
* if the template matches the step and to extract any variables.
*
* Example: The following alignment of a perfectly matching template and scenario step
* ```
* {username} has {action} the {object}.
* -----Peter has ----left the building.
* ```
* yields the variables `username = "Peter"`, `action = "left"` and `object = "building"`.
*
* If a scenario step does not align well, it is an unlikely match. Because alignment calculation is expensive,
* it will be aborted when the cost of the alignment exceeds `maxCost`.
*/
@Suppress("NestedBlockDepth")
internal class Alignment(
val stepTemplate: StepTemplate,
val step: String,
val maxCost: Int
) {
/* To calculate an optimal global alignment of the `StepTemplate` and the String `s` representing the scenario step,
* we use an adapted version of the Needleman-Wunsch algorithm. The algorithm runs in two phases:
*
* 1. construct a distance matrix
* 2. trace an optimal path back through the matrix to the origin
*/
/**
* Total cost of alignment is determined by the sum of the costs of the operations needed to turn the template
* into the step string. The cost of individual operations is defined below.
*/
val totalCost: Int by lazy {
distanceMatrix.last().last()
}
/**
* Returns whether the alignment calculation was aborted because the `totalCost` exceeded `maxCost`.
*/
fun isMisaligned() = totalCost >= maxCost
/**
* The variables extracted from the aligned step.
*/
val variables: Map<String, String> by lazy {
if (!isMisaligned()) extractVariables() else emptyMap()
}
val alignedStrings: Pair<String, String> by lazy {
if (!isMisaligned()) buildAlignedStrings() else Pair(stepTemplate.toString(), step)
}
val distanceMatrix: DistanceMatrix by lazy {
constructDistanceMatrix(stepTemplate, step)
}
/**
* Calculates the distance matrix. Think of this as putting the `StepTemplate` and the scenario step next to
* each other and judging how well the template fits to the step.
*
* The following shows the first part of a distance matrix for the template "User {name} has entered the building."
* and the scenario step "User Peter has entered the building.":
*
* ```
* U s e r P e t e r h a s ... -- s
* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
* U 1 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14
* s 2 1 0 1 2 3 4 5 6 7 8 9 10 11 12 13
* e 3 2 1 0 1 2 3 4 5 6 7 8 9 10 11 12
* r 4 3 2 1 0 1 2 3 4 5 6 7 8 9 10 11
* 5 4 3 2 1 0 1 2 3 4 5 6 7 8 9 10
* name 5 4 3 2 1 0 0 0 0 0 0 0 0 0 0 0
* 6 5 4 3 2 1 1 1 1 1 1 0 1 1 1 0
* h 7 6 5 4 3 2 2 2 2 2 2 1 0 1 2 1
* a 8 7 6 5 4 3 3 3 3 3 3 2 1 0 1 2
* s 9 8 7 6 5 4 4 4 4 4 4 3 2 1 0 1
* 10 9 8 7 6 5 5 5 5 5 5 4 3 2 1 0
* ...
* |
* stepTemplate("User ", name, " has entered the building.")
* ```
*
* The matrix tracks the alignment cost for all pairs of substrings of the template and step.
*
* Cost grows monotonically from the top-left origin to the bottom-right. No row can contain a cost lower
* than the lowest value of the previous row. Because calculating the entire matrix is O(n²) in time, we can abort
* the calculation, once the minimum value in a row exceeds `maxCost` and it becomes obvious that the template
* does not match the scenario step.
*/
private fun constructDistanceMatrix(stepTemplate: StepTemplate, s: String): DistanceMatrix {
val d = Array(stepTemplate.length() + 1) { IntArray(s.length + 1) }
for (j in 0..s.length) {
d[0][j] = j * costInsertion
}
var offset = 1
for (fragment in stepTemplate.fragments) {
for (i in offset until (offset + length(fragment))) {
when (fragment) {
is Text -> {
d[i][0] = d[i - 1][0] + costDeletion(fragment.content[i - offset])
var currentMinDistance = d[i][0]
for (j in 1..s.length) {
d[i][j] = d[i][j - 1] + costInsertion
d[i][j] = min(d[i][j], d[i - 1][j] + costDeletion(fragment.content[i - offset]))
d[i][j] = min(
d[i][j],
d[i - 1][j - 1] + costSubstitution(fragment.content[i - offset], s[j - 1])
)
currentMinDistance = min(currentMinDistance, d[i][j])
}
if (currentMinDistance > maxCost) {
d[d.lastIndex][s.length] = currentMinDistance
return d
}
}
is Variable -> {
d[offset][0] = d[offset - 1][0] + costVariableDeletion
for (j in 1..s.length) {
d[offset][j] = d[offset - 1][j] + costVariableDeletion
d[offset][j] = min(d[offset][j], d[offset][j - 1] + costVariableExtension(s[j - 1]))
d[offset][j] = min(d[offset][j], d[offset - 1][j - 1] + costVariableExtension(s[j - 1]))
}
}
}
}
offset += length(fragment)
}
return d
}
/* The following values define how we calculate the cost for aligning template and step.
* Some hints:
* - matching identical characters should be cheapest (we want that to happen as much as possible)
* - extending a variable should be cheaper than changing a text fragment
* - cost for insertion, deletion and substitution has to fulfill the triangle inequality for substitution
* to be considered in an alignment: costSubstitution <= costInsertion + costDeletion
* - costs should not be negative (this would screw up the `maxCost` optimization)
*/
private val costInsertion = 2
private val costSimpleDeletion = 2
private val costDeletedQuotationChar = maxCost
private fun costDeletion(deletedCharInFragment: Char): Int {
return if (stepTemplate.quotationCharacters.contains(deletedCharInFragment))
costDeletedQuotationChar
else
costSimpleDeletion
}
private val costMatchingCharacters = 0
private val costSimpleSubstitution = costInsertion + costSimpleDeletion // TODO: remove substitution?
private val costSubstitutedQuotationChar = maxCost
private fun costSubstitution(inFragment: Char, inStep: Char): Int {
return if (inFragment != inStep) {
if (stepTemplate.quotationCharacters.contains(inFragment))
costSubstitutedQuotationChar
else
costSimpleSubstitution
} else
costMatchingCharacters
}
private val costVariableSimpleExtension = 1
private val costVariableExtensionOverQuotationChar = maxCost
private fun costVariableExtension(extension: Char): Int {
return if (stepTemplate.quotationCharacters.contains(extension))
costVariableExtensionOverQuotationChar
else
costVariableSimpleExtension
}
private val costVariableDeletion = 1
/**
* Extracts the variables from the scenario step and returns them as a map of variable names to their respective
* values.
*/
private fun extractVariables(): Map<String, String> {
val variables = mutableMapOf<String, String>()
var currentValue = ""
backtrace(
onMatchOrSubstitution = { fragment, _, stepIndex ->
if (fragment is Variable) {
currentValue = step[stepIndex] + currentValue
variables[fragment.name] = currentValue
} else {
currentValue = ""
}
},
onInsertion = { fragment, _, stepIndex ->
if (fragment is Variable) {
currentValue = step[stepIndex] + currentValue
}
},
onDeletion = { fragment, _, _ ->
if (fragment is Variable) {
variables[fragment.name] = currentValue
} else {
currentValue = ""
}
})
return variables
}
/**
* Returns a pair of strings representing the alignment of the `StepTemplate` and the scenario step. Useful for
* debugging and error messages.
*/
private fun buildAlignedStrings(): Pair<String, String> {
var alignedTemplate = ""
var alignedString = ""
backtrace(
onMatchOrSubstitution = { fragment, fragmentIndex, stepIndex ->
val fragmentChar = if (fragment is Text) fragment.content[fragmentIndex] else 'X'
alignedTemplate = fragmentChar + alignedTemplate
alignedString = step[stepIndex] + alignedString
},
onInsertion = { fragment, _, stepIndex ->
val gap = if (fragment is Text) '-' else 'X'
alignedTemplate = gap + alignedTemplate
alignedString = step[stepIndex] + alignedString
},
onDeletion = { fragment, fragmentIndex, _ ->
val fragmentChar = if (fragment is Text) fragment.content[fragmentIndex] else 'X'
alignedTemplate = fragmentChar + alignedTemplate
alignedString = "-$alignedString"
})
return Pair(alignedTemplate, alignedString)
}
/**
* Performs the second phase of the Needleman-Wunsch algorithm: tracing back a path through the distance
* matrix to determine an optimal global alignment. Such a path follows the smallest alignment cost
* back to the origin:
*
* ```
* U s e r P e t e r h a s ... -- s
* 0
* U 0
* s 0
* e 0
* r 0
* 0
* name 0 0 0 0 0
* 0
* h 0
* a 0
* s 0
* 0
* ...
* |
* stepTemplate("User ", name, " has entered the building.")
* ```
*
* Each step along that path corresponds to an editing action (match or substitution, insertion, deletion). It falls
* to the supplied handler to decide how each operation is processed.
*/
private fun backtrace(
onMatchOrSubstitution: BacktraceHandler,
onInsertion: BacktraceHandler,
onDeletion: BacktraceHandler
) {
var offset = stepTemplate.length()
var i = offset
var j = step.length
for (fragment in stepTemplate.fragments.reversed()) {
offset -= length(fragment)
while (i > offset || (i == 0 && j > 0)) {
if (evaluateMatrixAndOffset(i, offset, j)) {
--i; --j
onMatchOrSubstitution(fragment, i - offset, j)
} else if (i > offset && (j == 0 || distanceMatrix[i - 1][j] <= distanceMatrix[i][j - 1])) {
--i
onDeletion(fragment, i - offset, j)
} else {
assert(j > 0)
--j
onInsertion(fragment, i - offset, j)
}
}
}
}
private fun evaluateMatrixAndOffset(i: Int, offset: Int, j: Int): Boolean {
return i > offset && j > 0 &&
distanceMatrix[i - 1][j - 1] <= distanceMatrix[i - 1][j] &&
distanceMatrix[i - 1][j - 1] <= distanceMatrix[i][j - 1]
}
}
internal typealias DistanceMatrix = Array<IntArray>
private typealias BacktraceHandler = (fragment: Fragment, fragmentIndex: Int, stepIndex: Int) -> Unit
private fun StepTemplate.length() = fragments.map { length(it) }.sum()
private fun length(fragment: Fragment): Int = when (fragment) {
is Text -> fragment.content.length
else -> 1
}
| apache-2.0 | fe4987352fdca384ee755fe89bdc15b5 | 39.94586 | 120 | 0.546939 | 4.320228 | false | false | false | false |
PlateStack/PlateAPI | src/main/kotlin/org/platestack/api/message/ClickEvent.kt | 1 | 2830 | /*
* Copyright (C) 2017 José Roberto de Araújo Júnior
*
* 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.platestack.api.message
import java.net.URL
import java.nio.file.Path
sealed class ClickEvent(val action: String, val value: Message) {
companion object {
internal fun <B, R> B.tryTo(action: B.() -> R): R? {
try {
return action()
}
catch (e: Exception) {
return null
}
}
}
class OpenURL(url: Message): ClickEvent("open_url", url) {
constructor(url: String): this(Message(url))
constructor(url: URL): this(url.toString())
}
class OpenFile(file: Message): ClickEvent("open_file", file) {
constructor(file: String): this(Message(file))
constructor(path: Path): this(path.toString())
}
@Deprecated("Removed from Minecraft 1.8+")
class TwitchUserInfo(user: Message): ClickEvent("twitch_user_info", user) {
@Suppress("DEPRECATION")
constructor(user: String): this(Message(user))
}
class RunCommand(command: Message): ClickEvent("run_command", command) {
constructor(command: String): this(Message(command))
}
class SuggestCommand(command: Message): ClickEvent("suggest_command", command) {
constructor(command: String): this(Message(command))
}
class ChangePage private constructor(val page: Int?, value: Message): ClickEvent("change_page", value) {
constructor(page: String): this(page.tryTo { toInt() }, Message(page))
constructor(page: Int): this(page.toString())
override fun toString(): String {
return "ChangePage(page=$page, value=$value)"
}
}
override fun toString(): String {
return "${javaClass.simpleName}(action='$action', value=$value)"
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other?.javaClass != javaClass) return false
other as ClickEvent
if (action != other.action) return false
if (value != other.value) return false
return true
}
override fun hashCode(): Int {
var result = action.hashCode()
result = 31 * result + value.hashCode()
return result
}
} | apache-2.0 | a89eb4f1753a9a2dfe53332b16ddff01 | 30.775281 | 108 | 0.630704 | 4.206845 | false | false | false | false |
DavidHamm/wizard-pager | lib/src/main/kotlin/com/hammwerk/wizardpager/core/Page.kt | 1 | 1308 | package com.hammwerk.wizardpager.core
import android.os.Parcel
import android.os.Parcelable
abstract class Page : Parcelable {
val title: String
val fragmentName: String
private val required: Boolean
constructor(source: Parcel) {
fun Parcel.readBoolean(): Boolean {
return readByte() == 1.toByte()
}
this.title = source.readString()
this.fragmentName = source.readString()
this.required = source.readBoolean()
this.completed = source.readBoolean()
}
constructor(title: String, fragmentName: String, required: Boolean = false) {
this.title = title
this.fragmentName = fragmentName
this.required = required
}
var onPageValid: ((Page) -> Unit)? = null
var onPageInvalid: ((Page) -> Unit)? = null
var completed: Boolean = false
set(value) {
field = value
if (required) {
if (value) {
onPageValid?.let { it(this) }
} else {
onPageInvalid?.let { it(this) }
}
}
}
val valid: Boolean
get() = completed or !required
override fun writeToParcel(dest: Parcel?, flags: Int) {
fun Parcel.writeBoolean(value: Boolean) {
writeByte(if (value) 1 else 0)
}
dest?.writeString(title)
dest?.writeString(fragmentName)
dest?.writeBoolean(required)
dest?.writeBoolean(completed)
}
override fun describeContents(): Int {
return 0
}
}
| mit | 693d40c8fc45d4b9513ab9ccb74789a2 | 21.169492 | 78 | 0.688838 | 3.433071 | false | false | false | false |
jriley/HackerNews | mobile/src/main/kotlin/dev/jriley/hackernews/data/StoryRepository.kt | 1 | 1926 | package dev.jriley.hackernews.data
import dev.jriley.hackernews.services.HackerNewsService
import dev.jriley.hackernews.services.KotlinServices
import io.reactivex.Flowable
import io.reactivex.Scheduler
import io.reactivex.Single
import io.reactivex.schedulers.Schedulers
import timber.log.Timber
class StoryRepository(private val storyData: StoryData = DatabaseProvider.dataBase.storyEntityDao(),
private val hackerNewsService: HackerNewsService = KotlinServices.hackerNewsService,
private val ioScheduler: Scheduler = Schedulers.io()) {
fun isLoaded(): Single<Boolean> = storyData.isLoaded().subscribeOn(ioScheduler)
fun loadBest(): Single<List<Long>> = loadStoryIds(hackerNewsService.best, StoryTypes.BEST)
fun loadTop(): Single<List<Long>> = loadStoryIds(hackerNewsService.top, StoryTypes.TOP)
fun loadNew(): Single<List<Long>> = loadStoryIds(hackerNewsService.new, StoryTypes.NEW)
fun flowBest(): Flowable<List<Story>> = storyData.storyList()
fun bookmarkStory(story: Story): Single<Int> = storyData.update(story).subscribeOn(ioScheduler)
private fun loadStoryIds(api: Single<List<Long>>, st: StoryTypes): Single<List<Long>> =
api.map { id -> Timber.tag("@@@@").i("Original $st size: ${id.size}"); id.filter { !storyData.isLoaded(it) } }
.toObservable()
.flatMapIterable { filteredList -> Timber.tag("@").i("Filtered size:${filteredList.size}"); filteredList }
.map { filteredId -> hackerNewsService.getStory(filteredId.toString()) }
.map { story -> storyData.insert(Story(story.blockingGet(), st)) }
.map { storyId -> storyId.blockingGet() }
.toList()
.subscribeOn(ioScheduler)
}
object StoryRepositoryFactory {
val storyRepository: StoryRepository by lazy { StoryRepository() }
}
| mpl-2.0 | e8baf730bb852054320f1bebf8b91c5b | 45.97561 | 126 | 0.683801 | 4.20524 | false | false | false | false |
exponentjs/exponent | packages/expo-sensors/android/src/main/java/expo/modules/sensors/modules/PedometerModule.kt | 2 | 1957 | // Copyright 2015-present 650 Industries. All rights reserved.
package expo.modules.sensors.modules
import android.content.Context
import android.content.pm.PackageManager
import android.hardware.SensorEvent
import android.os.Bundle
import expo.modules.interfaces.sensors.SensorServiceInterface
import expo.modules.interfaces.sensors.services.PedometerServiceInterface
import expo.modules.core.Promise
import expo.modules.core.interfaces.ExpoMethod
class PedometerModule(reactContext: Context?) : BaseSensorModule(reactContext) {
private var stepsAtTheBeginning: Int? = null
override val eventName: String = "Exponent.pedometerUpdate"
override fun getName(): String {
return "ExponentPedometer"
}
override fun getSensorService(): SensorServiceInterface {
return moduleRegistry.getModule(PedometerServiceInterface::class.java)
}
override fun eventToMap(sensorEvent: SensorEvent): Bundle {
if (stepsAtTheBeginning == null) {
stepsAtTheBeginning = sensorEvent.values[0].toInt() - 1
}
return Bundle().apply {
putDouble("steps", (sensorEvent.values[0] - stepsAtTheBeginning!!).toDouble())
}
}
@ExpoMethod
fun startObserving(promise: Promise) {
super.startObserving()
stepsAtTheBeginning = null
promise.resolve(null)
}
@ExpoMethod
fun stopObserving(promise: Promise) {
super.stopObserving()
stepsAtTheBeginning = null
promise.resolve(null)
}
@ExpoMethod
fun setUpdateInterval(updateInterval: Int, promise: Promise) {
super.setUpdateInterval(updateInterval)
promise.resolve(null)
}
@ExpoMethod
fun isAvailableAsync(promise: Promise) {
promise.resolve(context.packageManager.hasSystemFeature(PackageManager.FEATURE_SENSOR_STEP_COUNTER))
}
@ExpoMethod
fun getStepCountAsync(startDate: Int?, endDate: Int?, promise: Promise) {
promise.reject("E_NOT_AVAILABLE", "Getting step count for date range is not supported on Android yet.")
}
}
| bsd-3-clause | c70957881bbb6ca58ab0454ec6714eb2 | 30.063492 | 107 | 0.759836 | 4.378076 | false | false | false | false |
square/wire | wire-library/wire-schema/src/jvmTest/kotlin/com/squareup/wire/schema/internal/parser/MessageElementTest.kt | 1 | 17717 | /*
* Copyright (C) 2014 Square, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.squareup.wire.schema.internal.parser
import com.squareup.wire.schema.Field.Label.OPTIONAL
import com.squareup.wire.schema.Field.Label.REPEATED
import com.squareup.wire.schema.Field.Label.REQUIRED
import com.squareup.wire.schema.Location
import com.squareup.wire.schema.internal.MAX_TAG_VALUE
import com.squareup.wire.schema.internal.parser.OptionElement.Kind
import org.assertj.core.api.Assertions.assertThat
import org.junit.Test
class MessageElementTest {
internal var location = Location.get("file.proto")
@Test
fun emptyToSchema() {
val element = MessageElement(
location = location,
name = "Message"
)
val expected = "message Message {}\n"
assertThat(element.toSchema()).isEqualTo(expected)
}
@Test
fun simpleToSchema() {
val element = MessageElement(
location = location,
name = "Message",
fields = listOf(
FieldElement(
location = location,
label = REQUIRED,
type = "string",
name = "name",
tag = 1
)
)
)
val expected = """
|message Message {
| required string name = 1;
|}
|""".trimMargin()
assertThat(element.toSchema()).isEqualTo(expected)
}
@Test
fun addMultipleFields() {
val firstName = FieldElement(
location = location,
label = REQUIRED,
type = "string",
name = "first_name",
tag = 1
)
val lastName = FieldElement(
location = location,
label = REQUIRED,
type = "string",
name = "last_name",
tag = 2
)
val element = MessageElement(
location = location,
name = "Message",
fields = listOf(firstName, lastName)
)
assertThat(element.fields).hasSize(2)
}
@Test
fun simpleWithDocumentationToSchema() {
val element = MessageElement(
location = location,
name = "Message",
documentation = "Hello",
fields = listOf(
FieldElement(
location = location,
label = REQUIRED,
type = "string",
name = "name",
tag = 1
)
)
)
val expected = """
|// Hello
|message Message {
| required string name = 1;
|}
|""".trimMargin()
assertThat(element.toSchema()).isEqualTo(expected)
}
@Test
fun simpleWithOptionsToSchema() {
val field = FieldElement(
location = location,
label = REQUIRED,
type = "string",
name = "name",
tag = 1
)
val element = MessageElement(
location = location,
name = "Message",
fields = listOf(field),
options = listOf(OptionElement.create("kit", Kind.STRING, "kat"))
)
val expected =
"""message Message {
| option kit = "kat";
|
| required string name = 1;
|}
|""".trimMargin()
assertThat(element.toSchema()).isEqualTo(expected)
}
@Test
fun addMultipleOptions() {
val field = FieldElement(
location = location,
label = REQUIRED,
type = "string",
name = "name",
tag = 1
)
val kitKat = OptionElement.create("kit", Kind.STRING, "kat")
val fooBar = OptionElement.create("foo", Kind.STRING, "bar")
val element = MessageElement(
location = location,
name = "Message",
fields = listOf(field),
options = listOf(kitKat, fooBar)
)
assertThat(element.options).hasSize(2)
}
@Test
fun simpleWithNestedElementsToSchema() {
val element = MessageElement(
location = location,
name = "Message",
fields = listOf(
FieldElement(
location = location,
label = REQUIRED,
type = "string",
name = "name",
tag = 1
)
),
nestedTypes = listOf(
MessageElement(
location = location,
name = "Nested",
fields = listOf(
FieldElement(
location = location,
label = REQUIRED,
type = "string",
name = "name",
tag = 1
)
)
)
)
)
val expected = """
|message Message {
| required string name = 1;
|
| message Nested {
| required string name = 1;
| }
|}
|""".trimMargin()
assertThat(element.toSchema()).isEqualTo(expected)
}
@Test
fun addMultipleTypes() {
val nested1 = MessageElement(
location = location,
name = "Nested1"
)
val nested2 = MessageElement(
location = location,
name = "Nested2"
)
val element = MessageElement(
location = location,
name = "Message",
fields = listOf(
FieldElement(
location = location,
label = REQUIRED,
type = "string",
name = "name",
tag = 1
)
),
nestedTypes = listOf(nested1, nested2)
)
assertThat(element.nestedTypes).hasSize(2)
}
@Test
fun simpleWithExtensionsToSchema() {
val element = MessageElement(
location = location,
name = "Message",
fields = listOf(
FieldElement(
location = location,
label = REQUIRED,
type = "string",
name = "name",
tag = 1
)
),
extensions = listOf(ExtensionsElement(location = location, values = listOf(500..501)))
)
val expected = """
|message Message {
| required string name = 1;
|
| extensions 500 to 501;
|}
|""".trimMargin()
assertThat(element.toSchema()).isEqualTo(expected)
}
@Test
fun addMultipleExtensions() {
val fives = ExtensionsElement(location = location, values = listOf(500..501))
val sixes = ExtensionsElement(location = location, values = listOf(600..601))
val element = MessageElement(
location = location,
name = "Message",
fields = listOf(
FieldElement(
location = location,
label = REQUIRED,
type = "string",
name = "name",
tag = 1
)
),
extensions = listOf(fives, sixes)
)
assertThat(element.extensions).hasSize(2)
}
@Test
fun oneOfToSchema() {
val element = MessageElement(
location = location,
name = "Message",
oneOfs = listOf(
OneOfElement(
name = "hi",
fields = listOf(
FieldElement(
location = location,
type = "string",
name = "name",
tag = 1
)
)
)
)
)
val expected = """
|message Message {
| oneof hi {
| string name = 1;
| }
|}
|""".trimMargin()
assertThat(element.toSchema()).isEqualTo(expected)
}
@Test
fun oneOfWithGroupToSchema() {
val element = MessageElement(
location = location,
name = "Message",
oneOfs = listOf(
OneOfElement(
name = "hi",
fields = listOf(
FieldElement(
location = location,
type = "string",
name = "name",
tag = 1
)
),
groups = listOf(
GroupElement(
location = location.at(5, 5),
name = "Stuff",
tag = 3,
fields = listOf(
FieldElement(
location = location.at(6, 7),
label = OPTIONAL,
type = "int32",
name = "result_per_page",
tag = 4
),
FieldElement(
location = location.at(7, 7),
label = OPTIONAL,
type = "int32",
name = "page_count",
tag = 5
)
)
)
)
)
)
)
// spotless:off because spotless will remove the indents (trailing spaces) in the oneof block.
val expected = """
|message Message {
| oneof hi {
| string name = 1;
|
| group Stuff = 3 {
| optional int32 result_per_page = 4;
| optional int32 page_count = 5;
| }
| }
|}
|""".trimMargin()
// spotless:on
assertThat(element.toSchema()).isEqualTo(expected)
}
@Test
fun addMultipleOneOfs() {
val hi = OneOfElement(
name = "hi",
fields = listOf(
FieldElement(
location = location,
type = "string",
name = "name",
tag = 1
)
)
)
val hey = OneOfElement(
name = "hey",
fields = listOf(
FieldElement(
location = location,
type = "string",
name = "city",
tag = 2
)
)
)
val element = MessageElement(
location = location,
name = "Message",
oneOfs = listOf(hi, hey)
)
assertThat(element.oneOfs).hasSize(2)
}
@Test
fun reservedToSchema() {
val element = MessageElement(
location = location,
name = "Message",
reserveds = listOf(
ReservedElement(location = location, values = listOf(10, 12..14, "foo")),
ReservedElement(location = location, values = listOf(10)),
ReservedElement(location = location, values = listOf(12..MAX_TAG_VALUE)),
ReservedElement(location = location, values = listOf("foo"))
)
)
val expected = """
|message Message {
| reserved 10, 12 to 14, "foo";
| reserved 10;
| reserved 12 to max;
| reserved "foo";
|}
|""".trimMargin()
assertThat(element.toSchema()).isEqualTo(expected)
}
@Test
fun groupToSchema() {
val element = MessageElement(
location = location.at(1, 1),
name = "SearchResponse",
groups = listOf(
GroupElement(
location = location.at(2, 3),
label = REPEATED,
name = "Result",
tag = 1,
fields = listOf(
FieldElement(
location = location.at(3, 5),
label = REQUIRED,
type = "string",
name = "url",
tag = 2
),
FieldElement(
location = location.at(4, 5),
label = OPTIONAL,
type = "string",
name = "title",
tag = 3
),
FieldElement(
location = location.at(5, 5),
label = REPEATED,
type = "string",
name = "snippets",
tag = 4
)
)
)
)
)
val expected = """
|message SearchResponse {
| repeated group Result = 1 {
| required string url = 2;
| optional string title = 3;
| repeated string snippets = 4;
| }
|}
|""".trimMargin()
assertThat(element.toSchema()).isEqualTo(expected)
}
@Test
fun multipleEverythingToSchema() {
val field1 = FieldElement(
location = location.at(1, 2),
label = REQUIRED,
type = "string",
name = "name",
tag = 2
)
val oneOf1Field1 = FieldElement(
location = location.at(1, 1),
type = "string",
name = "namey",
tag = 1
)
val oneOf1Field2 = FieldElement(
location = location.at(2, 1),
type = "int32",
name = "aField",
tag = 5
)
val oneOf1 = OneOfElement(
name = "thingy",
fields = listOf(oneOf1Field1, oneOf1Field2)
)
val field2 = FieldElement(
location = location.at(2, 3),
label = REQUIRED,
type = "bool",
name = "other_name",
tag = 3
)
val oneOf2Field = FieldElement(
location = location.at(3, 0),
type = "string",
name = "namer",
tag = 4
)
val oneOf2 = OneOfElement(
name = "thinger",
fields = listOf(oneOf2Field)
)
val extensions1 = ExtensionsElement(location = location.at(5, 0), values = listOf(500..501))
val extensions2 = ExtensionsElement(location = location.at(6, 2), values = listOf(503))
val nested = MessageElement(
location = location.at(7, 1),
name = "Nested",
fields = listOf(field1)
)
val option = OptionElement.create("kit", Kind.STRING, "kat")
val element = MessageElement(
location = location.at(0, 0),
name = "Message",
fields = listOf(field1, field2),
oneOfs = listOf(oneOf1, oneOf2),
nestedTypes = listOf(nested),
extensions = listOf(extensions1, extensions2),
options = listOf(option)
)
val expected = """
|message Message {
| option kit = "kat";
|
| oneof thingy {
| string namey = 1;
| int32 aField = 5;
| }
|
| required string name = 2;
|
| required bool other_name = 3;
|
| oneof thinger {
| string namer = 4;
| }
|
| extensions 500 to 501;
| extensions 503;
|
| message Nested {
| required string name = 2;
| }
|}
|""".trimMargin()
assertThat(element.toSchema()).isEqualTo(expected)
}
@Test
fun fieldToSchema() {
val field = FieldElement(
location = location,
label = REQUIRED,
type = "string",
name = "name",
tag = 1
)
val expected = "required string name = 1;\n"
assertThat(field.toSchema()).isEqualTo(expected)
}
@Test
fun fieldWithDefaultStringToSchemaInProto2() {
val field = FieldElement(
location = location,
label = REQUIRED,
type = "string",
name = "name",
tag = 1,
defaultValue = "benoît"
)
val expected = "required string name = 1 [default = \"benoît\"];\n"
assertThat(field.toSchema()).isEqualTo(expected)
}
@Test
fun fieldWithDefaultNumberToSchema() {
val field = FieldElement(
location = location,
label = REQUIRED,
type = "int32",
name = "age",
tag = 1,
defaultValue = "34"
)
val expected = "required int32 age = 1 [default = 34];\n"
assertThat(field.toSchema()).isEqualTo(expected)
}
@Test
fun fieldWithDefaultBoolToSchema() {
val field = FieldElement(
location = location,
label = REQUIRED,
type = "bool",
name = "human",
tag = 1,
defaultValue = "true"
)
val expected = "required bool human = 1 [default = true];\n"
assertThat(field.toSchema()).isEqualTo(expected)
}
@Test
fun oneOfFieldToSchema() {
val field = FieldElement(
location = location,
type = "string",
name = "name",
tag = 1
)
val expected = "string name = 1;\n"
assertThat(field.toSchema()).isEqualTo(expected)
}
@Test
fun fieldWithDocumentationToSchema() {
val field = FieldElement(
location = location,
label = REQUIRED,
type = "string",
name = "name",
tag = 1,
documentation = "Hello"
)
val expected =
"""// Hello
|required string name = 1;
|""".trimMargin()
assertThat(field.toSchema()).isEqualTo(expected)
}
@Test
fun fieldWithOneOptionToSchema() {
val field = FieldElement(
location = location,
label = REQUIRED,
type = "string",
name = "name",
tag = 1,
options = listOf(OptionElement.create("kit", Kind.STRING, "kat"))
)
val expected =
"""required string name = 1 [kit = "kat"];
|""".trimMargin()
assertThat(field.toSchema()).isEqualTo(expected)
}
@Test
fun fieldWithMoreThanOneOptionToSchema() {
val field = FieldElement(
location = location,
label = REQUIRED,
type = "string",
name = "name",
tag = 1,
options = listOf(
OptionElement.create("kit", Kind.STRING, "kat"),
OptionElement.create("dup", Kind.STRING, "lo")
)
)
val expected =
"""required string name = 1 [
| kit = "kat",
| dup = "lo"
|];
|""".trimMargin()
assertThat(field.toSchema()).isEqualTo(expected)
}
@Test fun oneOfWithOptions() {
val expected = """
|oneof page_info {
| option (my_option) = true;
|
| int32 page_number = 2;
| int32 result_per_page = 3;
|}
|""".trimMargin()
val oneOf = OneOfElement(
name = "page_info",
fields = listOf(
FieldElement(
location = location.at(4, 5),
type = "int32",
name = "page_number",
tag = 2
),
FieldElement(
location = location.at(5, 5),
type = "int32",
name = "result_per_page",
tag = 3
)
),
options = listOf(
OptionElement.create("my_option", Kind.BOOLEAN, "true", true)
)
)
assertThat(oneOf.toSchema()).isEqualTo(expected)
}
}
| apache-2.0 | e3fc29f50f49544a2bc31d7b285e6ccc | 24.12766 | 98 | 0.522947 | 4.32284 | false | false | false | false |
square/wire | wire-library/wire-grpc-server-generator/src/test/golden/RouteGuideWireGrpc.kt | 1 | 14215 | package routeguide
import com.google.protobuf.DescriptorProtos
import com.google.protobuf.Descriptors
import com.squareup.wire.kotlin.grpcserver.MessageSinkAdapter
import com.squareup.wire.kotlin.grpcserver.MessageSourceAdapter
import io.grpc.BindableService
import io.grpc.CallOptions
import io.grpc.Channel
import io.grpc.MethodDescriptor
import io.grpc.ServerServiceDefinition
import io.grpc.ServiceDescriptor
import io.grpc.ServiceDescriptor.newBuilder
import io.grpc.stub.AbstractStub
import io.grpc.stub.ClientCalls
import io.grpc.stub.ClientCalls.blockingServerStreamingCall
import io.grpc.stub.ClientCalls.blockingUnaryCall
import io.grpc.stub.ServerCalls.asyncBidiStreamingCall
import io.grpc.stub.ServerCalls.asyncClientStreamingCall
import io.grpc.stub.ServerCalls.asyncServerStreamingCall
import io.grpc.stub.ServerCalls.asyncUnaryCall
import io.grpc.stub.StreamObserver
import java.io.InputStream
import java.lang.UnsupportedOperationException
import java.util.concurrent.ExecutorService
import kotlin.Array
import kotlin.String
import kotlin.Unit
import kotlin.collections.Iterator
import kotlin.collections.Map
import kotlin.collections.Set
import kotlin.jvm.Volatile
public object RouteGuideWireGrpc {
public val SERVICE_NAME: String = "routeguide.RouteGuide"
@Volatile
private var serviceDescriptor: ServiceDescriptor? = null
private val descriptorMap: Map<String, DescriptorProtos.FileDescriptorProto> = mapOf(
"src/test/proto/RouteGuideProto.proto" to descriptorFor(arrayOf(
"CiRzcmMvdGVzdC9wcm90by9Sb3V0ZUd1aWRlUHJvdG8ucHJvdG8SCnJvdXRlZ3VpZGUiLAoFUG9pbnQS",
"EAoIbGF0aXR1ZGUYASABKAUSEQoJbG9uZ2l0dWRlGAIgASgFIkkKCVJlY3RhbmdsZRIdCgJsbxgBIAEo",
"CzIRLnJvdXRlZ3VpZGUuUG9pbnQSHQoCaGkYAiABKAsyES5yb3V0ZWd1aWRlLlBvaW50IjwKB0ZlYXR1",
"cmUSDAoEbmFtZRgBIAEoCRIjCghsb2NhdGlvbhgCIAEoCzIRLnJvdXRlZ3VpZGUuUG9pbnQiNwoPRmVh",
"dHVyZURhdGFiYXNlEiQKB2ZlYXR1cmUYASADKAsyEy5yb3V0ZWd1aWRlLkZlYXR1cmUiQQoJUm91dGVO",
"b3RlEiMKCGxvY2F0aW9uGAEgASgLMhEucm91dGVndWlkZS5Qb2ludBIPCgdtZXNzYWdlGAIgASgJImIK",
"DFJvdXRlU3VtbWFyeRITCgtwb2ludF9jb3VudBgBIAEoBRIVCg1mZWF0dXJlX2NvdW50GAIgASgFEhAK",
"CGRpc3RhbmNlGAMgASgFEhQKDGVsYXBzZWRfdGltZRgEIAEoBTL9AQoKUm91dGVHdWlkZRI0CgpHZXRG",
"ZWF0dXJlEhEucm91dGVndWlkZS5Qb2ludBoTLnJvdXRlZ3VpZGUuRmVhdHVyZRI8CgxMaXN0RmVhdHVy",
"ZXMSFS5yb3V0ZWd1aWRlLlJlY3RhbmdsZRoTLnJvdXRlZ3VpZGUuRmVhdHVyZTABEjwKC1JlY29yZFJv",
"dXRlEhEucm91dGVndWlkZS5Qb2ludBoYLnJvdXRlZ3VpZGUuUm91dGVTdW1tYXJ5KAESPQoJUm91dGVD",
"aGF0EhUucm91dGVndWlkZS5Sb3V0ZU5vdGUaFS5yb3V0ZWd1aWRlLlJvdXRlTm90ZSgBMAE=",
)),
)
@Volatile
private var getGetFeatureMethod: MethodDescriptor<Point, Feature>? = null
@Volatile
private var getListFeaturesMethod: MethodDescriptor<Rectangle, Feature>? = null
@Volatile
private var getRecordRouteMethod: MethodDescriptor<Point, RouteSummary>? = null
@Volatile
private var getRouteChatMethod: MethodDescriptor<RouteNote, RouteNote>? = null
private fun descriptorFor(`data`: Array<String>): DescriptorProtos.FileDescriptorProto {
val str = data.fold(java.lang.StringBuilder()) { b, s -> b.append(s) }.toString()
val bytes = java.util.Base64.getDecoder().decode(str)
return DescriptorProtos.FileDescriptorProto.parseFrom(bytes)
}
private fun fileDescriptor(path: String, visited: Set<String>): Descriptors.FileDescriptor {
val proto = descriptorMap[path]!!
val deps = proto.dependencyList.filter { !visited.contains(it) }.map { fileDescriptor(it,
visited + path) }
return Descriptors.FileDescriptor.buildFrom(proto, deps.toTypedArray())
}
public fun getServiceDescriptor(): ServiceDescriptor? {
var result = serviceDescriptor
if (result == null) {
synchronized(RouteGuideWireGrpc::class) {
result = serviceDescriptor
if (result == null) {
result = newBuilder(SERVICE_NAME)
.addMethod(getGetFeatureMethod())
.addMethod(getListFeaturesMethod())
.addMethod(getRecordRouteMethod())
.addMethod(getRouteChatMethod())
.setSchemaDescriptor(io.grpc.protobuf.ProtoFileDescriptorSupplier {
fileDescriptor("src/test/proto/RouteGuideProto.proto", emptySet())
})
.build()
serviceDescriptor = result
}
}
}
return result
}
public fun getGetFeatureMethod(): MethodDescriptor<Point, Feature> {
var result: MethodDescriptor<Point, Feature>? = getGetFeatureMethod
if (result == null) {
synchronized(RouteGuideWireGrpc::class) {
result = getGetFeatureMethod
if (result == null) {
getGetFeatureMethod = MethodDescriptor.newBuilder<Point, Feature>()
.setType(MethodDescriptor.MethodType.UNARY)
.setFullMethodName(
MethodDescriptor.generateFullMethodName(
"routeguide.RouteGuide", "GetFeature"
)
)
.setSampledToLocalTracing(true)
.setRequestMarshaller(RouteGuideImplBase.PointMarshaller())
.setResponseMarshaller(RouteGuideImplBase.FeatureMarshaller())
.build()
}
}
}
return getGetFeatureMethod!!
}
public fun getListFeaturesMethod(): MethodDescriptor<Rectangle, Feature> {
var result: MethodDescriptor<Rectangle, Feature>? = getListFeaturesMethod
if (result == null) {
synchronized(RouteGuideWireGrpc::class) {
result = getListFeaturesMethod
if (result == null) {
getListFeaturesMethod = MethodDescriptor.newBuilder<Rectangle, Feature>()
.setType(MethodDescriptor.MethodType.SERVER_STREAMING)
.setFullMethodName(
MethodDescriptor.generateFullMethodName(
"routeguide.RouteGuide", "ListFeatures"
)
)
.setSampledToLocalTracing(true)
.setRequestMarshaller(RouteGuideImplBase.RectangleMarshaller())
.setResponseMarshaller(RouteGuideImplBase.FeatureMarshaller())
.build()
}
}
}
return getListFeaturesMethod!!
}
public fun getRecordRouteMethod(): MethodDescriptor<Point, RouteSummary> {
var result: MethodDescriptor<Point, RouteSummary>? = getRecordRouteMethod
if (result == null) {
synchronized(RouteGuideWireGrpc::class) {
result = getRecordRouteMethod
if (result == null) {
getRecordRouteMethod = MethodDescriptor.newBuilder<Point, RouteSummary>()
.setType(MethodDescriptor.MethodType.CLIENT_STREAMING)
.setFullMethodName(
MethodDescriptor.generateFullMethodName(
"routeguide.RouteGuide", "RecordRoute"
)
)
.setSampledToLocalTracing(true)
.setRequestMarshaller(RouteGuideImplBase.PointMarshaller())
.setResponseMarshaller(RouteGuideImplBase.RouteSummaryMarshaller())
.build()
}
}
}
return getRecordRouteMethod!!
}
public fun getRouteChatMethod(): MethodDescriptor<RouteNote, RouteNote> {
var result: MethodDescriptor<RouteNote, RouteNote>? = getRouteChatMethod
if (result == null) {
synchronized(RouteGuideWireGrpc::class) {
result = getRouteChatMethod
if (result == null) {
getRouteChatMethod = MethodDescriptor.newBuilder<RouteNote, RouteNote>()
.setType(MethodDescriptor.MethodType.BIDI_STREAMING)
.setFullMethodName(
MethodDescriptor.generateFullMethodName(
"routeguide.RouteGuide", "RouteChat"
)
)
.setSampledToLocalTracing(true)
.setRequestMarshaller(RouteGuideImplBase.RouteNoteMarshaller())
.setResponseMarshaller(RouteGuideImplBase.RouteNoteMarshaller())
.build()
}
}
}
return getRouteChatMethod!!
}
public fun newStub(channel: Channel): RouteGuideStub = RouteGuideStub(channel)
public fun newBlockingStub(channel: Channel): RouteGuideBlockingStub =
RouteGuideBlockingStub(channel)
public abstract class RouteGuideImplBase : BindableService {
public open fun GetFeature(request: Point, response: StreamObserver<Feature>): Unit = throw
UnsupportedOperationException()
public open fun ListFeatures(request: Rectangle, response: StreamObserver<Feature>): Unit =
throw UnsupportedOperationException()
public open fun RecordRoute(response: StreamObserver<RouteSummary>): StreamObserver<Point> =
throw UnsupportedOperationException()
public open fun RouteChat(response: StreamObserver<RouteNote>): StreamObserver<RouteNote> =
throw UnsupportedOperationException()
public override fun bindService(): ServerServiceDefinition =
ServerServiceDefinition.builder(getServiceDescriptor()).addMethod(
getGetFeatureMethod(),
asyncUnaryCall(this@RouteGuideImplBase::GetFeature)
).addMethod(
getListFeaturesMethod(),
asyncServerStreamingCall(this@RouteGuideImplBase::ListFeatures)
).addMethod(
getRecordRouteMethod(),
asyncClientStreamingCall(this@RouteGuideImplBase::RecordRoute)
).addMethod(
getRouteChatMethod(),
asyncBidiStreamingCall(this@RouteGuideImplBase::RouteChat)
).build()
public class PointMarshaller : MethodDescriptor.Marshaller<Point> {
public override fun stream(`value`: Point): InputStream =
Point.ADAPTER.encode(value).inputStream()
public override fun parse(stream: InputStream): Point = Point.ADAPTER.decode(stream)
}
public class FeatureMarshaller : MethodDescriptor.Marshaller<Feature> {
public override fun stream(`value`: Feature): InputStream =
Feature.ADAPTER.encode(value).inputStream()
public override fun parse(stream: InputStream): Feature = Feature.ADAPTER.decode(stream)
}
public class RectangleMarshaller : MethodDescriptor.Marshaller<Rectangle> {
public override fun stream(`value`: Rectangle): InputStream =
Rectangle.ADAPTER.encode(value).inputStream()
public override fun parse(stream: InputStream): Rectangle = Rectangle.ADAPTER.decode(stream)
}
public class RouteSummaryMarshaller : MethodDescriptor.Marshaller<RouteSummary> {
public override fun stream(`value`: RouteSummary): InputStream =
RouteSummary.ADAPTER.encode(value).inputStream()
public override fun parse(stream: InputStream): RouteSummary =
RouteSummary.ADAPTER.decode(stream)
}
public class RouteNoteMarshaller : MethodDescriptor.Marshaller<RouteNote> {
public override fun stream(`value`: RouteNote): InputStream =
RouteNote.ADAPTER.encode(value).inputStream()
public override fun parse(stream: InputStream): RouteNote = RouteNote.ADAPTER.decode(stream)
}
}
public class RouteGuideImplLegacyAdapter(
private val streamExecutor: ExecutorService,
private val GetFeature: () -> RouteGuideGetFeatureBlockingServer,
private val ListFeatures: () -> RouteGuideListFeaturesBlockingServer,
private val RecordRoute: () -> RouteGuideRecordRouteBlockingServer,
private val RouteChat: () -> RouteGuideRouteChatBlockingServer,
) : RouteGuideImplBase() {
public override fun GetFeature(request: Point, response: StreamObserver<Feature>): Unit {
response.onNext(GetFeature().GetFeature(request))
response.onCompleted()
}
public override fun ListFeatures(request: Rectangle, response: StreamObserver<Feature>): Unit {
ListFeatures().ListFeatures(request, MessageSinkAdapter(response))
}
public override fun RecordRoute(response: StreamObserver<RouteSummary>): StreamObserver<Point> {
val requestStream = MessageSourceAdapter<Point>()
streamExecutor.submit {
response.onNext(RecordRoute().RecordRoute(requestStream))
response.onCompleted()
}
return requestStream
}
public override fun RouteChat(response: StreamObserver<RouteNote>): StreamObserver<RouteNote> {
val requestStream = MessageSourceAdapter<RouteNote>()
streamExecutor.submit {
RouteChat().RouteChat(requestStream, MessageSinkAdapter(response))
}
return requestStream
}
}
public class RouteGuideStub : AbstractStub<RouteGuideStub> {
internal constructor(channel: Channel) : super(channel)
internal constructor(channel: Channel, callOptions: CallOptions) : super(channel, callOptions)
public override fun build(channel: Channel, callOptions: CallOptions) = RouteGuideStub(channel,
callOptions)
public fun GetFeature(request: Point, response: StreamObserver<Feature>): Unit {
ClientCalls.asyncUnaryCall(channel.newCall(getGetFeatureMethod(), callOptions), request,
response)
}
public fun ListFeatures(request: Rectangle, response: StreamObserver<Feature>): Unit {
ClientCalls.asyncServerStreamingCall(channel.newCall(getListFeaturesMethod(), callOptions),
request, response)
}
public fun RecordRoute(response: StreamObserver<RouteSummary>): StreamObserver<Point> =
ClientCalls.asyncClientStreamingCall(channel.newCall(getRecordRouteMethod(), callOptions),
response)
public fun RouteChat(response: StreamObserver<RouteNote>): StreamObserver<RouteNote> =
ClientCalls.asyncBidiStreamingCall(channel.newCall(getRouteChatMethod(), callOptions),
response)
}
public class RouteGuideBlockingStub : AbstractStub<RouteGuideStub> {
internal constructor(channel: Channel) : super(channel)
internal constructor(channel: Channel, callOptions: CallOptions) : super(channel, callOptions)
public override fun build(channel: Channel, callOptions: CallOptions) = RouteGuideStub(channel,
callOptions)
public fun GetFeature(request: Point): Feature = blockingUnaryCall(channel,
getGetFeatureMethod(), callOptions, request)
public fun RecordRoute(request: Point): Iterator<RouteSummary> =
blockingServerStreamingCall(channel, getRecordRouteMethod(), callOptions, request)
}
}
| apache-2.0 | 797cb37728a158974c9bb7e476f516d0 | 40.564327 | 100 | 0.726979 | 4.542985 | false | false | false | false |
xiprox/Tensuu | app/src/main/java/tr/xip/scd/tensuu/ui/student/StudentActivity.kt | 1 | 4456 | package tr.xip.scd.tensuu.ui.student
import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.support.v7.widget.LinearLayoutManager
import android.view.Menu
import android.view.MenuItem
import android.view.View.GONE
import android.widget.Toast
import com.hannesdorfmann.mosby3.mvp.MvpActivity
import kotlinx.android.synthetic.main.activity_student.*
import tr.xip.scd.tensuu.R
import tr.xip.scd.tensuu.ui.common.adapter.PointsAdapter
import tr.xip.scd.tensuu.common.ui.view.RecyclerViewAdapterDataObserver
import tr.xip.scd.tensuu.common.ext.setDisplayedChildSafe
import tr.xip.scd.tensuu.common.ext.toVisibility
import java.text.SimpleDateFormat
class StudentActivity : MvpActivity<StudentView, StudentPresenter>(), StudentView {
val dataObserver = RecyclerViewAdapterDataObserver {
presenter.onDataChanged()
}
override fun createPresenter(): StudentPresenter = StudentPresenter()
@SuppressLint("SimpleDateFormat")
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_student)
setSupportActionBar(toolbar)
supportActionBar?.setDisplayHomeAsUpEnabled(true)
recycler.layoutManager = LinearLayoutManager(this)
restrictedRangeClose.setOnClickListener {
presenter.onRestrictedRangeClosed()
}
presenter.loadWith(intent.extras)
}
override fun onSupportNavigateUp(): Boolean {
super.onBackPressed()
return true
}
override fun onCreateOptionsMenu(menu: Menu?): Boolean {
menuInflater.inflate(R.menu.student, menu)
return super.onCreateOptionsMenu(menu)
}
@SuppressLint("SimpleDateFormat")
override fun onOptionsItemSelected(item: MenuItem?): Boolean {
presenter.onOptionsItemSelected(item)
return super.onOptionsItemSelected(item)
}
override fun setTitle(value: String) {
title = value
}
override fun setSsid(value: String?) {
if (value != null) {
ssid.text = value
} else {
ssid.visibility = GONE
}
}
override fun setGrade(value: String?) {
if (value != null) {
grade.text = value
} else {
grade.visibility = GONE
}
}
override fun setFloor(value: Int?) {
if (value != null) {
floor.text = "$value"
} else {
floor.visibility = GONE
}
}
override fun setPoints(value: Int) {
this.points.text = "$value"
}
@SuppressLint("SimpleDateFormat")
override fun setRestrictedRangeText(start: Long, end: Long) {
val format = SimpleDateFormat("MMM d ''yy")
restrictedRangeDate.text = getString(
R.string.info_showing_x_to_y,
format.format(start),
format.format(end)
)
}
override fun setFlipperChild(position: Int) {
flipper.setDisplayedChildSafe(position)
}
override fun setAdapter(value: PointsAdapter) {
recycler.adapter = value
recycler.adapter.registerAdapterDataObserver(dataObserver)
}
override fun getAdapter(): PointsAdapter {
return recycler.adapter as PointsAdapter
}
override fun showRestrictedRange(value: Boolean) {
restrictedRange.visibility = value.toVisibility()
}
override fun showToast(text: String) {
Toast.makeText(this, text, Toast.LENGTH_LONG).show()
}
override fun notifyDateChanged() {
dataObserver.onChanged()
}
override fun die() {
finish()
}
companion object {
internal val ARG_STUDENT_SSID = "student_ssid"
internal val ARG_RANGE_START = "range_start"
internal val ARG_RANGE_END = "range_end"
internal val FLIPPER_CONTENT = 0
internal val FLIPPER_NO_POINTS = 1
fun start(context: Context, ssid: String?) {
start(context, 0, 0, ssid)
}
fun start(context: Context, rangeStart: Long, rangeEnd: Long, ssid: String?) {
val intent = Intent(context, StudentActivity::class.java)
intent.putExtra(ARG_STUDENT_SSID, ssid)
intent.putExtra(ARG_RANGE_START, rangeStart)
intent.putExtra(ARG_RANGE_END, rangeEnd)
context.startActivity(intent)
}
}
} | gpl-3.0 | 518b925733c0fd380fb0c13df543892a | 28.713333 | 86 | 0.659336 | 4.593814 | false | false | false | false |
Maccimo/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/ReplaceNegatedIsEmptyWithIsNotEmptyInspection.kt | 1 | 4591 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.kotlin.idea.inspections
import com.intellij.codeInspection.LocalQuickFix
import com.intellij.codeInspection.ProblemDescriptor
import com.intellij.codeInspection.ProblemHighlightType
import com.intellij.codeInspection.ProblemsHolder
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiElementVisitor
import org.jetbrains.kotlin.idea.KotlinBundle
import org.jetbrains.kotlin.idea.caches.resolve.analyze
import org.jetbrains.kotlin.idea.base.psi.replaced
import org.jetbrains.kotlin.idea.inspections.collections.isCalling
import org.jetbrains.kotlin.idea.intentions.callExpression
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.getLastParentOfTypeInRow
import org.jetbrains.kotlin.psi.psiUtil.getStrictParentOfType
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
class ReplaceNegatedIsEmptyWithIsNotEmptyInspection : AbstractKotlinInspection() {
override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean): PsiElementVisitor {
return qualifiedExpressionVisitor(fun(expression) {
if (expression.getWrappingPrefixExpressionIfAny()?.operationToken != KtTokens.EXCL) return
val calleeExpression = expression.callExpression?.calleeExpression ?: return
val from = calleeExpression.text
val to = expression.invertSelectorFunction()?.callExpression?.calleeExpression?.text ?: return
holder.registerProblem(
calleeExpression,
KotlinBundle.message("replace.negated.0.with.1", from, to),
ProblemHighlightType.GENERIC_ERROR_OR_WARNING,
ReplaceNegatedIsEmptyWithIsNotEmptyQuickFix(from, to)
)
})
}
companion object {
fun KtQualifiedExpression.invertSelectorFunction(bindingContext: BindingContext? = null): KtQualifiedExpression? {
val callExpression = callExpression ?: return null
val fromFunctionName = callExpression.calleeExpression?.text ?: return null
val (fromFunctionFqNames, toFunctionName) = functionNames[fromFunctionName] ?: return null
val context = bindingContext ?: analyze(BodyResolveMode.PARTIAL)
if (fromFunctionFqNames.none { callExpression.isCalling(it, context) }) return null
return KtPsiFactory(this).createExpressionByPattern(
"$0.$toFunctionName()",
receiverExpression,
reformat = false
) as? KtQualifiedExpression
}
}
}
class ReplaceNegatedIsEmptyWithIsNotEmptyQuickFix(private val from: String, private val to: String) : LocalQuickFix {
override fun getName() = KotlinBundle.message("replace.negated.0.with.1", from, to)
override fun getFamilyName() = name
override fun applyFix(project: Project, descriptor: ProblemDescriptor) {
val qualifiedExpression = descriptor.psiElement.getStrictParentOfType<KtQualifiedExpression>() ?: return
val prefixExpression = qualifiedExpression.getWrappingPrefixExpressionIfAny() ?: return
prefixExpression.replaced(
KtPsiFactory(qualifiedExpression).createExpressionByPattern(
"$0.$to()",
qualifiedExpression.receiverExpression
)
)
}
}
private fun PsiElement.getWrappingPrefixExpressionIfAny() =
(getLastParentOfTypeInRow<KtParenthesizedExpression>() ?: this).parent as? KtPrefixExpression
private val packages = listOf(
"java.util.ArrayList",
"java.util.HashMap",
"java.util.HashSet",
"java.util.LinkedHashMap",
"java.util.LinkedHashSet",
"kotlin.collections",
"kotlin.collections.List",
"kotlin.collections.Set",
"kotlin.collections.Map",
"kotlin.collections.MutableList",
"kotlin.collections.MutableSet",
"kotlin.collections.MutableMap",
"kotlin.text"
)
private val functionNames: Map<String, Pair<List<FqName>, String>> by lazy {
mapOf(
"isEmpty" to Pair(packages.map { FqName("$it.isEmpty") }, "isNotEmpty"),
"isNotEmpty" to Pair(packages.map { FqName("$it.isNotEmpty") }, "isEmpty"),
"isBlank" to Pair(listOf(FqName("kotlin.text.isBlank")), "isNotBlank"),
"isNotBlank" to Pair(listOf(FqName("kotlin.text.isNotBlank")), "isBlank"),
)
}
| apache-2.0 | 37a935d0e3a5a7c0a65279dc4cda5fa7 | 44.91 | 122 | 0.726857 | 5.181716 | false | false | false | false |
futurice/freesound-android | app/src/main/java/com/futurice/freesound/feature/search/SearchActivityViewModel.kt | 1 | 3390 | /*
* Copyright 2016 Futurice GmbH
*
* 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.futurice.freesound.feature.search
import android.support.annotation.VisibleForTesting
import com.futurice.freesound.arch.mvvm.BaseViewModel
import com.futurice.freesound.common.Text
import com.futurice.freesound.common.rx.plusAssign
import com.futurice.freesound.feature.analytics.Analytics
import com.futurice.freesound.feature.audio.AudioPlayer
import com.futurice.freesound.feature.common.scheduling.SchedulerProvider
import io.reactivex.Completable
import io.reactivex.Observable
import io.reactivex.disposables.CompositeDisposable
import io.reactivex.subjects.BehaviorSubject
import timber.log.Timber.e
import java.util.concurrent.TimeUnit
@VisibleForTesting
const val SEARCH_DEBOUNCE_TIME_SECONDS = 1
@VisibleForTesting
const val SEARCH_DEBOUNCE_TAG = "SEARCH DEBOUNCE"
const val NO_SEARCH = Text.EMPTY
internal class SearchActivityViewModel(private val searchDataModel: SearchDataModel,
private val audioPlayer: AudioPlayer,
private val analytics: Analytics,
private val schedulerProvider: SchedulerProvider) : BaseViewModel() {
private val searchTermOnceAndStream = BehaviorSubject.createDefault(NO_SEARCH)
override fun bind(d: CompositeDisposable) {
audioPlayer.init()
d += searchTermOnceAndStream.observeOn(schedulerProvider.computation())
.distinctUntilChanged()
.switchMap { query ->
if (query.isNotEmpty())
querySearch(query).toObservable<Any>()
else
clearResults().toObservable<Any>()
}
.subscribeOn(schedulerProvider.computation())
.subscribe({}) { e(it, "Fatal error when setting search term") }
}
public override fun unbind() {
audioPlayer.release()
}
fun search(query: String) {
searchTermOnceAndStream.onNext(query.trim())
}
val isClearEnabledOnceAndStream: Observable<Boolean>
get() = searchTermOnceAndStream.observeOn(schedulerProvider.computation())
.map { isCloseEnabled(it) }
val searchStateOnceAndStream: Observable<SearchState>
get() = searchDataModel.searchStateOnceAndStream
private fun querySearch(query: String): Completable =
searchDataModel.querySearch(query, debounceQuery())
private fun clearResults() = searchDataModel.clear()
private fun debounceQuery(): Completable =
Completable.timer(SEARCH_DEBOUNCE_TIME_SECONDS.toLong(),
TimeUnit.SECONDS,
schedulerProvider.time(SEARCH_DEBOUNCE_TAG))
private fun isCloseEnabled(query: String): Boolean = query.isNotEmpty()
}
| apache-2.0 | cc62bc278d2e6abf1cd6fef253362e4d | 37.089888 | 108 | 0.69469 | 4.898844 | false | false | false | false |
blindpirate/gradle | subprojects/configuration-cache/src/main/kotlin/org/gradle/configurationcache/fingerprint/ConfigurationCacheFingerprintWriter.kt | 1 | 24753 | /*
* Copyright 2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gradle.configurationcache.fingerprint
import com.google.common.collect.Maps.newConcurrentMap
import com.google.common.collect.Sets.newConcurrentHashSet
import org.gradle.api.Describable
import org.gradle.api.artifacts.ModuleVersionIdentifier
import org.gradle.api.artifacts.component.ModuleComponentIdentifier
import org.gradle.api.artifacts.component.ModuleComponentSelector
import org.gradle.api.file.FileCollection
import org.gradle.api.internal.artifacts.configurations.ConfigurationInternal
import org.gradle.api.internal.artifacts.configurations.ProjectDependencyObservedListener
import org.gradle.api.internal.artifacts.configurations.dynamicversion.Expiry
import org.gradle.api.internal.artifacts.ivyservice.ivyresolve.ChangingValueDependencyResolutionListener
import org.gradle.api.internal.artifacts.ivyservice.resolveengine.projectresult.ResolvedProjectConfiguration
import org.gradle.api.internal.file.FileCollectionFactory
import org.gradle.api.internal.file.FileCollectionInternal
import org.gradle.api.internal.file.FileCollectionStructureVisitor
import org.gradle.api.internal.file.FileTreeInternal
import org.gradle.api.internal.file.collections.DirectoryFileTreeFactory
import org.gradle.api.internal.file.collections.FileSystemMirroringFileTree
import org.gradle.api.internal.project.ProjectState
import org.gradle.api.internal.provider.ValueSourceProviderFactory
import org.gradle.api.internal.provider.sources.EnvironmentVariableValueSource
import org.gradle.api.internal.provider.sources.EnvironmentVariablesPrefixedByValueSource
import org.gradle.api.internal.provider.sources.FileContentValueSource
import org.gradle.api.internal.provider.sources.GradlePropertyValueSource
import org.gradle.api.internal.provider.sources.SystemPropertiesPrefixedByValueSource
import org.gradle.api.internal.provider.sources.SystemPropertyValueSource
import org.gradle.api.internal.provider.sources.process.ProcessOutputValueSource
import org.gradle.api.provider.ValueSourceParameters
import org.gradle.api.tasks.util.PatternSet
import org.gradle.configurationcache.CoupledProjectsListener
import org.gradle.configurationcache.UndeclaredBuildInputListener
import org.gradle.configurationcache.extensions.uncheckedCast
import org.gradle.configurationcache.fingerprint.ConfigurationCacheFingerprint.InputFile
import org.gradle.configurationcache.fingerprint.ConfigurationCacheFingerprint.ValueSource
import org.gradle.configurationcache.problems.DocumentationSection
import org.gradle.configurationcache.problems.PropertyProblem
import org.gradle.configurationcache.problems.PropertyTrace
import org.gradle.configurationcache.problems.StructuredMessage
import org.gradle.configurationcache.serialization.DefaultWriteContext
import org.gradle.configurationcache.services.ConfigurationCacheEnvironment
import org.gradle.configurationcache.services.EnvironmentChangeTracker
import org.gradle.groovy.scripts.ScriptSource
import org.gradle.internal.concurrent.CompositeStoppable
import org.gradle.internal.execution.TaskExecutionTracker
import org.gradle.internal.execution.UnitOfWork
import org.gradle.internal.execution.WorkInputListener
import org.gradle.internal.execution.fingerprint.InputFingerprinter
import org.gradle.internal.execution.fingerprint.InputFingerprinter.InputVisitor
import org.gradle.internal.hash.HashCode
import org.gradle.internal.resource.local.FileResourceListener
import org.gradle.internal.scripts.ScriptExecutionListener
import org.gradle.util.Path
import java.io.File
import java.util.EnumSet
import kotlin.reflect.KProperty
internal
class ConfigurationCacheFingerprintWriter(
private val host: Host,
buildScopedContext: DefaultWriteContext,
projectScopedContext: DefaultWriteContext,
private val fileCollectionFactory: FileCollectionFactory,
private val directoryFileTreeFactory: DirectoryFileTreeFactory,
private val taskExecutionTracker: TaskExecutionTracker,
private val environmentChangeTracker: EnvironmentChangeTracker,
) : ValueSourceProviderFactory.ValueListener,
ValueSourceProviderFactory.ComputationListener,
WorkInputListener,
ScriptExecutionListener,
UndeclaredBuildInputListener,
ChangingValueDependencyResolutionListener,
ProjectDependencyObservedListener,
CoupledProjectsListener,
FileResourceListener,
ConfigurationCacheEnvironment.Listener {
interface Host {
val gradleUserHomeDir: File
val allInitScripts: List<File>
val startParameterProperties: Map<String, Any?>
val buildStartTime: Long
val cacheIntermediateModels: Boolean
fun fingerprintOf(fileCollection: FileCollectionInternal): HashCode
fun hashCodeOf(file: File): HashCode?
fun displayNameOf(file: File): String
fun reportInput(input: PropertyProblem)
fun location(consumer: String?): PropertyTrace
}
private
val buildScopedWriter = ScopedFingerprintWriter<ConfigurationCacheFingerprint>(buildScopedContext)
private
val buildScopedSink = BuildScopedSink(host, buildScopedWriter)
private
val projectScopedWriter = ScopedFingerprintWriter<ProjectSpecificFingerprint>(projectScopedContext)
private
val sinksForProject = newConcurrentMap<Path, ProjectScopedSink>()
private
val projectForThread = ThreadLocal<ProjectScopedSink>()
private
val projectDependencies = newConcurrentHashSet<ProjectSpecificFingerprint>()
private
val undeclaredSystemProperties = newConcurrentHashSet<String>()
private
val systemPropertiesPrefixedBy = newConcurrentHashSet<String>()
private
val undeclaredEnvironmentVariables = newConcurrentHashSet<String>()
private
val environmentVariablesPrefixedBy = newConcurrentHashSet<String>()
private
val reportedFiles = newConcurrentHashSet<File>()
private
val reportedValueSources = newConcurrentHashSet<String>()
private
var closestChangingValue: ConfigurationCacheFingerprint.ChangingDependencyResolutionValue? = null
private
var inputTrackingDisabledForThread by ThreadLocal.withInitial { false }
init {
val initScripts = host.allInitScripts
buildScopedSink.initScripts(initScripts)
buildScopedSink.write(
ConfigurationCacheFingerprint.GradleEnvironment(
host.gradleUserHomeDir,
jvmFingerprint(),
host.startParameterProperties
)
)
}
/**
* Stops all writers.
*
* **MUST ALWAYS BE CALLED**
*/
fun close() {
synchronized(this) {
closestChangingValue?.let {
buildScopedSink.write(it)
}
}
CompositeStoppable.stoppable(buildScopedWriter, projectScopedWriter).stop()
}
override fun onDynamicVersionSelection(requested: ModuleComponentSelector, expiry: Expiry, versions: Set<ModuleVersionIdentifier>) {
// Only consider repositories serving at least one version of the requested module.
// This is meant to avoid repetitively expiring cache entries due to a 404 response for the requested module metadata
// from one of the configured repositories.
if (versions.isEmpty()) return
val expireAt = host.buildStartTime + expiry.keepFor.toMillis()
onChangingValue(ConfigurationCacheFingerprint.DynamicDependencyVersion(requested.displayName, expireAt))
}
override fun onChangingModuleResolve(moduleId: ModuleComponentIdentifier, expiry: Expiry) {
val expireAt = host.buildStartTime + expiry.keepFor.toMillis()
onChangingValue(ConfigurationCacheFingerprint.ChangingModule(moduleId.displayName, expireAt))
}
private
fun onChangingValue(changingValue: ConfigurationCacheFingerprint.ChangingDependencyResolutionValue) {
synchronized(this) {
if (closestChangingValue == null || closestChangingValue!!.expireAt > changingValue.expireAt) {
closestChangingValue = changingValue
}
}
}
override fun fileObserved(file: File) {
if (inputTrackingDisabledForThread) {
return
}
captureFile(file)
}
override fun systemPropertyRead(key: String, value: Any?, consumer: String?) {
if (inputTrackingDisabledForThread || isSystemPropertyMutated(key)) {
return
}
sink().systemPropertyRead(key, value)
reportUniqueSystemPropertyInput(key, consumer)
}
override fun envVariableRead(key: String, value: String?, consumer: String?) {
if (inputTrackingDisabledForThread) {
return
}
sink().envVariableRead(key, value)
reportUniqueEnvironmentVariableInput(key, consumer)
}
override fun fileOpened(file: File, consumer: String?) {
if (inputTrackingDisabledForThread || taskExecutionTracker.currentTask.isPresent) {
// Ignore files that are read as part of the task actions. These should really be task
// inputs. Otherwise, we risk fingerprinting temporary files that will be gone at the
// end of the build.
return
}
captureFile(file)
reportUniqueFileInput(file, consumer)
}
override fun fileCollectionObserved(fileCollection: FileCollection, consumer: String) {
if (inputTrackingDisabledForThread) {
return
}
captureWorkInputs(consumer) { it(fileCollection as FileCollectionInternal) }
}
override fun systemPropertiesPrefixedBy(prefix: String, snapshot: Map<String, String?>) {
if (inputTrackingDisabledForThread) {
return
}
val filteredSnapshot = snapshot.mapValues { e ->
if (isSystemPropertyMutated(e.key)) {
ConfigurationCacheFingerprint.SystemPropertiesPrefixedBy.IGNORED
} else {
e.value
}
}
buildScopedSink.write(ConfigurationCacheFingerprint.SystemPropertiesPrefixedBy(prefix, filteredSnapshot))
}
override fun envVariablesPrefixedBy(prefix: String, snapshot: Map<String, String?>) {
if (inputTrackingDisabledForThread) {
return
}
buildScopedSink.write(ConfigurationCacheFingerprint.EnvironmentVariablesPrefixedBy(prefix, snapshot))
}
override fun beforeValueObtained() {
inputTrackingDisabledForThread = true
}
override fun afterValueObtained() {
inputTrackingDisabledForThread = false
}
override fun <T : Any, P : ValueSourceParameters> valueObtained(
obtainedValue: ValueSourceProviderFactory.ValueListener.ObtainedValue<T, P>,
source: org.gradle.api.provider.ValueSource<T, P>
) {
when (val parameters = obtainedValue.valueSourceParameters) {
is FileContentValueSource.Parameters -> {
parameters.file.orNull?.asFile?.let { file ->
// TODO - consider the potential race condition in computing the hash code here
captureFile(file)
reportUniqueFileInput(file)
}
}
is GradlePropertyValueSource.Parameters -> {
// The set of Gradle properties is already an input
}
is SystemPropertyValueSource.Parameters -> {
systemPropertyRead(parameters.propertyName.get(), obtainedValue.value.get(), null)
}
is SystemPropertiesPrefixedByValueSource.Parameters -> {
val prefix = parameters.prefix.get()
systemPropertiesPrefixedBy(prefix, obtainedValue.value.get().uncheckedCast())
reportUniqueSystemPropertiesPrefixedByInput(prefix)
}
is EnvironmentVariableValueSource.Parameters -> {
envVariableRead(parameters.variableName.get(), obtainedValue.value.get() as? String, null)
}
is EnvironmentVariablesPrefixedByValueSource.Parameters -> {
val prefix = parameters.prefix.get()
envVariablesPrefixedBy(prefix, obtainedValue.value.get().uncheckedCast())
reportUniqueEnvironmentVariablesPrefixedByInput(prefix)
}
is ProcessOutputValueSource.Parameters -> {
sink().write(ValueSource(obtainedValue.uncheckedCast()))
reportExternalProcessOutputRead(ProcessOutputValueSource.Parameters.getExecutable(parameters))
}
else -> {
sink().write(ValueSource(obtainedValue.uncheckedCast()))
reportUniqueValueSourceInput(
displayName = when (source) {
is Describable -> source.displayName
else -> null
},
typeName = obtainedValue.valueSourceType.simpleName
)
}
}
}
private
fun isSystemPropertyMutated(key: String): Boolean {
return environmentChangeTracker.isSystemPropertyMutated(key)
}
override fun onScriptClassLoaded(source: ScriptSource, scriptClass: Class<*>) {
source.resource.file?.let {
captureFile(it)
}
}
override fun onExecute(work: UnitOfWork, relevantTypes: EnumSet<InputFingerprinter.InputPropertyType>) {
captureWorkInputs(work, relevantTypes)
}
private
fun captureFile(file: File) {
sink().captureFile(file)
}
private
fun captureWorkInputs(work: UnitOfWork, relevantTypes: EnumSet<InputFingerprinter.InputPropertyType>) {
captureWorkInputs(work.displayName) { visitStructure ->
work.visitRegularInputs(object : InputVisitor {
override fun visitInputFileProperty(propertyName: String, type: InputFingerprinter.InputPropertyType, value: InputFingerprinter.FileValueSupplier) {
if (relevantTypes.contains(type)) {
visitStructure(value.files as FileCollectionInternal)
}
}
})
}
}
private
inline fun captureWorkInputs(workDisplayName: String, content: ((FileCollectionInternal) -> Unit) -> Unit) {
val fileSystemInputs = simplify(content)
sink().write(
ConfigurationCacheFingerprint.WorkInputs(
workDisplayName,
fileSystemInputs,
host.fingerprintOf(fileSystemInputs)
)
)
}
private
inline fun simplify(content: ((FileCollectionInternal) -> Unit) -> Unit): FileCollectionInternal {
val simplifyingVisitor = SimplifyingFileCollectionStructureVisitor(directoryFileTreeFactory, fileCollectionFactory)
content {
it.visitStructure(simplifyingVisitor)
}
return simplifyingVisitor.simplify()
}
fun <T> collectFingerprintForProject(identityPath: Path, action: () -> T): T {
val previous = projectForThread.get()
val projectSink = sinksForProject.computeIfAbsent(identityPath) { ProjectScopedSink(host, identityPath, projectScopedWriter) }
projectForThread.set(projectSink)
try {
return action()
} finally {
projectForThread.set(previous)
}
}
override fun dependencyObserved(consumingProject: ProjectState?, targetProject: ProjectState, requestedState: ConfigurationInternal.InternalState, target: ResolvedProjectConfiguration) {
if (host.cacheIntermediateModels && consumingProject != null) {
val dependency = ProjectSpecificFingerprint.ProjectDependency(consumingProject.identityPath, targetProject.identityPath)
if (projectDependencies.add(dependency)) {
projectScopedWriter.write(dependency)
}
}
}
override fun onProjectReference(referrer: ProjectState, target: ProjectState) {
if (host.cacheIntermediateModels) {
val dependency = ProjectSpecificFingerprint.CoupledProjects(referrer.identityPath, target.identityPath)
if (projectDependencies.add(dependency)) {
projectScopedWriter.write(dependency)
}
}
}
fun append(fingerprint: ProjectSpecificFingerprint) {
// TODO - should add to report as an input
projectScopedWriter.write(fingerprint)
}
private
fun sink(): Sink = projectForThread.get() ?: buildScopedSink
/**
* Transform the collection into a sequence of files or directory trees and remove dynamic behaviour
*/
private
class SimplifyingFileCollectionStructureVisitor(
private
val directoryFileTreeFactory: DirectoryFileTreeFactory,
private
val fileCollectionFactory: FileCollectionFactory
) : FileCollectionStructureVisitor {
private
val elements = mutableListOf<Any>()
override fun visitCollection(source: FileCollectionInternal.Source, contents: Iterable<File>) {
elements.addAll(contents)
}
override fun visitGenericFileTree(fileTree: FileTreeInternal, sourceTree: FileSystemMirroringFileTree) {
elements.addAll(fileTree)
}
override fun visitFileTree(root: File, patterns: PatternSet, fileTree: FileTreeInternal) {
elements.add(directoryFileTreeFactory.create(root, patterns))
}
override fun visitFileTreeBackedByFile(file: File, fileTree: FileTreeInternal, sourceTree: FileSystemMirroringFileTree) {
elements.add(file)
}
fun simplify(): FileCollectionInternal = fileCollectionFactory.resolving(elements)
}
private
fun reportUniqueValueSourceInput(displayName: String?, typeName: String) {
// We assume different types won't ever produce identical display names
if (reportedValueSources.add(displayName ?: typeName)) {
reportValueSourceInput(displayName, typeName)
}
}
private
fun reportValueSourceInput(displayName: String?, typeName: String) {
reportInput(consumer = null, documentationSection = null) {
text("value from custom source ")
reference(typeName)
displayName?.let {
text(", ")
text(it)
}
}
}
private
fun reportUniqueFileInput(file: File, consumer: String? = null) {
if (reportedFiles.add(file)) {
reportFileInput(file, consumer)
}
}
private
fun reportFileInput(file: File, consumer: String?) {
reportInput(consumer, null) {
text("file ")
reference(host.displayNameOf(file))
}
}
private
fun reportExternalProcessOutputRead(executable: String) {
reportInput(consumer = null, documentationSection = DocumentationSection.RequirementsExternalProcess) {
text("output of external process ")
reference(executable)
}
}
private
fun reportUniqueSystemPropertyInput(key: String, consumer: String?) {
if (undeclaredSystemProperties.add(key)) {
reportSystemPropertyInput(key, consumer)
}
}
private
fun reportSystemPropertyInput(key: String, consumer: String?) {
reportInput(consumer, DocumentationSection.RequirementsSysPropEnvVarRead) {
text("system property ")
reference(key)
}
}
private
fun reportUniqueSystemPropertiesPrefixedByInput(prefix: String) {
if (systemPropertiesPrefixedBy.add(prefix)) {
reportSystemPropertiesPrefixedByInput(prefix)
}
}
private
fun reportSystemPropertiesPrefixedByInput(prefix: String) {
reportInput(null, DocumentationSection.RequirementsSysPropEnvVarRead) {
if (prefix.isNotEmpty()) {
text("system properties prefixed by ")
reference(prefix)
} else {
text("system properties")
}
}
}
private
fun reportUniqueEnvironmentVariableInput(key: String, consumer: String?) {
if (undeclaredEnvironmentVariables.add(key)) {
reportEnvironmentVariableInput(key, consumer)
}
}
private
fun reportEnvironmentVariableInput(key: String, consumer: String?) {
reportInput(consumer, DocumentationSection.RequirementsSysPropEnvVarRead) {
text("environment variable ")
reference(key)
}
}
private
fun reportUniqueEnvironmentVariablesPrefixedByInput(prefix: String) {
if (environmentVariablesPrefixedBy.add(prefix)) {
reportEnvironmentVariablesPrefixedByInput(prefix)
}
}
private
fun reportEnvironmentVariablesPrefixedByInput(prefix: String) {
reportInput(null, DocumentationSection.RequirementsSysPropEnvVarRead) {
if (prefix.isNotEmpty()) {
text("environment variables prefixed by ")
reference(prefix)
} else {
text("environment variables")
}
}
}
private
fun reportInput(
consumer: String?,
documentationSection: DocumentationSection?,
messageBuilder: StructuredMessage.Builder.() -> Unit
) {
host.reportInput(
PropertyProblem(
locationFor(consumer),
StructuredMessage.build(messageBuilder),
null,
documentationSection = documentationSection
)
)
}
private
fun locationFor(consumer: String?) = host.location(consumer)
private
abstract class Sink(
private val host: Host
) {
val capturedFiles: MutableSet<File> = newConcurrentHashSet()
private
val undeclaredSystemProperties = newConcurrentHashSet<String>()
private
val undeclaredEnvironmentVariables = newConcurrentHashSet<String>()
fun captureFile(file: File) {
if (!capturedFiles.add(file)) {
return
}
write(inputFile(file))
}
fun systemPropertyRead(key: String, value: Any?) {
if (undeclaredSystemProperties.add(key)) {
write(ConfigurationCacheFingerprint.UndeclaredSystemProperty(key, value))
}
}
fun envVariableRead(key: String, value: String?) {
if (undeclaredEnvironmentVariables.add(key)) {
write(ConfigurationCacheFingerprint.UndeclaredEnvironmentVariable(key, value))
}
}
abstract fun write(value: ConfigurationCacheFingerprint)
fun inputFile(file: File) =
InputFile(
file,
host.hashCodeOf(file)
)
}
private
class BuildScopedSink(
host: Host,
private val writer: ScopedFingerprintWriter<ConfigurationCacheFingerprint>
) : Sink(host) {
override fun write(value: ConfigurationCacheFingerprint) {
writer.write(value)
}
fun initScripts(initScripts: List<File>) {
capturedFiles.addAll(initScripts)
write(
ConfigurationCacheFingerprint.InitScripts(
initScripts.map(::inputFile)
)
)
}
}
private
class ProjectScopedSink(
host: Host,
private val project: Path,
private val writer: ScopedFingerprintWriter<ProjectSpecificFingerprint>
) : Sink(host) {
override fun write(value: ConfigurationCacheFingerprint) {
writer.write(ProjectSpecificFingerprint.ProjectFingerprint(project, value))
}
}
}
internal
fun jvmFingerprint() = String.format(
"%s|%s|%s",
System.getProperty("java.vm.name"),
System.getProperty("java.vm.vendor"),
System.getProperty("java.vm.version")
)
private
operator fun <T> ThreadLocal<T>.getValue(thisRef: Any?, property: KProperty<*>) = get()
private
operator fun <T> ThreadLocal<T>.setValue(thisRef: Any?, property: KProperty<*>, value: T) = set(value)
| apache-2.0 | 05202c169ae06adb9428ab161055aacb | 36.675799 | 190 | 0.690058 | 5.310663 | false | true | false | false |
Hexworks/zircon | zircon.jvm.examples/src/main/kotlin/org/hexworks/zircon/examples/modifiers/FadeInExample.kt | 1 | 1882 | package org.hexworks.zircon.examples.modifiers
import org.hexworks.zircon.api.CP437TilesetResources
import org.hexworks.zircon.api.ColorThemes
import org.hexworks.zircon.api.Modifiers
import org.hexworks.zircon.api.SwingApplications
import org.hexworks.zircon.api.application.AppConfig
import org.hexworks.zircon.api.color.TileColor
import org.hexworks.zircon.api.data.Position
import org.hexworks.zircon.api.data.Size
import org.hexworks.zircon.api.data.Tile
import org.hexworks.zircon.api.modifier.FadeIn
object FadeInExample {
private val tileset = CP437TilesetResources.taffer20x20()
@JvmStatic
fun main(args: Array<String>) {
val tileGrid = SwingApplications.startTileGrid(
AppConfig.newBuilder()
.withDefaultTileset(tileset)
.withSize(Size.create(40, 10))
.withDebugMode(true)
.build()
)
val text = "This text fades in with a glow"
tileGrid.cursorPosition = Position.create(1, 1)
text.forEach { c ->
tileGrid.putTile(
Tile.defaultTile()
.withBackgroundColor(TileColor.transparent())
.withForegroundColor(ColorThemes.nord().accentColor)
.withCharacter(c)
.withModifiers(Modifiers.fadeIn(10, 2000))
)
}
val textWithoutGlow = "This text fades in without a glow"
tileGrid.cursorPosition = Position.create(1, 3)
textWithoutGlow.forEach { c ->
tileGrid.putTile(
Tile.defaultTile()
.withBackgroundColor(TileColor.transparent())
.withForegroundColor(ColorThemes.nord().accentColor)
.withCharacter(c)
.withModifiers(FadeIn(10, 2000, false))
)
}
}
}
| apache-2.0 | f86435bc7a28bdfc25e8e77127a71d3b | 25.885714 | 72 | 0.621679 | 4.579075 | false | false | false | false |
JetBrains/ideavim | src/test/java/org/jetbrains/plugins/ideavim/extension/matchit/MatchitGeneralTest.kt | 1 | 7286 | /*
* Copyright 2003-2022 The IdeaVim authors
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE.txt file or at
* https://opensource.org/licenses/MIT.
*/
package org.jetbrains.plugins.ideavim.extension.matchit
import com.intellij.ide.highlighter.HtmlFileType
import com.intellij.ide.highlighter.JavaFileType
import com.maddyhome.idea.vim.command.VimStateMachine
import com.maddyhome.idea.vim.helper.VimBehaviorDiffers
import com.maddyhome.idea.vim.helper.experimentalApi
import org.jetbrains.plugins.ideavim.VimTestCase
class MatchitGeneralTest : VimTestCase() {
@Throws(Exception::class)
override fun setUp() {
super.setUp()
enableExtensions("matchit")
}
/*
* Tests to make sure we didn't break the default % motion
*/
fun `test jump from Java comment start to end`() {
doTest(
"%",
"""
/$c**
*
*/
""".trimIndent(),
"""
/**
*
*$c/
""".trimIndent(),
fileType = JavaFileType.INSTANCE
)
}
fun `test jump from Java comment end to start`() {
doTest(
"%",
"""
/**
*
*$c/
""".trimIndent(),
"""
$c/**
*
*/
""".trimIndent(),
fileType = JavaFileType.INSTANCE
)
}
fun `test 25 percent jump`() {
doTest(
"25%",
"""
int a;
int b;
in${c}t c;
int d;
""".trimIndent(),
"""
${c}int a;
int b;
int c;
int d;
""".trimIndent(),
fileType = HtmlFileType.INSTANCE
)
}
fun `test jump from visual end of line to opening parenthesis`() {
doTest(
"v$%",
"""foo(${c}bar)""",
"""foo${s}$c(b${se}ar)""",
VimStateMachine.Mode.VISUAL, VimStateMachine.SubMode.VISUAL_CHARACTER, HtmlFileType.INSTANCE
)
}
fun `test jump from visual end of line to opening parenthesis then back to closing`() {
doTest(
"v$%%",
"""foo(${c}bar)""",
"""foo(${s}bar$c)$se""",
VimStateMachine.Mode.VISUAL, VimStateMachine.SubMode.VISUAL_CHARACTER, HtmlFileType.INSTANCE
)
}
fun `test delete everything from opening parenthesis to closing parenthesis`() {
doTest(
"d%",
"$c(x == 123)", "", fileType = HtmlFileType.INSTANCE
)
}
fun `test delete everything from closing parenthesis to opening parenthesis`() {
doTest(
"d%",
"(x == 123$c)", "", VimStateMachine.Mode.COMMAND, VimStateMachine.SubMode.NONE, HtmlFileType.INSTANCE
)
}
fun `test delete everything from opening curly brace to closing curly brace`() {
doTest(
"d%",
"$c{ foo: 123 }", "", VimStateMachine.Mode.COMMAND, VimStateMachine.SubMode.NONE, HtmlFileType.INSTANCE
)
}
fun `test delete everything from closing curly brace to opening curly brace`() {
doTest(
"d%",
"{ foo: 123 $c}", "", VimStateMachine.Mode.COMMAND, VimStateMachine.SubMode.NONE, HtmlFileType.INSTANCE
)
}
fun `test delete everything from opening square bracket to closing square bracket`() {
doTest(
"d%",
"$c[1, 2, 3]", "", VimStateMachine.Mode.COMMAND, VimStateMachine.SubMode.NONE, HtmlFileType.INSTANCE
)
}
fun `test delete everything from closing square bracket to opening square bracket`() {
doTest(
"d%",
"[1, 2, 3$c]", "", VimStateMachine.Mode.COMMAND, VimStateMachine.SubMode.NONE, HtmlFileType.INSTANCE
)
}
/*
* Tests for visual mode and deleting on the new Matchit patterns.
*/
fun `test jump from visual end of line to opening angle bracket`() {
doTest(
"v$%",
"""</h${c}tml>""",
"""${s}$c</ht${se}ml>""",
VimStateMachine.Mode.VISUAL, VimStateMachine.SubMode.VISUAL_CHARACTER, HtmlFileType.INSTANCE
)
}
fun `test jump from visual end of line to start of for loop`() {
doTest(
"v$%",
"""
for n in [1, 2, 3]
puts n
e${c}nd
""".trimIndent(),
"""
${s}${c}for n in [1, 2, 3]
puts n
en${se}d
""".trimIndent(),
VimStateMachine.Mode.VISUAL, VimStateMachine.SubMode.VISUAL_CHARACTER, fileName = "ruby.rb"
)
}
@VimBehaviorDiffers(
originalVimAfter = """
if x == 0
puts "Zero"
$c
puts "Positive"
end
""",
description = "Our code changes the motion type to linewise, but it should not"
)
fun `test delete from elseif to else`() {
doTest(
"d%",
"""
if x == 0
puts "Zero"
${c}elsif x < -1
puts "Negative"
else
puts "Positive"
end
""".trimIndent(),
if (experimentalApi()) {
"""
if x == 0
puts "Zero"
puts "Positive"
end
""".trimIndent()
} else {
"""
if x == 0
puts "Zero"
$c
puts "Positive"
end
""".trimIndent()
},
fileName = "ruby.rb"
)
}
fun `test delete from elseif to else 2`() {
doTest(
"d%",
"""
if x == 0
puts "Zero"
el${c}sif x < -1
puts "Negative"
else
puts "Positive"
end
""".trimIndent(),
"""
if x == 0
puts "Zero"
e${c}l
puts "Positive"
end
""".trimIndent(),
fileName = "ruby.rb"
)
}
fun `test delete from else to elsif with reverse motion`() {
doTest(
"dg%",
"""
if x == 0
puts "Zero"
elsif x < -1
puts "Negative"
${c}else
puts "Positive"
end
""".trimIndent(),
"""
if x == 0
puts "Zero"
${c}lse
puts "Positive"
end
""".trimIndent(),
fileName = "ruby.rb"
)
}
fun `test delete from opening to closing div`() {
doTest(
"d%",
"""
<${c}div>
<img src="fff">
</div>
""".trimIndent(),
"$c<",
fileType = HtmlFileType.INSTANCE
)
}
fun `test delete from opening angle bracket to closing angle bracket`() {
doTest(
"d%",
"""
$c<div></div>
""".trimIndent(),
"$c</div>",
fileType = HtmlFileType.INSTANCE
)
}
fun `test delete whole function from def`() {
doTest(
"d%",
"""
${c}def function
puts "hello"
end
""".trimIndent(),
"",
fileName = "ruby.rb"
)
}
fun `test delete whole function from def with reverse motion`() {
doTest(
"dg%",
"""
${c}def function
puts "hello"
end
""".trimIndent(),
"",
fileName = "ruby.rb"
)
}
fun `test delete whole function from end`() {
doTest(
"d%",
"""
def function
puts "hello"
en${c}d
""".trimIndent(),
"",
fileName = "ruby.rb"
)
}
fun `test delete whole function from end with reverse motion`() {
doTest(
"dg%",
"""
def function
puts "hello"
en${c}d
""".trimIndent(),
"",
fileName = "ruby.rb"
)
}
}
| mit | f8d826fc9ac04e445f7be01dc890e6dc | 20.814371 | 109 | 0.512901 | 4.158676 | false | true | false | false |
RadiationX/ForPDA | app/src/main/java/forpdateam/ru/forpda/presentation/favorites/FavoritesPresenter.kt | 1 | 7059 | package forpdateam.ru.forpda.presentation.favorites
import android.util.Log
import moxy.InjectViewState
import forpdateam.ru.forpda.common.Utils
import forpdateam.ru.forpda.common.mvp.BasePresenter
import forpdateam.ru.forpda.entity.app.TabNotification
import forpdateam.ru.forpda.entity.remote.favorites.FavItem
import forpdateam.ru.forpda.model.CountersHolder
import forpdateam.ru.forpda.model.data.remote.api.favorites.Sorting
import forpdateam.ru.forpda.model.interactors.CrossScreenInteractor
import forpdateam.ru.forpda.model.repository.events.EventsRepository
import forpdateam.ru.forpda.model.repository.faviorites.FavoritesRepository
import forpdateam.ru.forpda.model.repository.forum.ForumRepository
import forpdateam.ru.forpda.model.preferences.ListsPreferencesHolder
import forpdateam.ru.forpda.model.preferences.NotificationPreferencesHolder
import forpdateam.ru.forpda.presentation.IErrorHandler
import forpdateam.ru.forpda.presentation.ILinkHandler
import forpdateam.ru.forpda.presentation.Screen
import forpdateam.ru.forpda.presentation.TabRouter
/**
* Created by radiationx on 11.11.17.
*/
@InjectViewState
class FavoritesPresenter(
private val favoritesRepository: FavoritesRepository,
private val forumRepository: ForumRepository,
private val eventsRepository: EventsRepository,
private val listsPreferencesHolder: ListsPreferencesHolder,
private val notificationPreferencesHolder: NotificationPreferencesHolder,
private val crossScreenInteractor: CrossScreenInteractor,
private val router: TabRouter,
private val linkHandler: ILinkHandler,
private val countersHolder: CountersHolder,
private val errorHandler: IErrorHandler
) : BasePresenter<FavoritesView>() {
private var currentSt = 0
private var loadAll = listsPreferencesHolder.getFavLoadAll()
private var sorting: Sorting = Sorting(
listsPreferencesHolder.getSortingKey(),
listsPreferencesHolder.getSortingOrder()
)
override fun onFirstViewAttach() {
super.onFirstViewAttach()
viewState.initSorting(sorting)
listsPreferencesHolder
.observeFavLoadAll()
.subscribe { loadAll = it }
.untilDestroy()
listsPreferencesHolder
.observeShowDot()
.subscribe {
viewState.setShowDot(it)
}
.untilDestroy()
listsPreferencesHolder
.observeUnreadTop()
.subscribe {
viewState.setUnreadTop(it)
}
.untilDestroy()
eventsRepository
.observeEventsTab()
.subscribe {
Log.e("testtabnotify", "fav observeEventsTab $it")
handleEvent(it)
}
.untilDestroy()
favoritesRepository
.observeItems()
.subscribe({
Log.d("kokos", "observeContacts ${it.size} ${it.joinToString("; "){"${it.topicId}:${it.isNew}"}}")
viewState.onShowFavorite(it)
}, {
errorHandler.handle(it)
})
.untilDestroy()
favoritesRepository
.loadCache()
.subscribe({
viewState.onShowFavorite(it)
}, {
errorHandler.handle(it)
})
.untilDestroy()
crossScreenInteractor
.observeTopic()
.subscribe {
markRead(it)
}
.untilDestroy()
}
fun updateSorting(key: String, order: String) {
sorting.also {
it.key = key
it.order = order
}
listsPreferencesHolder.setSortingKey(key)
listsPreferencesHolder.setSortingOrder(order)
loadFavorites(currentSt)
}
fun refresh() {
loadFavorites(0)
}
fun loadFavorites(pageNum: Int) {
currentSt = pageNum
favoritesRepository
.loadFavorites(currentSt, loadAll, sorting)
.doOnSubscribe { viewState.setRefreshing(true) }
.doAfterTerminate { viewState.setRefreshing(false) }
.subscribe({
viewState.onLoadFavorites(it)
}, {
errorHandler.handle(it)
})
.untilDestroy()
}
private fun markRead(topicId: Int) {
favoritesRepository
.markRead(topicId)
.subscribe({
}, {
errorHandler.handle(it)
})
.untilDestroy()
}
private fun handleEvent(event: TabNotification) {
favoritesRepository
.handleEvent(event)
.subscribe({
Log.e("testtabnotify", "fav handleEvent $it")
}, {
errorHandler.handle(it)
})
.untilDestroy()
}
fun markAllRead() {
forumRepository
.markAllRead()
.subscribe({
viewState.onMarkAllRead()
}, {
errorHandler.handle(it)
})
.untilDestroy()
}
fun onItemClick(item: FavItem) {
val args = mapOf<String, String>(
Screen.ARG_TITLE to item.topicTitle.orEmpty()
)
if (item.isForum) {
linkHandler.handle("https://4pda.to/forum/index.php?showforum=" + item.forumId, router, args)
} else {
linkHandler.handle("https://4pda.to/forum/index.php?showtopic=" + item.topicId + "&view=getnewpost", router, args)
}
}
fun onItemLongClick(item: FavItem) {
viewState.showItemDialogMenu(item)
}
fun copyLink(item: FavItem) {
if (item.isForum) {
Utils.copyToClipBoard("https://4pda.to/forum/index.php?showforum=" + Integer.toString(item.forumId))
} else {
Utils.copyToClipBoard("https://4pda.to/forum/index.php?showtopic=" + Integer.toString(item.topicId))
}
}
fun openAttachments(item: FavItem) {
linkHandler.handle("https://4pda.to/forum/index.php?act=attach&code=showtopic&tid=" + item.topicId, router)
}
fun openForum(item: FavItem) {
linkHandler.handle("https://4pda.to/forum/index.php?showforum=" + item.forumId, router)
}
fun changeFav(action: Int, type: String?, favId: Int) {
favoritesRepository
.editFavorites(action, favId, favId, type)
.subscribe({
viewState.onChangeFav(it)
loadFavorites(currentSt)
}, {
errorHandler.handle(it)
})
.untilDestroy()
}
fun showSubscribeDialog(item: FavItem) {
viewState.showSubscribeDialog(item)
}
}
| gpl-3.0 | 80c02347be4153e2bbb287ca7cba22bd | 32.140845 | 126 | 0.583227 | 4.936364 | false | false | false | false |
ingokegel/intellij-community | plugins/ide-features-trainer/src/training/ui/welcomeScreen/OnboardingLessonPromoter.kt | 1 | 4395 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package training.ui.welcomeScreen
import com.intellij.ide.RecentProjectsManagerBase
import com.intellij.ide.util.PropertiesComponent
import com.intellij.idea.ActionsBundle
import com.intellij.openapi.application.invokeLater
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.projectRoots.Sdk
import com.intellij.openapi.wm.BannerStartPagePromoter
import com.intellij.openapi.wm.impl.welcomeScreen.WelcomeBalloonLayoutImpl
import com.intellij.openapi.wm.impl.welcomeScreen.WelcomeFrame
import com.intellij.ui.scale.JBUIScale
import com.intellij.util.ui.JBUI
import org.jetbrains.annotations.ApiStatus
import org.jetbrains.annotations.Nls
import org.jetbrains.annotations.NonNls
import training.FeaturesTrainerIcons
import training.dsl.LessonUtil
import training.dsl.dropMnemonic
import training.lang.LangManager
import training.learn.CourseManager
import training.learn.LearnBundle
import training.learn.OpenLessonActivities
import training.ui.showOnboardingFeedbackNotification
import training.util.resetPrimaryLanguage
import javax.swing.Icon
import javax.swing.JLabel
import javax.swing.JPanel
private const val PROMO_HIDDEN = "ift.hide.welcome.screen.promo"
/** Do not use lesson itself in the parameters to postpone IFT modules/lessons initialization */
@ApiStatus.Internal
open class OnboardingLessonPromoter(@NonNls private val lessonId: String,
@Nls private val lessonName: String,
@NonNls private val languageName: String) : BannerStartPagePromoter() {
override val promoImage: Icon
get() = FeaturesTrainerIcons.PluginIcon
override fun getPromotion(isEmptyState: Boolean): JPanel? {
scheduleOnboardingFeedback()
return super.getPromotion(isEmptyState)
}
override fun canCreatePromo(isEmptyState: Boolean): Boolean =
!PropertiesComponent.getInstance().getBoolean(PROMO_HIDDEN, false) &&
RecentProjectsManagerBase.getInstanceEx().getRecentPaths().size < 5
override val headerLabel: String
get() = LearnBundle.message("welcome.promo.header")
override val actionLabel: String
get() = LearnBundle.message("welcome.promo.start.tour")
override fun runAction() =
startOnboardingLessonWithSdk()
override val description: String
get() = LearnBundle.message("welcome.promo.description", LessonUtil.productName, languageName)
private fun startOnboardingLessonWithSdk() {
val lesson = CourseManager.instance.lessonsForModules.find { it.id == lessonId }
if (lesson == null) {
logger<OnboardingLessonPromoter>().error("No lesson with id $lessonId")
return
}
val primaryLanguage = lesson.module.primaryLanguage ?: error("No primary language for promoting lesson ${lesson.name}")
resetPrimaryLanguage(primaryLanguage)
LangManager.getInstance().getLangSupport()?.startFromWelcomeFrame { selectedSdk: Sdk? ->
OpenLessonActivities.openOnboardingFromWelcomeScreen(lesson, selectedSdk)
}
}
// A bit hacky way to schedule the onboarding feedback informer after the lesson was closed
private fun scheduleOnboardingFeedback() {
val langSupport = LangManager.getInstance().getLangSupport() ?: return
val onboardingFeedbackData = langSupport.onboardingFeedbackData ?: return
invokeLater {
langSupport.onboardingFeedbackData = null
showOnboardingFeedbackNotification(null, onboardingFeedbackData)
(WelcomeFrame.getInstance()?.balloonLayout as? WelcomeBalloonLayoutImpl)?.showPopup()
}
}
override val closeAction: ((JPanel) -> Unit) = { promoPanel ->
PropertiesComponent.getInstance().setValue(PROMO_HIDDEN, true)
promoPanel.removeAll()
promoPanel.border = JBUI.Borders.empty(0, 2, 0, 0)
promoPanel.isOpaque = false
val text = LearnBundle.message("welcome.promo.close.hint",
ActionsBundle.message("group.HelpMenu.text").dropMnemonic(),
LearnBundle.message("action.ShowLearnPanel.text"), lessonName)
promoPanel.add(JLabel("<html>$text</html>").also {
it.foreground = JBUI.CurrentTheme.ContextHelp.FOREGROUND
it.font = JBUI.Fonts.label().deriveFont(JBUI.Fonts.label().size2D + JBUIScale.scale(-1))
})
promoPanel.revalidate()
}
} | apache-2.0 | 6a85aa19806afb71878caec580ae6d55 | 42.098039 | 123 | 0.758817 | 4.715665 | false | false | false | false |
hermantai/samples | kotlin/udacity-kotlin-bootcamp/HelloKotlin/src/Spices/Spice.kt | 1 | 1441 | package Spices
abstract class Spice(val name: String, val spiciness: String = "mild", color: SpiceColor): SpiceColor by color{
val heat: Int
get() {
return when (spiciness) {
"mild" -> 1
"medium" -> 3
"spicy" -> 5
"very spicy" -> 7
"extremely spicy" -> 10
else -> 0
}
}
init {
println("Spice: name=$name, spiciness=$spiciness, heat=$heat, color=${color.color}")
}
abstract fun prepareSpice()
}
class Curry(name: String, spiciness : String = "extremely spice", color: SpiceColor = YellowSpiceColor) :
Spice(name, spiciness = spiciness, color = color), Grinder {
override fun prepareSpice() {
grind()
}
override fun grind() {
println("grind curry")
}
init {
println("color is $color")
}
}
interface Grinder {
fun grind()
}
interface SpiceColor {
val color: Color
}
object YellowSpiceColor : SpiceColor {
override val color = Color.YELLOW
}
data class SpiceContainer(val spice: Spice) {
val label = spice.name
}
enum class Color(val rgb: Int) {
RED(0xFF0000), GREEN(0x00FF00), BLUE(0x0000FF), YELLOW(0xFFFF00);
}
fun main(args: Array<String>) {
Curry(name = "yellow curry")
val spiceCabinet = listOf(SpiceContainer(Curry("Yellow Curry", "mild")),
SpiceContainer(Curry("Red Curry", "medium")),
SpiceContainer(Curry("Green Curry", "spicy")))
for(element in spiceCabinet) println(element.label)
} | apache-2.0 | dffadf7e34b511752a5bff90b1ad1bec | 20.522388 | 111 | 0.640527 | 3.188053 | false | false | false | false |
hermantai/samples | kotlin/kotlin-and-android-development-featuring-jetpack/chapter-5/app/src/main/java/dev/mfazio/pennydrop/data/PennyDropDatabase.kt | 1 | 1561 | package dev.mfazio.pennydrop.data
import android.content.Context
import androidx.room.Database
import androidx.room.Room
import androidx.room.RoomDatabase
import androidx.room.TypeConverters
import androidx.sqlite.db.SupportSQLiteDatabase
import dev.mfazio.pennydrop.game.AI
import dev.mfazio.pennydrop.types.Player
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.launch
@Database(
entities = [Game::class, Player::class, GameStatus::class],
version = 1,
exportSchema = false
)
@TypeConverters(Converters::class)
abstract class PennyDropDatabase : RoomDatabase() {
abstract fun pennyDropDao(): PennyDropDao
companion object {
@Volatile
private var instance: PennyDropDatabase? = null
fun getDatabase(
context: Context,
scope: CoroutineScope
): PennyDropDatabase =
instance ?: synchronized(this) {
val instance = Room.databaseBuilder(
context,
PennyDropDatabase::class.java,
"PennyDropDatabase"
).addCallback(object : RoomDatabase.Callback() {
override fun onCreate(db: SupportSQLiteDatabase) {
super.onCreate(db)
scope.launch {
instance?.pennyDropDao()?.insertPlayers(AI.basicAI.map(AI::toPlayer))
}
}
}).build()
this.instance = instance
instance
}
}
} | apache-2.0 | 9cc2d4222fb8dc38b1ece196925873ed | 30.24 | 97 | 0.605381 | 5.134868 | false | false | false | false |
dmeybohm/chocolate-cakephp | src/main/kotlin/com/daveme/chocolateCakePHP/view/ViewHelperGotoDeclarationHandler.kt | 1 | 1917 | package com.daveme.chocolateCakePHP.view
import com.daveme.chocolateCakePHP.Settings
import com.daveme.chocolateCakePHP.viewHelperClassesFromFieldName
import com.daveme.chocolateCakePHP.startsWithUppercaseCharacter
import com.intellij.codeInsight.navigation.actions.GotoDeclarationHandler
import com.intellij.openapi.actionSystem.DataContext
import com.intellij.openapi.editor.Editor
import com.intellij.patterns.PlatformPatterns
import com.intellij.psi.PsiElement
import com.jetbrains.php.PhpIndex
import com.jetbrains.php.lang.psi.elements.FieldReference
class ViewHelperGotoDeclarationHandler : GotoDeclarationHandler {
override fun getGotoDeclarationTargets(psiElement: PsiElement?, i: Int, editor: Editor): Array<PsiElement>? {
if (psiElement == null) {
return PsiElement.EMPTY_ARRAY
}
val settings = Settings.getInstance(psiElement.project)
if (!settings.enabled) {
return PsiElement.EMPTY_ARRAY
}
if (!PlatformPatterns.psiElement().withParent(FieldReference::class.java).accepts(psiElement)) {
return PsiElement.EMPTY_ARRAY
}
val parent = psiElement.parent ?: return PsiElement.EMPTY_ARRAY
val fieldReference = parent as FieldReference
val fieldName = fieldReference.name ?: return PsiElement.EMPTY_ARRAY
val classReference = fieldReference.classReference ?: return PsiElement.EMPTY_ARRAY
if (!fieldName.startsWithUppercaseCharacter()) {
return PsiElement.EMPTY_ARRAY
}
if (classReference.textMatches("\$this")) {
val project = psiElement.project
val phpIndex = PhpIndex.getInstance(project)
return phpIndex.viewHelperClassesFromFieldName(settings, fieldName).toTypedArray()
}
return PsiElement.EMPTY_ARRAY
}
override fun getActionText(dataContext: DataContext): String? = null
} | mit | 41ff8f914edc9b291a03e5d28f6b1b96 | 40.695652 | 113 | 0.735003 | 5.310249 | false | false | false | false |
GunoH/intellij-community | platform/core-impl/src/com/intellij/ide/plugins/PluginLoadingResult.kt | 2 | 6666 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
@file:Suppress("ReplaceGetOrSet", "ReplacePutWithAssignment")
package com.intellij.ide.plugins
import com.intellij.core.CoreBundle
import com.intellij.openapi.application.PathManager
import com.intellij.openapi.application.impl.ApplicationInfoImpl
import com.intellij.openapi.extensions.PluginId
import com.intellij.openapi.util.BuildNumber
import com.intellij.util.PlatformUtils
import com.intellij.util.text.VersionComparatorUtil
import org.jetbrains.annotations.ApiStatus
import org.jetbrains.annotations.TestOnly
import org.jetbrains.annotations.VisibleForTesting
import java.util.*
import kotlin.io.path.name
// https://www.jetbrains.org/intellij/sdk/docs/basics/getting_started/plugin_compatibility.html
// If a plugin does not include any module dependency tags in its plugin.xml,
// it's assumed to be a legacy plugin and is loaded only in IntelliJ IDEA.
@ApiStatus.Internal
class PluginLoadingResult(private val checkModuleDependencies: Boolean = !PlatformUtils.isIntelliJ()) {
private val incompletePlugins = HashMap<PluginId, IdeaPluginDescriptorImpl>()
@JvmField val enabledPluginsById = HashMap<PluginId, IdeaPluginDescriptorImpl>()
private val idMap = HashMap<PluginId, IdeaPluginDescriptorImpl>()
@JvmField var duplicateModuleMap: MutableMap<PluginId, MutableList<IdeaPluginDescriptorImpl>>? = null
private val pluginErrors = HashMap<PluginId, PluginLoadingError>()
@VisibleForTesting
@JvmField val shadowedBundledIds: MutableSet<PluginId> = Collections.newSetFromMap(HashMap())
@get:TestOnly
val hasPluginErrors: Boolean
get() = !pluginErrors.isEmpty()
@get:TestOnly
val enabledPlugins: List<IdeaPluginDescriptorImpl>
get() = enabledPluginsById.entries.sortedBy { it.key }.map { it.value }
internal fun copyPluginErrors(): MutableMap<PluginId, PluginLoadingError> = HashMap(pluginErrors)
fun getIncompleteIdMap(): Map<PluginId, IdeaPluginDescriptorImpl> = incompletePlugins
fun getIdMap(): Map<PluginId, IdeaPluginDescriptorImpl> = idMap
private fun addIncompletePlugin(plugin: IdeaPluginDescriptorImpl, error: PluginLoadingError?) {
// do not report if some compatible plugin were already added
// no race condition here: plugins from classpath are loaded before and not in parallel to loading from plugin dir
if (idMap.containsKey(plugin.pluginId)) {
return
}
val existingIncompletePlugin = incompletePlugins.putIfAbsent(plugin.pluginId, plugin)
if (existingIncompletePlugin != null && VersionComparatorUtil.compare(plugin.version, existingIncompletePlugin.version) > 0) {
incompletePlugins.put(plugin.pluginId, plugin)
if (error != null) {
// force put
pluginErrors.put(plugin.pluginId, error)
}
}
else if (error != null) {
pluginErrors.putIfAbsent(plugin.pluginId, error)
}
}
/**
* @see [com.intellij.openapi.project.ex.ProjectManagerEx]
*/
fun addAll(descriptors: Iterable<IdeaPluginDescriptorImpl?>, overrideUseIfCompatible: Boolean, productBuildNumber: BuildNumber) {
val isMainProcess = java.lang.Boolean.getBoolean("ide.per.project.instance")
&& !PathManager.getPluginsDir().name.startsWith("perProject_")
val applicationInfoEx = ApplicationInfoImpl.getShadowInstance()
for (descriptor in descriptors) {
if (descriptor != null
&& (!isMainProcess || applicationInfoEx.isEssentialPlugin(descriptor.pluginId))) {
add(descriptor, overrideUseIfCompatible, productBuildNumber)
}
}
}
private fun add(descriptor: IdeaPluginDescriptorImpl, overrideUseIfCompatible: Boolean, productBuildNumber: BuildNumber) {
val pluginId = descriptor.pluginId
descriptor.isIncomplete?.let { error ->
addIncompletePlugin(descriptor, error.takeIf { !it.isDisabledError })
return
}
if (checkModuleDependencies && !descriptor.isBundled && descriptor.packagePrefix == null && !hasModuleDependencies(descriptor)) {
addIncompletePlugin(descriptor, PluginLoadingError(
plugin = descriptor,
detailedMessageSupplier = { CoreBundle.message("plugin.loading.error.long.compatible.with.intellij.idea.only", descriptor.name) },
shortMessageSupplier = { CoreBundle.message("plugin.loading.error.short.compatible.with.intellij.idea.only") },
isNotifyUser = true
))
return
}
// remove any error that occurred for plugin with the same `id`
pluginErrors.remove(pluginId)
incompletePlugins.remove(pluginId)
val prevDescriptor = enabledPluginsById.put(pluginId, descriptor)
if (prevDescriptor == null) {
idMap.put(pluginId, descriptor)
for (module in descriptor.modules) {
checkAndAdd(descriptor, module)
}
return
}
if (prevDescriptor.isBundled || descriptor.isBundled) {
shadowedBundledIds.add(pluginId)
}
if (PluginManagerCore.checkBuildNumberCompatibility(descriptor, productBuildNumber) == null &&
(overrideUseIfCompatible || VersionComparatorUtil.compare(descriptor.version, prevDescriptor.version) > 0)) {
PluginManagerCore.getLogger().info("$descriptor overrides $prevDescriptor")
idMap.put(pluginId, descriptor)
return
}
else {
enabledPluginsById.put(pluginId, prevDescriptor)
return
}
}
private fun checkAndAdd(descriptor: IdeaPluginDescriptorImpl, id: PluginId) {
duplicateModuleMap?.get(id)?.let { duplicates ->
duplicates.add(descriptor)
return
}
val existingDescriptor = idMap.put(id, descriptor) ?: return
// if duplicated, both are removed
idMap.remove(id)
if (duplicateModuleMap == null) {
duplicateModuleMap = LinkedHashMap()
}
val list = ArrayList<IdeaPluginDescriptorImpl>(2)
list.add(existingDescriptor)
list.add(descriptor)
duplicateModuleMap!!.put(id, list)
}
}
// todo merge into PluginSetState?
@ApiStatus.Internal
data class PluginManagerState internal constructor(
@JvmField val pluginSet: PluginSet,
@JvmField val pluginIdsToDisable: Set<PluginId>,
@JvmField val pluginIdsToEnable: Set<PluginId>,
)
internal fun hasModuleDependencies(descriptor: IdeaPluginDescriptorImpl): Boolean {
for (dependency in descriptor.pluginDependencies) {
val dependencyPluginId = dependency.pluginId
if (PluginManagerCore.JAVA_PLUGIN_ID == dependencyPluginId ||
PluginManagerCore.JAVA_MODULE_ID == dependencyPluginId ||
PluginManagerCore.isModuleDependency(dependencyPluginId)) {
return true
}
}
return false
} | apache-2.0 | 56fad627c9aba53569d801e75b7c53fa | 38.922156 | 138 | 0.744824 | 4.778495 | false | false | false | false |
GunoH/intellij-community | plugins/maven/src/main/java/org/jetbrains/idea/maven/externalSystemIntegration/output/quickfixes/MavenBadJvmConfigEventParser.kt | 2 | 9341 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.idea.maven.externalSystemIntegration.output.quickfixes
import com.intellij.build.events.BuildEvent
import com.intellij.build.events.MessageEvent
import com.intellij.build.events.impl.BuildIssueEventImpl
import com.intellij.build.issue.BuildIssue
import com.intellij.build.issue.BuildIssueQuickFix
import com.intellij.build.issue.quickfix.OpenFileQuickFix
import com.intellij.build.output.BuildOutputInstantReader
import com.intellij.execution.RunnerAndConfigurationSettings
import com.intellij.execution.impl.RunDialog
import com.intellij.execution.impl.RunManagerImpl
import com.intellij.openapi.actionSystem.DataContext
import com.intellij.openapi.project.Project
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.pom.Navigatable
import org.jetbrains.idea.maven.buildtool.quickfix.OpenMavenImportingSettingsQuickFix
import org.jetbrains.idea.maven.buildtool.quickfix.OpenMavenRunnerSettingsQuickFix
import org.jetbrains.idea.maven.execution.MavenExternalParameters
import org.jetbrains.idea.maven.execution.MavenRunConfiguration
import org.jetbrains.idea.maven.execution.MavenRunConfigurationType
import org.jetbrains.idea.maven.externalSystemIntegration.output.LogMessageType
import org.jetbrains.idea.maven.externalSystemIntegration.output.MavenLogEntryReader
import org.jetbrains.idea.maven.externalSystemIntegration.output.MavenLoggedEventParser
import org.jetbrains.idea.maven.externalSystemIntegration.output.MavenParsingContext
import org.jetbrains.idea.maven.externalSystemIntegration.output.importproject.MavenImportLoggedEventParser
import org.jetbrains.idea.maven.project.MavenConfigurableBundle.message
import org.jetbrains.idea.maven.project.MavenProjectBundle
import org.jetbrains.idea.maven.project.MavenProjectsManager
import org.jetbrains.idea.maven.server.MavenDistributionsCache
import java.nio.file.Paths
import java.util.concurrent.CompletableFuture
import java.util.function.Consumer
class MavenBadJvmConfigEventParser : MavenLoggedEventParser {
override fun supportsType(type: LogMessageType?): Boolean {
return type == null
}
override fun checkLogLine(parentId: Any,
parsingContext: MavenParsingContext,
logLine: MavenLogEntryReader.MavenLogEntry,
logEntryReader: MavenLogEntryReader,
messageConsumer: Consumer<in BuildEvent?>): Boolean {
var errorLine = logLine.line
if (errorLine.startsWith(MavenJvmConfigBuildIssue.VM_INIT_ERROR)) {
val causeLine = logEntryReader.readLine()?.line ?: ""
if (causeLine.isNotEmpty()) {
errorLine += "\n$causeLine"
}
messageConsumer.accept(
BuildIssueEventImpl(
parentId,
MavenJvmConfigBuildIssue.getRunnerIssue(logLine.line, errorLine, parsingContext.ideaProject, parsingContext.runConfiguration),
MessageEvent.Kind.ERROR
)
)
return true
}
return false
}
}
class MavenImportBadJvmConfigEventParser : MavenImportLoggedEventParser {
override fun processLogLine(project: Project,
logLine: String,
reader: BuildOutputInstantReader,
messageConsumer: Consumer<in BuildEvent>): Boolean {
var errorLine = logLine
if (logLine.startsWith(MavenJvmConfigBuildIssue.VM_INIT_ERROR)) {
val causeLine = reader.readLine() ?: ""
if (causeLine.isNotEmpty()) {
errorLine += "\n$causeLine"
}
messageConsumer.accept(BuildIssueEventImpl(Any(),
MavenJvmConfigBuildIssue.getImportIssue(logLine, errorLine, project),
MessageEvent.Kind.ERROR))
return true
}
return false
}
}
class MavenJvmConfigOpenQuickFix(private val jvmConfig: VirtualFile) : BuildIssueQuickFix {
override val id: String = "open_maven_jvm_config_quick_fix_" + jvmConfig
override fun runQuickFix(project: Project, dataContext: DataContext): CompletableFuture<*> {
OpenFileQuickFix.showFile(project, jvmConfig.toNioPath(), null)
return CompletableFuture.completedFuture<Any>(null)
}
}
class MavenRunConfigurationOpenQuickFix(private val runnerAndConfigurationSettings: RunnerAndConfigurationSettings) : BuildIssueQuickFix {
override val id: String = "open_maven_run_configuration_open_quick_fix"
override fun runQuickFix(project: Project, dataContext: DataContext): CompletableFuture<*> {
RunDialog.editConfiguration(project, runnerAndConfigurationSettings, message("maven.settings.runner.vm.options"))
return CompletableFuture.completedFuture<Any>(null)
}
}
object MavenJvmConfigBuildIssue {
const val VM_INIT_ERROR: String = "Error occurred during initialization of VM"
fun getRunnerIssue(title: String, errorMessage: String, project: Project, runConfiguration: MavenRunConfiguration): BuildIssue {
val jvmConfig: VirtualFile? = MavenExternalParameters.getJvmConfig(runConfiguration.runnerParameters.workingDirPath)
val mavenProject = MavenProjectsManager.getInstance(project).projectsFiles
.asSequence()
.filter { Paths.get(runConfiguration.runnerParameters.workingDirPath).equals(it.toNioPath().parent) }
.map { MavenProjectsManager.getInstance(project).findProject(it) }
.firstOrNull()
val quickFixes = mutableListOf<BuildIssueQuickFix>()
val issueDescription = StringBuilder(errorMessage)
issueDescription.append("\n\n")
issueDescription.append(MavenProjectBundle.message("maven.quickfix.header.possible.solution"))
issueDescription.append("\n")
val openMavenRunnerSettingsQuickFix = OpenMavenRunnerSettingsQuickFix(message("maven.settings.runner.vm.options"))
quickFixes.add(openMavenRunnerSettingsQuickFix)
issueDescription.append(MavenProjectBundle.message("maven.quickfix.jvm.options.runner.settings", openMavenRunnerSettingsQuickFix.id))
issueDescription.append("\n")
val configurationById = runConfiguration
.let { RunManagerImpl.getInstanceImpl(project).findConfigurationByTypeAndName(MavenRunConfigurationType.getInstance(), it.name) }
if (configurationById != null && configurationById.configuration is MavenRunConfiguration) {
val configuration = configurationById.configuration as MavenRunConfiguration
if (!configuration.runnerSettings?.vmOptions.isNullOrBlank()) {
val mavenRunConfigurationOpenQuickFix = MavenRunConfigurationOpenQuickFix(configurationById)
quickFixes.add(mavenRunConfigurationOpenQuickFix)
issueDescription.append(MavenProjectBundle
.message("maven.quickfix.jvm.options.run.configuration", mavenRunConfigurationOpenQuickFix.id))
issueDescription.append("\n")
}
}
if (jvmConfig != null) {
val mavenJvmConfigOpenQuickFix = MavenJvmConfigOpenQuickFix(jvmConfig)
quickFixes.add(mavenJvmConfigOpenQuickFix)
issueDescription.append(MavenProjectBundle.message("maven.quickfix.jvm.options.config.file",
mavenProject?.displayName ?: "",
mavenJvmConfigOpenQuickFix.id))
}
return object : BuildIssue {
override val title: String = title
override val description: String = issueDescription.toString()
override val quickFixes = quickFixes
override fun getNavigatable(project: Project): Navigatable? = null
}
}
fun getImportIssue(title: String, errorMessage: String, project: Project): BuildIssue {
val quickFixes = mutableListOf<BuildIssueQuickFix>()
val issueDescription = StringBuilder(errorMessage)
issueDescription.append("\n\n")
issueDescription.append(MavenProjectBundle.message("maven.quickfix.header.possible.solution"))
issueDescription.append("\n")
val openMavenImportingSettingsQuickFix = OpenMavenImportingSettingsQuickFix(message("maven.settings.importing.vm.options"))
quickFixes.add(openMavenImportingSettingsQuickFix)
issueDescription.append(
MavenProjectBundle.message("maven.quickfix.jvm.options.import.settings", openMavenImportingSettingsQuickFix.id))
MavenProjectsManager.getInstance(project).rootProjects.forEach {
val jvmConfig: VirtualFile? = it.file.path
.let { MavenDistributionsCache.getInstance(project).getMultimoduleDirectory(it) }
.let { MavenExternalParameters.getJvmConfig(it) }
if (jvmConfig != null) {
val mavenJvmConfigOpenQuickFix = MavenJvmConfigOpenQuickFix(jvmConfig)
quickFixes.add(mavenJvmConfigOpenQuickFix)
issueDescription.append("\n")
issueDescription.append(MavenProjectBundle
.message("maven.quickfix.jvm.options.config.file", it.displayName, mavenJvmConfigOpenQuickFix.id))
}
}
return object : BuildIssue {
override val title: String = title
override val description: String = issueDescription.toString()
override val quickFixes = quickFixes
override fun getNavigatable(project: Project): Navigatable? = null
}
}
} | apache-2.0 | 88afc7067196e82a9d2402912041e112 | 47.910995 | 158 | 0.747779 | 5.082155 | false | true | false | false |
ronaldosanches/McCabe-Thiele-for-Android-Kotlin | app/src/main/java/com/ronaldosanches/VerticalTextView.kt | 1 | 1613 | package com.ronaldosanches.mccabethiele
import android.content.Context
import android.graphics.Canvas
import android.util.AttributeSet
import android.view.Gravity
import android.widget.TextView
/**
* Created by rnd on 08/09/2017.
*/
class VerticalTextView(context: Context,
attrs: AttributeSet) : TextView(context, attrs) {
internal val topDown: Boolean
init {
val gravity = gravity
if (Gravity.isVertical(gravity) && gravity and Gravity.VERTICAL_GRAVITY_MASK == Gravity.BOTTOM) {
setGravity(
gravity and Gravity.HORIZONTAL_GRAVITY_MASK or Gravity.TOP)
topDown = false
} else {
topDown = true
}
}
override fun onMeasure(widthMeasureSpec: Int,
heightMeasureSpec: Int) {
super.onMeasure(heightMeasureSpec,
widthMeasureSpec)
setMeasuredDimension(measuredHeight,
measuredWidth)
}
override fun onDraw(canvas: Canvas) {
val textPaint = paint
textPaint.color = currentTextColor
textPaint.drawableState = drawableState
canvas.save()
if (topDown) {
canvas.translate(width.toFloat(), 0f)
canvas.rotate(90f)
} else {
canvas.translate(0f, height.toFloat())
canvas.rotate(-90f)
}
canvas.translate(compoundPaddingLeft.toFloat(),
extendedPaddingTop.toFloat())
layout.draw(canvas)
canvas.restore()
}
}
| mit | 4579703468a35de1fee6c715ee09dd38 | 26.298246 | 105 | 0.584625 | 4.932722 | false | false | false | false |
himikof/intellij-rust | src/main/kotlin/org/rust/lang/core/psi/ext/RsSelfParameter.kt | 1 | 1238 | /*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.lang.core.psi.ext
import com.intellij.lang.ASTNode
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiNameIdentifierOwner
import com.intellij.psi.stubs.IStubElementType
import org.rust.ide.icons.RsIcons
import org.rust.lang.core.psi.RsSelfParameter
import org.rust.lang.core.stubs.RsSelfParameterStub
val RsSelfParameter.isMut: Boolean get() = stub?.isMut ?: (mut != null)
val RsSelfParameter.isRef: Boolean get() = stub?.isRef ?: (and != null)
abstract class RsSelfParameterImplMixin : RsStubbedElementImpl<RsSelfParameterStub>,
PsiNameIdentifierOwner,
RsSelfParameter {
constructor(node: ASTNode) : super(node)
constructor(stub: RsSelfParameterStub, nodeType: IStubElementType<*, *>) : super(stub, nodeType)
override fun getNameIdentifier(): PsiElement = self
override fun getName(): String = "self"
override fun setName(name: String): PsiElement? {
// can't rename self
throw UnsupportedOperationException()
}
override fun getIcon(flags: Int) = RsIcons.ARGUMENT
}
| mit | 44d87503e689f0637bd8a7569ca2b184 | 34.371429 | 100 | 0.701939 | 4.421429 | false | false | false | false |
codebutler/farebot | farebot-app/src/main/java/com/codebutler/farebot/app/feature/home/HomeScreen.kt | 1 | 6538 | /*
* HomeScreen.kt
*
* This file is part of FareBot.
* Learn more at: https://codebutler.github.io/farebot/
*
* Copyright (C) 2017 Eric Butler <[email protected]>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.codebutler.farebot.app.feature.home
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.nfc.NfcAdapter
import android.nfc.TagLostException
import android.provider.Settings
import androidx.appcompat.app.AlertDialog
import android.view.Menu
import com.codebutler.farebot.R
import com.codebutler.farebot.app.core.activity.ActivityOperations
import com.codebutler.farebot.app.core.analytics.AnalyticsEventName
import com.codebutler.farebot.app.core.analytics.logAnalyticsEvent
import com.codebutler.farebot.app.core.inject.ScreenScope
import com.codebutler.farebot.app.core.ui.ActionBarOptions
import com.codebutler.farebot.app.core.ui.FareBotScreen
import com.codebutler.farebot.app.core.util.ErrorUtils
import com.codebutler.farebot.app.feature.card.CardScreen
import com.codebutler.farebot.app.feature.help.HelpScreen
import com.codebutler.farebot.app.feature.history.HistoryScreen
import com.codebutler.farebot.app.feature.keys.KeysScreen
import com.codebutler.farebot.app.feature.main.MainActivity.MainActivityComponent
import com.codebutler.farebot.app.feature.prefs.FareBotPreferenceActivity
import com.crashlytics.android.Crashlytics
import com.uber.autodispose.kotlin.autoDisposable
import dagger.Component
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import javax.inject.Inject
class HomeScreen : FareBotScreen<HomeScreen.HomeComponent, HomeScreenView>(),
HomeScreenView.Listener {
companion object {
private val URL_ABOUT = Uri.parse("https://codebutler.github.com/farebot")
}
@Inject lateinit var activityOperations: ActivityOperations
@Inject lateinit var cardStream: CardStream
override fun onCreateView(context: Context): HomeScreenView = HomeScreenView(context, this)
override fun getTitle(context: Context): String = context.getString(R.string.app_name)
override fun getActionBarOptions(): ActionBarOptions = ActionBarOptions(shadow = false)
override fun onShow(context: Context) {
super.onShow(context)
activityOperations.menuItemClick
.autoDisposable(this)
.subscribe({ menuItem ->
when (menuItem.itemId) {
R.id.history -> navigator.goTo(HistoryScreen())
R.id.help -> navigator.goTo(HelpScreen())
R.id.prefs -> activity.startActivity(FareBotPreferenceActivity.newIntent(activity))
R.id.keys -> navigator.goTo(KeysScreen())
R.id.about -> {
activity.startActivity(Intent(Intent.ACTION_VIEW, URL_ABOUT))
}
}
})
val adapter = NfcAdapter.getDefaultAdapter(context)
if (adapter == null) {
view.showNfcError(HomeScreenView.NfcError.UNAVAILABLE)
} else if (!adapter.isEnabled) {
view.showNfcError(HomeScreenView.NfcError.DISABLED)
} else {
view.showNfcError(HomeScreenView.NfcError.NONE)
}
cardStream.observeCards()
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.autoDisposable(this)
.subscribe { card ->
logAnalyticsEvent(AnalyticsEventName.SCAN_CARD, card.cardType().toString())
navigator.goTo(CardScreen(card))
}
cardStream.observeLoading()
.observeOn(AndroidSchedulers.mainThread())
.autoDisposable(this)
.subscribe { loading -> view.showLoading(loading) }
cardStream.observeErrors()
.observeOn(AndroidSchedulers.mainThread())
.autoDisposable(this)
.subscribe { ex ->
logAnalyticsEvent(AnalyticsEventName.SCAN_CARD_ERROR, ErrorUtils.getErrorMessage(ex))
when (ex) {
is CardStream.CardUnauthorizedException -> AlertDialog.Builder(activity)
.setTitle(R.string.locked_card)
.setMessage(R.string.keys_required)
.setPositiveButton(android.R.string.ok, null)
.show()
is TagLostException -> AlertDialog.Builder(activity)
.setTitle(R.string.tag_lost)
.setMessage(R.string.tag_lost_message)
.setPositiveButton(android.R.string.ok, null)
.show()
else -> {
Crashlytics.logException(ex)
ErrorUtils.showErrorAlert(activity, ex)
}
}
}
}
override fun onUpdateMenu(menu: Menu) {
activity.menuInflater.inflate(R.menu.screen_main, menu)
}
override fun onNfcErrorButtonClicked() {
activity.startActivity(Intent(Settings.ACTION_WIRELESS_SETTINGS))
}
override fun onSampleButtonClicked() {
cardStream.emitSample()
}
override fun createComponent(parentComponent: MainActivityComponent): HomeComponent =
DaggerHomeScreen_HomeComponent.builder()
.mainActivityComponent(parentComponent)
.build()
override fun inject(component: HomeComponent) {
component.inject(this)
}
@ScreenScope
@Component(dependencies = arrayOf(MainActivityComponent::class))
interface HomeComponent {
fun inject(homeScreen: HomeScreen)
}
}
| gpl-3.0 | 4fc03cb320a976e8b971054581ae2453 | 39.8625 | 107 | 0.651422 | 4.842963 | false | false | false | false |
saffih/ElmDroid | app/src/main/java/elmdroid/elmdroid/example5/ItemDetailFragment.kt | 1 | 2157 | package elmdroid.elmdroid.example5
import android.os.Bundle
import android.support.v4.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import elmdroid.elmdroid.R
import elmdroid.elmdroid.example5.itemlist.MItem
import kotlinx.android.synthetic.main.activity_item_detail.*
import kotlinx.android.synthetic.main.item_detail.view.*
/**
* A fragment representing a single Item detail screen.
* This fragment is either contained in a [ItemListActivity]
* in two-pane mode (on tablets) or a [ItemDetailActivity]
* on handsets.
*/
/**
* Mandatory empty constructor for the fragment manager to instantiate the
* fragment (e.g. upon screen orientation changes).
*/
class ItemDetailFragment : Fragment() {
private var mItem: MItem? = null
/**
* The dummy content this fragment is presenting.
*/
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
if (arguments.containsKey(ARG_ITEM_ID)) {
// Load the dummy content specified by the fragment
// arguments. In a real-world scenario, use a Loader
// to load content from a content provider.
val key = arguments.getString(ItemDetailFragment.ARG_ITEM_ID)
mItem = ItemListActivity.itemListActivity!!.model.activity.byId.get(key)
val activity = this.activity as ItemDetailActivity
val appBarLayout = activity.toolbar_layout
appBarLayout.title = mItem!!.content
}
}
override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?,
savedInstanceState: Bundle?): View? {
val rootView = inflater!!.inflate(R.layout.item_detail, container, false)
// Show the dummy content as text in a TextView.
if (mItem != null) {
rootView.item_detail.text = mItem!!.details
}
return rootView
}
companion object {
/**
* The fragment argument representing the item ID that this fragment
* represents.
*/
val ARG_ITEM_ID = "item_id"
}
}
| apache-2.0 | 01054c1c2c18c8dfd2dc80b629ba0a7d | 31.19403 | 84 | 0.669912 | 4.599147 | false | false | false | false |
dahlstrom-g/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/intentions/ToOrdinaryStringLiteralIntention.kt | 2 | 4226 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.intentions
import com.intellij.codeInsight.intention.LowPriorityAction
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.util.text.StringUtil
import org.jetbrains.kotlin.idea.KotlinBundle
import org.jetbrains.kotlin.idea.base.psi.replaced
import org.jetbrains.kotlin.idea.inspections.collections.isCalling
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.endOffset
import org.jetbrains.kotlin.psi.psiUtil.getQualifiedExpressionForReceiver
import org.jetbrains.kotlin.psi.psiUtil.startOffset
class ToOrdinaryStringLiteralIntention : SelfTargetingOffsetIndependentIntention<KtStringTemplateExpression>(
KtStringTemplateExpression::class.java,
KotlinBundle.lazyMessage("to.ordinary.string.literal")
), LowPriorityAction {
companion object {
private val TRIM_INDENT_FUNCTIONS = listOf(FqName("kotlin.text.trimIndent"), FqName("kotlin.text.trimMargin"))
}
override fun isApplicableTo(element: KtStringTemplateExpression): Boolean {
return element.text.startsWith("\"\"\"")
}
override fun applyTo(element: KtStringTemplateExpression, editor: Editor?) {
val startOffset = element.startOffset
val endOffset = element.endOffset
val currentOffset = editor?.caretModel?.currentCaret?.offset ?: startOffset
val entries = element.entries
val trimIndentCall = getTrimIndentCall(element, entries)
val text = buildString {
append("\"")
if (trimIndentCall != null) {
append(trimIndentCall.stringTemplateText)
} else {
entries.joinTo(buffer = this, separator = "") {
if (it is KtLiteralStringTemplateEntry) it.text.escape() else it.text
}
}
append("\"")
}
val replaced = (trimIndentCall?.qualifiedExpression ?: element).replaced(KtPsiFactory(element).createExpression(text))
val offset = when {
currentOffset - startOffset < 2 -> startOffset
endOffset - currentOffset < 2 -> replaced.endOffset
else -> maxOf(currentOffset - 2, replaced.startOffset)
}
editor?.caretModel?.moveToOffset(offset)
}
private fun String.escape(escapeLineSeparators: Boolean = true): String {
var text = this
text = text.replace("\\", "\\\\")
text = text.replace("\"", "\\\"")
return if (escapeLineSeparators) text.escapeLineSeparators() else text
}
private fun String.escapeLineSeparators(): String {
return StringUtil.convertLineSeparators(this, "\\n")
}
private fun getTrimIndentCall(
element: KtStringTemplateExpression,
entries: Array<KtStringTemplateEntry>
): TrimIndentCall? {
val qualifiedExpression = element.getQualifiedExpressionForReceiver()?.takeIf {
it.callExpression?.isCalling(TRIM_INDENT_FUNCTIONS) == true
} ?: return null
val marginPrefix = if (qualifiedExpression.calleeName == "trimMargin") {
when (val arg = qualifiedExpression.callExpression?.valueArguments?.singleOrNull()?.getArgumentExpression()) {
null -> "|"
is KtStringTemplateExpression -> arg.entries.singleOrNull()?.takeIf { it is KtLiteralStringTemplateEntry }?.text
else -> null
} ?: return null
} else {
null
}
val stringTemplateText = entries
.joinToString(separator = "") {
if (it is KtLiteralStringTemplateEntry) it.text.escape(escapeLineSeparators = false) else it.text
}
.let { if (marginPrefix != null) it.trimMargin(marginPrefix) else it.trimIndent() }
.escapeLineSeparators()
return TrimIndentCall(qualifiedExpression, stringTemplateText)
}
private data class TrimIndentCall(
val qualifiedExpression: KtQualifiedExpression,
val stringTemplateText: String
)
}
| apache-2.0 | 10f808d0f820a4c6bca9e846468662b2 | 40.841584 | 158 | 0.67629 | 5.417949 | false | false | false | false |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.