repo_name
stringlengths
7
79
path
stringlengths
8
206
copies
stringclasses
36 values
size
stringlengths
2
6
content
stringlengths
55
523k
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
7.18
99.5
line_max
int64
16
979
alpha_frac
float64
0.3
0.87
ratio
float64
2.01
8.07
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
Maccimo/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/intentions/UsePropertyAccessSyntaxIntention.kt
2
14679
// 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.intentions import com.intellij.codeInspection.CleanupLocalInspectionTool import com.intellij.openapi.editor.Editor import com.intellij.openapi.project.Project import com.intellij.openapi.ui.LabeledComponent import com.intellij.openapi.util.Key import com.intellij.profile.codeInspection.InspectionProjectProfileManager import com.intellij.psi.PsiElement import org.jdom.Element import org.jetbrains.kotlin.descriptors.CallableDescriptor import org.jetbrains.kotlin.descriptors.FunctionDescriptor import org.jetbrains.kotlin.diagnostics.Severity import org.jetbrains.kotlin.idea.FrontendInternals import org.jetbrains.kotlin.idea.KotlinBundle import org.jetbrains.kotlin.idea.caches.resolve.analyzeInContext import org.jetbrains.kotlin.idea.caches.resolve.getResolutionFacade import org.jetbrains.kotlin.idea.caches.resolve.safeAnalyzeNonSourceRootCode import org.jetbrains.kotlin.idea.configuration.ui.NotPropertyListPanel import org.jetbrains.kotlin.idea.core.NotPropertiesService import org.jetbrains.kotlin.idea.base.psi.copied import org.jetbrains.kotlin.idea.base.psi.replaced import org.jetbrains.kotlin.idea.inspections.IntentionBasedInspection import org.jetbrains.kotlin.idea.resolve.ResolutionFacade import org.jetbrains.kotlin.idea.resolve.dataFlowValueFactory import org.jetbrains.kotlin.idea.resolve.frontendService import org.jetbrains.kotlin.idea.resolve.languageVersionSettings import org.jetbrains.kotlin.idea.util.application.runWriteActionIfPhysical import org.jetbrains.kotlin.idea.util.application.withPsiAttachment import org.jetbrains.kotlin.idea.util.getResolutionScope import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.name.FqNameUnsafe import org.jetbrains.kotlin.name.Name import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.getQualifiedExpressionForSelector import org.jetbrains.kotlin.psi.psiUtil.getQualifiedExpressionForSelectorOrThis import org.jetbrains.kotlin.renderer.render import org.jetbrains.kotlin.resolve.BindingContext import org.jetbrains.kotlin.resolve.DelegatingBindingTrace import org.jetbrains.kotlin.resolve.bindingContextUtil.getDataFlowInfoBefore import org.jetbrains.kotlin.resolve.bindingContextUtil.isUsedAsExpression import org.jetbrains.kotlin.resolve.calls.CallResolver import org.jetbrains.kotlin.resolve.calls.context.BasicCallResolutionContext import org.jetbrains.kotlin.resolve.calls.context.CheckArgumentTypesMode import org.jetbrains.kotlin.resolve.calls.context.ContextDependency import org.jetbrains.kotlin.resolve.calls.model.ResolvedCall import org.jetbrains.kotlin.resolve.calls.model.isReallySuccess import org.jetbrains.kotlin.resolve.calls.smartcasts.DataFlowInfo import org.jetbrains.kotlin.resolve.calls.util.DelegatingCall import org.jetbrains.kotlin.resolve.calls.util.getResolvedCall import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode import org.jetbrains.kotlin.resolve.scopes.LexicalScope import org.jetbrains.kotlin.resolve.scopes.SyntheticScopes import org.jetbrains.kotlin.synthetic.SyntheticJavaPropertyDescriptor import org.jetbrains.kotlin.synthetic.canBePropertyAccessor import org.jetbrains.kotlin.types.KotlinType import org.jetbrains.kotlin.types.TypeUtils import org.jetbrains.kotlin.types.typeUtil.isUnit import org.jetbrains.kotlin.util.shouldNotConvertToProperty import org.jetbrains.kotlin.utils.KotlinExceptionWithAttachments import javax.swing.JComponent @Suppress("DEPRECATION") class UsePropertyAccessSyntaxInspection : IntentionBasedInspection<KtCallExpression>(UsePropertyAccessSyntaxIntention::class), CleanupLocalInspectionTool { val fqNameList = NotPropertiesService.DEFAULT.map(::FqNameUnsafe).toMutableList() @Suppress("CAN_BE_PRIVATE") var fqNameStrings = NotPropertiesService.DEFAULT.toMutableList() override fun readSettings(node: Element) { super.readSettings(node) fqNameList.clear() fqNameStrings.mapTo(fqNameList, ::FqNameUnsafe) } override fun writeSettings(node: Element) { fqNameStrings.clear() fqNameList.mapTo(fqNameStrings) { it.asString() } super.writeSettings(node) } override fun createOptionsPanel(): JComponent { val list = NotPropertyListPanel(fqNameList) return LabeledComponent.create(list, KotlinBundle.message("excluded.methods")) } override fun inspectionTarget(element: KtCallExpression): PsiElement? { return element.calleeExpression } override fun inspectionProblemText(element: KtCallExpression): String { val accessor = when (element.valueArguments.size) { 0 -> "getter" 1 -> "setter" else -> null } return KotlinBundle.message("use.of.0.method.instead.of.property.access.syntax", accessor.toString()) } } class NotPropertiesServiceImpl(private val project: Project) : NotPropertiesService { override fun getNotProperties(element: PsiElement): Set<FqNameUnsafe> { val profile = InspectionProjectProfileManager.getInstance(project).currentProfile val tool = profile.getUnwrappedTool(USE_PROPERTY_ACCESS_INSPECTION, element) return (tool?.fqNameList ?: NotPropertiesService.DEFAULT.map(::FqNameUnsafe)).toSet() } companion object { val USE_PROPERTY_ACCESS_INSPECTION: Key<UsePropertyAccessSyntaxInspection> = Key.create("UsePropertyAccessSyntax") } } class UsePropertyAccessSyntaxIntention : SelfTargetingOffsetIndependentIntention<KtCallExpression>( KtCallExpression::class.java, KotlinBundle.lazyMessage("use.property.access.syntax") ) { override fun isApplicableTo(element: KtCallExpression): Boolean = detectPropertyNameToUse(element) != null override fun applyTo(element: KtCallExpression, editor: Editor?) { val propertyName = detectPropertyNameToUse(element) ?: return runWriteActionIfPhysical(element) { applyTo(element, propertyName, reformat = true) } } fun applyTo(element: KtCallExpression, propertyName: Name, reformat: Boolean): KtExpression = when (element.valueArguments.size) { 0 -> replaceWithPropertyGet(element, propertyName) 1 -> replaceWithPropertySet(element, propertyName, reformat) else -> error("More than one argument in call to accessor") } fun detectPropertyNameToUse(callExpression: KtCallExpression): Name? { if (callExpression.getQualifiedExpressionForSelector() ?.receiverExpression is KtSuperExpression ) return null // cannot call extensions on "super" val callee = callExpression.calleeExpression as? KtNameReferenceExpression ?: return null if (!canBePropertyAccessor(callee.getReferencedName())) return null val resolutionFacade = callExpression.getResolutionFacade() val bindingContext = callExpression.safeAnalyzeNonSourceRootCode(resolutionFacade, BodyResolveMode.PARTIAL_FOR_COMPLETION) val resolvedCall = callExpression.getResolvedCall(bindingContext) ?: return null if (!resolvedCall.isReallySuccess()) return null val function = resolvedCall.resultingDescriptor as? FunctionDescriptor ?: return null val notProperties = (inspection as? UsePropertyAccessSyntaxInspection)?.fqNameList?.toSet() ?: NotPropertiesService.getNotProperties(callExpression) if (function.shouldNotConvertToProperty(notProperties)) return null val resolutionScope = callExpression.getResolutionScope(bindingContext, resolutionFacade) @OptIn(FrontendInternals::class) val property = findSyntheticProperty(function, resolutionFacade.getFrontendService(SyntheticScopes::class.java)) ?: return null if (KtTokens.KEYWORDS.types.any { it.toString() == property.name.asString() }) return null val dataFlowInfo = bindingContext.getDataFlowInfoBefore(callee) val qualifiedExpression = callExpression.getQualifiedExpressionForSelectorOrThis() val expectedType = bindingContext[BindingContext.EXPECTED_EXPRESSION_TYPE, qualifiedExpression] ?: TypeUtils.NO_EXPECTED_TYPE if (!checkWillResolveToProperty( resolvedCall, property, bindingContext, resolutionScope, dataFlowInfo, expectedType, resolutionFacade ) ) return null val isSetUsage = callExpression.valueArguments.size == 1 val valueArgumentExpression = callExpression.valueArguments.firstOrNull()?.getArgumentExpression()?.takeUnless { it is KtLambdaExpression || it is KtNamedFunction || it is KtCallableReferenceExpression } if (isSetUsage && valueArgumentExpression == null) { return null } if (isSetUsage && qualifiedExpression.isUsedAsExpression(bindingContext)) { // call to the setter used as expression can be converted in the only case when it's used as body expression for some declaration and its type is Unit val parent = qualifiedExpression.parent if (parent !is KtDeclarationWithBody || qualifiedExpression != parent.bodyExpression) return null if (function.returnType?.isUnit() != true) return null } if (isSetUsage && property.type != function.valueParameters.single().type) { val qualifiedExpressionCopy = qualifiedExpression.copied() val callExpressionCopy = ((qualifiedExpressionCopy as? KtQualifiedExpression)?.selectorExpression ?: qualifiedExpressionCopy) as KtCallExpression val newExpression = applyTo(callExpressionCopy, property.name, reformat = false) val bindingTrace = DelegatingBindingTrace(bindingContext, "Temporary trace") val newBindingContext = newExpression.analyzeInContext( resolutionScope, contextExpression = callExpression, trace = bindingTrace, dataFlowInfo = dataFlowInfo, expectedType = expectedType, isStatement = true ) if (newBindingContext.diagnostics.any { it.severity == Severity.ERROR }) return null } return property.name } private fun checkWillResolveToProperty( resolvedCall: ResolvedCall<out CallableDescriptor>, property: SyntheticJavaPropertyDescriptor, bindingContext: BindingContext, resolutionScope: LexicalScope, dataFlowInfo: DataFlowInfo, expectedType: KotlinType, facade: ResolutionFacade ): Boolean { val project = resolvedCall.call.callElement.project val newCall = object : DelegatingCall(resolvedCall.call) { private val newCallee = KtPsiFactory(project).createExpressionByPattern("$0", property.name, reformat = false) override fun getCalleeExpression() = newCallee override fun getValueArgumentList(): KtValueArgumentList? = null override fun getValueArguments(): List<ValueArgument> = emptyList() override fun getFunctionLiteralArguments(): List<LambdaArgument> = emptyList() } val bindingTrace = DelegatingBindingTrace(bindingContext, "Temporary trace") val context = BasicCallResolutionContext.create( bindingTrace, resolutionScope, newCall, expectedType, dataFlowInfo, ContextDependency.INDEPENDENT, CheckArgumentTypesMode.CHECK_VALUE_ARGUMENTS, false, facade.languageVersionSettings, facade.dataFlowValueFactory ) @OptIn(FrontendInternals::class) val callResolver = facade.frontendService<CallResolver>() val result = callResolver.resolveSimpleProperty(context) return result.isSuccess && result.resultingDescriptor.original == property } private fun findSyntheticProperty(function: FunctionDescriptor, syntheticScopes: SyntheticScopes): SyntheticJavaPropertyDescriptor? { SyntheticJavaPropertyDescriptor.findByGetterOrSetter(function, syntheticScopes)?.let { return it } for (overridden in function.overriddenDescriptors) { findSyntheticProperty(overridden, syntheticScopes)?.let { return it } } return null } private fun replaceWithPropertyGet(callExpression: KtCallExpression, propertyName: Name): KtExpression { val newExpression = KtPsiFactory(callExpression).createExpression(propertyName.render()) return callExpression.replaced(newExpression) } private fun replaceWithPropertySet(callExpression: KtCallExpression, propertyName: Name, reformat: Boolean): KtExpression { val call = callExpression.getQualifiedExpressionForSelector() ?: callExpression val callParent = call.parent var callToConvert = callExpression if (callParent is KtDeclarationWithBody && call == callParent.bodyExpression) { ConvertToBlockBodyIntention.convert(callParent, true) val firstStatement = callParent.bodyBlockExpression?.statements?.first() callToConvert = (firstStatement as? KtQualifiedExpression)?.selectorExpression as? KtCallExpression ?: firstStatement as? KtCallExpression ?: throw KotlinExceptionWithAttachments("Unexpected contents of function after conversion: ${callParent::class.java}") .withPsiAttachment("callParent", callParent) } val qualifiedExpression = callToConvert.getQualifiedExpressionForSelector() val argument = callToConvert.valueArguments.single() if (qualifiedExpression != null) { val pattern = when (qualifiedExpression) { is KtDotQualifiedExpression -> "$0.$1=$2" is KtSafeQualifiedExpression -> "$0?.$1=$2" else -> error(qualifiedExpression) //TODO: make it sealed? } val newExpression = KtPsiFactory(callToConvert).createExpressionByPattern( pattern, qualifiedExpression.receiverExpression, propertyName, argument.getArgumentExpression()!!, reformat = reformat ) return qualifiedExpression.replaced(newExpression) } else { val newExpression = KtPsiFactory(callToConvert).createExpressionByPattern("$0=$1", propertyName, argument.getArgumentExpression()!!) return callToConvert.replaced(newExpression) } } }
apache-2.0
db281c5a7e60dc698f15dd16bfd02f5d
47.93
162
0.738742
5.637097
false
false
false
false
Appyx/AlexaHome
executor/src/main/kotlin/at/rgstoettner/alexahome/executor/plugin/v2/V2Plugin.kt
1
635
package at.rgstoettner.alexahome.executor.plugin.v2 import at.rgstoettner.alexahome.plugin.v2.V2Device class V2Plugin(val device: V2Device) { val amazonDevice = AmazonDevice() class AmazonDevice() { var applianceId: String? = null var friendlyName: String? = null var friendlyDescription: String? = null var isReachable = true var manufacturerName: String? = null var modelName: String? = null var version: String? = null var additionalApplianceDetails = Any() var applianceTypes = mutableListOf<String>() var actions = listOf<String>() } }
apache-2.0
ffb684c5b90dd48d9d441b153ea0672b
30.8
52
0.666142
4.018987
false
false
false
false
wordpress-mobile/WordPress-Android
WordPress/src/test/java/org/wordpress/android/ui/stats/refresh/lists/widget/today/TodayWidgetBlockListViewModelTest.kt
1
4379
package org.wordpress.android.ui.stats.refresh.lists.widget.today import android.content.Context import org.assertj.core.api.Assertions import org.junit.Before import org.junit.Test import org.junit.runner.RunWith import org.mockito.Mock import org.mockito.junit.MockitoJUnitRunner import org.mockito.kotlin.any import org.mockito.kotlin.eq import org.mockito.kotlin.isNull import org.mockito.kotlin.verify import org.mockito.kotlin.whenever import org.wordpress.android.R import org.wordpress.android.R.string import org.wordpress.android.fluxc.model.SiteModel import org.wordpress.android.fluxc.model.stats.VisitsModel import org.wordpress.android.fluxc.store.SiteStore import org.wordpress.android.fluxc.store.stats.insights.TodayInsightsStore import org.wordpress.android.ui.prefs.AppPrefsWrapper import org.wordpress.android.ui.stats.refresh.lists.widget.WidgetBlockListProvider.BlockItemUiModel import org.wordpress.android.ui.stats.refresh.lists.widget.configuration.StatsColorSelectionViewModel.Color import org.wordpress.android.ui.stats.refresh.utils.StatsUtils import org.wordpress.android.viewmodel.ResourceProvider @RunWith(MockitoJUnitRunner::class) class TodayWidgetBlockListViewModelTest { @Mock private lateinit var siteStore: SiteStore @Mock private lateinit var store: TodayInsightsStore @Mock private lateinit var resourceProvider: ResourceProvider @Mock private lateinit var statsUtils: StatsUtils @Mock private lateinit var site: SiteModel @Mock private lateinit var context: Context @Mock private lateinit var appPrefsWrapper: AppPrefsWrapper @Mock private lateinit var todayWidgetUpdater: TodayWidgetUpdater private lateinit var viewModel: TodayWidgetBlockListViewModel private val siteId: Int = 15 private val appWidgetId: Int = 1 private val color = Color.LIGHT @Before fun setUp() { viewModel = TodayWidgetBlockListViewModel( siteStore, store, resourceProvider, todayWidgetUpdater, appPrefsWrapper, statsUtils ) viewModel.start(siteId, color, appWidgetId) whenever(statsUtils.toFormattedString(any<Int>(), any())).then { (it.arguments[0] as Int).toString() } } @Test fun `builds ui model`() { whenever(siteStore.getSiteByLocalId(siteId)).thenReturn(site) val viewsKey = "Views" val visitorsKey = "Visitors" val likesKey = "Likes" val commentsKey = "Comments" val views = 500 val visitors = 100 val likes = 50 val comments = 300 whenever(resourceProvider.getString(string.stats_views)).thenReturn(viewsKey) whenever(resourceProvider.getString(string.stats_visitors)).thenReturn(visitorsKey) whenever(resourceProvider.getString(string.likes)).thenReturn(likesKey) whenever(resourceProvider.getString(string.stats_comments)).thenReturn(commentsKey) whenever(store.getTodayInsights(site)).thenReturn( VisitsModel("2019-10-10", views, visitors, likes, 0, comments, 0) ) viewModel.onDataSetChanged(context) Assertions.assertThat(viewModel.data).hasSize(2) assertListItem(viewModel.data[0], viewsKey, views, visitorsKey, visitors) assertListItem(viewModel.data[1], likesKey, likes, commentsKey, comments) verify(appPrefsWrapper).setAppWidgetHasData(true, appWidgetId) } @Test fun `shows error when site is missing`() { whenever(siteStore.getSiteByLocalId(siteId)).thenReturn(null) viewModel.onDataSetChanged(context) verify(todayWidgetUpdater).updateAppWidget(eq(context), any(), isNull()) } private fun assertListItem( listItem: BlockItemUiModel, startKey: String, startValue: Int, endKey: String, endValue: Int ) { Assertions.assertThat(listItem.layout).isEqualTo(R.layout.stats_widget_block_item_light) Assertions.assertThat(listItem.localSiteId).isEqualTo(siteId) Assertions.assertThat(listItem.startKey).isEqualTo(startKey) Assertions.assertThat(listItem.startValue).isEqualTo(startValue.toString()) Assertions.assertThat(listItem.endKey).isEqualTo(endKey) Assertions.assertThat(listItem.endValue).isEqualTo(endValue.toString()) } }
gpl-2.0
ae35fff6833b82b6f86e75d73c14b0b4
40.704762
110
0.732359
4.556712
false
true
false
false
wordpress-mobile/WordPress-Android
WordPress/src/main/java/org/wordpress/android/ui/stats/refresh/lists/sections/insights/usecases/TotalCommentsUseCase.kt
1
8825
package org.wordpress.android.ui.stats.refresh.lists.sections.insights.usecases import kotlinx.coroutines.CoroutineDispatcher import org.wordpress.android.R.string import org.wordpress.android.analytics.AnalyticsTracker import org.wordpress.android.analytics.AnalyticsTracker.Stat.STATS_TOTAL_COMMENTS_ERROR import org.wordpress.android.fluxc.model.SiteModel import org.wordpress.android.fluxc.model.stats.LimitMode import org.wordpress.android.fluxc.model.stats.time.VisitsAndViewsModel import org.wordpress.android.fluxc.network.utils.StatsGranularity.DAYS import org.wordpress.android.fluxc.store.StatsStore.InsightType.TOTAL_COMMENTS import org.wordpress.android.fluxc.store.stats.time.VisitsAndViewsStore import org.wordpress.android.modules.BG_THREAD import org.wordpress.android.modules.UI_THREAD import org.wordpress.android.ui.stats.StatsViewType import org.wordpress.android.ui.stats.refresh.NavigationTarget.ViewInsightDetails import org.wordpress.android.ui.stats.refresh.lists.StatsListViewModel.StatsSection import org.wordpress.android.ui.stats.refresh.lists.sections.BaseStatsUseCase.StatelessUseCase import org.wordpress.android.ui.stats.refresh.lists.sections.BaseStatsUseCase.UseCaseMode.BLOCK import org.wordpress.android.ui.stats.refresh.lists.sections.BlockListItem import org.wordpress.android.ui.stats.refresh.lists.sections.BlockListItem.Empty import org.wordpress.android.ui.stats.refresh.lists.sections.BlockListItem.ListItemGuideCard import org.wordpress.android.ui.stats.refresh.lists.sections.BlockListItem.TitleWithMore import org.wordpress.android.ui.stats.refresh.lists.sections.insights.InsightUseCaseFactory import org.wordpress.android.ui.stats.refresh.lists.widget.WidgetUpdater.StatsWidgetUpdaters import org.wordpress.android.ui.stats.refresh.utils.StatsDateFormatter import org.wordpress.android.ui.stats.refresh.utils.StatsSiteProvider import org.wordpress.android.ui.stats.refresh.utils.trackWithType import org.wordpress.android.ui.utils.ListItemInteraction import org.wordpress.android.util.AppLog import org.wordpress.android.util.AppLog.T import org.wordpress.android.util.LocaleManagerWrapper import org.wordpress.android.util.analytics.AnalyticsTrackerWrapper import org.wordpress.android.viewmodel.ResourceProvider import java.util.Calendar import javax.inject.Inject import javax.inject.Named import kotlin.math.ceil class TotalCommentsUseCase @Inject constructor( @Named(UI_THREAD) private val mainDispatcher: CoroutineDispatcher, @Named(BG_THREAD) private val bgDispatcher: CoroutineDispatcher, private val visitsAndViewsStore: VisitsAndViewsStore, private val statsSiteProvider: StatsSiteProvider, private val resourceProvider: ResourceProvider, private val statsDateFormatter: StatsDateFormatter, private val totalStatsMapper: TotalStatsMapper, private val analyticsTracker: AnalyticsTrackerWrapper, private val statsWidgetUpdaters: StatsWidgetUpdaters, private val localeManagerWrapper: LocaleManagerWrapper, private val useCaseMode: UseCaseMode ) : StatelessUseCase<VisitsAndViewsModel>(TOTAL_COMMENTS, mainDispatcher, bgDispatcher) { override fun buildLoadingItem() = listOf(TitleWithMore(string.stats_view_total_comments)) override fun buildEmptyItem() = listOf(buildTitle(), Empty()) override suspend fun loadCachedData(): VisitsAndViewsModel? { statsWidgetUpdaters.updateViewsWidget(statsSiteProvider.siteModel.siteId) val cachedData = visitsAndViewsStore.getVisits( statsSiteProvider.siteModel, DAYS, LimitMode.All ) if (cachedData != null) { logIfIncorrectData(cachedData, statsSiteProvider.siteModel, false) } return cachedData } override suspend fun fetchRemoteData(forced: Boolean): State<VisitsAndViewsModel> { val response = visitsAndViewsStore.fetchVisits( statsSiteProvider.siteModel, DAYS, LimitMode.Top(TOTAL_COMMENTS_ITEMS_TO_LOAD), forced ) val model = response.model val error = response.error return when { error != null -> State.Error(error.message ?: error.type.name) model != null && model.dates.isNotEmpty() -> { logIfIncorrectData(model, statsSiteProvider.siteModel, true) State.Data(model) } else -> State.Empty() } } /** * Track the incorrect data shown for some users * see https://github.com/wordpress-mobile/WordPress-Android/issues/11412 */ @Suppress("MagicNumber") private fun logIfIncorrectData( model: VisitsAndViewsModel, site: SiteModel, fetched: Boolean ) { model.dates.lastOrNull()?.let { lastDayData -> val yesterday = localeManagerWrapper.getCurrentCalendar() yesterday.add(Calendar.DAY_OF_YEAR, -1) val lastDayDate = statsDateFormatter.parseStatsDate(DAYS, lastDayData.period) if (lastDayDate.before(yesterday.time)) { val currentCalendar = localeManagerWrapper.getCurrentCalendar() val lastItemAge = ceil((currentCalendar.timeInMillis - lastDayDate.time) / 86400000.0) analyticsTracker.track( STATS_TOTAL_COMMENTS_ERROR, mapOf( "stats_last_date" to statsDateFormatter.printStatsDate(lastDayDate), "stats_current_date" to statsDateFormatter.printStatsDate(currentCalendar.time), "stats_age_in_days" to lastItemAge.toInt(), "is_jetpack_connected" to site.isJetpackConnected, "is_atomic" to site.isWPComAtomic, "action_source" to if (fetched) "remote" else "cached" ) ) } } } override fun buildUiModel(domainModel: VisitsAndViewsModel): List<BlockListItem> { val items = mutableListOf<BlockListItem>() if (domainModel.dates.isNotEmpty()) { items.add(buildTitle()) items.add(totalStatsMapper.buildTotalCommentsValue(domainModel.dates)) totalStatsMapper.buildTotalCommentsInformation(domainModel.dates)?.let { items.add(it) } if (useCaseMode == BLOCK && totalStatsMapper.shouldShowCommentsGuideCard(domainModel.dates)) { items.add(ListItemGuideCard(resourceProvider.getString(string.stats_insights_comments_guide_card))) } } else { AppLog.e(T.STATS, "There is no data to be shown in the total comments block") } return items } private fun buildTitle() = TitleWithMore( string.stats_view_total_comments, navigationAction = if (useCaseMode == BLOCK) ListItemInteraction.create(this::onViewMoreClick) else null ) private fun onViewMoreClick() { analyticsTracker.trackWithType(AnalyticsTracker.Stat.STATS_INSIGHTS_VIEW_MORE, TOTAL_COMMENTS) navigateTo( ViewInsightDetails( StatsSection.TOTAL_COMMENTS_DETAIL, StatsViewType.TOTAL_COMMENTS, null, null ) ) } companion object { private const val TOTAL_COMMENTS_ITEMS_TO_LOAD = 15 } class TotalCommentsUseCaseFactory @Inject constructor( @Named(UI_THREAD) private val mainDispatcher: CoroutineDispatcher, @Named(BG_THREAD) private val backgroundDispatcher: CoroutineDispatcher, private val visitsAndViewsStore: VisitsAndViewsStore, private val statsSiteProvider: StatsSiteProvider, private val resourceProvider: ResourceProvider, private val statsDateFormatter: StatsDateFormatter, private val totalStatsMapper: TotalStatsMapper, private val analyticsTracker: AnalyticsTrackerWrapper, private val statsWidgetUpdaters: StatsWidgetUpdaters, private val localeManagerWrapper: LocaleManagerWrapper ) : InsightUseCaseFactory { override fun build(useCaseMode: UseCaseMode) = TotalCommentsUseCase( mainDispatcher, backgroundDispatcher, visitsAndViewsStore, statsSiteProvider, resourceProvider, statsDateFormatter, totalStatsMapper, analyticsTracker, statsWidgetUpdaters, localeManagerWrapper, useCaseMode ) } }
gpl-2.0
8c5ccac58bff77e8a40dcfe17ab1f293
46.446237
116
0.688159
5.022766
false
false
false
false
KotlinNLP/SimpleDNN
src/test/kotlin/core/layers/merge/concatff/ConcatFFLayerStructureSpec.kt
1
3174
/* Copyright 2020-present Simone Cangialosi. All Rights Reserved. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, you can obtain contexte at http://mozilla.org/MPL/2.0/. * ------------------------------------------------------------------*/ package core.layers.merge.concatff import com.kotlinnlp.simplednn.core.optimizer.ParamsErrorsList import com.kotlinnlp.simplednn.core.optimizer.getErrorsOf import com.kotlinnlp.simplednn.simplemath.ndarray.dense.DenseNDArrayFactory import org.spekframework.spek2.Spek import org.spekframework.spek2.style.specification.describe import kotlin.test.assertTrue /** * */ class ConcatFFLayerStructureSpec : Spek({ describe("a ConcatLayer") { context("forward") { val layer = ConcatFFLayerUtils.buildLayer() layer.forward() it("should match the expected outputArray") { assertTrue { DenseNDArrayFactory.arrayOf(doubleArrayOf(-0.079830, -0.669590, -0.777888)).equals( layer.outputArray.values, tolerance = 1.0e-06) } } } context("backward") { val layer = ConcatFFLayerUtils.buildLayer() layer.forward() layer.outputArray.assignErrors(ConcatFFLayerUtils.getOutputErrors()) val paramsErrors: ParamsErrorsList = layer.backward(propagateToInput = true) it("should match the expected errors of the weights") { assertTrue { DenseNDArrayFactory.arrayOf(listOf( doubleArrayOf(0.625985, -0.625985, -0.417323, -0.069554, 0.0, -0.34777, 0.486877, 0.486877, -0.556431), doubleArrayOf(0.397187, -0.397187, -0.264791, -0.044132, 0.0, -0.22066, 0.308923, 0.308923, -0.353055), doubleArrayOf(-0.213241, 0.213241, 0.14216, 0.023693, 0.0, 0.118467, -0.165854, -0.165854, 0.189547) )).equals(paramsErrors.getErrorsOf(layer.params.output.unit.weights)!!.values, tolerance = 1.0e-06) } } it("should match the expected errors of the bias") { assertTrue { DenseNDArrayFactory.arrayOf(doubleArrayOf(-0.695539, -0.441319, 0.236934)) .equals(paramsErrors.getErrorsOf(layer.params.output.unit.biases)!!.values, tolerance = 1.0e-06) } } it("should match the expected errors of the inputArray at index 0") { assertTrue { layer.inputArrays[0].errors.equals( DenseNDArrayFactory.arrayOf(doubleArrayOf(-0.029384, 0.109724, -0.259506, -0.573413)), tolerance = 1.0e-06) } } it("should match the expected errors of the inputArray at index 1") { assertTrue { layer.inputArrays[1].errors.equals( DenseNDArrayFactory.arrayOf(doubleArrayOf(-0.104841, -0.234286)), tolerance = 1.0e-06) } } it("should match the expected errors of the inputArray at index 2") { assertTrue { layer.inputArrays[2].errors.equals( DenseNDArrayFactory.arrayOf(doubleArrayOf(-0.628016, 0.295197, 0.751871)), tolerance = 1.0e-06) } } } } })
mpl-2.0
1e32e19566253003a3e4d0471feaa280
34.266667
115
0.637681
3.792115
false
false
false
false
ingokegel/intellij-community
java/idea-ui/src/com/intellij/ide/starters/local/wizard/StarterLibrariesStep.kt
2
14951
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.ide.starters.local.wizard import com.intellij.icons.AllIcons import com.intellij.ide.starters.JavaStartersBundle import com.intellij.ide.starters.local.* import com.intellij.ide.starters.shared.* import com.intellij.ide.starters.shared.ui.LibraryDescriptionPanel import com.intellij.ide.starters.shared.ui.SelectedLibrariesPanel import com.intellij.ide.util.projectWizard.ModuleWizardStep import com.intellij.ide.wizard.withVisualPadding import com.intellij.openapi.ui.ComboBox import com.intellij.openapi.ui.DialogPanel import com.intellij.openapi.util.NlsSafe import com.intellij.ui.* import com.intellij.ui.components.JBLabel import com.intellij.ui.dsl.builder.BottomGap import com.intellij.ui.dsl.builder.panel import com.intellij.ui.dsl.gridLayout.HorizontalAlign import com.intellij.ui.dsl.gridLayout.VerticalAlign import com.intellij.util.containers.Convertor import com.intellij.util.ui.JBUI import com.intellij.util.ui.UIUtil import com.intellij.util.ui.components.BorderLayoutPanel import com.intellij.util.ui.tree.TreeUtil import java.awt.Dimension import java.awt.GridBagLayout import java.awt.event.ItemEvent import javax.swing.DefaultComboBoxModel import javax.swing.JComponent import javax.swing.JPanel import javax.swing.JTree import javax.swing.event.TreeSelectionListener import javax.swing.tree.DefaultMutableTreeNode import javax.swing.tree.DefaultTreeModel import javax.swing.tree.TreePath import javax.swing.tree.TreeSelectionModel open class StarterLibrariesStep(contextProvider: StarterContextProvider) : ModuleWizardStep() { protected val starterContext = contextProvider.starterContext protected val starterSettings: StarterWizardSettings = contextProvider.settings protected val moduleBuilder: StarterModuleBuilder = contextProvider.moduleBuilder private val topLevelPanel: BorderLayoutPanel = BorderLayoutPanel() private val contentPanel: DialogPanel by lazy { createComponent() } private val libraryDescriptionPanel: LibraryDescriptionPanel by lazy { LibraryDescriptionPanel() } private val selectedLibrariesPanel: SelectedLibrariesPanel by lazy { createSelectedLibrariesPanel() } private val dependencyConfig: Map<String, DependencyConfig> by lazy { moduleBuilder.loadDependencyConfigInternal() } private val selectedLibraryIds: MutableSet<String> = mutableSetOf() private var selectedStarterId: String? = null private val startersComboBox: ComboBox<Starter> by lazy { ComboBox<Starter>() } private val librariesList: CheckboxTreeBase by lazy { createLibrariesList() } override fun updateDataModel() { starterContext.starter = startersComboBox.selectedItem as? Starter starterContext.libraryIds.clear() starterContext.libraryIds.addAll(selectedLibraryIds) starterContext.starterDependencyConfig = dependencyConfig[starterContext.starter?.id] } override fun onStepLeaving() { super.onStepLeaving() updateDataModel() } override fun getComponent(): JComponent { return topLevelPanel } @NlsSafe private fun getLibraryVersion(library: Library): String? { if (library.group == null || library.artifact == null) return null val selectedStarter = startersComboBox.selectedItem as? Starter ?: return null return dependencyConfig[selectedStarter.id]?.getVersion(library.group, library.artifact) } override fun getPreferredFocusedComponent(): JComponent { return librariesList } private fun createLibrariesList(): CheckboxTreeBase { val list = CheckboxTreeBase(object : CheckboxTree.CheckboxTreeCellRenderer() { override fun customizeRenderer( tree: JTree?, value: Any?, selected: Boolean, expanded: Boolean, leaf: Boolean, row: Int, hasFocus: Boolean ) { if (value !is DefaultMutableTreeNode) return this.border = JBUI.Borders.empty(2) val renderer = textRenderer when (val item = value.userObject) { is LibraryCategory -> { renderer.icon = item.icon ?: AllIcons.Nodes.PpLibFolder renderer.append(item.title, SimpleTextAttributes.REGULAR_ATTRIBUTES) } is Library -> { renderer.icon = item.icon ?: AllIcons.Nodes.PpLib renderer.append(item.title, SimpleTextAttributes.REGULAR_ATTRIBUTES) val version = getLibraryVersion(item) if (version != null) { renderer.append(" ($version)", SimpleTextAttributes.GRAYED_ATTRIBUTES) } } } } }, null) enableEnterKeyHandling(list) list.rowHeight = 0 list.isRootVisible = false list.selectionModel.selectionMode = TreeSelectionModel.SINGLE_TREE_SELECTION list.addCheckboxTreeListener(object : CheckboxTreeListener { override fun nodeStateChanged(node: CheckedTreeNode) { val library = node.userObject as? Library ?: return val libraryId = library.id if (node.isChecked) { selectedLibraryIds.add(libraryId) selectedLibraryIds.removeAll(library.includesLibraries) } else { selectedLibraryIds.remove(libraryId) } updateIncludedLibraries(library, node) updateSelectedLibraries() list.repaint() } }) return list } private fun createComponent(): DialogPanel { startersComboBox.setMinimumAndPreferredWidth(200) startersComboBox.renderer = SimpleListCellRenderer.create("", Starter::title) startersComboBox.addItemListener { e -> if (e.stateChange == ItemEvent.SELECTED) { val newValue = e.item as? Starter if (newValue != null) { selectedStarterId = newValue.id updateLibrariesList(newValue, false) } } } TreeSpeedSearch(librariesList, Convertor { treePath: TreePath -> when (val dataObject = (treePath.lastPathComponent as DefaultMutableTreeNode).userObject) { is LibraryCategory -> dataObject.title is Library -> dataObject.title else -> "" } }) librariesList.selectionModel.addTreeSelectionListener(TreeSelectionListener { e -> val path = e.path if (path != null && e.isAddedPath) { when (val item = (path.lastPathComponent as? DefaultMutableTreeNode)?.userObject) { is LibraryCategory -> libraryDescriptionPanel.update(item.title, item.description) is Library -> libraryDescriptionPanel.update(item, null) } } else { libraryDescriptionPanel.reset() } }) val messages = starterSettings.customizedMessages return panel { if (starterContext.starterPack.starters.size > 1) { row(messages?.frameworkVersionLabel ?: JavaStartersBundle.message("title.project.version.label")) { cell(startersComboBox) }.bottomGap(BottomGap.SMALL) } row { label(messages?.dependenciesLabel ?: JavaStartersBundle.message("title.project.dependencies.label")) } row { cell(JPanel(GridBagLayout()).apply { add(ScrollPaneFactory.createScrollPane(librariesList).apply { preferredSize = Dimension(0, 0) }, gridConstraint(0, 0)) add(JPanel(GridBagLayout()).apply { border = JBUI.Borders.emptyLeft(UIUtil.DEFAULT_HGAP * 2) preferredSize = Dimension(0, 0) add(libraryDescriptionPanel.apply { preferredSize = Dimension(0, 0) }, gridConstraint(0, 0)) add(BorderLayoutPanel().apply { preferredSize = Dimension(0, 0) addToTop(JBLabel(messages?.selectedDependenciesLabel ?: JavaStartersBundle.message("title.project.dependencies.selected.label")).apply { border = JBUI.Borders.empty(0, 0, UIUtil.DEFAULT_VGAP * 2, 0) }) addToCenter(selectedLibrariesPanel) }, gridConstraint(0, 1)) }, gridConstraint(1, 0)) }).horizontalAlign(HorizontalAlign.FILL) .verticalAlign(VerticalAlign.FILL) }.resizableRow() }.withVisualPadding() } private fun createSelectedLibrariesPanel(): SelectedLibrariesPanel { val panel = SelectedLibrariesPanel() val messages = starterSettings.customizedMessages panel.emptyText.text = messages?.noDependenciesSelectedLabel ?: JavaStartersBundle.message("hint.dependencies.not.selected") panel.libraryRemoveListener = { libraryInfo -> // do not remove from selectedLibraryIds directly, library can be included walkCheckedTree(getLibrariesRoot()) { if (it.userObject == libraryInfo && it.isEnabled) { librariesList.setNodeState(it, false) } } updateSelectedLibraries() } return panel } private fun updateSelectedLibraries() { val selected = mutableListOf<LibraryInfo>() walkCheckedTree(getLibrariesRoot()) { val library = (it.userObject as? Library) if (library != null && it.isChecked) { selected.add(library) } } selectedLibrariesPanel.update(selected) } private fun getLibrariesRoot(): CheckedTreeNode? { return librariesList.model.root as? CheckedTreeNode } override fun _init() { super._init() if (topLevelPanel.componentCount == 0) { // create UI only on first show topLevelPanel.addToCenter(contentPanel) } // step became visible val starterPack = starterContext.starterPack startersComboBox.model = DefaultComboBoxModel(starterPack.starters.toTypedArray()) val initial = selectedStarterId == null val selectedStarter = when (val previouslySelectedStarter = starterContext.starter?.id) { null -> starterPack.starters.find { it.id == starterPack.defaultStarterId } ?: starterPack.starters.firstOrNull() else -> starterPack.starters.find { it.id == previouslySelectedStarter } } if (selectedStarter != null) { startersComboBox.selectedItem = selectedStarter selectedStarterId = selectedStarter.id selectedLibraryIds.clear() for (libraryId in starterContext.libraryIds) { val lib = selectedStarter.libraries.find { it.id == libraryId } if (lib != null) { selectedLibraryIds.add(libraryId) selectedLibraryIds.removeAll(lib.includesLibraries) } } updateLibrariesList(selectedStarter, initial) } } private fun updateLibrariesList(starter: Starter, init: Boolean) { val previouslyExpandedGroups = getExpandedCategories() val librariesRoot = CheckedTreeNode() val categoryNodes = mutableMapOf<LibraryCategory, DefaultMutableTreeNode>() val selectedLibraries = mutableListOf<Pair<Library, CheckedTreeNode>>() val libraryNodes = mutableListOf<CheckedTreeNode>() for (library in starter.libraries) { if (!moduleBuilder.isDependencyAvailableInternal(starter, library)) continue val libraryNode = CheckedTreeNode(library) if (library.isRequired || library.isDefault && init) { selectedLibraryIds.add(library.id) } libraryNode.isChecked = selectedLibraryIds.contains(library.id) libraryNode.isEnabled = !library.isRequired if (library.category == null) { librariesRoot.add(libraryNode) } else { val categoryNode = categoryNodes.getOrPut(library.category) { val newCategoryNode = DefaultMutableTreeNode(library.category, true) librariesRoot.add(newCategoryNode) newCategoryNode } categoryNode.add(libraryNode) } libraryNodes.add(libraryNode) if (libraryNode.isChecked) { selectedLibraries.add(library to libraryNode) } } val starterLibraryIds = starter.libraries.map { it.id }.toSet() selectedLibraryIds.removeIf { !starterLibraryIds.contains(it) } librariesList.model = DefaultTreeModel(librariesRoot) expandCategories(categoryNodes, librariesRoot, previouslyExpandedGroups, init) if (libraryNodes.isNotEmpty()) { val toExpand = libraryNodes.find { librariesList.isExpanded(TreeUtil.getPath(librariesRoot, it.parent)) } if (toExpand != null) { librariesList.selectionModel.addSelectionPath(TreeUtil.getPath(librariesRoot, toExpand)) } } for ((library, node) in selectedLibraries) { updateIncludedLibraries(library, node) } updateSelectedLibraries() } private fun expandCategories(categoryNodes: MutableMap<LibraryCategory, DefaultMutableTreeNode>, librariesRoot: CheckedTreeNode, expandedCategories: List<LibraryCategory>, isInitial: Boolean) { if (isInitial) { val collapsedCategories = moduleBuilder.getCollapsedDependencyCategoriesInternal() for ((_, node) in categoryNodes) { val categoryId = (node.userObject as? LibraryCategory)?.id val path = TreeUtil.getPath(librariesRoot, node) if (!collapsedCategories.contains(categoryId)) { librariesList.expandPath(path) } else { librariesList.collapsePath(path) } } } else { for (group in expandedCategories) { val newGroup = categoryNodes.entries.find { it.key == group } if (newGroup != null) { val path = TreeUtil.getPath(librariesRoot, newGroup.value) librariesList.expandPath(path) } } } } private fun getExpandedCategories(): List<LibraryCategory> { val librariesRoot = getLibrariesRoot() ?: return emptyList() return librariesRoot.children().toList() .filter { librariesList.isExpanded(TreeUtil.getPath(librariesRoot, it)) } .mapNotNull { (it as? DefaultMutableTreeNode)?.userObject as? LibraryCategory } } private fun updateIncludedLibraries(library: Library, node: CheckedTreeNode) { if (library.includesLibraries.isNotEmpty()) { val rootNode = librariesList.model.root as? CheckedTreeNode if (rootNode != null) { for (child in rootNode.children()) { if (child is CheckedTreeNode) { updateNodeIncluded(child, library, node) } else if (child is DefaultMutableTreeNode) { for (groupChild in child.children()) { updateNodeIncluded(groupChild, library, node) } } } } } } private fun updateNodeIncluded(child: Any?, library: Library, node: CheckedTreeNode) { val checkedNode = child as? CheckedTreeNode val nodeLibrary = checkedNode?.userObject as? Library ?: return if (library.includesLibraries.contains(nodeLibrary.id)) { checkedNode.isChecked = node.isChecked checkedNode.isEnabled = !node.isChecked } } }
apache-2.0
c02f359b2ab357f813c09e8dec553e30
35.737101
158
0.694134
4.963811
false
false
false
false
micolous/metrodroid
src/commonMain/kotlin/au/id/micolous/metrodroid/util/NumberUtils.kt
1
5522
/* * NumberUtils.kt * * Copyright 2011 Eric Butler <[email protected]> * Copyright 2015-2018 Michael Farrell <[email protected]> * Copyright 2019 Google * * 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 au.id.micolous.metrodroid.util val Byte.hexString: String get() = NumberUtils.byteToHex(this) val Int.hexString: String get() = NumberUtils.intToHex(this) val Long.hexString: String get() = NumberUtils.longToHex(this) object NumberUtils { fun byteToHex(v: Byte) = "0x" + (v.toInt() and 0xff).toString(16) fun intToHex(v: Int) = "0x" + v.toString(16) fun longToHex(v: Long): String = "0x" + v.toString(16) fun convertBCDtoInteger(data: Int): Int { var res = 0 for (i in 0..7) res = res * 10 + ((data shr (4 * (7 - i))) and 0xf) return res } fun convertBCDtoInteger(data: Byte): Int { val d = data.toInt() val h = (d and 0xf0) shr 4 val l = (d and 0x0f) return (if (h >= 9) { 90 } else { h * 10 }) + (if (l >= 9) { 9 } else { l }) } fun intToBCD(input: Int): Int { var cur = input var off = 0 var res = 0 while (cur > 0) { val dig = cur % 10 res = res or (dig shl off) off += 4 cur /= 10 } return res } fun isValidBCD(data: Int): Boolean = (0..7).all { ((data shr (4 * it)) and 0xf) in 0..9 } fun zeroPad(value: Int, minDigits: Int): String { val cand = value.toString() if (cand.length >= minDigits) return cand return String(CharArray(minDigits - cand.length) { '0' }) + cand } fun zeroPad(value: Long, minDigits: Int): String { val cand = value.toString() if (cand.length >= minDigits) return cand return String(CharArray(minDigits - cand.length) { '0' }) + cand } fun groupString(value: String, separator: String, vararg groups: Int): String { val ret = StringBuilder() var ptr = 0 for (g in groups) { ret.append(value, ptr, ptr + g).append(separator) ptr += g } ret.append(value, ptr, value.length) return ret.toString() } fun getDigitSum(value: Long): Int { var dig = value var digsum = 0 while (dig > 0) { digsum += (dig % 10).toInt() dig /= 10 } return digsum } fun getBitsFromInteger(buffer: Int, iStartBit: Int, iLength: Int): Int = (buffer shr iStartBit) and ((1 shl iLength) - 1) fun formatNumber(value: Long, separator: String, vararg groups: Int): String { val minDigit = groups.sum() val unformatted = zeroPad(value, minDigit) val numDigit = unformatted.length var last = numDigit - minDigit val ret = StringBuilder() ret.append(unformatted, 0, last) for (g in groups) { ret.append(unformatted, last, last + g).append(separator) last += g } return ret.substring(0, ret.length - 1) } private fun digitsOf(integer: Int): IntArray { return digitsOf(integer.toString()) } fun digitsOf(integer: Long): IntArray { return digitsOf(integer.toString()) } private fun digitsOf(integer: String): IntArray = integer.map { String(charArrayOf(it)).toInt() }.toIntArray() private fun luhnChecksum(cardNumber: String): Int { val checksum = digitsOf(cardNumber).reversed().withIndex().sumBy { (i, dig) -> if (i % 2 == 1) // we treat it as a 1-indexed array // so the first digit is odd digitsOf(dig * 2).sum() else dig } //Log.d(TAG, String.format("luhnChecksum(%s) = %d", cardNumber, checksum)); return checksum % 10 } /** * Given a partial card number, calculate the Luhn check digit. * * @param partialCardNumber Partial card number. * @return Final digit for card number. */ fun calculateLuhn(partialCardNumber: String): Int { val checkDigit = luhnChecksum(partialCardNumber + "0") return if (checkDigit == 0) 0 else 10 - checkDigit } /** * Given a complete card number, validate the Luhn check digit. * * @param cardNumber Complete card number. * @return true if valid, false if invalid. */ fun validateLuhn(cardNumber: String): Boolean { return luhnChecksum(cardNumber) == 0 } fun pow(a: Int, b: Int): Long { var ret: Long = 1 repeat(b) { ret *= a.toLong() } return ret } fun log10floor(value: Int): Int { var mul = 1 var ctr = 0 while (value >= 10 * mul) { ctr++ mul *= 10 } return ctr } }
gpl-3.0
b6a0aa019fb81e0cfda188bfa25cef51
30.02809
114
0.571532
3.875088
false
false
false
false
elpassion/cloud-timer-android
app/src/main/java/pl/elpassion/cloudtimer/common/Parcelable.kt
1
784
package pl.elpassion.cloudtimer.common import android.os.Parcel import android.os.Parcelable inline fun <reified T : Parcelable> createCreator(crossinline createObject: Parcel.() -> T) = object : Parcelable.Creator<T> { override fun createFromParcel(source: Parcel) = source.createObject() override fun newArray(size: Int) = arrayOfNulls<T>(size) } fun Parcel.readBoolean() = readInt() != 0 fun Parcel.writeBoolean(value: Boolean) = writeInt(if (value) 1 else 0) fun Parcelable?.writeNullableToParcel(dest: Parcel, flags: Int) { dest.writeBoolean(this != null) if (this != null) writeToParcel(dest, flags) } fun <T> Parcelable.Creator<T>.createNullableFromParcel(source: Parcel): T? = if (source.readBoolean()) createFromParcel(source) else null
apache-2.0
d19cff39f6f881ef7461f47960ea5b7a
34.636364
126
0.729592
3.881188
false
false
false
false
JavaEden/Orchid-Core
plugins/OrchidSourceDoc/src/main/kotlin/com/eden/orchid/sourcedoc/page/SourceDocResource.kt
2
1752
package com.eden.orchid.sourcedoc.page import com.copperleaf.kodiak.common.AutoDocument import com.copperleaf.kodiak.common.DocElement import com.eden.orchid.api.OrchidContext import com.eden.orchid.api.resources.resource.OrchidResource import com.eden.orchid.api.theme.menus.MenuItem import com.eden.orchid.api.theme.pages.OrchidReference import com.eden.orchid.sourcedoc.menu.SourceDocPageLinksMenuItemType import com.eden.orchid.utilities.asInputStream import com.eden.orchid.utilities.readToString import java.io.InputStream class SourceDocResource<T : DocElement>( context: OrchidContext, val element: T ) : OrchidResource(OrchidReference(context,"")) { init { reference.extension = "md" } override fun getContentStream(): InputStream { var ownCommentText = element.getCommentText() val pageSections = getSectionsData(element) for (section in pageSections) { section .elements .map { sectionElement -> ownCommentText += "${sectionElement.name}\n" ownCommentText += "${sectionElement.getCommentText()}\n" } } return ownCommentText.asInputStream() } private fun DocElement.getCommentText() : String = comment .components .joinToString(" ") { it.text } .asInputStream() .readToString() ?: "" fun getSectionsData(element: DocElement): List<SourceDocPage.Section> { if (element is AutoDocument) { return element .nodes .filter { it.elements.isNotEmpty() } .map { SourceDocPage.Section(element, it.name, it.elements) } } return emptyList() } }
mit
f30525bbccd1bebecfbbc569f36344d7
30.854545
77
0.65468
4.480818
false
false
false
false
GunoH/intellij-community
platform/workspaceModel/storage/tests/testSrc/com/intellij/workspaceModel/storage/impl/WorkspaceBuilderChangeLogTest.kt
2
19208
// Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.workspaceModel.storage.impl import com.intellij.testFramework.assertInstanceOf import com.intellij.workspaceModel.storage.createEmptyBuilder import com.intellij.workspaceModel.storage.entities.test.addChildWithOptionalParentEntity import com.intellij.workspaceModel.storage.entities.test.addParentEntity import com.intellij.workspaceModel.storage.entities.test.addSourceEntity import com.intellij.workspaceModel.storage.entities.test.api.* import org.junit.After import org.junit.Before import org.junit.Test import kotlin.test.assertEquals import kotlin.test.assertFalse import kotlin.test.assertTrue class WorkspaceBuilderChangeLogTest { internal lateinit var builder: MutableEntityStorageImpl internal lateinit var another: MutableEntityStorageImpl @Before fun setUp() { builder = createEmptyBuilder() another = createEmptyBuilder() } @After fun tearDown() { builder.assertConsistency() } @Test fun `add plus delete`() { val entity = builder.addNamedEntity("Parent") builder.removeEntity(entity) val log = builder.changeLog.changeLog assertEquals(0, log.size) } @Test fun `add plus modify`() { val entity = builder.addParentEntity("Parent") builder.modifyEntity(entity) { this.parentProperty = "Another Parent" } val log = builder.changeLog.changeLog assertEquals(1, log.size) val changeEntry = log.values.single() assertTrue(changeEntry is ChangeEntry.AddEntity) assertEquals("Another Parent", (changeEntry.entityData as XParentEntityData).parentProperty) } @Test fun `add plus change source`() { val entity = builder.addParentEntity("Parent") builder.modifyEntity(entity) { this.entitySource = AnotherSource } val log = builder.changeLog.changeLog assertEquals(1, log.size) val changeEntry = log.values.single() assertTrue(changeEntry is ChangeEntry.AddEntity) assertEquals(changeEntry.entityData.entitySource, AnotherSource) } @Test fun `add plus change source and modify`() { val entity = builder.addParentEntity("Parent") builder.modifyEntity(entity) { this.entitySource = AnotherSource } builder.modifyEntity(entity) { this.parentProperty = "Another Parent" } val log = builder.changeLog.changeLog assertEquals(1, log.size) val changeEntry = log.values.single() assertTrue(changeEntry is ChangeEntry.AddEntity) assertEquals("Another Parent", (changeEntry.entityData as XParentEntityData).parentProperty) assertEquals(changeEntry.entityData.entitySource, AnotherSource) } @Test fun `modify plus change source`() { val entity = builder.addParentEntity("Parent") builder.changeLog.clear() builder.modifyEntity(entity) { this.parentProperty = "Another Parent" } builder.modifyEntity(entity) { this.entitySource = AnotherSource } val log = builder.changeLog.changeLog assertEquals(1, log.size) val changeEntry = log.values.single() assertTrue(changeEntry is ChangeEntry.ReplaceAndChangeSource) assertEquals((changeEntry.dataChange.newData as XParentEntityData).parentProperty, "Another Parent") assertEquals(changeEntry.sourceChange.newData.entitySource, AnotherSource) } @Test fun `modify plus remove`() { val entity = builder.addParentEntity("Parent") builder.changeLog.clear() builder.modifyEntity(entity) { this.parentProperty = "Another Parent" } builder.removeEntity(entity) val log = builder.changeLog.changeLog assertEquals(1, log.size) val changeEntry = log.values.single() assertTrue(changeEntry is ChangeEntry.RemoveEntity) } @Test fun `change source plus modify`() { val entity = builder.addParentEntity("Parent") builder.changeLog.clear() builder.modifyEntity(entity) { this.entitySource = AnotherSource } builder.modifyEntity(entity) { this.parentProperty = "Another Parent" } val log = builder.changeLog.changeLog assertEquals(1, log.size) val changeEntry = log.values.single() assertTrue(changeEntry is ChangeEntry.ReplaceAndChangeSource) assertEquals((changeEntry.dataChange.newData as XParentEntityData).parentProperty, "Another Parent") assertEquals(changeEntry.sourceChange.newData.entitySource, AnotherSource) } @Test fun `change source plus remove`() { val entity = builder.addParentEntity("Parent") builder.changeLog.clear() builder.modifyEntity(entity) { this.entitySource = AnotherSource } builder.removeEntity(entity) val log = builder.changeLog.changeLog assertEquals(1, log.size) val changeEntry = log.values.single() assertTrue(changeEntry is ChangeEntry.RemoveEntity) } @Test fun `change source and modify plus remove`() { val entity = builder.addParentEntity("Parent") builder.changeLog.clear() builder.modifyEntity(entity) { this.entitySource = AnotherSource } builder.modifyEntity(entity) { this.parentProperty = "Another Parent" } builder.removeEntity(entity) val log = builder.changeLog.changeLog assertEquals(1, log.size) val changeEntry = log.values.single() assertTrue(changeEntry is ChangeEntry.RemoveEntity) } @Test fun `change source and modify plus change source`() { val entity = builder.addParentEntity("Parent") builder.changeLog.clear() builder.modifyEntity(entity) { this.entitySource = AnotherSource } builder.modifyEntity(entity) { this.parentProperty = "Another Parent" } builder.modifyEntity(entity) { this.entitySource = SampleEntitySource("X") } val log = builder.changeLog.changeLog assertEquals(1, log.size) val changeEntry = log.values.single() assertInstanceOf<ChangeEntry.ReplaceAndChangeSource>(changeEntry) assertEquals(((changeEntry as ChangeEntry.ReplaceAndChangeSource).dataChange.newData as XParentEntityData).parentProperty, "Another Parent") assertEquals(changeEntry.sourceChange.newData.entitySource, SampleEntitySource("X")) } @Test fun `change source and modify plus modify`() { val entity = builder.addParentEntity("Parent") builder.changeLog.clear() builder.modifyEntity(entity) { entitySource = AnotherSource } builder.modifyEntity(entity) { this.parentProperty = "Another Parent" } builder.modifyEntity(entity) { this.parentProperty = "Third Parent" } val log = builder.changeLog.changeLog assertEquals(1, log.size) val changeEntry = log.values.single() assertInstanceOf<ChangeEntry.ReplaceAndChangeSource>(changeEntry) assertEquals(((changeEntry as ChangeEntry.ReplaceAndChangeSource).dataChange.newData as XParentEntityData).parentProperty, "Third Parent") assertEquals(changeEntry.sourceChange.newData.entitySource, AnotherSource) } @Test fun `modify add children`() { val entity = builder.addParentEntity("Parent") val firstChild = builder.addChildWithOptionalParentEntity(null) val secondChild = builder.addChildWithOptionalParentEntity(null) builder.changeLog.clear() builder.modifyEntity(entity) { this.optionalChildren = listOf(firstChild, secondChild) } val log = builder.changeLog.changeLog assertEquals(1, log.size) val changeEntry = log.values.single() assertTrue(changeEntry is ChangeEntry.ReplaceEntity) changeEntry as ChangeEntry.ReplaceEntity assertEquals(0, changeEntry.removedChildren.size) assertEquals(2, changeEntry.newChildren.size) assertEquals(0, changeEntry.modifiedParents.size) } @Test fun `modify remove children`() { val entity = builder.addParentEntity("Parent") builder.addChildWithOptionalParentEntity(entity) builder.addChildWithOptionalParentEntity(entity) builder.changeLog.clear() builder.modifyEntity(entity) { this.optionalChildren = listOf() } val log = builder.changeLog.changeLog assertEquals(1, log.size) val changeEntry = log.values.single() assertTrue(changeEntry is ChangeEntry.ReplaceEntity) changeEntry as ChangeEntry.ReplaceEntity assertEquals(2, changeEntry.removedChildren.size) assertEquals(0, changeEntry.newChildren.size) assertEquals(0, changeEntry.modifiedParents.size) } @Test fun `modify add and remove children`() { val entity = builder.addParentEntity("Parent") val child = builder.addChildWithOptionalParentEntity(null) builder.addChildWithOptionalParentEntity(entity) builder.changeLog.clear() builder.modifyEntity(entity) { this.optionalChildren = listOf(child) } val log = builder.changeLog.changeLog assertEquals(1, log.size) val changeEntry = log.values.single() assertTrue(changeEntry is ChangeEntry.ReplaceEntity) changeEntry as ChangeEntry.ReplaceEntity assertEquals(1, changeEntry.removedChildren.size) assertEquals(1, changeEntry.newChildren.size) assertEquals(0, changeEntry.modifiedParents.size) } @Test fun `modify twice add and remove children`() { val entity = builder.addParentEntity("Parent") val firstChild = builder.addChildWithOptionalParentEntity(null) val secondChild = builder.addChildWithOptionalParentEntity(null) builder.changeLog.clear() builder.modifyEntity(entity) { this.optionalChildren = listOf(firstChild, secondChild) } builder.modifyEntity(entity) { this.optionalChildren = listOf() } val log = builder.changeLog.changeLog assertEquals(0, log.size) } @Test fun `modify twice remove and add children`() { val entity = builder.addParentEntity("Parent") val firstChild = builder.addChildWithOptionalParentEntity(entity) val secondChild = builder.addChildWithOptionalParentEntity(entity) builder.changeLog.clear() builder.modifyEntity(entity) { this.optionalChildren = listOf() } builder.modifyEntity(entity) { this.optionalChildren = listOf(firstChild, secondChild) } val log = builder.changeLog.changeLog assertEquals(0, log.size) } @Test fun `modify twice remove and remove children`() { val entity = builder.addParentEntity("Parent") val firstChild = builder.addChildWithOptionalParentEntity(entity) builder.addChildWithOptionalParentEntity(entity) builder.changeLog.clear() builder.modifyEntity(entity) { this.optionalChildren = listOf(firstChild) } builder.modifyEntity(entity) { this.optionalChildren = listOf() } val log = builder.changeLog.changeLog assertEquals(1, log.size) val changeEntry = log.values.single() assertTrue(changeEntry is ChangeEntry.ReplaceEntity) changeEntry as ChangeEntry.ReplaceEntity assertEquals(2, changeEntry.removedChildren.size) assertEquals(0, changeEntry.newChildren.size) assertEquals(0, changeEntry.modifiedParents.size) } @Test fun `modify twice add and add children`() { val entity = builder.addParentEntity("Parent") val firstChild = builder.addChildWithOptionalParentEntity(null) val secondChild = builder.addChildWithOptionalParentEntity(null) builder.changeLog.clear() builder.modifyEntity(entity) { this.optionalChildren = listOf(firstChild) } builder.modifyEntity(entity) { this.optionalChildren = listOf(firstChild, secondChild) } val log = builder.changeLog.changeLog assertEquals(1, log.size) val changeEntry = log.values.single() assertTrue(changeEntry is ChangeEntry.ReplaceEntity) changeEntry as ChangeEntry.ReplaceEntity assertEquals(0, changeEntry.removedChildren.size) assertEquals(2, changeEntry.newChildren.size) assertEquals(0, changeEntry.modifiedParents.size) } // ------------- Testing events collapsing ---- @Test fun `collaps empty modify`() { val entity = builder.addNamedEntity("Parent") builder.changeLog.clear() builder.modifyEntity(entity) {} val log = builder.changeLog.changeLog assertEquals(0, log.size) } @Test fun `collaps two modify`() { val entity = builder.addNamedEntity("Parent") builder.changeLog.clear() builder.modifyEntity(entity) { myName = "AnotherName" } builder.modifyEntity(entity) { myName = "Parent" } val log = builder.changeLog.changeLog assertEquals(0, log.size) } @Test fun `collaps two modify with parent refs`() { val parent1 = builder.addNamedEntity("Parent") val parent2 = builder.addNamedEntity("Parent2") val child1 = builder.addNamedChildEntity(parent1) builder.changeLog.clear() builder.modifyEntity(child1) { this.parentEntity = parent2 } builder.modifyEntity(child1) { this.parentEntity = parent1 } val log = builder.changeLog.changeLog assertEquals(0, log.size) } @Test fun `collaps two modify with children refs`() { val parent = builder.addParentEntity() val child1 = builder.addChildWithOptionalParentEntity(parent) val child2 = builder.addChildWithOptionalParentEntity(parent) val child3 = builder.addChildWithOptionalParentEntity(parent) builder.changeLog.clear() builder.modifyEntity(parent) { this.optionalChildren = listOf() } builder.modifyEntity(parent) { this.optionalChildren = listOf(child1, child2, child3) } val log = builder.changeLog.changeLog assertEquals(0, log.size) } @Test fun `collaps three modify`() { val entity = builder.addNamedEntity("Parent") builder.changeLog.clear() builder.modifyEntity(entity) { myName = "AnotherName" } builder.modifyEntity(entity) { myName = "AndAnotherName" } builder.modifyEntity(entity) { myName = "Parent" } val log = builder.changeLog.changeLog assertEquals(0, log.size) } @Test fun `collaps two modify and source change`() { val entity = builder.addNamedEntity("Parent") builder.changeLog.clear() builder.modifyEntity(entity) { myName = "AnotherName" } builder.modifyEntity(entity) { this.entitySource = AnotherSource } builder.modifyEntity(entity) { myName = "Parent" } val log = builder.changeLog.changeLog assertEquals(1, log.size) assertInstanceOf<ChangeEntry.ChangeEntitySource>(log.entries.single ().value) } @Test fun `collaps two modify and two source change`() { val entity = builder.addNamedEntity("Parent") builder.changeLog.clear() builder.modifyEntity(entity) { myName = "AnotherName" } builder.modifyEntity(entity) { this.entitySource = AnotherSource } builder.modifyEntity(entity) { this.entitySource = MySource } builder.modifyEntity(entity) { myName = "Parent" } val log = builder.changeLog.changeLog assertEquals(0, log.size) } @Test fun `collaps two modify and two source change in mix`() { val entity = builder.addNamedEntity("Parent") builder.changeLog.clear() builder.modifyEntity(entity) { myName = "AnotherName" } builder.modifyEntity(entity) { this.entitySource = AnotherSource } builder.modifyEntity(entity) { myName = "Parent" } builder.modifyEntity(entity) { this.entitySource = MySource } val log = builder.changeLog.changeLog assertEquals(0, log.size) } @Test fun `collaps empty source change`() { val entity = builder.addNamedEntity("Parent", source = MySource) builder.changeLog.clear() builder.modifyEntity(entity) { this.entitySource = MySource } val log = builder.changeLog.changeLog assertEquals(0, log.size) } @Test fun `collaps source change twice`() { val entity = builder.addNamedEntity("Parent", source = MySource) builder.changeLog.clear() builder.modifyEntity(entity) { this.entitySource = AnotherSource } builder.modifyEntity(entity) { this.entitySource = MySource } val log = builder.changeLog.changeLog assertEquals(0, log.size) } @Test fun `add and change source`() { val oldSource = SampleEntitySource("oldSource") val entity = builder.addSourceEntity("one", oldSource) builder.modifyEntity(entity) { this.entitySource = SampleEntitySource("newSource") } val change = builder.changeLog.changeLog.values.single() assertInstanceOf<ChangeEntry.AddEntity>(change) } @Test fun `join remove plus add`() { val oldSource = SampleEntitySource("oldSource") val entity = builder.addSourceEntity("one", oldSource) builder.changeLog.clear() val original = builder.toSnapshot() builder.removeEntity(entity) builder.addSourceEntity("one", oldSource) assertTrue(builder.hasSameEntities(original as AbstractEntityStorage)) } @Test fun `join remove plus add content root`() { val moduleTestEntity = ModuleTestEntity("data", MySource) { contentRoots = listOf( ContentRootTestEntity(MySource) ) } builder.addEntity(moduleTestEntity) builder.changeLog.clear() val original = builder.toSnapshot() builder.removeEntity(builder.entities(ModuleTestEntity::class.java).single().contentRoots.single()) builder.addEntity(ContentRootTestEntity(MySource) { module = moduleTestEntity }) assertTrue(builder.hasSameEntities(original as AbstractEntityStorage)) } @Test fun `join remove plus add content root with mappings`() { val moduleTestEntity = ModuleTestEntity("data", MySource) { contentRoots = listOf( ContentRootTestEntity(MySource) ) } builder.addEntity(moduleTestEntity) builder.changeLog.clear() val contentRoot = builder.entities(ModuleTestEntity::class.java).single().contentRoots.single() builder.getMutableExternalMapping<Any>("data").addMapping(contentRoot, 1) val original = builder.toSnapshot() builder.removeEntity(contentRoot) builder.addEntity(ContentRootTestEntity(MySource) { module = moduleTestEntity }) assertFalse(builder.hasSameEntities(original as AbstractEntityStorage)) } @Test fun `join remove plus add content root with mappings 2`() { val moduleTestEntity = ModuleTestEntity("data", MySource) { contentRoots = listOf( ContentRootTestEntity(MySource) ) } builder.addEntity(moduleTestEntity) builder.changeLog.clear() val contentRoot = builder.entities(ModuleTestEntity::class.java).single().contentRoots.single() val original = builder.toSnapshot() builder.removeEntity(contentRoot) val newContentRoot = ContentRootTestEntity(MySource) { module = moduleTestEntity } builder.addEntity(newContentRoot) builder.getMutableExternalMapping<Any>("data").addMapping(newContentRoot, 1) assertFalse(builder.hasSameEntities(original as AbstractEntityStorage)) } // ------------- Testing events collapsing end ---- }
apache-2.0
73a4d4d23081fb6eaf3ccff258992e9f
29.393987
140
0.713973
4.62509
false
true
false
false
GunoH/intellij-community
platform/lang-impl/src/com/intellij/ide/bookmark/actions/NodeEditAction.kt
5
1375
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.ide.bookmark.actions import com.intellij.CommonBundle.messagePointer import com.intellij.ide.bookmark.BookmarksListProviderService import com.intellij.openapi.actionSystem.ActionUpdateThread import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.project.DumbAwareAction internal class NodeEditAction : DumbAwareAction(messagePointer("button.edit")) { override fun getActionUpdateThread(): ActionUpdateThread = ActionUpdateThread.BGT override fun update(event: AnActionEvent) { event.presentation.isEnabled = false val project = event.project ?: return val node = event.bookmarkNodes?.singleOrNull() ?: return val provider = BookmarksListProviderService.findProvider(project) { it.canEdit(node) } ?: return provider.editActionText?.let { event.presentation.text = it } event.presentation.isEnabled = true } override fun actionPerformed(event: AnActionEvent) { val project = event.project ?: return val view = event.bookmarksView ?: return val node = event.bookmarkNodes?.singleOrNull() ?: return BookmarksListProviderService.findProvider(project) { it.canEdit(node) }?.performEdit(node, view.tree) } init { isEnabledInModalContext = true } }
apache-2.0
0727cc55677a4d7982db9cd7e640bd35
40.666667
120
0.775273
4.676871
false
false
false
false
AsamK/TextSecure
app/src/main/java/org/thoughtcrime/securesms/components/emoji/EmojiItemDecoration.kt
3
2267
package org.thoughtcrime.securesms.components.emoji import android.graphics.Canvas import android.graphics.Rect import android.graphics.drawable.Drawable import android.view.View import androidx.appcompat.widget.AppCompatTextView import androidx.recyclerview.widget.RecyclerView import org.thoughtcrime.securesms.components.emoji.EmojiPageViewGridAdapter.EmojiModel import org.thoughtcrime.securesms.util.InsetItemDecoration import org.thoughtcrime.securesms.util.ViewUtil private val EDGE_LENGTH: Int = ViewUtil.dpToPx(6) private val HORIZONTAL_INSET: Int = ViewUtil.dpToPx(6) private val EMOJI_VERTICAL_INSET: Int = ViewUtil.dpToPx(5) private val HEADER_VERTICAL_INSET: Int = ViewUtil.dpToPx(8) /** * Use super class to add insets to the emojis and use the [onDrawOver] to draw the variation * hint if the emoji has more than one variation. */ class EmojiItemDecoration(private val allowVariations: Boolean, private val variationsDrawable: Drawable) : InsetItemDecoration(SetInset()) { override fun onDrawOver(canvas: Canvas, parent: RecyclerView, state: RecyclerView.State) { super.onDrawOver(canvas, parent, state) val adapter: EmojiPageViewGridAdapter? = parent.adapter as? EmojiPageViewGridAdapter if (allowVariations && adapter != null) { for (i in 0 until parent.childCount) { val child: View = parent.getChildAt(i) val position: Int = parent.getChildAdapterPosition(child) if (position >= 0 && position <= adapter.itemCount) { val model = adapter.currentList[position] if (model is EmojiModel && model.emoji.hasMultipleVariations()) { variationsDrawable.setBounds(child.right, child.bottom - EDGE_LENGTH, child.right + EDGE_LENGTH, child.bottom) variationsDrawable.draw(canvas) } } } } } private class SetInset : InsetItemDecoration.SetInset() { override fun setInset(outRect: Rect, view: View, parent: RecyclerView) { val isHeader = view.javaClass == AppCompatTextView::class.java outRect.left = HORIZONTAL_INSET outRect.right = HORIZONTAL_INSET outRect.top = if (isHeader) HEADER_VERTICAL_INSET else EMOJI_VERTICAL_INSET outRect.bottom = if (isHeader) 0 else EMOJI_VERTICAL_INSET } } }
gpl-3.0
debad31da5f992102ed548c0fac798de
41.773585
141
0.74195
4.376448
false
false
false
false
Philip-Trettner/GlmKt
GlmKt/src/glm/vec/String/StringVec3.kt
1
18582
package glm data class StringVec3(val x: String, val y: String, val z: String) { // Initializes each element by evaluating init from 0 until 2 constructor(init: (Int) -> String) : this(init(0), init(1), init(2)) operator fun get(idx: Int): String = when (idx) { 0 -> x 1 -> y 2 -> z else -> throw IndexOutOfBoundsException("index $idx is out of bounds") } // Operators inline fun map(func: (String) -> String): StringVec3 = StringVec3(func(x), func(y), func(z)) fun toList(): List<String> = listOf(x, y, z) // Predefined vector constants companion object Constants { val zero: StringVec3 = StringVec3("", "", "") } // Conversions to Float inline fun toVec(conv: (String) -> Float): Vec3 = Vec3(conv(x), conv(y), conv(z)) inline fun toVec2(conv: (String) -> Float): Vec2 = Vec2(conv(x), conv(y)) inline fun toVec3(conv: (String) -> Float): Vec3 = Vec3(conv(x), conv(y), conv(z)) inline fun toVec4(w: Float = 0f, conv: (String) -> Float): Vec4 = Vec4(conv(x), conv(y), conv(z), w) // Conversions to Float inline fun toMutableVec(conv: (String) -> Float): MutableVec3 = MutableVec3(conv(x), conv(y), conv(z)) inline fun toMutableVec2(conv: (String) -> Float): MutableVec2 = MutableVec2(conv(x), conv(y)) inline fun toMutableVec3(conv: (String) -> Float): MutableVec3 = MutableVec3(conv(x), conv(y), conv(z)) inline fun toMutableVec4(w: Float = 0f, conv: (String) -> Float): MutableVec4 = MutableVec4(conv(x), conv(y), conv(z), w) // Conversions to Double inline fun toDoubleVec(conv: (String) -> Double): DoubleVec3 = DoubleVec3(conv(x), conv(y), conv(z)) inline fun toDoubleVec2(conv: (String) -> Double): DoubleVec2 = DoubleVec2(conv(x), conv(y)) inline fun toDoubleVec3(conv: (String) -> Double): DoubleVec3 = DoubleVec3(conv(x), conv(y), conv(z)) inline fun toDoubleVec4(w: Double = 0.0, conv: (String) -> Double): DoubleVec4 = DoubleVec4(conv(x), conv(y), conv(z), w) // Conversions to Double inline fun toMutableDoubleVec(conv: (String) -> Double): MutableDoubleVec3 = MutableDoubleVec3(conv(x), conv(y), conv(z)) inline fun toMutableDoubleVec2(conv: (String) -> Double): MutableDoubleVec2 = MutableDoubleVec2(conv(x), conv(y)) inline fun toMutableDoubleVec3(conv: (String) -> Double): MutableDoubleVec3 = MutableDoubleVec3(conv(x), conv(y), conv(z)) inline fun toMutableDoubleVec4(w: Double = 0.0, conv: (String) -> Double): MutableDoubleVec4 = MutableDoubleVec4(conv(x), conv(y), conv(z), w) // Conversions to Int inline fun toIntVec(conv: (String) -> Int): IntVec3 = IntVec3(conv(x), conv(y), conv(z)) inline fun toIntVec2(conv: (String) -> Int): IntVec2 = IntVec2(conv(x), conv(y)) inline fun toIntVec3(conv: (String) -> Int): IntVec3 = IntVec3(conv(x), conv(y), conv(z)) inline fun toIntVec4(w: Int = 0, conv: (String) -> Int): IntVec4 = IntVec4(conv(x), conv(y), conv(z), w) // Conversions to Int inline fun toMutableIntVec(conv: (String) -> Int): MutableIntVec3 = MutableIntVec3(conv(x), conv(y), conv(z)) inline fun toMutableIntVec2(conv: (String) -> Int): MutableIntVec2 = MutableIntVec2(conv(x), conv(y)) inline fun toMutableIntVec3(conv: (String) -> Int): MutableIntVec3 = MutableIntVec3(conv(x), conv(y), conv(z)) inline fun toMutableIntVec4(w: Int = 0, conv: (String) -> Int): MutableIntVec4 = MutableIntVec4(conv(x), conv(y), conv(z), w) // Conversions to Long inline fun toLongVec(conv: (String) -> Long): LongVec3 = LongVec3(conv(x), conv(y), conv(z)) inline fun toLongVec2(conv: (String) -> Long): LongVec2 = LongVec2(conv(x), conv(y)) inline fun toLongVec3(conv: (String) -> Long): LongVec3 = LongVec3(conv(x), conv(y), conv(z)) inline fun toLongVec4(w: Long = 0L, conv: (String) -> Long): LongVec4 = LongVec4(conv(x), conv(y), conv(z), w) // Conversions to Long inline fun toMutableLongVec(conv: (String) -> Long): MutableLongVec3 = MutableLongVec3(conv(x), conv(y), conv(z)) inline fun toMutableLongVec2(conv: (String) -> Long): MutableLongVec2 = MutableLongVec2(conv(x), conv(y)) inline fun toMutableLongVec3(conv: (String) -> Long): MutableLongVec3 = MutableLongVec3(conv(x), conv(y), conv(z)) inline fun toMutableLongVec4(w: Long = 0L, conv: (String) -> Long): MutableLongVec4 = MutableLongVec4(conv(x), conv(y), conv(z), w) // Conversions to Short inline fun toShortVec(conv: (String) -> Short): ShortVec3 = ShortVec3(conv(x), conv(y), conv(z)) inline fun toShortVec2(conv: (String) -> Short): ShortVec2 = ShortVec2(conv(x), conv(y)) inline fun toShortVec3(conv: (String) -> Short): ShortVec3 = ShortVec3(conv(x), conv(y), conv(z)) inline fun toShortVec4(w: Short = 0.toShort(), conv: (String) -> Short): ShortVec4 = ShortVec4(conv(x), conv(y), conv(z), w) // Conversions to Short inline fun toMutableShortVec(conv: (String) -> Short): MutableShortVec3 = MutableShortVec3(conv(x), conv(y), conv(z)) inline fun toMutableShortVec2(conv: (String) -> Short): MutableShortVec2 = MutableShortVec2(conv(x), conv(y)) inline fun toMutableShortVec3(conv: (String) -> Short): MutableShortVec3 = MutableShortVec3(conv(x), conv(y), conv(z)) inline fun toMutableShortVec4(w: Short = 0.toShort(), conv: (String) -> Short): MutableShortVec4 = MutableShortVec4(conv(x), conv(y), conv(z), w) // Conversions to Byte inline fun toByteVec(conv: (String) -> Byte): ByteVec3 = ByteVec3(conv(x), conv(y), conv(z)) inline fun toByteVec2(conv: (String) -> Byte): ByteVec2 = ByteVec2(conv(x), conv(y)) inline fun toByteVec3(conv: (String) -> Byte): ByteVec3 = ByteVec3(conv(x), conv(y), conv(z)) inline fun toByteVec4(w: Byte = 0.toByte(), conv: (String) -> Byte): ByteVec4 = ByteVec4(conv(x), conv(y), conv(z), w) // Conversions to Byte inline fun toMutableByteVec(conv: (String) -> Byte): MutableByteVec3 = MutableByteVec3(conv(x), conv(y), conv(z)) inline fun toMutableByteVec2(conv: (String) -> Byte): MutableByteVec2 = MutableByteVec2(conv(x), conv(y)) inline fun toMutableByteVec3(conv: (String) -> Byte): MutableByteVec3 = MutableByteVec3(conv(x), conv(y), conv(z)) inline fun toMutableByteVec4(w: Byte = 0.toByte(), conv: (String) -> Byte): MutableByteVec4 = MutableByteVec4(conv(x), conv(y), conv(z), w) // Conversions to Char inline fun toCharVec(conv: (String) -> Char): CharVec3 = CharVec3(conv(x), conv(y), conv(z)) inline fun toCharVec2(conv: (String) -> Char): CharVec2 = CharVec2(conv(x), conv(y)) inline fun toCharVec3(conv: (String) -> Char): CharVec3 = CharVec3(conv(x), conv(y), conv(z)) inline fun toCharVec4(w: Char, conv: (String) -> Char): CharVec4 = CharVec4(conv(x), conv(y), conv(z), w) // Conversions to Char inline fun toMutableCharVec(conv: (String) -> Char): MutableCharVec3 = MutableCharVec3(conv(x), conv(y), conv(z)) inline fun toMutableCharVec2(conv: (String) -> Char): MutableCharVec2 = MutableCharVec2(conv(x), conv(y)) inline fun toMutableCharVec3(conv: (String) -> Char): MutableCharVec3 = MutableCharVec3(conv(x), conv(y), conv(z)) inline fun toMutableCharVec4(w: Char, conv: (String) -> Char): MutableCharVec4 = MutableCharVec4(conv(x), conv(y), conv(z), w) // Conversions to Boolean fun toBoolVec(): BoolVec3 = BoolVec3(x != "", y != "", z != "") inline fun toBoolVec(conv: (String) -> Boolean): BoolVec3 = BoolVec3(conv(x), conv(y), conv(z)) fun toBoolVec2(): BoolVec2 = BoolVec2(x != "", y != "") inline fun toBoolVec2(conv: (String) -> Boolean): BoolVec2 = BoolVec2(conv(x), conv(y)) fun toBoolVec3(): BoolVec3 = BoolVec3(x != "", y != "", z != "") inline fun toBoolVec3(conv: (String) -> Boolean): BoolVec3 = BoolVec3(conv(x), conv(y), conv(z)) fun toBoolVec4(w: Boolean = false): BoolVec4 = BoolVec4(x != "", y != "", z != "", w) inline fun toBoolVec4(w: Boolean = false, conv: (String) -> Boolean): BoolVec4 = BoolVec4(conv(x), conv(y), conv(z), w) // Conversions to Boolean fun toMutableBoolVec(): MutableBoolVec3 = MutableBoolVec3(x != "", y != "", z != "") inline fun toMutableBoolVec(conv: (String) -> Boolean): MutableBoolVec3 = MutableBoolVec3(conv(x), conv(y), conv(z)) fun toMutableBoolVec2(): MutableBoolVec2 = MutableBoolVec2(x != "", y != "") inline fun toMutableBoolVec2(conv: (String) -> Boolean): MutableBoolVec2 = MutableBoolVec2(conv(x), conv(y)) fun toMutableBoolVec3(): MutableBoolVec3 = MutableBoolVec3(x != "", y != "", z != "") inline fun toMutableBoolVec3(conv: (String) -> Boolean): MutableBoolVec3 = MutableBoolVec3(conv(x), conv(y), conv(z)) fun toMutableBoolVec4(w: Boolean = false): MutableBoolVec4 = MutableBoolVec4(x != "", y != "", z != "", w) inline fun toMutableBoolVec4(w: Boolean = false, conv: (String) -> Boolean): MutableBoolVec4 = MutableBoolVec4(conv(x), conv(y), conv(z), w) // Conversions to String fun toStringVec(): StringVec3 = StringVec3(x, y, z) inline fun toStringVec(conv: (String) -> String): StringVec3 = StringVec3(conv(x), conv(y), conv(z)) fun toStringVec2(): StringVec2 = StringVec2(x, y) inline fun toStringVec2(conv: (String) -> String): StringVec2 = StringVec2(conv(x), conv(y)) fun toStringVec3(): StringVec3 = StringVec3(x, y, z) inline fun toStringVec3(conv: (String) -> String): StringVec3 = StringVec3(conv(x), conv(y), conv(z)) fun toStringVec4(w: String = ""): StringVec4 = StringVec4(x, y, z, w) inline fun toStringVec4(w: String = "", conv: (String) -> String): StringVec4 = StringVec4(conv(x), conv(y), conv(z), w) // Conversions to String fun toMutableStringVec(): MutableStringVec3 = MutableStringVec3(x, y, z) inline fun toMutableStringVec(conv: (String) -> String): MutableStringVec3 = MutableStringVec3(conv(x), conv(y), conv(z)) fun toMutableStringVec2(): MutableStringVec2 = MutableStringVec2(x, y) inline fun toMutableStringVec2(conv: (String) -> String): MutableStringVec2 = MutableStringVec2(conv(x), conv(y)) fun toMutableStringVec3(): MutableStringVec3 = MutableStringVec3(x, y, z) inline fun toMutableStringVec3(conv: (String) -> String): MutableStringVec3 = MutableStringVec3(conv(x), conv(y), conv(z)) fun toMutableStringVec4(w: String = ""): MutableStringVec4 = MutableStringVec4(x, y, z, w) inline fun toMutableStringVec4(w: String = "", conv: (String) -> String): MutableStringVec4 = MutableStringVec4(conv(x), conv(y), conv(z), w) // Conversions to T2 inline fun <T2> toTVec(conv: (String) -> T2): TVec3<T2> = TVec3<T2>(conv(x), conv(y), conv(z)) inline fun <T2> toTVec2(conv: (String) -> T2): TVec2<T2> = TVec2<T2>(conv(x), conv(y)) inline fun <T2> toTVec3(conv: (String) -> T2): TVec3<T2> = TVec3<T2>(conv(x), conv(y), conv(z)) inline fun <T2> toTVec4(w: T2, conv: (String) -> T2): TVec4<T2> = TVec4<T2>(conv(x), conv(y), conv(z), w) // Conversions to T2 inline fun <T2> toMutableTVec(conv: (String) -> T2): MutableTVec3<T2> = MutableTVec3<T2>(conv(x), conv(y), conv(z)) inline fun <T2> toMutableTVec2(conv: (String) -> T2): MutableTVec2<T2> = MutableTVec2<T2>(conv(x), conv(y)) inline fun <T2> toMutableTVec3(conv: (String) -> T2): MutableTVec3<T2> = MutableTVec3<T2>(conv(x), conv(y), conv(z)) inline fun <T2> toMutableTVec4(w: T2, conv: (String) -> T2): MutableTVec4<T2> = MutableTVec4<T2>(conv(x), conv(y), conv(z), w) // Allows for swizzling, e.g. v.swizzle.xzx inner class Swizzle { val xx: StringVec2 get() = StringVec2(x, x) val xy: StringVec2 get() = StringVec2(x, y) val xz: StringVec2 get() = StringVec2(x, z) val yx: StringVec2 get() = StringVec2(y, x) val yy: StringVec2 get() = StringVec2(y, y) val yz: StringVec2 get() = StringVec2(y, z) val zx: StringVec2 get() = StringVec2(z, x) val zy: StringVec2 get() = StringVec2(z, y) val zz: StringVec2 get() = StringVec2(z, z) val xxx: StringVec3 get() = StringVec3(x, x, x) val xxy: StringVec3 get() = StringVec3(x, x, y) val xxz: StringVec3 get() = StringVec3(x, x, z) val xyx: StringVec3 get() = StringVec3(x, y, x) val xyy: StringVec3 get() = StringVec3(x, y, y) val xyz: StringVec3 get() = StringVec3(x, y, z) val xzx: StringVec3 get() = StringVec3(x, z, x) val xzy: StringVec3 get() = StringVec3(x, z, y) val xzz: StringVec3 get() = StringVec3(x, z, z) val yxx: StringVec3 get() = StringVec3(y, x, x) val yxy: StringVec3 get() = StringVec3(y, x, y) val yxz: StringVec3 get() = StringVec3(y, x, z) val yyx: StringVec3 get() = StringVec3(y, y, x) val yyy: StringVec3 get() = StringVec3(y, y, y) val yyz: StringVec3 get() = StringVec3(y, y, z) val yzx: StringVec3 get() = StringVec3(y, z, x) val yzy: StringVec3 get() = StringVec3(y, z, y) val yzz: StringVec3 get() = StringVec3(y, z, z) val zxx: StringVec3 get() = StringVec3(z, x, x) val zxy: StringVec3 get() = StringVec3(z, x, y) val zxz: StringVec3 get() = StringVec3(z, x, z) val zyx: StringVec3 get() = StringVec3(z, y, x) val zyy: StringVec3 get() = StringVec3(z, y, y) val zyz: StringVec3 get() = StringVec3(z, y, z) val zzx: StringVec3 get() = StringVec3(z, z, x) val zzy: StringVec3 get() = StringVec3(z, z, y) val zzz: StringVec3 get() = StringVec3(z, z, z) val xxxx: StringVec4 get() = StringVec4(x, x, x, x) val xxxy: StringVec4 get() = StringVec4(x, x, x, y) val xxxz: StringVec4 get() = StringVec4(x, x, x, z) val xxyx: StringVec4 get() = StringVec4(x, x, y, x) val xxyy: StringVec4 get() = StringVec4(x, x, y, y) val xxyz: StringVec4 get() = StringVec4(x, x, y, z) val xxzx: StringVec4 get() = StringVec4(x, x, z, x) val xxzy: StringVec4 get() = StringVec4(x, x, z, y) val xxzz: StringVec4 get() = StringVec4(x, x, z, z) val xyxx: StringVec4 get() = StringVec4(x, y, x, x) val xyxy: StringVec4 get() = StringVec4(x, y, x, y) val xyxz: StringVec4 get() = StringVec4(x, y, x, z) val xyyx: StringVec4 get() = StringVec4(x, y, y, x) val xyyy: StringVec4 get() = StringVec4(x, y, y, y) val xyyz: StringVec4 get() = StringVec4(x, y, y, z) val xyzx: StringVec4 get() = StringVec4(x, y, z, x) val xyzy: StringVec4 get() = StringVec4(x, y, z, y) val xyzz: StringVec4 get() = StringVec4(x, y, z, z) val xzxx: StringVec4 get() = StringVec4(x, z, x, x) val xzxy: StringVec4 get() = StringVec4(x, z, x, y) val xzxz: StringVec4 get() = StringVec4(x, z, x, z) val xzyx: StringVec4 get() = StringVec4(x, z, y, x) val xzyy: StringVec4 get() = StringVec4(x, z, y, y) val xzyz: StringVec4 get() = StringVec4(x, z, y, z) val xzzx: StringVec4 get() = StringVec4(x, z, z, x) val xzzy: StringVec4 get() = StringVec4(x, z, z, y) val xzzz: StringVec4 get() = StringVec4(x, z, z, z) val yxxx: StringVec4 get() = StringVec4(y, x, x, x) val yxxy: StringVec4 get() = StringVec4(y, x, x, y) val yxxz: StringVec4 get() = StringVec4(y, x, x, z) val yxyx: StringVec4 get() = StringVec4(y, x, y, x) val yxyy: StringVec4 get() = StringVec4(y, x, y, y) val yxyz: StringVec4 get() = StringVec4(y, x, y, z) val yxzx: StringVec4 get() = StringVec4(y, x, z, x) val yxzy: StringVec4 get() = StringVec4(y, x, z, y) val yxzz: StringVec4 get() = StringVec4(y, x, z, z) val yyxx: StringVec4 get() = StringVec4(y, y, x, x) val yyxy: StringVec4 get() = StringVec4(y, y, x, y) val yyxz: StringVec4 get() = StringVec4(y, y, x, z) val yyyx: StringVec4 get() = StringVec4(y, y, y, x) val yyyy: StringVec4 get() = StringVec4(y, y, y, y) val yyyz: StringVec4 get() = StringVec4(y, y, y, z) val yyzx: StringVec4 get() = StringVec4(y, y, z, x) val yyzy: StringVec4 get() = StringVec4(y, y, z, y) val yyzz: StringVec4 get() = StringVec4(y, y, z, z) val yzxx: StringVec4 get() = StringVec4(y, z, x, x) val yzxy: StringVec4 get() = StringVec4(y, z, x, y) val yzxz: StringVec4 get() = StringVec4(y, z, x, z) val yzyx: StringVec4 get() = StringVec4(y, z, y, x) val yzyy: StringVec4 get() = StringVec4(y, z, y, y) val yzyz: StringVec4 get() = StringVec4(y, z, y, z) val yzzx: StringVec4 get() = StringVec4(y, z, z, x) val yzzy: StringVec4 get() = StringVec4(y, z, z, y) val yzzz: StringVec4 get() = StringVec4(y, z, z, z) val zxxx: StringVec4 get() = StringVec4(z, x, x, x) val zxxy: StringVec4 get() = StringVec4(z, x, x, y) val zxxz: StringVec4 get() = StringVec4(z, x, x, z) val zxyx: StringVec4 get() = StringVec4(z, x, y, x) val zxyy: StringVec4 get() = StringVec4(z, x, y, y) val zxyz: StringVec4 get() = StringVec4(z, x, y, z) val zxzx: StringVec4 get() = StringVec4(z, x, z, x) val zxzy: StringVec4 get() = StringVec4(z, x, z, y) val zxzz: StringVec4 get() = StringVec4(z, x, z, z) val zyxx: StringVec4 get() = StringVec4(z, y, x, x) val zyxy: StringVec4 get() = StringVec4(z, y, x, y) val zyxz: StringVec4 get() = StringVec4(z, y, x, z) val zyyx: StringVec4 get() = StringVec4(z, y, y, x) val zyyy: StringVec4 get() = StringVec4(z, y, y, y) val zyyz: StringVec4 get() = StringVec4(z, y, y, z) val zyzx: StringVec4 get() = StringVec4(z, y, z, x) val zyzy: StringVec4 get() = StringVec4(z, y, z, y) val zyzz: StringVec4 get() = StringVec4(z, y, z, z) val zzxx: StringVec4 get() = StringVec4(z, z, x, x) val zzxy: StringVec4 get() = StringVec4(z, z, x, y) val zzxz: StringVec4 get() = StringVec4(z, z, x, z) val zzyx: StringVec4 get() = StringVec4(z, z, y, x) val zzyy: StringVec4 get() = StringVec4(z, z, y, y) val zzyz: StringVec4 get() = StringVec4(z, z, y, z) val zzzx: StringVec4 get() = StringVec4(z, z, z, x) val zzzy: StringVec4 get() = StringVec4(z, z, z, y) val zzzz: StringVec4 get() = StringVec4(z, z, z, z) } val swizzle: Swizzle get() = Swizzle() } fun vecOf(x: String, y: String, z: String): StringVec3 = StringVec3(x, y, z)
mit
c8c160a64ce96d05e72e38a6d574df97
64.2
149
0.624368
3.297604
false
false
false
false
DemonWav/MinecraftDev
src/main/kotlin/com/demonwav/mcdev/platform/mixin/action/GenerateOverwriteAction.kt
1
4545
/* * Minecraft Dev for IntelliJ * * https://minecraftdev.org * * Copyright (c) 2018 minecraft-dev * * MIT License */ package com.demonwav.mcdev.platform.mixin.action import com.demonwav.mcdev.platform.mixin.util.MixinConstants import com.demonwav.mcdev.platform.mixin.util.findMethods import com.demonwav.mcdev.platform.mixin.util.findSource import com.demonwav.mcdev.util.MinecraftFileTemplateGroupFactory.Companion.MIXIN_OVERWRITE_FALLBACK import com.demonwav.mcdev.util.findContainingClass import com.demonwav.mcdev.util.ifEmpty import com.demonwav.mcdev.util.toTypedArray import com.intellij.codeInsight.generation.GenerateMembersUtil import com.intellij.codeInsight.generation.OverrideImplementUtil import com.intellij.codeInsight.generation.PsiGenerationInfo import com.intellij.codeInsight.generation.PsiMethodMember import com.intellij.codeInsight.hint.HintManager import com.intellij.ide.fileTemplates.FileTemplateManager import com.intellij.ide.util.MemberChooser import com.intellij.openapi.application.runWriteAction import com.intellij.openapi.editor.Editor import com.intellij.openapi.project.Project import com.intellij.psi.JavaPsiFacade import com.intellij.psi.PsiFile import com.intellij.psi.PsiMember import com.intellij.psi.PsiMethod import com.intellij.psi.codeStyle.CodeStyleManager class GenerateOverwriteAction : MixinCodeInsightAction() { override fun invoke(project: Project, editor: Editor, file: PsiFile) { val offset = editor.caretModel.offset val psiClass = file.findElementAt(offset)?.findContainingClass() ?: return val methods = (findMethods(psiClass) ?: return) .map(::PsiMethodMember).toTypedArray() if (methods.isEmpty()) { HintManager.getInstance().showErrorHint(editor, "No methods to overwrite have been found") return } val chooser = MemberChooser<PsiMethodMember>(methods, false, true, project) chooser.title = "Select Methods to Overwrite" chooser.setCopyJavadocVisible(false) chooser.show() val elements = (chooser.selectedElements ?: return).ifEmpty { return } val requiredMembers = LinkedHashSet<PsiMember>() runWriteAction { val newMethods = elements.map { val method = it.element.findSource() val sourceClass = method.containingClass val codeBlock = method.body val newMethod: PsiMethod if (sourceClass != null && codeBlock != null) { // Source of method is available // Collect all references to potential @Shadow members requiredMembers.addAll(collectRequiredMembers(codeBlock, sourceClass)) } // Create temporary (dummy) method var tmpMethod = JavaPsiFacade.getElementFactory(project).createMethod(method.name, method.returnType!!, psiClass) // Replace temporary method with a copy of the original method tmpMethod = tmpMethod.replace(method) as PsiMethod // Remove Javadocs OverrideImplementUtil.deleteDocComment(tmpMethod) // Reformat the code with the project settings newMethod = CodeStyleManager.getInstance(project).reformat(tmpMethod) as PsiMethod if (codeBlock == null) { // Generate fallback method body if source is not available OverrideImplementUtil.setupMethodBody(newMethod, method, psiClass, FileTemplateManager.getInstance(project).getCodeTemplate(MIXIN_OVERWRITE_FALLBACK)) } // TODO: Automatically add Javadoc comment for @Overwrite? - yes please // Add @Overwrite annotation newMethod.modifierList.addAnnotation(MixinConstants.Annotations.OVERWRITE) PsiGenerationInfo(newMethod) } // Insert new methods GenerateMembersUtil.insertMembersAtOffset(file, offset, newMethods) // Select first element in editor .first().positionCaret(editor, true) } // Generate needed shadows val newShadows = createShadowMembers(project, psiClass, filterNewShadows(requiredMembers, psiClass)) disableAnnotationWrapping(project) { runWriteAction { // Insert shadows insertShadows(psiClass, newShadows) } } } }
mit
a54cc342f1a1131fb6e6cc1a5df0bae0
39.221239
129
0.680088
5.248268
false
false
false
false
code-disaster/lwjgl3
modules/lwjgl/rpmalloc/src/templates/kotlin/rpmalloc/rpmallocTypes.kt
4
11882
/* * Copyright LWJGL. All rights reserved. * License terms: https://www.lwjgl.org/license */ package rpmalloc import org.lwjgl.generator.* import java.io.* fun config() { Generator.register(object : GeneratorTarget(Module.RPMALLOC, "RPmallocAllocator") { init { javaImport("org.lwjgl.system.MemoryUtil.*") javaImport("static org.lwjgl.system.rpmalloc.RPmalloc.*") documentation = "A {@link MemoryAllocator} implementation using the rpmalloc library." } override fun PrintWriter.generateJava() { generateJavaPreamble() println("""public class RPmallocAllocator implements MemoryAllocator { static { // initialize rpmalloc LibRPmalloc.initialize(); rpmalloc_initialize(); } @Override public long getMalloc() { return rpmalloc_address(); } @Override public long getCalloc() { return rpcalloc_address(); } @Override public long getRealloc() { return rprealloc_address(); } @Override public long getFree() { return rpfree_address(); } @Override public long getAlignedAlloc() { return rpaligned_alloc_address(); } @Override public long getAlignedFree() { return rpfree_address(); } @Override public long malloc(long size) { return nrpmalloc(size); } @Override public long calloc(long num, long size) { return nrpcalloc(num, size); } @Override public long realloc(long ptr, long size) { return nrprealloc(ptr, size); } @Override public void free(long ptr) { nrpfree(ptr); } @Override public long aligned_alloc(long alignment, long size) { return nrpaligned_alloc(alignment, size); } @Override public void aligned_free(long ptr) { nrpfree(ptr); } }""") } }) } val rpmalloc_heap_t = "rpmalloc_heap_t".opaque val rpmalloc_config_t = struct(Module.RPMALLOC, "RPMallocConfig", nativeName = "rpmalloc_config_t", skipBuffer = true) { documentation = """ This struct enables configuration of a memory mapper providing map/unmap of memory pages. Defaults to {@code VirtualAlloc}/{@code mmap} if none provided. This allows rpmalloc to be used in contexts where memory is provided by internal means. Page size may be set explicitly in initialization. This allows the allocator to be used as a sub-allocator where the page granularity should be lower to reduce risk of wasting unused memory ranges. If rpmalloc is built with {@code ENABLE_GUARDS}, {@code memory_overwrite} may be set to detect writes before or after allocated memory blocks. This is not enabled in the default LWJGL build. """ nullable..Module.RPMALLOC.callback { opaque_p( "RPMemoryMapCallback", """ Map memory pages for the given number of bytes. The returned address MUST be aligned to the rpmalloc span size, which will always be a power of two. Optionally the function can store an alignment offset in the offset variable in case it performs alignment and the returned pointer is offset from the actual start of the memory region due to this alignment. The alignment offset will be passed to the memory unmap function. The alignment offset MUST NOT be larger than 65535 (storable in an {@code uint16_t}), if it is you must use natural alignment to shift it into 16 bits. If you set a {@code memory_map} function, you must also set a {@code memory_unmap} function or else the default implementation will be used for both. """, size_t("size", "the number of bytes to map"), Check(1)..size_t.p("offset", "the alignment offset") ) { documentation = "Instances of this interface may be set to the ##RPMallocConfig struct." } }("memory_map", "the memory map callback function") nullable..Module.RPMALLOC.callback { void( "RPMemoryUnmapCallback", """ Unmap the memory pages starting at address and spanning the given number of bytes. If release is set to non-zero, the unmap is for an entire span range as returned by a previous call to {@code memory_map} and that the entire range should be released. The release argument holds the size of the entire span range. If {@code release} is set to 0, the unmap is a partial decommit of a subset of the mapped memory range. If you set a {@code memory_unmap} function, you must also set a {@code memory_map} function or else the default implementation will be used for both. """, //void* address, size_t size, size_t offset, int release opaque_p("address", "the address to unmap"), size_t("size", "the size of the mapped pages, in bytes"), size_t("offset", "the alignment offset"), intb("release", "the release flag") ) { documentation = "Instances of this interface may be set to the ##RPMallocConfig struct." } }("memory_unmap", "the memory unmap callback function") nullable..Module.RPMALLOC.callback { void( "RPErrorCallback", "Called when an assert fails, if asserts are enabled. Will use the standard {@code assert()} if this is not set.", charASCII.const.p("message", "") ) { documentation = "Instances of this interface may be set to the ##RPMallocConfig struct." } }("error_callback", "the error callback function") nullable..Module.RPMALLOC.callback { int( "RPMapFailCallback", """ Called when a call to map memory pages fails (out of memory). If this callback is not set or returns zero the library will return a null pointer in the allocation call. If this callback returns non-zero the map call will be retried. The argument passed is the number of bytes that was requested in the map call. Only used if the default system memory map function is used ({@code memory_map} callback is not set). """, size_t("size", "") ) { documentation = "Instances of this interface may be set to the ##RPMallocConfig struct." } }("map_fail_callback", "the map fail callback function") size_t( "page_size", """ the size of memory pages. The page size MUST be a power of two in {@code [512,16384]} range (2<sup>9</sup> to 2<sup>14</sup>) unless 0 - set to 0 to use system page size. All memory mapping requests to {@code memory_map} will be made with size set to a multiple of the page size. Used if {@code RPMALLOC_CONFIGURABLE} is defined to 1, otherwise system page size is used. """ ) size_t( "span_size", """ size of a span of memory blocks. MUST be a power of two, and in {@code [4096,262144]} range (unless 0 - set to 0 to use the default span size). Used if {@code RPMALLOC_CONFIGURABLE} is defined to 1. """ ) size_t( "span_map_count", """ number of spans to map at each request to map new virtual memory blocks. This can be used to minimize the system call overhead at the cost of virtual memory address space. The extra mapped pages will not be written until actually used, so physical committed memory should not be affected in the default implementation. Will be aligned to a multiple of spans that match memory page size in case of huge pages. """ ) intb( "enable_huge_pages", """ enable use of large/huge pages. If this flag is set to non-zero and page size is zero, the allocator will try to enable huge pages and auto detect the configuration. If this is set to non-zero and page_size is also non-zero, the allocator will assume huge pages have been configured and enabled prior to initializing the allocator. For Windows, see <a href="https://docs.microsoft.com/en-us/windows/desktop/memory/large-page-support">large-page-support</a>. For Linux, see <a href="https://www.kernel.org/doc/Documentation/vm/hugetlbpage.txt">hugetlbpage.txt</a>. """ ) padding(4) } val rpmalloc_global_statistics_t = struct( Module.RPMALLOC, "RPmallocGlobalStatistics", nativeName = "rpmalloc_global_statistics_t", mutable = false ) { size_t("mapped", "Current amount of virtual memory mapped, all of which might not have been committed (only if {@code ENABLE_STATISTICS=1})") size_t("mapped_peak", "Peak amount of virtual memory mapped, all of which might not have been committed (only if {@code ENABLE_STATISTICS=1})") size_t("cached", "Current amount of memory in global caches for small and medium sizes (&lt;32KiB)") size_t( "huge_alloc", """ Current amount of memory allocated in huge allocations, i.e larger than {@code LARGE_SIZE_LIMIT} which is 2MiB by default (only if {@code ENABLE_STATISTICS=1}) """ ) size_t( "huge_alloc_peak", """ Peak amount of memory allocated in huge allocations, i.e larger than {@code LARGE_SIZE_LIMIT} which is 2MiB by default (only if {@code ENABLE_STATISTICS=1}) """ ) size_t("mapped_total", "Total amount of memory mapped since initialization (only if {@code ENABLE_STATISTICS=1})") size_t("unmapped_total", "Total amount of memory unmapped since initialization (only if {@code ENABLE_STATISTICS=1})") } val rpmalloc_thread_statistics_t = struct( Module.RPMALLOC, "RPmallocThreadStatistics", nativeName = "rpmalloc_thread_statistics_t", mutable = false ) { size_t("sizecache", "Current number of bytes available in thread size class caches for small and medium sizes (&lt;32KiB)") size_t("spancache", "Current number of bytes available in thread span caches for small and medium sizes (&lt;32KiB)") size_t("thread_to_global", "Total number of bytes transitioned from thread cache to global cache (only if {@code ENABLE_STATISTICS=1})") size_t("global_to_thread", "Total number of bytes transitioned from global cache to thread cache (only if {@code ENABLE_STATISTICS=1})") struct { size_t("current", "Currently used number of spans") size_t("peak", "High water mark of spans used") size_t("to_global", "Number of spans transitioned to global cache") size_t("from_global", "Number of spans transitioned from global cache") size_t("to_cache", "Number of spans transitioned to thread cache") size_t("from_cache", "Number of spans transitioned from thread cache") size_t("to_reserved", "Number of spans transitioned to reserved state") size_t("from_reserved", "Number of spans transitioned from reserved state") size_t("map_calls", "Number of raw memory map calls (not hitting the reserve spans but resulting in actual OS mmap calls)") }("span_use", "Per span count statistics (only if {@code ENABLE_STATISTICS=1})")[64] struct { size_t("alloc_current", "Current number of allocations") size_t("alloc_peak", "Peak number of allocations") size_t("alloc_total", "Total number of allocations") size_t("free_total", "Total number of frees") size_t("spans_to_cache", "Number of spans transitioned to cache") size_t("spans_from_cache", "Number of spans transitioned from cache") size_t("spans_from_reserved", "Number of spans transitioned from reserved state") size_t("map_calls", "Number of raw memory map calls (not hitting the reserve spans but resulting in actual OS mmap calls)") }("size_use", "Per size class statistics (only if {@code ENABLE_STATISTICS=1})")[128] }
bsd-3-clause
29e1f996f3210547f6f0373ff0350265
42.6875
161
0.657633
4.164739
false
false
false
false
Frederikam/FredBoat
FredBoat/src/test/java/fredboat/testutil/sentinel/Raws.kt
1
3196
package fredboat.testutil.sentinel import com.fredboat.sentinel.entities.Ban import fredboat.perms.Permission import fredboat.sentinel.* /** * Welcome to FredBoat Hangout! This is a small Discord server with 4 members including a bot! * * We recently pruned the server of some >100k members. * * Roster: * * Fre_d: who happens to be the owner of this place * * FredBoat: The bot * * Napster: Admin wielding a banhammer * * RealKC: Generic shitposter * * Marisa was banned for theft */ /* Don't use immutable lists here. We want to be able to modify state directly */ @Suppress("MemberVisibilityCanBePrivate") object Raws { val botAdminRole = RawRole( 236842565855147826, "Bot Admin", 0 ) val adminRole = RawRole( 174824663258497024, "Admin", (Permission.BAN_MEMBERS + Permission.KICK_MEMBERS + Permission.MESSAGE_MANAGE).raw ) val uberAdminRole = RawRole( 318730262314834812, "Über Admin", (Permission.BAN_MEMBERS + Permission.KICK_MEMBERS + Permission.MESSAGE_MANAGE).raw ) val owner = RawMember( 81011298891993088, "Fre_d", "Fred", "0310", 174820236481134592, false, mutableListOf(), null ) val self = RawMember( 152691313123393536, "FredBoat♪♪", "FredBoat", "7284", 174820236481134592, true, mutableListOf(uberAdminRole.id), null ) val napster = RawMember( 166604053629894657, "Napster", "Napster", "0001", 174820236481134592, false, mutableListOf(adminRole.id), null ) val realkc = RawMember( 165912402716524544, "RealKC (RealKingChuck | KC)™", "RealKC", "7788", 174820236481134592, false, mutableListOf(), null ) val generalChannel = RawTextChannel( 174820236481134592, "general", (Permission.MESSAGE_READ + Permission.MESSAGE_WRITE).raw ) val privateChannel = RawTextChannel( 184358843206074368, "private", 0 ) val musicChannel = RawVoiceChannel( 226661001754443776, "Music", mutableListOf(), 5, (Permission.VIEW_CHANNEL + Permission.VOICE_CONNECT + Permission.VOICE_SPEAK).raw ) val guild = RawGuild( 174820236481134592, "FredBoat Hangout", owner.id, mutableListOf(owner, self, napster, realkc), mutableListOf(generalChannel, privateChannel), mutableListOf(musicChannel), mutableListOf(botAdminRole, uberAdminRole, adminRole), voiceServerUpdate = null ) val banList = mutableListOf(Ban(RawUser( id = 12345678901234, name = "Marisa Kirisame", discrim = "5678", bot = false ), "Theft")) }
mit
73e347196a7a753f6de32042964d3bfe
24.725806
94
0.552838
4.067602
false
false
false
false
fwcd/kotlin-language-server
shared/src/main/kotlin/org/javacs/kt/util/Utils.kt
1
3211
package org.javacs.kt.util import org.javacs.kt.LOG import java.io.PrintStream import java.nio.file.Path import java.nio.file.Paths import java.util.concurrent.CompletableFuture fun execAndReadStdout(shellCommand: List<String>, directory: Path): String { val process = ProcessBuilder(shellCommand).directory(directory.toFile()).start() val stdout = process.inputStream return stdout.bufferedReader().use { it.readText() } } fun execAndReadStdoutAndStderr(shellCommand: List<String>, directory: Path): Pair<String, String> { val process = ProcessBuilder(shellCommand).directory(directory.toFile()).start() val stdout = process.inputStream val stderr = process.errorStream var output = "" var errors = "" val outputThread = Thread { stdout.bufferedReader().use { output += it.readText() } } val errorsThread = Thread { stderr.bufferedReader().use { errors += it.readText() } } outputThread.start() errorsThread.start() outputThread.join() errorsThread.join() return Pair(output, errors) } inline fun withCustomStdout(delegateOut: PrintStream, task: () -> Unit) { val actualOut = System.out System.setOut(delegateOut) task() System.setOut(actualOut) } fun winCompatiblePathOf(path: String): Path { if (path.get(2) == ':' && path.get(0) == '/') { // Strip leading '/' when dealing with paths on Windows return Paths.get(path.substring(1)) } else { return Paths.get(path) } } fun String.partitionAroundLast(separator: String): Pair<String, String> = lastIndexOf(separator) .let { Pair(substring(0, it), substring(it, length)) } fun Path.replaceExtensionWith(newExtension: String): Path { val oldName = fileName.toString() val newName = oldName.substring(0, oldName.lastIndexOf(".")) + newExtension return resolveSibling(newName) } inline fun <T, C : Iterable<T>> C.onEachIndexed(transform: (index: Int, T) -> Unit): C = apply { var i = 0 for (element in this) { transform(i, element) i++ } } fun <T> noResult(message: String, result: T): T { LOG.info(message) return result } fun <T> noFuture(message: String, contents: T): CompletableFuture<T> = noResult(message, CompletableFuture.completedFuture(contents)) fun <T> emptyResult(message: String): List<T> = noResult(message, emptyList()) fun <T> nullResult(message: String): T? = noResult(message, null) fun <T> firstNonNull(vararg optionals: () -> T?): T? { for (optional in optionals) { val result = optional() if (result != null) { return result } } return null } fun <T> nonNull(item: T?, errorMsgIfNull: String): T = if (item == null) { throw NullPointerException(errorMsgIfNull) } else item inline fun <T> tryResolving(what: String, resolver: () -> T?): T? { try { val resolved = resolver() if (resolved != null) { LOG.info("Successfully resolved {}", what) return resolved } else { LOG.info("Could not resolve {} as it is null", what) } } catch (e: Exception) { LOG.info("Could not resolve {}: {}", what, e.message) } return null }
mit
b233297c6522f9132dfbad525d747713
30.480392
133
0.654625
3.8
false
false
false
false
dahlstrom-g/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/codeInliner/UsageReplacementStrategy.kt
2
8100
// 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.codeInliner import com.intellij.openapi.application.ModalityState import com.intellij.openapi.diagnostic.ControlFlowException import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.progress.ProgressIndicator import com.intellij.openapi.progress.ProgressManager import com.intellij.openapi.progress.Task import com.intellij.openapi.util.Key import com.intellij.openapi.util.NlsContexts import com.intellij.psi.PsiElement import com.intellij.psi.search.GlobalSearchScope import com.intellij.psi.search.searches.ReferencesSearch import com.intellij.util.ModalityUiUtil import org.jetbrains.kotlin.descriptors.DeclarationDescriptor import org.jetbrains.kotlin.descriptors.FunctionDescriptor import org.jetbrains.kotlin.idea.caches.resolve.resolveToCall import org.jetbrains.kotlin.idea.caches.resolve.resolveToDescriptorIfAny import org.jetbrains.kotlin.idea.core.compareDescriptors import org.jetbrains.kotlin.idea.core.targetDescriptors import org.jetbrains.kotlin.idea.intentions.ConvertReferenceToLambdaIntention import org.jetbrains.kotlin.idea.intentions.SpecifyExplicitLambdaSignatureIntention import org.jetbrains.kotlin.idea.references.KtSimpleReference import org.jetbrains.kotlin.idea.base.projectStructure.scope.KotlinSourceFilterScope import org.jetbrains.kotlin.idea.util.application.executeWriteCommand import org.jetbrains.kotlin.idea.util.application.runReadAction import org.jetbrains.kotlin.idea.util.reformatted import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.* import org.jetbrains.kotlin.utils.addToStdlib.safeAs interface UsageReplacementStrategy { fun createReplacer(usage: KtReferenceExpression): (() -> KtElement?)? companion object { val KEY = Key<Unit>("UsageReplacementStrategy.replaceUsages") } } private val LOG = Logger.getInstance(UsageReplacementStrategy::class.java) fun UsageReplacementStrategy.replaceUsagesInWholeProject( targetPsiElement: PsiElement, @NlsContexts.DialogTitle progressTitle: String, @NlsContexts.Command commandName: String, unwrapSpecialUsages: Boolean = true, ) { val project = targetPsiElement.project ProgressManager.getInstance().run( object : Task.Modal(project, progressTitle, true) { override fun run(indicator: ProgressIndicator) { val usages = runReadAction { val searchScope = KotlinSourceFilterScope.projectSources(GlobalSearchScope.projectScope(project), project) ReferencesSearch.search(targetPsiElement, searchScope) .filterIsInstance<KtSimpleReference<KtReferenceExpression>>() .map { ref -> ref.expression } } ModalityUiUtil.invokeLaterIfNeeded(ModalityState.NON_MODAL) { project.executeWriteCommand(commandName) { [email protected](usages, unwrapSpecialUsages) } } } }) } fun UsageReplacementStrategy.replaceUsages(usages: Collection<KtReferenceExpression>, unwrapSpecialUsages: Boolean = true) { val usagesByFile = usages.groupBy { it.containingFile } for ((file, usagesInFile) in usagesByFile) { usagesInFile.forEach { it.putCopyableUserData(UsageReplacementStrategy.KEY, Unit) } // we should delete imports later to not affect other usages val importsToDelete = mutableListOf<KtImportDirective>() var usagesToProcess = usagesInFile while (usagesToProcess.isNotEmpty()) { if (processUsages(usagesToProcess, importsToDelete, unwrapSpecialUsages)) break // some usages may get invalidated we need to find them in the tree usagesToProcess = file.collectDescendantsOfType { it.getCopyableUserData(UsageReplacementStrategy.KEY) != null } } file.forEachDescendantOfType<KtSimpleNameExpression> { it.putCopyableUserData(UsageReplacementStrategy.KEY, null) } importsToDelete.forEach { it.delete() } } } /** * @return false if some usages were invalidated */ private fun UsageReplacementStrategy.processUsages( usages: List<KtReferenceExpression>, importsToDelete: MutableList<KtImportDirective>, unwrapSpecialUsages: Boolean, ): Boolean { val sortedUsages = usages.sortedWith { element1, element2 -> if (element1.parent.textRange.intersects(element2.parent.textRange)) { compareValuesBy(element2, element1) { it.startOffset } } else { compareValuesBy(element1, element2) { it.startOffset } } } var invalidUsagesFound = false for (usage in sortedUsages) { try { if (!usage.isValid) { invalidUsagesFound = true continue } if (unwrapSpecialUsages) { val specialUsage = unwrapSpecialUsageOrNull(usage) if (specialUsage != null) { createReplacer(specialUsage)?.invoke() continue } } //TODO: keep the import if we don't know how to replace some of the usages val importDirective = usage.getStrictParentOfType<KtImportDirective>() if (importDirective != null) { if (!importDirective.isAllUnder && importDirective.targetDescriptors().size == 1) { importsToDelete.add(importDirective) } continue } createReplacer(usage)?.invoke()?.parent?.parent?.parent?.reformatted(true) } catch (e: Throwable) { if (e is ControlFlowException) throw e LOG.error(e) } } return !invalidUsagesFound } fun unwrapSpecialUsageOrNull( usage: KtReferenceExpression ): KtSimpleNameExpression? { if (usage !is KtSimpleNameExpression) return null when (val usageParent = usage.parent) { is KtCallableReferenceExpression -> { if (usageParent.callableReference != usage) return null val (name, descriptor) = usage.nameAndDescriptor return ConvertReferenceToLambdaIntention.applyTo(usageParent)?.let { findNewUsage(it, name, descriptor) } } is KtCallElement -> { for (valueArgument in usageParent.valueArguments.asReversed()) { val callableReferenceExpression = valueArgument.getArgumentExpression() as? KtCallableReferenceExpression ?: continue ConvertReferenceToLambdaIntention.applyTo(callableReferenceExpression) } val lambdaExpressions = usageParent.valueArguments.mapNotNull { it.getArgumentExpression() as? KtLambdaExpression } if (lambdaExpressions.isEmpty()) return null val (name, descriptor) = usage.nameAndDescriptor val grandParent = usageParent.parent for (lambdaExpression in lambdaExpressions) { val functionDescriptor = lambdaExpression.functionLiteral.resolveToDescriptorIfAny() as? FunctionDescriptor ?: continue if (functionDescriptor.valueParameters.isNotEmpty()) { SpecifyExplicitLambdaSignatureIntention.applyTo(lambdaExpression) } } return grandParent.safeAs<KtElement>()?.let { findNewUsage(it, name, descriptor) } } } return null } private val KtSimpleNameExpression.nameAndDescriptor get() = getReferencedName() to resolveToCall()?.candidateDescriptor private fun findNewUsage( element: KtElement, targetName: String?, targetDescriptor: DeclarationDescriptor? ): KtSimpleNameExpression? = element.findDescendantOfType { it.getReferencedName() == targetName && compareDescriptors(it.project, targetDescriptor, it.resolveToCall()?.candidateDescriptor) }
apache-2.0
27e76baa9dc6a864e6224f61d6f46cc1
40.968912
158
0.701605
5.425318
false
false
false
false
zbeboy/ISY
src/main/java/top/zbeboy/isy/web/platform/common/UsersMethodControllerCommon.kt
1
4435
package top.zbeboy.isy.web.platform.common import org.springframework.stereotype.Component import org.springframework.util.ObjectUtils import org.springframework.util.StringUtils import top.zbeboy.isy.config.Workbook import top.zbeboy.isy.service.cache.CacheManageService import top.zbeboy.isy.service.data.StaffService import top.zbeboy.isy.service.data.StudentService import top.zbeboy.isy.service.platform.UsersKeyService import top.zbeboy.isy.service.platform.UsersService import top.zbeboy.isy.service.platform.UsersUniqueInfoService import top.zbeboy.isy.service.system.AuthoritiesService import top.zbeboy.isy.web.util.AjaxUtils import top.zbeboy.isy.web.util.SmallPropsUtils import javax.annotation.Resource /** * Created by zbeboy 2017-12-18 . **/ @Component open class UsersMethodControllerCommon { @Resource open lateinit var usersService: UsersService @Resource open lateinit var authoritiesService: AuthoritiesService @Resource open lateinit var cacheManageService: CacheManageService @Resource open lateinit var studentService: StudentService @Resource open lateinit var staffService: StaffService @Resource open lateinit var usersKeyService: UsersKeyService @Resource open lateinit var usersUniqueInfoService: UsersUniqueInfoService /** * 更新用户状态 * * @param userIds ids * @param enabled 状态 * @return true 成功 false 失败 */ fun usersUpdateEnabled(userIds: String, enabled: Byte?): AjaxUtils<*> { if (StringUtils.hasLength(userIds)) { usersService.updateEnabled(SmallPropsUtils.StringIdsToStringList(userIds), enabled) return AjaxUtils.of<Any>().success().msg("注销用户成功") } return AjaxUtils.of<Any>().fail().msg("注销用户失败") } /** * 删除无角色关联的用户 * * @param userIds 用户账号 * @return true 成功 false 失败 */ fun deleteUsers(userIds: String): AjaxUtils<*> { val ajaxUtils = AjaxUtils.of<Any>() if (StringUtils.hasLength(userIds)) { val ids = SmallPropsUtils.StringIdsToStringList(userIds) loop@ for (id in ids) { val authoritiesRecords = authoritiesService.findByUsername(id) if (!ObjectUtils.isEmpty(authoritiesRecords) && !authoritiesRecords.isEmpty()) { ajaxUtils.fail().msg("用户'$id'存在角色关联,无法删除") break } else { val users = usersService.findByUsername(id) if (!ObjectUtils.isEmpty(users)) { val usersType = cacheManageService.findByUsersTypeId(users!!.usersTypeId) when (usersType.usersTypeName) { Workbook.STUDENT_USERS_TYPE // 学生 -> { studentService.deleteByUsername(id) usersService.deleteById(id) usersKeyService.deleteByUsername(id) cacheManageService.deleteUsersKey(id) usersUniqueInfoService.deleteByUsername(id) ajaxUtils.success().msg("删除用户成功") } Workbook.STAFF_USERS_TYPE // 教职工 -> { staffService.deleteByUsername(id) usersService.deleteById(id) usersKeyService.deleteByUsername(id) cacheManageService.deleteUsersKey(id) usersUniqueInfoService.deleteByUsername(id) ajaxUtils.success().msg("删除用户成功") } else -> { ajaxUtils.fail().msg("未获取到用户'$id'类型") break@loop } } } else { ajaxUtils.fail().msg("未查询到用户'$id'") break } } } } else { ajaxUtils.fail().msg("用户账号为空") } return ajaxUtils } }
mit
e7b779f321ba8337fb19414c1126c09f
36.298246
97
0.563867
5.152727
false
false
false
false
paplorinc/intellij-community
java/java-impl/src/com/intellij/codeInsight/intention/impl/JavaElementActionsFactory.kt
1
5765
// 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.codeInsight.intention.impl import com.intellij.codeInsight.daemon.impl.quickfix.ModifierFix import com.intellij.codeInsight.intention.IntentionAction import com.intellij.lang.java.JavaLanguage import com.intellij.lang.java.actions.* import com.intellij.lang.jvm.* import com.intellij.lang.jvm.actions.* import com.intellij.lang.jvm.types.JvmType import com.intellij.openapi.components.ServiceManager import com.intellij.openapi.editor.Editor import com.intellij.openapi.project.Project import com.intellij.psi.* import com.intellij.psi.util.PsiUtil import java.util.* class JavaElementActionsFactory : JvmElementActionsFactory() { private val renderer = JavaElementRenderer.getInstance() override fun createChangeModifierActions(target: JvmModifiersOwner, request: MemberRequest.Modifier): List<IntentionAction> { return with(request) { val declaration = target as PsiModifierListOwner if (declaration.language != JavaLanguage.INSTANCE) return@with emptyList() listOf(ModifierFix(declaration, renderer.render(modifier), shouldPresent, false)) } } override fun createChangeModifierActions(target: JvmModifiersOwner, request: ChangeModifierRequest): List<IntentionAction> { val declaration = target as PsiModifierListOwner if (declaration.language != JavaLanguage.INSTANCE) return emptyList() val fix = object : ModifierFix(declaration, renderer.render(request.modifier), request.shouldBePresent(), true) { override fun isAvailable(): Boolean = request.isValid && super.isAvailable() override fun isAvailable(project: Project, file: PsiFile, editor: Editor?, startElement: PsiElement, endElement: PsiElement): Boolean = request.isValid && super.isAvailable(project, file, editor, startElement, endElement) } return listOf(fix) } override fun createAddAnnotationActions(target: JvmModifiersOwner, request: AnnotationRequest): List<IntentionAction> { val declaration = target as? PsiModifierListOwner ?: return emptyList() if (declaration.language != JavaLanguage.INSTANCE) return emptyList() return listOf(CreateAnnotationAction(declaration, request)) } override fun createAddFieldActions(targetClass: JvmClass, request: CreateFieldRequest): List<IntentionAction> { val javaClass = targetClass.toJavaClassOrNull() ?: return emptyList() val constantRequested = request.isConstant || javaClass.isInterface || request.modifiers.containsAll(constantModifiers) val result = ArrayList<IntentionAction>() if (constantRequested || request.fieldName.toUpperCase(Locale.ENGLISH) == request.fieldName) { result += CreateConstantAction(javaClass, request) } if (!constantRequested) { result += CreateFieldAction(javaClass, request) } if (canCreateEnumConstant(javaClass, request)) { result += CreateEnumConstantAction(javaClass, request) } return result } override fun createAddMethodActions(targetClass: JvmClass, request: CreateMethodRequest): List<IntentionAction> { val javaClass = targetClass.toJavaClassOrNull() ?: return emptyList() val requestedModifiers = request.modifiers val staticMethodRequested = JvmModifier.STATIC in requestedModifiers if (staticMethodRequested) { // static method in interfaces are allowed starting with Java 8 if (javaClass.isInterface && !PsiUtil.isLanguageLevel8OrHigher(javaClass)) return emptyList() // static methods in inner classes are disallowed JLS §8.1.3 if (javaClass.containingClass != null && !javaClass.hasModifierProperty(PsiModifier.STATIC)) return emptyList() } val result = ArrayList<IntentionAction>() result += CreateMethodAction(javaClass, request, false) if (!staticMethodRequested && javaClass.hasModifierProperty(PsiModifier.ABSTRACT) && !javaClass.isInterface) { result += CreateMethodAction(javaClass, request, true) } if (!javaClass.isInterface) { result += CreatePropertyAction(javaClass, request) result += CreateGetterWithFieldAction(javaClass, request) result += CreateSetterWithFieldAction(javaClass, request) } return result } override fun createAddConstructorActions(targetClass: JvmClass, request: CreateConstructorRequest): List<IntentionAction> { val javaClass = targetClass.toJavaClassOrNull() ?: return emptyList() return listOf(CreateConstructorAction(javaClass, request)) } override fun createChangeParametersActions(target: JvmMethod, request: ChangeParametersRequest): List<IntentionAction> { val psiMethod = target as? PsiMethod ?: return emptyList() if (psiMethod.language != JavaLanguage.INSTANCE) return emptyList() if (request.expectedParameters.any { it.expectedTypes.isEmpty() || it.semanticNames.isEmpty() }) return emptyList() return listOf(ChangeMethodParameters(psiMethod, request)) } } class JavaElementRenderer { companion object { @JvmStatic fun getInstance(): JavaElementRenderer { return ServiceManager.getService(JavaElementRenderer::class.java) } } fun render(visibilityModifiers: List<JvmModifier>): String = visibilityModifiers.joinToString(" ") { render(it) } fun render(jvmType: JvmType): String = (jvmType as PsiType).canonicalText fun render(jvmAnnotation: JvmAnnotation): String = "@" + (jvmAnnotation as PsiAnnotation).qualifiedName!! @PsiModifier.ModifierConstant fun render(modifier: JvmModifier): String = modifier.toPsiModifier() }
apache-2.0
ded1b6f4620d927c65d0ce84da38897f
43.338462
140
0.745836
5.087379
false
false
false
false
auricgoldfinger/Memento-Namedays
android_mobile/src/main/java/com/alexstyl/specialdates/dailyreminder/actions/PersonActionsActivity.kt
3
3383
package com.alexstyl.specialdates.dailyreminder.actions import android.content.Context import android.content.Intent import android.content.Intent.ACTION_CALL import android.content.Intent.ACTION_SENDTO import android.os.Bundle import android.support.v7.widget.LinearLayoutManager import android.support.v7.widget.RecyclerView import com.alexstyl.specialdates.CrashAndErrorTracker import com.alexstyl.specialdates.MementoApplication import com.alexstyl.specialdates.R import com.alexstyl.specialdates.contact.Contact import com.alexstyl.specialdates.contact.ContactIntentExtractor import com.alexstyl.specialdates.person.AndroidContactActions import com.alexstyl.specialdates.person.ContactActionsAdapter import com.alexstyl.specialdates.ui.base.ThemedMementoActivity import javax.inject.Inject class PersonActionsActivity : ThemedMementoActivity() { var presenter: ContactActionsPresenter? = null @Inject set var extractor: ContactIntentExtractor? = null @Inject set var errorTracker: CrashAndErrorTracker? = null @Inject set var view: ContactActionsView? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_call) (application as MementoApplication).applicationModule.inject(this) val recyclerView = findViewById<RecyclerView>(R.id.actions_list)!! recyclerView.layoutManager = LinearLayoutManager(this, RecyclerView.VERTICAL, false) val adapter = ContactActionsAdapter { it.action.run() finish() } recyclerView.adapter = adapter val contact = extractor?.getContactExtra(intent) if (contact != null && contact.isPresent) { view = AndroidContactActionsView(contact.get(), adapter) } else { errorTracker?.track(RuntimeException("Tried to load the actions for a contact from $intent")) finish() } } override fun onStart() { super.onStart() if (view != null) { startPresentingInto(view!!) } } private fun startPresentingInto(view: ContactActionsView) { val action = AndroidContactActions(this) when { intent.action == ACTION_CALL -> presenter?.startPresentingCallsInto(view, action) intent.action == ACTION_SENDTO -> presenter?.startPresentingMessagingInto(view, action) else -> { } } } override fun onStop() { super.onStop() presenter?.stopPresenting() } companion object { fun buildCallIntentFor(context: Context, contact: Contact): Intent { return Intent(context, PersonActionsActivity::class.java) .setAction(ACTION_CALL) .putContactExtra(contact) } fun buildSendIntentFor(context: Context, contact: Contact): Intent { return Intent(context, PersonActionsActivity::class.java) .setAction(ACTION_SENDTO) .putContactExtra(contact) } private fun Intent.putContactExtra(contact: Contact): Intent { return putExtra(ContactIntentExtractor.EXTRA_CONTACT_ID, contact.contactID) .putExtra(ContactIntentExtractor.EXTRA_CONTACT_SOURCE, contact.source) } } }
mit
d9752793ea7a57e689381d953308db8d
34.239583
105
0.684304
4.910015
false
false
false
false
lisuperhong/ModularityApp
CommonBusiness/src/main/java/com/company/commonbusiness/base/BaseApplication.kt
1
2994
package com.company.commonbusiness.base import android.app.Activity import android.app.Application import android.content.Context import android.content.Intent import android.os.Bundle import android.support.multidex.MultiDex import android.support.multidex.MultiDexApplication import com.alibaba.android.arouter.launcher.ARouter import com.company.commonbusiness.util.Utils import com.crland.wuye.commonbusiness.BuildConfig import com.orhanobut.logger.AndroidLogAdapter import com.orhanobut.logger.Logger import kotlin.properties.Delegates /** * @author 李昭鸿 * @desc: Application基类,主要做各种初始化工作,主app和各module都应继承该基类 * @date Created on 2017/8/5 16:57 * @github: https://github.com/lisuperhong */ open class BaseApplication : MultiDexApplication() { companion object { // 以下属性应用于整个应用程序,合理利用资源,减少资源浪费 var context: Context by Delegates.notNull() private set var instance: BaseApplication? = null private set } override fun attachBaseContext(context: Context) { super.attachBaseContext(context) MultiDex.install(this) } override fun onCreate() { super.onCreate() instance = this context = applicationContext // 初始化ARouter ARouter.init(this) // 尽可能早,推荐在Application中初始化 if (BuildConfig.DEBUG) { ARouter.openLog() // 打印日志 ARouter.openDebug() // 开启调试模式(如果在InstantRun模式下运行,必须开启调试模式!线上版本需要关闭,否则有安全风险) } // 初始化Logger Logger.addLogAdapter(AndroidLogAdapter()) // 初始化工具类 Utils.init(this) registerActivityLifecycleCallbacks(callbacks) } private val callbacks = object : Application.ActivityLifecycleCallbacks { override fun onActivityCreated(activity: Activity, bundle: Bundle?) { Logger.d(activity.componentName.className + " onCreate") } override fun onActivityStarted(activity: Activity) { } override fun onActivityResumed(activity: Activity) { Logger.d(activity.componentName.className + " onResume") } override fun onActivityPaused(activity: Activity) { } override fun onActivityStopped(activity: Activity) { } override fun onActivitySaveInstanceState(activity: Activity, bundle: Bundle) { } override fun onActivityDestroyed(activity: Activity) { Logger.d(activity.componentName.className + " onDestroy") } } /** * 重启当前应用 */ fun restart() { val intent = context.packageManager.getLaunchIntentForPackage(context.packageName) intent!!.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP) context.startActivity(intent) } }
apache-2.0
d83b73c0e28ae4b89925c67c979d8191
26.4
90
0.678102
4.376997
false
false
false
false
paplorinc/intellij-community
platform/lang-impl/src/com/intellij/execution/compound/CompoundRunConfiguration.kt
3
7757
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.execution.compound import com.intellij.execution.* import com.intellij.execution.configurations.* import com.intellij.execution.executors.DefaultRunExecutor import com.intellij.execution.impl.ExecutionManagerImpl import com.intellij.execution.impl.RunManagerImpl import com.intellij.execution.impl.compareTypesForUi import com.intellij.execution.runners.ExecutionEnvironment import com.intellij.execution.runners.ExecutionUtil import com.intellij.icons.AllIcons import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.components.BaseState import com.intellij.openapi.project.Project import com.intellij.util.xmlb.annotations.Property import com.intellij.util.xmlb.annotations.Tag import com.intellij.util.xmlb.annotations.XCollection import org.jetbrains.annotations.TestOnly import java.util.* import java.util.concurrent.atomic.AtomicBoolean import javax.swing.Icon import kotlin.collections.LinkedHashMap data class SettingsAndEffectiveTarget(val configuration: RunConfiguration, val target: ExecutionTarget) class CompoundRunConfiguration @JvmOverloads constructor(name: String? = null, project: Project, factory: ConfigurationFactory = runConfigurationType<CompoundRunConfigurationType>()) : RunConfigurationMinimalBase<CompoundRunConfigurationOptions>(name, factory, project), RunnerIconProvider, WithoutOwnBeforeRunSteps, Cloneable { companion object { @JvmField internal val COMPARATOR: Comparator<RunConfiguration> = Comparator { o1, o2 -> val compareTypeResult = compareTypesForUi(o1.type, o2.type) if (compareTypeResult == 0) o1.name.compareTo(o2.name) else compareTypeResult } } // have to use RunConfiguration instead of RunnerAndConfigurationSettings because setConfigurations (called from CompoundRunConfigurationSettingsEditor.applyEditorTo) cannot use RunnerAndConfigurationSettings private var sortedConfigurationsWithTargets = LinkedHashMap<RunConfiguration, ExecutionTarget?>() private var isInitialized = false private val isDirty = AtomicBoolean() fun getConfigurationsWithTargets(runManager: RunManagerImpl): Map<RunConfiguration, ExecutionTarget?> { initIfNeed(runManager) return sortedConfigurationsWithTargets } fun setConfigurationsWithTargets(value: Map<RunConfiguration, ExecutionTarget?>) { markInitialized() sortedConfigurationsWithTargets.clear() sortedConfigurationsWithTargets.putAll(value) isDirty.set(true) } fun setConfigurationsWithoutTargets(value: Collection<RunConfiguration>) { setConfigurationsWithTargets(value.associate { it to null }) } private fun initIfNeed(runManager: RunManagerImpl) { if (isInitialized) { return } doInit(runManager) } @TestOnly fun doInit(runManager: RunManagerImpl) { sortedConfigurationsWithTargets.clear() val targetManager = ExecutionTargetManager.getInstance(project) as ExecutionTargetManagerImpl for (item in options.configurations) { val type = item.type val name = item.name if (type == null || name == null) { continue } val settings = runManager.findConfigurationByTypeAndName(type, name)?.configuration if (settings != null && settings !== this) { val target = item.targetId?.let { targetManager.findTargetByIdFor(settings, it) } sortedConfigurationsWithTargets.put(settings, target) } } markInitialized() } private fun markInitialized() { isInitialized = true } override fun getConfigurationEditor() = CompoundRunConfigurationSettingsEditor(project) override fun checkConfiguration() { if (sortedConfigurationsWithTargets.isEmpty()) { throw RuntimeConfigurationException("There is nothing to run") } if (ExecutionTargetManager.getInstance(project).getTargetsFor(this).isEmpty()) { throw RuntimeConfigurationException("No suitable targets to run on; please choose a target for each configuration") } } override fun getState(executor: Executor, environment: ExecutionEnvironment): RunProfileState? { try { checkConfiguration() } catch (e: RuntimeConfigurationException) { throw ExecutionException(e.message) } promptUserToUseRunDashboard(project, getConfigurationsWithEffectiveRunTargets().map { it.configuration.type }) return RunProfileState { _, _ -> ApplicationManager.getApplication().invokeLater { val groupId = ExecutionEnvironment.getNextUnusedExecutionId() for ((configuration, target) in getConfigurationsWithEffectiveRunTargets()) { val settings = RunManagerImpl.getInstanceImpl(project).findSettings(configuration) ?: continue ExecutionUtil.runConfiguration(settings, executor, target, groupId) } } null } } fun getConfigurationsWithEffectiveRunTargets(): List<SettingsAndEffectiveTarget> { val activeTarget = ExecutionTargetManager.getActiveTarget(project) val defaultTarget = DefaultExecutionTarget.INSTANCE return sortedConfigurationsWithTargets.mapNotNull { (configuration, specifiedTarget) -> val effectiveTarget = specifiedTarget ?: if (ExecutionTargetManager.canRun(configuration, activeTarget)) activeTarget else defaultTarget SettingsAndEffectiveTarget(configuration, effectiveTarget) } } override fun getState(): CompoundRunConfigurationOptions? { if (isDirty.compareAndSet(true, false)) { options.configurations = sortedConfigurationsWithTargets.mapTo(ArrayList()) { entry -> TypeNameTarget(entry.key.type.id, entry.key.name, entry.value?.id) } } return options } override fun loadState(state: CompoundRunConfigurationOptions) { super.loadState(state) sortedConfigurationsWithTargets.clear() isInitialized = false } override fun clone(): RunConfiguration { val clone = CompoundRunConfiguration(name, project, factory) clone.loadState(state!!) return clone } override fun getExecutorIcon(configuration: RunConfiguration, executor: Executor): Icon { return when { DefaultRunExecutor.EXECUTOR_ID == executor.id && hasRunningSingletons() -> AllIcons.Actions.Restart else -> executor.icon } } private fun hasRunningSingletons(): Boolean { val project = project if (project.isDisposed) { return false } return ExecutionManagerImpl.getInstance(project).getRunningDescriptors { s -> val manager = RunManagerImpl.getInstanceImpl(project) for ((configuration, _) in sortedConfigurationsWithTargets) { if (configuration is CompoundRunConfiguration && configuration.hasRunningSingletons()) { return@getRunningDescriptors true } val settings = manager.findSettings(configuration) if (settings != null && !settings.configuration.isAllowRunningInParallel && configuration == s.configuration) { return@getRunningDescriptors true } } false }.isNotEmpty() } } class CompoundRunConfigurationOptions : BaseState() { @get:XCollection() @get:Property(surroundWithTag = false) var configurations by list<TypeNameTarget>() } @Tag("toRun") @Property(style = Property.Style.ATTRIBUTE) class TypeNameTarget() : BaseState() { constructor(type: String, name: String, targetId: String?) : this() { this.type = type this.name = name this.targetId = targetId } var type by string() var name by string() var targetId by string() }
apache-2.0
78f56078bd324d595ee46b955ce08629
35.767773
210
0.742168
5.116755
false
true
false
false
google/intellij-community
platform/platform-impl/src/com/intellij/ui/layout/ComponentPredicate.kt
3
4862
// 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.ui.layout import com.intellij.openapi.Disposable import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.options.advanced.AdvancedSettings import com.intellij.openapi.options.advanced.AdvancedSettingsChangeListener import com.intellij.ui.DocumentAdapter import javax.swing.AbstractButton import javax.swing.JComboBox import javax.swing.JTextField import javax.swing.event.DocumentEvent import javax.swing.text.JTextComponent abstract class ComponentPredicate : () -> Boolean { abstract fun addListener(listener: (Boolean) -> Unit) } val AbstractButton.selected: ComponentPredicate get() = object : ComponentPredicate() { override fun invoke(): Boolean = isSelected override fun addListener(listener: (Boolean) -> Unit) { addChangeListener { listener(isSelected) } } } fun <T> JComboBox<T>.selectedValueMatches(predicate: (T?) -> Boolean): ComponentPredicate { return ComboBoxPredicate(this, predicate) } class ComboBoxPredicate<T>(private val comboBox: JComboBox<T>, private val predicate: (T?) -> Boolean) : ComponentPredicate() { override fun invoke(): Boolean = predicate(comboBox.selectedItem as T?) override fun addListener(listener: (Boolean) -> Unit) { comboBox.addActionListener { listener(predicate(comboBox.selectedItem as T?)) } } } /** * Used for editable ComboBoxes */ fun JComboBox<*>.editableValueMatches(predicate: (Any?) -> Boolean): ComponentPredicate { return EditableComboBoxPredicate(this, predicate) } private class EditableComboBoxPredicate(private val comboBox: JComboBox<*>, private val predicate: (Any?) -> Boolean) : ComponentPredicate() { override fun invoke(): Boolean = predicate(comboBox.editor.item) override fun addListener(listener: (Boolean) -> Unit) { val textField = comboBox.editor.editorComponent as JTextField textField.document.addDocumentListener(object : DocumentAdapter() { override fun textChanged(e: DocumentEvent) { listener(invoke()) } }) } } fun JTextComponent.enteredTextSatisfies(predicate: (String) -> Boolean): ComponentPredicate { return TextComponentPredicate(this, predicate) } private class TextComponentPredicate(private val component: JTextComponent, private val predicate: (String) -> Boolean) : ComponentPredicate() { override fun invoke(): Boolean = predicate(component.text) override fun addListener(listener: (Boolean) -> Unit) { component.document.addDocumentListener(object : DocumentAdapter() { override fun textChanged(e: DocumentEvent) { listener(invoke()) } }) } } fun <T> JComboBox<T>.selectedValueIs(value: T): ComponentPredicate = selectedValueMatches { it == value } infix fun ComponentPredicate.and(other: ComponentPredicate): ComponentPredicate { return AndPredicate(this, other) } infix fun ComponentPredicate.or(other: ComponentPredicate): ComponentPredicate { return OrPredicate(this, other) } fun ComponentPredicate.not() : ComponentPredicate { return NotPredicate(this) } private class AndPredicate(private val lhs: ComponentPredicate, private val rhs: ComponentPredicate) : ComponentPredicate() { override fun invoke(): Boolean = lhs.invoke() && rhs.invoke() override fun addListener(listener: (Boolean) -> Unit) { val andListener: (Boolean) -> Unit = { listener(lhs.invoke() && rhs.invoke()) } lhs.addListener(andListener) rhs.addListener(andListener) } } private class OrPredicate(private val lhs: ComponentPredicate, private val rhs: ComponentPredicate) : ComponentPredicate() { override fun invoke(): Boolean = lhs.invoke() || rhs.invoke() override fun addListener(listener: (Boolean) -> Unit) { val andListener: (Boolean) -> Unit = { listener(lhs.invoke() || rhs.invoke()) } lhs.addListener(andListener) rhs.addListener(andListener) } } private class NotPredicate(private val that: ComponentPredicate) : ComponentPredicate() { override fun invoke(): Boolean = !that.invoke() override fun addListener(listener: (Boolean) -> Unit) { val notListener: (Boolean) -> Unit = { listener(!that.invoke()) } that.addListener(notListener) } } class AdvancedSettingsPredicate(val id: String, val disposable: Disposable) : ComponentPredicate() { override fun addListener(listener: (Boolean) -> Unit) { ApplicationManager.getApplication().messageBus.connect(disposable) .subscribe(AdvancedSettingsChangeListener.TOPIC, object : AdvancedSettingsChangeListener { override fun advancedSettingChanged(id: String, oldValue: Any, newValue: Any) { listener(invoke()) } }) } override fun invoke(): Boolean = AdvancedSettings.getBoolean(id) }
apache-2.0
df137459f673c8702a6e7b69d8e22209
36.122137
144
0.740436
4.578154
false
false
false
false
thomasgalvin/Featherfall
src/main/kotlin/galvin/ff/tools/AccountManager.kt
1
12970
package galvin.ff.tools import galvin.ff.* import galvin.ff.PadTo.paddedLayout import org.joda.time.format.DateTimeFormat import java.io.File import java.io.PrintStream import java.util.stream.Collectors class AccountManager{ fun printShort( users: List<User>, out: PrintStream = System.out ){ val logins = createList( "Login" ) val legal = createList( "Legal Name" ) val active = createList( "Active" ) val locked = createList( "Locked" ) val roles = createList( "Roles" ) for( user in users ){ logins.add( user.login ) legal.add( user.sortName ) active.add( if(user.active) "Active" else "Inactive" ) locked.add( if(user.locked) "Locked" else "" ) roles.add( user.roles.stream().collect(Collectors.joining(", ")) ) } val table = paddedLayout( '-', logins, legal, active, locked, roles ) out.println(table) } fun printLong( users: List<User>, out: PrintStream = System.out ){ val dateTimeFormat = DateTimeFormat.forPattern("yyyy/MM/dd kk:mm") val text = StringBuilder() for( (index,user) in users.withIndex() ){ val created = dateTimeFormat.print(user.created) text.append( "Sort By Name: " ) text.append( user.sortName ) text.append("\n") text.append( "Login: " ) text.append( user.login ) text.append("\n") text.append( "Name: " ) text.append( user.name ) text.append("\n") text.append( "Display Name: " ) text.append( user.displayName ) text.append("\n") text.append( "Prepend to Name: " ) text.append( user.prependToName ) text.append("\n") text.append( "Append to Name: " ) text.append( user.appendToName ) text.append("\n") text.append( "Credential: " ) text.append( user.credential ) text.append("\n") text.append( "Serial Number: " ) text.append( user.serialNumber ) text.append("\n") text.append( "Distinguished Name: " ) text.append( user.distinguishedName ) text.append("\n") text.append( "Agency: " ) text.append( user.agency ) text.append("\n") text.append( "Country Code: " ) text.append( user.countryCode ) text.append("\n") text.append( "Citizenship: " ) text.append( user.citizenship ) text.append("\n") text.append( "Created On: " ) text.append( created ) text.append("\n") text.append( "Active: " ) text.append( if(user.active){ "Active" } else{ "Inactive" } ) text.append("\n") text.append( "Locked: " ) text.append( if(user.locked){ "Locked" } else{ "Unlocked" } ) text.append("\n") text.append( "Contact Info:\n" ) for( contact in user.contact ){ text.append( " - " ) text.append( contact.contact ) if( !isBlank(contact.description) ) { text.append(" (") text.append(contact.description) text.append(")") } if( contact.primary ){ text.append(" * Primary") } text.append("\n") } text.append( "Roles:\n" ) for( roleName in user.roles){ text.append( " - " ) text.append( roleName ) text.append("\n") } if( index < users.size-1) { text.append("------------------------------\n") } } out.println( text.toString().trim() ) } fun retrieveAllUsers(options: AccountManagerOptions): List<User>{ val userDB = connectUserDB(options) return userDB.retrieveUsers() } // locked / unlocked users fun retrieveLockedUsers(options: AccountManagerOptions): List<User>{ val userDB = connectUserDB(options) return userDB.retrieveUsersByLocked(true) } fun retrieveUnlockedUsers(options: AccountManagerOptions): List<User>{ val userDB = connectUserDB(options) return userDB.retrieveUsersByLocked(false) } fun lockUser( options: AccountManagerOptions, login: String ){ val userDB = connectUserDB(options) val uuid = userDB.retrieveUuidByLogin(login) if( uuid != null && !isBlank(uuid) ){ userDB.setLocked(uuid, true) if( options.verbose ){ println("User locked: $login") } } else{ println("No such user: $login") } } fun unlockUser( options: AccountManagerOptions, login: String ){ val userDB = connectUserDB(options) val uuid = userDB.retrieveUuidByLogin(login) if( uuid != null && !isBlank(uuid) ){ userDB.setLocked(uuid, false) if( options.verbose ){ println("User locked: $login") } } else{ println("No such user: $login") } } // active / inactive users fun retrieveInactiveUsers(options: AccountManagerOptions): List<User>{ val userDB = connectUserDB(options) return userDB.retrieveUsersByActive(false) } fun retrieveActiveUsers(options: AccountManagerOptions): List<User>{ val userDB = connectUserDB(options) return userDB.retrieveUsersByActive(true) } fun deactivateUser( options: AccountManagerOptions, login: String ){ val userDB = connectUserDB(options) val uuid = userDB.retrieveUuidByLogin(login) if( uuid != null && !isBlank(uuid) ){ userDB.setActive(uuid, false) if( options.verbose ){ println("User deactivated: $login") } } else{ println("No such user: $login") } } fun activateUser( options: AccountManagerOptions, login: String ){ val userDB = connectUserDB(options) val uuid = userDB.retrieveUuidByLogin(login) if( uuid != null && !isBlank(uuid) ){ userDB.setActive(uuid, true) if( options.verbose ){ println("User deactivated: $login") } } else{ println("No such user: $login") } } // passwords and credentials fun updatePassword( options: AccountManagerOptions, login: String, plainTextPassword: String ){ val userDB = connectUserDB(options) userDB.setPasswordByLogin(login, plainTextPassword) } fun updateCredentials( options: AccountManagerOptions, login: String, credential: String? = null, serialNumber: String? = null, distinguishedName: String? = null, countryCode: String? = null, citizenship: String? = null ){ val userDB = connectUserDB(options) val uuid = userDB.retrieveUuidByLogin(login) if( uuid != null && !isBlank(uuid) ){ val current = userDB.retrieveCredentials(uuid) if( current != null ) { val updateCredentials = CertificateData( credential = elseIfNull(credential, current.credential), serialNumber = elseIfNull(serialNumber, current.serialNumber), distinguishedName = elseIfNull(distinguishedName, current.distinguishedName), countryCode = elseIfNull(countryCode, current.countryCode), citizenship = elseIfNull(citizenship, current.citizenship) ) userDB.updateCredentials(uuid, updateCredentials) } else{ println("No such user: $login") } } else{ println("No such user: $login") } } fun updateCredentialsFromFile( options: AccountManagerOptions, login: String, file: File ){ if( !file.exists() || !file.canRead() ){ println("Unable to read file: ${file.absolutePath}") return } val x509 = loadCertificateFromFile(file) val certData = parsePKI(x509) val userDB = connectUserDB(options) val uuid = userDB.retrieveUuidByLogin(login) if( uuid != null && !isBlank(uuid) ){ userDB.updateCredentials(uuid, certData) } else{ println("No such user: $login") } } // roles fun printRoles( options: AccountManagerOptions, out: PrintStream = System.out ){ val userDB = connectUserDB(options) val roles = userDB.listRoles() val text = StringBuilder() for( role in roles ){ text.append( role.name ) text.append( " (" ) text.append( if(role.active){ "Active" } else{ "Inactive" } ) text.append( ")\n" ) for( permission in role.permissions ){ text.append(" - ") text.append( permission ) text.append("\n") } } out.println( text.toString().trim() ) } fun createRoles( options: AccountManagerOptions, roleNames: List<String>, permissions: List<String> ){ val userDB = connectUserDB(options) for( roleName in roleNames ) { val role = userDB.retrieveRole(roleName) if( role == null ){ userDB.storeRole( Role( name = roleName, permissions = permissions ) ) } } } fun addPermissions(options: AccountManagerOptions, roleNames: List<String>, addedPermissions: List<String> ){ val userDB = connectUserDB(options) for( roleName in roleNames ) { val role = userDB.retrieveRole(roleName) if( role != null ){ val newPermissions = mutableListOf<String>() newPermissions.addAll( role.permissions ) for( permission in addedPermissions){ if( !newPermissions.contains(permission) ){ newPermissions.add(permission) } } userDB.storeRole( role.copy(permissions = newPermissions) ) } } } fun removePermissions(options: AccountManagerOptions, roleNames: List<String>, deletedPermissions: List<String> ){ val userDB = connectUserDB(options) for( roleName in roleNames ) { val role = userDB.retrieveRole(roleName) if( role != null ){ val newPermissions = mutableListOf<String>() for( permission in role.permissions ){ if( !deletedPermissions.contains(permission) ){ newPermissions.add(permission) } } userDB.storeRole( role.copy(permissions = newPermissions) ) } } } fun activateRoles(options: AccountManagerOptions, roleNames: List<String> ){ val userDB = connectUserDB(options) for( roleName in roleNames ) { userDB.activate(roleName) } } fun deactivateRoles(options: AccountManagerOptions, roleNames: List<String> ){ val userDB = connectUserDB(options) for( roleName in roleNames ) { userDB.deactivate(roleName) } } // // utilities // private fun connectUserDB(options: AccountManagerOptions): UserDB { if( options.userDB != null ) return options.userDB if( !isBlank(options.sqlite) ){ val file = File(options.sqlite) return UserDB.SQLite(maxConnections = options.maxConnections, databaseFile = file ) } else if( !isBlank(options.psql) ){ return UserDB.PostgreSQL(maxConnections = options.maxConnections, connectionURL = options.psql, username = options.dbuser, password = options.dbpass ) } throw Exception("Unable to connect to user DB: no connection criteria specified") } } data class AccountManagerOptions( val verbose: Boolean = false, val showHelp: Boolean = false, val showManual: Boolean = false, val maxConnections: Int = 10, val timeout: Long = 60_000, val userDB: UserDB? = null, val sqlite: String = "", val psql: String = "", val dbuser: String? = null, val dbpass: String? = null )
apache-2.0
6d63aa1827f9266f868e3c64eeedaa79
32.778646
162
0.540864
4.627185
false
false
false
false
google/intellij-community
plugins/kotlin/project-wizard/core/src/org/jetbrains/kotlin/tools/projectWizard/Versions.kt
4
1898
/* * Copyright 2010-2020 JetBrains s.r.o. and Kotlin Programming Language contributors. * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.tools.projectWizard import org.jetbrains.kotlin.tools.projectWizard.settings.version.Version @Suppress("ClassName", "SpellCheckingInspection") object Versions { val KOTLIN = version("1.5.0") // used as fallback version val GRADLE = version("7.4.2") val KTOR = version("2.0.2") val JUNIT = version("4.13.2") val JUNIT5 = version("5.8.2") val JETBRAINS_COMPOSE = version("1.1.1") val KOTLIN_VERSION_FOR_COMPOSE = version("1.6.10") val GRADLE_VERSION_FOR_COMPOSE = version("7.4.2") object COMPOSE { val ANDROID_ACTIVITY_COMPOSE = version("1.4.0") } object ANDROID { val ANDROID_MATERIAL = version("1.5.0") val ANDROIDX_APPCOMPAT = version("1.4.1") val ANDROIDX_CONSTRAINTLAYOUT = version("2.1.3") val ANDROIDX_KTX = version("1.7.0") } object KOTLINX { val KOTLINX_HTML = version("0.7.2") val KOTLINX_NODEJS: Version = version("0.0.7") } object JS_WRAPPERS { val KOTLIN_REACT = wrapperVersion("18.2.0") val KOTLIN_REACT_DOM = KOTLIN_REACT val KOTLIN_EMOTION = wrapperVersion("11.9.3") val KOTLIN_REACT_ROUTER_DOM = wrapperVersion("6.3.0") val KOTLIN_REDUX = wrapperVersion("4.1.2") val KOTLIN_REACT_REDUX = wrapperVersion("7.2.6") private fun wrapperVersion(version: String): Version = version("$version-pre.346") } object GRADLE_PLUGINS { val ANDROID = version("7.0.4") } object MAVEN_PLUGINS { val SUREFIRE = version("2.22.2") val FAILSAFE = SUREFIRE } } private fun version(version: String) = Version.fromString(version)
apache-2.0
9f4b87bbfefd021c10456ebdc1206369
30.633333
115
0.641728
3.554307
false
false
false
false
JetBrains/intellij-community
platform/workspaceModel/storage/src/com/intellij/workspaceModel/storage/bridgeEntities/dependencies.kt
1
5643
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.workspaceModel.storage.bridgeEntities import com.intellij.workspaceModel.storage.* import com.intellij.workspaceModel.storage.EntitySource import com.intellij.workspaceModel.storage.GeneratedCodeApiVersion import com.intellij.workspaceModel.storage.MutableEntityStorage import com.intellij.workspaceModel.storage.WorkspaceEntity import com.intellij.workspaceModel.storage.impl.containers.toMutableWorkspaceList import com.intellij.workspaceModel.storage.url.VirtualFileUrl import kotlin.jvm.JvmName import kotlin.jvm.JvmOverloads import kotlin.jvm.JvmStatic import org.jetbrains.deft.ObjBuilder import org.jetbrains.deft.Type import org.jetbrains.deft.annotations.Child import java.io.Serializable interface LibraryEntity : WorkspaceEntityWithSymbolicId { val name: String val tableId: LibraryTableId val roots: List<LibraryRoot> val excludedRoots: List<@Child ExcludeUrlEntity> @Child val sdk: SdkEntity? @Child val libraryProperties: LibraryPropertiesEntity? @Child val libraryFilesPackagingElement: LibraryFilesPackagingElementEntity? override val symbolicId: LibraryId get() = LibraryId(name, tableId) //region generated code @GeneratedCodeApiVersion(1) interface Builder : LibraryEntity, WorkspaceEntity.Builder<LibraryEntity>, ObjBuilder<LibraryEntity> { override var entitySource: EntitySource override var name: String override var tableId: LibraryTableId override var roots: MutableList<LibraryRoot> override var excludedRoots: List<ExcludeUrlEntity> override var sdk: SdkEntity? override var libraryProperties: LibraryPropertiesEntity? override var libraryFilesPackagingElement: LibraryFilesPackagingElementEntity? } companion object : Type<LibraryEntity, Builder>() { @JvmOverloads @JvmStatic @JvmName("create") operator fun invoke(name: String, tableId: LibraryTableId, roots: List<LibraryRoot>, entitySource: EntitySource, init: (Builder.() -> Unit)? = null): LibraryEntity { val builder = builder() builder.name = name builder.tableId = tableId builder.roots = roots.toMutableWorkspaceList() builder.entitySource = entitySource init?.invoke(builder) return builder } } //endregion } //region generated code fun MutableEntityStorage.modifyEntity(entity: LibraryEntity, modification: LibraryEntity.Builder.() -> Unit) = modifyEntity( LibraryEntity.Builder::class.java, entity, modification) var LibraryEntity.Builder.externalSystemId: @Child LibraryExternalSystemIdEntity? by WorkspaceEntity.extension() //endregion val ExcludeUrlEntity.library: LibraryEntity? by WorkspaceEntity.extension() interface LibraryPropertiesEntity : WorkspaceEntity { val library: LibraryEntity val libraryType: String val propertiesXmlTag: String? //region generated code @GeneratedCodeApiVersion(1) interface Builder : LibraryPropertiesEntity, WorkspaceEntity.Builder<LibraryPropertiesEntity>, ObjBuilder<LibraryPropertiesEntity> { override var entitySource: EntitySource override var library: LibraryEntity override var libraryType: String override var propertiesXmlTag: String? } companion object : Type<LibraryPropertiesEntity, Builder>() { @JvmOverloads @JvmStatic @JvmName("create") operator fun invoke(libraryType: String, entitySource: EntitySource, init: (Builder.() -> Unit)? = null): LibraryPropertiesEntity { val builder = builder() builder.libraryType = libraryType builder.entitySource = entitySource init?.invoke(builder) return builder } } //endregion } //region generated code fun MutableEntityStorage.modifyEntity(entity: LibraryPropertiesEntity, modification: LibraryPropertiesEntity.Builder.() -> Unit) = modifyEntity( LibraryPropertiesEntity.Builder::class.java, entity, modification) //endregion interface SdkEntity : WorkspaceEntity { val library: LibraryEntity val homeUrl: VirtualFileUrl //region generated code @GeneratedCodeApiVersion(1) interface Builder : SdkEntity, WorkspaceEntity.Builder<SdkEntity>, ObjBuilder<SdkEntity> { override var entitySource: EntitySource override var library: LibraryEntity override var homeUrl: VirtualFileUrl } companion object : Type<SdkEntity, Builder>() { @JvmOverloads @JvmStatic @JvmName("create") operator fun invoke(homeUrl: VirtualFileUrl, entitySource: EntitySource, init: (Builder.() -> Unit)? = null): SdkEntity { val builder = builder() builder.homeUrl = homeUrl builder.entitySource = entitySource init?.invoke(builder) return builder } } //endregion } //region generated code fun MutableEntityStorage.modifyEntity(entity: SdkEntity, modification: SdkEntity.Builder.() -> Unit) = modifyEntity( SdkEntity.Builder::class.java, entity, modification) //endregion data class LibraryRootTypeId(val name: String) : Serializable { companion object { val COMPILED = LibraryRootTypeId("CLASSES") val SOURCES = LibraryRootTypeId("SOURCES") } } data class LibraryRoot( val url: VirtualFileUrl, val type: LibraryRootTypeId, val inclusionOptions: InclusionOptions = InclusionOptions.ROOT_ITSELF ) : Serializable { enum class InclusionOptions { ROOT_ITSELF, ARCHIVES_UNDER_ROOT, ARCHIVES_UNDER_ROOT_RECURSIVELY } }
apache-2.0
e43dba47493fd17b51afeb6f90ab6912
33.408537
135
0.745348
5.283708
false
false
false
false
allotria/intellij-community
plugins/github/src/org/jetbrains/plugins/github/pullrequest/action/GHPRSelectPullRequestForFileAction.kt
1
1768
// Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.plugins.github.pullrequest.action import com.intellij.icons.AllIcons import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.actionSystem.PlatformDataKeys import com.intellij.openapi.components.service import com.intellij.openapi.fileEditor.FileEditorManager import com.intellij.openapi.project.DumbAwareAction import org.jetbrains.plugins.github.i18n.GithubBundle import org.jetbrains.plugins.github.pullrequest.GHPRToolWindowController import org.jetbrains.plugins.github.pullrequest.GHPRVirtualFile import java.util.function.Supplier class GHPRSelectPullRequestForFileAction : DumbAwareAction(GithubBundle.messagePointer("pull.request.select.action"), Supplier<String?> { null }, AllIcons.General.Locate) { override fun update(e: AnActionEvent) { val project = e.project if (project == null) { e.presentation.isEnabled = false return } val files = FileEditorManager.getInstance(project).selectedFiles.filterIsInstance<GHPRVirtualFile>() if (files.isEmpty()) { e.presentation.isEnabled = false return } e.presentation.isEnabled = true } override fun actionPerformed(e: AnActionEvent) { val project = e.getRequiredData(PlatformDataKeys.PROJECT) val file = FileEditorManager.getInstance(project).selectedFiles.filterIsInstance<GHPRVirtualFile>().first() project.service<GHPRToolWindowController>().activate { it.componentController?.viewPullRequest(file.pullRequest) } } }
apache-2.0
d762b93f6e57b2d2fd439605f8b863ed
41.119048
140
0.735294
4.911111
false
false
false
false
savekirk/FizzBuzzGame
app/src/main/java/com/savekirk/fizzbuzzgame/Data/GameDataRepository.kt
1
1106
package com.savekirk.fizzbuzzgame.Data import java.util.* object GameDataRepository : GameDataSource { var gameCache : Map<String, Int>? = null val SCORE = "score" val LIFE = "life" override fun getScore(callback: GameDataSource.GetScoreCallback) { if (gameCache().containsKey(SCORE)) { callback.onScoreLoaded(gameCache().get(SCORE)!!) } else { callback.onDataNotAvailable() } } override fun saveScore(score: Int) { gameCache().put(SCORE, score) } override fun getLives(callback: GameDataSource.GetLivesCallback) { if (gameCache().containsKey(LIFE)) { callback.onLivesLoaded(gameCache().get(LIFE)!!) } else { callback.onLivesNotAvailable() } } override fun saveLives(lives: Int) { gameCache().put(LIFE, lives) } private fun gameCache() : LinkedHashMap<String, Int> { return if (gameCache == null) { LinkedHashMap<String, Int>() } else { gameCache as LinkedHashMap<String, Int> } } }
mit
dd4cc09a532a3990f68dad7510e5f4d6
23.065217
70
0.597649
4.142322
false
false
false
false
marcelstoer/open-data-smn
src/main/kotlin/com/frightanic/smn/api/geojson/Feature.kt
1
812
package com.frightanic.smn.api.geojson import com.frightanic.smn.api.SmnRecord import com.frightanic.smn.api.Station /** * Representation of a single feature within a feature collection. */ @Suppress("MemberVisibilityCanBePrivate") class Feature(crs: CrsType, val properties: SmnRecord){ val type = "Feature" val geometry: Geometry = createGeometry(crs, properties.station) private fun createGeometry(crs: CrsType, station: Station?): Geometry { val coordinates: Array<Number> = if (crs === CrsType.WGS84){ // lat/lng are inverted according to GeoJSON spec: http://geojson.org/geojson-spec.html#id2 arrayOf(station!!.lng, station.lat) } else { arrayOf(station!!.ch1903X, station.ch1903Y) } return Geometry(coordinates) } }
mit
fb062a97ccd9b31a435b8902216e4a14
34.304348
103
0.689655
3.776744
false
false
false
false
zdary/intellij-community
plugins/groovy/src/org/jetbrains/plugins/groovy/intentions/style/inference/driver/closure/ClosureDriver.kt
12
8337
// Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.plugins.groovy.intentions.style.inference.driver.closure import com.intellij.psi.* import com.intellij.psi.impl.source.resolve.graphInference.constraints.ConstraintFormula import com.intellij.psi.search.GlobalSearchScope import com.intellij.psi.util.parentOfType import org.jetbrains.plugins.groovy.intentions.style.inference.* import org.jetbrains.plugins.groovy.intentions.style.inference.driver.* import org.jetbrains.plugins.groovy.intentions.style.inference.driver.BoundConstraint.ContainMarker.INHABIT import org.jetbrains.plugins.groovy.intentions.style.inference.driver.BoundConstraint.ContainMarker.UPPER import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrCall import org.jetbrains.plugins.groovy.lang.psi.api.statements.params.GrParameter import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.members.GrMethod class ClosureDriver private constructor(private val closureParameters: Map<GrParameter, ParameterizedClosure>, private val method: GrMethod, private val environment: SignatureInferenceEnvironment) : InferenceDriver { companion object { fun createFromMethod(method: GrMethod, virtualMethodPointer: SmartPsiElementPointer<GrMethod>, generator: NameGenerator, environment: SignatureInferenceEnvironment): InferenceDriver { val virtualMethod = virtualMethodPointer.element ?: return EmptyDriver val builder = ClosureParametersStorageBuilder(generator, virtualMethod) val visitedParameters = builder.extractClosuresFromOuterCalls(method, virtualMethod, environment.getAllCallsToMethod(virtualMethod)) virtualMethod.forEachParameterUsage { parameter, instructions -> if (!parameter.type.isClosureTypeDeep() || parameter in visitedParameters) { return@forEachParameterUsage } val callUsages = instructions.mapNotNull { it.element?.parentOfType<GrCall>() } if (!builder.extractClosuresFromCallInvocation(callUsages, parameter)) { builder.extractClosuresFromOtherMethodInvocations(callUsages, parameter) } } val closureParameters = builder.build() return if (closureParameters.isEmpty()) EmptyDriver else ClosureDriver(closureParameters, virtualMethod, environment) } } private fun produceParameterizedClosure(parameterMapping: Map<GrParameter, GrParameter>, closureParameter: ParameterizedClosure, substitutor: PsiSubstitutor, manager: ParameterizationManager): ParameterizedClosure { val newParameter = parameterMapping.getValue(closureParameter.parameter) val newTypes = mutableListOf<PsiType>() val newTypeParameters = mutableListOf<PsiTypeParameter>() for (directInnerParameter in closureParameter.typeParameters) { val substitutedType = substitutor.substitute(directInnerParameter)?.forceWildcardsAsTypeArguments() val generifiedType = substitutedType ?: getJavaLangObject(closureParameter.parameter) val (createdType, createdTypeParameters) = manager.createDeeplyParameterizedType(generifiedType) newTypes.add(createdType) newTypeParameters.addAll(createdTypeParameters) } return ParameterizedClosure(newParameter, newTypeParameters, closureParameter.closureArguments, newTypes) } override fun createParameterizedDriver(manager: ParameterizationManager, targetMethod: GrMethod, substitutor: PsiSubstitutor): InferenceDriver { val parameterMapping = setUpParameterMapping(method, targetMethod) val newClosureParameters = mutableMapOf<GrParameter, ParameterizedClosure>() val typeParameterList = targetMethod.typeParameterList ?: return EmptyDriver for ((_, closureParameter) in closureParameters) { val newClosureParameter = produceParameterizedClosure(parameterMapping, closureParameter, substitutor, manager) newClosureParameter.typeParameters.forEach { typeParameterList.add(it) } newClosureParameters[newClosureParameter.parameter] = newClosureParameter } return ClosureDriver(newClosureParameters, targetMethod, environment) } override fun typeParameters(): Collection<PsiTypeParameter> { return closureParameters.flatMap { it.value.typeParameters } } override fun collectOuterConstraints(): Collection<ConstraintFormula> { val constraintCollector = mutableListOf<ConstraintFormula>() method.forEachParameterUsage { parameter, instructions -> if (parameter in closureParameters) { constraintCollector.addAll(extractConstraintsFromClosureInvocations(closureParameters.getValue(parameter), instructions)) } } return constraintCollector } private fun collectDeepClosureArgumentsConstraints(): List<TypeUsageInformation> { return closureParameters.values.flatMap { parameter -> parameter.closureArguments.map { closureBlock -> val newMethod = createMethodFromClosureBlock(closureBlock, parameter, method.typeParameterList!!) val emptyEnvironment = SignatureInferenceEnvironment(method, GlobalSearchScope.EMPTY_SCOPE, environment.signatureInferenceContext, true) val commonDriver = CommonDriver.createDirectlyFromMethod(newMethod, emptyEnvironment) val usageInformation = commonDriver.collectInnerConstraints() val typeParameterMapping = newMethod.typeParameters.zip(method.typeParameters).toMap() val shiftedRequiredTypes = usageInformation.requiredClassTypes.map { (param, list) -> typeParameterMapping.getValue(param) to list.map { if (it.marker == UPPER) BoundConstraint(it.type, INHABIT) else it } }.toMap() val newUsageInformation = usageInformation.run { TypeUsageInformation(shiftedRequiredTypes, constraints, dependentTypes.map { typeParameterMapping.getValue(it) }.toSet(), constrainingExpressions) } newUsageInformation } } } private fun collectClosureInvocationConstraints(): TypeUsageInformation { val builder = TypeUsageInformationBuilder(method, environment.signatureInferenceContext) method.forEachParameterUsage { parameter, instructions -> if (parameter in closureParameters.keys) { analyzeClosureUsages(closureParameters.getValue(parameter), instructions, builder) } } return builder.build() } override fun collectInnerConstraints(): TypeUsageInformation { val closureBodyAnalysisResult = TypeUsageInformation.merge(collectDeepClosureArgumentsConstraints()) val closureInvocationConstraints = collectClosureInvocationConstraints() return closureInvocationConstraints + closureBodyAnalysisResult } override fun instantiate(resultMethod: GrMethod) { val mapping = setUpParameterMapping(method, resultMethod) for ((_, closureParameter) in closureParameters) { val createdAnnotations = closureParameter.renderTypes(method.parameterList) for ((parameter, anno) in createdAnnotations) { if (anno.isEmpty()) { continue } mapping.getValue(parameter).modifierList.addAnnotation(anno.substring(1)) } } } override fun acceptTypeVisitor(visitor: PsiTypeMapper, resultMethod: GrMethod): InferenceDriver { val mapping = setUpParameterMapping(method, resultMethod) val parameterizedClosureCollector = mutableListOf<Pair<GrParameter, ParameterizedClosure>>() for ((parameter, closure) in closureParameters) { val newTypes = closure.types.map { it.accept(visitor) } val newParameter = mapping.getValue(parameter) val newParameterizedClosure = ParameterizedClosure(newParameter, closure.typeParameters, closure.closureArguments, newTypes, closure.delegatesToCombiner) parameterizedClosureCollector.add(newParameter to newParameterizedClosure) } return ClosureDriver(parameterizedClosureCollector.toMap(), resultMethod, environment) } }
apache-2.0
d3b2ddfa1c8636c03925c6473affe664
53.490196
159
0.748111
5.659878
false
false
false
false
leafclick/intellij-community
platform/vcs-impl/src/com/intellij/vcs/commit/ToggleAmendCommitOption.kt
1
1329
// 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.vcs.commit import com.intellij.ide.ui.UISettings import com.intellij.openapi.Disposable import com.intellij.openapi.vcs.CheckinProjectPanel import com.intellij.ui.components.JBCheckBox import org.jetbrains.annotations.ApiStatus import java.awt.event.KeyEvent @ApiStatus.Internal class ToggleAmendCommitOption(commitPanel: CheckinProjectPanel, parent: Disposable) : JBCheckBox("Amend commit") { private val amendCommitHandler = commitPanel.commitWorkflowHandler.amendCommitHandler init { isFocusable = UISettings.shadowInstance.disableMnemonicsInControls mnemonic = KeyEvent.VK_M toolTipText = "Merge this commit with the previous one" addActionListener { amendCommitHandler.isAmendCommitMode = isSelected } amendCommitHandler.addAmendCommitModeListener(object : AmendCommitModeListener { override fun amendCommitModeToggled() { isSelected = amendCommitHandler.isAmendCommitMode } }, parent) } companion object { @JvmStatic fun isAmendCommitOptionSupported(commitPanel: CheckinProjectPanel, amendAware: AmendCommitAware) = !commitPanel.isNonModalCommit && amendAware.isAmendCommitSupported() } }
apache-2.0
e39d65828b1736f54ae6ca98ceb4b0ae
39.30303
140
0.795335
4.977528
false
false
false
false
zdary/intellij-community
platform/platform-tests/testSrc/com/intellij/openapi/roots/impl/indexing/IndexableFilesBeneathExcludedDirectoryTest.kt
3
5476
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.openapi.roots.impl.indexing import com.intellij.openapi.project.Project import com.intellij.openapi.roots.AdditionalLibraryRootsProvider import com.intellij.openapi.roots.ModuleRootModificationUtil import com.intellij.openapi.roots.OrderRootType import com.intellij.openapi.roots.SyntheticLibrary import com.intellij.openapi.vfs.VirtualFile import com.intellij.testFramework.RunsInEdt import com.intellij.util.indexing.IndexableSetContributor import org.junit.Test @RunsInEdt class IndexableFilesBeneathExcludedDirectoryTest : IndexableFilesBaseTest() { @Test fun `excluded files must not be indexed`() { projectModelRule.createJavaModule("moduleName") { content("contentRoot") { excluded("excluded") { file("ExcludedFile.java", "class ExcludedFile {}") } } } assertIndexableFiles() } @Test fun `source root beneath excluded directory must be indexed`() { lateinit var aJava: FileSpec projectModelRule.createJavaModule("moduleName") { content("contentRoot") { excluded("excluded") { source("sources") { aJava = file("A.java", "class A {}") } } } } assertIndexableFiles(aJava.file) } @Test fun `files of a Library residing beneath module excluded directory must be indexed`() { lateinit var libraryRoot: DirectorySpec lateinit var libraryClass: FileSpec val module = projectModelRule.createJavaModule("moduleName") { content("contentRoot") { excluded("excluded") { // Must be indexed despite being excluded by module. libraryRoot = dir("library") { libraryClass = file("LibraryClass.java", "class LibraryClass {}") } } } } projectModelRule.addModuleLevelLibrary(module, "libraryName") { model -> model.addRoot(libraryRoot.file, OrderRootType.CLASSES) } assertIndexableFiles(libraryClass.file) } @Test fun `files of an SDK residing beneath module excluded directory must be indexed`() { lateinit var sdkRoot: DirectorySpec lateinit var sdkClass: FileSpec val module = projectModelRule.createJavaModule("moduleName") { content("contentRoot") { excluded("excluded") { // Must be indexed despite being excluded by module. sdkRoot = dir("sdk") { sdkClass = file("SdkClass.java", "class SdkClass {}") } } } } val sdk = projectModelRule.addSdk(projectModelRule.createSdk("sdkName")) { sdkModificator -> sdkModificator.addRoot(sdkRoot.file, OrderRootType.CLASSES) } ModuleRootModificationUtil.setModuleSdk(module, sdk) assertIndexableFiles(sdkClass.file) } // Roots provided by AdditionalLibraryRootsProvider are considered library source roots, // and they must be indexed even if they reside beneath excluded directories. @Test fun `files of AdditionalLibraryRootsProvider residing beneath module excluded directory must be indexed`() { lateinit var targetSource: FileSpec lateinit var targetSources: DirectorySpec lateinit var targetBinary: FileSpec lateinit var targetBinaries: DirectorySpec projectModelRule.createJavaModule("moduleName") { content("contentRoot") { excluded("excluded") { targetSources = moduleDir("sources") { targetSource = file("TargetSource.java", "class TargetSource {}") } targetBinaries = moduleDir("binaries") { targetBinary = file("TargetBinary.java", "class TargetBinary {}") } } } } val additionalLibraryRootsProvider = object : AdditionalLibraryRootsProvider() { override fun getAdditionalProjectLibraries(project: Project) = listOf( SyntheticLibrary.newImmutableLibrary( listOf(targetSources.file), listOf(targetBinaries.file), emptySet(), null ) ) } maskAdditionalLibraryRootsProviders(additionalLibraryRootsProvider) assertIndexableFiles(targetSource.file, targetBinary.file) } @Test fun `files of IndexableSetContributor residing beneath module excluded directory must not be indexed`() { lateinit var additionalRoots: DirectorySpec lateinit var additionalProjectRoots: DirectorySpec lateinit var projectFile: FileSpec lateinit var appFile: FileSpec projectModelRule.createJavaModule("moduleName") { // Must not be indexed despite being provided by IndexableSetContributor. content("contentRoot") { excluded("excluded") { additionalProjectRoots = dir("additionalProjectRoots") { projectFile = file("ExcludedFile.java", "class ExcludedFile {}") } additionalRoots = dir("additionalRoots") { appFile = file("ExcludedFile.java", "class ExcludedFile {}") } } } } val contributor = object : IndexableSetContributor() { override fun getAdditionalProjectRootsToIndex(project: Project): Set<VirtualFile> = setOf(additionalProjectRoots.file) override fun getAdditionalRootsToIndex(): Set<VirtualFile> = setOf(additionalRoots.file) } maskIndexableSetContributors(contributor) assertIndexableFiles(projectFile.file, appFile.file) } }
apache-2.0
2132cc7b844cfb1aca9095f81e139d06
33.446541
140
0.689189
5.235182
false
true
false
false
aconsuegra/algorithms-playground
src/main/kotlin/me/consuegra/algorithms/KSymmetricBinaryTree.kt
1
1649
package me.consuegra.algorithms import me.consuegra.datastructure.KBinaryTreeNode /** * Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center). * Example : * * 1 * / \ * 2 2 * / \ / \ * 3 4 4 3 * * The above binary tree is symmetric. * But the following is not: * * 1 * / \ * 2 2 * \ \ * 3 3 * */ class KSymmetricBinaryTree { fun isSymmetric(treeNode: KBinaryTreeNode<Int>): Boolean { val preOrder = preOrder(treeNode) val postOrder = postOrder(treeNode) if (preOrder.length != postOrder.length) { return false } var j = postOrder.length - 1 for (c in preOrder) { if (c != postOrder[j]) { return false } j-- } return true } private fun preOrder(treeNode: KBinaryTreeNode<Int>?): String = preOrder(treeNode, StringBuilder()).toString() private fun preOrder(treeNode: KBinaryTreeNode<Int>?, acc: StringBuilder): StringBuilder { treeNode?.let { acc.append(treeNode.data) preOrder(treeNode.left, acc) preOrder(treeNode.right, acc) } return acc } private fun postOrder(treeNode: KBinaryTreeNode<Int>?): String = postOrder(treeNode, StringBuilder()).toString() private fun postOrder(treeNode: KBinaryTreeNode<Int>?, acc: StringBuilder): StringBuilder { treeNode?.let { postOrder(treeNode.left, acc) postOrder(treeNode.right, acc) acc.append(treeNode.data) } return acc } }
mit
924d03fc62f01af693aff465d3d60fc0
23.61194
116
0.578532
3.983092
false
false
false
false
smmribeiro/intellij-community
platform/platform-util-io/src/com/intellij/execution/process/SynchronizedProcessOutput.kt
12
1731
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.execution.process import com.intellij.openapi.diagnostic.Logger import java.util.concurrent.CompletableFuture import java.util.concurrent.CompletionStage class SynchronizedProcessOutput : ProcessOutput() { private val finished = CompletableFuture<SynchronizedProcessOutput>() fun onFinished(): CompletionStage<SynchronizedProcessOutput> = finished.copy() // @formatter:off override fun appendStdout(text: String?) = synchronized(this) { super.appendStdout(text) } override fun appendStderr(text: String?) = synchronized(this) { super.appendStderr(text) } override fun getStdout(): String = synchronized(this) { super.getStdout() } override fun getStderr(): String = synchronized(this) { super.getStderr() } override fun checkSuccess(logger: Logger) = synchronized(this) { super.checkSuccess(logger) } override fun getExitCode(): Int = synchronized(this) { super.getExitCode() } override fun isExitCodeSet(): Boolean = synchronized(this) { super.isExitCodeSet() } override fun isTimeout(): Boolean = synchronized(this) { super.isTimeout() } override fun isCancelled(): Boolean = synchronized(this) { super.isCancelled() } override fun setExitCode(exitCode: Int) = finish { super.setExitCode(exitCode) } override fun setTimeout() = finish { super.setTimeout() } override fun setCancelled() = finish { super.setCancelled() } // @formatter:on private fun finish(block: () -> Unit) { synchronized(this) { block() } finished.complete(this) } }
apache-2.0
660bdd1029d382a79d0653da2290db85
48.485714
140
0.714038
4.371212
false
false
false
false
google/intellij-community
plugins/kotlin/j2k/idea/src/org/jetbrains/kotlin/idea/j2k/J2kPostProcessor.kt
2
7445
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.j2k import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.application.ModalityState import com.intellij.openapi.diagnostic.ControlFlowException import com.intellij.openapi.editor.RangeMarker import com.intellij.openapi.util.Disposer import com.intellij.openapi.util.TextRange import com.intellij.psi.PsiElement import com.intellij.psi.PsiRecursiveElementVisitor import com.intellij.psi.codeStyle.CodeStyleManager import com.intellij.refactoring.suggested.range import kotlinx.coroutines.runBlocking import kotlinx.coroutines.withContext import org.jetbrains.kotlin.idea.caches.resolve.getResolutionFacade import org.jetbrains.kotlin.idea.caches.resolve.resolveImportReference import org.jetbrains.kotlin.idea.core.KotlinPluginDisposable import org.jetbrains.kotlin.idea.core.util.EDT import org.jetbrains.kotlin.idea.util.ImportInsertHelper import org.jetbrains.kotlin.idea.util.application.runReadAction import org.jetbrains.kotlin.idea.util.application.runWriteAction import org.jetbrains.kotlin.j2k.* import org.jetbrains.kotlin.name.FqName import org.jetbrains.kotlin.psi.KtElement import org.jetbrains.kotlin.psi.KtFile import org.jetbrains.kotlin.psi.psiUtil.elementsInRange import org.jetbrains.kotlin.resolve.diagnostics.Diagnostics import java.util.* class J2kPostProcessor(private val formatCode: Boolean) : PostProcessor { override val phasesCount: Int = 1 override fun insertImport(file: KtFile, fqName: FqName) { ApplicationManager.getApplication().invokeAndWait { runWriteAction { val descriptors = file.resolveImportReference(fqName) descriptors.firstOrNull()?.let { ImportInsertHelper.getInstance(file.project).importDescriptor(file, it) } } } } private enum class RangeFilterResult { SKIP, GO_INSIDE, PROCESS } override fun doAdditionalProcessing( target: JKPostProcessingTarget, converterContext: ConverterContext?, onPhaseChanged: ((Int, String) -> Unit)? ) { val (file, rangeMarker) = when (target) { is JKPieceOfCodePostProcessingTarget -> target.file to target.rangeMarker is JKMultipleFilesPostProcessingTarget -> target.files.single() to null } val disposable = KotlinPluginDisposable.getInstance(file.project) runBlocking(EDT.ModalityStateElement(ModalityState.defaultModalityState())) { do { var modificationStamp: Long? = file.modificationStamp val elementToActions: List<ActionData> = run { while (!Disposer.isDisposed(disposable)) { try { return@run runReadAction { collectAvailableActions(file, rangeMarker) } } catch (e: Exception) { if (e is ControlFlowException) continue throw e } } emptyList() } withContext(EDT) { for ((element, action, _, writeActionNeeded) in elementToActions) { if (element.isValid) { if (writeActionNeeded) { runWriteAction { action() } } else { action() } } else { modificationStamp = null } } } if (modificationStamp == file.modificationStamp) break } while (elementToActions.isNotEmpty()) if (formatCode) { withContext(EDT) { runWriteAction { val codeStyleManager = CodeStyleManager.getInstance(file.project) if (rangeMarker != null) { if (rangeMarker.isValid) { codeStyleManager.reformatRange(file, rangeMarker.startOffset, rangeMarker.endOffset) } } else { codeStyleManager.reformat(file) } Unit } } } } } private data class ActionData(val element: KtElement, val action: () -> Unit, val priority: Int, val writeActionNeeded: Boolean) private fun collectAvailableActions(file: KtFile, rangeMarker: RangeMarker?): List<ActionData> { val diagnostics = analyzeFileRange(file, rangeMarker) val availableActions = ArrayList<ActionData>() file.accept(object : PsiRecursiveElementVisitor() { override fun visitElement(element: PsiElement) { if (element is KtElement) { val rangeResult = rangeFilter(element, rangeMarker) if (rangeResult == RangeFilterResult.SKIP) return super.visitElement(element) if (rangeResult == RangeFilterResult.PROCESS) { val postProcessingRegistrar = J2KPostProcessingRegistrar.instance postProcessingRegistrar.processings.forEach { processing -> val action = processing.createAction(element, diagnostics) if (action != null) { availableActions.add( ActionData( element, action, postProcessingRegistrar.priority(processing), processing.writeActionNeeded ) ) } } } } } }) availableActions.sortBy { it.priority } return availableActions } private fun analyzeFileRange(file: KtFile, rangeMarker: RangeMarker?): Diagnostics { val range = rangeMarker?.range val elements = if (range == null) listOf(file) else file.elementsInRange(range).filterIsInstance<KtElement>() return if (elements.isNotEmpty()) file.getResolutionFacade().analyzeWithAllCompilerChecks(elements).bindingContext.diagnostics else Diagnostics.EMPTY } private fun rangeFilter(element: PsiElement, rangeMarker: RangeMarker?): RangeFilterResult { if (rangeMarker == null) return RangeFilterResult.PROCESS if (!rangeMarker.isValid) return RangeFilterResult.SKIP val range = TextRange(rangeMarker.startOffset, rangeMarker.endOffset) val elementRange = element.textRange return when { range.contains(elementRange) -> RangeFilterResult.PROCESS range.intersects(elementRange) -> RangeFilterResult.GO_INSIDE else -> RangeFilterResult.SKIP } } }
apache-2.0
eead6ffd1fd697232fe29caa4b7382c8
40.592179
158
0.579987
5.989541
false
false
false
false
anitawoodruff/habitica-android
Habitica/src/main/java/com/habitrpg/android/habitica/models/user/User.kt
1
7104
package com.habitrpg.android.habitica.models.user import com.google.gson.annotations.SerializedName import com.habitrpg.android.habitica.models.* import com.habitrpg.android.habitica.models.invitations.Invitations import com.habitrpg.android.habitica.models.social.ChallengeMembership import com.habitrpg.android.habitica.models.social.UserParty import com.habitrpg.android.habitica.models.tasks.TaskList import com.habitrpg.android.habitica.models.tasks.TasksOrder import io.realm.RealmList import io.realm.RealmObject import io.realm.annotations.Ignore import io.realm.annotations.PrimaryKey import java.util.* open class User : RealmObject(), Avatar, VersionedObject { @Ignore var tasks: TaskList? = null @PrimaryKey @SerializedName("_id") var id: String? = null set(id) { field = id if (stats?.isManaged != true) { stats?.userId = id } if (inbox?.isManaged != true) { this.inbox?.userId = id } if (preferences?.isManaged != true) { preferences?.userId = id } if (this.profile?.isManaged != true) { this.profile?.userId = id } if (this.items?.isManaged != true) { this.items?.userId = id } if (this.authentication?.isManaged != true) { this.authentication?.userId = id } if (this.flags?.isManaged != true) { this.flags?.userId = id } if (this.contributor?.isManaged != true) { this.contributor?.userId = id } if (this.invitations?.isManaged != true) { this.invitations?.userId = id } for (test in abTests ?: emptyList<ABTest>()) { test.userID = id } } @SerializedName("_v") override var versionNumber: Int = 0 var balance: Double = 0.toDouble() private var stats: Stats? = null var inbox: Inbox? = null set(inbox) { field = inbox if (inbox != null && this.id != null && !inbox.isManaged) { inbox.userId = this.id } } private var preferences: Preferences? = null var profile: Profile? = null set(profile) { field = profile if (profile != null && this.id != null && !profile.isManaged) { profile.userId = this.id } } var party: UserParty? = null set(party) { field = party if (party != null && this.id != null && !party.isManaged) { party.userId = this.id } } var items: Items? = null set(items) { field = items if (items != null && this.id != null && !items.isManaged) { items.userId = this.id } } @SerializedName("auth") var authentication: Authentication? = null set(authentication) { field = authentication if (authentication != null && this.id != null) { authentication.userId = this.id } } var flags: Flags? = null set(flags) { field = flags if (flags != null && this.id != null) { flags.userId = this.id } } var contributor: ContributorInfo? = null set(contributor) { field = contributor if (contributor != null && this.id != null && !contributor.isManaged) { contributor.userId = this.id } } var backer: Backer? = null set(backer) { field = backer if (backer != null && this.id != null && !backer.isManaged) { backer.id = this.id } } var invitations: Invitations? = null set(invitations) { field = invitations if (invitations != null && this.id != null && !invitations.isManaged) { invitations.userId = this.id } } var tags = RealmList<Tag>() var questAchievements = RealmList<QuestAchievement>() set(value) { field = value field.forEach { it.userID = id } } @Ignore var pushDevices: List<PushDevice>? = null var purchased: Purchases? = null set(purchased) { field = purchased if (purchased != null && this.id != null) { purchased.userId = this.id } } @Ignore var tasksOrder: TasksOrder? = null var challenges: RealmList<ChallengeMembership>? = null var abTests: RealmList<ABTest>? = null var lastCron: Date? = null var needsCron: Boolean = false var loginIncentives: Int = 0 var streakCount: Int = 0 val petsFoundCount: Int get() = this.items?.pets?.size ?: 0 val mountsTamedCount: Int get() = this.items?.mounts?.size ?: 0 val contributorColor: Int get() = this.contributor?.contributorColor ?: android.R.color.black val username: String? get() = authentication?.localAuthentication?.username val formattedUsername: String? get() = if (username != null) "@$username" else null override fun getPreferences(): Preferences? { return preferences } fun setPreferences(preferences: Preferences?) { this.preferences = preferences if (preferences != null && this.id != null && !preferences.isManaged) { preferences.userId = this.id } } override fun getStats(): Stats? { return stats } fun setStats(stats: Stats?) { this.stats = stats if (stats != null && this.id != null && !stats.isManaged) { stats.userId = this.id } } override fun getGemCount(): Int { return (this.balance * 4).toInt() } override fun getHourglassCount(): Int { return purchased?.plan?.consecutive?.trinkets ?: 0 } override fun getCostume(): Outfit? { return items?.gear?.costume } override fun getEquipped(): Outfit? { return items?.gear?.equipped } override fun hasClass(): Boolean { return preferences?.disableClasses != true && flags?.classSelected == true && stats?.habitClass?.isNotEmpty() == true } override fun getCurrentMount(): String? { return items?.currentMount ?: "" } override fun getCurrentPet(): String? { return items?.currentPet ?: "" } override fun getSleep(): Boolean { return preferences?.sleep ?: false } fun hasParty(): Boolean { return this.party?.id?.length ?: 0 > 0 } val isSubscribed: Boolean get() { val plan = purchased?.plan var isSubscribed = false if (plan != null) { if (plan.isActive) { isSubscribed = true } } return isSubscribed } }
gpl-3.0
c39a74327c81111980bfea8507d08aa5
28.477178
125
0.540681
4.607004
false
false
false
false
Flank/flank
flank-scripts/src/main/kotlin/flank/scripts/ops/github/CopyGitHubProperties.kt
1
3012
package flank.scripts.ops.github import com.github.kittinunf.result.getOrNull import com.github.kittinunf.result.map import com.github.kittinunf.result.onError import com.github.kittinunf.result.success import flank.scripts.data.github.getGitHubIssue import flank.scripts.data.github.getGitHubPullRequest import flank.scripts.data.github.getLabelsFromIssue import flank.scripts.data.github.objects.GithubPullRequest import flank.scripts.data.github.setAssigneesToPullRequest import flank.scripts.data.github.setLabelsToPullRequest import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.coroutineScope import kotlinx.coroutines.joinAll import kotlinx.coroutines.launch import kotlinx.coroutines.runBlocking fun copyGitHubProperties(githubToken: String, prNumber: Int) = runBlocking { getGitHubPullRequest(githubToken, prNumber) .onError { println("Could not copy properties, because of ${it.message}") } .success { pullRequest -> val issueNumber = pullRequest.findReferenceNumber() checkNotNull(issueNumber) { "Reference issue not found on description and branch" } println("Found referenced issue #$issueNumber") launch(Dispatchers.IO) { copyGitHubProperties( githubToken, issueNumber, prNumber ) } } } internal fun GithubPullRequest.findReferenceNumber() = (tryGetReferenceNumberFromBody() ?: tryGetReferenceNumberFromBranch()) ?.trim() ?.replace("#", "") ?.toInt() private fun GithubPullRequest.tryGetReferenceNumberFromBody() = bodyReferenceRegex.find(body)?.value private fun GithubPullRequest.tryGetReferenceNumberFromBranch() = branchReferenceRegex.find(head?.ref.orEmpty())?.value private val bodyReferenceRegex = "#\\d+\\s".toRegex() private val branchReferenceRegex = "#\\d+".toRegex() private suspend fun copyGitHubProperties( githubToken: String, baseIssueNumber: Int, prNumber: Int ) = coroutineScope { listOf( launch { copyAssignees(githubToken, baseIssueNumber, prNumber) }, launch { copyLabels(githubToken, baseIssueNumber, prNumber) }, ).joinAll() } internal suspend fun copyAssignees(githubToken: String, baseIssueNumber: Int, pullRequestNumber: Int) { getGitHubIssue(githubToken, baseIssueNumber) .onError { println("Could not copy assignees because of ${it.message}") } .map { githubIssue -> githubIssue.assignees.map { it.login } } .getOrNull() ?.let { setAssigneesToPullRequest(githubToken, pullRequestNumber, it) } } internal suspend fun copyLabels(githubToken: String, issueNumber: Int, pullRequestNumber: Int) { getLabelsFromIssue(githubToken, issueNumber) .onError { println("Could not copy labels because of ${it.message}") } .map { it.map { label -> label.name } } .getOrNull() ?.run { setLabelsToPullRequest(githubToken, pullRequestNumber, this) } }
apache-2.0
ed37ecdee3f0b61f1d13ac0e4446c675
39.702703
119
0.719124
4.591463
false
false
false
false
Pattonville-App-Development-Team/Android-App
app/src/main/java/org/pattonvillecs/pattonvilleapp/viewmodel/calendar/events/CalendarEventsFragmentViewModel.kt
1
2958
/* * Copyright (C) 2017 - 2018 Mitchell Skaggs, Keturah Gadson, Ethan Holtgrieve, Nathan Skelton, Pattonville School District * * 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 org.pattonvillecs.pattonvilleapp.viewmodel.calendar.events import android.app.Application import android.arch.lifecycle.AndroidViewModel import android.arch.lifecycle.LiveData import android.arch.lifecycle.MutableLiveData import android.view.View import org.pattonvillecs.pattonvilleapp.preferences.PreferenceUtils import org.pattonvillecs.pattonvilleapp.service.model.DataSource import org.pattonvillecs.pattonvilleapp.service.model.calendar.event.PinnableCalendarEvent import org.pattonvillecs.pattonvilleapp.service.repository.calendar.CalendarRepository import org.pattonvillecs.pattonvilleapp.view.ui.calendar.DateHeader import org.pattonvillecs.pattonvilleapp.view.ui.calendar.PinnableCalendarEventItem import org.pattonvillecs.pattonvilleapp.view.ui.calendar.map import org.pattonvillecs.pattonvilleapp.view.ui.calendar.switchMap import org.pattonvillecs.pattonvilleapp.viewmodel.app import org.threeten.bp.LocalDate /** * This class is a ViewModel for a FlexibleAdapter that derives its source from a set of DataSources. * * @since 1.2.0 * @author Mitchell Skaggs */ class CalendarEventsFragmentViewModel(application: Application) : AndroidViewModel(application) { lateinit var calendarRepository: CalendarRepository private val _searchText: MutableLiveData<String> = MutableLiveData() val searchText: LiveData<String> = _searchText private val selectedDataSources: LiveData<Set<DataSource>> = PreferenceUtils.getSelectedSchoolsLiveData(app) private val events: LiveData<List<PinnableCalendarEvent>> by lazy { selectedDataSources.switchMap { calendarRepository.getEventsByDataSource(it.toList()) } } val eventItems: LiveData<List<PinnableCalendarEventItem>> by lazy { events.map { val headerMap = mutableMapOf<LocalDate, DateHeader>() it.map { PinnableCalendarEventItem(it, headerMap.getOrPut(it.calendarEvent.startDate, { DateHeader(it.calendarEvent.startDate) })) } } } fun setSearchText(text: String) { _searchText.value = text } val backgroundTextVisibility: LiveData<Int> by lazy { eventItems.map { if (it.isEmpty()) View.VISIBLE else View.INVISIBLE } } }
gpl-3.0
297c417fbe0c9dfa73acef854f5fa223
45.234375
161
0.78668
4.57187
false
false
false
false
vanniktech/lint-rules
lint-rules-android-lint/src/test/java/com/vanniktech/lintrules/android/InvalidStringDetectorTest.kt
1
6551
@file:Suppress("UnstableApiUsage") // We know that Lint APIs aren't final. package com.vanniktech.lintrules.android import com.android.tools.lint.checks.infrastructure.TestFiles.xml import com.android.tools.lint.checks.infrastructure.TestLintTask.lint import org.junit.Test class InvalidStringDetectorTest { @Test fun validString() { lint() .files( xml( "res/values/strings.xml", """ <resources> <string name="my_string">My string</string> </resources> """, ).indented(), ) .issues(ISSUE_INVALID_STRING) .run() .expectClean() } @Test fun stringContainingNewLine() { lint() .files( xml( "res/values/strings.xml", """ <resources> <string name="my_string">My string" </string> </resources> """, ).indented(), ) .issues(ISSUE_INVALID_STRING) .run() .expect( """ |res/values/strings.xml:2: Warning: Text contains new line. [InvalidString] | <string name="my_string">My string" | ^ |0 errors, 1 warnings """.trimMargin(), ) .expectFixDiffs( """ |Fix for res/values/strings.xml line 1: Fix it: |@@ -2 +2 |- <string name="my_string">My string" |- </string> |+ <string name="my_string">My string"</string> """.trimMargin(), ) } @Test fun trailingWhitespaceAtEndString() { lint() .files( xml( "res/values/strings.xml", """ <resources> <string name="my_string">My string </string> </resources> """, ).indented(), ) .issues(ISSUE_INVALID_STRING) .run() .expect( """ |res/values/strings.xml:2: Warning: Text contains trailing whitespace. [InvalidString] | <string name="my_string">My string </string> | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ |0 errors, 1 warnings """.trimMargin(), ) .expectFixDiffs( """ |Fix for res/values/strings.xml line 1: Fix it: |@@ -2 +2 |- <string name="my_string">My string </string> |+ <string name="my_string">My string</string> """.trimMargin(), ) } @Test fun trailingWhitespaceAtBeginningOfString() { lint() .files( xml( "res/values/strings.xml", """ <resources> <string name="my_string"> My string</string> </resources> """, ).indented(), ) .issues(ISSUE_INVALID_STRING) .run() .expect( """ |res/values/strings.xml:2: Warning: Text contains trailing whitespace. [InvalidString] | <string name="my_string"> My string</string> | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ |0 errors, 1 warnings """.trimMargin(), ) .expectFixDiffs( """ |Fix for res/values/strings.xml line 1: Fix it: |@@ -2 +2 |- <string name="my_string"> My string</string> |+ <string name="my_string">My string</string> """.trimMargin(), ) } @Test fun validPluralString() { lint() .files( xml( "res/values/strings.xml", """ <plurals name="days"> <item quantity="one">%d Day</item> <item quantity="other">%d Days</item> </plurals> """, ).indented(), ) .issues(ISSUE_INVALID_STRING) .run() .expectClean() } @Test fun trailingWhitespaceAtPluralStrings() { lint() .files( xml( "res/values/strings.xml", """ <plurals name="days"> <item quantity="one"> %d Day</item> <item quantity="other">%d Days </item> </plurals> """, ).indented(), ) .issues(ISSUE_INVALID_STRING) .run() .expect( """ |res/values/strings.xml:2: Warning: Text contains trailing whitespace. [InvalidString] | <item quantity="one"> %d Day</item> | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ |res/values/strings.xml:3: Warning: Text contains trailing whitespace. [InvalidString] | <item quantity="other">%d Days </item> | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ |0 errors, 2 warnings """.trimMargin(), ) .expectFixDiffs( """ |Fix for res/values/strings.xml line 1: Fix it: |@@ -2 +2 |- <item quantity="one"> %d Day</item> |+ <item quantity="one">%d Day</item> |Fix for res/values/strings.xml line 2: Fix it: |@@ -3 +3 |- <item quantity="other">%d Days </item> |+ <item quantity="other">%d Days</item> """.trimMargin(), ) } @Test fun validStringArrayString() { lint() .files( xml( "res/values/strings.xml", """ <string-array name="foo"> <item>1</item> <item>2</item> </string-array> """, ).indented(), ) .issues(ISSUE_INVALID_STRING) .run() .expectClean() } @Test fun trailingWhitespaceAtStringArrayStrings() { lint() .files( xml( "res/values/strings.xml", """ <string-array name="bar"> <item> 1</item> <item>2 </item> </string-array> """, ).indented(), ) .issues(ISSUE_INVALID_STRING) .run() .expect( """ |res/values/strings.xml:2: Warning: Text contains trailing whitespace. [InvalidString] | <item> 1</item> | ~~~~~~~~~~~~~~~~~ |res/values/strings.xml:3: Warning: Text contains trailing whitespace. [InvalidString] | <item>2 </item> | ~~~~~~~~~~~~~~~~~ |0 errors, 2 warnings """.trimMargin(), ) .expectFixDiffs( """ |Fix for res/values/strings.xml line 1: Fix it: |@@ -2 +2 |- <item> 1</item> |+ <item>1</item> |Fix for res/values/strings.xml line 2: Fix it: |@@ -3 +3 |- <item>2 </item> |+ <item>2</item> """.trimMargin(), ) } }
apache-2.0
7313e136db7df43b17542a34d8612bb6
26.295833
96
0.461304
4.125315
false
false
false
false
jotomo/AndroidAPS
app/src/main/java/info/nightscout/androidaps/plugins/general/smsCommunicator/otp/OneTimePassword.kt
1
4531
package info.nightscout.androidaps.plugins.general.smsCommunicator.otp import android.util.Base64 import com.eatthepath.otp.HmacOneTimePasswordGenerator import com.google.common.io.BaseEncoding import info.nightscout.androidaps.Constants import info.nightscout.androidaps.R import info.nightscout.androidaps.utils.DateUtil import info.nightscout.androidaps.utils.resources.ResourceHelper import info.nightscout.androidaps.utils.sharedPreferences.SP import java.net.URLEncoder import javax.crypto.KeyGenerator import javax.crypto.SecretKey import javax.crypto.spec.SecretKeySpec import javax.inject.Inject import javax.inject.Singleton @Singleton class OneTimePassword @Inject constructor( private val sp: SP, private val resourceHelper: ResourceHelper ) { private var key: SecretKey? = null private var pin: String = "" private val totp = HmacOneTimePasswordGenerator() init { instance = this configure() } companion object { private lateinit var instance: OneTimePassword @JvmStatic fun getInstance(): OneTimePassword = instance } /** * If OTP Authenticator support is enabled by user */ fun isEnabled(): Boolean { return sp.getBoolean(R.string.key_smscommunicator_otp_enabled, true) } /** * Name of master device (target of OTP) */ fun name(): String { val defaultUserName = resourceHelper.gs(R.string.patient_name_default) var userName = sp.getString(R.string.key_patient_name, defaultUserName).replace(":", "").trim() if (userName.isEmpty()) userName = defaultUserName return userName } /** * Make sure if private key for TOTP is generated, creating it when necessary or requested */ fun ensureKey(forceNewKey: Boolean = false) { val keyBytes: ByteArray val strSecret = sp.getString(R.string.key_smscommunicator_otp_secret, "").trim() if (strSecret.isEmpty() || forceNewKey) { val keyGenerator = KeyGenerator.getInstance(totp.algorithm) keyGenerator.init(Constants.OTP_GENERATED_KEY_LENGTH_BITS) val generatedKey = keyGenerator.generateKey() keyBytes = generatedKey.encoded sp.putString(R.string.key_smscommunicator_otp_secret, Base64.encodeToString(keyBytes, Base64.NO_WRAP + Base64.NO_PADDING)) } else { keyBytes = Base64.decode(strSecret, Base64.DEFAULT) } key = SecretKeySpec(keyBytes, 0, keyBytes.size, "SHA1") } private fun configure() { ensureKey() pin = sp.getString(R.string.key_smscommunicator_otp_password, "").trim() } private fun generateOneTimePassword(counter: Long): String = key?.let { String.format("%06d", totp.generateOneTimePassword(key, counter)) } ?: "" /** * Check if given OTP+PIN is valid */ fun checkOTP(otp: String): OneTimePasswordValidationResult { configure() val normalisedOtp = otp.replace(" ", "").replace("-", "").trim() if (pin.length < 3) { return OneTimePasswordValidationResult.ERROR_WRONG_PIN } if (normalisedOtp.length != (6 + pin.length)) { return OneTimePasswordValidationResult.ERROR_WRONG_LENGTH } if (normalisedOtp.substring(6) != pin) { return OneTimePasswordValidationResult.ERROR_WRONG_PIN } val counter: Long = DateUtil.now() / 30000L val acceptableTokens: MutableList<String> = mutableListOf(generateOneTimePassword(counter)) for (i in 0 until Constants.OTP_ACCEPT_OLD_TOKENS_COUNT) { acceptableTokens.add(generateOneTimePassword(counter - i - 1)) } val candidateOtp = normalisedOtp.substring(0, 6) if (acceptableTokens.any { candidate -> candidateOtp == candidate }) { return OneTimePasswordValidationResult.OK } return OneTimePasswordValidationResult.ERROR_WRONG_OTP } /** * Return URI used to provision Authenticator apps */ fun provisioningURI(): String? = key?.let { "otpauth://totp/AndroidAPS:" + URLEncoder.encode(name(), "utf-8").replace("+", "%20") + "?secret=" + BaseEncoding.base32().encode(it.encoded).replace("=", "") + "&issuer=AndroidAPS" } /** * Return secret used to provision Authenticator apps, in Base32 format */ fun provisioningSecret(): String? = key?.let { BaseEncoding.base32().encode(it.encoded).replace("=", "") } }
agpl-3.0
399ced3633765ecc55bd47a079a6cbc8
33.861538
202
0.665857
4.424805
false
false
false
false
anitawoodruff/habitica-android
Habitica/src/main/java/com/habitrpg/android/habitica/ui/GemPurchaseOptionsView.kt
1
1234
package com.habitrpg.android.habitica.ui import android.content.Context import android.util.AttributeSet import android.widget.FrameLayout import com.habitrpg.android.habitica.R import com.habitrpg.android.habitica.databinding.PurchaseGemViewBinding import com.habitrpg.android.habitica.extensions.layoutInflater class GemPurchaseOptionsView(context: Context, attrs: AttributeSet) : FrameLayout(context, attrs) { private var binding: PurchaseGemViewBinding = PurchaseGemViewBinding.inflate(context.layoutInflater, this, true) var sku: String? = null init { val a = context.theme.obtainStyledAttributes( attrs, R.styleable.GemPurchaseOptionsView, 0, 0) binding.gemAmount.text = a.getText(R.styleable.GemPurchaseOptionsView_gemAmount) val iconRes = a.getDrawable(R.styleable.GemPurchaseOptionsView_gemDrawable) if (iconRes != null) { binding.gemImage.setImageDrawable(iconRes) } } fun setOnPurchaseClickListener(listener: OnClickListener) { binding.purchaseButton.setOnClickListener(listener) } fun setPurchaseButtonText(price: String) { binding.purchaseButton.text = price } }
gpl-3.0
1c986d8c5a8404cb923e87359d027e19
31.473684
116
0.728525
4.536765
false
false
false
false
mdaniel/intellij-community
platform/build-scripts/groovy/org/jetbrains/intellij/build/ProductProperties.kt
2
11970
// 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.intellij.build import kotlinx.collections.immutable.PersistentMap import kotlinx.collections.immutable.persistentMapOf import org.jetbrains.annotations.ApiStatus import org.jetbrains.intellij.build.impl.productInfo.CustomProperty import org.jetbrains.jps.model.module.JpsModule import java.nio.file.Path import java.util.* import java.util.function.BiPredicate /** * Describes distribution of an IntelliJ-based IDE. Override this class and build distribution of your product. */ abstract class ProductProperties { /** * The base name for script files (*.bat, *.sh, *.exe), usually a shortened product name in lower case * (e.g. 'idea' for IntelliJ IDEA, 'datagrip' for DataGrip). */ lateinit var baseFileName: String /** * Deprecated: specify product code in 'number' attribute in 'build' tag in *ApplicationInfo.xml file instead (see its schema for details); * if you need to get the product code in the build scripts, use [ApplicationInfoProperties.productCode] instead; * if you need to override product code value from *ApplicationInfo.xml - [ProductProperties.customProductCode] can be used. */ @Deprecated("see the doc") var productCode: String? = null /** * This value overrides specified product code in 'number' attribute in 'build' tag in *ApplicationInfo.xml file. */ var customProductCode: String? = null /** * Value of 'idea.platform.prefix' property. It's also used as a prefix for 'ApplicationInfo.xml' product descriptor. */ var platformPrefix: String? = null /** * Name of the module containing ${platformPrefix}ApplicationInfo.xml product descriptor in 'idea' package. */ lateinit var applicationInfoModule: String /** * Enables fast activation of a running IDE instance from the launcher * (at the moment, it is only implemented in the native Windows one). */ var fastInstanceActivation = true /** * An entry point into application's Java code, usually [com.intellij.idea.Main]. */ var mainClassName = "com.intellij.idea.Main" /** * Paths to directories containing images specified by 'logo/@url' and 'icon/@ico' attributes in ApplicationInfo.xml file. * <br> * todo(nik) get rid of this and make sure that these resources are located in [applicationInfoModule] instead */ var brandingResourcePaths: List<Path> = emptyList() /** * Name of the command which runs IDE in 'offline inspections' mode * (returned by [com.intellij.openapi.application.ApplicationStarter.getCommandName]). * This property will be also used to name sh/bat scripts which execute this command. */ var inspectCommandName = "inspect" /** * `true` if tools.jar from JDK must be added to the IDE classpath. */ var toolsJarRequired = false var isAntRequired = false /** * Whether to use splash for application start-up. */ var useSplash = false /** * Class-loader that product application should use by default. * <p/> * `com.intellij.util.lang.PathClassLoader` is used by default as * it unifies class-loading logic of an application and allows to avoid double-loading of bootstrap classes. */ var classLoader: String? = "com.intellij.util.lang.PathClassLoader" /** * Additional arguments which will be added to JVM command line in IDE launchers for all operating systems. */ var additionalIdeJvmArguments: MutableList<String> = mutableListOf() /** * The specified options will be used instead of/in addition to the default JVM memory options for all operating systems. */ var customJvmMemoryOptions: MutableMap<String, String> = mutableMapOf() /** * An identifier which will be used to form names for directories where configuration and caches will be stored, usually a product name * without spaces with an added version ('IntelliJIdea2016.1' for IntelliJ IDEA 2016.1). */ open fun getSystemSelector(appInfo: ApplicationInfoProperties, buildNumber: String): String { return "${appInfo.productName}${appInfo.majorVersion}.${appInfo.minorVersionMainPart}" } /** * If `true`, Alt+Button1 shortcut will be removed from 'Quick Evaluate Expression' action and assigned to 'Add/Remove Caret' action * (instead of Alt+Shift+Button1) in the default keymap. */ var reassignAltClickToMultipleCarets = false /** * Now file containing information about third-party libraries is bundled and shown inside the IDE. * If `true`, HTML & JSON files of third-party libraries will be placed alongside built artifacts. */ var generateLibraryLicensesTable = true /** * List of licenses information about all libraries which can be used in the product modules. */ var allLibraryLicenses: List<LibraryLicense> = CommunityLibraryLicenses.LICENSES_LIST /** * If `true`, the product's main JAR file will be scrambled using [ProprietaryBuildTools.scrambleTool]. */ var scrambleMainJar = false @ApiStatus.Experimental var useProductJar = true /** * If `false`, names of private fields won't be scrambled (to avoid problems with serialization). * This field is ignored if [scrambleMainJar] is `false`. */ var scramblePrivateFields = true /** * Path to an alternative scramble script which will should be used for a product. */ var alternativeScrambleStubPath: Path? = null /** * Describes which modules should be included in the product's platform and which plugins should be bundled with the product. */ val productLayout = ProductModulesLayout() /** * If `true`, a cross-platform ZIP archive containing binaries for all OSes will be built. * The archive will be generated in [BuildPaths.artifactDir] directory and have ".portable" suffix by default * (override [getCrossPlatformZipFileName] to change the file name). * Cross-platform distribution is required for [plugins development](https://github.com/JetBrains/gradle-intellij-plugin). */ var buildCrossPlatformDistribution = false /** * Specifies name of cross-platform ZIP archive if `[buildCrossPlatformDistribution]` is set to `true`. */ open fun getCrossPlatformZipFileName(applicationInfo: ApplicationInfoProperties, buildNumber: String): String = getBaseArtifactName(applicationInfo, buildNumber) + ".portable.zip" /** * A config map for [org.jetbrains.intellij.build.impl.ClassVersionChecker], * when .class file version verification inside [buildCrossPlatformDistribution] is needed. */ var versionCheckerConfig: PersistentMap<String, String> = persistentMapOf() /** * Strings which are forbidden as a part of resulting class file path */ var forbiddenClassFileSubPaths: List<String> = emptyList() /** * Paths to properties files the content of which should be appended to idea.properties file. */ var additionalIDEPropertiesFilePaths: List<Path> = emptyList() /** * Paths to directories the content of which should be added to 'license' directory of IDE distribution. */ var additionalDirectoriesWithLicenses: List<Path> = emptyList() /** * Base file name (without an extension) for product archives and installers (*.exe, *.tar.gz, *.dmg). */ abstract fun getBaseArtifactName(appInfo: ApplicationInfoProperties, buildNumber: String): String /** * @return an instance of the class containing properties specific for Windows distribution, * or `null` if the product doesn't have Windows distribution. */ abstract fun createWindowsCustomizer(projectHome: String): WindowsDistributionCustomizer? /** * @return an instance of the class containing properties specific for Linux distribution, * or `null` if the product doesn't have Linux distribution. */ abstract fun createLinuxCustomizer(projectHome: String): LinuxDistributionCustomizer? /** * @return an instance of the class containing properties specific for macOS distribution, * or `null` if the product doesn't have macOS distribution. */ abstract fun createMacCustomizer(projectHome: String): MacDistributionCustomizer? /** * If `true`, a .zip archive containing sources of modules included in the product will be produced. * See also [includeIntoSourcesArchiveFilter]. */ var buildSourcesArchive = false /** * Determines sources of which modules should be included in the source archive when [buildSourcesArchive] is `true`. */ var includeIntoSourcesArchiveFilter: BiPredicate<JpsModule, BuildContext> = BiPredicate { _, _ -> true } /** * Specifies how Maven artifacts for IDE modules should be generated; by default, no artifacts are generated. */ val mavenArtifacts = MavenArtifactsProperties() /** * Specified additional modules (not included into the product layout) which need to be compiled when product is built. * todo(nik) get rid of this */ var additionalModulesToCompile: List<String> = emptyList() /** * Specified modules which tests need to be compiled when product is built. * todo(nik) get rid of this */ var modulesToCompileTests: List<String> = emptyList() var runtimeDistribution: JetBrainsRuntimeDistribution = JetBrainsRuntimeDistribution.JCEF /** * A prefix for names of environment variables used by Windows and Linux distributions * to allow users to customize location of the product runtime (`<PRODUCT>_JDK` variable), * *.vmoptions file (`<PRODUCT>_VM_OPTIONS`), `idea.properties` file (`<PRODUCT>_PROPERTIES`). */ open fun getEnvironmentVariableBaseName(applicationInfo: ApplicationInfoProperties) = applicationInfo.upperCaseProductName /** * Override this method to copy additional files to distributions of all operating systems. */ open fun copyAdditionalFiles(context: BuildContext, targetDirectory: String) { } /** * Override this method if the product has several editions to ensure that their artifacts won't be mixed up. * @return the name of a subdirectory under `projectHome/out` where build artifacts will be placed, * must be unique among all products built from the same sources. */ open fun getOutputDirectoryName(appInfo: ApplicationInfoProperties) = appInfo.productName.lowercase(Locale.ROOT) /** * Paths to externally built plugins to be included in the IDE. * They will be copied into the build, as well as included in the IDE classpath when launching it to build search index, .jar order, etc. */ open fun getAdditionalPluginPaths(context: BuildContext): List<Path> = emptyList() /** * @return custom properties for [org.jetbrains.intellij.build.impl.productInfo.ProductInfoData]. */ open fun generateCustomPropertiesForProductInfo(): List<CustomProperty> = emptyList() /** * If `true`, a distribution contains libraries and launcher script for running IDE in Remote Development mode. */ @ApiStatus.Internal open fun addRemoteDevelopmentLibraries(): Boolean = productLayout.bundledPluginModules.contains("intellij.remoteDevServer") /** * Build steps which are always skipped for this product. * Can be extended via [org.jetbrains.intellij.build.BuildOptions.buildStepsToSkip], but not overridden. */ var incompatibleBuildSteps: List<String> = emptyList() /** * Names of JARs inside IDE_HOME/lib directory which need to be added to the Xbootclasspath to start the IDE */ var xBootClassPathJarNames: List<String> = emptyList() /** * Allows customizing `PRODUCT_CODE-builtinModules.json` file, which contains information about product modules, * bundled plugins, and file extensions. The file is used to populate marketplace settings of the product. * <p> * It's particularly useful when you want to limit modules used to calculate compatible plugins on the marketplace. */ open fun customizeBuiltinModules(context: BuildContext, builtinModulesFile: Path) { } }
apache-2.0
1efa316a360153c2d726142795d07b49
39.714286
141
0.740267
4.672131
false
false
false
false
K0zka/kerub
src/main/kotlin/com/github/kerubistan/kerub/utils/junix/storagemanager/lvm/Constants.kt
2
973
package com.github.kerubistan.kerub.utils.junix.storagemanager.lvm const val separator = "--end" const val fields = "vg_name,lv_uuid,lv_name,lv_path,lv_size,raid_min_recovery_rate,raid_max_recovery_rate,lv_layout,data_percent" const val vgFields = "vg_uuid,vg_name,vg_size,vg_free,vg_extent_count,vg_free_count" const val fieldSeparator = ":" const val listOptions = "--noheadings --units b --separator=$fieldSeparator" val vgName = fieldPosition("vg_name") val lvUuid = fieldPosition("lv_uuid") val lvName = fieldPosition("lv_name") val lvPath = fieldPosition("lv_path") val lvSize = fieldPosition("lv_size") val lvLayout = fieldPosition("lv_layout") val raidMinRecoveryRate = fieldPosition("raid_min_recovery_rate") val raidMaxRecoveryRate = fieldPosition("raid_max_recovery_rate") val dataPercent = fieldPosition("data_percent") val nrOfLvsOutputColumns = fields.split(",").size private fun fieldPosition(columnName: String) = fields.split(",").indexOf(columnName)
apache-2.0
b810bafe99564a1f2d322a6f571c2922
45.333333
112
0.766701
3.298305
false
false
false
false
mickele/DBFlow
dbflow-processor/src/main/java/com/raizlabs/android/dbflow/processor/definition/Methods.kt
1
21535
package com.raizlabs.android.dbflow.processor.definition import com.raizlabs.android.dbflow.processor.ClassNames import com.raizlabs.android.dbflow.processor.utils.ModelUtils import com.raizlabs.android.dbflow.processor.utils.isNullOrEmpty import com.raizlabs.android.dbflow.sql.QueryBuilder import com.squareup.javapoet.* import java.util.* import java.util.concurrent.atomic.AtomicInteger import javax.lang.model.element.Modifier /** * Description: */ interface MethodDefinition { val methodSpec: MethodSpec? } /** * Description: * * @author Andrew Grosner (fuzz) */ /** * Description: Writes the bind to content values method in the ModelDAO. */ class BindToContentValuesMethod(private val baseTableDefinition: BaseTableDefinition, private val isInsert: Boolean, private val implementsContentValuesListener: Boolean) : MethodDefinition { override val methodSpec: MethodSpec get() { val methodBuilder = MethodSpec.methodBuilder(if (isInsert) "bindToInsertValues" else "bindToContentValues") .addAnnotation(Override::class.java) .addModifiers(Modifier.PUBLIC, Modifier.FINAL) .addParameter(ClassNames.CONTENT_VALUES, PARAM_CONTENT_VALUES) .addParameter(baseTableDefinition.parameterClassName, ModelUtils.variable) .returns(TypeName.VOID) if (isInsert) { baseTableDefinition.columnDefinitions.forEach { if (!it.isPrimaryKeyAutoIncrement && !it.isRowId) { methodBuilder.addCode(it.contentValuesStatement) } } if (implementsContentValuesListener) { methodBuilder.addStatement("\$L.onBindTo\$LValues(\$L)", ModelUtils.variable, if (isInsert) "Insert" else "Content", PARAM_CONTENT_VALUES) } } else { if (baseTableDefinition.hasAutoIncrement || baseTableDefinition.hasRowID) { val autoIncrement = baseTableDefinition.autoIncrementColumn autoIncrement?.let { methodBuilder.addCode(autoIncrement.contentValuesStatement) } } methodBuilder.addStatement("bindToInsertValues(\$L, \$L)", PARAM_CONTENT_VALUES, ModelUtils.variable) if (implementsContentValuesListener) { methodBuilder.addStatement("\$L.onBindTo\$LValues(\$L)", ModelUtils.variable, if (isInsert) "Insert" else "Content", PARAM_CONTENT_VALUES) } } return methodBuilder.build() } companion object { val PARAM_CONTENT_VALUES = "values" } } /** * Description: */ class BindToStatementMethod(private val tableDefinition: TableDefinition, private val isInsert: Boolean) : MethodDefinition { override val methodSpec: MethodSpec get() { val methodBuilder = MethodSpec.methodBuilder(if (isInsert) "bindToInsertStatement" else "bindToStatement") .addAnnotation(Override::class.java) .addModifiers(Modifier.PUBLIC, Modifier.FINAL) .addParameter(ClassNames.DATABASE_STATEMENT, PARAM_STATEMENT) .addParameter(tableDefinition.parameterClassName, ModelUtils.variable).returns(TypeName.VOID) // write the reference method if (isInsert) { methodBuilder.addParameter(TypeName.INT, PARAM_START) val realCount = AtomicInteger(1) tableDefinition.columnDefinitions.forEach { if (!it.isPrimaryKeyAutoIncrement && !it.isRowId) { methodBuilder.addCode(it.getSQLiteStatementMethod(realCount)) realCount.incrementAndGet() } } if (tableDefinition.implementsSqlStatementListener) { methodBuilder.addStatement("\$L.onBindTo\$LStatement(\$L)", ModelUtils.variable, if (isInsert) "Insert" else "", PARAM_STATEMENT) } } else { var start = 0 if (tableDefinition.hasAutoIncrement || tableDefinition.hasRowID) { val autoIncrement = tableDefinition.autoIncrementColumn autoIncrement?.let { methodBuilder.addStatement("int start = 0") methodBuilder.addCode(it.getSQLiteStatementMethod(AtomicInteger(++start))) } } methodBuilder.addStatement("bindToInsertStatement(\$L, \$L, \$L)", PARAM_STATEMENT, ModelUtils.variable, start) if (tableDefinition.implementsSqlStatementListener) { methodBuilder.addStatement("\$L.onBindTo\$LStatement(\$L)", ModelUtils.variable, if (isInsert) "Insert" else "", PARAM_STATEMENT) } } return methodBuilder.build() } companion object { val PARAM_STATEMENT = "statement" val PARAM_START = "start" } } /** * Description: */ class CreationQueryMethod(private val tableDefinition: TableDefinition) : MethodDefinition { override val methodSpec: MethodSpec get() { val methodBuilder = MethodSpec.methodBuilder("getCreationQuery") .addAnnotation(Override::class.java) .addModifiers(Modifier.PUBLIC, Modifier.FINAL) .returns(ClassName.get(String::class.java)) val creationBuilder = CodeBlock.builder().add("CREATE TABLE IF NOT EXISTS ") .add(QueryBuilder.quote(tableDefinition.tableName)).add("(") (0..tableDefinition.columnDefinitions.size - 1).forEach { i -> if (i > 0) { creationBuilder.add(",") } creationBuilder.add(tableDefinition.columnDefinitions[i].creationName) } tableDefinition.uniqueGroupsDefinitions.forEach { if (!it.columnDefinitionList.isEmpty()) creationBuilder.add(it.creationName) } if (!tableDefinition.hasAutoIncrement) { val primarySize = tableDefinition.primaryColumnDefinitions.size for (i in 0..primarySize - 1) { if (i == 0) { creationBuilder.add(", PRIMARY KEY(") } if (i > 0) { creationBuilder.add(",") } val primaryDefinition = tableDefinition.primaryColumnDefinitions[i] creationBuilder.add(primaryDefinition.primaryKeyName) if (i == primarySize - 1) { creationBuilder.add(")") if (!tableDefinition.primaryKeyConflictActionName.isNullOrEmpty()) { creationBuilder.add(" ON CONFLICT " + tableDefinition.primaryKeyConflictActionName) } } } } val foreignSize = tableDefinition.foreignKeyDefinitions.size val foreignKeyBlocks = ArrayList<CodeBlock>() val tableNameBlocks = ArrayList<CodeBlock>() val referenceKeyBlocks = ArrayList<CodeBlock>() for (i in 0..foreignSize - 1) { val foreignKeyBuilder = CodeBlock.builder() val referenceBuilder = CodeBlock.builder() val foreignKeyColumnDefinition = tableDefinition.foreignKeyDefinitions[i] foreignKeyBuilder.add(", FOREIGN KEY(") (0..foreignKeyColumnDefinition._foreignKeyReferenceDefinitionList.size - 1).forEach { j -> if (j > 0) { foreignKeyBuilder.add(",") } val referenceDefinition = foreignKeyColumnDefinition._foreignKeyReferenceDefinitionList[j] foreignKeyBuilder.add("\$L", QueryBuilder.quote(referenceDefinition.columnName)) } foreignKeyBuilder.add(") REFERENCES ") foreignKeyBlocks.add(foreignKeyBuilder.build()) tableNameBlocks.add(CodeBlock.builder().add("\$T.getTableName(\$T.class)", ClassNames.FLOW_MANAGER, foreignKeyColumnDefinition.referencedTableClassName).build()) referenceBuilder.add("(") for (j in 0..foreignKeyColumnDefinition._foreignKeyReferenceDefinitionList.size - 1) { if (j > 0) { referenceBuilder.add(", ") } val referenceDefinition = foreignKeyColumnDefinition._foreignKeyReferenceDefinitionList[j] referenceBuilder.add("\$L", QueryBuilder.quote(referenceDefinition.foreignColumnName)) } referenceBuilder.add(") ON UPDATE \$L ON DELETE \$L", foreignKeyColumnDefinition.onUpdate.name.replace("_", " "), foreignKeyColumnDefinition.onDelete.name.replace("_", " ")) referenceKeyBlocks.add(referenceBuilder.build()) } val codeBuilder = CodeBlock.builder().add("return \$S", creationBuilder.build().toString()) if (foreignSize > 0) { for (i in 0..foreignSize - 1) { codeBuilder.add("+ \$S + \$L + \$S", foreignKeyBlocks[i], tableNameBlocks[i], referenceKeyBlocks[i]) } } codeBuilder.add(" + \$S", ");").add(";\n") methodBuilder.addCode(codeBuilder.build()) return methodBuilder.build() } } /** * Description: Writes out the custom type converter fields. */ class CustomTypeConverterPropertyMethod(private val baseTableDefinition: BaseTableDefinition) : TypeAdder, CodeAdder { override fun addToType(typeBuilder: TypeSpec.Builder) { val customTypeConverters = baseTableDefinition.associatedTypeConverters.keys customTypeConverters.forEach { typeBuilder.addField(FieldSpec.builder(it, "typeConverter" + it.simpleName(), Modifier.PRIVATE, Modifier.FINAL).initializer("new \$T()", it).build()) } val globalTypeConverters = baseTableDefinition.globalTypeConverters.keys globalTypeConverters.forEach { typeBuilder.addField(FieldSpec.builder(it, "global_typeConverter" + it.simpleName(), Modifier.PRIVATE, Modifier.FINAL).build()) } } override fun addCode(code: CodeBlock.Builder) { // Constructor code val globalTypeConverters = baseTableDefinition.globalTypeConverters.keys globalTypeConverters.forEach { val def = baseTableDefinition.globalTypeConverters[it] val firstDef = def?.get(0) firstDef?.typeConverterElementNames?.forEach { elementName -> code.addStatement("global_typeConverter\$L = (\$T) \$L.getTypeConverterForClass(\$T.class)", it.simpleName(), it, "holder", elementName).build() } } } } /** * Description: */ class ExistenceMethod(private val tableDefinition: BaseTableDefinition) : MethodDefinition { override val methodSpec: MethodSpec get() { val methodBuilder = MethodSpec.methodBuilder("exists") .addAnnotation(Override::class.java) .addParameter(tableDefinition.parameterClassName, ModelUtils.variable) .addParameter(ClassNames.DATABASE_WRAPPER, "wrapper") .addModifiers(Modifier.PUBLIC, Modifier.FINAL).returns(TypeName.BOOLEAN) // only quick check if enabled. var primaryColumn = tableDefinition.autoIncrementColumn if (primaryColumn == null) { primaryColumn = tableDefinition.primaryColumnDefinitions[0] } val code = CodeBlock.builder() primaryColumn.appendExistenceMethod(code) methodBuilder.addCode(code.build()) return methodBuilder.build() } } /** * Description: */ class InsertStatementQueryMethod(private val tableDefinition: TableDefinition, private val isInsert: Boolean) : MethodDefinition { override val methodSpec: MethodSpec get() { val methodBuilder = MethodSpec.methodBuilder(if (isInsert) "getInsertStatementQuery" else "getCompiledStatementQuery").addAnnotation(Override::class.java).addModifiers(Modifier.PUBLIC, Modifier.FINAL).returns(ClassName.get(String::class.java)) val codeBuilder = CodeBlock.builder().add("INSERT ") if (!tableDefinition.insertConflictActionName.isEmpty()) { codeBuilder.add("OR \$L ", tableDefinition.insertConflictActionName) } codeBuilder.add("INTO ").add(QueryBuilder.quote(tableDefinition.tableName)) val isSingleAutoincrement = tableDefinition.hasAutoIncrement && tableDefinition.columnDefinitions.size == 1 && isInsert codeBuilder.add("(") val columnSize = tableDefinition.columnDefinitions.size var columnCount = 0 tableDefinition.columnDefinitions.forEach { if (!it.isPrimaryKeyAutoIncrement && !it.isRowId || !isInsert || isSingleAutoincrement) { if (columnCount > 0) codeBuilder.add(",") codeBuilder.add(it.insertStatementColumnName) columnCount++ } } codeBuilder.add(")") codeBuilder.add(" VALUES (") columnCount = 0 for (i in 0..columnSize - 1) { val definition = tableDefinition.columnDefinitions[i] if (!definition.isPrimaryKeyAutoIncrement && !definition.isRowId || !isInsert) { if (columnCount > 0) { codeBuilder.add(",") } codeBuilder.add(definition.insertStatementValuesString) columnCount++ } } if (isSingleAutoincrement) { codeBuilder.add("NULL") } codeBuilder.add(")") methodBuilder.addStatement("return \$S", codeBuilder.build().toString()) return methodBuilder.build() } } /** * Description: */ class LoadFromCursorMethod(private val baseTableDefinition: BaseTableDefinition) : MethodDefinition { override val methodSpec: MethodSpec get() { val methodBuilder = MethodSpec.methodBuilder("loadFromCursor").addAnnotation(Override::class.java) .addModifiers(Modifier.PUBLIC, Modifier.FINAL) .addParameter(ClassNames.CURSOR, PARAM_CURSOR) .addParameter(baseTableDefinition.parameterClassName, ModelUtils.variable).returns(TypeName.VOID) val index = AtomicInteger(0) baseTableDefinition.columnDefinitions.forEach { methodBuilder.addCode(it.getLoadFromCursorMethod(true, index)) index.incrementAndGet() } if (baseTableDefinition is TableDefinition) { val codeBuilder = CodeBlock.builder() for (oneToMany in baseTableDefinition.oneToManyDefinitions) { if (oneToMany.isLoad) oneToMany.writeLoad(codeBuilder) } methodBuilder.addCode(codeBuilder.build()) } if (baseTableDefinition is TableDefinition && baseTableDefinition.implementsLoadFromCursorListener) { methodBuilder.addStatement("\$L.onLoadFromCursor(\$L)", ModelUtils.variable, PARAM_CURSOR) } return methodBuilder.build() } companion object { val PARAM_CURSOR = "cursor" } } /** * Description: */ class OneToManyDeleteMethod(private val tableDefinition: TableDefinition, private val useWrapper: Boolean) : MethodDefinition { override val methodSpec: MethodSpec? get() { var shouldWrite = false for (oneToManyDefinition in tableDefinition.oneToManyDefinitions) { if (oneToManyDefinition.isDelete) { shouldWrite = true break } } if (shouldWrite || tableDefinition.cachingEnabled) { val builder = CodeBlock.builder() if (tableDefinition.cachingEnabled) { builder.addStatement("getModelCache().removeModel(getCachingId(\$L))", ModelUtils.variable) } builder.addStatement("super.delete(\$L\$L)", ModelUtils.variable, if (useWrapper) ", " + ModelUtils.wrapper else "") tableDefinition.oneToManyDefinitions.forEach { it.writeDelete(builder, useWrapper) } val delete = MethodSpec.methodBuilder("delete").addAnnotation(Override::class.java) .addModifiers(Modifier.PUBLIC, Modifier.FINAL) .addParameter(tableDefinition.elementClassName, ModelUtils.variable) .addCode(builder.build()).returns(TypeName.VOID) if (useWrapper) { delete.addParameter(ClassNames.DATABASE_WRAPPER, ModelUtils.wrapper) } return delete.build() } return null } } /** * Description: Overrides the save, update, and insert methods if the [com.raizlabs.android.dbflow.annotation.OneToMany.Method.SAVE] is used. */ class OneToManySaveMethod(private val tableDefinition: TableDefinition, private val methodName: String, private val useWrapper: Boolean) : MethodDefinition { override val methodSpec: MethodSpec? get() { if (!tableDefinition.oneToManyDefinitions.isEmpty() || tableDefinition.cachingEnabled) { val code = CodeBlock.builder() if (methodName == METHOD_INSERT) { code.add("long rowId = ") } code.addStatement("super.\$L(\$L\$L)", methodName, ModelUtils.variable, if (useWrapper) ", " + ModelUtils.wrapper else "") if (tableDefinition.cachingEnabled) { code.addStatement("getModelCache().addModel(getCachingId(\$L), \$L)", ModelUtils.variable, ModelUtils.variable) } for (oneToManyDefinition in tableDefinition.oneToManyDefinitions) { when (methodName) { METHOD_SAVE -> oneToManyDefinition.writeSave(code, useWrapper) METHOD_UPDATE -> oneToManyDefinition.writeUpdate(code, useWrapper) METHOD_INSERT -> oneToManyDefinition.writeInsert(code, useWrapper) } } val builder = MethodSpec.methodBuilder(methodName) .addAnnotation(Override::class.java) .addModifiers(Modifier.PUBLIC, Modifier.FINAL) .addParameter(tableDefinition.elementClassName, ModelUtils.variable) .addCode(code.build()) if (methodName == METHOD_INSERT) { builder.returns(ClassName.LONG) builder.addStatement("return rowId") } if (useWrapper) { builder.addParameter(ClassNames.DATABASE_WRAPPER, ModelUtils.wrapper) } return builder.build() } else { return null } } companion object { val METHOD_SAVE = "save" val METHOD_UPDATE = "update" val METHOD_INSERT = "insert" } } /** * Description: Creates a method that builds a clause of ConditionGroup that represents its primary keys. Useful * for updates or deletes. */ class PrimaryConditionMethod(private val tableDefinition: BaseTableDefinition) : MethodDefinition { override val methodSpec: MethodSpec? get() { val methodBuilder = MethodSpec.methodBuilder("getPrimaryConditionClause") .addAnnotation(Override::class.java) .addModifiers(Modifier.PUBLIC, Modifier.FINAL) .addParameter(tableDefinition.parameterClassName, ModelUtils.variable).returns(ClassNames.CONDITION_GROUP) val code = CodeBlock.builder() code.addStatement("\$T clause = \$T.clause()", ClassNames.CONDITION_GROUP, ClassNames.CONDITION_GROUP) tableDefinition.primaryColumnDefinitions.forEach { val codeBuilder = CodeBlock.builder() it.appendPropertyComparisonAccessStatement(codeBuilder) code.add(codeBuilder.build()) } methodBuilder.addCode(code.build()) methodBuilder.addStatement("return clause") return methodBuilder.build() } }
mit
6d64ad50b7e9622a7860ca7438597233
40.019048
255
0.585187
5.590602
false
false
false
false
nrizzio/Signal-Android
app/src/main/java/org/thoughtcrime/securesms/conversation/MessageStyler.kt
1
1783
package org.thoughtcrime.securesms.conversation import android.graphics.Typeface import android.text.SpannableString import android.text.Spanned import android.text.style.CharacterStyle import android.text.style.StyleSpan import android.text.style.TypefaceSpan import org.thoughtcrime.securesms.database.model.databaseprotos.BodyRangeList import org.thoughtcrime.securesms.util.PlaceholderURLSpan /** * Helper for applying style-based [BodyRangeList.BodyRange]s to text. */ object MessageStyler { @JvmStatic fun style(messageRanges: BodyRangeList, span: SpannableString): Result { var hasLinks = false var bottomButton: BodyRangeList.BodyRange.Button? = null for (range in messageRanges.rangesList) { if (range.hasStyle()) { val styleSpan: CharacterStyle? = when (range.style) { BodyRangeList.BodyRange.Style.BOLD -> TypefaceSpan("sans-serif-medium") BodyRangeList.BodyRange.Style.ITALIC -> StyleSpan(Typeface.ITALIC) else -> null } if (styleSpan != null) { span.setSpan(styleSpan, range.start, range.start + range.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE) } } else if (range.hasLink() && range.link != null) { span.setSpan(PlaceholderURLSpan(range.link), range.start, range.start + range.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE) hasLinks = true } else if (range.hasButton() && range.button != null) { bottomButton = range.button } } return Result(hasLinks, bottomButton) } data class Result(val hasStyleLinks: Boolean = false, val bottomButton: BodyRangeList.BodyRange.Button? = null) { companion object { @JvmStatic val NO_STYLE = Result() @JvmStatic fun none(): Result = NO_STYLE } } }
gpl-3.0
e13b366211247f72741c0fd757831d46
32.018519
127
0.702187
4.21513
false
false
false
false
GunoH/intellij-community
java/java-tests/testSrc/com/intellij/java/codeInspection/SingleInspectionProfilePanelTest.kt
7
4458
/* * 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.java.codeInspection import com.intellij.codeInspection.ex.InspectionProfileImpl import com.intellij.codeInspection.ex.InspectionProfileTest import com.intellij.codeInspection.ex.LocalInspectionToolWrapper import com.intellij.codeInspection.javaDoc.JavadocDeclarationInspection import com.intellij.openapi.project.ProjectManager import com.intellij.profile.codeInspection.ProjectInspectionProfileManager import com.intellij.profile.codeInspection.ui.SingleInspectionProfilePanel import com.intellij.testFramework.LightIdeaTestCase import com.intellij.testFramework.configureInspections import com.intellij.testFramework.createProfile import com.intellij.testFramework.runInInitMode import junit.framework.TestCase import org.assertj.core.api.Assertions.assertThat class SingleInspectionProfilePanelTest : LightIdeaTestCase() { private val myInspection = JavadocDeclarationInspection() // see IDEA-85700 fun testSettingsModification() { runInInitMode { val project = ProjectManager.getInstance().defaultProject val profile = configureInspections(arrayOf(myInspection), project, testRootDisposable) val model = profile.modifiableModel val panel = SingleInspectionProfilePanel(ProjectInspectionProfileManager.getInstance(project), model) panel.isVisible = true panel.reset() val tool = getInspection(model) assertEquals("", tool.ADDITIONAL_TAGS) tool.ADDITIONAL_TAGS = "foo" model.setModified(true) panel.apply() assertThat(InspectionProfileTest.countInitializedTools(model)).isEqualTo(1) assertThat(getInspection(profile).ADDITIONAL_TAGS).isEqualTo("foo") panel.disposeUI() } } fun testModifyInstantiatedTool() { val project = ProjectManager.getInstance().defaultProject val profileManager = ProjectInspectionProfileManager.getInstance(project) val profile = profileManager.createProfile(myInspection, testRootDisposable) profile.initInspectionTools(project) val originalTool = getInspection(profile) originalTool.ADDITIONAL_TAGS = "foo" val model = profile.modifiableModel val panel = SingleInspectionProfilePanel(profileManager, model) panel.isVisible = true panel.reset() TestCase.assertEquals(InspectionProfileTest.getInitializedTools(model).toString(), 1, InspectionProfileTest.countInitializedTools(model)) val copyTool = getInspection(model) copyTool.ADDITIONAL_TAGS = "bar" model.setModified(true) panel.apply() assertThat(InspectionProfileTest.countInitializedTools(model)).isEqualTo(1) assertEquals("bar", getInspection(profile).ADDITIONAL_TAGS) panel.disposeUI() } fun testDoNotChangeSettingsOnCancel() { val project = ProjectManager.getInstance().defaultProject val profileManager = ProjectInspectionProfileManager.getInstance(project) val profile = profileManager.createProfile(myInspection, testRootDisposable) profile.initInspectionTools(project) val originalTool = getInspection(profile) assertThat(originalTool.ADDITIONAL_TAGS).isEmpty() val model = profile.modifiableModel val copyTool = getInspection(model) copyTool.ADDITIONAL_TAGS = "foo" // this change IS NOT COMMITTED assertEquals("", getInspection(profile).ADDITIONAL_TAGS) } private fun getInspection(profile: InspectionProfileImpl): JavadocDeclarationInspection { return (profile.getInspectionTool(myInspection.shortName, getProject()) as LocalInspectionToolWrapper?)!!.tool as JavadocDeclarationInspection } override fun setUp() { InspectionProfileImpl.INIT_INSPECTIONS = true super.setUp() } override fun tearDown() { InspectionProfileImpl.INIT_INSPECTIONS = false super.tearDown() } override fun configureLocalInspectionTools() = arrayOf(myInspection) }
apache-2.0
32d8ba0b2e261ef30382580c3ad980c2
36.779661
146
0.77546
4.992161
false
true
false
false
SimpleMobileTools/Simple-Calendar
app/src/main/kotlin/com/simplemobiletools/calendar/pro/helpers/CalDAVHelper.kt
1
22829
package com.simplemobiletools.calendar.pro.helpers import android.annotation.SuppressLint import android.content.ContentUris import android.content.ContentValues import android.content.Context import android.provider.CalendarContract.* import android.util.SparseIntArray import android.widget.Toast import com.google.gson.Gson import com.google.gson.reflect.TypeToken import com.simplemobiletools.calendar.pro.R import com.simplemobiletools.calendar.pro.extensions.* import com.simplemobiletools.calendar.pro.models.* import com.simplemobiletools.calendar.pro.objects.States.isUpdatingCalDAV import com.simplemobiletools.commons.extensions.* import com.simplemobiletools.commons.helpers.PERMISSION_READ_CALENDAR import com.simplemobiletools.commons.helpers.PERMISSION_WRITE_CALENDAR import org.joda.time.DateTimeZone import org.joda.time.format.DateTimeFormat import java.util.* import kotlin.math.max @SuppressLint("MissingPermission") class CalDAVHelper(val context: Context) { private val eventsHelper = context.eventsHelper fun refreshCalendars(showToasts: Boolean, scheduleNextSync: Boolean, callback: () -> Unit) { if (isUpdatingCalDAV) { return } isUpdatingCalDAV = true try { val calDAVCalendars = getCalDAVCalendars(context.config.caldavSyncedCalendarIds, showToasts) for (calendar in calDAVCalendars) { val localEventType = eventsHelper.getEventTypeWithCalDAVCalendarId(calendar.id) ?: continue if (calendar.displayName != localEventType.title || calendar.color != localEventType.color) { localEventType.apply { title = calendar.displayName caldavDisplayName = calendar.displayName caldavEmail = calendar.accountName color = calendar.color eventsHelper.insertOrUpdateEventTypeSync(this) } } fetchCalDAVCalendarEvents(calendar.id, localEventType.id!!, showToasts) } if (scheduleNextSync) { context.scheduleCalDAVSync(true) } callback() } finally { isUpdatingCalDAV = false } } @SuppressLint("MissingPermission") fun getCalDAVCalendars(ids: String, showToasts: Boolean): ArrayList<CalDAVCalendar> { val calendars = ArrayList<CalDAVCalendar>() if (!context.hasPermission(PERMISSION_WRITE_CALENDAR) || !context.hasPermission(PERMISSION_READ_CALENDAR)) { return calendars } val uri = Calendars.CONTENT_URI val projection = arrayOf( Calendars._ID, Calendars.CALENDAR_DISPLAY_NAME, Calendars.ACCOUNT_NAME, Calendars.ACCOUNT_TYPE, Calendars.OWNER_ACCOUNT, Calendars.CALENDAR_COLOR, Calendars.CALENDAR_ACCESS_LEVEL ) val selection = if (ids.trim().isNotEmpty()) "${Calendars._ID} IN ($ids)" else null context.queryCursor(uri, projection, selection, showErrors = showToasts) { cursor -> val id = cursor.getIntValue(Calendars._ID) val displayName = cursor.getStringValue(Calendars.CALENDAR_DISPLAY_NAME) val accountName = cursor.getStringValue(Calendars.ACCOUNT_NAME) val accountType = cursor.getStringValue(Calendars.ACCOUNT_TYPE) val ownerName = cursor.getStringValue(Calendars.OWNER_ACCOUNT) ?: "" val color = cursor.getIntValue(Calendars.CALENDAR_COLOR) val accessLevel = cursor.getIntValue(Calendars.CALENDAR_ACCESS_LEVEL) val calendar = CalDAVCalendar(id, displayName, accountName, accountType, ownerName, color, accessLevel) calendars.add(calendar) } return calendars } fun updateCalDAVCalendar(eventType: EventType) { val uri = ContentUris.withAppendedId(Calendars.CONTENT_URI, eventType.caldavCalendarId.toLong()) val values = ContentValues().apply { val colorKey = getCalDAVColorKey(eventType) if (colorKey != null) { put(Calendars.CALENDAR_COLOR_KEY, getCalDAVColorKey(eventType)) } else { put(Calendars.CALENDAR_COLOR, eventType.color) put(Calendars.CALENDAR_COLOR_KEY, "") } put(Calendars.CALENDAR_DISPLAY_NAME, eventType.title) } try { context.contentResolver.update(uri, values, null, null) context.eventTypesDB.insertOrUpdate(eventType) } catch (e: IllegalArgumentException) { } catch (e: SecurityException) { context.showErrorToast(e) } } private fun getCalDAVColorKey(eventType: EventType): String? { val colors = getAvailableCalDAVCalendarColors(eventType) val colorKey = colors.indexOf(eventType.color) return if (colorKey > 0) { colorKey.toString() } else { null } } @SuppressLint("MissingPermission") fun getAvailableCalDAVCalendarColors(eventType: EventType): ArrayList<Int> { val colors = SparseIntArray() val uri = Colors.CONTENT_URI val projection = arrayOf(Colors.COLOR, Colors.COLOR_KEY) val selection = "${Colors.COLOR_TYPE} = ? AND ${Colors.ACCOUNT_NAME} = ?" val selectionArgs = arrayOf(Colors.TYPE_CALENDAR.toString(), eventType.caldavEmail) context.queryCursor(uri, projection, selection, selectionArgs) { cursor -> val colorKey = cursor.getIntValue(Colors.COLOR_KEY) val color = cursor.getIntValue(Colors.COLOR) colors.put(colorKey, color) } var sortedColors = ArrayList<Int>(colors.size()) (0 until colors.size()).mapTo(sortedColors) { colors[it] } if (sortedColors.isNotEmpty()) { sortedColors = sortedColors.distinct() as ArrayList<Int> } return sortedColors } @SuppressLint("MissingPermission") private fun fetchCalDAVCalendarEvents(calendarId: Int, eventTypeId: Long, showToasts: Boolean) { val importIdsMap = HashMap<String, Event>() val fetchedEventIds = ArrayList<String>() var errorFetchingLocalEvents = false val existingEvents = try { context.eventsDB.getEventsFromCalDAVCalendar("$CALDAV-$calendarId") } catch (e: Exception) { errorFetchingLocalEvents = true ArrayList() } existingEvents.forEach { importIdsMap[it.importId] = it } val uri = Events.CONTENT_URI val projection = arrayOf( Events._ID, Events.TITLE, Events.DESCRIPTION, Events.DTSTART, Events.DTEND, Events.DURATION, Events.EXDATE, Events.ALL_DAY, Events.RRULE, Events.ORIGINAL_ID, Events.ORIGINAL_INSTANCE_TIME, Events.EVENT_LOCATION, Events.EVENT_TIMEZONE, Events.CALENDAR_TIME_ZONE, Events.DELETED, Events.AVAILABILITY ) val selection = "${Events.CALENDAR_ID} = $calendarId" context.queryCursorInlined(uri, projection, selection, showErrors = showToasts) { cursor -> val deleted = cursor.getIntValue(Events.DELETED) if (deleted == 1) { return@queryCursorInlined } val id = cursor.getLongValue(Events._ID) val title = cursor.getStringValue(Events.TITLE) ?: "" if (errorFetchingLocalEvents) { context.toast(context.getString(R.string.fetching_event_failed, "\"$title\""), Toast.LENGTH_LONG) return } val description = cursor.getStringValue(Events.DESCRIPTION) ?: "" val startTS = cursor.getLongValue(Events.DTSTART) / 1000L var endTS = cursor.getLongValue(Events.DTEND) / 1000L val allDay = cursor.getIntValue(Events.ALL_DAY) val rrule = cursor.getStringValue(Events.RRULE) ?: "" val location = cursor.getStringValue(Events.EVENT_LOCATION) ?: "" val originalId = cursor.getStringValue(Events.ORIGINAL_ID) val originalInstanceTime = cursor.getLongValue(Events.ORIGINAL_INSTANCE_TIME) val reminders = getCalDAVEventReminders(id) val attendees = Gson().toJson(getCalDAVEventAttendees(id)) val availability = cursor.getIntValue(Events.AVAILABILITY) if (endTS == 0L) { val duration = cursor.getStringValue(Events.DURATION) ?: "" endTS = startTS + Parser().parseDurationSeconds(duration) } val reminder1 = reminders.getOrNull(0) val reminder2 = reminders.getOrNull(1) val reminder3 = reminders.getOrNull(2) val importId = getCalDAVEventImportId(calendarId, id) val eventTimeZone = cursor.getStringValue(Events.EVENT_TIMEZONE) ?: cursor.getStringValue(Events.CALENDAR_TIME_ZONE) ?: DateTimeZone.getDefault().id val source = "$CALDAV-$calendarId" val repeatRule = Parser().parseRepeatInterval(rrule, startTS) val event = Event( null, startTS, endTS, title, location, description, reminder1?.minutes ?: REMINDER_OFF, reminder2?.minutes ?: REMINDER_OFF, reminder3?.minutes ?: REMINDER_OFF, reminder1?.type ?: REMINDER_NOTIFICATION, reminder2?.type ?: REMINDER_NOTIFICATION, reminder3?.type ?: REMINDER_NOTIFICATION, repeatRule.repeatInterval, repeatRule.repeatRule, repeatRule.repeatLimit, ArrayList(), attendees, importId, eventTimeZone, allDay, eventTypeId, source = source, availability = availability ) if (event.getIsAllDay()) { event.toLocalAllDayEvent() } fetchedEventIds.add(importId) // if the event is an exception from another events repeat rule, find the original parent event if (originalInstanceTime != 0L) { val parentImportId = "$source-$originalId" val parentEvent = context.eventsDB.getEventWithImportId(parentImportId) val originalDayCode = Formatter.getDayCodeFromTS(originalInstanceTime / 1000L) if (parentEvent != null && !parentEvent.repetitionExceptions.contains(originalDayCode)) { val storedEventId = context.eventsDB.getEventIdWithImportId(importId) if (storedEventId != null) { event.id = storedEventId } event.parentId = parentEvent.id!! parentEvent.addRepetitionException(originalDayCode) eventsHelper.insertEvent(parentEvent, addToCalDAV = false, showToasts = false) event.parentId = parentEvent.id!! event.addRepetitionException(originalDayCode) eventsHelper.insertEvent(event, addToCalDAV = false, showToasts = false) return@queryCursorInlined } } // some calendars add repeatable event exceptions with using the "exdate" field, not by creating a child event that is an exception // exdate can be stored as "20190216T230000Z", but also as "Europe/Madrid;20201208T000000Z" val exdate = cursor.getStringValue(Events.EXDATE) ?: "" if (exdate.length > 8) { val lines = exdate.split("\n") for (line in lines) { val dates = line.split(",", ";") dates.filter { it.isNotEmpty() && it[0].isDigit() }.forEach { if (it.endsWith("Z")) { // convert for example "20190216T230000Z" to "20190217000000" in Slovakia in a weird way val formatter = DateTimeFormat.forPattern("yyyyMMdd'T'HHmmss'Z'") val offset = DateTimeZone.getDefault().getOffset(System.currentTimeMillis()) val dt = formatter.parseDateTime(it).plusMillis(offset) val dayCode = Formatter.getDayCodeFromDateTime(dt) event.repetitionExceptions.add(dayCode) } else { val potentialTS = it.substring(0, 8) if (potentialTS.areDigitsOnly()) { event.repetitionExceptions.add(potentialTS) } } } } } if (importIdsMap.containsKey(event.importId)) { val existingEvent = importIdsMap[importId] val originalEventId = existingEvent!!.id existingEvent.apply { this.id = null color = 0 lastUpdated = 0L repetitionExceptions = ArrayList() } if (existingEvent.hashCode() != event.hashCode() && title.isNotEmpty()) { event.id = originalEventId eventsHelper.updateEvent(event, updateAtCalDAV = false, showToasts = false) } } else { if (title.isNotEmpty()) { importIdsMap[event.importId] = event eventsHelper.insertEvent(event, addToCalDAV = false, showToasts = false) } } } val eventIdsToDelete = ArrayList<Long>() importIdsMap.keys.filter { !fetchedEventIds.contains(it) }.forEach { val caldavEventId = it existingEvents.forEach { event -> if (event.importId == caldavEventId) { eventIdsToDelete.add(event.id!!) } } } eventsHelper.deleteEvents(eventIdsToDelete.toMutableList(), false) } @SuppressLint("MissingPermission") fun insertCalDAVEvent(event: Event) { val uri = Events.CONTENT_URI val values = fillEventContentValues(event) val newUri = context.contentResolver.insert(uri, values) val calendarId = event.getCalDAVCalendarId() val eventRemoteID = java.lang.Long.parseLong(newUri!!.lastPathSegment!!) event.importId = getCalDAVEventImportId(calendarId, eventRemoteID) setupCalDAVEventReminders(event) setupCalDAVEventAttendees(event) setupCalDAVEventImportId(event) refreshCalDAVCalendar(event) } fun updateCalDAVEvent(event: Event) { val uri = Events.CONTENT_URI val values = fillEventContentValues(event) val eventRemoteID = event.getCalDAVEventId() event.importId = getCalDAVEventImportId(event.getCalDAVCalendarId(), eventRemoteID) val newUri = ContentUris.withAppendedId(uri, eventRemoteID) context.contentResolver.update(newUri, values, null, null) setupCalDAVEventReminders(event) setupCalDAVEventAttendees(event) setupCalDAVEventImportId(event) refreshCalDAVCalendar(event) } private fun setupCalDAVEventReminders(event: Event) { clearEventReminders(event) event.getReminders().forEach { val contentValues = ContentValues().apply { put(Reminders.MINUTES, it.minutes) put(Reminders.METHOD, if (it.type == REMINDER_EMAIL) Reminders.METHOD_EMAIL else Reminders.METHOD_ALERT) put(Reminders.EVENT_ID, event.getCalDAVEventId()) } try { context.contentResolver.insert(Reminders.CONTENT_URI, contentValues) } catch (e: Exception) { context.toast(R.string.unknown_error_occurred) } } } private fun setupCalDAVEventAttendees(event: Event) { clearEventAttendees(event) val attendees = Gson().fromJson<ArrayList<Attendee>>(event.attendees, object : TypeToken<List<Attendee>>() {}.type) ?: ArrayList() attendees.forEach { val contentValues = ContentValues().apply { put(Attendees.ATTENDEE_NAME, it.name) put(Attendees.ATTENDEE_EMAIL, it.email) put(Attendees.ATTENDEE_STATUS, it.status) put(Attendees.ATTENDEE_RELATIONSHIP, it.relationship) put(Attendees.EVENT_ID, event.getCalDAVEventId()) } try { context.contentResolver.insert(Attendees.CONTENT_URI, contentValues) } catch (e: Exception) { context.toast(R.string.unknown_error_occurred) } } } private fun setupCalDAVEventImportId(event: Event) { context.eventsDB.updateEventImportIdAndSource(event.importId, "$CALDAV-${event.getCalDAVCalendarId()}", event.id!!) } private fun fillEventContentValues(event: Event): ContentValues { return ContentValues().apply { put(Events.CALENDAR_ID, event.getCalDAVCalendarId()) put(Events.TITLE, event.title) put(Events.DESCRIPTION, event.description) put(Events.EVENT_LOCATION, event.location) put(Events.STATUS, Events.STATUS_CONFIRMED) put(Events.AVAILABILITY, event.availability) val repeatRule = Parser().getRepeatCode(event) if (repeatRule.isEmpty()) { putNull(Events.RRULE) } else { put(Events.RRULE, repeatRule) } if (event.getIsAllDay()) { event.toUtcAllDayEvent() put(Events.ALL_DAY, 1) } else { put(Events.ALL_DAY, 0) } put(Events.DTSTART, event.startTS * 1000L) put(Events.EVENT_TIMEZONE, event.getTimeZoneString()) if (event.repeatInterval > 0) { put(Events.DURATION, getDurationCode(event)) putNull(Events.DTEND) } else { put(Events.DTEND, event.endTS * 1000L) putNull(Events.DURATION) } } } private fun clearEventReminders(event: Event) { val selection = "${Reminders.EVENT_ID} = ?" val selectionArgs = arrayOf(event.getCalDAVEventId().toString()) context.contentResolver.delete(Reminders.CONTENT_URI, selection, selectionArgs) } private fun clearEventAttendees(event: Event) { val selection = "${Attendees.EVENT_ID} = ?" val selectionArgs = arrayOf(event.getCalDAVEventId().toString()) context.contentResolver.delete(Attendees.CONTENT_URI, selection, selectionArgs) } private fun getDurationCode(event: Event): String { return if (event.getIsAllDay()) { val dur = max(1, (event.endTS - event.startTS) / DAY) "P${dur}D" } else { Parser().getDurationCode((event.endTS - event.startTS) / 60L) } } fun deleteCalDAVCalendarEvents(calendarId: Long) { val eventIds = context.eventsDB.getCalDAVCalendarEvents("$CALDAV-$calendarId").toMutableList() eventsHelper.deleteEvents(eventIds, false) } fun deleteCalDAVEvent(event: Event) { val uri = Events.CONTENT_URI val contentUri = ContentUris.withAppendedId(uri, event.getCalDAVEventId()) try { context.contentResolver.delete(contentUri, null, null) } catch (ignored: Exception) { } refreshCalDAVCalendar(event) } fun insertEventRepeatException(event: Event, occurrenceTS: Long) { val uri = Events.CONTENT_URI val values = fillEventRepeatExceptionValues(event, occurrenceTS) try { context.contentResolver.insert(uri, values) refreshCalDAVCalendar(event) } catch (e: Exception) { context.showErrorToast(e) } } private fun fillEventRepeatExceptionValues(event: Event, occurrenceTS: Long): ContentValues { return ContentValues().apply { put(Events.CALENDAR_ID, event.getCalDAVCalendarId()) put(Events.DTSTART, occurrenceTS) put(Events.DTEND, occurrenceTS + (event.endTS - event.startTS)) put(Events.ORIGINAL_ID, event.getCalDAVEventId()) put(Events.EVENT_TIMEZONE, TimeZone.getDefault().id.toString()) put(Events.ORIGINAL_INSTANCE_TIME, occurrenceTS * 1000L) put(Events.EXDATE, Formatter.getDayCodeFromTS(occurrenceTS)) } } private fun getCalDAVEventReminders(eventId: Long): List<Reminder> { val reminders = ArrayList<Reminder>() val uri = Reminders.CONTENT_URI val projection = arrayOf( Reminders.MINUTES, Reminders.METHOD ) val selection = "${Reminders.EVENT_ID} = $eventId" context.queryCursor(uri, projection, selection) { cursor -> val minutes = cursor.getIntValue(Reminders.MINUTES) val method = cursor.getIntValue(Reminders.METHOD) if (method == Reminders.METHOD_ALERT || method == Reminders.METHOD_EMAIL) { val type = if (method == Reminders.METHOD_EMAIL) REMINDER_EMAIL else REMINDER_NOTIFICATION val reminder = Reminder(minutes, type) reminders.add(reminder) } } return reminders.sortedBy { it.minutes } } private fun getCalDAVEventAttendees(eventId: Long): List<Attendee> { val attendees = ArrayList<Attendee>() val uri = Attendees.CONTENT_URI val projection = arrayOf( Attendees.ATTENDEE_NAME, Attendees.ATTENDEE_EMAIL, Attendees.ATTENDEE_STATUS, Attendees.ATTENDEE_RELATIONSHIP ) val selection = "${Attendees.EVENT_ID} = $eventId" context.queryCursor(uri, projection, selection) { cursor -> val name = cursor.getStringValue(Attendees.ATTENDEE_NAME) ?: "" val email = cursor.getStringValue(Attendees.ATTENDEE_EMAIL) ?: "" val status = cursor.getIntValue(Attendees.ATTENDEE_STATUS) val relationship = cursor.getIntValue(Attendees.ATTENDEE_RELATIONSHIP) val attendee = Attendee(0, name, email, status, "", false, relationship) attendees.add(attendee) } return attendees } private fun getCalDAVEventImportId(calendarId: Int, eventId: Long) = "$CALDAV-$calendarId-$eventId" private fun refreshCalDAVCalendar(event: Event) = context.refreshCalDAVCalendars(event.getCalDAVCalendarId().toString(), false) }
gpl-3.0
25cbf450d86c115b809b27ea51254417
41.512104
154
0.611109
4.788966
false
false
false
false
phase/lang-kotlin-antlr-compiler
src/main/kotlin/xyz/jadonfowler/compiler/Compiler.kt
1
6650
package xyz.jadonfowler.compiler import org.antlr.v4.runtime.ANTLRInputStream import org.antlr.v4.runtime.CommonTokenStream import org.antlr.v4.runtime.ParserRuleContext import org.antlr.v4.runtime.RuleContext import xyz.jadonfowler.compiler.ast.Module import xyz.jadonfowler.compiler.backend.JVMBackend import xyz.jadonfowler.compiler.backend.LLVMBackend import xyz.jadonfowler.compiler.parser.LangLexer import xyz.jadonfowler.compiler.parser.LangParser import xyz.jadonfowler.compiler.pass.ConstantFoldPass import xyz.jadonfowler.compiler.pass.PrintPass import xyz.jadonfowler.compiler.pass.SemanticAnalysis import xyz.jadonfowler.compiler.pass.TypePass import xyz.jadonfowler.compiler.visitor.ASTBuilder import java.io.File val globalModules = mutableListOf<Module>() val EXTENSION = "l" fun main(args: Array<String>) { val files: MutableList<String> = mutableListOf() val options: MutableList<String> = mutableListOf() args.forEach { if (it.startsWith("--")) // This argument is an option options.add(it.substring(2, it.length)) else // This argument is a file files.add(it) } if (files.isEmpty()) { println("No input files found!") System.exit(2) } // <Name, Code> val modulesToCompile: MutableMap<String, String> = mutableMapOf() val nonStdFiles = files.size // Standard Lib val stdDirectory = File("std") if (stdDirectory.exists() && stdDirectory.isDirectory) { val stdFiles = stdDirectory.listFiles() fun addFiles(it: File) { if (it.isFile && it.extension == EXTENSION) files.add(it.canonicalPath) else if (it.isDirectory) it.listFiles().forEach(::addFiles) } stdFiles.forEach(::addFiles) } // Read files that we need to compile files.forEach { val file = File(it) if (file.exists() && !file.isDirectory) { var moduleName = file.parentFile.name + "." + file.nameWithoutExtension // Get package name var parent = file.parentFile.parentFile while (parent != null && parent.isDirectory) { val filesInParent = parent.listFiles().filter { it.extension == EXTENSION } if (filesInParent.isNotEmpty()) { moduleName = parent.name + "." + moduleName } else break parent = parent.parentFile } modulesToCompile.put(moduleName, file.readLines().joinToString("\n")) } else { println("Can't find file '$it'.") System.exit(1) } } // Go over every module and parse it val modules: List<Module> = modulesToCompile.map { compileString(it.key, it.value) } var failed = false // Default passes modules.forEach { SemanticAnalysis(it) TypePass(it) ConstantFoldPass(it) if (it.errors.size > 0) { println("Found ${it.errors.size} errors in ${it.name}:") it.errors.forEach(::println) failed = true } } if (failed) System.exit(1) // The output should be the same for no matter the order of arguments options.sort() options.forEach { when (it.toLowerCase()) { "ast" -> { // Print the AST for each input module (0..nonStdFiles - 1).forEach { println(PrintPass(modules[it]).output) } } "llvm" -> { // Output native code through LLVM Backend val bin = File("bin") if (!bin.exists()) bin.mkdirs() modules.forEach { LLVMBackend(it).output(File("bin/${it.name}")) } // Compile LLVM specific Std Modules val runtime = Runtime.getRuntime() val stdLlvmDir = File("std/llvm/") if (!stdLlvmDir.exists() || !stdLlvmDir.isDirectory) stdLlvmDir.mkdirs() val stdLlvmBin = File("bin/llvm") if (!stdLlvmBin.exists()) stdLlvmBin.mkdirs() val stdLlvmFiles = stdLlvmDir.listFiles().map { it.canonicalPath } stdLlvmFiles.forEach { val llcProcess = runtime.exec("llc $it -filetype=obj -o bin/llvm/$it.o") llcProcess.waitFor() } // Link object files together val linkCommand = modules.map { "bin/${it.name}.o" }.toMutableList() stdLlvmFiles.forEach { linkCommand.add(it) } linkCommand.add(0, "clang") linkCommand.add("-lm") linkCommand.add("-o") linkCommand.add("bin/exec/${modules[0].name}") val execDir = File("bin/exec") if (!execDir.exists()) execDir.mkdirs() val clangProcess = runtime.exec(linkCommand.joinToString(separator = " ")) println(clangProcess.waitFor()) println("Compiled Executable " + String(clangProcess.inputStream.readBytes())) println(String(clangProcess.errorStream.readBytes())) } "jvm" -> { val bin = File("bin") if (!bin.exists()) bin.mkdirs() modules.forEach { JVMBackend(it).output(File("bin/${it.name}.class")) } } } } } fun compileString(moduleName: String, code: String, explore: Boolean = false): Module { val stream = ANTLRInputStream(code) val lexer = LangLexer(stream) val tokens = CommonTokenStream(lexer) val parser = LangParser(tokens) val result = parser.program() val astBuilder = ASTBuilder(moduleName, code) if (explore) explore(result, 0) return astBuilder.visitProgram(result) } fun explore(ctx: RuleContext, indentation: Int = 0) { val ignore = ctx.childCount === 1 && ctx.getChild(0) is ParserRuleContext if (!ignore) { val ruleName = LangParser.ruleNames[ctx.ruleIndex] println(" ".repeat(indentation) + ctx.javaClass.name.split(".").last() + " " + ruleName + ":\n" + " ".repeat(indentation) + ctx.text + "\n") } (0..ctx.childCount - 1).forEach { val element = ctx.getChild(it) if (element is RuleContext) explore(element, indentation + (if (ignore) 0 else 1)) } }
mpl-2.0
d0c33d842bb62d0e6a9d12cc59e2f29c
33.816754
94
0.566767
4.306995
false
false
false
false
GunoH/intellij-community
platform/vcs-impl/src/com/intellij/ide/todo/TodoViewChangesSupportImpl.kt
7
3106
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.ide.todo import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.application.ModalityState import com.intellij.openapi.project.Project import com.intellij.openapi.vcs.ProjectLevelVcsManager import com.intellij.openapi.vcs.VcsMappingListener import com.intellij.ui.content.Content import com.intellij.ui.content.ContentManager import com.intellij.util.messages.MessageBusConnection import javax.swing.JTree class TodoViewChangesSupportImpl : TodoViewChangesSupport() { override fun isContentVisible(project: Project): Boolean { return ProjectLevelVcsManager.getInstance(project).hasActiveVcss() } override fun getTabName(project: Project): String { return ChangeListTodosPanel.getTabName(project) } override fun createPanel(project: Project, settings: TodoPanelSettings, content: Content, factory: TodoTreeBuilderFactory): TodoPanel { return object : ChangeListTodosPanel(project, settings, content) { override fun createTreeBuilder(tree: JTree, project: Project): TodoTreeBuilder { val builder = factory.createTreeBuilder(tree, project) builder.init() return builder } } } override fun createPanel(project: Project, settings: TodoPanelSettings, content: Content): TodoPanel { return createPanel(project, settings, content, TodoTreeBuilderFactory { tree, p -> ChangeListTodosTreeBuilder(tree, p) }) } override fun installListener(project: Project, connection: MessageBusConnection, contentManagerFunc: () -> ContentManager?, contentFunc: () -> Content): Listener { val listener = MyVcsListener(project, contentManagerFunc, contentFunc) connection.subscribe(ProjectLevelVcsManager.VCS_CONFIGURATION_CHANGED, listener) return listener } private class MyVcsListener( private val project: Project, private val contentManagerFunc: () -> ContentManager?, private val contentFunc: () -> Content) : VcsMappingListener, Listener { private var myIsVisible = false override fun setVisible(value: Boolean) { myIsVisible = value } override fun directoryMappingChanged() { ApplicationManager.getApplication().invokeLater( { val contentManager = contentManagerFunc() if (contentManager == null || project.isDisposed) { // was not initialized yet return@invokeLater } val content = contentFunc() val hasActiveVcss = ProjectLevelVcsManager.getInstance(project).hasActiveVcss() if (myIsVisible && !hasActiveVcss) { contentManager.removeContent(content, false) myIsVisible = false } else if (!myIsVisible && hasActiveVcss) { contentManager.addContent(content) myIsVisible = true } }, ModalityState.NON_MODAL) } } }
apache-2.0
098593c1042200743a97b0740ad7d22b
37.8375
140
0.703155
5.075163
false
false
false
false
smmribeiro/intellij-community
plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/codeInspection/untypedUnresolvedAccess/requests/CreateMethodFromGroovyUsageRequest.kt
7
1756
// 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 org.jetbrains.plugins.groovy.codeInspection.untypedUnresolvedAccess.requests import com.intellij.lang.jvm.JvmModifier import com.intellij.lang.jvm.actions.CreateMethodRequest import com.intellij.lang.jvm.actions.ExpectedType import com.intellij.lang.jvm.actions.expectedType import com.intellij.lang.jvm.actions.expectedTypes import com.intellij.psi.PsiType import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrMethodCall import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrReferenceExpression import org.jetbrains.plugins.groovy.lang.psi.expectedTypes.GroovyExpectedTypesProvider import org.jetbrains.plugins.groovy.lang.resolve.api.Argument import org.jetbrains.plugins.groovy.lang.resolve.impl.getArguments internal class CreateMethodFromGroovyUsageRequest( methodCall: GrMethodCall, modifiers: Collection<JvmModifier> ) : CreateExecutableFromGroovyUsageRequest<GrMethodCall>(methodCall, modifiers), CreateMethodRequest { override fun getArguments(): List<Argument>? { return call.getArguments() } override fun isValid() = super.isValid() && call.let { getRefExpression()?.referenceName != null } private fun getRefExpression() = call.invokedExpression as? GrReferenceExpression override fun getMethodName() = getRefExpression()?.referenceName!! override fun getReturnType() : List<ExpectedType> { val expected = GroovyExpectedTypesProvider.getDefaultExpectedTypes(call) if (expected.isEmpty()) { return expectedTypes(PsiType.VOID) } return expected.map { expectedType(it, ExpectedType.Kind.EXACT) } } }
apache-2.0
3fc54fa2c7d44f87da2995537525de5d
42.9
140
0.805239
4.479592
false
false
false
false
smmribeiro/intellij-community
platform/lang-impl/src/com/intellij/ide/bookmark/actions/NodeMoveAction.kt
4
2749
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.ide.bookmark.actions import com.intellij.ide.bookmark.BookmarksManagerImpl import com.intellij.ide.bookmark.ui.tree.BookmarkNode import com.intellij.ide.bookmark.ui.tree.GroupNode import com.intellij.openapi.actionSystem.* import com.intellij.openapi.project.DumbAwareAction import com.intellij.openapi.wm.ToolWindowId import com.intellij.ui.UIBundle.messagePointer import com.intellij.util.ui.tree.TreeUtil import java.util.function.Supplier internal class NodeMoveUpAction : NodeMoveAction(false, messagePointer("move.up.action.name")) internal class NodeMoveDownAction : NodeMoveAction(true, messagePointer("move.down.action.name")) internal abstract class NodeMoveAction(val next: Boolean, dynamicText: Supplier<String>) : DumbAwareAction(dynamicText) { override fun update(event: AnActionEvent) = with(event.presentation) { isEnabledAndVisible = process(event, false) if (!isVisible) isVisible = !ActionPlaces.isPopupPlace(event.place) } override fun actionPerformed(event: AnActionEvent) { process(event, true) } private fun process(event: AnActionEvent, perform: Boolean): Boolean { val manager = event.bookmarksManager as? BookmarksManagerImpl ?: return false val tree = event.bookmarksViewFromToolWindow?.tree ?: return false val path = TreeUtil.getSelectedPathIfOne(tree) val node1 = TreeUtil.getAbstractTreeNode(path) val node2 = TreeUtil.getAbstractTreeNode(when { next -> TreeUtil.nextVisibleSibling(tree, path) else -> TreeUtil.previousVisibleSibling(tree, path) }) return when { node1 is GroupNode && node2 is GroupNode -> { val group1 = node1.value ?: return false val group2 = node2.value ?: return false if (group1.isDefault || group2.isDefault) return false if (perform) manager.move(group1, group2) true } node1 is BookmarkNode && node2 is BookmarkNode -> { val group = node1.bookmarkGroup ?: return false if (group != node2.bookmarkGroup) return false val bookmark1 = node1.value ?: return false val bookmark2 = node2.value ?: return false if (perform) manager.move(group, bookmark1, bookmark2) true } else -> false } } } internal class NodeMoveActionPromoter : ActionPromoter { override fun suppress(actions: List<AnAction>, context: DataContext) = when { context.getData(PlatformDataKeys.TOOL_WINDOW)?.id != ToolWindowId.BOOKMARKS -> null actions.none { it is NodeMoveAction } -> null else -> actions.filter { it !is NodeMoveAction } } }
apache-2.0
7068d221632612ec51346dbb70940e18
42.634921
158
0.733358
4.262016
false
false
false
false
smmribeiro/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/RedundantInnerClassModifierInspection.kt
1
9193
// 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.codeInspection.* import com.intellij.openapi.project.Project import com.intellij.psi.PsiClass import com.intellij.psi.PsiElement import com.intellij.psi.search.searches.ReferencesSearch import com.intellij.psi.util.parentsOfType import org.jetbrains.kotlin.descriptors.CallableDescriptor import org.jetbrains.kotlin.descriptors.ClassDescriptor import org.jetbrains.kotlin.descriptors.ClassifierDescriptor import org.jetbrains.kotlin.idea.KotlinBundle import org.jetbrains.kotlin.idea.caches.resolve.analyze import org.jetbrains.kotlin.idea.caches.resolve.resolveToCall import org.jetbrains.kotlin.idea.caches.resolve.util.getJavaClassDescriptor import org.jetbrains.kotlin.idea.core.ShortenReferences import org.jetbrains.kotlin.idea.intentions.receiverType import org.jetbrains.kotlin.idea.references.mainReference import org.jetbrains.kotlin.idea.search.usagesSearch.descriptor import org.jetbrains.kotlin.idea.util.getThisReceiverOwner import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.* import org.jetbrains.kotlin.resolve.BindingContext import org.jetbrains.kotlin.resolve.calls.callUtil.getResolvedCall import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameOrNull import org.jetbrains.kotlin.resolve.descriptorUtil.isSubclassOf import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode import org.jetbrains.kotlin.synthetic.SyntheticJavaPropertyDescriptor import org.jetbrains.kotlin.utils.addToStdlib.safeAs class RedundantInnerClassModifierInspection : AbstractKotlinInspection() { override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean) = classVisitor(fun(targetClass) { val innerModifier = targetClass.modifierList?.getModifier(KtTokens.INNER_KEYWORD) ?: return if (targetClass.containingClassOrObject.safeAs<KtObjectDeclaration>()?.isObjectLiteral() == true) return val outerClasses = targetClass.parentsOfType<KtClass>().dropWhile { it == targetClass }.toSet() if (outerClasses.isEmpty() || outerClasses.any { it.isLocal || it.isInner() }) return if (targetClass.hasOuterClassMemberReference(outerClasses)) return holder.registerProblem( innerModifier, KotlinBundle.message("inspection.redundant.inner.class.modifier.descriptor"), ProblemHighlightType.LIKE_UNUSED_SYMBOL, RemoveInnerModifierFix() ) }) private fun KtClass.hasOuterClassMemberReference(outerClasses: Set<KtClass>): Boolean { val targetClass = this val outerClassDescriptors by lazy { val context = targetClass.analyze(BodyResolveMode.PARTIAL) outerClasses.mapNotNull { context[BindingContext.DECLARATION_TO_DESCRIPTOR, it] as? ClassDescriptor } } val hasSuperType = outerClasses.any { it.getSuperTypeList() != null } return anyDescendantOfType<KtExpression> { expression -> when (expression) { is KtNameReferenceExpression -> { val reference = expression.mainReference.resolve()?.let { (it as? KtConstructor<*>)?.containingClass() ?: it } if (reference is PsiClass && reference.parent is PsiClass) { return@anyDescendantOfType reference.getJavaClassDescriptor()?.isInner == true } if (reference is KtObjectDeclaration || (reference as? KtDeclaration)?.containingClassOrObject is KtObjectDeclaration) { return@anyDescendantOfType false } val referenceContainingClass = reference?.getStrictParentOfType<KtClass>() if (referenceContainingClass != null) { if (referenceContainingClass == targetClass) return@anyDescendantOfType false if (referenceContainingClass in outerClasses) { val parentQualified = (expression.parent as? KtCallExpression ?: expression).getQualifiedExpressionForSelector() if (parentQualified != null && !parentQualified.hasThisReceiverOfOuterClass(outerClassDescriptors)) { val receiverTypeOfReference = reference.receiverTypeReference() if (receiverTypeOfReference == null) { return@anyDescendantOfType false } else { val context = parentQualified.analyze(BodyResolveMode.PARTIAL) val receiverOwnerType = parentQualified.getResolvedCall(context)?.dispatchReceiver ?.getThisReceiverOwner(context)?.safeAs<CallableDescriptor>()?.receiverType() if (receiverOwnerType == context[BindingContext.TYPE, receiverTypeOfReference]) { return@anyDescendantOfType false } } } return@anyDescendantOfType reference !is KtClass || reference.isInner() } } if (!hasSuperType) return@anyDescendantOfType false val referenceClassDescriptor = referenceContainingClass?.descriptor as? ClassDescriptor ?: reference?.getStrictParentOfType<PsiClass>()?.getJavaClassDescriptor() ?: (expression.resolveToCall()?.resultingDescriptor as? SyntheticJavaPropertyDescriptor) ?.getMethod?.containingDeclaration as? ClassDescriptor ?: return@anyDescendantOfType false outerClassDescriptors.any { outer -> outer.isSubclassOf(referenceClassDescriptor) } } is KtThisExpression -> expression.referenceClassDescriptor() in outerClassDescriptors else -> false } } } private fun KtQualifiedExpression.hasThisReceiverOfOuterClass(outerClassDescriptors: List<ClassDescriptor>): Boolean { return parent !is KtQualifiedExpression && receiverExpression is KtThisExpression && receiverExpression.referenceClassDescriptor() in outerClassDescriptors } private fun KtExpression.referenceClassDescriptor(): ClassifierDescriptor? { return resolveToCall()?.resultingDescriptor?.returnType?.constructor?.declarationDescriptor } private fun PsiElement.receiverTypeReference(): KtTypeReference? { return safeAs<KtNamedFunction>()?.receiverTypeReference ?: safeAs<KtProperty>()?.receiverTypeReference } private class RemoveInnerModifierFix : LocalQuickFix { override fun getName() = KotlinBundle.message("remove.redundant.0.modifier", KtTokens.INNER_KEYWORD.value) override fun getFamilyName() = name override fun applyFix(project: Project, descriptor: ProblemDescriptor) { val targetClass = descriptor.psiElement.getStrictParentOfType<KtClass>() ?: return val fixedElements = fixReceiverOnCallSite(targetClass) targetClass.removeModifier(KtTokens.INNER_KEYWORD) fixedElements.filterIsInstance<KtQualifiedExpression>().forEach { ShortenReferences.DEFAULT.process(it) } } private fun fixReceiverOnCallSite(targetClass: KtClass): List<PsiElement> { val containingClass = targetClass.getStrictParentOfType<KtClass>() ?: return emptyList() val bindingContext = containingClass.analyze(BodyResolveMode.PARTIAL) val fqName = bindingContext[BindingContext.DECLARATION_TO_DESCRIPTOR, containingClass]?.fqNameOrNull()?.asString() ?: return emptyList() val psiFactory = KtPsiFactory(targetClass) val newReceiver = psiFactory.createExpression(fqName) return ReferencesSearch.search(targetClass, targetClass.useScope).mapNotNull { val callExpression = it.element.parent as? KtCallExpression ?: return@mapNotNull null val qualifiedExpression = callExpression.getQualifiedExpressionForSelector() val parentClass = callExpression.getStrictParentOfType<KtClass>() when { // Explicit receiver qualifiedExpression != null -> if (parentClass == containingClass) { qualifiedExpression.replace(callExpression) } else { qualifiedExpression.receiverExpression.replace(newReceiver) } // Implicit receiver else -> callExpression.replace(psiFactory.createExpressionByPattern("$0.$1", newReceiver, callExpression)) } } } } }
apache-2.0
6e21ab3e0cdefff162e9348766b206e0
58.694805
158
0.665506
6.379598
false
false
false
false
smmribeiro/intellij-community
platform/platform-impl/src/com/intellij/diagnostic/hprof/util/HeapReportUtils.kt
10
2758
/* * Copyright (C) 2019 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.intellij.diagnostic.hprof.util import org.jetbrains.annotations.NonNls import java.util.Locale object HeapReportUtils { private val SI_PREFIXES = charArrayOf('K', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y') // Kilo, Mega, Giga, Peta, etc. const val STRING_PADDING_FOR_COUNT = 5 const val STRING_PADDING_FOR_SIZE = STRING_PADDING_FOR_COUNT + 1 const val SECTION_HEADER_SIZE = 50 fun toShortStringAsCount(count: Long): String { return toShortString(count) } fun toPaddedShortStringAsCount(count: Long): String { return toShortString(count).padStart(STRING_PADDING_FOR_COUNT) } fun toShortStringAsSize(size: Long): String { return toShortString(size) + "B" } fun toPaddedShortStringAsSize(size: Long): String { return toShortStringAsSize(size).padStart(STRING_PADDING_FOR_SIZE) } fun sectionHeader(@NonNls name: String): String { val uppercaseName = name.toUpperCase(Locale.US) return if (uppercaseName.length >= SECTION_HEADER_SIZE - 2) { uppercaseName } else { StringBuilder().apply { append("=".repeat((SECTION_HEADER_SIZE - uppercaseName.length) / 2)) append(" $uppercaseName ") append("=".repeat((SECTION_HEADER_SIZE - uppercaseName.length - 1) / 2)) }.toString() } } /** * @return String representing {@code num} with 3 most significant digits using SI prefixes. * <p> * Examples: 12 returns "12", 12345 returns "12.3K", 123456789 returns "123M" */ private fun toShortString(num: Long): String { var shiftCount = 0 var localNum = num while (localNum >= 1000) { shiftCount++ localNum /= 10 } if (shiftCount > 0) { val siPrefixIndex = (shiftCount - 1) / 3 assert(siPrefixIndex < SI_PREFIXES.size) val suffix = SI_PREFIXES[siPrefixIndex] val value = when (shiftCount % 3) { 0 -> localNum.toString() 1 -> (localNum.toDouble() / 100).toString() 2 -> (localNum.toDouble() / 10).toString() else -> { assert(false); "????" } } return value + suffix } return localNum.toString() } }
apache-2.0
6874e22e6788e3590241ae26b09b60a7
31.081395
111
0.659898
3.798898
false
false
false
false
cy6erGn0m/kotlin-frontend-plugin
kotlin-frontend/src/main/kotlin/org/jetbrains/kotlin/gradle/frontend/servers/AbstractStartStopTask.kt
1
4528
package org.jetbrains.kotlin.gradle.frontend.servers import net.rubygrapefruit.platform.* import org.gradle.api.* import org.gradle.api.tasks.* import org.jetbrains.kotlin.gradle.frontend.util.* import java.io.* import java.util.concurrent.* /** * @author Sergey Mashkov */ abstract class AbstractStartStopTask<S : Any> : DefaultTask() { @get:Internal open val startupTimeoutSeconds: Int = project.findProperty("org.kotlin.frontend.startup.timeout")?.toString()?.toInt() ?: 30 @get:Internal open val shutdownTimeoutSeconds: Int = project.findProperty("org.kotlin.frontend.shutdown.timeout")?.toString()?.toInt() ?: 30 @get:Internal protected abstract val identifier: String protected abstract fun checkIsRunning(stopInfo: S?): Boolean protected abstract fun builder(): ProcessBuilder protected abstract fun beforeStart(): S? protected abstract fun stop(state: S?) protected open fun needRestart(oldState: S?, newState: S?) = oldState != newState protected abstract fun readState(file: File): S? protected abstract fun writeState(file: File, state: S) protected open fun notRunningThenKilledMessage(): Unit = logger.error("$identifier: startup timeout") protected open fun notRunningExitCodeMessage(exitCode: Int): Unit = logger.error("$identifier: exited with exit code $exitCode") protected open fun alreadyRunningMessage(): Unit = logger.warn("$identifier is already running") protected open fun needRestartMessage(): Unit = logger.warn("$identifier needs restart") protected open fun startedMessage(): Unit = logger.warn("$identifier started") protected open fun stoppedMessage(): Unit = logger.warn("$identifier stopped") fun serverLog() = serverLog(project.buildDir.resolve("logs")) protected open fun serverLog(logsDir: File): File = logsDir.resolve("$identifier.log") protected open val stateFile: File get() = project.buildDir.resolve(".run-$identifier.txt") protected fun doStart() { val oldStopInfo = tryReadState(stateFile) val newState = beforeStart() if (checkIsRunning(oldStopInfo)) { if (needRestart(oldStopInfo, newState)) { needRestartMessage() doStop() } else { alreadyRunningMessage() return } } stateFile.delete() serverLog().let { it.delete() it.parentFile.mkdirsOrFail() } val launcher = Native.get(ProcessLauncher::class.java)!! val builder = builder() .redirectErrorStream(true) .redirectOutput(serverLog()) .addCommandPathToSystemPath() if (logger.isDebugEnabled) { logger.debug("Running ${builder.command().joinToString(" ")}") } val process = launcher.start(builder) for (i in 1..startupTimeoutSeconds.times(2).coerceAtLeast(1)) { if (process.waitFor(500, TimeUnit.MILLISECONDS)) { break } if (checkIsRunning(newState)) { break } } if (!checkIsRunning(newState)) { if (process.isAlive) { process.destroyForcibly() notRunningThenKilledMessage() } else { notRunningExitCodeMessage(process.exitValue()) } throw GradleException("$identifier startup failed") } if (newState != null) { try { writeState(stateFile, newState) } catch (t: Throwable) { stateFile.delete() throw t } } startedMessage() } protected fun doStop() { val state = tryReadState(stateFile) if (!checkIsRunning(state)) { logger.info("$identifier: Not running") return } for (i in 1..shutdownTimeoutSeconds.div(2).coerceAtLeast(1)) { stop(state) if (!checkIsRunning(state)) { break } Thread.sleep(500) } if (checkIsRunning(state)) { logger.error("Failed to stop $identifier: still running") } else { stoppedMessage() stateFile.delete() } } private fun tryReadState(stateFile: File): S? = try { if (stateFile.canRead()) readState(stateFile) else null } catch (e: IOException) { null } }
apache-2.0
7c666be4e7bfb3b5b9dfb4c292bfbc0e
31.342857
132
0.603799
4.786469
false
false
false
false
excref/kotblog
blog/service/core/src/main/kotlin/com/excref/kotblog/blog/service/post/domain/Post.kt
1
1001
package com.excref.kotblog.blog.service.post.domain import com.excref.kotblog.blog.service.blog.domain.Blog import com.excref.kotblog.blog.service.category.domain.Category import com.excref.kotblog.blog.service.common.UuidAwareDomain import com.excref.kotblog.blog.service.tag.domain.Tag import javax.persistence.* /** * @author Rafayel Mirzoyan * @since 6/10/17 6:59 PM */ @Entity class Post( @Column(name = "title", nullable = false) val title: String, @Column(name = "content", nullable = false) val content: String, @OneToOne(optional = false, fetch = FetchType.LAZY) @JoinColumn(name = "blog_id", nullable = false) val blog: Blog, @OneToMany(cascade = arrayOf(CascadeType.ALL)) @JoinColumn(name = "tag_id") val tags: List<Tag> = listOf(), @OneToMany(cascade = arrayOf(CascadeType.ALL)) @JoinColumn(name = "category_id") var categories: List<Category> = listOf() ) : UuidAwareDomain()
apache-2.0
26ea133713cdb5926a8e42961ef0919a
30.3125
63
0.671329
3.64
false
false
false
false
prof18/RSS-Parser
samplekotlin/src/main/java/com/prof/rssparser/sample/kotlin/ArticleAdapter.kt
1
4827
/* * Copyright 2016 Marco Gomiero * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.prof.rssparser.sample.kotlin import android.annotation.SuppressLint import android.text.method.LinkMovementMethod import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.webkit.WebChromeClient import android.webkit.WebView import android.widget.ImageView import android.widget.TextView import androidx.recyclerview.widget.RecyclerView import com.prof.rssparser.Article import com.squareup.picasso.Picasso import java.text.SimpleDateFormat import java.util.* class ArticleAdapter(private var articles: List<Article>) : RecyclerView.Adapter<ArticleAdapter.ViewHolder>() { override fun onCreateViewHolder(parent: ViewGroup, viewType: Int) = ViewHolder(LayoutInflater.from(parent.context).inflate(R.layout.row, parent, false)) override fun getItemCount() = articles.size override fun onBindViewHolder(holder: ArticleAdapter.ViewHolder, position: Int) = holder.bind(articles[position]) fun clearArticles() { articles = emptyList() notifyDataSetChanged() } inner class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) { private val title = itemView.findViewById<TextView>(R.id.title) private val pubDate = itemView.findViewById<TextView>(R.id.pubDate) private val categoriesText = itemView.findViewById<TextView>(R.id.categories) private val image = itemView.findViewById<ImageView>(R.id.image) @SuppressLint("SetJavaScriptEnabled") fun bind(article: Article) { var pubDateString = article.pubDate try { val sourceDateString = article.pubDate val sourceSdf = SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss Z", Locale.ENGLISH) if (sourceDateString != null) { val date = sourceSdf.parse(sourceDateString) if (date != null) { val sdf = SimpleDateFormat("dd MMMM yyyy", Locale.getDefault()) pubDateString = sdf.format(date) } } } catch (e: Exception) { e.printStackTrace() } title.text = article.title Picasso.get() .load(article.image) .placeholder(R.drawable.placeholder) .into(image) pubDate.text = pubDateString var categories = "" for (i in 0 until article.categories.size) { categories = if (i == article.categories.size - 1) { categories + article.categories[i] } else { categories + article.categories[i] + ", " } } categoriesText.text = categories itemView.setOnClickListener { //show article content inside a dialog val articleView = WebView(itemView.context) articleView.settings.loadWithOverviewMode = true articleView.settings.javaScriptEnabled = true articleView.isHorizontalScrollBarEnabled = false articleView.webChromeClient = WebChromeClient() articleView.loadDataWithBaseURL( null, "<style>img{display: inline; height: auto; max-width: 100%;} " + "</style>\n" + "<style>iframe{ height: auto; width: auto;}" + "</style>\n" + article.content, null, "utf-8", null ) val alertDialog = androidx.appcompat.app.AlertDialog.Builder(itemView.context).create() alertDialog.setTitle(article.title) alertDialog.setView(articleView) alertDialog.setButton( androidx.appcompat.app.AlertDialog.BUTTON_NEUTRAL, "OK" ) { dialog, _ -> dialog.dismiss() } alertDialog.show() (alertDialog.findViewById<View>(android.R.id.message) as TextView).movementMethod = LinkMovementMethod.getInstance() } } } }
apache-2.0
7a16a8420115c86254d615ded69116b1
36.71875
121
0.609488
4.960946
false
false
false
false
koma-im/koma
src/main/kotlin/link/continuum/desktop/database/util.kt
1
3768
package link.continuum.database import io.requery.Persistable import io.requery.kotlin.eq import io.requery.kotlin.findAttribute import io.requery.sql.KotlinConfiguration import io.requery.sql.KotlinEntityDataStore import io.requery.sql.SchemaModifier import io.requery.sql.TableCreationMode import kotlinx.serialization.json.Json import link.continuum.database.models.Membership import link.continuum.database.models.Models import link.continuum.desktop.database.models.meta.DbColumns import mu.KotlinLogging import org.h2.jdbcx.JdbcConnectionPool import org.h2.jdbcx.JdbcDataSource import java.io.File import kotlin.time.ExperimentalTime import kotlin.time.TimeSource.Monotonic as MonoClock import link.continuum.desktop.database.models.meta.Models as DbModels private val logger = KotlinLogging.logger {} private val jsonConfiguration = Json { ignoreUnknownKeys = true prettyPrint = true prettyPrintIndent= " " } internal val jsonMain = (jsonConfiguration) /** * find and open database */ @ExperimentalTime fun loadDesktopDatabase(dir: File): KotlinEntityDataStore<Persistable>{ val desktop = dir.resolve("desktop") desktop.mkdirs() val dbPath = desktop.resolve("continuum-desktop").canonicalPath val db = openStore(dbPath) return db } @ExperimentalTime fun openStore(dbPath: String, level: Int=1): KotlinEntityDataStore<Persistable> { val mark = MonoClock.markNow() val dataSource = JdbcDataSource() dataSource.setURL("jdbc:h2:$dbPath;TRACE_LEVEL_FILE=0;TRACE_LEVEL_SYSTEM_OUT=$level") val dataSourcePool = JdbcConnectionPool.create(dataSource) val conf = KotlinConfiguration(dataSource = dataSourcePool, model = Models.DEFAULT) val s = KotlinEntityDataStore<Persistable>(conf) logger.trace { "opening db takes ${mark.elapsedNow()}"} val sm = SchemaModifier(conf) getDbColumns(dataSourcePool).let { columns -> logger.trace { "opening db and getting columns takes ${mark.elapsedNow()}"} val addedTypes = Models.DEFAULT.types.filterNot { columns.contains(it.name.toLowerCase()) } if (addedTypes.isNotEmpty()) { logger.info { "creating tables of ${addedTypes.map { it.name }}"} sm.createTables(TableCreationMode.CREATE_NOT_EXISTS) } } addMissingColumn(getDbColumns(dataSourcePool), sm) return s } private fun getDbColumns(dataSource: JdbcConnectionPool): Map<String, HashSet<String>> { val s0 = KotlinEntityDataStore<Persistable>( KotlinConfiguration(dataSource = dataSource, model = DbModels.H2INFO) ) val existingColumns = hashMapOf<String, HashSet<String>>() val c = DbColumns::tableSchema.eq("PUBLIC") s0.select(DbColumns::class) .where(c) .get().forEach { existingColumns.computeIfAbsent(it.tableName.toLowerCase()) { hashSetOf() }.add(it.columnName.toLowerCase()) } return existingColumns } private fun addMissingColumn( existingColumns: Map<String, HashSet<String>>, modifier: SchemaModifier ) { arrayOf(Membership::since, Membership::joiningRoom ).map { findAttribute(it) }.filter { val t = it.declaringType.name val typeColumns = existingColumns[t.toLowerCase()] check(typeColumns != null) { "Table $t unknown" } val c = it.name if (!typeColumns.contains(c.toLowerCase())) { logger.debug { "column $c of $t has not been added"} true } else { false } }.forEach { attribute -> logger.debug { "adding column '${attribute.name}' to table ${attribute.declaringType.name}"} modifier.addColumn(attribute) } }
gpl-3.0
1b0ddc03d1dc36d4d30cf7ac503381a2
33.898148
100
0.696125
4.262443
false
false
false
false
breadwallet/breadwallet-android
app/src/main/java/com/breadwallet/ui/scanner/ScannerController.kt
1
5603
/** * BreadWallet * * Created by Drew Carlson <[email protected]> on 8/13/19. * Copyright (c) 2019 breadwallet LLC * * 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.breadwallet.ui.scanner import android.Manifest import android.content.Intent import android.content.pm.PackageManager import android.os.Bundle import android.view.View import androidx.core.content.ContextCompat import com.breadwallet.R import com.breadwallet.breadbox.BreadBox import com.breadwallet.databinding.ControllerScannerBinding import com.breadwallet.logger.logDebug import com.breadwallet.logger.logError import com.breadwallet.tools.qrcode.scannedText import com.breadwallet.tools.util.BRConstants import com.breadwallet.tools.util.Link import com.breadwallet.tools.util.asLink import com.breadwallet.ui.BaseController import com.breadwallet.ui.MainActivity import com.breadwallet.util.CryptoUriParser import kotlinx.coroutines.Dispatchers.Default import kotlinx.coroutines.Dispatchers.Main import kotlinx.coroutines.delay import kotlinx.coroutines.flow.flowOn import kotlinx.coroutines.flow.launchIn import kotlinx.coroutines.flow.mapLatest import kotlinx.coroutines.flow.onEach import kotlinx.coroutines.flow.take import kotlinx.coroutines.flow.transformLatest import org.kodein.di.erased.instance private const val CAMERA_UI_UPDATE_MS = 100L class ScannerController( args: Bundle? = null ) : BaseController(args) { interface Listener { fun onLinkScanned(link: Link) fun onRawTextScanned(text: String) = Unit } private val breadBox by instance<BreadBox>() private val uriParser by instance<CryptoUriParser>() private val binding by viewBinding(ControllerScannerBinding::inflate) override fun onAttach(view: View) { super.onAttach(view) val context = checkNotNull(applicationContext) val cameraPermission = ContextCompat.checkSelfPermission(context, Manifest.permission.CAMERA) if (cameraPermission == PackageManager.PERMISSION_GRANTED) { startScanner(breadBox, uriParser) } else { requestPermissions( arrayOf(Manifest.permission.CAMERA), BRConstants.CAMERA_REQUEST_ID ) } } override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) { super.onRequestPermissionsResult(requestCode, permissions, grantResults) if (requestCode == BRConstants.CAMERA_REQUEST_ID) { when (grantResults.singleOrNull()) { PackageManager.PERMISSION_GRANTED -> startScanner(breadBox, uriParser) PackageManager.PERMISSION_DENIED, null -> router.popController(this) } } } private fun startScanner(breadBox: BreadBox, uriParser: CryptoUriParser) { binding.qrdecoderview .scannedText(true) .mapLatest { text -> text to text.asLink(breadBox, uriParser, scanned = true) } .flowOn(Default) .transformLatest { (text, link) -> if (link == null) { logError("Found incompatible QR code") showGuideError() } else { logDebug("Found compatible QR code") binding.scanGuide.setImageResource(R.drawable.cameraguide) emit(text to link) } } .take(1) .onEach { (text, link) -> handleValidLink(text, link) } .flowOn(Main) .launchIn(viewAttachScope) } private fun handleValidLink(text: String, link: Link) { // Try calling the targetController to handle the link, // if no listener handles it, dispatch to MainActivity. val consumed: Unit? = findListener<Listener>()?.run { onRawTextScanned(text) onLinkScanned(link) } if (consumed == null) { Intent(applicationContext, MainActivity::class.java) .addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP) .putExtra(MainActivity.EXTRA_DATA, text) .run(this::startActivity) } router.popController(this@ScannerController) } /** Display an error state for [CAMERA_UI_UPDATE_MS] then reset. */ private suspend fun showGuideError() { binding.scanGuide.setImageResource(R.drawable.cameraguide_red) delay(CAMERA_UI_UPDATE_MS) binding.scanGuide.setImageResource(R.drawable.cameraguide) } }
mit
bc74db2db9dbe7cf4a88756b3c6b711a
38.457746
119
0.693557
4.665279
false
false
false
false
aosp-mirror/platform_frameworks_support
room/compiler/src/main/kotlin/androidx/room/solver/query/result/PojoRowAdapter.kt
1
6336
/* * Copyright (C) 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 androidx.room.solver.query.result import androidx.room.ext.L import androidx.room.ext.S import androidx.room.ext.T import androidx.room.processor.Context import androidx.room.processor.ProcessorErrors import androidx.room.solver.CodeGenScope import androidx.room.verifier.QueryResultInfo import androidx.room.vo.Field import androidx.room.vo.FieldWithIndex import androidx.room.vo.Pojo import androidx.room.vo.RelationCollector import androidx.room.vo.Warning import androidx.room.writer.FieldReadWriteWriter import com.squareup.javapoet.TypeName import stripNonJava import javax.lang.model.type.TypeMirror /** * Creates the entity from the given info. * <p> * The info comes from the query processor so we know about the order of columns in the result etc. */ class PojoRowAdapter( context: Context, private val info: QueryResultInfo?, val pojo: Pojo, out: TypeMirror) : RowAdapter(out) { val mapping: Mapping val relationCollectors: List<RelationCollector> init { // toMutableList documentation is not clear if it copies so lets be safe. val remainingFields = pojo.fields.mapTo(mutableListOf(), { it }) val unusedColumns = arrayListOf<String>() val matchedFields: List<Field> if (info != null) { matchedFields = info.columns.mapNotNull { column -> // first check remaining, otherwise check any. maybe developer wants to map the same // column into 2 fields. (if they want to post process etc) val field = remainingFields.firstOrNull { it.columnName == column.name } ?: pojo.fields.firstOrNull { it.columnName == column.name } if (field == null) { unusedColumns.add(column.name) null } else { remainingFields.remove(field) field } } if (unusedColumns.isNotEmpty() || remainingFields.isNotEmpty()) { val warningMsg = ProcessorErrors.cursorPojoMismatch( pojoTypeName = pojo.typeName, unusedColumns = unusedColumns, allColumns = info.columns.map { it.name }, unusedFields = remainingFields, allFields = pojo.fields ) context.logger.w(Warning.CURSOR_MISMATCH, null, warningMsg) } val nonNulls = remainingFields.filter { it.nonNull } if (nonNulls.isNotEmpty()) { context.logger.e(ProcessorErrors.pojoMissingNonNull( pojoTypeName = pojo.typeName, missingPojoFields = nonNulls.map { it.name }, allQueryColumns = info.columns.map { it.name })) } if (matchedFields.isEmpty()) { context.logger.e(ProcessorErrors.CANNOT_FIND_QUERY_RESULT_ADAPTER) } } else { matchedFields = remainingFields.map { it } remainingFields.clear() } relationCollectors = RelationCollector.createCollectors(context, pojo.relations) mapping = Mapping( matchedFields = matchedFields, unusedColumns = unusedColumns, unusedFields = remainingFields ) } fun relationTableNames(): List<String> { return relationCollectors.flatMap { val queryTableNames = it.loadAllQuery.tables.map { it.name } if (it.rowAdapter is PojoRowAdapter) { it.rowAdapter.relationTableNames() + queryTableNames } else { queryTableNames } }.distinct() } override fun onCursorReady(cursorVarName: String, scope: CodeGenScope) { relationCollectors.forEach { it.writeInitCode(scope) } mapping.fieldsWithIndices = mapping.matchedFields.map { val indexVar = scope.getTmpVar("_cursorIndexOf${it.name.stripNonJava().capitalize()}") val indexMethod = if (info == null) { "getColumnIndex" } else { "getColumnIndexOrThrow" } scope.builder().addStatement("final $T $L = $L.$L($S)", TypeName.INT, indexVar, cursorVarName, indexMethod, it.columnName) FieldWithIndex(field = it, indexVar = indexVar, alwaysExists = info != null) } } override fun convert(outVarName: String, cursorVarName: String, scope: CodeGenScope) { scope.builder().apply { FieldReadWriteWriter.readFromCursor( outVar = outVarName, outPojo = pojo, cursorVar = cursorVarName, fieldsWithIndices = mapping.fieldsWithIndices, relationCollectors = relationCollectors, scope = scope) } } override fun onCursorFinished(): ((CodeGenScope) -> Unit)? = if (relationCollectors.isEmpty()) { // it is important to return empty to notify that we don't need any post process // task null } else { { scope -> relationCollectors.forEach { collector -> collector.writeCollectionCode(scope) } } } data class Mapping( val matchedFields: List<Field>, val unusedColumns: List<String>, val unusedFields: List<Field>) { // set when cursor is ready. lateinit var fieldsWithIndices: List<FieldWithIndex> } }
apache-2.0
a9610f78289d1e1dd2280f009deb4343
39.356688
100
0.59959
4.977219
false
false
false
false
fossasia/rp15
app/src/fdroid/java/org/fossasia/openevent/general/search/location/GeoLocationViewModel.kt
1
1180
package org.fossasia.openevent.general.search.location import androidx.lifecycle.LiveData import androidx.lifecycle.ViewModel import io.reactivex.disposables.CompositeDisposable import io.reactivex.rxkotlin.plusAssign import org.fossasia.openevent.general.common.SingleLiveEvent import java.lang.IllegalArgumentException class GeoLocationViewModel(private val locationService: LocationService) : ViewModel() { private val mutableLocation = SingleLiveEvent<String>() val location: LiveData<String> = mutableLocation private val mutableErrorMessage = SingleLiveEvent<String>() val errorMessage: LiveData<String> = mutableErrorMessage private val compositeDisposable = CompositeDisposable() fun configure() { compositeDisposable += locationService.getAdministrativeArea() .subscribe({ mutableLocation.value = it }, { mutableErrorMessage.value = if (it is IllegalArgumentException) "No area found" else "Something went wrong" }) } override fun onCleared() { super.onCleared() compositeDisposable.clear() } }
apache-2.0
5073c17ff8c0047707833f279bccd1bb
37.064516
95
0.70678
5.673077
false
false
false
false
Austin72/Charlatano
src/main/kotlin/com/charlatano/scripts/Trigger.kt
1
1211
/* * Charlatano: Free and open-source (FOSS) cheat for CS:GO/CS:CO * Copyright (C) 2017 - Thomas G. P. Nappo, Jonathan Beaudoin * * 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 com.charlatano.scripts import com.charlatano.game.entity.EntityType import com.charlatano.game.forEntities import com.charlatano.game.me import com.charlatano.settings.TRIGGER_DURATION import com.charlatano.utils.every fun trigger() = every(TRIGGER_DURATION) { forEntities { val entity = it.entity if (entity <= 0 || me == entity || it.type != EntityType.CCSPlayer) return@forEntities } }
agpl-3.0
bb79c0511c188765a0d6b47f8b112efd
34.647059
88
0.748968
3.893891
false
false
false
false
EMResearch/EvoMaster
core/src/test/kotlin/org/evomaster/core/search/impact/impactinfocollection/individual/IndividualGeneImpactTest.kt
1
16599
package org.evomaster.core.search.impact.impactinfocollection.individual import org.evomaster.core.EMConfig import org.evomaster.core.output.EvaluatedIndividualBuilder.Companion.generateIndividualResults import org.evomaster.core.search.* import org.evomaster.core.search.gene.Gene import org.evomaster.core.search.gene.numeric.IntegerGene import org.evomaster.core.search.gene.string.StringGene import org.evomaster.core.search.impact.impactinfocollection.ImpactUtils import org.evomaster.core.search.service.Randomness import org.evomaster.core.search.service.mutator.EvaluatedMutation import org.evomaster.core.search.service.mutator.MutatedGeneSpecification import org.evomaster.core.search.tracer.TraceableElementCopyFilter import org.evomaster.core.search.tracer.TrackOperator import org.junit.jupiter.api.Test import org.junit.jupiter.api.Assertions.* /** * created by manzh on 2019-12-05 */ class IndividualGeneImpactTest { @Test fun testCompleteInitializationImpactUpdate(){ val simulatedMutator = SimulatedMutator() simulatedMutator.config.abstractInitializationGeneToMutate = false val evi_ind1 = simulatedMutator.getFakeEvaluatedIndividualWithInitialization(initActionSize = 0) val addedInit = IndAction.getSeqIndInitAction(templates = arrayOf(2,3), repeat = arrayOf(1,3)) evi_ind1.initAddedInitializationGenes(addedInit,0) assertNotNull(evi_ind1.impactInfo) assertEquals(2*(1+1) + 3*(3+1), evi_ind1.getInitializationGeneImpact().size) } @Test fun testAbstractInitializationImpactUpdate(){ val simulatedMutator = SimulatedMutator() simulatedMutator.config.abstractInitializationGeneToMutate = true val evi_ind1 = simulatedMutator.getFakeEvaluatedIndividualWithInitialization(initActionSize = 0) val addedInit = IndAction.getSeqIndInitAction(templates = arrayOf(2,3), repeat = arrayOf(1,3)) evi_ind1.initAddedInitializationGenes(addedInit,0) assertNotNull(evi_ind1.impactInfo) assertEquals(5, evi_ind1.getInitializationGeneImpact().size) } @Test fun testGeneImpactUpdate(){ val simulatedMutator = SimulatedMutator() val config = EMConfig() val evi_ind1 = simulatedMutator.getFakeEvaluatedIndividual() evi_ind1.wrapWithTracking(null, 10, mutableListOf(evi_ind1.copy(TraceableElementCopyFilter.WITH_ONLY_EVALUATED_RESULT))) assert(evi_ind1.getSizeOfImpact(fromInitialization = false) == 2) val mutatedIndex = 1 val spec = MutatedGeneSpecification() val evi_ind2 = simulatedMutator.fakeMutator(evi_ind1, mutatedIndex, spec, 1) assert(spec.mutatedIndividual != null) assert(spec.mutatedGenes.size == 1) val mutatedGeneId = ImpactUtils.generateGeneId(spec.mutatedIndividual!!, spec.mutatedGenes.first().gene!!) val evaluatedTargets = mutableMapOf<Int, EvaluatedMutation>() evaluatedTargets[simulatedMutator.getNewTarget()] = EvaluatedMutation.BETTER_THAN evi_ind1.fitness.computeDifference( other = evi_ind2.fitness, targetSubset = simulatedMutator.getInitialTargets(), targetInfo = evaluatedTargets, config = config ) val improvedTarget = evaluatedTargets.filter { it.value == EvaluatedMutation.BETTER_THAN } val impactTarget = evaluatedTargets.filter { it.value != EvaluatedMutation.EQUAL_WITH } assertEquals(2, impactTarget.size) assertEquals(2, improvedTarget.size) assert(improvedTarget.keys.containsAll(setOf(2,3))) assert(impactTarget.keys.containsAll(setOf(2,3))) val tracked_evi_ind2 = evi_ind1.next( next = evi_ind2, copyFilter = TraceableElementCopyFilter.WITH_ONLY_EVALUATED_RESULT, evaluatedResult = EvaluatedMutation.BETTER_THAN ) assert(tracked_evi_ind2 != null) tracked_evi_ind2!!.updateImpactOfGenes( previous = evi_ind1, mutated = tracked_evi_ind2, mutatedGenes = spec, targetsInfo = evaluatedTargets ) assert(tracked_evi_ind2.getSizeOfImpact(false) == 2) val evi_ind1impactInfo = evi_ind1.getImpactOfFixedAction(mutatedIndex, false) assert(evi_ind1impactInfo!= null) val ind1impact = evi_ind1impactInfo!![mutatedGeneId] assert(ind1impact != null) assert(ind1impact!!.getTimesOfImpacts().containsKey(2)) assert(ind1impact.getTimesOfImpacts().containsKey(3)) val tracked_evi_ind2impactInfo = tracked_evi_ind2.getImpactOfFixedAction(mutatedIndex, false) assert(tracked_evi_ind2impactInfo!=null) val ind2impact = tracked_evi_ind2impactInfo!![mutatedGeneId] val tracked_evi_ind2impactInfo_otheer = tracked_evi_ind2.getImpactOfFixedAction(0, false) assert(tracked_evi_ind2impactInfo_otheer!=null) val ind2impactdifAction = tracked_evi_ind2impactInfo_otheer!![mutatedGeneId] assert(ind2impact != null) assert(ind1impact.shared == ind2impact!!.shared) assert(ind2impact.getTimesOfImpacts().containsKey(2)) assert(ind2impact.getTimesOfImpacts().containsKey(3)) assert(ind2impactdifAction != null) assert(ind2impactdifAction!!.getTimesOfImpacts().isEmpty()) assert(ind2impactdifAction.getTimesToManipulate() == 0) } @Test fun testGeneImpactUpdateByStructureMutator(){ val simulatedMutator = SimulatedMutator() val evi_ind1 = simulatedMutator.getFakeEvaluatedIndividual() evi_ind1.wrapWithTracking(null, 10, mutableListOf(evi_ind1.copy(TraceableElementCopyFilter.WITH_ONLY_EVALUATED_RESULT))) assert(evi_ind1.getSizeOfImpact(false) == 2) val mutatedIndex = 1 val spec = MutatedGeneSpecification() val evi_ind2 = simulatedMutator.fakeStructureMutator(evi_ind1, mutatedIndex, true, spec, 1) val evaluatedTargets = mutableMapOf<Int, EvaluatedMutation>() evaluatedTargets[simulatedMutator.getNewTarget()] = EvaluatedMutation.BETTER_THAN evi_ind1.fitness.computeDifference( other = evi_ind2.fitness, targetSubset = simulatedMutator.getInitialTargets(), targetInfo = evaluatedTargets, config = EMConfig() ) val improvedTarget = evaluatedTargets.filter { it.value == EvaluatedMutation.BETTER_THAN } val impactTarget = evaluatedTargets.filter { it.value != EvaluatedMutation.EQUAL_WITH } assertEquals(2, impactTarget.size) assertEquals(2, improvedTarget.size) assert(improvedTarget.keys.containsAll(setOf(2,3))) assert(impactTarget.keys.containsAll(setOf(2,3))) val tracked_evi_ind2 = evi_ind1.next( next = evi_ind2, copyFilter = TraceableElementCopyFilter.WITH_ONLY_EVALUATED_RESULT, evaluatedResult = EvaluatedMutation.BETTER_THAN ) assert(tracked_evi_ind2 != null) tracked_evi_ind2!!.updateImpactOfGenes( previous = evi_ind1, mutated = evi_ind2, mutatedGenes = spec, targetsInfo = evaluatedTargets ) assertEquals(1, tracked_evi_ind2.getSizeOfImpact(false)) } class SimulatedMutator :TrackOperator{ val config = EMConfig() init { config.enableTrackEvaluatedIndividual = true //config.probOfArchiveMutation = 0.5 config.doCollectImpact = true } fun fakeMutator(evaluatedIndividual: EvaluatedIndividual<Ind>, mutatedIndex : Int, mutatedGeneSpecification: MutatedGeneSpecification, index: Int) : EvaluatedIndividual<Ind>{ val ind2 = evaluatedIndividual.individual.copy() as Ind val mutatedGene = (ind2.seeFixedMainActions()[mutatedIndex].seeTopGenes()[1] as StringGene) mutatedGeneSpecification.addMutatedGene( isDb = false, isInit = false, position = mutatedIndex, localId = null, valueBeforeMutation = mutatedGene.value, gene = mutatedGene ) mutatedGene.value = "mutated_index2" mutatedGeneSpecification.setMutatedIndividual(ind2) val fv2 = evaluatedIndividual.fitness.copy() fv2.updateTarget(getNewTarget(), 0.5, mutatedIndex) fv2.updateTarget(getExistingImprovedTarget(), 0.5, mutatedIndex) return EvaluatedIndividual(fv2, ind2, generateIndividualResults(ind2), index = index) } fun fakeStructureMutator(evaluatedIndividual: EvaluatedIndividual<Ind>, mutatedIndex : Int, remove: Boolean, mutatedGeneSpecification: MutatedGeneSpecification, index : Int) : EvaluatedIndividual<Ind>{ val ind2 = evaluatedIndividual.individual.copy() as Ind if (ind2.seeFixedMainActions().size == 1 && remove) throw IllegalArgumentException("action cannot be removed since there is only one action") if (remove){ val removedAction = ind2.seeFixedMainActions()[mutatedIndex] mutatedGeneSpecification.addRemovedOrAddedByAction( removedAction, mutatedIndex, localId = null, true,mutatedIndex ) //ind2.actions.removeAt(mutatedIndex) ind2.killChildByIndex(mutatedIndex) }else{ val action = IndAction.getIndMainAction(1).first() mutatedGeneSpecification.addRemovedOrAddedByAction( action, mutatedIndex, localId = null, false,mutatedIndex ) //ind2.actions.add(mutatedIndex, action) ind2.addChild(mutatedIndex, action) } mutatedGeneSpecification.setMutatedIndividual(ind2) val fv2 = evaluatedIndividual.fitness.copy() val actionIndex = if (remove){ if (mutatedIndex - 1 >=0) mutatedIndex - 1 else mutatedIndex + 1 }else{ mutatedIndex } fv2.updateTarget(getNewTarget(), 0.5, actionIndex) fv2.updateTarget(getExistingImprovedTarget(), 0.5, actionIndex) return EvaluatedIndividual(fv2, ind2, generateIndividualResults(ind2), index = index) } fun getNewTarget() = 3 fun getExistingImprovedTarget() = 2 fun getInitialTargets() = setOf(1,2) fun getFakeEvaluatedIndividual() : EvaluatedIndividual<Ind>{ val ind1 = Ind.getInd() val fv1 = FitnessValue(ind1.seeAllActions().size.toDouble()) fv1.updateTarget(id = 1, value = 0.1, actionIndex = 0) fv1.updateTarget(id = 2, value = 0.1, actionIndex = 1) return EvaluatedIndividual( fitness = fv1, individual = ind1, results = generateIndividualResults(ind1), trackOperator = this, config = config) } fun getFakeEvaluatedIndividualWithInitialization(actionSize: Int = 2, initActionSize: Int) : EvaluatedIndividual<Ind>{ val ind1 = Ind.getIndWithInitialization(actionSize, initActionSize) val fv1 = FitnessValue(actionSize.toDouble()) fv1.updateTarget(id = 1, value = 0.1, actionIndex = 0) fv1.updateTarget(id = 2, value = 0.1, actionIndex = 1) return EvaluatedIndividual( fitness = fv1, individual = ind1, results = generateIndividualResults(ind1), trackOperator = this, config = config) } } class Ind(actions : MutableList<IndMainAction>, initialization : MutableList<IndInitAction> = mutableListOf()) : Individual(children = initialization.plus(actions).toMutableList()){ companion object{ fun getInd() : Ind{ return Ind(IndAction.getIndMainAction(2).toMutableList()).apply { this.doInitializeLocalId() } } fun getIndWithInitialization(actionSize: Int, initializationSize: Int) : Ind{ return Ind(IndAction.getIndMainAction(actionSize).toMutableList(), IndAction.getSeqIndInitAction(initializationSize).toMutableList()) .apply { this.doInitializeLocalId() } } } override fun copyContent(): Individual { return Ind(children.filterIsInstance<IndMainAction>().map { it.copy() as IndMainAction }.toMutableList(), children.filterIsInstance<IndInitAction>().map { it.copy() as IndInitAction }.toMutableList()) } override fun seeGenes(filter: GeneFilter): List<out Gene> { return when(filter){ GeneFilter.ONLY_SQL -> seeInitializingActions().flatMap(Action::seeTopGenes) GeneFilter.NO_SQL -> seeAllActions().flatMap(Action::seeTopGenes) GeneFilter.ALL -> seeInitializingActions().plus(seeAllActions()).flatMap(Action::seeTopGenes) else -> throw IllegalArgumentException("$filter is not supported by ImpactTest Individual") } } override fun size(): Int = seeAllActions().size override fun verifyInitializationActions(): Boolean { return true } override fun repairInitializationActions(randomness: Randomness) {} } abstract class IndAction(genes : List<out Gene>) : Action(genes){ companion object{ fun getIndMainAction(size: Int = 1): List<IndMainAction>{ if(size < 1) throw IllegalArgumentException("size should be at least 1, but $size") return (0 until size).map { IndMainAction(listOf( StringGene("index1","index1"), StringGene("index2", "index2") )) .apply { doInitialize(Randomness().apply { updateSeed(42) }) }} } fun getSeqIndInitAction(size : Int) : List<IndInitAction>{ if(size < 0) throw IllegalArgumentException("size should not be less than 0, but $size") if (size == 0) return listOf() return (0 until size).map { IndInitAction(listOf( IntegerGene( name = "index$it", value = it ) )) } } fun getSeqIndInitAction(templates : Array<Int>, repeat : Array<Int>) : List<List<IndInitAction>>{ if(templates.any { it < 1 }) throw IllegalArgumentException("size of template should be at least 1") if (repeat.any { it < 0 }) throw IllegalArgumentException("repeat times should not be less than 0") if (templates.size != repeat.size) throw IllegalArgumentException("size of the configuration for template and repeat should be same") val actions = mutableListOf<List<IndInitAction>>() templates.forEachIndexed { t, i -> (0..repeat[t]).forEach { _-> actions.add((0 until i).map { IndInitAction(listOf( IntegerGene( name = "index$t$it", value = it ) )) }) } } return actions } } override fun getName(): String { return seeTopGenes().joinToString(",") { it.name } } override fun seeTopGenes(): List<out Gene> { return children.filterIsInstance<Gene>() } // override fun copyContent(): Action { // return IndAction(genes.map { it.copy() }) // } override fun shouldCountForFitnessEvaluations(): Boolean = true } class IndMainAction(genes: List<out Gene>) : IndAction(genes){ override fun copyContent(): Action { return IndMainAction(seeTopGenes().map { it.copy() }) } } class IndInitAction(genes: List<out Gene>) : IndAction(genes){ override fun copyContent(): Action { return IndInitAction(seeTopGenes().map { it.copy() }) } } }
lgpl-3.0
497195cb16fb67cbee2cf59bfa29a560
39.786241
209
0.627146
4.618531
false
false
false
false
cretz/asmble
compiler/src/main/kotlin/asmble/compile/jvm/CompileErr.kt
1
4491
package asmble.compile.jvm import asmble.AsmErr import java.util.* sealed class CompileErr(message: String, cause: Throwable? = null) : RuntimeException(message, cause), AsmErr { class StackMismatch( val expected: Array<out TypeRef>, val actual: TypeRef? ) : CompileErr("Expected any type of ${Arrays.toString(expected)}, got $actual") { override val asmErrString get() = "type mismatch" override val asmErrStrings get() = listOf(asmErrString, "mismatching label") } class StackInjectionMismatch( val injectBackwardsCount: Int, val attemptedInsn: Insn ) : CompileErr("Unable to inject $attemptedInsn back $injectBackwardsCount stack values") { override val asmErrString get() = "type mismatch" } class BlockEndMismatch( val expectedStack: List<TypeRef>, val actualStack: List<TypeRef> ) : CompileErr("At block end, expected stack $expectedStack, got $actualStack") { override val asmErrString get() = "type mismatch" } class SelectMismatch( val value1: TypeRef, val value2: TypeRef ) : CompileErr("Select values $value1 and $value2 are not the same type") { override val asmErrString get() = "type mismatch" } class TableTargetMismatch( val defaultTypes: List<TypeRef>, val targetTypes: List<TypeRef> ) : CompileErr("Table jump target has types $targetTypes, but default has $defaultTypes") { override val asmErrString get() = "type mismatch" } class GlobalConstantMismatch( val index: Int, val expected: TypeRef, val actual: TypeRef ) : CompileErr("Global $index expected const of type $expected, got $actual") { override val asmErrString get() = "type mismatch" } class IfThenValueWithoutElse : CompileErr("If has value but no else clause") { override val asmErrString get() = "type mismatch" } class UnusedStackOnReturn( val leftover: List<TypeRef> ) : CompileErr("Expected empty stack on return, still leftover with: $leftover") { override val asmErrString get() = "type mismatch" } class NoBlockAtDepth( val attemptedDepth: Int ) : CompileErr("Attempted to access block at depth $attemptedDepth, but not there") { override val asmErrString get() = "unknown label" } class UnknownFunc( val index: Int ) : CompileErr("Unknown function at index $index") { override val asmErrString get() = "unknown function $index" } class UnknownLocal( val index: Int ) : CompileErr("Unknown local at index $index") { override val asmErrString get() = "unknown local" } class UnknownGlobal( val index: Int ) : CompileErr("Unknown global at index $index") { override val asmErrString get() = "unknown global" } class UnknownMemory(val index: Int) : CompileErr("No memory present at index $index") { override val asmErrString get() = "unknown memory $index" } class UnknownTable(val index: Int) : CompileErr("No table present at index $index") { override val asmErrString get() = "unknown table" override val asmErrStrings get() = listOf(asmErrString, "unknown table $index") } class UnknownType(val index: Int) : CompileErr("No type present for index $index") { override val asmErrString get() = "unknown type" } class SetImmutableGlobal( val index: Int ) : CompileErr("Attempting to set global $index which is immutable") { override val asmErrString get() = "global is immutable" } class GlobalInitNotConstant( val index: Int ) : CompileErr("Expected init for global $index to be single constant value") { override val asmErrString get() = "constant expression required" override val asmErrStrings get() = listOf(asmErrString, "type mismatch") } class OffsetNotConstant : CompileErr("Expected offset to be constant") { override val asmErrString get() = "constant expression required" } class InvalidStartFunctionType( val index: Int ) : CompileErr("Start function at $index must take no params and return nothing") { override val asmErrString get() = "start function" } class DuplicateExport(val name: String) : CompileErr("Duplicate export '$name'") { override val asmErrString get() = "duplicate export name" } }
mit
02206c2087be5c83ac59743b8a571c81
34.936
111
0.6611
4.415929
false
false
false
false
frendyxzc/KotlinNews
model/src/main/java/vip/frendy/model/router/Router.kt
1
857
package vip.frendy.model.router import android.app.Activity import android.content.Intent /** * Created by frend on 2017/6/8. */ object Router { val NEWS_DETAIL_ACTIVITY = "vip.frendy.news.DetailActivity" val NEWS_URL: String = "url" val VIDEO_DETAIL_ACTIVITY = "vip.frendy.video.DetailActivity" val VIDEO_PATH: String = "videoPath" val VIDEO_TITLE: String = "videoTitle" fun intentToNewsDetail(activity: Activity, url: String) { val intent = Intent(NEWS_DETAIL_ACTIVITY) intent.putExtra(NEWS_URL, url) activity.startActivity(intent) } fun intentToVideoDetail(activity: Activity, path: String, title: String) { val intent = Intent(VIDEO_DETAIL_ACTIVITY) intent.putExtra(VIDEO_PATH, path) intent.putExtra(VIDEO_TITLE, title) activity.startActivity(intent) } }
mit
77b408dbee95d7257bc17e539358964d
28.586207
78
0.688448
3.77533
false
false
false
false
duftler/orca
orca-queue/src/test/kotlin/com/netflix/spinnaker/orca/q/handler/RunTaskHandlerTest.kt
1
59367
/* * Copyright 2017 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License") * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.spinnaker.orca.q.handler import com.netflix.spectator.api.NoopRegistry import com.netflix.spinnaker.kork.dynamicconfig.DynamicConfigService import com.netflix.spinnaker.orca.ExecutionStatus.CANCELED import com.netflix.spinnaker.orca.ExecutionStatus.FAILED_CONTINUE import com.netflix.spinnaker.orca.ExecutionStatus.PAUSED import com.netflix.spinnaker.orca.ExecutionStatus.RUNNING import com.netflix.spinnaker.orca.ExecutionStatus.SKIPPED import com.netflix.spinnaker.orca.ExecutionStatus.STOPPED import com.netflix.spinnaker.orca.ExecutionStatus.SUCCEEDED import com.netflix.spinnaker.orca.ExecutionStatus.TERMINAL import com.netflix.spinnaker.orca.StageResolver import com.netflix.spinnaker.orca.TaskExecutionInterceptor import com.netflix.spinnaker.orca.TaskResult import com.netflix.spinnaker.orca.api.SimpleStage import com.netflix.spinnaker.orca.exceptions.ExceptionHandler import com.netflix.spinnaker.orca.fixture.pipeline import com.netflix.spinnaker.orca.fixture.stage import com.netflix.spinnaker.orca.fixture.task import com.netflix.spinnaker.orca.pipeline.DefaultStageDefinitionBuilderFactory import com.netflix.spinnaker.orca.pipeline.RestrictExecutionDuringTimeWindow import com.netflix.spinnaker.orca.pipeline.model.DefaultTrigger import com.netflix.spinnaker.orca.pipeline.model.Execution.ExecutionType.PIPELINE import com.netflix.spinnaker.orca.pipeline.model.Execution.PausedDetails import com.netflix.spinnaker.orca.pipeline.model.Stage import com.netflix.spinnaker.orca.pipeline.model.Stage.STAGE_TIMEOUT_OVERRIDE_KEY import com.netflix.spinnaker.orca.pipeline.persistence.ExecutionRepository import com.netflix.spinnaker.orca.pipeline.util.ContextParameterProcessor import com.netflix.spinnaker.orca.pipeline.util.StageNavigator import com.netflix.spinnaker.orca.q.CompleteTask import com.netflix.spinnaker.orca.q.DummyTask import com.netflix.spinnaker.orca.q.DummyCloudProviderAwareTask import com.netflix.spinnaker.orca.q.DummyTimeoutOverrideTask import com.netflix.spinnaker.orca.q.InvalidTask import com.netflix.spinnaker.orca.q.InvalidTaskType import com.netflix.spinnaker.orca.q.PauseTask import com.netflix.spinnaker.orca.q.RunTask import com.netflix.spinnaker.orca.q.singleTaskStage import com.netflix.spinnaker.q.Queue import com.netflix.spinnaker.spek.and import com.netflix.spinnaker.time.fixedClock import com.nhaarman.mockito_kotlin.any import com.nhaarman.mockito_kotlin.anyOrNull import com.nhaarman.mockito_kotlin.check import com.nhaarman.mockito_kotlin.doReturn import com.nhaarman.mockito_kotlin.doThrow import com.nhaarman.mockito_kotlin.eq import com.nhaarman.mockito_kotlin.isA import com.nhaarman.mockito_kotlin.mock import com.nhaarman.mockito_kotlin.never import com.nhaarman.mockito_kotlin.reset import com.nhaarman.mockito_kotlin.verify import com.nhaarman.mockito_kotlin.verifyZeroInteractions import com.nhaarman.mockito_kotlin.whenever import org.assertj.core.api.Assertions.assertThat import org.jetbrains.spek.api.dsl.describe import org.jetbrains.spek.api.dsl.given import org.jetbrains.spek.api.dsl.it import org.jetbrains.spek.api.dsl.on import org.jetbrains.spek.api.lifecycle.CachingMode.GROUP import org.jetbrains.spek.subject.SubjectSpek import org.threeten.extra.Minutes import java.time.Duration import kotlin.collections.first import kotlin.collections.forEach import kotlin.collections.hashMapOf import kotlin.collections.listOf import kotlin.collections.mapOf import kotlin.collections.set import kotlin.collections.setOf import kotlin.reflect.jvm.jvmName object RunTaskHandlerTest : SubjectSpek<RunTaskHandler>({ val queue: Queue = mock() val repository: ExecutionRepository = mock() val stageNavigator: StageNavigator = mock() val task: DummyTask = mock() val cloudProviderAwareTask: DummyCloudProviderAwareTask = mock() val timeoutOverrideTask: DummyTimeoutOverrideTask = mock() val exceptionHandler: ExceptionHandler = mock() val clock = fixedClock() val contextParameterProcessor = ContextParameterProcessor() val dynamicConfigService: DynamicConfigService = mock() val taskExecutionInterceptors: List<TaskExecutionInterceptor> = listOf(mock()) val stageResolver = StageResolver(emptyList(), emptyList<SimpleStage<Object>>()) subject(GROUP) { RunTaskHandler( queue, repository, stageNavigator, DefaultStageDefinitionBuilderFactory(stageResolver), contextParameterProcessor, listOf(task, timeoutOverrideTask, cloudProviderAwareTask), clock, listOf(exceptionHandler), taskExecutionInterceptors, NoopRegistry(), dynamicConfigService ) } fun resetMocks() = reset(queue, repository, task, timeoutOverrideTask, cloudProviderAwareTask, exceptionHandler) describe("running a task") { describe("that completes successfully") { val pipeline = pipeline { stage { type = "whatever" task { id = "1" startTime = clock.instant().toEpochMilli() } } } val stage = pipeline.stages.first() val message = RunTask(pipeline.type, pipeline.id, "foo", stage.id, "1", DummyTask::class.java) and("has no context updates outputs") { val taskResult = TaskResult.SUCCEEDED beforeGroup { taskExecutionInterceptors.forEach { whenever(it.beforeTaskExecution(task, stage)) doReturn stage } taskExecutionInterceptors.forEach { whenever(it.afterTaskExecution(task, stage, taskResult)) doReturn taskResult } whenever(task.execute(any())) doReturn taskResult whenever(repository.retrieve(PIPELINE, message.executionId)) doReturn pipeline } afterGroup(::resetMocks) action("the handler receives a message") { subject.handle(message) } it("executes the task") { verify(task).execute(pipeline.stages.first()) } it("completes the task") { verify(queue).push(check<CompleteTask> { assertThat(it.status).isEqualTo(SUCCEEDED) }) } it("does not update the stage or global context") { verify(repository, never()).storeStage(any()) } } and("has context updates") { val stageOutputs = mapOf("foo" to "covfefe") val taskResult = TaskResult.builder(SUCCEEDED).context(stageOutputs).build() beforeGroup { taskExecutionInterceptors.forEach { whenever(it.beforeTaskExecution(task, stage)) doReturn stage } taskExecutionInterceptors.forEach { whenever(it.afterTaskExecution(task, stage, taskResult)) doReturn taskResult } whenever(task.execute(any())) doReturn taskResult whenever(repository.retrieve(PIPELINE, message.executionId)) doReturn pipeline } afterGroup(::resetMocks) action("the handler receives a message") { subject.handle(message) } it("updates the stage context") { verify(repository).storeStage(check { assertThat(stageOutputs).isEqualTo(it.context) }) } } and("has outputs") { val outputs = mapOf("foo" to "covfefe") val taskResult = TaskResult.builder(SUCCEEDED).outputs(outputs).build() beforeGroup { taskExecutionInterceptors.forEach { whenever(it.beforeTaskExecution(task, stage)) doReturn stage } taskExecutionInterceptors.forEach { whenever(it.afterTaskExecution(task, stage, taskResult)) doReturn taskResult } whenever(task.execute(any())) doReturn taskResult whenever(repository.retrieve(PIPELINE, message.executionId)) doReturn pipeline } afterGroup(::resetMocks) action("the handler receives a message") { subject.handle(message) } it("updates the stage outputs") { verify(repository).storeStage(check { assertThat(it.outputs).isEqualTo(outputs) }) } } and("outputs a stageTimeoutMs value") { val outputs = mapOf( "foo" to "covfefe", "stageTimeoutMs" to Long.MAX_VALUE ) val taskResult = TaskResult.builder(SUCCEEDED).outputs(outputs).build() beforeGroup { taskExecutionInterceptors.forEach { whenever(it.beforeTaskExecution(task, stage)) doReturn stage } taskExecutionInterceptors.forEach { whenever(it.afterTaskExecution(task, stage, taskResult)) doReturn taskResult } whenever(task.execute(any())) doReturn taskResult whenever(repository.retrieve(PIPELINE, message.executionId)) doReturn pipeline } afterGroup(::resetMocks) action("the handler receives a message") { subject.handle(message) } it("does not write stageTimeoutMs to outputs") { verify(repository).storeStage(check { assertThat(it.outputs) .containsKey("foo") .doesNotContainKey("stageTimeoutMs") }) } } } describe("that is not yet complete") { val pipeline = pipeline { stage { type = "whatever" task { id = "1" startTime = clock.instant().toEpochMilli() } } } val stage = pipeline.stages.first() val message = RunTask(pipeline.type, pipeline.id, "foo", stage.id, "1", DummyTask::class.java) val taskResult = TaskResult.RUNNING val taskBackoffMs = 30_000L val maxBackOffLimit = 120_000L beforeGroup { taskExecutionInterceptors.forEach { whenever(it.maxTaskBackoff()) doReturn maxBackOffLimit } taskExecutionInterceptors.forEach { whenever(it.beforeTaskExecution(task, stage)) doReturn stage } taskExecutionInterceptors.forEach { whenever(it.afterTaskExecution(task, stage, taskResult)) doReturn taskResult } whenever(task.execute(any())) doReturn taskResult whenever(task.getDynamicBackoffPeriod(any(), any())) doReturn taskBackoffMs whenever(dynamicConfigService.getConfig(eq(Long::class.java), eq("tasks.global.backOffPeriod"), any())) doReturn 0L whenever(repository.retrieve(PIPELINE, message.executionId)) doReturn pipeline } afterGroup(::resetMocks) action("the handler receives a message") { subject.handle(message) } it("re-queues the command") { verify(queue).push(message, Duration.ofMillis(taskBackoffMs)) } } setOf(TERMINAL, CANCELED).forEach { taskStatus -> describe("that fails with $taskStatus") { val pipeline = pipeline { stage { refId = "1" type = "whatever" task { id = "1" startTime = clock.instant().toEpochMilli() } } } val stage = pipeline.stages.first() val message = RunTask(pipeline.type, pipeline.id, "foo", stage.id, "1", DummyTask::class.java) val taskResult = TaskResult.ofStatus(taskStatus) and("no overrides are in place") { beforeGroup { taskExecutionInterceptors.forEach { whenever(it.beforeTaskExecution(task, stage)) doReturn stage } taskExecutionInterceptors.forEach { whenever(it.afterTaskExecution(task, stage, taskResult)) doReturn taskResult } whenever(task.execute(any())) doReturn taskResult whenever(repository.retrieve(PIPELINE, message.executionId)) doReturn pipeline } afterGroup(::resetMocks) action("the handler receives a message") { subject.handle(message) } it("marks the task $taskStatus") { verify(queue).push(check<CompleteTask> { assertThat(it.status).isEqualTo(taskStatus) }) } } and("the task should not fail the whole pipeline, only the branch") { beforeGroup { pipeline.stageByRef("1").apply { context["failPipeline"] = false context["continuePipeline"] = false } whenever(task.execute(any())) doReturn taskResult whenever(repository.retrieve(PIPELINE, message.executionId)) doReturn pipeline } afterGroup(::resetMocks) afterGroup { pipeline.stages.first().context.clear() } action("the handler receives a message") { subject.handle(message) } it("marks the task STOPPED") { verify(queue).push(check<CompleteTask> { assertThat(it.status).isEqualTo(STOPPED) }) } } and("the task should allow the pipeline to proceed") { beforeGroup { pipeline.stageByRef("1").apply { context["failPipeline"] = false context["continuePipeline"] = true } whenever(task.execute(any())) doReturn taskResult whenever(repository.retrieve(PIPELINE, message.executionId)) doReturn pipeline } afterGroup(::resetMocks) afterGroup { pipeline.stages.first().context.clear() } action("the handler receives a message") { subject.handle(message) } it("marks the task FAILED_CONTINUE") { verify(queue).push(check<CompleteTask> { assertThat(it.status).isEqualTo(FAILED_CONTINUE) }) } } } } describe("that throws an exception") { val pipeline = pipeline { stage { refId = "1" type = "whatever" task { id = "1" startTime = clock.instant().toEpochMilli() } } } val stage = pipeline.stages.first() val message = RunTask(pipeline.type, pipeline.id, "foo", stage.id, "1", DummyTask::class.java) val taskResult = TaskResult.ofStatus(TERMINAL) and("it is not recoverable") { val exceptionDetails = ExceptionHandler.Response( RuntimeException::class.qualifiedName, "o noes", ExceptionHandler.responseDetails("o noes"), false ) and("the task should fail the pipeline") { beforeGroup { taskExecutionInterceptors.forEach { whenever(it.beforeTaskExecution(task, stage)) doReturn stage } taskExecutionInterceptors.forEach { whenever(it.afterTaskExecution(task, stage, taskResult)) doThrow RuntimeException("o noes") } whenever(task.execute(any())) doThrow RuntimeException("o noes") whenever(repository.retrieve(PIPELINE, message.executionId)) doReturn pipeline whenever(exceptionHandler.handles(any())) doReturn true whenever(exceptionHandler.handle(anyOrNull(), any())) doReturn exceptionDetails } afterGroup(::resetMocks) action("the handler receives a message") { subject.handle(message) } it("marks the task as terminal") { verify(queue).push(check<CompleteTask> { assertThat(it.status).isEqualTo(TERMINAL) }) } it("attaches the exception to the stage context") { verify(repository).storeStage(check { assertThat(it.context["exception"]).isEqualTo(exceptionDetails) }) } } and("the task should not fail the whole pipeline, only the branch") { beforeGroup { pipeline.stageByRef("1").apply { context["failPipeline"] = false context["continuePipeline"] = false } whenever(task.execute(any())) doThrow RuntimeException("o noes") whenever(repository.retrieve(PIPELINE, message.executionId)) doReturn pipeline whenever(exceptionHandler.handles(any())) doReturn true whenever(exceptionHandler.handle(anyOrNull(), any())) doReturn exceptionDetails } afterGroup(::resetMocks) afterGroup { pipeline.stages.first().context.clear() } action("the handler receives a message") { subject.handle(message) } it("marks the task STOPPED") { verify(queue).push(check<CompleteTask> { assertThat(it.status).isEqualTo(STOPPED) }) } } and("the task should allow the pipeline to proceed") { beforeGroup { pipeline.stageByRef("1").apply { context["failPipeline"] = false context["continuePipeline"] = true } whenever(task.execute(any())) doThrow RuntimeException("o noes") whenever(repository.retrieve(PIPELINE, message.executionId)) doReturn pipeline whenever(exceptionHandler.handles(any())) doReturn true whenever(exceptionHandler.handle(anyOrNull(), any())) doReturn exceptionDetails } afterGroup(::resetMocks) afterGroup { pipeline.stages.first().context.clear() } action("the handler receives a message") { subject.handle(message) } it("marks the task FAILED_CONTINUE") { verify(queue).push(check<CompleteTask> { assertThat(it.status).isEqualTo(FAILED_CONTINUE) }) } } } and("it is recoverable") { val taskBackoffMs = 30_000L val exceptionDetails = ExceptionHandler.Response( RuntimeException::class.qualifiedName, "o noes", ExceptionHandler.responseDetails("o noes"), true ) beforeGroup { whenever(task.getDynamicBackoffPeriod(any(), any())) doReturn taskBackoffMs whenever(task.execute(any())) doThrow RuntimeException("o noes") whenever(repository.retrieve(PIPELINE, message.executionId)) doReturn pipeline whenever(exceptionHandler.handles(any())) doReturn true whenever(exceptionHandler.handle(anyOrNull(), any())) doReturn exceptionDetails } afterGroup(::resetMocks) action("the handler receives a message") { subject.handle(message) } it("re-runs the task") { verify(queue).push(eq(message), eq(Duration.ofMillis(taskBackoffMs))) } } } describe("when the execution has stopped") { val pipeline = pipeline { status = TERMINAL stage { type = "whatever" task { id = "1" startTime = clock.instant().toEpochMilli() } } } val stage = pipeline.stages.first() val message = RunTask(pipeline.type, pipeline.id, "foo", pipeline.stages.first().id, "1", DummyTask::class.java) beforeGroup { taskExecutionInterceptors.forEach { whenever(it.beforeTaskExecution(task, stage)) doReturn stage } whenever(repository.retrieve(PIPELINE, message.executionId)) doReturn pipeline } afterGroup(::resetMocks) action("the handler receives a message") { subject.handle(message) } it("emits an event indicating that the task was canceled") { verify(queue).push(CompleteTask( message.executionType, message.executionId, "foo", message.stageId, message.taskId, CANCELED, CANCELED )) } it("does not execute the task") { verifyZeroInteractions(task) } } describe("when the execution has been canceled") { val pipeline = pipeline { status = RUNNING isCanceled = true stage { type = "whatever" task { id = "1" startTime = clock.instant().toEpochMilli() } } } val stage = pipeline.stages.first() val message = RunTask(pipeline.type, pipeline.id, "foo", stage.id, "1", DummyTask::class.java) beforeGroup { taskExecutionInterceptors.forEach { whenever(it.beforeTaskExecution(task, stage)) doReturn stage } whenever(repository.retrieve(PIPELINE, message.executionId)) doReturn pipeline } afterGroup(::resetMocks) action("the handler receives a message") { subject.handle(message) } it("marks the task as canceled") { verify(queue).push(CompleteTask( message.executionType, message.executionId, "foo", message.stageId, message.taskId, CANCELED, CANCELED )) } it("it tries to cancel the task") { verify(task).onCancel(any()) } } describe("when the execution has been paused") { val pipeline = pipeline { status = PAUSED stage { type = "whatever" status = RUNNING task { id = "1" startTime = clock.instant().toEpochMilli() } } } val stage = pipeline.stages.first() val message = RunTask(pipeline.type, pipeline.id, "foo", pipeline.stages.first().id, "1", DummyTask::class.java) beforeGroup { taskExecutionInterceptors.forEach { whenever(it.beforeTaskExecution(task, stage)) doReturn stage } whenever(repository.retrieve(PIPELINE, message.executionId)) doReturn pipeline } afterGroup(::resetMocks) action("the handler receives a message") { subject.handle(message) } it("marks the task as paused") { verify(queue).push(PauseTask(message)) } it("does not execute the task") { verifyZeroInteractions(task) } } describe("when the task has exceeded its timeout") { given("the execution was never paused") { val timeout = Duration.ofMinutes(5) val pipeline = pipeline { stage { type = "whatever" task { id = "1" status = RUNNING startTime = clock.instant().minusMillis(timeout.toMillis() + 1).toEpochMilli() } } } val stage = pipeline.stages.first() val message = RunTask(pipeline.type, pipeline.id, "foo", stage.id, "1", DummyTask::class.java) beforeGroup { taskExecutionInterceptors.forEach { whenever(it.beforeTaskExecution(task, stage)) doReturn stage } whenever(repository.retrieve(PIPELINE, message.executionId)) doReturn pipeline whenever(task.getDynamicTimeout(any())) doReturn timeout.toMillis() } afterGroup(::resetMocks) action("the handler receives a message") { subject.handle(message) } it("fails the task") { verify(queue).push(CompleteTask(message, TERMINAL)) } it("does not execute the task") { verify(task, never()).execute(any()) } } given("the execution was marked to continue") { val timeout = Duration.ofMinutes(5) val pipeline = pipeline { stage { type = "whatever" task { id = "1" status = RUNNING startTime = clock.instant().minusMillis(timeout.toMillis() + 1).toEpochMilli() } context["failPipeline"] = false context["continuePipeline"] = true } } val stage = pipeline.stages.first() val message = RunTask(pipeline.type, pipeline.id, "foo", stage.id, "1", DummyTask::class.java) beforeGroup { taskExecutionInterceptors.forEach { whenever(it.beforeTaskExecution(task, stage)) doReturn stage } whenever(repository.retrieve(PIPELINE, message.executionId)) doReturn pipeline whenever(task.getDynamicTimeout(any())) doReturn timeout.toMillis() } afterGroup(::resetMocks) action("the handler receives a message") { subject.handle(message) } it("marks the task as failed but continue") { verify(queue).push(CompleteTask(message, FAILED_CONTINUE, TERMINAL)) } } given("the execution is marked to succeed on timeout") { val timeout = Duration.ofMinutes(5) val pipeline = pipeline { stage { type = "whatever" context = hashMapOf<String, Any>("markSuccessfulOnTimeout" to true) task { id = "1" status = RUNNING startTime = clock.instant().minusMillis(timeout.toMillis() + 1).toEpochMilli() } } } val stage = pipeline.stages.first() val message = RunTask(pipeline.type, pipeline.id, "foo", stage.id, "1", DummyTask::class.java) beforeGroup { taskExecutionInterceptors.forEach { whenever(it.beforeTaskExecution(task, stage)) doReturn stage } whenever(repository.retrieve(PIPELINE, message.executionId)) doReturn pipeline whenever(task.getDynamicTimeout(any())) doReturn timeout.toMillis() } afterGroup(::resetMocks) action("the handler receives a message") { subject.handle(message) } it("marks the task as succeeded") { verify(queue).push(CompleteTask(message, SUCCEEDED)) } it("does not execute the task") { verify(task, never()).execute(any()) } } given("the execution had been paused") { val timeout = Duration.ofMinutes(5) val pipeline = pipeline { paused = PausedDetails().apply { pauseTime = clock.instant().minus(Minutes.of(3)).toEpochMilli() resumeTime = clock.instant().minus(Minutes.of(2)).toEpochMilli() } stage { type = "whatever" task { id = "1" status = RUNNING startTime = clock.instant().minusMillis(timeout.toMillis() + 1).toEpochMilli() } } } val stage = pipeline.stages.first() val message = RunTask(pipeline.type, pipeline.id, "foo", stage.id, "1", DummyTask::class.java) beforeGroup { taskExecutionInterceptors.forEach { whenever(it.beforeTaskExecution(task, stage)) doReturn stage } whenever(repository.retrieve(PIPELINE, message.executionId)) doReturn pipeline whenever(task.getDynamicTimeout(any())) doReturn timeout.toMillis() } afterGroup(::resetMocks) action("the handler receives a message") { subject.handle(message) } it("executes the task") { verify(task).execute(any()) } } given("the execution had been paused but is timed out anyway") { val timeout = Duration.ofMinutes(5) val pipeline = pipeline { paused = PausedDetails().apply { pauseTime = clock.instant().minus(Minutes.of(3)).toEpochMilli() resumeTime = clock.instant().minus(Minutes.of(2)).toEpochMilli() } stage { type = "whatever" task { id = "1" status = RUNNING startTime = clock.instant().minusMillis(timeout.plusMinutes(1).toMillis() + 1).toEpochMilli() } } } val stage = pipeline.stages.first() val message = RunTask(pipeline.type, pipeline.id, "foo", stage.id, "1", DummyTask::class.java) beforeGroup { taskExecutionInterceptors.forEach { whenever(it.beforeTaskExecution(task, stage)) doReturn stage } whenever(repository.retrieve(PIPELINE, message.executionId)) doReturn pipeline whenever(task.getDynamicTimeout(any())) doReturn timeout.toMillis() } afterGroup(::resetMocks) action("the handler receives a message") { subject.handle(message) } it("fails the task") { verify(queue).push(CompleteTask(message, TERMINAL)) } it("does not execute the task") { verify(task, never()).execute(any()) } } given("the execution had been paused but only before this task started running") { val timeout = Duration.ofMinutes(5) val pipeline = pipeline { paused = PausedDetails().apply { pauseTime = clock.instant().minus(Minutes.of(10)).toEpochMilli() resumeTime = clock.instant().minus(Minutes.of(9)).toEpochMilli() } stage { type = "whatever" task { id = "1" status = RUNNING startTime = clock.instant().minusMillis(timeout.toMillis() + 1).toEpochMilli() } } } val stage = pipeline.stages.first() val message = RunTask(pipeline.type, pipeline.id, "foo", stage.id, "1", DummyTask::class.java) beforeGroup { taskExecutionInterceptors.forEach { whenever(it.beforeTaskExecution(task, stage)) doReturn stage } whenever(repository.retrieve(PIPELINE, message.executionId)) doReturn pipeline whenever(task.getDynamicTimeout(any())) doReturn timeout.toMillis() } afterGroup(::resetMocks) action("the handler receives a message") { subject.handle(message) } it("fails the task") { verify(queue).push(CompleteTask(message, TERMINAL)) } it("does not execute the task") { verify(task, never()).execute(any()) } } given("the stage waited for an execution window") { val timeout = Duration.ofMinutes(5) val windowDuration = Duration.ofHours(1) val windowStartedAt = clock.instant().minus(timeout).minus(windowDuration).plusSeconds(1) val windowEndedAt = clock.instant().minus(timeout).plusSeconds(1) val pipeline = pipeline { stage { stage { type = RestrictExecutionDuringTimeWindow.TYPE status = SUCCEEDED startTime = windowStartedAt.toEpochMilli() endTime = windowEndedAt.toEpochMilli() } refId = "1" type = "whatever" context[STAGE_TIMEOUT_OVERRIDE_KEY] = timeout.toMillis() startTime = windowStartedAt.toEpochMilli() task { id = "1" startTime = windowEndedAt.toEpochMilli() status = RUNNING } } } val stage = pipeline.stages.first() val message = RunTask(pipeline.type, pipeline.id, pipeline.application, stage.id, "1", DummyTask::class.java) beforeGroup { taskExecutionInterceptors.forEach { whenever(it.beforeTaskExecution(task, stage)) doReturn stage } whenever(repository.retrieve(PIPELINE, message.executionId)) doReturn pipeline whenever(task.getDynamicTimeout(any())) doReturn timeout.toMillis() } afterGroup(::resetMocks) action("the handler receives a message") { subject.handle(message) } it("executes the task") { verify(task).execute(pipeline.stageByRef("1")) } } given("the stage waited for an execution window but is timed out anyway") { val timeout = Duration.ofMinutes(5) val windowDuration = Duration.ofHours(1) val windowStartedAt = clock.instant().minus(timeout).minus(windowDuration).minusSeconds(1) val windowEndedAt = clock.instant().minus(timeout).minusSeconds(1) val pipeline = pipeline { stage { stage { type = RestrictExecutionDuringTimeWindow.TYPE status = SUCCEEDED startTime = windowStartedAt.toEpochMilli() endTime = windowEndedAt.toEpochMilli() } refId = "1" type = "whatever" context[STAGE_TIMEOUT_OVERRIDE_KEY] = timeout.toMillis() startTime = windowStartedAt.toEpochMilli() task { id = "1" startTime = windowEndedAt.toEpochMilli() status = RUNNING } } } val message = RunTask(pipeline.type, pipeline.id, pipeline.application, pipeline.stages.first().id, "1", DummyTask::class.java) beforeGroup { whenever(repository.retrieve(PIPELINE, message.executionId)) doReturn pipeline whenever(task.getDynamicTimeout(any())) doReturn timeout.toMillis() } afterGroup(::resetMocks) action("the handler receives a message") { subject.handle(message) } it("fails the task") { verify(queue).push(CompleteTask(message, TERMINAL)) } it("does not execute the task") { verify(task, never()).execute(any()) } } } describe("handles onTimeout responses") { val timeout = Duration.ofMinutes(5) val pipeline = pipeline { stage { type = "whatever" task { id = "1" status = RUNNING startTime = clock.instant().minusMillis(timeout.toMillis() + 1).toEpochMilli() } } } val stage = pipeline.stages.first() val message = RunTask(pipeline.type, pipeline.id, "foo", stage.id, "1", DummyTask::class.java) given("the task returns fail_continue") { beforeGroup { taskExecutionInterceptors.forEach { whenever(it.beforeTaskExecution(task, stage)) doReturn stage } whenever(repository.retrieve(PIPELINE, message.executionId)) doReturn pipeline whenever(task.getDynamicTimeout(any())) doReturn timeout.toMillis() whenever(task.onTimeout(any())) doReturn TaskResult.ofStatus(FAILED_CONTINUE) } afterGroup(::resetMocks) action("the handler receives a message") { subject.handle(message) } it("marks the task fail_continue") { verify(queue).push(CompleteTask(message, FAILED_CONTINUE)) } it("does not execute the task") { verify(task, never()).execute(any()) } } given("the task returns terminal") { beforeGroup { taskExecutionInterceptors.forEach { whenever(it.beforeTaskExecution(task, stage)) doReturn stage } whenever(repository.retrieve(PIPELINE, message.executionId)) doReturn pipeline whenever(task.getDynamicTimeout(any())) doReturn timeout.toMillis() whenever(task.onTimeout(any())) doReturn TaskResult.ofStatus(TERMINAL) } afterGroup(::resetMocks) action("the handler receives a message") { subject.handle(message) } it("marks the task terminal") { verify(queue).push(CompleteTask(message, TERMINAL)) } it("does not execute the task") { verify(task, never()).execute(any()) } } given("the task returns succeeded") { beforeGroup { whenever(repository.retrieve(PIPELINE, message.executionId)) doReturn pipeline whenever(task.getDynamicTimeout(any())) doReturn timeout.toMillis() whenever(task.onTimeout(any())) doReturn TaskResult.ofStatus(SUCCEEDED) } afterGroup(::resetMocks) action("the handler receives a message") { subject.handle(message) subject } it("marks the task terminal") { verify(queue).push(CompleteTask(message, TERMINAL)) } it("does not execute the task") { verify(task, never()).execute(any()) } } } given("there is a timeout override") { val timeout = Duration.ofMinutes(5) val timeoutOverride = Duration.ofMinutes(10) timeoutOverride.toMillis().let { listOf(it.toInt(), it, it.toDouble()) }.forEach { stageTimeoutMs -> and("the override is a ${stageTimeoutMs.javaClass.simpleName}") { and("the stage is between the default and overridden duration") { val pipeline = pipeline { stage { type = "whatever" context["stageTimeoutMs"] = stageTimeoutMs startTime = clock.instant().minusMillis(timeout.toMillis() + 1).toEpochMilli() task { id = "1" status = RUNNING startTime = clock.instant().minusMillis(timeout.toMillis() - 1).toEpochMilli() } } } val stage = pipeline.stages.first() val taskResult = TaskResult.RUNNING val message = RunTask(pipeline.type, pipeline.id, "foo", stage.id, "1", DummyTask::class.java) beforeGroup { taskExecutionInterceptors.forEach { whenever(it.beforeTaskExecution(task, stage)) doReturn stage } taskExecutionInterceptors.forEach { whenever(it.afterTaskExecution(task, stage, taskResult)) doReturn taskResult } whenever(repository.retrieve(PIPELINE, message.executionId)) doReturn pipeline whenever(task.getDynamicTimeout(any())) doReturn timeout.toMillis() } afterGroup(::resetMocks) on("receiving $message") { subject.handle(message) } it("executes the task") { verify(task).execute(any()) } } and("the timeout override has been exceeded by stage") { and("the stage has never been paused") { val pipeline = pipeline { stage { type = "whatever" context["stageTimeoutMs"] = stageTimeoutMs startTime = clock.instant().minusMillis(timeoutOverride.toMillis() + 1).toEpochMilli() task { id = "1" status = RUNNING startTime = clock.instant().minusMillis(timeout.toMillis() - 1).toEpochMilli() } } } val stage = pipeline.stages.first() val taskResult = TaskResult.RUNNING val message = RunTask(pipeline.type, pipeline.id, "foo", stage.id, "1", DummyTask::class.java) beforeGroup { taskExecutionInterceptors.forEach { whenever(it.beforeTaskExecution(task, stage)) doReturn stage } taskExecutionInterceptors.forEach { whenever(it.afterTaskExecution(task, stage, taskResult)) doReturn taskResult } whenever(repository.retrieve(PIPELINE, message.executionId)) doReturn pipeline whenever(task.getDynamicTimeout(any())) doReturn timeout.toMillis() } afterGroup(::resetMocks) on("receiving $message") { subject.handle(message) } it("fails the task") { verify(queue).push(CompleteTask(message, TERMINAL)) } it("does not execute the task") { verify(task, never()).execute(any()) } } and("the execution had been paused") { val pipeline = pipeline { paused = PausedDetails().apply { pauseTime = clock.instant().minus(Minutes.of(3)).toEpochMilli() resumeTime = clock.instant().minus(Minutes.of(2)).toEpochMilli() } stage { type = "whatever" context["stageTimeoutMs"] = stageTimeoutMs startTime = clock.instant().minusMillis(timeoutOverride.toMillis() + 1).toEpochMilli() task { id = "1" status = RUNNING startTime = clock.instant().minusMillis(timeout.toMillis() - 1).toEpochMilli() } } } val stage = pipeline.stages.first() val taskResult = TaskResult.RUNNING val message = RunTask(pipeline.type, pipeline.id, "foo", pipeline.stages.first().id, "1", DummyTask::class.java) beforeGroup { taskExecutionInterceptors.forEach { whenever(it.beforeTaskExecution(task, stage)) doReturn stage } taskExecutionInterceptors.forEach { whenever(it.afterTaskExecution(task, stage, taskResult)) doReturn taskResult } whenever(repository.retrieve(PIPELINE, message.executionId)) doReturn pipeline whenever(task.getDynamicTimeout(any())) doReturn timeout.toMillis() } afterGroup(::resetMocks) action("the handler receives a message") { subject.handle(message) } it("executes the task") { verify(task).execute(any()) } } and("the execution had been paused but is timed out anyway") { val pipeline = pipeline { paused = PausedDetails().apply { pauseTime = clock.instant().minus(Minutes.of(3)).toEpochMilli() resumeTime = clock.instant().minus(Minutes.of(2)).toEpochMilli() } stage { type = "whatever" context["stageTimeoutMs"] = stageTimeoutMs startTime = clock.instant().minusMillis(timeoutOverride.plusMinutes(1).toMillis() + 1).toEpochMilli() task { id = "1" status = RUNNING startTime = clock.instant().minusMillis(timeout.toMillis() - 1).toEpochMilli() } } } val message = RunTask(pipeline.type, pipeline.id, "foo", pipeline.stages.first().id, "1", DummyTask::class.java) beforeGroup { whenever(repository.retrieve(PIPELINE, message.executionId)) doReturn pipeline whenever(task.getDynamicTimeout(any())) doReturn timeout.toMillis() } afterGroup(::resetMocks) action("the handler receives a message") { subject.handle(message) } it("fails the task") { verify(queue).push(CompleteTask(message, TERMINAL)) } it("does not execute the task") { verify(task, never()).execute(any()) } } and("the execution had been paused but only before this stage started running") { val pipeline = pipeline { paused = PausedDetails().apply { pauseTime = clock.instant().minus(Minutes.of(15)).toEpochMilli() resumeTime = clock.instant().minus(Minutes.of(14)).toEpochMilli() } stage { type = "whatever" context["stageTimeoutMs"] = stageTimeoutMs startTime = clock.instant().minusMillis(timeoutOverride.toMillis() + 1).toEpochMilli() task { id = "1" status = RUNNING startTime = clock.instant().minusMillis(timeout.toMillis() - 1).toEpochMilli() } } } val message = RunTask(pipeline.type, pipeline.id, "foo", pipeline.stages.first().id, "1", DummyTask::class.java) beforeGroup { whenever(repository.retrieve(PIPELINE, message.executionId)) doReturn pipeline whenever(task.getDynamicTimeout(any())) doReturn timeout.toMillis() } afterGroup(::resetMocks) action("the handler receives a message") { subject.handle(message) } it("fails the task") { verify(queue).push(CompleteTask(message, TERMINAL)) } it("does not execute the task") { verify(task, never()).execute(any()) } } } and("the task is an overridabletimeout task that shouldn't time out") { val pipeline = pipeline { stage { type = "whatever" context["stageTimeoutMs"] = stageTimeoutMs startTime = clock.instant().minusMillis(timeout.toMillis() + 1).toEpochMilli() // started 5.1 minutes ago task { id = "1" implementingClass = DummyTimeoutOverrideTask::class.jvmName status = RUNNING startTime = clock.instant().minusMillis(timeout.toMillis() + 1).toEpochMilli() // started 5.1 minutes ago } } } val stage = pipeline.stages.first() val taskResult = TaskResult.RUNNING val message = RunTask(pipeline.type, pipeline.id, "foo", stage.id, "1", DummyTimeoutOverrideTask::class.java) beforeGroup { taskExecutionInterceptors.forEach { whenever(it.beforeTaskExecution(timeoutOverrideTask, stage)) doReturn stage } taskExecutionInterceptors.forEach { whenever(it.afterTaskExecution(timeoutOverrideTask, stage, taskResult)) doReturn taskResult } whenever(repository.retrieve(PIPELINE, message.executionId)) doReturn pipeline whenever(timeoutOverrideTask.timeout) doReturn timeout.toMillis() } afterGroup(::resetMocks) on("receiving $message") { subject.handle(message) } it("executes the task") { verify(timeoutOverrideTask).execute(any()) } } } } } } describe("expressions in the context") { mapOf( "\${1 == 2}" to false, "\${1 == 1}" to true, mapOf("key" to "\${1 == 2}") to mapOf("key" to false), mapOf("key" to "\${1 == 1}") to mapOf("key" to true), mapOf("key" to mapOf("key" to "\${1 == 2}")) to mapOf("key" to mapOf("key" to false)), mapOf("key" to mapOf("key" to "\${1 == 1}")) to mapOf("key" to mapOf("key" to true)) ).forEach { expression, expected -> given("an expression $expression in the stage context") { val pipeline = pipeline { stage { refId = "1" type = "whatever" context["expr"] = expression task { id = "1" startTime = clock.instant().toEpochMilli() } } } val stage = pipeline.stages.first() val taskResult = TaskResult.SUCCEEDED val message = RunTask(pipeline.type, pipeline.id, "foo", pipeline.stageByRef("1").id, "1", DummyTask::class.java) beforeGroup { taskExecutionInterceptors.forEach { whenever(it.beforeTaskExecution(task, stage)) doReturn stage } taskExecutionInterceptors.forEach { whenever(it.afterTaskExecution(task, stage, taskResult)) doReturn taskResult } whenever(task.execute(any())) doReturn taskResult whenever(repository.retrieve(PIPELINE, message.executionId)) doReturn pipeline } afterGroup(::resetMocks) action("the handler receives a message") { subject.handle(message) } it("parses the expression") { verify(task).execute(check { assertThat(it.context["expr"]).isEqualTo(expected) }) } } } describe("can reference non-existent trigger props") { mapOf( "\${trigger.type == 'manual'}" to true, "\${trigger.buildNumber == null}" to true, "\${trigger.quax ?: 'no quax'}" to "no quax" ).forEach { expression, expected -> given("an expression $expression in the stage context") { val pipeline = pipeline { stage { refId = "1" type = "whatever" context["expr"] = expression trigger = DefaultTrigger("manual") task { id = "1" startTime = clock.instant().toEpochMilli() } } } val stage = pipeline.stages.first() val taskResult = TaskResult.SUCCEEDED val message = RunTask(pipeline.type, pipeline.id, "foo", pipeline.stageByRef("1").id, "1", DummyTask::class.java) beforeGroup { taskExecutionInterceptors.forEach { whenever(it.beforeTaskExecution(task, stage)) doReturn stage } taskExecutionInterceptors.forEach { whenever(it.afterTaskExecution(task, stage, taskResult)) doReturn taskResult } whenever(task.execute(any())) doReturn taskResult whenever(repository.retrieve(PIPELINE, message.executionId)) doReturn pipeline } afterGroup(::resetMocks) action("the handler receives a message") { subject.handle(message) } it("evaluates the expression") { verify(task).execute(check { assertThat(it.context["expr"]).isEqualTo(expected) }) } } } } given("a reference to deployedServerGroups in the stage context") { val pipeline = pipeline { stage { refId = "1" type = "createServerGroup" context = mapOf( "deploy.server.groups" to mapOf( "us-west-1" to listOf( "spindemo-test-v008" ) ), "account" to "mgmttest", "region" to "us-west-1" ) status = SUCCEEDED } stage { refId = "2" requisiteStageRefIds = setOf("1") type = "whatever" context["command"] = "serverGroupDetails.groovy \${ deployedServerGroups[0].account } \${ deployedServerGroups[0].region } \${ deployedServerGroups[0].serverGroup }" task { id = "1" startTime = clock.instant().toEpochMilli() } } } val stage = pipeline.stageByRef("2") val taskResult = TaskResult.SUCCEEDED val message = RunTask(pipeline.type, pipeline.id, "foo", pipeline.stageByRef("2").id, "1", DummyTask::class.java) beforeGroup { taskExecutionInterceptors.forEach { whenever(it.beforeTaskExecution(task, stage)) doReturn stage } taskExecutionInterceptors.forEach { whenever(it.afterTaskExecution(task, stage, taskResult)) doReturn taskResult } whenever(task.execute(any())) doReturn taskResult whenever(repository.retrieve(PIPELINE, message.executionId)) doReturn pipeline } afterGroup(::resetMocks) action("the handler receives a message") { subject.handle(message) } it("resolves deployed server groups") { verify(task).execute(check { assertThat(it.context["command"]).isEqualTo("serverGroupDetails.groovy mgmttest us-west-1 spindemo-test-v008") }) } } given("parameters in the context and in the pipeline") { val pipeline = pipeline { trigger = DefaultTrigger(type = "manual", parameters = mapOf("dummy" to "foo")) stage { refId = "1" type = "jenkins" context["parameters"] = mapOf( "message" to "o hai" ) task { id = "1" startTime = clock.instant().toEpochMilli() } } } val stage = pipeline.stages.first() val taskResult = TaskResult.SUCCEEDED val message = RunTask(pipeline.type, pipeline.id, "foo", pipeline.stageByRef("1").id, "1", DummyTask::class.java) beforeGroup { taskExecutionInterceptors.forEach { whenever(it.beforeTaskExecution(task, stage)) doReturn stage } taskExecutionInterceptors.forEach { whenever(it.afterTaskExecution(task, stage, taskResult)) doReturn taskResult } whenever(task.execute(any())) doReturn taskResult whenever(repository.retrieve(PIPELINE, message.executionId)) doReturn pipeline } afterGroup(::resetMocks) action("the handler receives a message") { subject.handle(message) } it("does not overwrite the stage's parameters with the pipeline's") { verify(task).execute(check { assertThat(it.context["parameters"]).isEqualTo(mapOf("message" to "o hai")) }) } } given("an expression in the context that refers to a prior stage output") { val pipeline = pipeline { stage { refId = "1" outputs["foo"] = "bar" } stage { refId = "2" requisiteStageRefIds = setOf("1") context["expression"] = "\${foo}" type = "whatever" task { id = "1" startTime = clock.instant().toEpochMilli() } } } val stage = pipeline.stageByRef("2") val taskResult = TaskResult.SUCCEEDED val message = RunTask(pipeline.type, pipeline.id, "foo", stage.id, "1", DummyTask::class.java) beforeGroup { taskExecutionInterceptors.forEach { whenever(it.beforeTaskExecution(task, stage)) doReturn stage } taskExecutionInterceptors.forEach { whenever(it.afterTaskExecution(task, stage, taskResult)) doReturn taskResult } whenever(task.execute(any())) doReturn taskResult whenever(repository.retrieve(PIPELINE, message.executionId)) doReturn pipeline } afterGroup(::resetMocks) on("receiving $message") { subject.handle(message) } it("passes the decoded expression to the task") { verify(task).execute(check { assertThat(it.context["expression"]).isEqualTo("bar") }) } } } describe("no such task") { val pipeline = pipeline { stage { type = "whatever" task { id = "1" implementingClass = InvalidTask::class.jvmName } } } val message = RunTask(pipeline.type, pipeline.id, "foo", pipeline.stages.first().id, "1", InvalidTask::class.java) beforeGroup { whenever(repository.retrieve(PIPELINE, message.executionId)) doReturn pipeline } afterGroup(::resetMocks) action("the handler receives a message") { subject.handle(message) } it("does not run any tasks") { verifyZeroInteractions(task) } it("emits an error event") { verify(queue).push(isA<InvalidTaskType>()) } } describe("manual skip behavior") { given("a stage with a manual skip flag") { val pipeline = pipeline { stage { type = singleTaskStage.type task { id = "1" implementingClass = DummyTask::class.jvmName } context["manualSkip"] = true } } val stage = pipeline.stageByRef("1") val taskResult = TaskResult.SUCCEEDED val message = RunTask(pipeline.type, pipeline.id, "foo", stage.id, "1", DummyTask::class.java) beforeGroup { taskExecutionInterceptors.forEach { whenever(it.beforeTaskExecution(task, stage)) doReturn stage } taskExecutionInterceptors.forEach { whenever(it.afterTaskExecution(task, stage, taskResult)) doReturn taskResult } whenever(repository.retrieve(PIPELINE, message.executionId)) doReturn pipeline } afterGroup(::resetMocks) action("the handler receives a message") { subject.handle(message) } it("sets the task's status to SKIPPED and completes the task") { verify(queue).push(CompleteTask(message, SKIPPED)) } } } describe("max configurable back off value") { setOf( BackOff(5_000L, 10_000L, 20_000L, 30_000L, 30_000L), BackOff(10_000L, 20_000L, 30_000L, 5_000L, 30_000L), BackOff(20_000L, 30_000L, 5_000L, 10_000L, 30_000L), BackOff(30_000L, 5_000L, 10_000L, 20_000L, 30_000L), BackOff(20_000L, 5_000L, 10_000L, 30_002L, 30_001L) ).forEach { backOff -> given("the back off values $backOff") { val pipeline = pipeline { stage { type = "whatever" task { id = "1" implementingClass = DummyCloudProviderAwareTask::class.jvmName startTime = clock.instant().toEpochMilli() context["cloudProvider"] = "aws" context["deploy.account.name"] = "someAccount" } } } val stage = pipeline.stages.first() val message = RunTask(pipeline.type, pipeline.id, "foo", stage.id, "1", DummyCloudProviderAwareTask::class.java) val taskResult = TaskResult.RUNNING beforeGroup { whenever(cloudProviderAwareTask.execute(any())) doReturn taskResult taskExecutionInterceptors.forEach { whenever(it.maxTaskBackoff()) doReturn backOff.limit } taskExecutionInterceptors.forEach { whenever(it.beforeTaskExecution(cloudProviderAwareTask, stage)) doReturn stage } taskExecutionInterceptors.forEach { whenever(it.afterTaskExecution(cloudProviderAwareTask, stage, taskResult)) doReturn taskResult } whenever(cloudProviderAwareTask.getDynamicBackoffPeriod(any(), any())) doReturn backOff.taskBackOffMs whenever(dynamicConfigService.getConfig(eq(Long::class.java), eq("tasks.global.backOffPeriod"), any())) doReturn backOff.globalBackOffMs whenever(cloudProviderAwareTask.hasCloudProvider(any())) doReturn true whenever(cloudProviderAwareTask.getCloudProvider(any<Stage>())) doReturn "aws" whenever(dynamicConfigService.getConfig(eq(Long::class.java), eq("tasks.aws.backOffPeriod"), any())) doReturn backOff.cloudProviderBackOffMs whenever(cloudProviderAwareTask.hasCredentials(any())) doReturn true whenever(cloudProviderAwareTask.getCredentials(any<Stage>())) doReturn "someAccount" whenever(dynamicConfigService.getConfig(eq(Long::class.java), eq("tasks.aws.someAccount.backOffPeriod"), any())) doReturn backOff.accountBackOffMs whenever(repository.retrieve(PIPELINE, message.executionId)) doReturn pipeline } afterGroup(::resetMocks) action("the handler receives a message") { subject.handle(message) } it("selects the max value, unless max value is over limit ${backOff.limit} in which case limit is used") { verify(queue).push(message, Duration.ofMillis(backOff.expectedMaxBackOffMs)) } } } } }) data class BackOff( val taskBackOffMs: Long, val globalBackOffMs: Long, val cloudProviderBackOffMs: Long, val accountBackOffMs: Long, val expectedMaxBackOffMs: Long, val limit: Long = 30_001L )
apache-2.0
11cd35b002712ae5faecdd1114c986ef
35.60111
175
0.603854
4.926313
false
false
false
false
joseph-roque/BowlingCompanion
app/src/main/java/ca/josephroque/bowlingcompanion/teams/teammember/TeamMemberDialog.kt
1
7899
package ca.josephroque.bowlingcompanion.teams.teammember import android.app.Dialog import android.content.Context import android.os.Bundle import android.support.v4.app.DialogFragment import android.support.v4.app.FragmentManager import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.view.Window import ca.josephroque.bowlingcompanion.R import ca.josephroque.bowlingcompanion.common.Android import ca.josephroque.bowlingcompanion.common.FabController import ca.josephroque.bowlingcompanion.common.fragments.BaseDialogFragment import ca.josephroque.bowlingcompanion.common.fragments.ListFragment import ca.josephroque.bowlingcompanion.common.interfaces.IIdentifiable import ca.josephroque.bowlingcompanion.leagues.League import ca.josephroque.bowlingcompanion.leagues.LeagueListFragment import ca.josephroque.bowlingcompanion.series.Series import ca.josephroque.bowlingcompanion.series.SeriesListFragment import ca.josephroque.bowlingcompanion.utils.safeLet import kotlinx.android.synthetic.main.dialog_team_member.view.* import kotlinx.android.synthetic.main.view_screen_header.view.* import kotlinx.coroutines.experimental.launch /** * Copyright (C) 2018 Joseph Roque * * Dialog to select league and series for a team member. */ class TeamMemberDialog : BaseDialogFragment(), ListFragment.ListFragmentDelegate, FragmentManager.OnBackStackChangedListener { companion object { @Suppress("unused") private const val TAG = "TeamMemberDialog" private const val ARG_TEAM_MEMBER = "${TAG}_team_member" private const val ARG_SELECTED_LEAGUE = "${TAG}_selected_league" fun newInstance(teamMember: TeamMember): TeamMemberDialog { val dialog = TeamMemberDialog() dialog.arguments = Bundle().apply { putParcelable(ARG_TEAM_MEMBER, teamMember) } return dialog } } private var teamMember: TeamMember? = null private var selectedLeague: League? = null private var selectedSeries: Series? = null private var delegate: TeamMemberDialogDelegate? = null private lateinit var fabController: FabController // MARK: Lifecycle functions override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setStyle(DialogFragment.STYLE_NORMAL, R.style.Dialog) } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { teamMember = arguments?.getParcelable(ARG_TEAM_MEMBER) selectedLeague = savedInstanceState?.getParcelable(ARG_SELECTED_LEAGUE) val rootView = inflater.inflate(R.layout.dialog_team_member, container, false) setupToolbar(rootView) setupFab(rootView) prepareActions(rootView, selectedLeague == null) setupChildFragment(savedInstanceState) childFragmentManager.addOnBackStackChangedListener(this) return rootView } override fun onAttach(context: Context?) { super.onAttach(context) val parent = parentFragment as? TeamMemberDialogDelegate ?: throw RuntimeException("${parentFragment!!} must implement TeamMemberDialogDelegate") delegate = parent } override fun onDetach() { super.onDetach() delegate = null } override fun onStart() { super.onStart() dialog.window?.setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT) view?.let { prepareActions(it, selectedLeague == null) } } override fun onSaveInstanceState(outState: Bundle) { super.onSaveInstanceState(outState) outState.putParcelable(ARG_SELECTED_LEAGUE, selectedLeague) } override fun onCreateDialog(savedInstanceState: Bundle?): Dialog { val dialog = super.onCreateDialog(savedInstanceState) dialog.requestWindowFeature(Window.FEATURE_NO_TITLE) return dialog } override fun dismiss() { activity?.supportFragmentManager?.popBackStack() super.dismiss() } // MARK: ListFragmentDelegate override fun onItemSelected(item: IIdentifiable, longPress: Boolean) { if (item is League) { selectedLeague = item if (item.isEvent) { saveTeamMember() } else { val fragment = SeriesListFragment.newInstance(item, true) childFragmentManager.beginTransaction().apply { replace(R.id.fragment_container, fragment) addToBackStack(resources.getString(R.string.leagues)) commit() } } } else if (item is Series) { selectedSeries = item saveTeamMember() } } override fun onItemDeleted(item: IIdentifiable) { // Intentionally left blank } // MARK: OnBackStackChangedListener override fun onBackStackChanged() { view?.let { prepareActions(it, childFragmentManager.backStackEntryCount == 0) } } // MARK: Private functions private fun setupToolbar(rootView: View) { rootView.toolbar_team_member.apply { setNavigationOnClickListener { if (selectedLeague == null) { dismiss() } else { selectedLeague = null childFragmentManager.popBackStack() } } } } private fun setupFab(rootView: View) { fabController = FabController(rootView.fab, View.OnClickListener { if (selectedLeague != null) { saveTeamMember() } }) } private fun prepareActions(rootView: View, forLeague: Boolean) { if (forLeague) { rootView.tv_header_title.setText(R.string.league) rootView.tv_header_caption.setText(R.string.team_members_leagues_select_a_league) fabController.image = null rootView.toolbar_team_member.apply { setNavigationIcon(R.drawable.ic_dismiss) title = teamMember?.bowlerName } } else { rootView.tv_header_title.setText(R.string.series) rootView.tv_header_caption.setText(R.string.team_members_series_select_a_series) fabController.image = R.drawable.ic_add rootView.toolbar_team_member.apply { setNavigationIcon(R.drawable.ic_arrow_back) title = selectedLeague?.name } } } private fun setupChildFragment(savedInstanceState: Bundle?) { teamMember?.let { if (savedInstanceState == null) { val fragment = LeagueListFragment.newInstance( bowlerId = it.bowlerId, show = LeagueListFragment.Companion.Show.Both, singleSelectMode = true ) childFragmentManager.beginTransaction().apply { add(R.id.fragment_container, fragment) commit() } } } } private fun saveTeamMember() { launch(Android) { safeLet(teamMember, selectedLeague) { teamMember, league -> val newTeamMember = TeamMember( teamId = teamMember.teamId, bowlerName = teamMember.bowlerName, bowlerId = teamMember.bowlerId, league = league, series = selectedSeries ) delegate?.onFinishTeamMember(newTeamMember) dismiss() } } } // MARK: TeamMemberDialogDelegate interface TeamMemberDialogDelegate { fun onFinishTeamMember(teamMember: TeamMember) } }
mit
9bc9c7ed31e37a992d310f42f4a40324
34.106667
116
0.643373
5.102713
false
false
false
false
pchrysa/Memento-Calendar
memento/src/main/java/com/alexstyl/specialdates/date/Date.kt
1
3285
package com.alexstyl.specialdates.date import com.alexstyl.specialdates.Optional import org.joda.time.IllegalFieldValueException import org.joda.time.LocalDate import java.util.* /** * A specific date on a specific year */ data class Date private constructor(private val localDate: LocalDate, private val year: Optional<Int>) : Comparable<Date> { fun addDay(i: Int): Date { val addedDate = localDate.plusDays(i) return Date(addedDate, Optional(addedDate.year)) } val dayOfMonth: Int get() = localDate.dayOfMonth // JodaTime follows the same indexing as our project val month: Int @MonthInt get() = localDate.monthOfYear fun getYear(): Int = year.get() fun toMillis(): Long = localDate.toDate().time fun minusDay(days: Int): Date { val minusDays = localDate.minusDays(days) return Date(minusDays, Optional(minusDays.year)) } val dayOfWeek: Int get() = localDate.dayOfWeek fun addWeek(weeks: Int): Date = addDay(7 * weeks) fun daysDifferenceTo(otherEvent: Date): Int { val dayOfYear = localDate.dayOfYear().get() val otherDayOfYear = otherEvent.localDate.dayOfYear().get() val daysOfYearsDifference = (getYear() - otherEvent.getYear()) * 365 return otherDayOfYear - dayOfYear - daysOfYearsDifference } fun hasYear(): Boolean = year.isPresent fun hasNoYear(): Boolean = !year.isPresent override fun compareTo(right: Date): Int { if (this.hasYear() && right.hasYear()) { val yearOne = this.getYear() val yearTwo = right.getYear() if (yearOne > yearTwo) { return 1 } else if (yearOne < yearTwo) { return -1 } } if (this.month < right.month) { return -1 } else if (this.month > right.month) { return 1 } return this.dayOfMonth - right.dayOfMonth } companion object { var CURRENT_YEAR: Int = 0 init { CURRENT_YEAR = LocalDate.now().year } fun today(): Date { val localDate = LocalDate.now() return Date(localDate, Optional(localDate.year)) } fun on(dayOfMonth: Int, @MonthInt month: Int): Date { val localDate = LocalDate(Months.NO_YEAR, month, dayOfMonth) return Date(localDate, Optional.absent<Int>()) } fun on(dayOfMonth: Int, @MonthInt month: Int, year: Int): Date { if (year <= 0) { throw IllegalArgumentException( "Do not call DayDate.on() if no year is present. Call the respective method without the year argument instead") } try { val localDate = LocalDate(year, month, dayOfMonth) return Date(localDate, Optional(year)) } catch (a: IllegalFieldValueException) { throw IllegalArgumentException(String.format(Locale.US, "%d/%d/%d is invalid", dayOfMonth, month, year)) } } fun startOfYear(year: Int): Date = Date.on(1, Months.JANUARY, year) fun endOfYear(currentYear: Int): Date = Date.on(31, Months.DECEMBER, currentYear) } }
mit
b3b8533dd1fb209cfd7d8148d466ccb1
30.285714
135
0.59726
4.368351
false
false
false
false
prgpascal/android-qr-data-transfer
android-qr-data-transfer/src/main/java/com/prgpascal/qrdatatransfer/activities/BaseTransferActivity.kt
1
2349
/* * Copyright (C) 2016 Riccardo Leschiutta * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.prgpascal.qrdatatransfer.activities import android.app.Activity import android.bluetooth.BluetoothAdapter import android.content.Intent import android.os.Bundle import com.prgpascal.qrdatatransfer.utils.TransferParams.Companion.ERROR_BT_DISABLED import com.prgpascal.qrdatatransfer.utils.TransferParams.Companion.ERROR_BT_NOT_AVAILABLE import com.prgpascal.qrdatatransfer.utils.TransferParams.Companion.ERROR_PERMISSIONS_NOT_GRANTED import com.prgpascal.qrdatatransfer.utils.TransferParams.Companion.PARAM_ERROR import com.prgpascal.qrdatatransfer.utils.preventScreenRotation abstract class BaseTransferActivity : PermissionsActivity() { var isFinishingTransmission = false override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) preventScreenRotation(this) checkAppPermissions() } override fun permissionsGranted() { checkBluetooth() } override fun permissionsNotGranted() { finishTransmissionWithError(error = ERROR_PERMISSIONS_NOT_GRANTED) } private fun checkBluetooth() { val btAdapter = BluetoothAdapter.getDefaultAdapter() if (btAdapter == null) { finishTransmissionWithError(error = ERROR_BT_NOT_AVAILABLE) } else if (!btAdapter.isEnabled) { finishTransmissionWithError(error = ERROR_BT_DISABLED) } else { createLayout() } } abstract fun createLayout() fun finishTransmissionWithError(error: String? = null) { val returnIntent = Intent() if (error != null) { returnIntent.putExtra(PARAM_ERROR, error) } setResult(Activity.RESULT_CANCELED, returnIntent) finish() } }
apache-2.0
b926ba36a8ccc56691ba62d880fad65d
34.074627
96
0.727118
4.382463
false
false
false
false
googlecodelabs/android-compose-codelabs
AdvancedStateAndSideEffectsCodelab/app/src/main/java/androidx/compose/samples/crane/home/SearchUserInput.kt
1
4499
/* * Copyright 2020 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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 androidx.compose.samples.crane.home import androidx.compose.animation.animateColor import androidx.compose.animation.core.MutableTransitionState import androidx.compose.animation.core.tween import androidx.compose.animation.core.updateTransition import androidx.compose.foundation.layout.Column import androidx.compose.material.MaterialTheme import androidx.compose.material.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.State import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.samples.crane.R import androidx.compose.samples.crane.base.CraneEditableUserInput import androidx.compose.samples.crane.base.CraneUserInput import androidx.compose.samples.crane.home.PeopleUserInputAnimationState.Invalid import androidx.compose.samples.crane.home.PeopleUserInputAnimationState.Valid import androidx.compose.samples.crane.ui.CraneTheme import androidx.compose.ui.graphics.Color import androidx.compose.ui.tooling.preview.Preview enum class PeopleUserInputAnimationState { Valid, Invalid } class PeopleUserInputState { var people by mutableStateOf(1) private set val animationState: MutableTransitionState<PeopleUserInputAnimationState> = MutableTransitionState(Valid) fun addPerson() { people = (people % (MAX_PEOPLE + 1)) + 1 updateAnimationState() } private fun updateAnimationState() { val newState = if (people > MAX_PEOPLE) Invalid else Valid if (animationState.currentState != newState) animationState.targetState = newState } } @Composable fun PeopleUserInput( titleSuffix: String? = "", onPeopleChanged: (Int) -> Unit, peopleState: PeopleUserInputState = remember { PeopleUserInputState() } ) { Column { val transitionState = remember { peopleState.animationState } val tint = tintPeopleUserInput(transitionState) val people = peopleState.people CraneUserInput( text = if (people == 1) "$people Adult$titleSuffix" else "$people Adults$titleSuffix", vectorImageId = R.drawable.ic_person, tint = tint.value, onClick = { peopleState.addPerson() onPeopleChanged(peopleState.people) } ) if (transitionState.targetState == Invalid) { Text( text = "Error: We don't support more than $MAX_PEOPLE people", style = MaterialTheme.typography.body1.copy(color = MaterialTheme.colors.secondary) ) } } } @Composable fun FromDestination() { CraneUserInput(text = "Seoul, South Korea", vectorImageId = R.drawable.ic_location) } @Composable fun ToDestinationUserInput(onToDestinationChanged: (String) -> Unit) { CraneEditableUserInput( hint = "Choose Destination", caption = "To", vectorImageId = R.drawable.ic_plane, onInputChanged = onToDestinationChanged ) } @Composable fun DatesUserInput() { CraneUserInput( caption = "Select Dates", text = "", vectorImageId = R.drawable.ic_calendar ) } @Composable private fun tintPeopleUserInput( transitionState: MutableTransitionState<PeopleUserInputAnimationState> ): State<Color> { val validColor = MaterialTheme.colors.onSurface val invalidColor = MaterialTheme.colors.secondary val transition = updateTransition(transitionState, label = "") return transition.animateColor( transitionSpec = { tween(durationMillis = 300) }, label = "" ) { if (it == Valid) validColor else invalidColor } } @Preview @Composable fun PeopleUserInputPreview() { CraneTheme { PeopleUserInput(onPeopleChanged = {}) } }
apache-2.0
5e499d774a72dfbe572d00aa136ae144
31.601449
99
0.717048
4.517068
false
false
false
false
willowtreeapps/assertk
assertk/src/commonMain/kotlin/assertk/assertions/number.kt
1
941
package assertk.assertions import assertk.Assert import assertk.assertions.support.expected import assertk.assertions.support.show /** * Asserts the number is 0. * @see [isNotZero] */ fun Assert<Number>.isZero() = given { actual -> if (actual.toDouble() == 0.0) return expected("to be 0 but was:${show(actual)}") } /** * Asserts the number is not 0. * @see [isZero] */ fun Assert<Number>.isNotZero() = given { actual -> if (actual.toDouble() != 0.0) return expected("to not be 0") } /** * Asserts the number is greater than 0. * @see [isNegative] */ fun Assert<Number>.isPositive() = given { actual -> if (actual.toDouble() > 0) return expected("to be positive but was:${show(actual)}") } /** * Asserts the number is less than 0. * @see [isPositive] */ fun Assert<Number>.isNegative() = given { actual -> if (actual.toDouble() < 0) return expected("to be negative but was:${show(actual)}") }
mit
f9aea51b7a249bcd02bb8d9758b1d264
21.95122
54
0.648247
3.472325
false
false
false
false
Fondesa/RecyclerViewDivider
recycler-view-divider/src/main/kotlin/com/fondesa/recyclerviewdivider/DividerItemDecoration.kt
1
12126
/* * Copyright (c) 2020 Giorgio Antonioli * * 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.fondesa.recyclerviewdivider import android.graphics.Canvas import android.graphics.PorterDuff import android.graphics.PorterDuffColorFilter import android.graphics.Rect import android.graphics.drawable.Drawable import android.view.View import androidx.annotation.ColorInt import androidx.annotation.Px import androidx.annotation.VisibleForTesting import androidx.core.graphics.drawable.DrawableCompat import androidx.recyclerview.widget.GridLayoutManager import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import androidx.recyclerview.widget.StaggeredGridLayoutManager import com.fondesa.recyclerviewdivider.cache.GridCache import com.fondesa.recyclerviewdivider.drawable.DrawableProvider import com.fondesa.recyclerviewdivider.drawable.drawWithBounds import com.fondesa.recyclerviewdivider.inset.InsetProvider import com.fondesa.recyclerviewdivider.offset.DividerOffsetProvider import com.fondesa.recyclerviewdivider.size.SizeProvider import com.fondesa.recyclerviewdivider.tint.TintProvider import com.fondesa.recyclerviewdivider.visibility.VisibilityProvider import kotlin.math.roundToInt /** * Implementation of [DividerItemDecoration] used in a [LinearLayoutManager]/[GridLayoutManager]. * * @param asSpace true if the divider should behave as a space. * @param drawableProvider the provider of the divider's drawable. * @param insetProvider the provider of the divider's inset. * @param sizeProvider the provider of the divider's size. * @param tintProvider the provider of the divider's tint color. * @param visibilityProvider the provider of the divider's visibility. * @param offsetProvider balances the offsets of the divider. * @param cache caches the creation of the [Grid]. */ internal class DividerItemDecoration( asSpace: Boolean, @VisibleForTesting internal val drawableProvider: DrawableProvider, @VisibleForTesting internal val insetProvider: InsetProvider, @VisibleForTesting internal val sizeProvider: SizeProvider, @VisibleForTesting internal val tintProvider: TintProvider, @VisibleForTesting internal val visibilityProvider: VisibilityProvider, @VisibleForTesting internal val offsetProvider: DividerOffsetProvider, @VisibleForTesting internal val cache: GridCache ) : BaseDividerItemDecoration(asSpace) { override fun getItemOffsets( layoutManager: RecyclerView.LayoutManager, outRect: Rect, itemView: View, itemCount: Int, itemIndex: Int ) = layoutManager.withLinear { val grid = cachedGrid(itemCount) val dividers = grid.dividersAroundCell(absoluteCellIndex = itemIndex) val startDivider = dividers.getValue(Side.START) val topDivider = dividers.getValue(Side.TOP) val bottomDivider = dividers.getValue(Side.BOTTOM) val endDivider = dividers.getValue(Side.END) val layoutBottomToTop = grid.layoutDirection.isBottomToTop val layoutRightToLeft = grid.layoutDirection.isRightToLeft topDivider.computeOffsetSize(grid) { dividerSize -> @Px val size = offsetProvider.getOffsetFromSize(grid, topDivider, Side.TOP, dividerSize) if (layoutBottomToTop) outRect.bottom = size else outRect.top = size } startDivider.computeOffsetSize(grid) { dividerSize -> @Px val size = offsetProvider.getOffsetFromSize(grid, startDivider, Side.START, dividerSize) if (layoutRightToLeft) outRect.right = size else outRect.left = size } bottomDivider.computeOffsetSize(grid) { dividerSize -> @Px val size = offsetProvider.getOffsetFromSize(grid, bottomDivider, Side.BOTTOM, dividerSize) if (layoutBottomToTop) outRect.top = size else outRect.bottom = size } endDivider.computeOffsetSize(grid) { dividerSize -> @Px val size = offsetProvider.getOffsetFromSize(grid, endDivider, Side.END, dividerSize) if (layoutRightToLeft) outRect.left = size else outRect.right = size } } override fun onDraw( canvas: Canvas, recyclerView: RecyclerView, layoutManager: RecyclerView.LayoutManager, itemCount: Int ) = layoutManager.withLinear { val grid = cachedGrid(itemCount) recyclerView.forEachItem(itemCount) { itemIndex, itemView -> itemView.drawDividers(canvas, grid, itemIndex) } } override fun onDataChanged() { super.onDataChanged() cache.clear() } private fun LinearLayoutManager.cachedGrid(itemCount: Int): Grid { val spanCount = (this as? GridLayoutManager)?.spanCount ?: 1 val cachedGrid = cache.get(spanCount, itemCount) if (cachedGrid != null) return cachedGrid return grid(itemCount).also { grid -> cache.put(spanCount = spanCount, itemCount = itemCount, grid = grid) } } private fun View.drawDividers(canvas: Canvas, grid: Grid, itemIndex: Int) { val layoutBottomToTop = grid.layoutDirection.isBottomToTop val layoutRightToLeft = grid.layoutDirection.isRightToLeft val translationX = translationX.roundToInt() val translationY = translationY.roundToInt() val left = leftWithMargin + translationX val right = rightWithMargin + translationX val top = topWithMargin + translationY val bottom = bottomWithMargin + translationY val dividers = grid.dividersAroundCell(absoluteCellIndex = itemIndex) val startDivider = dividers.getValue(Side.START) val topDivider = dividers.getValue(Side.TOP) val bottomDivider = dividers.getValue(Side.BOTTOM) val endDivider = dividers.getValue(Side.END) @Px val topDividerSize = topDivider.takeIf { it.isTopDivider && it.isVisible(grid) }?.draw(grid) { size, insetStart, insetEnd -> val insetLeft = if (layoutRightToLeft) insetEnd else insetStart val insetRight = if (layoutRightToLeft) insetStart else insetEnd val topBound = if (layoutBottomToTop) bottom else top - size val bottomBound = if (layoutBottomToTop) bottom + size else top drawWithBounds(canvas = canvas, left = left + insetLeft, top = topBound, right = right - insetRight, bottom = bottomBound) } ?: 0 @Px val bottomDividerSize = bottomDivider.takeIf { it.isVisible(grid) }?.draw(grid) { size, insetStart, insetEnd -> val insetLeft = if (layoutRightToLeft) insetEnd else insetStart val insetRight = if (layoutRightToLeft) insetStart else insetEnd val topBound = if (layoutBottomToTop) top - size else bottom val bottomBound = if (layoutBottomToTop) top else bottom + size drawWithBounds(canvas = canvas, left = left + insetLeft, top = topBound, right = right - insetRight, bottom = bottomBound) } ?: 0 val topFillSize = if (layoutBottomToTop) bottomDividerSize else topDividerSize val bottomFillSize = if (layoutBottomToTop) topDividerSize else bottomDividerSize startDivider.takeIf { it.isStartDivider && it.isVisible(grid) }?.draw(grid) { size, insetStart, insetEnd -> val insetTop = if (layoutBottomToTop) insetEnd else insetStart val insetBottom = if (layoutBottomToTop) insetStart else insetEnd val filledInsetTop = if (insetTop > 0) insetTop else -topFillSize val filledInsetBottom = if (insetBottom > 0) -insetBottom else bottomFillSize val leftBound = if (layoutRightToLeft) right else left - size val rightBound = if (layoutRightToLeft) right + size else left drawWithBounds( canvas = canvas, left = leftBound, top = top + filledInsetTop, right = rightBound, bottom = bottom + filledInsetBottom ) } endDivider.takeIf { it.isVisible(grid) }?.draw(grid) { size, insetStart, insetEnd -> val insetTop = if (layoutBottomToTop) insetEnd else insetStart val insetBottom = if (layoutBottomToTop) insetStart else insetEnd val filledInsetTop = if (insetTop > 0) insetTop else -topFillSize val filledInsetBottom = if (insetBottom > 0) -insetBottom else bottomFillSize val leftBound = if (layoutRightToLeft) left - size else right val rightBound = if (layoutRightToLeft) left else right + size drawWithBounds( canvas = canvas, left = leftBound, top = top + filledInsetTop, right = rightBound, bottom = bottom + filledInsetBottom ) } } @Px private inline fun Divider.draw(grid: Grid, drawBlock: Drawable.(size: Int, insetStart: Int, insetEnd: Int) -> Unit): Int { val dividerDrawable = tintedDrawable(grid = grid) @Px val dividerSize = sizeProvider.getDividerSize(grid = grid, divider = this, dividerDrawable = dividerDrawable) @Px val insetStart = insetProvider.getDividerInsetStart(grid = grid, divider = this) @Px val insetEnd = insetProvider.getDividerInsetEnd(grid = grid, divider = this) drawBlock(dividerDrawable, dividerSize, insetStart, insetEnd) return dividerSize } private inline fun Divider.computeOffsetSize(grid: Grid, block: (dividerSize: Int) -> Unit) { if (!isVisible(grid)) return val dividerDrawable = drawableProvider.getDividerDrawable(grid = grid, divider = this) @Px val dividerSize = sizeProvider.getDividerSize(grid = grid, divider = this, dividerDrawable = dividerDrawable) block(dividerSize) } private fun Divider.isVisible(grid: Grid): Boolean = visibilityProvider.isDividerVisible(grid = grid, divider = this) private fun Divider.tintedDrawable(grid: Grid): Drawable { val dividerDrawable = drawableProvider.getDividerDrawable(grid = grid, divider = this) val tintColor = tintProvider.getDividerTintColor(grid = grid, divider = this) return dividerDrawable.tinted(tintColor) } private fun Drawable.tinted(@ColorInt tintColor: Int?): Drawable { // We can't use setColorTintList() here because setColorTintList(null) doesn't behave correctly when the drawable which // should be tinted is completely opaque. // A similar issue is reported here: https://issuetracker.google.com/issues/141678225. // e.g. using `addDivider()` with a DayNight theme and the dark mode on, the original drawable color is changed after // the call to setColorTintList(null) used to reset the tint list for each divider. val wrappedDrawable = DrawableCompat.wrap(this) if (tintColor == null) { wrappedDrawable.clearColorFilter() } else { wrappedDrawable.colorFilter = PorterDuffColorFilter(tintColor, PorterDuff.Mode.SRC_ATOP) } return wrappedDrawable } private inline fun RecyclerView.LayoutManager.withLinear(onLinear: LinearLayoutManager.() -> Unit) { when (this) { is LinearLayoutManager -> onLinear() is StaggeredGridLayoutManager -> throw IllegalLayoutManagerException( layoutManagerClass = this::class.java, suggestedBuilderClass = StaggeredDividerBuilder::class.java ) else -> throw IllegalLayoutManagerException(layoutManagerClass = this::class.java) } } }
apache-2.0
e06ac1a1c726ff52f0d85f9933d6c0fe
49.525
136
0.703282
4.775896
false
false
false
false
google-developer-training/android-basics-kotlin-inventory-app
app/src/main/java/com/example/inventory/ItemListAdapter.kt
1
2500
/* * 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.example.inventory import android.view.LayoutInflater import android.view.ViewGroup import androidx.recyclerview.widget.DiffUtil import androidx.recyclerview.widget.ListAdapter import androidx.recyclerview.widget.RecyclerView import com.example.inventory.data.Item import com.example.inventory.data.getFormattedPrice import com.example.inventory.databinding.ItemListItemBinding /** * [ListAdapter] implementation for the recyclerview. */ class ItemListAdapter(private val onItemClicked: (Item) -> Unit) : ListAdapter<Item, ItemListAdapter.ItemViewHolder>(DiffCallback) { override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ItemViewHolder { return ItemViewHolder( ItemListItemBinding.inflate( LayoutInflater.from( parent.context ) ) ) } override fun onBindViewHolder(holder: ItemViewHolder, position: Int) { val current = getItem(position) holder.itemView.setOnClickListener { onItemClicked(current) } holder.bind(current) } class ItemViewHolder(private var binding: ItemListItemBinding) : RecyclerView.ViewHolder(binding.root) { fun bind(item: Item) { binding.itemName.text = item.itemName binding.itemPrice.text = item.getFormattedPrice() binding.itemQuantity.text = item.quantityInStock.toString() } } companion object { private val DiffCallback = object : DiffUtil.ItemCallback<Item>() { override fun areItemsTheSame(oldItem: Item, newItem: Item): Boolean { return oldItem === newItem } override fun areContentsTheSame(oldItem: Item, newItem: Item): Boolean { return oldItem.itemName == newItem.itemName } } } }
apache-2.0
fcde8e7a277a9ad574256f1fc7be1cd2
33.246575
87
0.684
4.901961
false
false
false
false
Bastien7/Lux-transport-analyzer
src/main/com/bastien7/transport/analyzer/forecast/algorithms/impl/PreviousWeeksAlgorithm.kt
1
1953
package com.bastien7.transport.analyzer.forecast.algorithms.impl import com.bastien7.transport.analyzer.configuration.DataParameters import com.bastien7.transport.analyzer.forecast.algorithms.ForecastAlgorithm import com.bastien7.transport.analyzer.forecast.entity.ParkForecast import com.bastien7.transport.analyzer.forecast.entity.ParkStateForecast import com.bastien7.transport.analyzer.park.entity.Park import com.bastien7.transport.analyzer.park.entity.ParkState import com.bastien7.transport.analyzer.park.service.ParkStateService import java.time.LocalDateTime object PreviousWeeksAlgorithm : ForecastAlgorithm { override fun getForecast(parkStateService: ParkStateService, date: LocalDateTime): ParkStateForecast { var referenceDate = date val now = LocalDateTime.now() //Optimization while (referenceDate.isAfter(now)) referenceDate = referenceDate.minusWeeks(1) val parkStates: List<ParkState> = (1..DataParameters.NUMBER_OF_WEEK_CONSIDERED) .map { referenceDate.minusWeeks(it.toLong()) } .map { parkStateService.getParkState(it) } .filterNotNull() return ParkStateForecast(parkStates.flatMap { it.parks }.groupBy { it.id }.map { getAverage(it.value) }, referenceDate) } fun getAverage(parks: List<Park>): ParkForecast { val first: Park = parks.first() val availablePlaces: Int = parks.sumBy { it.availablePlaces } / parks.size val totalPlaces: Int = parks.maxBy { it.totalPlaces }?.totalPlaces ?: 0 val open: Boolean = parks.find { !it.open } !is Park val paid: Boolean = parks.find { !it.paid } !is Park val reliability: Double = Math.sqrt(parks.sumByDouble { Math.pow((it.availablePlaces - availablePlaces).toDouble(), 2.0) } / parks.size) return ParkForecast(first.id, first.name, availablePlaces, totalPlaces, null, open, paid, first.address, reliability) } }
apache-2.0
b190005172f96c28272f85642a19650e
50.421053
144
0.728623
4.010267
false
false
false
false
coil-kt/coil
coil-base/src/test/java/coil/util/DrawableUtilsTest.kt
1
3382
package coil.util import android.content.Context import android.graphics.Bitmap import android.graphics.drawable.VectorDrawable import androidx.appcompat.content.res.AppCompatResources import androidx.core.graphics.applyCanvas import androidx.core.graphics.component1 import androidx.core.graphics.component2 import androidx.core.graphics.component3 import androidx.core.graphics.component4 import androidx.test.core.app.ApplicationProvider import coil.base.R import coil.size.Scale import coil.size.Size import kotlin.test.assertEquals import org.junit.Test import org.junit.runner.RunWith import org.robolectric.RobolectricTestRunner @RunWith(RobolectricTestRunner::class) class DrawableUtilsTest { @Test fun `vector with hardware config is converted correctly`() { val size = Size(200, 200) val input = object : VectorDrawable() { override fun getIntrinsicWidth() = 100 override fun getIntrinsicHeight() = 100 } val output = DrawableUtils.convertToBitmap( drawable = input, config = Bitmap.Config.HARDWARE, size = size, scale = Scale.FIT, allowInexactSize = true ) assertEquals(Bitmap.Config.ARGB_8888, output.config) assertEquals(size, output.size) } /** Regression test: https://github.com/coil-kt/coil/issues/1081 */ @Test fun `rectangular vector is converted correctly`() { val size = Size(200, 200) val context: Context = ApplicationProvider.getApplicationContext() val vector = AppCompatResources.getDrawable(context, R.drawable.ic_100tb)!! val expected = createBitmap(200, 74).applyCanvas { val (oldLeft, oldTop, oldRight, oldBottom) = vector.bounds vector.setBounds(0, 0, width, height) vector.draw(this) vector.setBounds(oldLeft, oldTop, oldRight, oldBottom) } val actual = DrawableUtils.convertToBitmap( drawable = vector, config = Bitmap.Config.HARDWARE, size = size, scale = Scale.FIT, allowInexactSize = true ) actual.assertIsSimilarTo(expected) } @Test fun `unimplemented intrinsic size does not crash`() { val size = Size(200, 200) val input = object : VectorDrawable() { override fun getIntrinsicWidth() = -1 override fun getIntrinsicHeight() = -1 } val output = DrawableUtils.convertToBitmap( drawable = input, size = size, config = Bitmap.Config.HARDWARE, scale = Scale.FIT, allowInexactSize = true ) assertEquals(Bitmap.Config.ARGB_8888, output.config) assertEquals(size, output.size) } @Test fun `aspect ratio is preserved`() { val input = object : VectorDrawable() { override fun getIntrinsicWidth() = 125 override fun getIntrinsicHeight() = 250 } val output = DrawableUtils.convertToBitmap( drawable = input, size = Size(200, 200), config = Bitmap.Config.ARGB_8888, scale = Scale.FIT, allowInexactSize = true ) assertEquals(Bitmap.Config.ARGB_8888, output.config) assertEquals(Size(100, 200), output.size) } }
apache-2.0
fcc0a5b527568d510676e5f9e376008d
31.834951
83
0.637788
4.743338
false
true
false
false
sungmin-park/validator.kt
src/main/kotlin/com/github/sungminpark/validator/OneOf.kt
1
2650
package com.github.sungminpark.validator import org.apache.commons.beanutils.PropertyUtils import javax.validation.Constraint import javax.validation.ConstraintValidator import javax.validation.ConstraintValidatorContext import javax.validation.Payload import kotlin.reflect.KClass @Suppress("DEPRECATED_JAVA_ANNOTATION") @Target(AnnotationTarget.CLASS) @Retention @Constraint(validatedBy = arrayOf(OneOfValidator::class)) @Repeatable @java.lang.annotation.Repeatable(OneOfList::class) annotation class OneOf(val value: String, val items: String, val message: String = "{com.github.sungminpark.validator.OneOf}", @Suppress("unused") val groups: Array<KClass<*>> = arrayOf(), @Suppress("unused") val payload: Array<KClass<out Payload>> = arrayOf()) @Target(AnnotationTarget.CLASS) @Retention annotation class OneOfList(val value: Array<OneOf>) class OneOfValidator : ConstraintValidator<OneOf, Any> { private lateinit var value: String private lateinit var items: String private lateinit var message: String override fun initialize(constraintAnnotation: OneOf) { this.value = constraintAnnotation.value this.items = constraintAnnotation.items this.message = constraintAnnotation.message } override fun isValid(value: Any?, context: ConstraintValidatorContext): Boolean { if (value == null) { return true } val target = PropertyUtils.getSimpleProperty(value, this.value) ?: return true val items = PropertyUtils.getSimpleProperty(value, items) ?: return true val targets = when (target) { is Collection<*> -> target.filterNotNull() else -> listOf(target) } val isValid = targets.firstOrNull { !validate(it, items) } == null if (!isValid) { context.disableDefaultConstraintViolation() context .buildConstraintViolationWithTemplate(message) .addPropertyNode(this.value) .addConstraintViolation() } return isValid } private fun validate(value: Any, items: Any): Boolean { return when (items) { is Collection<*> -> { items.firstOrNull { it == value } != null } is Map<*, *> -> { validate(value, items.keys) } is Array<*> -> { validate(value, items.toList()) } else -> throw IllegalArgumentException("Items should be collection or map.") } } }
mit
9946e3fa10fdf022a679df468db0ab11
32.974359
95
0.629434
4.94403
false
false
false
false
STUDIO-apps/GeoShare_Android
mobile/src/main/java/uk/co/appsbystudio/geoshare/utils/geocoder/GeocodingFromLatLngTask.kt
1
1383
package uk.co.appsbystudio.geoshare.utils.geocoder import android.arch.lifecycle.MutableLiveData import android.os.AsyncTask import org.json.JSONArray import org.json.JSONException import org.json.JSONObject import uk.co.appsbystudio.geoshare.utils.downloadUrl import uk.co.appsbystudio.geoshare.utils.getReverseGeocodingUrl import java.io.IOException class GeocodingFromLatLngTask(private val lat: Double, private val lng: Double, private val liveData: MutableLiveData<String>? = null) : AsyncTask<Void, Void, String>() { override fun doInBackground(vararg voids: Void): String? { var finalAddress: String? = null val url = getReverseGeocodingUrl(lat, lng) try { val jsonResponse = downloadUrl(url) val jsonObject = JSONObject(jsonResponse) finalAddress = (jsonObject.get("results") as JSONArray).getJSONObject(0).getString("formatted_address") } catch (e: IOException) { e.printStackTrace() } catch (e: JSONException) { e.printStackTrace() } return finalAddress } override fun onPostExecute(result: String?) { super.onPostExecute(result) if (liveData != null && result != null && !result.isBlank()) { liveData.value = result return } liveData?.value = "Could not get address..." } }
apache-2.0
7294f1063b0e5a087291d77f9d8643ac
30.454545
170
0.673174
4.564356
false
false
false
false
YounesRahimi/java-utils
src/main/java/ir/iais/utilities/javautils/services/db/HSession.kt
2
2600
//package ir.iais.utilities.javautils.services.db // //import ir.iais.utilities.javautils.IQ //import ir.iais.utilities.javautils.services.db.interfaces.ISession //import org.hibernate.Session //import org.hibernate.SessionFactory //import org.hibernate.resource.transaction.spi.TransactionStatus.COMMITTED //import org.hibernate.resource.transaction.spi.TransactionStatus.ROLLED_BACK //import org.springframework.stereotype.Component //import javax.inject.Inject //import javax.persistence.EntityManager //import javax.persistence.EntityManagerFactory // ////@Deprecated("Use spring data jpa framework ") //@Component //class HSession @Inject //constructor(private @Transient val emfSupl: IEntityManagerFactorySupplier) : ISession, IQ { // // constructor(emfs: () -> EntityManagerFactory) : this(emfs.toEMFSupplier) // // private val entityManager by lazy { emfSupl().createEntityManager()!! } // private var counter: Int = 0 // // // override fun openSession(beginTransaction: Boolean): HSession { // if (canBeginTransaction(beginTransaction)) entityManager.transaction.begin() // return this // } // // val isOpen: Boolean // get() = entityManager.isOpen // // override fun session(): EntityManager { // return entityManager // } // // override fun commit() { // if (isOpen && isTransactionBegun) entityManager.transaction.commit() // } // // override fun rollback() { // if (isOpen && isTransactionBegun) { // logger.info("entityManager rolled back. hashCode: " + entityManager.hashCode()) // entityManager.transaction.rollback() // } // } // // override fun close() { // if (!isOpen) return // entityManager.clear() // entityManager.close() // } // // private fun canBeginTransaction(beginTransaction: Boolean): Boolean { // return beginTransaction && (entityManager.transaction == null // || !entityManager.transaction.isActive // || entityManager.unwrap(Session::class.java).transaction.status.isOneOf(COMMITTED, ROLLED_BACK)) // } // // private val isTransactionBegun: Boolean // get() = !canBeginTransaction(java.lang.Boolean.TRUE) // // override fun evict(entity: Any) { // entityManager.unwrap(Session::class.java).evict(entity) // if ((++counter) % FetchSize == 0) { // emfSupl().unwrap(SessionFactory::class.java).cache.evictEntityRegion(entity.javaClass) // System.gc() // } // } // // companion object { // val FetchSize = 500 // } //}
gpl-3.0
9aba437b4d733e247c87f53481c7b6dd
34.135135
114
0.663846
3.933434
false
false
false
false
JayNewstrom/ScreenSwitcher
screen-switcher-sample/src/androidTest/java/screenswitchersample/activity/MainActivityTest.kt
1
7167
package screenswitchersample.activity import android.animation.ValueAnimator import androidx.test.espresso.Espresso.onView import androidx.test.espresso.Espresso.pressBack import androidx.test.espresso.action.ViewActions.click import androidx.test.espresso.action.ViewActions.replaceText import androidx.test.espresso.assertion.ViewAssertions.matches import androidx.test.espresso.matcher.ViewMatchers.isDisplayed import androidx.test.espresso.matcher.ViewMatchers.withId import androidx.test.espresso.matcher.ViewMatchers.withText import androidx.test.ext.junit.runners.AndroidJUnit4 import androidx.test.rule.ActivityTestRule import org.fest.assertions.api.Assertions.assertThat import org.junit.Before import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith import screenswitchersample.R import screenswitchersample.core.activity.ScreenSwitcherActivity import screenswitchersample.espressotestingbootstrap.matchers.withTextView import screenswitchersample.espressotestingbootstrap.test.recreateActivity @RunWith(AndroidJUnit4::class) class MainActivityTest { @get:Rule val activityTestRule = ActivityTestRule(ScreenSwitcherActivity::class.java) // Animations need to be turned off in order for these to pass. @Before fun setup() { val method = ValueAnimator::class.java.getDeclaredMethod("setDurationScale", Float::class.javaPrimitiveType) method.invoke(null, 0.toFloat()) } @Test fun testAllTheThings() { onView(withId(R.id.btn_second)).perform(click()) pressBack() onView(withId(R.id.btn_confirm_pop)).perform(click()) onView(withId(R.id.btn_second)).perform(click()) onView(withId(R.id.btn_third)).perform(click()) pressBack() onView(withId(R.id.btn_third)).perform(click()) onView(withId(R.id.btn_pop_two)).perform(click()) onView(withId(R.id.btn_confirm_pop)).check(matches(isDisplayed())) } @Test fun testReplaceRootScreenInTabBar() { onView(withId(R.id.btn_replace_with_second)).perform(click()) onView(withTextView(id = R.id.title_text_view, text = "Second Screen")).check(matches(isDisplayed())) onView(withText("Color")).perform(click()) onView(withTextView(id = R.id.color_text_view, text = "#FF0000")).check(matches(isDisplayed())) onView(withText("Demo")).perform(click()) onView(withTextView(id = R.id.title_text_view, text = "Second Screen")).check(matches(isDisplayed())) } @Test fun testClickingTabItemPopsToRootOfTab() { onView(withId(R.id.btn_second)).perform(click()) onView(withText("Color")).perform(click()) onView(withTextView(id = R.id.edit_text, text = "")).perform(replaceText("#00FF00")) onView(withTextView(id = R.id.submit_button, text = "Submit")).perform(click()) onView(withTextView(id = R.id.color_text_view, text = "#00FF00")).check(matches(isDisplayed())) onView(withTextView(id = R.id.edit_text, text = "")).perform(replaceText("#0000FF")) onView(withTextView(id = R.id.submit_button, text = "Submit")).perform(click()) onView(withTextView(id = R.id.color_text_view, text = "#0000FF")).check(matches(isDisplayed())) onView(withText("Color")).perform(click()) onView(withTextView(id = R.id.color_text_view, text = "#FF0000")).check(matches(isDisplayed())) } @Test fun testExitConfirmation() { onView(withId(R.id.btn_second)).perform(click()) onView(withText("Color")).perform(click()) onView(withTextView(id = R.id.edit_text, text = "")).perform(replaceText("#00FF00")) onView(withText("Submit")).perform(click()) onView(withTextView(id = R.id.color_text_view, text = "#00FF00")).check(matches(isDisplayed())) pressBack() onView(withTextView(id = R.id.color_text_view, text = "#FF0000")).check(matches(isDisplayed())) pressBack() onView(withTextView(id = R.id.title_text_view, text = "Second Screen")).check(matches(isDisplayed())) pressBack() onView(withId(R.id.btn_confirm_pop)).perform(click()) onView(withText("First Screen")).check(matches(isDisplayed())) pressBack() onView(withText("Are you sure you want to exit?")).check(matches(isDisplayed())) onView(withText("Exit")).perform(click()) assertThat(activityTestRule.activity.isFinishing).isTrue } @Test fun testDialogSavedStateRestoration() { onView(withId(R.id.btn_show_first_dialog)).perform(click()) onView(withId(R.id.first_edit_text)).perform(replaceText("This is some text!")) activityTestRule.recreateActivity() onView(withId(R.id.first_edit_text)).check(matches(withText("This is some text!"))) } @Test fun testContentSavedStateRestoration() { onView(withText("Color")).perform(click()) onView(withTextView(id = R.id.color_text_view, text = "#FF0000")).check(matches(isDisplayed())) onView(withTextView(id = R.id.edit_text, text = "")).perform(replaceText("#00FF00")) onView(withId(R.id.submit_button)).perform(click()) onView(withTextView(id = R.id.color_text_view, text = "#00FF00")).check(matches(isDisplayed())) onView(withTextView(id = R.id.edit_text, text = "")).perform(replaceText("preserve me!")) activityTestRule.recreateActivity() onView(withTextView(id = R.id.color_text_view, text = "#00FF00")).check(matches(isDisplayed())) onView(withTextView(id = R.id.edit_text, text = "preserve me!")).check(matches(isDisplayed())) pressBack() onView(withTextView(id = R.id.edit_text, text = "#00FF00")).check(matches(isDisplayed())) } @Test fun testBadgeIconUpdate() { onView(withText("Badge")).perform(click()) onView(withTextView(id = R.id.bottom_bar_badge_text_view, text = "5")).check(matches(isDisplayed())) onView(withText("Increment 1")).perform(click()) onView(withTextView(id = R.id.bottom_bar_badge_text_view, text = "6")).check(matches(isDisplayed())) onView(withText("Increment 1")).perform(click(), click()) onView(withTextView(id = R.id.bottom_bar_badge_text_view, text = "8")).check(matches(isDisplayed())) onView(withText("Decrement 1")).perform(click(), click(), click(), click()) onView(withTextView(id = R.id.bottom_bar_badge_text_view, text = "4")).check(matches(isDisplayed())) } @Test fun testDialogWithNavigationWorks() { onView(withId(R.id.btn_show_navigate_dialog)).perform(click()) onView(withId(R.id.navigate_to_second_screen_button)).perform(click()) pressBack() onView(withId(R.id.btn_confirm_pop)).perform(click()) onView(withId(R.id.btn_show_navigate_dialog)).perform(click()) activityTestRule.recreateActivity() onView(withId(R.id.navigate_to_second_screen_button)).perform(click()) pressBack() onView(withId(R.id.btn_confirm_pop)).check(matches(isDisplayed())).perform(click()) // Ensure removing the screen doesn't leak anything! onView(withId(R.id.btn_replace_with_second)).perform(click()) } }
apache-2.0
c40179694dfb6a7b111b11022eaea5f3
52.088889
116
0.687735
3.907852
false
true
false
false
anton-okolelov/intellij-rust
src/main/kotlin/org/rust/ide/lineMarkers/RsCrateDocLineMarkerProvider.kt
2
1654
/* * Use of this source code is governed by the MIT license that can be * found in the LICENSE file. */ package org.rust.ide.lineMarkers import com.intellij.codeHighlighting.Pass import com.intellij.codeInsight.daemon.LineMarkerInfo import com.intellij.codeInsight.daemon.LineMarkerProvider import com.intellij.ide.BrowserUtil import com.intellij.openapi.editor.markup.GutterIconRenderer import com.intellij.psi.PsiElement import org.rust.ide.icons.RsIcons import org.rust.lang.core.psi.RsExternCrateItem import org.rust.lang.core.psi.ext.containingCargoPackage /** * Provides an external crate imports with gutter icons that open documentation on docs.rs. */ class RsCrateDocLineMarkerProvider : LineMarkerProvider { override fun getLineMarkerInfo(element: PsiElement): LineMarkerInfo<PsiElement>? { val parent = element.parent if (!(parent is RsExternCrateItem && parent.crate == element)) return null val crateName = parent.name ?: return null val crate = parent.containingCargoPackage?.findDependency(crateName) ?: return null if (crate.pkg.source == null) return null return LineMarkerInfo( element, element.textRange, RsIcons.DOCS_MARK, Pass.LINE_MARKERS, { "Open documentation for `${crate.pkg.normName}`" }, { _, _ -> BrowserUtil.browse("https://docs.rs/${crate.pkg.name}/${crate.pkg.version}/${crate.normName}") }, GutterIconRenderer.Alignment.LEFT ) } override fun collectSlowLineMarkers(elements: List<PsiElement>, result: MutableCollection<LineMarkerInfo<PsiElement>>) { } }
mit
8855a3ab5243f93e279fb0a8b58dcb3f
37.465116
124
0.71584
4.633053
false
false
false
false
anton-okolelov/intellij-rust
src/test/kotlin/org/rust/cargo/project/model/CargoProjectsServiceTest.kt
3
1219
/* * Use of this source code is governed by the MIT license that can be * found in the LICENSE file. */ package org.rust.cargo.project.model import com.intellij.testFramework.LightPlatformTestCase import org.rust.cargo.project.model.impl.CargoProjectsServiceImpl import org.rust.openapiext.elementFromXmlString import org.rust.openapiext.toXmlString import java.nio.file.Paths class CargoProjectsServiceTest : LightPlatformTestCase() { fun `test serialization`() { val service = CargoProjectsServiceImpl(LightPlatformTestCase.getProject()) val text = """ <state> <cargoProject FILE="/foo" /> <cargoProject FILE="/bar" /> </state> """ service.loadState(elementFromXmlString(text)) val actual = service.state.toXmlString() check(actual == text.trimIndent()) { "Expected:\n$text\nActual:\n$actual" } val projects = service.allProjects.sortedBy { it.manifest }.map { it.manifest } val expectedProjects = listOf(Paths.get("/bar"), Paths.get("/foo")) check(projects == expectedProjects) { "Expected:\n$expectedProjects\nActual:\n$projects" } } }
mit
73e47d8da85da14ce3b4f4d4a8777f4c
33.828571
87
0.659557
4.384892
false
true
false
false
anton-okolelov/intellij-rust
src/main/kotlin/org/rust/lang/core/psi/ext/RsItemsOwner.kt
1
1682
/* * 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.psi.stubs.StubElement import org.rust.lang.core.psi.RsBlock import org.rust.lang.core.psi.RsFile import org.rust.lang.core.psi.RsMacroCall import org.rust.lang.core.psi.RsModItem interface RsItemsOwner : RsElement val RsItemsOwner.itemsAndMacros: Sequence<RsElement> get() { val stubChildren: List<StubElement<*>>? = run { when (this) { is RsFile -> { val stub = stub if (stub != null) return@run stub.childrenStubs } is RsModItem -> { val stub = stub if (stub != null) return@run stub.childrenStubs } is RsBlock -> { val stub = stub if(stub != null) return@run stub.childrenStubs } } null } return if (stubChildren != null) { stubChildren.asSequence().map { it.psi } } else { generateSequence(firstChild) { it.nextSibling } }.filterIsInstance<RsElement>() } fun RsItemsOwner.processExpandedItems(f: (RsItemElement) -> Boolean): Boolean { for (psi in itemsAndMacros) { when (psi) { is RsMacroCall -> for (expanded in psi.expansion.orEmpty()) { if (expanded is RsItemElement && f(expanded)) return true } is RsItemElement -> if (f(psi)) return true } } return false }
mit
a0e9af5eb5b6a0854ca531847a61a424
28
79
0.53805
4.558266
false
false
false
false
shaeberling/euler
kotlin/src/com/s13g/aoc/aoc2020/Day2.kt
1
970
package com.s13g.aoc.aoc2020 import com.s13g.aoc.Result import com.s13g.aoc.Solver /** * --- Day 2: Password Philosophy --- * https://adventofcode.com/2020/day/2 */ class Day2 : Solver { private val regex = """(\d+)-(\d+) (.): (.*)""".toRegex() override fun solve(lines: List<String>): Result { val input = lines.map { parse(it) } val resultA = input.count { it.isLegalA() } val resultB = input.count { it.isLegalB() } return Result("$resultA", "$resultB") } private fun parse(row: String): Rule { val (a, b, ch, pass) = row.match(regex) return Rule(a.toInt(), b.toInt(), ch[0], pass) } private data class Rule(val a: Int, val b: Int, val ch: Char, val pass: String) private fun Rule.isLegalA() = pass.count { it == ch }.let { it in a..b } private fun Rule.isLegalB() = (pass.length >= a && pass[a - 1] == ch) xor (pass.length >= b && pass[b - 1] == ch) } private fun String.match(r: Regex) = r.find(this)!!.destructured
apache-2.0
1b717df536166a10fadff22a2af1e4d0
30.322581
115
0.613402
2.993827
false
false
false
false
beyama/winter
winter-testing/src/main/kotlin/io/jentz/winter/testing/ReflectExt.kt
1
1772
package io.jentz.winter.testing import io.jentz.winter.ClassTypeKey import io.jentz.winter.TypeKey import io.jentz.winter.WinterException import javax.inject.Named import kotlin.reflect.KClass import kotlin.reflect.KMutableProperty1 import kotlin.reflect.KProperty1 import kotlin.reflect.full.declaredMemberProperties import kotlin.reflect.full.findAnnotation import kotlin.reflect.jvm.javaField internal val KProperty1<*, *>.typeKey: TypeKey<Any> get() { val clazz = (returnType.classifier as? KClass<*>)?.javaObjectType ?: throw IllegalArgumentException("Can't get return type for property `$name`") return ClassTypeKey(clazz, namedAnnotationValue) } internal val KProperty1<*, *>.namedAnnotationValue: String? get() = findAnnotationIncludingField<Named>()?.value internal inline fun <reified T : Annotation> KProperty1<*, *>.findAnnotationIncludingField(): T? = findAnnotation() ?: (this as? KMutableProperty1)?.setter?.findAnnotation() ?: javaField?.getAnnotation(T::class.java) internal fun KClass<*>.getDeclaredMemberProperty(name: String): KProperty1<Any, *> { val property = this.declaredMemberProperties.find { it.name == name } ?: throw WinterException("Property with name `$name` not found.") @Suppress("UNCHECKED_CAST") return property as KProperty1<Any, *> } internal fun KProperty1<*, *>.hasMockAnnotation(): Boolean { if (annotations.any { containsMockOrSpy(it.annotationClass.java.simpleName) }) { return true } val field = javaField ?: return false return field.annotations.any { containsMockOrSpy(it.annotationClass.java.name) } } private fun containsMockOrSpy(string: String): Boolean = string.contains("Mock") || string.contains("Spy")
apache-2.0
b5bae8039e262dd68abc5726fc90a280
36.702128
91
0.734763
4.397022
false
false
false
false
sepatel/tekniq
tekniq-core/src/test/kotlin/io/tekniq/schedule/TqCronSpek.kt
1
1460
package io.tekniq.schedule import org.spekframework.spek2.Spek import org.spekframework.spek2.style.specification.describe import java.util.* import kotlin.test.assertEquals object TqCronSpek : Spek({ val base = Calendar.getInstance().apply { set(Calendar.YEAR, 2017) set(Calendar.MONTH, Calendar.APRIL) set(Calendar.DAY_OF_MONTH, 1) set(Calendar.HOUR_OF_DAY, 0) set(Calendar.MINUTE, 0) set(Calendar.SECOND, 0) set(Calendar.MILLISECOND, 0) }.time describe("basic pattern") { it("triggers every 10th second") { val cron = TqCron("10 * * * * *") var now = base IntRange(1, 8).forEach { now = cron.next(now) assertEquals(10000L + ((it - 1) * 60000L), now.time - base.time) } } it("triggers every 10 seconds") { val cron = TqCron("*/10 * * * * *") var now = base IntRange(1, 8).forEach { now = cron.next(now) assertEquals(10000L + ((it - 1) * 10000L), now.time - base.time) } } it("triggers at noon daily") { val cron = TqCron("0 0 12 * * *") var now = base IntRange(1, 8).forEach { now = cron.next(now) assertEquals(60000L * 60 * 12 + ((it - 1) * 60000L * 60 * 24), now.time - base.time) } } } })
mit
e9bee192ec84d2393cb190c21625df62
29.416667
100
0.512329
3.782383
false
false
false
false
uber/RIBs
android/libraries/rib-workflow/src/main/kotlin/com/uber/rib/workflow/core/Step.kt
1
5351
/* * Copyright (C) 2017. Uber Technologies * * 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.uber.rib.workflow.core import com.google.common.base.Optional import com.uber.rib.core.lifecycle.InteractorEvent import io.reactivex.Observable import io.reactivex.Single import io.reactivex.android.schedulers.AndroidSchedulers import io.reactivex.functions.BiFunction /** * Represents a unit of work for workflows. * * @param <T> type of return value (if any) for this step. * @param <A> type of [ActionableItem] this step returns when finished. */ open class Step<T, A : ActionableItem> private constructor( private val stepDataSingle: Single<Optional<Data<T, A>>> ) { /** * Chains another step to be performed after this step completes. If the previous step results in * an error and does not emit a new actionable item, future chained onStep calls will not be * called. * * @param func to return the next step when this current step completes. This function will * receive the result of the previous step and the next actionable item to take an action on. * @param <T2> the value type returned by the next step. * @param <A2> the actionable item type returned by the next step. * @return a [Step] to chain more calls to. */ @SuppressWarnings("RxJavaToSingle") // Replace singleOrError() with firstOrError() open fun <T2, A2 : ActionableItem> onStep(func: BiFunction<T, A, Step<T2, A2>>): Step<T2, A2> { return Step( asObservable() .flatMap { data: Optional<Data<T, A>> -> if (data.isPresent) { func.apply(data.get().getValue(), data.get().actionableItem).asObservable() } else { Observable.just(Optional.absent()) } } .singleOrError() ) } internal open fun asResultObservable(): Observable<Optional<T>> { return asObservable().map { data -> Optional.fromNullable(data.orNull()?.getValue()) } } internal open fun asObservable(): Observable<Optional<Data<T, A>>> { val cachedObservable: Observable<Optional<Data<T, A>>> = stepDataSingle.toObservable() .observeOn(AndroidSchedulers.mainThread()) .cache() return cachedObservable.flatMap { dataOptional: Optional<Data<T, A>> -> if (dataOptional.isPresent) { dataOptional.get() .actionableItem .lifecycle() .filter { interactorEvent -> interactorEvent === InteractorEvent.ACTIVE } .zipWith(cachedObservable) { _, data -> data } } else { Observable.just(Optional.absent()) } } } /** * Data model for the result of a step. * * @param <T> type of return value (if any) for this step. * @param <A> type of [ActionableItem] this step returns when finished. * @param value for this instance. * @param actionableItem for this instance. */ open class Data<T, A : ActionableItem>(private val value: T, internal val actionableItem: A) { internal open fun getValue() = value companion object { /** * Convenience function to create a [Step.Data] instance that does not have a return value * type. * * @param actionableItem to advance to. * @param <A> type of actionable item. * @return a new [Step.Data] instance. </A> */ @JvmStatic fun <A : ActionableItem> toActionableItem(actionableItem: A): Data<NoValue, A> { return Data(NoValueHolder.INSTANCE, actionableItem) } } } /** Used to indicate that a step has no return value. */ open class NoValue /** Initialization On Demand Singleton for [NoValue]. */ private object NoValueHolder { val INSTANCE = NoValue() } companion object { /** * Create a new step with a single that always returns a value. * * @param stepDataSingle - a single that returns a result for this step. * @param <T> type of return value (if any) for this step. * @param <A> type of [ActionableItem] this step returns when finished * @return a new [Step]. */ @JvmStatic fun <T, A : ActionableItem> from(stepDataSingle: Single<Data<T, A>>): Step<T, A> { return Step(stepDataSingle.map { Optional.of(it) }) } /** * Create a new step with a single that can emit an absent result. * * Absent results should be used when a step could not complete its action and can not move * forward. * * @param stepDataSingle - a single that returns a result for this step. * @param <T> type of return value (if any) for this step. * @param <A> type of [ActionableItem] this step returns when finished * @return a new [Step]. */ @JvmStatic fun <T, A : ActionableItem> fromOptional( stepDataSingle: Single<Optional<Data<T, A>>> ): Step<T, A> = Step(stepDataSingle) } }
apache-2.0
10f6c23555a65e332ae7a4a74aaf5c24
35.155405
99
0.663427
4.002244
false
false
false
false
kvnxiao/kommandant
kommandant-configurable/src/test/kotlin/testcommands/EnabledDisabledCommands.kt
2
1839
/* * Copyright 2017 Ze Hao Xiao * * 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 testcommands import com.github.kvnxiao.kommandant.command.CommandAnn import com.github.kvnxiao.kommandant.command.CommandContext class EnabledDisabledCommands { @CommandAnn( uniqueName = "enabled", aliases = arrayOf("enabled"), isDisabled = false ) fun enabled(context: CommandContext, vararg opt: Any?): String { return "This command is enabled" } @CommandAnn( uniqueName = "disabled", aliases = arrayOf("disabled"), isDisabled = true ) fun disabled(context: CommandContext, vararg opt: Any?): String { return "This command is disabled" } @CommandAnn( uniqueName = "parentenabled", aliases = arrayOf("parent"), isDisabled = false ) fun parentEnabled(context: CommandContext, vararg opt: Any?): String { return "This main command is enabled" } @CommandAnn( uniqueName = "childdisabled", aliases = arrayOf("child"), isDisabled = true, parentName = "parentenabled" ) fun childDisabled(context: CommandContext, vararg opt: Any?): String { return "This sub command is disabled" } }
apache-2.0
8c864296d1f4c575fed2da2bce664e68
29.666667
75
0.648722
4.655696
false
false
false
false
asymmetric-team/secure-messenger-android
conversations-list-view/src/main/java/com/safechat/conversation/select/ConversationsListActivity.kt
1
2850
package com.safechat.conversation.select import android.content.Context import android.content.Intent import android.graphics.Typeface import android.os.Bundle import android.support.annotation.IdRes import android.support.v4.content.ContextCompat import android.support.v7.app.AppCompatActivity import android.support.v7.widget.LinearLayoutManager import android.support.v7.widget.RecyclerView import android.support.v7.widget.Toolbar import android.view.View import android.widget.TextView import android.widget.ViewFlipper import com.elpassion.android.commons.recycler.BaseRecyclerViewAdapter import com.elpassion.android.commons.recycler.ItemAdapter import com.safechat.message.Message class ConversationsListActivity : AppCompatActivity(), ConversationsListView { val controller by lazy { conversationsListControllerProvider(this) } val contentFlipper by lazy { findViewById(R.id.conversation_list_flipper) as ViewFlipper } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.select_conversation) setSupportActionBar(findViewById(R.id.toolbar) as Toolbar) supportActionBar!!.setTitle(R.string.conversation_list_title) findViewById(R.id.conversation_menu)!!.setOnClickListener { onCreateConversationSelect(this) } } override fun onResume() { super.onResume() controller.onResume() } override fun showEmptyConversationsPlaceholder() { contentFlipper.show(R.id.empty_conversation_placeholder) } override fun showConversations(conversations: Map<String, Message>) { contentFlipper.show(R.id.conversation_select_list) val recycler = findViewById(R.id.conversation_select_list) as RecyclerView recycler.layoutManager = LinearLayoutManager(this) recycler.adapter = BaseRecyclerViewAdapter( conversations.map { mapToItemAdapter(it.key, it.value) } .flatMap { listOf(it, SeparatorItemAdapter()) } ) } private fun mapToItemAdapter(user: String, message: Message): UserItemAdapter { return UserItemAdapter(user, message, onRsaSelected) } private val onRsaSelected: (String) -> Unit = { rsa -> onPublicKeySelect(this, rsa) } companion object { lateinit var conversationsListControllerProvider: (ConversationsListActivity) -> ConversationsListController lateinit var onPublicKeySelect: (Context, String) -> Unit lateinit var onCreateConversationSelect: (Context) -> Unit fun start(context: Context) { context.startActivity(Intent(context, ConversationsListActivity::class.java)) } } } fun ViewFlipper.show(@IdRes viewId: Int) { val child = findViewById(viewId) displayedChild = indexOfChild(child) }
apache-2.0
fef25fe66da667ed76bf0102eb75acf7
36.5
116
0.742807
4.765886
false
false
false
false
http4k/http4k
http4k-opentelemetry/src/test/kotlin/org/http4k/filter/OpenTelemetryMetricsServerTest.kt
1
8323
package org.http4k.filter import com.natpryce.hamkrest.MatchResult import com.natpryce.hamkrest.MatchResult.Match import com.natpryce.hamkrest.MatchResult.Mismatch import com.natpryce.hamkrest.Matcher import com.natpryce.hamkrest.and import com.natpryce.hamkrest.assertion.assertThat import io.opentelemetry.api.GlobalOpenTelemetry import io.opentelemetry.api.common.AttributeKey.stringKey import io.opentelemetry.api.common.Attributes import io.opentelemetry.sdk.metrics.data.MetricData import org.http4k.core.Method import org.http4k.core.Method.DELETE import org.http4k.core.Method.GET import org.http4k.core.Method.POST import org.http4k.core.Request import org.http4k.core.Response import org.http4k.core.Status import org.http4k.core.Status.Companion.INTERNAL_SERVER_ERROR import org.http4k.core.Status.Companion.OK import org.http4k.hamkrest.hasBody import org.http4k.hamkrest.hasStatus import org.http4k.lens.Path import org.http4k.routing.bind import org.http4k.routing.routes import org.http4k.routing.static import org.http4k.util.TickingClock import org.junit.jupiter.api.BeforeAll import org.junit.jupiter.api.Test class OpenTelemetryMetricsServerTest { companion object { @BeforeAll @JvmStatic fun setup() { GlobalOpenTelemetry.resetForTest() setupOpenTelemetryMeterProvider() } } private val clock = TickingClock() private var requestTimer = ServerFilters.OpenTelemetryMetrics.RequestTimer(clock = clock) private var requestCounter = ServerFilters.OpenTelemetryMetrics.RequestCounter(clock = clock) private val server by lazy { routes( "/timed" bind routes( "/one" bind GET to { Response(OK) }, "/two/{name:.*}" bind POST to { Response(OK).body(Path.of("name")(it)) } ).withFilter(requestTimer), "/counted" bind routes( "/one" bind GET to { Response(OK) }, "/two/{name:.*}" bind POST to { Response(OK).body(Path.of("name")(it)) } ).withFilter(requestCounter), "/unmetered" bind routes( "one" bind GET to { Response(OK) }, "two" bind DELETE to { Response(INTERNAL_SERVER_ERROR) } ), "/otherTimed" bind static().withFilter(requestTimer), "/otherCounted" bind static().withFilter(requestCounter) ) } @Test fun `routes with timer generate request timing metrics tagged with path and method and status`() { assertThat(server(Request(GET, "/timed/one")), hasStatus(OK)) repeat(2) { assertThat(server(Request(POST, "/timed/two/bob")), (hasStatus(OK) and hasBody("bob"))) } val data = exportMetricsFromOpenTelemetry() assertThat( data, hasRequestTimer( 1, 1000.0, Attributes.of(stringKey("path"), "timed_one", stringKey("method"), "GET", stringKey("status"), "200") ) ) assertThat( data, hasRequestTimer( 2, 2000.0, Attributes.of( stringKey("path"), "timed_two_name", stringKey("method"), "POST", stringKey("status"), "200" ) ) ) } @Test fun `routes with counter generate request count metrics tagged with path and method and status`() { assertThat(server(Request(GET, "/counted/one")), hasStatus(OK)) repeat(2) { assertThat(server(Request(POST, "/counted/two/bob")), (hasStatus(OK) and hasBody("bob"))) } val data = exportMetricsFromOpenTelemetry() assertThat( data, hasRequestCounter( 1, Attributes.of(stringKey("path"), "counted_one", stringKey("method"), "GET", stringKey("status"), "200") ) ) assertThat( data, hasRequestCounter( 2, Attributes.of( stringKey("path"), "counted_two_name", stringKey("method"), "POST", stringKey("status"), "200" ) ) ) } @Test fun `routes without metrics generate nothing`() { assertThat(server(Request(GET, "/unmetered/one")), hasStatus(OK)) assertThat(server(Request(DELETE, "/unmetered/two")), hasStatus(INTERNAL_SERVER_ERROR)) val data = exportMetricsFromOpenTelemetry() assertThat(data, hasNoRequestTimer(GET, "unmetered_one", OK)) assertThat(data, hasNoRequestTimer(DELETE, "unmetered_two", INTERNAL_SERVER_ERROR)) assertThat(data, hasNoRequestCounter(GET, "unmetered_one", OK)) assertThat(data, hasNoRequestCounter(DELETE, "unmetered_two", INTERNAL_SERVER_ERROR)) } @Test fun `request timer meter names and request id formatter can be configured`() { requestTimer = ServerFilters.OpenTelemetryMetrics.RequestTimer( name = "custom.requests", description = "custom.description", labeler = { it.label("foo", "bar") }) assertThat(server(Request(GET, "/timed/one")), hasStatus(OK)) val data = exportMetricsFromOpenTelemetry() assertThat( data, hasRequestTimer( 1, 1000.0, Attributes.of(stringKey("foo"), "bar", stringKey("routingGroup"), "timed/one"), "custom.requests" ) ) } @Test fun `request counter meter names and request id formatter can be configured`() { requestCounter = ServerFilters.OpenTelemetryMetrics.RequestCounter( name = "custom.requests2", description = "custom.description", labeler = { it.label("foo", "bar") }) assertThat(server(Request(GET, "/counted/one")), hasStatus(OK)) assertThat( exportMetricsFromOpenTelemetry(), hasRequestCounter( 1, Attributes.of(stringKey("foo"), "bar", stringKey("routingGroup"), "counted/one"), "custom.requests2" ) ) } @Test fun `timed routes without uri template generate request timing metrics tagged with unmapped path value`() { assertThat(server(Request(GET, "/otherTimed/test.json")), hasStatus(OK)) assertThat( exportMetricsFromOpenTelemetry(), hasRequestTimer( 1, 1000.0, Attributes.of(stringKey("path"), "UNMAPPED", stringKey("method"), "GET", stringKey("status"), "200") ) ) } @Test fun `counted routes without uri template generate request count metrics tagged with unmapped path value`() { assertThat(server(Request(GET, "/otherCounted/test.json")), hasStatus(OK)) assertThat( exportMetricsFromOpenTelemetry(), hasRequestCounter( 1, Attributes.of(stringKey("path"), "UNMAPPED", stringKey("method"), "GET", stringKey("status"), "200") ) ) } private fun hasNoRequestTimer(method: Method, path: String, status: Status) = object : Matcher<List<MetricData>> { override val description = "http.server.request.latency" override fun invoke(actual: List<MetricData>): MatchResult = if (actual.firstOrNull { it.name == description } ?.doubleGaugeData ?.points ?.any { println(it.attributes) Attributes.of( stringKey("path"), path, stringKey("method"), method.name, stringKey("status"), status.code.toString() ) == it.attributes } != true) Match else Mismatch(actual.toString()) } }
apache-2.0
e44f4249ac076d980acf4a98a3dd7ca1
35.344978
119
0.566863
4.745154
false
true
false
false
openMF/android-client
mifosng-android/src/main/java/com/mifos/mifosxdroid/online/loancharge/LoanChargePresenter.kt
1
2381
package com.mifos.mifosxdroid.online.loancharge import com.mifos.api.DataManager import com.mifos.mifosxdroid.base.BasePresenter import com.mifos.objects.client.Charges import com.mifos.utils.MFErrorParser import retrofit2.adapter.rxjava.HttpException import rx.Subscriber import rx.Subscription import rx.android.schedulers.AndroidSchedulers import rx.plugins.RxJavaPlugins import rx.schedulers.Schedulers import javax.inject.Inject /** * Created by Rajan Maurya on 07/06/16. */ class LoanChargePresenter @Inject constructor(private val mDataManager: DataManager) : BasePresenter<LoanChargeMvpView?>() { private var mSubscription: Subscription? = null override fun attachView(mvpView: LoanChargeMvpView?) { super.attachView(mvpView) } override fun detachView() { super.detachView() if (mSubscription != null) mSubscription!!.unsubscribe() } fun loadLoanChargesList(loanId: Int) { checkViewAttached() mvpView!!.showProgressbar(true) if (mSubscription != null) mSubscription!!.unsubscribe() mSubscription = mDataManager.getListOfLoanCharges(loanId) .observeOn(AndroidSchedulers.mainThread()) .subscribeOn(Schedulers.io()) .subscribe(object : Subscriber<List<Charges?>?>() { override fun onCompleted() {} override fun onError(e: Throwable) { mvpView!!.showProgressbar(false) try { if (e is HttpException) { val errorMessage = e.response().errorBody() .string() mvpView!!.showFetchingError(MFErrorParser .parseError(errorMessage) .errors[0].defaultUserMessage) } } catch (throwable: Throwable) { RxJavaPlugins.getInstance().errorHandler.handleError(e) } } override fun onNext(chargesPage: List<Charges?>?) { mvpView!!.showProgressbar(false) mvpView!!.showLoanChargesList(chargesPage as MutableList<Charges>) } }) } }
mpl-2.0
720f51020e9b1d860212c58a46c07b0f
38.7
124
0.576648
5.696172
false
false
false
false
It-projects-Ke-401-CA/CruelAlarm
app/src/main/java/com/weiaett/cruelalarm/img_proc/ImgProcessor.kt
1
1703
package com.weiaett.cruelalarm.img_proc import android.content.Context import android.graphics.Bitmap import android.graphics.BitmapFactory import android.net.Uri import android.util.Log import android.widget.Toast import com.weiaett.cruelalarm.utils.ImageLoader import java.io.File import java.io.FileInputStream val tag = "MaImageProcessor" class ImgProcessor{ companion object{ fun process(ctx: Context, fileUri: Uri, turn: Boolean):Uri?{ Log.d(tag, "Compressing started") val bmp = compress(fileUri.path, turn) val delSuccess = File(fileUri.path).delete() Log.d(tag, "Compressing finished, deleted=$delSuccess") val enough = Comparator.Companion.hasEnoughFeatures(bmp) if(enough) { Log.d(tag, "Save started") val uri = ImageLoader.savePhoto(ctx, bmp) Log.d(tag, "Save finished") return uri } return null } fun compress(path: String, turn: Boolean): Bitmap{ val options = BitmapFactory.Options() // get size options.inJustDecodeBounds = true BitmapFactory.decodeFile(path, options) options.inJustDecodeBounds = false // really will be closest power of 2 options.inSampleSize = Math.max(options.outWidth / 800.0, options.outHeight / 1000.0).toInt() val bitmap = BitmapFactory.decodeFile(path, options) Log.d(tag, "after scale w=${bitmap.width} h=${bitmap.height}") return if(turn) transToBitmap(rotateMat(loadToMat(bitmap))) else bitmap } } }
gpl-3.0
ce2375eef61a2f1839040977b364acee
31.132075
105
0.618321
4.355499
false
false
false
false
xiaopansky/Sketch
sample/src/main/java/me/panpf/sketch/sample/ui/UnsplashFragment.kt
1
6541
package me.panpf.sketch.sample.ui import android.content.Intent import android.graphics.Color import android.net.Uri import android.os.Bundle import android.view.View import android.widget.Toast import kotlinx.android.synthetic.main.fragment_recycler.* import me.panpf.adapter.AssemblyAdapter import me.panpf.adapter.AssemblyRecyclerAdapter import me.panpf.adapter.more.OnLoadMoreListener import me.panpf.sketch.sample.R import me.panpf.sketch.sample.base.BaseFragment import me.panpf.sketch.sample.base.BindContentView import me.panpf.sketch.sample.bean.Image import me.panpf.sketch.sample.bean.UnsplashImage import me.panpf.sketch.sample.item.LoadMoreItem import me.panpf.sketch.sample.item.UnsplashPhotosItemFactory import me.panpf.sketch.sample.net.NetServices import me.panpf.sketch.sample.util.ScrollingPauseLoadManager import me.panpf.sketch.sample.widget.HintView import org.greenrobot.eventbus.EventBus import retrofit2.Call import retrofit2.Callback import retrofit2.Response import java.lang.ref.WeakReference import java.util.* @BindContentView(R.layout.fragment_recycler) class UnsplashFragment : BaseFragment(), UnsplashPhotosItemFactory.UnsplashPhotosItemEventListener, OnLoadMoreListener, androidx.swiperefreshlayout.widget.SwipeRefreshLayout.OnRefreshListener { private var adapter: AssemblyRecyclerAdapter? = null private var pageIndex = 1 override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) recycler_recyclerFragment_content.layoutManager = androidx.recyclerview.widget.LinearLayoutManager(context) recycler_recyclerFragment_content.addOnScrollListener(ScrollingPauseLoadManager(view.context)) refresh_recyclerFragment.setOnRefreshListener(this) if (adapter != null) { recycler_recyclerFragment_content.adapter = adapter } else { refresh_recyclerFragment.post { onRefresh() } } } private fun loadData(pageIndex: Int) { this.pageIndex = pageIndex NetServices.unsplash().listPhotos(pageIndex).enqueue(LoadDataCallback(this, pageIndex)) } override fun onClickImage(position: Int, image: UnsplashImage, optionsKey: String) { val activity = activity ?: return var finalOptionsKey: String? = optionsKey // 含有这些信息时,说明这张图片不仅仅是缩小,而是会被改变,因此不能用作loading图了 if (finalOptionsKey!!.contains("Resize") || finalOptionsKey.contains("ImageProcessor") || finalOptionsKey.contains("thumbnailMode")) { finalOptionsKey = null } @Suppress("UNCHECKED_CAST") val images = adapter!!.dataList as List<UnsplashImage> val imageArrayList = ArrayList<Image>(images.size) images.mapTo(imageArrayList) { Image(it.urls!!.regular!!, it.urls!!.raw!!) } ImageDetailActivity.launch(activity, dataTransferHelper.put("urlList", imageArrayList), finalOptionsKey!!, position) } override fun onClickUser(position: Int, user: UnsplashImage.User) { val uri = Uri.parse(user.links!!.html) .buildUpon() .appendQueryParameter("utm_source", "SketchSample") .appendQueryParameter("utm_medium", "referral") .appendQueryParameter("utm_campaign", "api-credit") .build() val intent = Intent(Intent.ACTION_VIEW) intent.data = uri startActivity(intent) } override fun onRefresh() { if (adapter != null) { adapter!!.loadMoreFinished(false) } if (!refresh_recyclerFragment.isRefreshing) { refresh_recyclerFragment.isRefreshing = true } loadData(1) } override fun onLoadMore(adapter1: AssemblyAdapter) { loadData(pageIndex + 1) } private class LoadDataCallback internal constructor(fragment: UnsplashFragment, private val pageIndex: Int) : Callback<List<UnsplashImage>> { private val reference: WeakReference<UnsplashFragment> = WeakReference(fragment) init { if (pageIndex == 1) { fragment.hint_recyclerFragment.hidden() } } override fun onResponse(call: Call<List<UnsplashImage>>, response: Response<List<UnsplashImage>>) { val fragment = reference.get() ?: return if (!fragment.isViewCreated) { return } if (pageIndex == 1) { create(fragment, response) } else { loadMore(fragment, response) } fragment.refresh_recyclerFragment.isRefreshing = false } override fun onFailure(call: Call<List<UnsplashImage>>, t: Throwable) { val fragment = reference.get() ?: return val activity = fragment.activity ?: return if (!fragment.isViewCreated) { return } if (pageIndex == 1) { fragment.hint_recyclerFragment.failed(t, View.OnClickListener { fragment.onRefresh() }) fragment.refresh_recyclerFragment.isRefreshing = false } else { fragment.adapter!!.loadMoreFailed() Toast.makeText(fragment.activity, HintView.getCauseByException(activity, t), Toast.LENGTH_LONG).show() } } private fun create(fragment: UnsplashFragment, response: Response<List<UnsplashImage>>) { val activity = fragment.activity ?: return val images = response.body() if (images == null || images.isEmpty()) { fragment.hint_recyclerFragment.empty("No photos") return } val adapter = AssemblyRecyclerAdapter(images) adapter.addItemFactory(UnsplashPhotosItemFactory(activity, fragment)) adapter.setMoreItem(LoadMoreItem.Factory(fragment)) fragment.recycler_recyclerFragment_content.adapter = adapter fragment.adapter = adapter } private fun loadMore(fragment: UnsplashFragment, response: Response<List<UnsplashImage>>) { val images = response.body() if (images == null || images.isEmpty()) { fragment.adapter!!.loadMoreFinished(true) return } fragment.adapter!!.addAll(images) fragment.adapter!!.loadMoreFinished(images.size < 20) } } }
apache-2.0
754c35e5a86ed74cbaebe71121183658
37.278107
193
0.660999
4.760118
false
false
false
false
Vavassor/Tusky
app/src/main/java/com/keylesspalace/tusky/AccountActivity.kt
1
24803
/* Copyright 2018 Conny Duck * * This file is a part of Tusky. * * 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. * * Tusky 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 Tusky; if not, * see <http://www.gnu.org/licenses>. */ package com.keylesspalace.tusky import android.animation.ArgbEvaluator import android.content.Context import android.content.Intent import android.graphics.Color import android.graphics.PorterDuff import android.os.Bundle import android.preference.PreferenceManager import android.view.Menu import android.view.MenuItem import android.view.View import android.view.ViewGroup import androidx.annotation.AttrRes import androidx.annotation.ColorInt import androidx.annotation.Px import androidx.appcompat.app.AlertDialog import androidx.core.app.ActivityOptionsCompat import androidx.core.content.ContextCompat import androidx.emoji.text.EmojiCompat import androidx.fragment.app.Fragment import androidx.lifecycle.Observer import androidx.lifecycle.ViewModelProviders import androidx.recyclerview.widget.LinearLayoutManager import com.google.android.material.appbar.AppBarLayout import com.google.android.material.appbar.CollapsingToolbarLayout import com.google.android.material.floatingactionbutton.FloatingActionButton import com.google.android.material.snackbar.Snackbar import com.keylesspalace.tusky.adapter.AccountFieldAdapter import com.keylesspalace.tusky.di.ViewModelFactory import com.keylesspalace.tusky.entity.Account import com.keylesspalace.tusky.entity.Relationship import com.keylesspalace.tusky.interfaces.ActionButtonActivity import com.keylesspalace.tusky.interfaces.LinkListener import com.keylesspalace.tusky.pager.AccountPagerAdapter import com.keylesspalace.tusky.util.* import com.keylesspalace.tusky.viewmodel.AccountViewModel import com.squareup.picasso.Picasso import dagger.android.AndroidInjector import dagger.android.DispatchingAndroidInjector import dagger.android.support.HasSupportFragmentInjector import kotlinx.android.synthetic.main.activity_account.* import kotlinx.android.synthetic.main.view_account_moved.* import java.text.NumberFormat import javax.inject.Inject class AccountActivity : BottomSheetActivity(), ActionButtonActivity, HasSupportFragmentInjector, LinkListener { @Inject lateinit var dispatchingAndroidInjector: DispatchingAndroidInjector<androidx.fragment.app.Fragment> @Inject lateinit var viewModelFactory: ViewModelFactory private lateinit var viewModel: AccountViewModel private val accountFieldAdapter = AccountFieldAdapter(this) private lateinit var accountId: String private var followState: FollowState = FollowState.NOT_FOLLOWING private var blocking: Boolean = false private var muting: Boolean = false private var showingReblogs: Boolean = false private var isSelf: Boolean = false private var loadedAccount: Account? = null // fields for scroll animation private var hideFab: Boolean = false private var oldOffset: Int = 0 @ColorInt private var toolbarColor: Int = 0 @ColorInt private var backgroundColor: Int = 0 @ColorInt private var statusBarColorTransparent: Int = 0 @ColorInt private var statusBarColorOpaque: Int = 0 @ColorInt private var textColorPrimary: Int = 0 @ColorInt private var textColorSecondary: Int = 0 @Px private var avatarSize: Float = 0f @Px private var titleVisibleHeight: Int = 0 private enum class FollowState { NOT_FOLLOWING, FOLLOWING, REQUESTED } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) viewModel = ViewModelProviders.of(this, viewModelFactory)[AccountViewModel::class.java] viewModel.accountData.observe(this, Observer<Resource<Account>> { when (it) { is Success -> onAccountChanged(it.data) is Error -> { Snackbar.make(accountCoordinatorLayout, R.string.error_generic, Snackbar.LENGTH_LONG) .setAction(R.string.action_retry) { reload() } .show() } } }) viewModel.relationshipData.observe(this, Observer<Resource<Relationship>> { val relation = it?.data if (relation != null) { onRelationshipChanged(relation) } if (it is Error) { Snackbar.make(accountCoordinatorLayout, R.string.error_generic, Snackbar.LENGTH_LONG) .setAction(R.string.action_retry) { reload() } .show() } }) val decorView = window.decorView decorView.systemUiVisibility = decorView.systemUiVisibility or View.SYSTEM_UI_FLAG_LAYOUT_STABLE or View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN window.statusBarColor = Color.TRANSPARENT setContentView(R.layout.activity_account) val intent = intent accountId = intent.getStringExtra(KEY_ACCOUNT_ID) // set toolbar top margin according to system window insets accountCoordinatorLayout.setOnApplyWindowInsetsListener { _, insets -> val top = insets.systemWindowInsetTop val toolbarParams = accountToolbar.layoutParams as CollapsingToolbarLayout.LayoutParams toolbarParams.topMargin = top insets.consumeSystemWindowInsets() } // Setup the toolbar. setSupportActionBar(accountToolbar) supportActionBar?.title = null supportActionBar?.setDisplayHomeAsUpEnabled(true) supportActionBar?.setDisplayShowHomeEnabled(true) hideFab = PreferenceManager.getDefaultSharedPreferences(this).getBoolean("fabHide", false) toolbarColor = ThemeUtils.getColor(this, R.attr.toolbar_background_color) backgroundColor = ThemeUtils.getColor(this, android.R.attr.colorBackground) statusBarColorTransparent = ContextCompat.getColor(this, R.color.header_background_filter) statusBarColorOpaque = ThemeUtils.getColor(this, R.attr.colorPrimaryDark) textColorPrimary = ThemeUtils.getColor(this, android.R.attr.textColorPrimary) textColorSecondary = ThemeUtils.getColor(this, android.R.attr.textColorSecondary) avatarSize = resources.getDimensionPixelSize(R.dimen.account_activity_avatar_size).toFloat() titleVisibleHeight = resources.getDimensionPixelSize(R.dimen.account_activity_scroll_title_visible_height) ThemeUtils.setDrawableTint(this, accountToolbar.navigationIcon, R.attr.account_toolbar_icon_tint_uncollapsed) ThemeUtils.setDrawableTint(this, accountToolbar.overflowIcon, R.attr.account_toolbar_icon_tint_uncollapsed) // Add a listener to change the toolbar icon color when it enters/exits its collapsed state. accountAppBarLayout.addOnOffsetChangedListener(object : AppBarLayout.OnOffsetChangedListener { @AttrRes var priorAttribute = R.attr.account_toolbar_icon_tint_uncollapsed override fun onOffsetChanged(appBarLayout: AppBarLayout, verticalOffset: Int) { @AttrRes val attribute = if (titleVisibleHeight + verticalOffset < 0) { accountToolbar.setTitleTextColor(textColorPrimary) accountToolbar.setSubtitleTextColor(textColorSecondary) R.attr.account_toolbar_icon_tint_collapsed } else { accountToolbar.setTitleTextColor(Color.TRANSPARENT) accountToolbar.setSubtitleTextColor(Color.TRANSPARENT) R.attr.account_toolbar_icon_tint_uncollapsed } if (attribute != priorAttribute) { priorAttribute = attribute val context = accountToolbar.context ThemeUtils.setDrawableTint(context, accountToolbar.navigationIcon, attribute) ThemeUtils.setDrawableTint(context, accountToolbar.overflowIcon, attribute) } if (hideFab && !isSelf && !blocking) { if (verticalOffset > oldOffset) { accountFloatingActionButton.show() } if (verticalOffset < oldOffset) { accountFloatingActionButton.hide() } } oldOffset = verticalOffset val scaledAvatarSize = (avatarSize + verticalOffset) / avatarSize accountAvatarImageView.scaleX = scaledAvatarSize accountAvatarImageView.scaleY = scaledAvatarSize accountAvatarImageView.visible(scaledAvatarSize > 0) var transparencyPercent = Math.abs(verticalOffset) / titleVisibleHeight.toFloat() if (transparencyPercent > 1) transparencyPercent = 1f window.statusBarColor = argbEvaluator.evaluate(transparencyPercent, statusBarColorTransparent, statusBarColorOpaque) as Int val evaluatedToolbarColor = argbEvaluator.evaluate(transparencyPercent, Color.TRANSPARENT, toolbarColor) as Int val evaluatedTabBarColor = argbEvaluator.evaluate(transparencyPercent, backgroundColor, toolbarColor) as Int accountToolbar.setBackgroundColor(evaluatedToolbarColor) accountHeaderInfoContainer.setBackgroundColor(evaluatedTabBarColor) accountTabLayout.setBackgroundColor(evaluatedTabBarColor) } }) // Initialise the default UI states. accountFloatingActionButton.hide() accountFollowButton.hide() accountFollowsYouTextView.hide() // Obtain information to fill out the profile. viewModel.obtainAccount(accountId) val activeAccount = accountManager.activeAccount if (accountId == activeAccount?.accountId) { isSelf = true updateButtons() } else { isSelf = false viewModel.obtainRelationship(accountId) } // setup the RecyclerView for the account fields accountFieldList.isNestedScrollingEnabled = false accountFieldList.layoutManager = LinearLayoutManager(this) accountFieldList.adapter = accountFieldAdapter // Setup the tabs and timeline pager. val adapter = AccountPagerAdapter(supportFragmentManager, accountId) val pageTitles = arrayOf(getString(R.string.title_statuses), getString(R.string.title_statuses_with_replies), getString(R.string.title_statuses_pinned), getString(R.string.title_media)) adapter.setPageTitles(pageTitles) accountFragmentViewPager.pageMargin = resources.getDimensionPixelSize(R.dimen.tab_page_margin) val pageMarginDrawable = ThemeUtils.getDrawable(this, R.attr.tab_page_margin_drawable, R.drawable.tab_page_margin_dark) accountFragmentViewPager.setPageMarginDrawable(pageMarginDrawable) accountFragmentViewPager.adapter = adapter accountFragmentViewPager.offscreenPageLimit = 2 accountTabLayout.setupWithViewPager(accountFragmentViewPager) val accountListClickListener = { v: View -> val type = when (v.id) { R.id.accountFollowers-> AccountListActivity.Type.FOLLOWERS R.id.accountFollowing -> AccountListActivity.Type.FOLLOWS else -> throw AssertionError() } val accountListIntent = AccountListActivity.newIntent(this, type, accountId) startActivityWithSlideInAnimation(accountListIntent) } accountFollowers.setOnClickListener(accountListClickListener) accountFollowing.setOnClickListener(accountListClickListener) accountStatuses.setOnClickListener { // Make nice ripple effect on tab accountTabLayout.getTabAt(0)!!.select() val poorTabView = (accountTabLayout.getChildAt(0) as ViewGroup).getChildAt(0) poorTabView.isPressed = true accountTabLayout.postDelayed({ poorTabView.isPressed = false }, 300) } } private fun onAccountChanged(account: Account?) { if (account != null) { loadedAccount = account val usernameFormatted = getString(R.string.status_username_format, account.username) accountUsernameTextView.text = usernameFormatted accountDisplayNameTextView.text = CustomEmojiHelper.emojifyString(account.name, account.emojis, accountDisplayNameTextView) if (supportActionBar != null) { try { supportActionBar?.title = EmojiCompat.get().process(account.name) } catch (e: IllegalStateException) { supportActionBar?.title = account.name } val subtitle = String.format(getString(R.string.status_username_format), account.username) supportActionBar?.subtitle = subtitle } val emojifiedNote = CustomEmojiHelper.emojifyText(account.note, account.emojis, accountNoteTextView) LinkHelper.setClickableText(accountNoteTextView, emojifiedNote, null, this) accountLockedImageView.visible(account.locked) accountBadgeTextView.visible(account.bot) Picasso.with(this) .load(account.avatar) .placeholder(R.drawable.avatar_default) .into(accountAvatarImageView) Picasso.with(this) .load(account.header) .fit() // prevents crash with large header images .centerCrop() .into(accountHeaderImageView) accountAvatarImageView.setOnClickListener { avatarView -> val intent = ViewMediaActivity.newAvatarIntent(avatarView.context, account.avatar) avatarView.transitionName = account.avatar val options = ActivityOptionsCompat.makeSceneTransitionAnimation(this, avatarView, account.avatar) startActivity(intent, options.toBundle()) } accountFieldAdapter.fields = account.fields ?: emptyList() accountFieldAdapter.emojis = account.emojis ?: emptyList() accountFieldAdapter.notifyDataSetChanged() if (account.moved != null) { val movedAccount = account.moved accountMovedView.show() // necessary because accountMovedView is now replaced in layout hierachy findViewById<View>(R.id.accountMovedView).setOnClickListener { onViewAccount(movedAccount.id) } accountMovedDisplayName.text = movedAccount.name accountMovedUsername.text = getString(R.string.status_username_format, movedAccount.username) Picasso.with(this) .load(movedAccount.avatar) .placeholder(R.drawable.avatar_default) .into(accountMovedAvatar) accountMovedText.text = getString(R.string.account_moved_description, movedAccount.displayName) // this is necessary because API 19 can't handle vector compound drawables val movedIcon = ContextCompat.getDrawable(this, R.drawable.ic_briefcase)?.mutate() val textColor = ThemeUtils.getColor(this, android.R.attr.textColorTertiary) movedIcon?.setColorFilter(textColor, PorterDuff.Mode.SRC_IN) accountMovedText.setCompoundDrawablesRelativeWithIntrinsicBounds(movedIcon, null, null, null) accountFollowers.hide() accountFollowing.hide() accountStatuses.hide() accountTabLayout.hide() accountFragmentViewPager.hide() } if (account.isRemote()) { accountRemoveView.show() accountRemoveView.setOnClickListener { LinkHelper.openLink(account.url, this) } } val numberFormat = NumberFormat.getNumberInstance() accountFollowersTextView.text = numberFormat.format(account.followersCount) accountFollowingTextView.text = numberFormat.format(account.followingCount) accountStatusesTextView.text = numberFormat.format(account.statusesCount) accountFloatingActionButton.setOnClickListener { mention() } accountFollowButton.setOnClickListener { if (isSelf) { val intent = Intent(this@AccountActivity, EditProfileActivity::class.java) startActivity(intent) return@setOnClickListener } when (followState) { AccountActivity.FollowState.NOT_FOLLOWING -> { viewModel.changeFollowState(accountId) } AccountActivity.FollowState.REQUESTED -> { showFollowRequestPendingDialog() } AccountActivity.FollowState.FOLLOWING -> { showUnfollowWarningDialog() } } updateFollowButton() } } } override fun onSaveInstanceState(outState: Bundle) { outState.putString(KEY_ACCOUNT_ID, accountId) super.onSaveInstanceState(outState) } private fun onRelationshipChanged(relation: Relationship) { followState = when { relation.following -> FollowState.FOLLOWING relation.requested -> FollowState.REQUESTED else -> FollowState.NOT_FOLLOWING } blocking = relation.blocking muting = relation.muting showingReblogs = relation.showingReblogs accountFollowsYouTextView.visible(relation.followedBy) updateButtons() } private fun reload() { viewModel.obtainAccount(accountId, true) viewModel.obtainRelationship(accountId) } private fun updateFollowButton() { if(isSelf) { accountFollowButton.setText(R.string.action_edit_own_profile) return } when (followState) { AccountActivity.FollowState.NOT_FOLLOWING -> { accountFollowButton.setText(R.string.action_follow) } AccountActivity.FollowState.REQUESTED -> { accountFollowButton.setText(R.string.state_follow_requested) } AccountActivity.FollowState.FOLLOWING -> { accountFollowButton.setText(R.string.action_unfollow) } } } private fun updateButtons() { invalidateOptionsMenu() if (!blocking && loadedAccount?.moved == null) { accountFollowButton.show() updateFollowButton() if(isSelf) { accountFloatingActionButton.hide() } else { accountFloatingActionButton.show() } } else { accountFloatingActionButton.hide() accountFollowButton.hide() } } override fun onCreateOptionsMenu(menu: Menu): Boolean { menuInflater.inflate(R.menu.account_toolbar, menu) if (!isSelf) { val follow = menu.findItem(R.id.action_follow) follow.title = if (followState == FollowState.NOT_FOLLOWING) { getString(R.string.action_follow) } else { getString(R.string.action_unfollow) } follow.isVisible = followState != FollowState.REQUESTED val block = menu.findItem(R.id.action_block) block.title = if (blocking) { getString(R.string.action_unblock) } else { getString(R.string.action_block) } val mute = menu.findItem(R.id.action_mute) mute.title = if (muting) { getString(R.string.action_unmute) } else { getString(R.string.action_mute) } if (followState == FollowState.FOLLOWING) { val showReblogs = menu.findItem(R.id.action_show_reblogs) showReblogs.title = if (showingReblogs) { getString(R.string.action_hide_reblogs) } else { getString(R.string.action_show_reblogs) } } else { menu.removeItem(R.id.action_show_reblogs) } } else { // It shouldn't be possible to block or follow yourself. menu.removeItem(R.id.action_follow) menu.removeItem(R.id.action_block) menu.removeItem(R.id.action_mute) menu.removeItem(R.id.action_show_reblogs) } return super.onCreateOptionsMenu(menu) } private fun showFollowRequestPendingDialog() { AlertDialog.Builder(this) .setMessage(R.string.dialog_message_cancel_follow_request) .setPositiveButton(android.R.string.ok) { _, _ -> viewModel.changeFollowState(accountId) } .setNegativeButton(android.R.string.cancel, null) .show() } private fun showUnfollowWarningDialog() { AlertDialog.Builder(this) .setMessage(R.string.dialog_unfollow_warning) .setPositiveButton(android.R.string.ok) { _, _ -> viewModel.changeFollowState(accountId) } .setNegativeButton(android.R.string.cancel, null) .show() } private fun mention() { loadedAccount?.let { val intent = ComposeActivity.IntentBuilder() .mentionedUsernames(setOf(it.username)) .build(this) startActivity(intent) } } override fun onViewTag(tag: String) { val intent = Intent(this, ViewTagActivity::class.java) intent.putExtra("hashtag", tag) startActivityWithSlideInAnimation(intent) } override fun onViewAccount(id: String) { val intent = Intent(this, AccountActivity::class.java) intent.putExtra("id", id) startActivityWithSlideInAnimation(intent) } override fun onViewUrl(url: String) { viewUrl(url) } override fun onOptionsItemSelected(item: MenuItem): Boolean { when (item.itemId) { android.R.id.home -> { onBackPressed() return true } R.id.action_mention -> { mention() return true } R.id.action_open_in_web -> { // If the account isn't loaded yet, eat the input. if (loadedAccount != null) { LinkHelper.openLink(loadedAccount?.url, this) } return true } R.id.action_follow -> { viewModel.changeFollowState(accountId) return true } R.id.action_block -> { viewModel.changeBlockState(accountId) return true } R.id.action_mute -> { viewModel.changeMuteState(accountId) return true } R.id.action_show_reblogs -> { viewModel.changeShowReblogsState(accountId) return true } } return super.onOptionsItemSelected(item) } override fun getActionButton(): FloatingActionButton? { return if (!isSelf && !blocking) { accountFloatingActionButton } else null } override fun supportFragmentInjector(): AndroidInjector<Fragment> { return dispatchingAndroidInjector } companion object { private const val KEY_ACCOUNT_ID = "id" private val argbEvaluator = ArgbEvaluator() @JvmStatic fun getIntent(context: Context, accountId: String): Intent { val intent = Intent(context, AccountActivity::class.java) intent.putExtra(KEY_ACCOUNT_ID, accountId) return intent } } }
gpl-3.0
4236e2203f458d0af9048842bec0ea56
39.26461
193
0.640124
5.303186
false
false
false
false
pdvrieze/ProcessManager
ProcessEngine/core/src/jvmTest/kotlin/nl/adaptivity/process/engine/patterns/WCP10.kt
1
2224
/* * Copyright (c) 2017. * * This file is part of ProcessManager. * * ProcessManager is free software: you can redistribute it and/or modify it under the terms of version 3 of the * GNU Lesser General Public License as published by the Free Software Foundation. * * ProcessManager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even * the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License along with ProcessManager. If not, * see <http://www.gnu.org/licenses/>. */ package nl.adaptivity.process.engine.patterns import nl.adaptivity.process.engine.* import nl.adaptivity.process.processModel.configurableModel.* import nl.adaptivity.process.util.Identifier import org.junit.jupiter.api.DisplayName @DisplayName("WCP10: arbitrary cycles") class WCP10: TraceTest(Companion) { companion object: TraceTest.ConfigBase() { override val modelData: ModelData = run { val model = object : TestConfigurableModel("WCP10") { val start1 by startNode val join by join(start1, Identifier("ac2")) { min = 1; max = 1; isMultiMerge = true } val ac1 by activity(join) { isMultiInstance = true } val split by split(ac1) { min = 1; max = 1; isMultiInstance = true } val ac2 by activity(split) { isMultiInstance = true } val ac3 by activity(split) val end by endNode(ac3)/* { isMultiInstance = true }*/ } val validTraces = with(model) { trace { (start1 .. join[1] .. ac1[1] .. ac2[1] .. split[1] .. join[2] .. ac1[2] .. ac3 .. split[2] ..end) or (start1 .. join[1] .. ac1[1] .. ac3 .. split[1] ..end) }} val invalidTraces = with(model) { trace { join or ac2 or ac3 or end or ((start1 .. join[1] .. ac1[1] .. ac2[1] .. split[1]) * (ac3[ANYINSTANCE] or split[2] or end[ANYINSTANCE])) }} ModelData(model, validTraces, invalidTraces) } } }
lgpl-3.0
5437149e0279ad21f12c455729e89049
45.333333
126
0.62455
3.943262
false
true
false
false
ccomeaux/boardgamegeek4android
app/src/main/java/com/boardgamegeek/db/UserDao.kt
1
8484
package com.boardgamegeek.db import android.content.ContentValues import android.net.Uri import android.provider.BaseColumns import androidx.core.content.contentValuesOf import androidx.core.database.getLongOrNull import androidx.core.database.getStringOrNull import com.boardgamegeek.BggApplication import com.boardgamegeek.auth.Authenticator import com.boardgamegeek.entities.BriefBuddyEntity import com.boardgamegeek.entities.UserEntity import com.boardgamegeek.extensions.load import com.boardgamegeek.extensions.queryInt import com.boardgamegeek.extensions.queryLong import com.boardgamegeek.extensions.queryString import com.boardgamegeek.provider.BggContract.Avatars import com.boardgamegeek.provider.BggContract.Buddies import com.boardgamegeek.provider.BggContract.Companion.COLLATE_NOCASE import com.boardgamegeek.provider.BggContract.Companion.INVALID_ID import com.boardgamegeek.util.FileUtils import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext import timber.log.Timber class UserDao(private val context: BggApplication) { enum class UsersSortBy { FIRST_NAME, LAST_NAME, USERNAME } suspend fun loadUser(username: String): UserEntity? = withContext(Dispatchers.IO) { context.contentResolver.load( Buddies.buildBuddyUri(username), arrayOf( BaseColumns._ID, Buddies.Columns.BUDDY_ID, Buddies.Columns.BUDDY_NAME, Buddies.Columns.BUDDY_FIRSTNAME, Buddies.Columns.BUDDY_LASTNAME, Buddies.Columns.AVATAR_URL, Buddies.Columns.PLAY_NICKNAME, Buddies.Columns.UPDATED, ) )?.use { if (it.moveToFirst()) { UserEntity( internalId = it.getLong(0), id = it.getInt(1), userName = it.getStringOrNull(2).orEmpty(), firstName = it.getStringOrNull(3).orEmpty(), lastName = it.getStringOrNull(4).orEmpty(), avatarUrlRaw = it.getStringOrNull(5).orEmpty(), playNickname = it.getStringOrNull(6).orEmpty(), updatedTimestamp = it.getLongOrNull(7) ?: 0L ) } else null } } suspend fun loadBuddies(sortBy: UsersSortBy = UsersSortBy.USERNAME, buddiesOnly: Boolean = true): List<UserEntity> = withContext(Dispatchers.IO) { val results = arrayListOf<UserEntity>() val sortOrder = when (sortBy) { UsersSortBy.USERNAME -> Buddies.Columns.BUDDY_NAME UsersSortBy.FIRST_NAME -> Buddies.Columns.BUDDY_FIRSTNAME UsersSortBy.LAST_NAME -> Buddies.Columns.BUDDY_LASTNAME }.plus(" $COLLATE_NOCASE ASC") context.contentResolver.load( Buddies.CONTENT_URI, arrayOf( BaseColumns._ID, Buddies.Columns.BUDDY_ID, Buddies.Columns.BUDDY_NAME, Buddies.Columns.BUDDY_FIRSTNAME, Buddies.Columns.BUDDY_LASTNAME, Buddies.Columns.AVATAR_URL, Buddies.Columns.PLAY_NICKNAME, Buddies.Columns.UPDATED ), if (buddiesOnly) "${Buddies.Columns.BUDDY_ID}!=? AND ${Buddies.Columns.BUDDY_FLAG}=1" else null, if (buddiesOnly) arrayOf(Authenticator.getUserId(context)) else null, sortOrder )?.use { if (it.moveToFirst()) { do { results += UserEntity( internalId = it.getLong(0), id = it.getInt(1), userName = it.getStringOrNull(2).orEmpty(), firstName = it.getStringOrNull(3).orEmpty(), lastName = it.getStringOrNull(4).orEmpty(), avatarUrlRaw = it.getStringOrNull(5).orEmpty(), playNickname = it.getStringOrNull(6).orEmpty(), updatedTimestamp = it.getLongOrNull(7) ?: 0L, ) } while (it.moveToNext()) } } results } suspend fun saveUser(user: UserEntity, updateTime: Long = System.currentTimeMillis()): UserEntity = withContext(Dispatchers.IO) { if (user.userName.isNotBlank()) { val values = contentValuesOf( Buddies.Columns.UPDATED to updateTime, Buddies.Columns.UPDATED_LIST to updateTime ) val oldSyncHashCode = context.contentResolver.queryInt(Buddies.buildBuddyUri(user.userName), Buddies.Columns.SYNC_HASH_CODE) val newSyncHashCode = user.generateSyncHashCode() if (oldSyncHashCode != newSyncHashCode) { values.put(Buddies.Columns.BUDDY_ID, user.id) values.put(Buddies.Columns.BUDDY_NAME, user.userName) values.put(Buddies.Columns.BUDDY_FIRSTNAME, user.firstName) values.put(Buddies.Columns.BUDDY_LASTNAME, user.lastName) values.put(Buddies.Columns.AVATAR_URL, user.avatarUrl) values.put(Buddies.Columns.SYNC_HASH_CODE, newSyncHashCode) } val internalId = upsert(values, user.userName, user.id) user.copy(internalId = internalId, updatedTimestamp = updateTime) } else user } suspend fun saveBuddy(buddy: BriefBuddyEntity) = withContext(Dispatchers.IO) { if (buddy.id != INVALID_ID && buddy.userName.isNotBlank()) { val values = contentValuesOf( Buddies.Columns.BUDDY_ID to buddy.id, Buddies.Columns.BUDDY_NAME to buddy.userName, Buddies.Columns.BUDDY_FLAG to true, Buddies.Columns.UPDATED_LIST to buddy.updatedTimestamp ) upsert(values, buddy.userName, buddy.id) } else { Timber.i("Un-savable buddy %s (%d)", buddy.userName, buddy.id) } } suspend fun upsert(values: ContentValues, username: String, userId: Int? = null): Long = withContext(Dispatchers.IO) { val resolver = context.contentResolver val uri = Buddies.buildBuddyUri(username) val internalId = resolver.queryLong(uri, BaseColumns._ID, INVALID_ID.toLong()) if (internalId != INVALID_ID.toLong()) { values.remove(Buddies.Columns.BUDDY_NAME) val count = resolver.update(uri, values, null, null) Timber.d("Updated %,d buddy rows at %s", count, uri) maybeDeleteAvatar(values, uri) internalId } else { values.put(Buddies.Columns.BUDDY_NAME, username) userId?.let { values.put(Buddies.Columns.BUDDY_ID, it) } val insertedUri = resolver.insert(Buddies.CONTENT_URI, values) Timber.d("Inserted buddy at %s", insertedUri) insertedUri?.lastPathSegment?.toLongOrNull() ?: INVALID_ID.toLong() } } private suspend fun maybeDeleteAvatar(values: ContentValues, uri: Uri) = withContext(Dispatchers.IO) { if (values.containsKey(Buddies.Columns.AVATAR_URL)) { val newAvatarUrl: String = values.getAsString(Buddies.Columns.AVATAR_URL).orEmpty() val oldAvatarUrl = context.contentResolver.queryString(uri, Buddies.Columns.AVATAR_URL) if (newAvatarUrl != oldAvatarUrl) { val avatarFileName = FileUtils.getFileNameFromUrl(oldAvatarUrl) if (avatarFileName.isNotBlank()) { context.contentResolver.delete(Avatars.buildUri(avatarFileName), null, null) } } } } suspend fun deleteUsers(): Int = withContext(Dispatchers.IO) { context.contentResolver.delete(Buddies.CONTENT_URI, null, null) } suspend fun deleteUsersAsOf(updateTimestamp: Long): Int = withContext(Dispatchers.IO) { context.contentResolver.delete( Buddies.CONTENT_URI, "${Buddies.Columns.UPDATED_LIST}<?", arrayOf(updateTimestamp.toString()) ) } }
gpl-3.0
f053ea7e4b91a9aca93adb353df143c9
44.368984
140
0.590995
4.906883
false
false
false
false
ccomeaux/boardgamegeek4android
app/src/main/java/com/boardgamegeek/extensions/View.kt
1
9658
package com.boardgamegeek.extensions import android.animation.Animator import android.animation.AnimatorListenerAdapter import android.annotation.SuppressLint import android.graphics.Color import android.graphics.LinearGradient import android.graphics.Shader import android.graphics.drawable.Drawable import android.graphics.drawable.GradientDrawable import android.graphics.drawable.PaintDrawable import android.graphics.drawable.ShapeDrawable import android.graphics.drawable.shapes.RectShape import android.os.Build import android.util.TypedValue import android.view.Gravity import android.view.View import android.view.View.GONE import android.view.View.VISIBLE import android.view.ViewGroup import android.view.animation.Animation import android.view.animation.AnimationUtils import android.widget.ImageView import android.widget.TextView import androidx.annotation.ColorInt import androidx.core.content.ContextCompat import androidx.core.graphics.alpha import androidx.core.graphics.blue import androidx.core.graphics.green import androidx.core.graphics.red import androidx.core.view.ViewCompat import androidx.core.view.children import com.boardgamegeek.R import com.google.android.material.snackbar.Snackbar import java.util.* import kotlin.math.pow fun View.fade(fadeIn: Boolean, animate: Boolean = true) { if (fadeIn) this.fadeIn(animate) else this.fadeOut(animate = animate) } fun View.fadeIn(animate: Boolean = true) { clearAnimation() if (animate) { val animationDuration = resources.getInteger(android.R.integer.config_shortAnimTime) apply { alpha = 0f visibility = VISIBLE animate() .alpha(1f) .setDuration(animationDuration.toLong()) .setListener(null) } } else { visibility = VISIBLE } } fun View.fadeOut(visibility: Int = GONE, animate: Boolean = true) { clearAnimation() if (animate) { val animationDuration = resources.getInteger(android.R.integer.config_shortAnimTime) apply { animate() .alpha(0f) .setDuration(animationDuration.toLong()) .setListener(object : AnimatorListenerAdapter() { override fun onAnimationEnd(animation: Animator) { [email protected] = visibility } }) } } else { clearAnimation() this.visibility = visibility } } fun View.slideUpIn() { val animation = AnimationUtils.loadAnimation(this.context, R.anim.slide_up) this.startAnimation(animation) this.visibility = VISIBLE } fun View.slideDownOut() { val animation = AnimationUtils.loadAnimation(this.context, R.anim.slide_down) animation.setAnimationListener(object : Animation.AnimationListener { override fun onAnimationStart(animation: Animation) {} override fun onAnimationEnd(animation: Animation) { visibility = GONE } override fun onAnimationRepeat(animation: Animation) {} }) this.startAnimation(animation) } @Suppress("SpellCheckingInspection") /** * Set the background of an {@link android.widget.ImageView} to an oval of the specified color, with a darker * version of the color as a border. For a {@link android.widget.TextView}, changes the text color instead. Doesn't * do anything for other views. Modified from Roman Nurik's DashClock (https://code.google.com/p/dashclock/). */ fun View.setColorViewValue(color: Int) { if (this is ImageView) { val currentDrawable = drawable val colorChoiceDrawable = if (currentDrawable is GradientDrawable) { // Reuse drawable currentDrawable } else { GradientDrawable().apply { shape = GradientDrawable.OVAL } } colorChoiceDrawable.setColor(color) colorChoiceDrawable.setStroke( TypedValue.applyDimension( TypedValue.COMPLEX_UNIT_DIP, 1f, resources.displayMetrics ).toInt(), color.darkenColor() ) setImageDrawable(colorChoiceDrawable) } else if (this is TextView) { if (color != Color.TRANSPARENT) { setTextColor(color) } } } fun View.applyDarkScrim() { val color = ContextCompat.getColor(context, R.color.black_overlay) val drawable = makeCubicGradientScrimDrawable(color) ViewCompat.setBackground(this, drawable) } @SuppressLint("RtlHardcoded") private fun makeCubicGradientScrimDrawable( @ColorInt baseColor: Int, numberOfStops: Int = 3, gravity: Int = Gravity.BOTTOM ): Drawable { val numStops = numberOfStops.coerceAtLeast(2) val paintDrawable = PaintDrawable().apply { shape = RectShape() } val stopColors = IntArray(numStops) for (i in 0 until numStops) { val opacity = (i * 1f / (numStops - 1)).toDouble().pow(3).toFloat().coerceIn(0f, 1f) stopColors[i] = Color.argb((baseColor.alpha * opacity).toInt(), baseColor.red, baseColor.green, baseColor.blue) } val x0 = if (gravity and Gravity.HORIZONTAL_GRAVITY_MASK == Gravity.LEFT) 1f else 0f val x1 = if (gravity and Gravity.HORIZONTAL_GRAVITY_MASK == Gravity.RIGHT) 1f else 0f val y0 = if (gravity and Gravity.VERTICAL_GRAVITY_MASK == Gravity.TOP) 1f else 0f val y1 = if (gravity and Gravity.VERTICAL_GRAVITY_MASK == Gravity.BOTTOM) 1f else 0f paintDrawable.shaderFactory = object : ShapeDrawable.ShaderFactory() { override fun resize(width: Int, height: Int): Shader { return LinearGradient( width * x0, height * y0, width * x1, height * y1, stopColors, null, Shader.TileMode.CLAMP ) } } return paintDrawable } /** * Set the background of a [View] o the specified color, with a darker version of the color as a 1dp border. */ fun View.setViewBackground(@ColorInt color: Int) { val r = this.resources val currentDrawable = background val backgroundDrawable = if (currentDrawable != null && currentDrawable is GradientDrawable) { // Reuse drawable currentDrawable } else { GradientDrawable() } backgroundDrawable.setColor(color) backgroundDrawable.cornerRadius = resources.getDimensionPixelSize(R.dimen.colored_background_corner_radius).toFloat() backgroundDrawable.setStroke( TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 1f, r.displayMetrics).toInt(), color.darkenColor() ) ViewCompat.setBackground(this, backgroundDrawable) } fun View.setSelectableBackgroundBorderless() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { setSelectableBackground(android.R.attr.selectableItemBackgroundBorderless) } else { setSelectableBackground() } } fun View.setSelectableBackground(backgroundResId: Int = android.R.attr.selectableItemBackground) { val outValue = TypedValue() context.theme.resolveAttribute(backgroundResId, outValue, true) setBackgroundResource(outValue.resourceId) isClickable = true visibility = VISIBLE } fun View.setOrClearOnClickListener(clickable: Boolean = false, l: (View) -> Unit = { }) { if (clickable) { setOnClickListener(l) } else { setOnClickListener { } isClickable = false } } @Suppress("NOTHING_TO_INLINE") inline fun View.snackbar(messageResourceId: Int) = Snackbar .make(this, messageResourceId, Snackbar.LENGTH_SHORT) .apply { show() } @Suppress("NOTHING_TO_INLINE") inline fun View.snackbar(message: CharSequence) = Snackbar .make(this, message, Snackbar.LENGTH_SHORT) .apply { show() } @Suppress("NOTHING_TO_INLINE") inline fun View.longSnackbar(messageResourceId: Int) = Snackbar .make(this, messageResourceId, Snackbar.LENGTH_LONG) .apply { show() } @Suppress("NOTHING_TO_INLINE") inline fun View.longSnackbar(message: CharSequence) = Snackbar .make(this, message, Snackbar.LENGTH_LONG) .apply { show() } @Suppress("NOTHING_TO_INLINE") inline fun View.indefiniteSnackbar(message: CharSequence) = Snackbar .make(this, message, Snackbar.LENGTH_INDEFINITE) .apply { show() } @Suppress("NOTHING_TO_INLINE") inline fun View.indefiniteSnackbar(message: CharSequence, actionText: CharSequence, noinline action: (View) -> Unit) = Snackbar .make(this, message, Snackbar.LENGTH_INDEFINITE) .setAction(actionText, action) .apply { show() } fun View.childrenRecursiveSequence(): Sequence<View> = ViewChildrenRecursiveSequence(this) private class ViewChildrenRecursiveSequence(private val view: View) : Sequence<View> { override fun iterator(): Iterator<View> { return if (view is ViewGroup) RecursiveViewIterator(view) else emptyList<View>().iterator() } private class RecursiveViewIterator(view: ViewGroup) : Iterator<View> { private val sequences = arrayListOf(view.children) private var current = sequences.removeLast().iterator() override fun next(): View { if (!hasNext()) throw NoSuchElementException() val view = current.next() if (view is ViewGroup && view.childCount > 0) { sequences.add(view.children) } return view } override fun hasNext(): Boolean { if (!current.hasNext() && sequences.isNotEmpty()) { current = sequences.removeLast().iterator() } return current.hasNext() } } }
gpl-3.0
6e14ec2549933e4d66cce6899bb44375
33.127208
127
0.680265
4.46097
false
false
false
false
WindSekirun/RichUtilsKt
demo/src/main/java/pyxis/uzuki/live/richutilskt/demo/item/ExecuteItem.kt
1
820
package pyxis.uzuki.live.richutilskt.demo.item import android.content.Context import android.os.Parcel import android.os.Parcelable import java.io.Serializable /** * RichUtilsKt * Class: ExecuteItem * Created by Pyxis on 2017-11-06. * * Description: */ data class ExecuteItem(val category: CategoryItem, val title: String, val message: String, val execute: ((Context) -> Unit)? = null, val kotlinSample: String, val javaSample: String) : Serializable fun generateExecuteItem(category: CategoryItem, title: String, message: String = "", kotlinSample: String = "", javaSample: String = "", execute: ((Context) -> Unit)? = null): ExecuteItem { return ExecuteItem(category, title, message, execute, kotlinSample, javaSample) } fun String.toEscape() = "\"$this\""
apache-2.0
72e5b95b7c7a68438ea8748630755252
33.208333
132
0.693902
4.059406
false
false
false
false
bobrofon/easysshfs
app/src/main/java/ru/nsu/bobrofon/easysshfs/log/AppLog.kt
1
1460
package ru.nsu.bobrofon.easysshfs.log import java.lang.ref.WeakReference import android.util.Log private const val TAG = "AppLog" private const val SIZE_LIMIT = 4 * 1024 * 1024 class AppLog(private val logBuffer: StringBuffer = StringBuffer()) : LogView { private val observable = LogObservable(this) init { Log.i(TAG, "new instance") } override fun toString(): String = logBuffer.toString() fun addMessage(message: CharSequence) { if (logBuffer.length > SIZE_LIMIT) { logBuffer.setLength(0) } Log.i(TAG, "new message: $message") logBuffer.append(">_ ").append(message).append("\n") observable.notifyChanged() } fun clean() { logBuffer.setLength(0) observable.notifyChanged() } fun registerObserver(logChangeObserver: LogChangeObserver) = observable.registerObserver(logChangeObserver) fun unregisterObserver(logChangeObserver: LogChangeObserver) = observable.unregisterObserver(logChangeObserver) companion object { private var instance = WeakReference<AppLog?>(null) @Synchronized fun instance(): AppLog { val oldInstance = instance.get() if (oldInstance == null) { val newInstance = AppLog() instance = WeakReference(newInstance) return newInstance } return oldInstance } } }
mit
f0cf95f6e2dcddcfa101dc5294cf7c15
26.037037
78
0.629452
4.664537
false
false
false
false
QuickBlox/quickblox-android-sdk
sample-chat-kotlin/app/src/main/java/com/quickblox/sample/chat/kotlin/ui/activity/NewGroupActivity.kt
1
3599
package com.quickblox.sample.chat.kotlin.ui.activity import android.app.Activity import android.content.Intent import android.os.Bundle import android.os.SystemClock import android.text.Editable import android.text.TextUtils import android.text.TextWatcher import android.view.Menu import android.view.MenuItem import android.view.View import android.widget.EditText import android.widget.ImageView import android.widget.TextView import com.quickblox.sample.chat.kotlin.R import com.quickblox.sample.chat.kotlin.utils.isDialogNameValid private const val CLICK_DELAY = 1000L class NewGroupActivity : BaseActivity() { private lateinit var menu: Menu private lateinit var etDialogName: EditText private lateinit var tvDialogNameHint: TextView private lateinit var ivClear: ImageView private var lastClickTime = 0L companion object { fun startForResult(activity: Activity, code: Int) { val intent = Intent(activity, NewGroupActivity::class.java) activity.startActivityForResult(intent, code) } } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_enter_chat_name) etDialogName = findViewById(R.id.et_dialog_name) tvDialogNameHint = findViewById(R.id.tv_group_name_hint) ivClear = findViewById(R.id.iv_clear) etDialogName.addTextChangedListener(TextWatcherListener(etDialogName)) ivClear.setOnClickListener { etDialogName.setText("") } supportActionBar?.title = getString(R.string.select_users_create_chat_title) supportActionBar?.setDisplayHomeAsUpEnabled(true) } override fun onCreateOptionsMenu(menu: Menu): Boolean { this.menu = menu menuInflater.inflate(R.menu.menu_activity_new_group, menu) return true } override fun onOptionsItemSelected(item: MenuItem): Boolean { if (SystemClock.uptimeMillis() - lastClickTime < CLICK_DELAY) { return super.onOptionsItemSelected(item) } lastClickTime = SystemClock.uptimeMillis() when (item.itemId) { R.id.menu_finish -> { passResultToCallerActivity() } else -> return super.onOptionsItemSelected(item) } return true } private fun passResultToCallerActivity() { val dialogName = etDialogName.text.toString().trim { it <= ' ' } val intent = Intent() if (!TextUtils.isEmpty(dialogName)) { intent.putExtra(EXTRA_CHAT_NAME, dialogName) } setResult(Activity.RESULT_OK, intent) finish() } private fun validateFields() { menu.getItem(0).isVisible = isDialogNameValid(etDialogName) tvDialogNameHint.visibility = if (isDialogNameValid(etDialogName)) { View.GONE } else { View.VISIBLE } } private inner class TextWatcherListener(private var editText: EditText) : TextWatcher { override fun beforeTextChanged(charSequence: CharSequence?, start: Int, count: Int, after: Int) { } override fun onTextChanged(charSequence: CharSequence?, start: Int, before: Int, count: Int) { val text = charSequence.toString().replace(" ", " ") if (editText.text.toString() != text) { editText.setText(text) editText.setSelection(text.length) } validateFields() } override fun afterTextChanged(s: Editable?) { } } }
bsd-3-clause
41a5d727f803a89abe032370bc892bec
32.027523
105
0.666574
4.625964
false
false
false
false
ansman/okhttp
okhttp/src/main/kotlin/okhttp3/internal/ws/RealWebSocket.kt
7
21596
/* * Copyright (C) 2016 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 okhttp3.internal.ws import java.io.Closeable import java.io.IOException import java.net.ProtocolException import java.net.SocketTimeoutException import java.util.ArrayDeque import java.util.Random import java.util.concurrent.TimeUnit import java.util.concurrent.TimeUnit.MILLISECONDS import okhttp3.Call import okhttp3.Callback import okhttp3.EventListener import okhttp3.OkHttpClient import okhttp3.Protocol import okhttp3.Request import okhttp3.Response import okhttp3.WebSocket import okhttp3.WebSocketListener import okhttp3.internal.assertThreadHoldsLock import okhttp3.internal.closeQuietly import okhttp3.internal.concurrent.Task import okhttp3.internal.concurrent.TaskRunner import okhttp3.internal.connection.Exchange import okhttp3.internal.connection.RealCall import okhttp3.internal.okHttpName import okhttp3.internal.ws.WebSocketProtocol.CLOSE_CLIENT_GOING_AWAY import okhttp3.internal.ws.WebSocketProtocol.CLOSE_MESSAGE_MAX import okhttp3.internal.ws.WebSocketProtocol.OPCODE_BINARY import okhttp3.internal.ws.WebSocketProtocol.OPCODE_TEXT import okhttp3.internal.ws.WebSocketProtocol.validateCloseCode import okio.BufferedSink import okio.BufferedSource import okio.ByteString import okio.ByteString.Companion.encodeUtf8 import okio.ByteString.Companion.toByteString class RealWebSocket( taskRunner: TaskRunner, /** The application's original request unadulterated by web socket headers. */ private val originalRequest: Request, internal val listener: WebSocketListener, private val random: Random, private val pingIntervalMillis: Long, /** * For clients this is initially null, and will be assigned to the agreed-upon extensions. For * servers it should be the agreed-upon extensions immediately. */ private var extensions: WebSocketExtensions?, /** If compression is negotiated, outbound messages of this size and larger will be compressed. */ private var minimumDeflateSize: Long ) : WebSocket, WebSocketReader.FrameCallback { private val key: String /** Non-null for client web sockets. These can be canceled. */ private var call: Call? = null /** This task processes the outgoing queues. Call [runWriter] to after enqueueing. */ private var writerTask: Task? = null /** Null until this web socket is connected. Only accessed by the reader thread. */ private var reader: WebSocketReader? = null // All mutable web socket state is guarded by this. /** Null until this web socket is connected. Note that messages may be enqueued before that. */ private var writer: WebSocketWriter? = null /** Used for writes, pings, and close timeouts. */ private var taskQueue = taskRunner.newQueue() /** Names this web socket for observability and debugging. */ private var name: String? = null /** * The streams held by this web socket. This is non-null until all incoming messages have been * read and all outgoing messages have been written. It is closed when both reader and writer are * exhausted, or if there is any failure. */ private var streams: Streams? = null /** Outgoing pongs in the order they should be written. */ private val pongQueue = ArrayDeque<ByteString>() /** Outgoing messages and close frames in the order they should be written. */ private val messageAndCloseQueue = ArrayDeque<Any>() /** The total size in bytes of enqueued but not yet transmitted messages. */ private var queueSize = 0L /** True if we've enqueued a close frame. No further message frames will be enqueued. */ private var enqueuedClose = false /** The close code from the peer, or -1 if this web socket has not yet read a close frame. */ private var receivedCloseCode = -1 /** The close reason from the peer, or null if this web socket has not yet read a close frame. */ private var receivedCloseReason: String? = null /** True if this web socket failed and the listener has been notified. */ private var failed = false /** Total number of pings sent by this web socket. */ private var sentPingCount = 0 /** Total number of pings received by this web socket. */ private var receivedPingCount = 0 /** Total number of pongs received by this web socket. */ private var receivedPongCount = 0 /** True if we have sent a ping that is still awaiting a reply. */ private var awaitingPong = false init { require("GET" == originalRequest.method) { "Request must be GET: ${originalRequest.method}" } this.key = ByteArray(16).apply { random.nextBytes(this) }.toByteString().base64() } override fun request(): Request = originalRequest @Synchronized override fun queueSize(): Long = queueSize override fun cancel() { call!!.cancel() } fun connect(client: OkHttpClient) { if (originalRequest.header("Sec-WebSocket-Extensions") != null) { failWebSocket(ProtocolException( "Request header not permitted: 'Sec-WebSocket-Extensions'"), null) return } val webSocketClient = client.newBuilder() .eventListener(EventListener.NONE) .protocols(ONLY_HTTP1) .build() val request = originalRequest.newBuilder() .header("Upgrade", "websocket") .header("Connection", "Upgrade") .header("Sec-WebSocket-Key", key) .header("Sec-WebSocket-Version", "13") .header("Sec-WebSocket-Extensions", "permessage-deflate") .build() call = RealCall(webSocketClient, request, forWebSocket = true) call!!.enqueue(object : Callback { override fun onResponse(call: Call, response: Response) { val exchange = response.exchange val streams: Streams try { checkUpgradeSuccess(response, exchange) streams = exchange!!.newWebSocketStreams() } catch (e: IOException) { exchange?.webSocketUpgradeFailed() failWebSocket(e, response) response.closeQuietly() return } // Apply the extensions. If they're unacceptable initiate a graceful shut down. // TODO(jwilson): Listeners should get onFailure() instead of onClosing() + onClosed(1010). val extensions = WebSocketExtensions.parse(response.headers) [email protected] = extensions if (!extensions.isValid()) { synchronized(this@RealWebSocket) { messageAndCloseQueue.clear() // Don't transmit any messages. close(1010, "unexpected Sec-WebSocket-Extensions in response header") } } // Process all web socket messages. try { val name = "$okHttpName WebSocket ${request.url.redact()}" initReaderAndWriter(name, streams) listener.onOpen(this@RealWebSocket, response) loopReader() } catch (e: Exception) { failWebSocket(e, null) } } override fun onFailure(call: Call, e: IOException) { failWebSocket(e, null) } }) } private fun WebSocketExtensions.isValid(): Boolean { // If the server returned parameters we don't understand, fail the web socket. if (unknownValues) return false // If the server returned a value for client_max_window_bits, fail the web socket. if (clientMaxWindowBits != null) return false // If the server returned an illegal server_max_window_bits, fail the web socket. if (serverMaxWindowBits != null && serverMaxWindowBits !in 8..15) return false // Success. return true } @Throws(IOException::class) internal fun checkUpgradeSuccess(response: Response, exchange: Exchange?) { if (response.code != 101) { throw ProtocolException( "Expected HTTP 101 response but was '${response.code} ${response.message}'") } val headerConnection = response.header("Connection") if (!"Upgrade".equals(headerConnection, ignoreCase = true)) { throw ProtocolException( "Expected 'Connection' header value 'Upgrade' but was '$headerConnection'") } val headerUpgrade = response.header("Upgrade") if (!"websocket".equals(headerUpgrade, ignoreCase = true)) { throw ProtocolException( "Expected 'Upgrade' header value 'websocket' but was '$headerUpgrade'") } val headerAccept = response.header("Sec-WebSocket-Accept") val acceptExpected = (key + WebSocketProtocol.ACCEPT_MAGIC).encodeUtf8().sha1().base64() if (acceptExpected != headerAccept) { throw ProtocolException( "Expected 'Sec-WebSocket-Accept' header value '$acceptExpected' but was '$headerAccept'") } if (exchange == null) { throw ProtocolException("Web Socket exchange missing: bad interceptor?") } } @Throws(IOException::class) fun initReaderAndWriter(name: String, streams: Streams) { val extensions = this.extensions!! synchronized(this) { this.name = name this.streams = streams this.writer = WebSocketWriter( isClient = streams.client, sink = streams.sink, random = random, perMessageDeflate = extensions.perMessageDeflate, noContextTakeover = extensions.noContextTakeover(streams.client), minimumDeflateSize = minimumDeflateSize ) this.writerTask = WriterTask() if (pingIntervalMillis != 0L) { val pingIntervalNanos = MILLISECONDS.toNanos(pingIntervalMillis) taskQueue.schedule("$name ping", pingIntervalNanos) { writePingFrame() return@schedule pingIntervalNanos } } if (messageAndCloseQueue.isNotEmpty()) { runWriter() // Send messages that were enqueued before we were connected. } } reader = WebSocketReader( isClient = streams.client, source = streams.source, frameCallback = this, perMessageDeflate = extensions.perMessageDeflate, noContextTakeover = extensions.noContextTakeover(!streams.client) ) } /** Receive frames until there are no more. Invoked only by the reader thread. */ @Throws(IOException::class) fun loopReader() { while (receivedCloseCode == -1) { // This method call results in one or more onRead* methods being called on this thread. reader!!.processNextFrame() } } /** * For testing: receive a single frame and return true if there are more frames to read. Invoked * only by the reader thread. */ @Throws(IOException::class) fun processNextFrame(): Boolean { return try { reader!!.processNextFrame() receivedCloseCode == -1 } catch (e: Exception) { failWebSocket(e, null) false } } /** For testing: wait until the web socket's executor has terminated. */ @Throws(InterruptedException::class) fun awaitTermination(timeout: Long, timeUnit: TimeUnit) { taskQueue.idleLatch().await(timeout, timeUnit) } /** For testing: force this web socket to release its threads. */ @Throws(InterruptedException::class) fun tearDown() { taskQueue.shutdown() taskQueue.idleLatch().await(10, TimeUnit.SECONDS) } @Synchronized fun sentPingCount(): Int = sentPingCount @Synchronized fun receivedPingCount(): Int = receivedPingCount @Synchronized fun receivedPongCount(): Int = receivedPongCount @Throws(IOException::class) override fun onReadMessage(text: String) { listener.onMessage(this, text) } @Throws(IOException::class) override fun onReadMessage(bytes: ByteString) { listener.onMessage(this, bytes) } @Synchronized override fun onReadPing(payload: ByteString) { // Don't respond to pings after we've failed or sent the close frame. if (failed || enqueuedClose && messageAndCloseQueue.isEmpty()) return pongQueue.add(payload) runWriter() receivedPingCount++ } @Synchronized override fun onReadPong(payload: ByteString) { // This API doesn't expose pings. receivedPongCount++ awaitingPong = false } override fun onReadClose(code: Int, reason: String) { require(code != -1) var toClose: Streams? = null var readerToClose: WebSocketReader? = null var writerToClose: WebSocketWriter? = null synchronized(this) { check(receivedCloseCode == -1) { "already closed" } receivedCloseCode = code receivedCloseReason = reason if (enqueuedClose && messageAndCloseQueue.isEmpty()) { toClose = this.streams this.streams = null readerToClose = this.reader this.reader = null writerToClose = this.writer this.writer = null this.taskQueue.shutdown() } } try { listener.onClosing(this, code, reason) if (toClose != null) { listener.onClosed(this, code, reason) } } finally { toClose?.closeQuietly() readerToClose?.closeQuietly() writerToClose?.closeQuietly() } } // Writer methods to enqueue frames. They'll be sent asynchronously by the writer thread. override fun send(text: String): Boolean { return send(text.encodeUtf8(), OPCODE_TEXT) } override fun send(bytes: ByteString): Boolean { return send(bytes, OPCODE_BINARY) } @Synchronized private fun send(data: ByteString, formatOpcode: Int): Boolean { // Don't send new frames after we've failed or enqueued a close frame. if (failed || enqueuedClose) return false // If this frame overflows the buffer, reject it and close the web socket. if (queueSize + data.size > MAX_QUEUE_SIZE) { close(CLOSE_CLIENT_GOING_AWAY, null) return false } // Enqueue the message frame. queueSize += data.size.toLong() messageAndCloseQueue.add(Message(formatOpcode, data)) runWriter() return true } @Synchronized fun pong(payload: ByteString): Boolean { // Don't send pongs after we've failed or sent the close frame. if (failed || enqueuedClose && messageAndCloseQueue.isEmpty()) return false pongQueue.add(payload) runWriter() return true } override fun close(code: Int, reason: String?): Boolean { return close(code, reason, CANCEL_AFTER_CLOSE_MILLIS) } @Synchronized fun close( code: Int, reason: String?, cancelAfterCloseMillis: Long ): Boolean { validateCloseCode(code) var reasonBytes: ByteString? = null if (reason != null) { reasonBytes = reason.encodeUtf8() require(reasonBytes.size <= CLOSE_MESSAGE_MAX) { "reason.size() > $CLOSE_MESSAGE_MAX: $reason" } } if (failed || enqueuedClose) return false // Immediately prevent further frames from being enqueued. enqueuedClose = true // Enqueue the close frame. messageAndCloseQueue.add(Close(code, reasonBytes, cancelAfterCloseMillis)) runWriter() return true } private fun runWriter() { this.assertThreadHoldsLock() val writerTask = writerTask if (writerTask != null) { taskQueue.schedule(writerTask) } } /** * Attempts to remove a single frame from a queue and send it. This prefers to write urgent pongs * before less urgent messages and close frames. For example it's possible that a caller will * enqueue messages followed by pongs, but this sends pongs followed by messages. Pongs are always * written in the order they were enqueued. * * If a frame cannot be sent - because there are none enqueued or because the web socket is not * connected - this does nothing and returns false. Otherwise this returns true and the caller * should immediately invoke this method again until it returns false. * * This method may only be invoked by the writer thread. There may be only thread invoking this * method at a time. */ @Throws(IOException::class) internal fun writeOneFrame(): Boolean { val writer: WebSocketWriter? val pong: ByteString? var messageOrClose: Any? = null var receivedCloseCode = -1 var receivedCloseReason: String? = null var streamsToClose: Streams? = null var readerToClose: WebSocketReader? = null var writerToClose: WebSocketWriter? = null synchronized(this@RealWebSocket) { if (failed) { return false // Failed web socket. } writer = this.writer pong = pongQueue.poll() if (pong == null) { messageOrClose = messageAndCloseQueue.poll() if (messageOrClose is Close) { receivedCloseCode = this.receivedCloseCode receivedCloseReason = this.receivedCloseReason if (receivedCloseCode != -1) { streamsToClose = this.streams this.streams = null readerToClose = this.reader this.reader = null writerToClose = this.writer this.writer = null this.taskQueue.shutdown() } else { // When we request a graceful close also schedule a cancel of the web socket. val cancelAfterCloseMillis = (messageOrClose as Close).cancelAfterCloseMillis taskQueue.execute("$name cancel", MILLISECONDS.toNanos(cancelAfterCloseMillis)) { cancel() } } } else if (messageOrClose == null) { return false // The queue is exhausted. } } } try { if (pong != null) { writer!!.writePong(pong) } else if (messageOrClose is Message) { val message = messageOrClose as Message writer!!.writeMessageFrame(message.formatOpcode, message.data) synchronized(this) { queueSize -= message.data.size.toLong() } } else if (messageOrClose is Close) { val close = messageOrClose as Close writer!!.writeClose(close.code, close.reason) // We closed the writer: now both reader and writer are closed. if (streamsToClose != null) { listener.onClosed(this, receivedCloseCode, receivedCloseReason!!) } } else { throw AssertionError() } return true } finally { streamsToClose?.closeQuietly() readerToClose?.closeQuietly() writerToClose?.closeQuietly() } } internal fun writePingFrame() { val writer: WebSocketWriter val failedPing: Int synchronized(this) { if (failed) return writer = this.writer ?: return failedPing = if (awaitingPong) sentPingCount else -1 sentPingCount++ awaitingPong = true } if (failedPing != -1) { failWebSocket(SocketTimeoutException("sent ping but didn't receive pong within " + "${pingIntervalMillis}ms (after ${failedPing - 1} successful ping/pongs)"), null) return } try { writer.writePing(ByteString.EMPTY) } catch (e: IOException) { failWebSocket(e, null) } } fun failWebSocket(e: Exception, response: Response?) { val streamsToClose: Streams? val readerToClose: WebSocketReader? val writerToClose: WebSocketWriter? synchronized(this) { if (failed) return // Already failed. failed = true streamsToClose = this.streams this.streams = null readerToClose = this.reader this.reader = null writerToClose = this.writer this.writer = null taskQueue.shutdown() } try { listener.onFailure(this, e, response) } finally { streamsToClose?.closeQuietly() readerToClose?.closeQuietly() writerToClose?.closeQuietly() } } internal class Message( val formatOpcode: Int, val data: ByteString ) internal class Close( val code: Int, val reason: ByteString?, val cancelAfterCloseMillis: Long ) abstract class Streams( val client: Boolean, val source: BufferedSource, val sink: BufferedSink ) : Closeable private inner class WriterTask : Task("$name writer") { override fun runOnce(): Long { try { if (writeOneFrame()) return 0L } catch (e: IOException) { failWebSocket(e, null) } return -1L } } companion object { private val ONLY_HTTP1 = listOf(Protocol.HTTP_1_1) /** * The maximum number of bytes to enqueue. Rather than enqueueing beyond this limit we tear down * the web socket! It's possible that we're writing faster than the peer can read. */ private const val MAX_QUEUE_SIZE = 16L * 1024 * 1024 // 16 MiB. /** * The maximum amount of time after the client calls [close] to wait for a graceful shutdown. If * the server doesn't respond the web socket will be canceled. */ private const val CANCEL_AFTER_CLOSE_MILLIS = 60L * 1000 /** * The smallest message that will be compressed. We use 1024 because smaller messages already * fit comfortably within a single ethernet packet (1500 bytes) even with framing overhead. * * For tests this must be big enough to realize real compression on test messages like * 'aaaaaaaaaa...'. Our tests check if compression was applied just by looking at the size if * the inbound buffer. */ const val DEFAULT_MINIMUM_DEFLATE_SIZE = 1024L } }
apache-2.0
2d626c246a6de322d2fa7443e16e722f
32.071975
100
0.679061
4.48888
false
false
false
false