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
androidx/androidx
tv/tv-foundation/src/main/java/androidx/tv/foundation/lazy/list/LazyListMeasure.kt
3
22253
/* * Copyright 2020 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.tv.foundation.lazy.list import androidx.compose.foundation.gestures.Orientation import androidx.compose.foundation.layout.Arrangement import androidx.compose.ui.layout.MeasureResult import androidx.compose.ui.layout.Placeable import androidx.compose.ui.unit.Constraints import androidx.compose.ui.unit.Density import androidx.compose.ui.unit.LayoutDirection import androidx.compose.ui.unit.constrainHeight import androidx.compose.ui.unit.constrainWidth import androidx.compose.ui.util.fastForEach import androidx.tv.foundation.lazy.LazyListBeyondBoundsInfo import kotlin.contracts.ExperimentalContracts import kotlin.contracts.contract import kotlin.math.abs import kotlin.math.min import kotlin.math.roundToInt import kotlin.math.sign /** * Measures and calculates the positions for the requested items. The result is produced * as a [LazyListMeasureResult] which contains all the calculations. */ internal fun measureLazyList( itemsCount: Int, itemProvider: LazyMeasuredItemProvider, mainAxisAvailableSize: Int, beforeContentPadding: Int, afterContentPadding: Int, spaceBetweenItems: Int, firstVisibleItemIndex: DataIndex, firstVisibleItemScrollOffset: Int, scrollToBeConsumed: Float, constraints: Constraints, isVertical: Boolean, headerIndexes: List<Int>, verticalArrangement: Arrangement.Vertical?, horizontalArrangement: Arrangement.Horizontal?, reverseLayout: Boolean, density: Density, placementAnimator: LazyListItemPlacementAnimator, beyondBoundsInfo: LazyListBeyondBoundsInfo, beyondBoundsItemCount: Int, layout: (Int, Int, Placeable.PlacementScope.() -> Unit) -> MeasureResult ): LazyListMeasureResult { require(beforeContentPadding >= 0) require(afterContentPadding >= 0) if (itemsCount <= 0) { // empty data set. reset the current scroll and report zero size return LazyListMeasureResult( firstVisibleItem = null, firstVisibleItemScrollOffset = 0, canScrollForward = false, consumedScroll = 0f, measureResult = layout(constraints.minWidth, constraints.minHeight) {}, visibleItemsInfo = emptyList(), viewportStartOffset = -beforeContentPadding, viewportEndOffset = mainAxisAvailableSize + afterContentPadding, totalItemsCount = 0, reverseLayout = reverseLayout, orientation = if (isVertical) Orientation.Vertical else Orientation.Horizontal, afterContentPadding = afterContentPadding ) } else { var currentFirstItemIndex = firstVisibleItemIndex var currentFirstItemScrollOffset = firstVisibleItemScrollOffset if (currentFirstItemIndex.value >= itemsCount) { // the data set has been updated and now we have less items that we were // scrolled to before currentFirstItemIndex = DataIndex(itemsCount - 1) currentFirstItemScrollOffset = 0 } // represents the real amount of scroll we applied as a result of this measure pass. var scrollDelta = scrollToBeConsumed.roundToInt() // applying the whole requested scroll offset. we will figure out if we can't consume // all of it later currentFirstItemScrollOffset -= scrollDelta // if the current scroll offset is less than minimally possible if (currentFirstItemIndex == DataIndex(0) && currentFirstItemScrollOffset < 0) { scrollDelta += currentFirstItemScrollOffset currentFirstItemScrollOffset = 0 } // this will contain all the MeasuredItems representing the visible items val visibleItems = mutableListOf<LazyMeasuredItem>() // define min and max offsets val minOffset = -beforeContentPadding + if (spaceBetweenItems < 0) spaceBetweenItems else 0 val maxOffset = mainAxisAvailableSize // include the start padding so we compose items in the padding area and neutralise item // spacing (if the spacing is negative this will make sure the previous item is composed) // before starting scrolling forward we will remove it back currentFirstItemScrollOffset += minOffset // max of cross axis sizes of all visible items var maxCrossAxis = 0 // we had scrolled backward or we compose items in the start padding area, which means // items before current firstItemScrollOffset should be visible. compose them and update // firstItemScrollOffset while (currentFirstItemScrollOffset < 0 && currentFirstItemIndex > DataIndex(0)) { val previous = DataIndex(currentFirstItemIndex.value - 1) val measuredItem = itemProvider.getAndMeasure(previous) visibleItems.add(0, measuredItem) maxCrossAxis = maxOf(maxCrossAxis, measuredItem.crossAxisSize) currentFirstItemScrollOffset += measuredItem.sizeWithSpacings currentFirstItemIndex = previous } // if we were scrolled backward, but there were not enough items before. this means // not the whole scroll was consumed if (currentFirstItemScrollOffset < minOffset) { scrollDelta += currentFirstItemScrollOffset currentFirstItemScrollOffset = minOffset } // neutralize previously added padding as we stopped filling the before content padding currentFirstItemScrollOffset -= minOffset var index = currentFirstItemIndex val maxMainAxis = (maxOffset + afterContentPadding).coerceAtLeast(0) var currentMainAxisOffset = -currentFirstItemScrollOffset // first we need to skip items we already composed while composing backward visibleItems.fastForEach { index++ currentMainAxisOffset += it.sizeWithSpacings } // then composing visible items forward until we fill the whole viewport. // we want to have at least one item in visibleItems even if in fact all the items are // offscreen, this can happen if the content padding is larger than the available size. while (index.value < itemsCount && (currentMainAxisOffset < maxMainAxis || currentMainAxisOffset <= 0 || // filling beforeContentPadding area visibleItems.isEmpty()) ) { val measuredItem = itemProvider.getAndMeasure(index) currentMainAxisOffset += measuredItem.sizeWithSpacings if (currentMainAxisOffset <= minOffset && index.value != itemsCount - 1) { // this item is offscreen and will not be placed. advance firstVisibleItemIndex currentFirstItemIndex = index + 1 currentFirstItemScrollOffset -= measuredItem.sizeWithSpacings } else { maxCrossAxis = maxOf(maxCrossAxis, measuredItem.crossAxisSize) visibleItems.add(measuredItem) } index++ } // we didn't fill the whole viewport with items starting from firstVisibleItemIndex. // lets try to scroll back if we have enough items before firstVisibleItemIndex. if (currentMainAxisOffset < maxOffset) { val toScrollBack = maxOffset - currentMainAxisOffset currentFirstItemScrollOffset -= toScrollBack currentMainAxisOffset += toScrollBack while (currentFirstItemScrollOffset < beforeContentPadding && currentFirstItemIndex > DataIndex(0) ) { val previousIndex = DataIndex(currentFirstItemIndex.value - 1) val measuredItem = itemProvider.getAndMeasure(previousIndex) visibleItems.add(0, measuredItem) maxCrossAxis = maxOf(maxCrossAxis, measuredItem.crossAxisSize) currentFirstItemScrollOffset += measuredItem.sizeWithSpacings currentFirstItemIndex = previousIndex } scrollDelta += toScrollBack if (currentFirstItemScrollOffset < 0) { scrollDelta += currentFirstItemScrollOffset currentMainAxisOffset += currentFirstItemScrollOffset currentFirstItemScrollOffset = 0 } } // report the amount of pixels we consumed. scrollDelta can be smaller than // scrollToBeConsumed if there were not enough items to fill the offered space or it // can be larger if items were resized, or if, for example, we were previously // displaying the item 15, but now we have only 10 items in total in the data set. val consumedScroll = if (scrollToBeConsumed.roundToInt().sign == scrollDelta.sign && abs(scrollToBeConsumed.roundToInt()) >= abs(scrollDelta) ) { scrollDelta.toFloat() } else { scrollToBeConsumed } // the initial offset for items from visibleItems list require(currentFirstItemScrollOffset >= 0) val visibleItemsScrollOffset = -currentFirstItemScrollOffset var firstItem = visibleItems.first() // even if we compose items to fill before content padding we should ignore items fully // located there for the state's scroll position calculation (first item + first offset) if (beforeContentPadding > 0 || spaceBetweenItems < 0) { for (i in visibleItems.indices) { val size = visibleItems[i].sizeWithSpacings if (currentFirstItemScrollOffset != 0 && size <= currentFirstItemScrollOffset && i != visibleItems.lastIndex ) { currentFirstItemScrollOffset -= size firstItem = visibleItems[i + 1] } else { break } } } // Compose extra items before val extraItemsBefore = createItemsBeforeList( beyondBoundsInfo = beyondBoundsInfo, currentFirstItemIndex = currentFirstItemIndex, itemProvider = itemProvider, itemsCount = itemsCount, beyondBoundsItemCount = beyondBoundsItemCount ) // Update maxCrossAxis with extra items extraItemsBefore.fastForEach { maxCrossAxis = maxOf(maxCrossAxis, it.crossAxisSize) } // Compose items after last item val extraItemsAfter = createItemsAfterList( beyondBoundsInfo = beyondBoundsInfo, visibleItems = visibleItems, itemProvider = itemProvider, itemsCount = itemsCount, beyondBoundsItemCount = beyondBoundsItemCount ) // Update maxCrossAxis with extra items extraItemsAfter.fastForEach { maxCrossAxis = maxOf(maxCrossAxis, it.crossAxisSize) } val noExtraItems = firstItem == visibleItems.first() && extraItemsBefore.isEmpty() && extraItemsAfter.isEmpty() val layoutWidth = constraints.constrainWidth(if (isVertical) maxCrossAxis else currentMainAxisOffset) val layoutHeight = constraints.constrainHeight(if (isVertical) currentMainAxisOffset else maxCrossAxis) val positionedItems = calculateItemsOffsets( items = visibleItems, extraItemsBefore = extraItemsBefore, extraItemsAfter = extraItemsAfter, layoutWidth = layoutWidth, layoutHeight = layoutHeight, finalMainAxisOffset = currentMainAxisOffset, maxOffset = maxOffset, itemsScrollOffset = visibleItemsScrollOffset, isVertical = isVertical, verticalArrangement = verticalArrangement, horizontalArrangement = horizontalArrangement, reverseLayout = reverseLayout, density = density, ) placementAnimator.onMeasured( consumedScroll = consumedScroll.toInt(), layoutWidth = layoutWidth, layoutHeight = layoutHeight, reverseLayout = reverseLayout, positionedItems = positionedItems, itemProvider = itemProvider ) val headerItem = if (headerIndexes.isNotEmpty()) { findOrComposeLazyListHeader( composedVisibleItems = positionedItems, itemProvider = itemProvider, headerIndexes = headerIndexes, beforeContentPadding = beforeContentPadding, layoutWidth = layoutWidth, layoutHeight = layoutHeight ) } else { null } return LazyListMeasureResult( firstVisibleItem = firstItem, firstVisibleItemScrollOffset = currentFirstItemScrollOffset, canScrollForward = index.value < itemsCount || currentMainAxisOffset > maxOffset, consumedScroll = consumedScroll, measureResult = layout(layoutWidth, layoutHeight) { positionedItems.fastForEach { if (it !== headerItem) { it.place(this) } } // the header item should be placed (drawn) after all other items headerItem?.place(this) }, viewportStartOffset = -beforeContentPadding, viewportEndOffset = maxOffset + afterContentPadding, visibleItemsInfo = if (noExtraItems) positionedItems else positionedItems.fastFilter { (it.index >= visibleItems.first().index && it.index <= visibleItems.last().index) || it === headerItem }, totalItemsCount = itemsCount, reverseLayout = reverseLayout, orientation = if (isVertical) Orientation.Vertical else Orientation.Horizontal, afterContentPadding = afterContentPadding ) } } private fun createItemsAfterList( beyondBoundsInfo: LazyListBeyondBoundsInfo, visibleItems: MutableList<LazyMeasuredItem>, itemProvider: LazyMeasuredItemProvider, itemsCount: Int, beyondBoundsItemCount: Int ): List<LazyMeasuredItem> { fun LazyListBeyondBoundsInfo.endIndex() = min(end, itemsCount - 1) fun addItemsAfter(startIndex: Int, endIndex: Int): List<LazyMeasuredItem> { return mutableListOf<LazyMeasuredItem>().apply { for (i in startIndex until endIndex) { val item = itemProvider.getAndMeasure(DataIndex(i + 1)) add(item) } } } val (startNonVisibleItems, endNonVisibleItems) = if (beyondBoundsItemCount != 0 && visibleItems.last().index + beyondBoundsItemCount <= itemsCount - 1 ) { visibleItems.last().index to visibleItems.last().index + beyondBoundsItemCount } else { EmptyRange } val (startBeyondBoundItems, endBeyondBoundItems) = if (beyondBoundsInfo.hasIntervals() && visibleItems.last().index < beyondBoundsInfo.endIndex() ) { val start = (visibleItems.last().index + beyondBoundsItemCount).coerceAtMost(itemsCount - 1) val end = (beyondBoundsInfo.endIndex() + beyondBoundsItemCount).coerceAtMost(itemsCount - 1) start to end } else { EmptyRange } return if (startNonVisibleItems.notInEmptyRange && startBeyondBoundItems.notInEmptyRange) { addItemsAfter( startNonVisibleItems, endBeyondBoundItems ) } else if (startNonVisibleItems.notInEmptyRange) { addItemsAfter(startNonVisibleItems, endNonVisibleItems) } else if (startBeyondBoundItems.notInEmptyRange) { addItemsAfter(startBeyondBoundItems, endBeyondBoundItems) } else { emptyList() } } private fun createItemsBeforeList( beyondBoundsInfo: LazyListBeyondBoundsInfo, currentFirstItemIndex: DataIndex, itemProvider: LazyMeasuredItemProvider, itemsCount: Int, beyondBoundsItemCount: Int ): List<LazyMeasuredItem> { fun LazyListBeyondBoundsInfo.startIndex() = min(start, itemsCount - 1) fun addItemsBefore(startIndex: Int, endIndex: Int): List<LazyMeasuredItem> { return mutableListOf<LazyMeasuredItem>().apply { for (i in startIndex downTo endIndex) { val item = itemProvider.getAndMeasure(DataIndex(i)) add(item) } } } val (startNonVisibleItems, endNonVisibleItems) = if (beyondBoundsItemCount != 0 && currentFirstItemIndex.value - beyondBoundsItemCount > 0) { currentFirstItemIndex.value - 1 to currentFirstItemIndex.value - beyondBoundsItemCount } else { EmptyRange } val (startBeyondBoundItems, endBeyondBoundItems) = if (beyondBoundsInfo.hasIntervals() && currentFirstItemIndex.value > beyondBoundsInfo.startIndex() ) { val start = (currentFirstItemIndex.value - beyondBoundsItemCount - 1).coerceAtLeast(0) val end = (beyondBoundsInfo.startIndex() - beyondBoundsItemCount).coerceAtLeast(0) start to end } else { EmptyRange } return if (startNonVisibleItems.notInEmptyRange && startBeyondBoundItems.notInEmptyRange) { addItemsBefore( startNonVisibleItems, endBeyondBoundItems ) } else if (startNonVisibleItems.notInEmptyRange) { addItemsBefore(startNonVisibleItems, endNonVisibleItems) } else if (startBeyondBoundItems.notInEmptyRange) { addItemsBefore(startBeyondBoundItems, endBeyondBoundItems) } else { emptyList() } } /** * Calculates [LazyMeasuredItem]s offsets. */ private fun calculateItemsOffsets( items: List<LazyMeasuredItem>, extraItemsBefore: List<LazyMeasuredItem>, extraItemsAfter: List<LazyMeasuredItem>, layoutWidth: Int, layoutHeight: Int, finalMainAxisOffset: Int, maxOffset: Int, itemsScrollOffset: Int, isVertical: Boolean, verticalArrangement: Arrangement.Vertical?, horizontalArrangement: Arrangement.Horizontal?, reverseLayout: Boolean, density: Density, ): MutableList<LazyListPositionedItem> { val mainAxisLayoutSize = if (isVertical) layoutHeight else layoutWidth val hasSpareSpace = finalMainAxisOffset < minOf(mainAxisLayoutSize, maxOffset) if (hasSpareSpace) { check(itemsScrollOffset == 0) } val positionedItems = ArrayList<LazyListPositionedItem>(items.size + extraItemsBefore.size + extraItemsAfter.size) if (hasSpareSpace) { require(extraItemsBefore.isEmpty() && extraItemsAfter.isEmpty()) val itemsCount = items.size fun Int.reverseAware() = if (!reverseLayout) this else itemsCount - this - 1 val sizes = IntArray(itemsCount) { index -> items[index.reverseAware()].size } val offsets = IntArray(itemsCount) { 0 } if (isVertical) { with(requireNotNull(verticalArrangement)) { density.arrange(mainAxisLayoutSize, sizes, offsets) } } else { with(requireNotNull(horizontalArrangement)) { // Enforces Ltr layout direction as it is mirrored with placeRelative later. density.arrange(mainAxisLayoutSize, sizes, LayoutDirection.Ltr, offsets) } } val reverseAwareOffsetIndices = if (!reverseLayout) offsets.indices else offsets.indices.reversed() for (index in reverseAwareOffsetIndices) { val absoluteOffset = offsets[index] // when reverseLayout == true, offsets are stored in the reversed order to items val item = items[index.reverseAware()] val relativeOffset = if (reverseLayout) { // inverse offset to align with scroll direction for positioning mainAxisLayoutSize - absoluteOffset - item.size } else { absoluteOffset } positionedItems.add(item.position(relativeOffset, layoutWidth, layoutHeight)) } } else { var currentMainAxis = itemsScrollOffset extraItemsBefore.fastForEach { currentMainAxis -= it.sizeWithSpacings positionedItems.add(it.position(currentMainAxis, layoutWidth, layoutHeight)) } currentMainAxis = itemsScrollOffset items.fastForEach { positionedItems.add(it.position(currentMainAxis, layoutWidth, layoutHeight)) currentMainAxis += it.sizeWithSpacings } extraItemsAfter.fastForEach { positionedItems.add(it.position(currentMainAxis, layoutWidth, layoutHeight)) currentMainAxis += it.sizeWithSpacings } } return positionedItems } /** * Returns a list containing only elements matching the given [predicate]. * * **Do not use for collections that come from public APIs**, since they may not support random * access in an efficient way, and this method may actually be a lot slower. Only use for * collections that are created by code we control and are known to support random access. */ @OptIn(ExperimentalContracts::class) internal fun <T> List<T>.fastFilter(predicate: (T) -> Boolean): List<T> { contract { callsInPlace(predicate) } val target = ArrayList<T>(size) fastForEach { if (predicate(it)) target += (it) } return target } private val EmptyRange = Int.MIN_VALUE to Int.MIN_VALUE private val Int.notInEmptyRange get() = this != Int.MIN_VALUE
apache-2.0
a66b0e25b63e99cbd19141f312b2c1ce
40.209259
100
0.662428
6.053591
false
false
false
false
siosio/intellij-community
plugins/kotlin/completion/src/org/jetbrains/kotlin/idea/completion/handlers/WithTailInsertHandler.kt
1
4236
// 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.completion.handlers import com.intellij.codeInsight.AutoPopupController import com.intellij.codeInsight.completion.InsertHandler import com.intellij.codeInsight.completion.InsertionContext import com.intellij.codeInsight.lookup.Lookup import com.intellij.codeInsight.lookup.LookupElement import com.intellij.openapi.editor.Document import com.intellij.psi.PsiDocumentManager import org.jetbrains.kotlin.idea.completion.KEEP_OLD_ARGUMENT_LIST_ON_TAB_KEY import org.jetbrains.kotlin.idea.completion.smart.SmartCompletion import org.jetbrains.kotlin.idea.completion.tryGetOffset class WithTailInsertHandler( val tailText: String, val spaceBefore: Boolean, val spaceAfter: Boolean, val overwriteText: Boolean = true ) : InsertHandler<LookupElement> { override fun handleInsert(context: InsertionContext, item: LookupElement) { item.handleInsert(context) postHandleInsert(context, item) } fun postHandleInsert(context: InsertionContext, item: LookupElement) { val completionChar = context.completionChar if (completionChar == tailText.singleOrNull() || (spaceAfter && completionChar == ' ')) { context.setAddCompletionChar(false) } //TODO: what if completion char is different? val document = context.document PsiDocumentManager.getInstance(context.project).doPostponedOperationsAndUnblockDocument(document) var tailOffset = context.tailOffset if (completionChar == Lookup.REPLACE_SELECT_CHAR && item.getUserData(KEEP_OLD_ARGUMENT_LIST_ON_TAB_KEY) != null) { context.offsetMap.tryGetOffset(SmartCompletion.OLD_ARGUMENTS_REPLACEMENT_OFFSET) ?.let { tailOffset = it } } val moveCaret = context.editor.caretModel.offset == tailOffset //TODO: analyze parenthesis balance to decide whether to replace or not var insert = true if (overwriteText) { var offset = tailOffset if (tailText != " ") { offset = document.charsSequence.skipSpacesAndLineBreaks(offset) } if (shouldOverwriteChar(document, offset)) { insert = false offset += tailText.length tailOffset = offset if (spaceAfter && document.charsSequence.isCharAt(offset, ' ')) { document.deleteString(offset, offset + 1) } } } var textToInsert = "" if (insert) { textToInsert = tailText if (spaceBefore) textToInsert = " " + textToInsert } if (spaceAfter) textToInsert += " " document.insertString(tailOffset, textToInsert) if (moveCaret) { context.editor.caretModel.moveToOffset(tailOffset + textToInsert.length) if (tailText == ",") { AutoPopupController.getInstance(context.project)?.autoPopupParameterInfo(context.editor, null) } } } private fun shouldOverwriteChar(document: Document, offset: Int): Boolean { if (!document.isTextAt(offset, tailText)) return false if (tailText == " " && document.charsSequence.isCharAt(offset + 1, '}')) return false // do not overwrite last space before '}' return true } companion object { val COMMA = WithTailInsertHandler(",", spaceBefore = false, spaceAfter = true /*TODO: use code style option*/) val RPARENTH = WithTailInsertHandler(")", spaceBefore = false, spaceAfter = false) val RBRACKET = WithTailInsertHandler("]", spaceBefore = false, spaceAfter = false) val RBRACE = WithTailInsertHandler("}", spaceBefore = true, spaceAfter = false) val ELSE = WithTailInsertHandler("else", spaceBefore = true, spaceAfter = true) val EQ = WithTailInsertHandler("=", spaceBefore = true, spaceAfter = true) /*TODO: use code style options*/ val SPACE = WithTailInsertHandler(" ", spaceBefore = false, spaceAfter = false, overwriteText = true) } }
apache-2.0
f39ad0034422a9446d51ce06e32ff893
43.125
158
0.671624
4.863375
false
false
false
false
JetBrains/xodus
query/src/main/kotlin/jetbrains/exodus/query/IterableDecorator.kt
1
2620
/** * Copyright 2010 - 2022 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 * * 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 jetbrains.exodus.query import jetbrains.exodus.entitystore.Entity import jetbrains.exodus.entitystore.iterate.EntityIterableBase import jetbrains.exodus.query.metadata.ModelMetaData class IterableDecorator(iterable: Iterable<Entity>) : NodeBase() { private val it = StaticTypedEntityIterable.instantiate(iterable) override fun instantiate( entityType: String, queryEngine: QueryEngine, metaData: ModelMetaData, context: InstantiateContext ): Iterable<Entity> { metaData.getEntityMetaData(entityType)?.let { emd -> if (!emd.hasSubTypes() && emd.superType == null) { return it } } val entityStore = queryEngine.persistentStore val txn = entityStore.andCheckCurrentTransaction if (it is EntityIterableBase) { return queryEngine.wrap(it.source.intersect(queryEngine.instantiateGetAll(txn, entityType))) } val typeId = entityStore.getEntityTypeId(txn, entityType, false) if (it is List<*>) { return it.filter { entity -> entity.id.typeId == typeId } } return it.asSequence().filter { entity -> entity.id.typeId == typeId }.asIterable() } override fun getClone() = IterableDecorator(it) override fun equals(other: Any?): Boolean { if (this === other) return true other?.let { r -> return r is IterableDecorator && (it === r.it || (it is EntityIterableBase && r.it is EntityIterableBase && it.source.handle == r.it.source.handle)) } return false } override fun getHandle(sb: StringBuilder): StringBuilder { super.getHandle(sb).append('(') if (it is EntityIterableBase) { sb.append(it.source.handle.toString()) } else { sb.append(it.hashCode() and 0x7fffffff) } return sb.append(')') } override fun getSimpleName() = "id" override fun canBeCached() = false }
apache-2.0
ea7000a20cedcb9ecd128ced1d9eef49
34.90411
135
0.65458
4.501718
false
false
false
false
ErikKarlsson/SmashApp-Android
app/src/main/java/net/erikkarlsson/smashapp/base/data/Lce.kt
1
843
package net.erikkarlsson.smashapp.base.data data class Lce<T>(val data: T?, val error: Throwable?, val isIdle: Boolean) { companion object { @JvmStatic fun <T> idle(): Lce<T> { return Lce<T>(null, null, true); } @JvmStatic fun <T> loading(): Lce<T> { return Lce<T>(null, null, false); } @JvmStatic fun <T> data(data: T): Lce<T> { return Lce<T>(data, null, false); } @JvmStatic fun <T> error(error: Throwable): Lce<T> { return Lce<T>(null, error, false); } } fun isLoading(): Boolean { return !isIdle && data == null && error == null } fun hasError(): Boolean { return error != null } fun hasData(): Boolean { return data != null } }
apache-2.0
70f8324251e124d690d19afc4b29bd08
23.114286
60
0.495848
3.995261
false
false
false
false
jwren/intellij-community
plugins/package-search/src/com/jetbrains/packagesearch/intellij/plugin/ui/services/DependencyNavigationService.kt
1
4317
package com.jetbrains.packagesearch.intellij.plugin.ui.services import com.intellij.buildsystem.model.unified.UnifiedCoordinates import com.intellij.buildsystem.model.unified.UnifiedDependency import com.intellij.openapi.application.EDT import com.intellij.openapi.components.service import com.intellij.openapi.module.Module import com.intellij.openapi.project.Project import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.PackageSearchToolWindowFactory import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.ModuleModel import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.TargetModules import com.jetbrains.packagesearch.intellij.plugin.util.lifecycleScope import com.jetbrains.packagesearch.intellij.plugin.util.packageSearchProjectService import com.jetbrains.packagesearch.intellij.plugin.util.uiStateModifier import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch class DependencyNavigationService(private val project: Project) { /** * Open the Dependency toolwindows at the selected [module] if found and searches for the first * coordinates that matches the ones of [coordinates]. * @param module The native [Module] into which look for the dependency. * @param coordinates The [UnifiedCoordinates] to search, the first result will be used. */ fun navigateToDependency(module: Module, coordinates: UnifiedCoordinates): NavigationResult { val entry = project.packageSearchProjectService.dependenciesByModuleStateFlow.value .entries.find { (k, _) -> k.nativeModule == module } return when { entry != null -> { val (projectModule, installedDependencies) = entry val isFound = installedDependencies.find { it.coordinates == coordinates } val moduleModel = project.packageSearchProjectService.moduleModelsStateFlow.value .find { it.projectModule == projectModule } when { isFound != null && moduleModel != null -> onSuccess(moduleModel, isFound) else -> NavigationResult.CoordinatesNotFound(module, coordinates) } } else -> NavigationResult.ModuleNotSupported(module) } } /** * Open the Dependency toolwindows at the selected [module] if found and searches for the exact * dependency that matches the ones of [dependency]. * @param module The native [Module] into which look for the dependency. * @param dependency The [UnifiedDependency] to search. */ fun navigateToDependency(module: Module, dependency: UnifiedDependency): NavigationResult { val entry = project.packageSearchProjectService.dependenciesByModuleStateFlow.value .entries.find { (k, _) -> k.nativeModule == module } return when { entry != null -> { val (projectModule, installedDependencies) = entry val moduleModel = project.packageSearchProjectService.moduleModelsStateFlow.value .find { it.projectModule == projectModule } when { dependency in installedDependencies && moduleModel != null -> onSuccess(moduleModel, dependency) else -> NavigationResult.DependencyNotFound(module, dependency) } } else -> NavigationResult.ModuleNotSupported(module) } } private fun onSuccess(moduleModel: ModuleModel, dependency: UnifiedDependency): NavigationResult.Success { project.lifecycleScope.launch(Dispatchers.EDT) { PackageSearchToolWindowFactory.activateToolWindow(project) { project.uiStateModifier.setTargetModules(TargetModules.from(moduleModel)) project.uiStateModifier.setDependency(dependency) } } return NavigationResult.Success } } sealed class NavigationResult { object Success : NavigationResult() data class ModuleNotSupported(val module: Module) : NavigationResult() data class DependencyNotFound(val module: Module, val dependency: UnifiedDependency) : NavigationResult() data class CoordinatesNotFound(val module: Module, val coordinates: UnifiedCoordinates) : NavigationResult() }
apache-2.0
89f7966a363988566fafe16e6e53b135
50.392857
116
0.709057
5.450758
false
false
false
false
GunoH/intellij-community
plugins/kotlin/idea/tests/testData/multiplatform/kt48291/jvm/I_JVM.kt
8
710
package sample actual interface <!LINE_MARKER("descr='Has expects in common module'"), LINE_MARKER("descr='Is implemented by CommonMainImpl [jvm] Click or press ... to navigate'")!>CommonMainInterface<!> { actual val <!LINE_MARKER("descr='Has expects in common module'"), LINE_MARKER("descr='Is implemented in sample.CommonMainImpl'")!>propertyFromInterface<!>: Int } actual class <!LINE_MARKER("descr='Has expects in common module'")!>CommonMainImpl<!> : CommonMainInterface { override val <!LINE_MARKER("descr='Implements property in 'CommonMainInterface''")!>propertyFromInterface<!>: Int = 42 actual val <!LINE_MARKER("descr='Has expects in common module'")!>propertyFromImpl<!>: Int = 42 }
apache-2.0
0f1957d98ff7269112d0cd903d1511ba
70
191
0.732394
4.382716
false
false
false
false
smmribeiro/intellij-community
platform/lang-impl/src/com/intellij/openapi/editor/actions/lists/ListSplitJoinContext.kt
9
2924
// 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.openapi.editor.actions.lists import com.intellij.codeInspection.util.IntentionName import com.intellij.lang.LanguageExtension import com.intellij.openapi.util.TextRange import com.intellij.psi.PsiElement import com.intellij.psi.PsiFile import org.jetbrains.annotations.ApiStatus /** * Describe the structure of split / join operations for list elements. * <code> * test(p1, p2, p3) * </code> * and * <code> * test(p1, * p2, * p3) * </code> * The actions provide operations to convert form (1) to (2) and back * * @see DefaultListSplitJoinContext default implementation */ @ApiStatus.Experimental interface ListSplitJoinContext { companion object { val EXTENSION = LanguageExtension<ListSplitJoinContext>("com.intellij.listSplitJoinContext") } /** * Checks if the split operation is available in the context */ fun isSplitAvailable(data: ListWithElements): Boolean /** * Checks if the join operation is available in the context */ fun isJoinAvailable(data: ListWithElements): Boolean /** * Extracts list and elements for the operations. Null means that the operation isn't available */ fun extractData(context: PsiElement): ListWithElements? /** * Text for the split operation, to show in the editor */ @IntentionName fun getSplitText(data: ListWithElements): String /** * Text for the join operation, to show in the editor */ @IntentionName fun getJoinText(data: ListWithElements): String /** * Reformat the range after processing. It is delegated to context, because based on the psi structure it can be optional */ fun reformatRange(file: PsiFile, rangeToAdjust: TextRange, split: JoinOrSplit) /** * Collects the ordered list (asc) of replacements to update document for the splitting */ fun getReplacementsForSplitting(data: ListWithElements): List<Pair<TextRange, String>> /** * Collects the ordered list (asc) of replacements to update document for the joining */ fun getReplacementsForJoining(data: ListWithElements): List<Pair<TextRange, String>> } class ListWithElements(val list: PsiElement, val elements: List<PsiElement>) enum class JoinOrSplit { JOIN, SPLIT } fun getListSplitJoinContext(element: PsiElement, joinOrSplit: JoinOrSplit): Pair<ListSplitJoinContext, ListWithElements>? { val language = element.language val extensions = ListSplitJoinContext.EXTENSION.allForLanguage(language) for (extension in extensions) { val data = extension.extractData(element) ?: continue if (joinOrSplit == JoinOrSplit.SPLIT && extension.isSplitAvailable(data) || joinOrSplit == JoinOrSplit.JOIN && extension.isJoinAvailable(data)) { return extension to data } } return null }
apache-2.0
09d9eedebebfd23c89b25e31c46d250c
31.5
158
0.740082
4.183119
false
false
false
false
ianhanniballake/muzei
muzei-api/src/main/java/com/google/android/apps/muzei/api/provider/MuzeiArtDocumentsProvider.kt
2
21111
/* * Copyright 2020 Google 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.google.android.apps.muzei.api.provider import android.annotation.SuppressLint import android.content.ContentUris import android.content.Context import android.content.pm.PackageManager import android.content.pm.ProviderInfo import android.content.res.AssetFileDescriptor import android.database.Cursor import android.database.MatrixCursor import android.graphics.Bitmap import android.graphics.BitmapFactory import android.graphics.Matrix import android.graphics.Point import android.net.Uri import android.os.Binder import android.os.Build import android.os.CancellationSignal import android.os.ParcelFileDescriptor import android.provider.DocumentsContract import android.provider.DocumentsProvider import android.util.Log import androidx.annotation.RequiresApi import androidx.exifinterface.media.ExifInterface import java.io.File import java.io.FileNotFoundException import java.io.FileOutputStream import java.io.IOException import kotlin.math.max /** * An implementation of [DocumentsProvider] that provides users direct access to the * images of one or more [MuzeiArtProvider] instances. * * ### Linking a [MuzeiArtProvider] to [MuzeiArtDocumentsProvider] * * Each [MuzeiArtProvider] has an authority associated with it, which uniquely * defines it across all apps. This means it should generally be namespaced similar to * your application ID - i.e., `com.example.artprovider`. * * A [MuzeiArtDocumentsProvider] uses the `android:authorities` assigned to it as the mechanism * for linking it to a single [MuzeiArtProvider] instances from your app - the * authority used **must** be that of a valid [MuzeiArtProvider] plus the suffix * `.documents`. For example, if your [MuzeiArtProvider] had the authority of * `com.example.artprovider`, you would use an authority of `com.example.artprovider.documents`: * * ``` * <provider android:name="com.google.android.apps.muzei.api.provider.MuzeiArtDocumentsProvider" * android:authorities="com.example.artprovider.documents" * android:exported="true" * android:grantUriPermissions="true" * android:permission="android.permission.MANAGE_DOCUMENTS"> * <intent-filter> * <action android:name="android.content.action.DOCUMENTS_PROVIDER" /> * </intent-filter> * </provider> * ``` * * The [MuzeiArtDocumentsProvider] will automatically make the artwork from the * [MuzeiArtProvider] available via the system file picker and Files app. * * ### Subclassing [MuzeiArtDocumentsProvider] * * Android enforces that a single `android:name` can only be present at most once in the manifest. * While in most cases this is not an issue, it does mean that only a single * [MuzeiArtDocumentsProvider] class can be added to the final merged application manifest. * * Therefore in cases where you do not control the final application manifest (e.g., when * providing a [MuzeiArtProvider] and [MuzeiArtDocumentsProvider] pair as part of a library), * it is strongly recommended to subclass [MuzeiArtDocumentsProvider], ensuring that the * `android:name` in the manifest is unique. * * ``` * class MyArtDocumentsProvider : MuzeiArtDocumentsProvider() * ``` * * It is not necessary to override any methods in [MuzeiArtDocumentsProvider]. * * ### Supporting multiple [MuzeiArtProvider] instances in your app * * Each [MuzeiArtDocumentsProvider] is associated with a single [MuzeiArtProvider] via the * `android:authorities` attribute. To support multiple [MuzeiArtProvider] instances in your * app, you must subclass [MuzeiArtDocumentsProvider] (as described above) and add each * separate instance to your manifest, each with the appropriate authority. * * @constructor Constructs a `MuzeiArtDocumentsProvider`. */ @RequiresApi(Build.VERSION_CODES.KITKAT) public open class MuzeiArtDocumentsProvider : DocumentsProvider() { public companion object { private const val TAG = "MuzeiArtDocProvider" /** * Default root projection */ private val DEFAULT_ROOT_PROJECTION = arrayOf( DocumentsContract.Root.COLUMN_ROOT_ID, DocumentsContract.Root.COLUMN_ICON, DocumentsContract.Root.COLUMN_TITLE, DocumentsContract.Root.COLUMN_SUMMARY, DocumentsContract.Root.COLUMN_FLAGS, DocumentsContract.Root.COLUMN_MIME_TYPES, DocumentsContract.Root.COLUMN_DOCUMENT_ID) /** * Default document projection */ private val DEFAULT_DOCUMENT_PROJECTION = arrayOf( DocumentsContract.Document.COLUMN_DOCUMENT_ID, DocumentsContract.Document.COLUMN_DISPLAY_NAME, DocumentsContract.Document.COLUMN_SUMMARY, DocumentsContract.Document.COLUMN_MIME_TYPE, DocumentsContract.Document.COLUMN_FLAGS, DocumentsContract.Document.COLUMN_SIZE, DocumentsContract.Document.COLUMN_LAST_MODIFIED) } private lateinit var providerInfos: Map<String, ProviderInfo> /** * @suppress */ final override fun onCreate(): Boolean = true /** * @suppress */ @Suppress("DEPRECATION") final override fun attachInfo(context: Context, info: ProviderInfo) { super.attachInfo(context, info) val authorities = info.authority.split(";") if (authorities.size > 1) { Log.w(TAG, "There are known issues with OEMs not supporting multiple " + "authorities in a single DocumentsProvider. It is recommended to subclass " + "MuzeiArtDocumentsProvider and use a single authority for each. " + "Received $authorities") } providerInfos = authorities.asSequence().filter { authority -> val authorityEndsWithDocuments = authority.endsWith(".documents") if (!authorityEndsWithDocuments) { Log.e(TAG, "Authority $authority must end in \".documents\"") } authorityEndsWithDocuments }.map { authority -> authority.substringBeforeLast(".documents") }.mapNotNull { authority -> val pm = context.packageManager pm.resolveContentProvider(authority, PackageManager.GET_DISABLED_COMPONENTS).also { providerInfo -> if (providerInfo == null) { Log.e(TAG, "Could not find MuzeiArtProvider " + "associated with authority $authority") } } }.filter { providerInfo -> if (!providerInfo.enabled) { if (Log.isLoggable(TAG, Log.INFO)) { Log.i(TAG, "Ignoring ${providerInfo.authority} as it is disabled") } } providerInfo.enabled }.map { providerInfo -> providerInfo.authority to providerInfo }.toList().toMap() } /** * @suppress */ @SuppressLint("InlinedApi") @Throws(FileNotFoundException::class) final override fun queryRoots(projection: Array<String>?): Cursor { val result = MatrixCursor(projection ?: DEFAULT_ROOT_PROJECTION) val context = context ?: return result val pm = context.packageManager providerInfos.forEach { (authority, providerInfo) -> val title = providerInfo.loadLabel(pm).toString() val appName = providerInfo.applicationInfo.loadLabel(pm).toString() val providerIcon = providerInfo.icon val appIcon = providerInfo.applicationInfo.icon result.newRow().apply { add(DocumentsContract.Root.COLUMN_ROOT_ID, authority) add(DocumentsContract.Root.COLUMN_ICON, if (providerIcon != 0) providerIcon else appIcon) if (title.isNotBlank()) { add(DocumentsContract.Root.COLUMN_TITLE, title) if (title != appName) { add(DocumentsContract.Root.COLUMN_SUMMARY, appName) } } else { add(DocumentsContract.Root.COLUMN_TITLE, appName) } add(DocumentsContract.Root.COLUMN_FLAGS, DocumentsContract.Root.FLAG_SUPPORTS_IS_CHILD or DocumentsContract.Root.FLAG_SUPPORTS_RECENTS) add(DocumentsContract.Root.COLUMN_MIME_TYPES, "image/png") add(DocumentsContract.Root.COLUMN_DOCUMENT_ID, authority) } } return result } /** * @suppress */ final override fun queryRecentDocuments( authority: String, projection: Array<String>? ): Cursor { val result = MatrixCursor(projection ?: DEFAULT_DOCUMENT_PROJECTION) val context = context ?: return result val contentUri = ProviderContract.getContentUri(authority) val token = Binder.clearCallingIdentity() try { context.contentResolver.query(contentUri, null, null, null, "${ProviderContract.Artwork.DATE_MODIFIED} DESC", null )?.use { data -> while (data.moveToNext() && result.count < 64) { result.addArtwork(authority, Artwork.fromCursor(data)) } } } finally { Binder.restoreCallingIdentity(token) } result.setNotificationUri(context.contentResolver, DocumentsContract.buildRecentDocumentsUri(authority, authority)) return result } /** * @suppress */ @Throws(FileNotFoundException::class) final override fun queryChildDocuments( authority: String, projection: Array<String>?, sortOrder: String? ): Cursor { val result = MatrixCursor(projection ?: DEFAULT_DOCUMENT_PROJECTION) val context = context ?: return result val contentUri = ProviderContract.getContentUri(authority) val token = Binder.clearCallingIdentity() try { context.contentResolver.query(contentUri, null, null, null, null, null )?.use { data -> while (data.moveToNext()) { result.addArtwork(authority, Artwork.fromCursor(data)) } } } finally { Binder.restoreCallingIdentity(token) } result.setNotificationUri(context.contentResolver, DocumentsContract.buildChildDocumentsUri(authority, authority)) return result } /** * @suppress */ @Throws(FileNotFoundException::class) final override fun queryDocument(documentId: String, projection: Array<String>?): Cursor { val result = MatrixCursor(projection ?: DEFAULT_DOCUMENT_PROJECTION) val context = context ?: return result if (documentId.contains("/")) { val (authority, id) = documentId.split("/") val contentUri = ProviderContract.getContentUri(authority) val uri = ContentUris.withAppendedId(contentUri, id.toLong()) val token = Binder.clearCallingIdentity() try { context.contentResolver.query(uri, null, null, null, null )?.use { data -> if (data.moveToFirst()) { result.addArtwork(authority, Artwork.fromCursor(data)) } } } finally { Binder.restoreCallingIdentity(token) } result.setNotificationUri(context.contentResolver, DocumentsContract.buildDocumentUri(authority, documentId)) } else { // This is the root item for the MuzeiArtProvider val providerInfo = providerInfos[documentId] ?: return result val pm = context.packageManager result.newRow().apply { add(DocumentsContract.Document.COLUMN_DOCUMENT_ID, documentId) add(DocumentsContract.Document.COLUMN_DISPLAY_NAME, providerInfo.loadLabel(pm)) add(DocumentsContract.Document.COLUMN_MIME_TYPE, DocumentsContract.Document.MIME_TYPE_DIR) add(DocumentsContract.Document.COLUMN_FLAGS, DocumentsContract.Document.FLAG_DIR_PREFERS_GRID or DocumentsContract.Document.FLAG_DIR_PREFERS_LAST_MODIFIED) add(DocumentsContract.Document.COLUMN_SIZE, null) } result.setNotificationUri(context.contentResolver, DocumentsContract.buildDocumentUri(documentId, documentId)) } return result } private fun MatrixCursor.addArtwork(authority: String, artwork: Artwork) { newRow().apply { add(DocumentsContract.Document.COLUMN_DOCUMENT_ID, "$authority/${artwork.id}") add(DocumentsContract.Document.COLUMN_DISPLAY_NAME, artwork.title) add(DocumentsContract.Document.COLUMN_SUMMARY, artwork.byline) add(DocumentsContract.Document.COLUMN_MIME_TYPE, "image/png") add(DocumentsContract.Document.COLUMN_FLAGS, DocumentsContract.Document.FLAG_SUPPORTS_THUMBNAIL) add(DocumentsContract.Document.COLUMN_SIZE, null) add(DocumentsContract.Document.COLUMN_LAST_MODIFIED, artwork.dateModified.time) } } /** * @suppress */ final override fun isChildDocument(parentDocumentId: String, documentId: String): Boolean { // The only parents are the authorities, the only children are authority/id return documentId.startsWith("$parentDocumentId/") } /** * @suppress */ @Throws(FileNotFoundException::class) final override fun getDocumentType( documentId: String ): String = if (documentId.contains("/")) { "image/png" } else DocumentsContract.Document.MIME_TYPE_DIR /** * @suppress */ @Throws(FileNotFoundException::class) final override fun openDocument( documentId: String, mode: String, signal: CancellationSignal? ): ParcelFileDescriptor? { val (authority, id) = documentId.split("/") val contentUri = ProviderContract.getContentUri(authority) val uri = ContentUris.withAppendedId(contentUri, id.toLong()) val token = Binder.clearCallingIdentity() return try { context?.contentResolver?.openFileDescriptor(uri, mode, signal) } finally { Binder.restoreCallingIdentity(token) } } /** * @suppress */ @Throws(FileNotFoundException::class) final override fun openDocumentThumbnail( documentId: String, sizeHint: Point, signal: CancellationSignal? ): AssetFileDescriptor? { val (authority, id) = documentId.split("/") val tempFile = getThumbnailFile(authority, id) if (tempFile.exists() && tempFile.length() != 0L) { // We already have a cached thumbnail return AssetFileDescriptor(ParcelFileDescriptor.open(tempFile, ParcelFileDescriptor.MODE_READ_ONLY), 0, AssetFileDescriptor.UNKNOWN_LENGTH) } // We need to generate a new thumbnail val contentUri = ProviderContract.getContentUri(authority) val uri = ContentUris.withAppendedId(contentUri, id.toLong()) val token = Binder.clearCallingIdentity() val bitmap = try { decodeUri(uri, sizeHint.x / 2, sizeHint.y / 2 ) ?: run { throw FileNotFoundException("Unable to generate thumbnail for $uri") } } finally { Binder.restoreCallingIdentity(token) } // Write out the thumbnail to a temporary file try { FileOutputStream(tempFile).use { out -> bitmap.compress(Bitmap.CompressFormat.PNG, 90, out) } } catch (e: IOException) { Log.e(TAG, "Error writing thumbnail", e) return null } return AssetFileDescriptor(ParcelFileDescriptor.open(tempFile, ParcelFileDescriptor.MODE_READ_ONLY), 0, AssetFileDescriptor.UNKNOWN_LENGTH) } @Throws(FileNotFoundException::class) private fun getThumbnailFile(authority: String, id: String): File { val context = context ?: throw FileNotFoundException("Unable to create cache directory") val authorityDirectory = File(context.cacheDir, "muzei_$authority") val thumbnailDirectory = File(authorityDirectory, "thumbnails") if (!thumbnailDirectory.exists() && !thumbnailDirectory.mkdirs()) { throw FileNotFoundException("Unable to create thumbnail directory") } return File(thumbnailDirectory, id) } private fun decodeUri(uri: Uri, targetWidth: Int, targetHeight: Int): Bitmap? { val context = context ?: return null val openInputStream = { context.contentResolver.openInputStream(uri) } return try { // First we need to get the original width and height of the image val (originalWidth, originalHeight) = openInputStream()?.use { input -> val options = BitmapFactory.Options().apply { inJustDecodeBounds = true } BitmapFactory.decodeStream(input, null, options) Pair(options.outWidth, options.outHeight) } ?: return null.also { Log.w(TAG, "Unable to get width and height for $uri") } // Then we need to get the rotation of the image val rotation = try { openInputStream()?.use { input -> val exifInterface = ExifInterface(input) when (exifInterface.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL)) { ExifInterface.ORIENTATION_ROTATE_90 -> 90 ExifInterface.ORIENTATION_ROTATE_180 -> 180 ExifInterface.ORIENTATION_ROTATE_270 -> 270 else -> 0 } } } catch (e: Exception) { Log.w(TAG, "Couldn't open EXIF interface for ${toString()}", e) } ?: 0 // Then we need to swap the width and height depending on the rotation val width = if (rotation == 90 || rotation == 270) originalHeight else originalWidth val height = if (rotation == 90 || rotation == 270) originalWidth else originalHeight // And now get the image, sampling it down to the appropriate size if needed openInputStream()?.use { input -> BitmapFactory.decodeStream(input, null, BitmapFactory.Options().apply { inPreferredConfig = Bitmap.Config.ARGB_8888 if (targetWidth != 0) { inSampleSize = max( width.sampleSize(targetWidth), height.sampleSize(targetHeight)) } }) }?.run { // Correctly rotate the final, downsampled image when (rotation) { 0 -> this else -> { val rotateMatrix = Matrix().apply { postRotate(rotation.toFloat()) } Bitmap.createBitmap( this, 0, 0, this.width, this.height, rotateMatrix, true).also { rotatedBitmap -> if (rotatedBitmap != this) { recycle() } } } } } } catch (e: Exception) { Log.w(TAG, "Unable to get thumbnail for $uri", e) null } } private fun Int.sampleSize(targetSize: Int): Int { var sampleSize = 1 while (this / (sampleSize shl 1) > targetSize) { sampleSize = sampleSize shl 1 } return sampleSize } }
apache-2.0
c682c518a8a898b500e4f0e88d8635b5
41.053785
171
0.612382
5.211306
false
false
false
false
dariopellegrini/Spike
app/src/main/java/com/dariopellegrini/spikeapp/UserApi.kt
1
2442
package com.dariopellegrini.spikeapp import com.dariopellegrini.spike.TargetType import com.dariopellegrini.spike.network.SpikeMethod /** * Created by dariopellegrini on 28/07/17. */ data class SignUp(val username: String, val password: String, val nickname: String, val profileImage: String): UserTarget() data class Login(val username: String, val password: String): UserTarget() sealed class UserTarget: TargetType { override val baseURL: String get() = "http://www.comixtime.it/api/web/api/" override val path: String get() { return when(this) { is SignUp -> "signUp" is Login -> "logins" } } override val headers: Map<String, String>? get() = mapOf( "Content-Type" to "application/json; charset=utf-8") override val method: SpikeMethod get() { return when(this) { is SignUp -> SpikeMethod.POST is Login -> SpikeMethod.POST } } override val parameters: Map<String, Any>? get() { return when(this) { is SignUp -> mapOf("username" to username, "password" to password, "nickname" to nickname, "profileImage" to profileImage) is Login -> mapOf("email" to username, "password" to password) } } /* override val successClosure: ((String, Map<String, String>?) -> Any?)? get() = { result, headers -> when(this) { is SignUp -> null is Login -> { var user = Gson().fromJson<User>(result) if (headers != null && headers["authToken"] != null) { user.token = headers["authToken"] as String } user } } } override val errorClose: ((String, Map<String, String>?) -> Any?)? get() = { errorResult, _ -> Gson().fromJson<BackendError>(errorResult) } override val sampleResult: String? get() { return when(this) { is Login -> "{" + "\"username\":\"[email protected]\"}" else -> null } } override val sampleHeaders: Map<String, String>? get() { return when(this) { is Login -> mapOf("token" to "aoisdusdaoidasum") else -> null } } */ }
mit
ecd84a0452b44f6ba5c9be2cf11d2049
29.148148
138
0.527846
4.29174
false
false
false
false
kvnxiao/meirei
meirei-core/src/main/kotlin/com/github/kvnxiao/discord/meirei/permission/PermissionDefaults.kt
1
2370
/* * Copyright (C) 2017-2018 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 com.github.kvnxiao.discord.meirei.permission object PermissionDefaults { /** * The setting for whether the command requires a bot mention to activate, defaults to false. */ const val REQUIRE_MENTION = false /** * The setting for whether the command can be activated through direct message to the bot, defaults to false. */ const val ALLOW_DIRECT_MSGING = false /** * The setting for whether the command must be activated through direct message with the bot, defaults to false. */ const val FORCE_DIRECT_MSGING = false /** * The setting for whether the command replies are forced as a direct message, defaults to false. */ const val FORCE_DIRECT_REPLY = false /** * The setting for whether the message used to activate the command should be removed post-activation, defaults to false. */ const val REMOVE_CALL_MSG = false /** * The time period for rate limiting a command in milliseconds, defaults to 1000 ms or 1 second. */ const val RATE_LIMIT_PERIOD_MS: Long = 1000 /** * The number of valid tokens or calls per rate limit period for a command, defaults to 3 calls per second. */ const val TOKENS_PER_PERIOD: Long = 3 /** * The setting for whether rate limiting is per guild or per user, defaults to false meaning per user. */ const val RATE_LIMIT_ON_GUILD = false /** * The setting for whether the command can only be issued by the guild owner, defaults to false. */ const val REQUIRE_GUILD_OWNER = false /** * The setting for whether the command can only be issued by the bot owner, defaults to false. */ const val REQUIRE_BOT_OWNER = false }
apache-2.0
2c495057d177f7eac52ea73930242d37
33.347826
125
0.681435
4.356618
false
false
false
false
google/intellij-gn-plugin
src/main/java/com/google/idea/gn/psi/impl/GnBinaryExprImpl.kt
1
1153
// Copyright (c) 2020 Google LLC All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package com.google.idea.gn.psi.impl import com.google.idea.gn.psi.* import com.google.idea.gn.psi.scope.Scope import com.intellij.extapi.psi.ASTWrapperPsiElement import com.intellij.lang.ASTNode abstract class GnBinaryExprImpl(node: ASTNode) : ASTWrapperPsiElement(node), GnBinaryExpr { override fun evaluate(scope: Scope): GnValue? { val list = exprList val left = GnPsiUtil.evaluate(list[0], scope) ?: return null val right = GnPsiUtil.evaluate(list[1], scope) ?: return null return when (this) { is GnGtExpr -> left.greaterThan(right) is GnGeExpr -> left.greaterThanOrEqual(right) is GnLtExpr -> left.lessThan(right) is GnLeExpr -> left.lessThanOrEqual(right) is GnAndExpr -> left.and(right) is GnOrExpr -> left.or(right) is GnEqualExpr -> GnValue(left == right) is GnNotEqualExpr -> GnValue(left != right) is GnPlusExpr -> left.plus(right) is GnMinusExpr -> left.minus(right) else -> null } } }
bsd-3-clause
8c8abf9d78ff248bcff762b7082a8262
32.911765
91
0.694709
3.660317
false
false
false
false
dtretyakov/teamcity-rust
plugin-rust-agent/src/main/kotlin/jetbrains/buildServer/rust/logging/CargoCompileLogger.kt
1
1718
/* * Copyright 2000-2021 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"). * See LICENSE in the project root for license information. */ package jetbrains.buildServer.rust.logging import jetbrains.buildServer.agent.BuildProgressLogger import java.util.regex.Pattern /** * Compiling logger. */ class CargoCompileLogger(private val myLogger: BuildProgressLogger) : CargoDefaultLogger(myLogger) { private var myProjectName: String? = null override fun onEnter(text: String) { val matcher = PROJECT_NAME_PATTERN.matcher(text) myProjectName = if (matcher.find()) ":" + matcher.group(1) else "" myLogger.message(String.format(COMPILATION_STARTED_FORMAT, myProjectName)) val message = String.format("%s %s", CargoState.Compiling, text) myLogger.message(String.format(COMPILATION_MESSAGE_FORMAT, message)) } override fun processLine(text: String) { myLogger.message(String.format(COMPILATION_MESSAGE_FORMAT, text.trim())) } override fun canChangeState(state: CargoState, text: String): Boolean { return !(state == CargoState.Running && text.startsWith("`rustc")) } override fun onLeave() { myLogger.message(String.format(COMPILATION_FINISHED_FORMAT, myProjectName)) } companion object { private val PROJECT_NAME_PATTERN = Pattern.compile("([^\\s]+)") private const val COMPILATION_STARTED_FORMAT = "##teamcity[compilationStarted compiler='rustc%s']" private const val COMPILATION_FINISHED_FORMAT = "##teamcity[compilationFinished compiler='rustc%s']" private const val COMPILATION_MESSAGE_FORMAT = "##teamcity[message text='%s']" } }
apache-2.0
1a268136a22ee242e10a1c669b0d792d
35.553191
108
0.701979
4.241975
false
false
false
false
savoirfairelinux/ring-client-android
ring-android/libjamiclient/src/main/kotlin/net/jami/services/CallService.kt
1
30122
/* * Copyright (C) 2004-2021 Savoir-faire Linux Inc. * * Author: Thibault Wittemberg <[email protected]> * Author: Adrien Béraud <[email protected]> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ package net.jami.services import io.reactivex.rxjava3.core.Completable import io.reactivex.rxjava3.core.Observable import io.reactivex.rxjava3.core.Single import io.reactivex.rxjava3.schedulers.Schedulers import io.reactivex.rxjava3.subjects.PublishSubject import net.jami.daemon.Blob import net.jami.daemon.JamiService import net.jami.daemon.StringMap import net.jami.daemon.VectMap import net.jami.model.Call import net.jami.model.Call.CallStatus import net.jami.model.Conference import net.jami.model.Conference.ParticipantInfo import net.jami.model.Media import net.jami.model.Uri import net.jami.utils.Log import net.jami.utils.StringUtils import java.util.* import java.util.concurrent.ScheduledExecutorService class CallService( private val mExecutor: ScheduledExecutorService, private val mContactService: ContactService, private val mAccountService: AccountService ) { private val currentCalls: MutableMap<String, Call> = HashMap() private val currentConferences: MutableMap<String, Conference> = HashMap() private val callSubject = PublishSubject.create<Call>() private val conferenceSubject = PublishSubject.create<Conference>() // private final Set<String> currentConnections = new HashSet<>(); // private final BehaviorSubject<Integer> connectionSubject = BehaviorSubject.createDefault(0); val confsUpdates: Observable<Conference> get() = conferenceSubject private fun getConfCallUpdates(conf: Conference): Observable<Conference> { Log.w(TAG, "getConfCallUpdates " + conf.id) return conferenceSubject .filter { c -> c == conf } .startWithItem(conf) .map(Conference::participants) .switchMap { list: List<Call> -> Observable.fromIterable(list) .flatMap { call: Call -> callSubject.filter { c -> c == call } } } .map { conf } .startWithItem(conf) } fun getConfUpdates(confId: String): Observable<Conference> { return getCurrentCallForId(confId)?.let { getConfUpdates(it) } ?: Observable.error(IllegalArgumentException()) /*Conference call = currentConferences.get(confId); return call == null ? Observable.error(new IllegalArgumentException()) : conferenceSubject .filter(c -> c.getId().equals(confId));//getConfUpdates(call);*/ } /*public Observable<Boolean> getConnectionUpdates() { return connectionSubject .map(i -> i > 0) .distinctUntilChanged(); }*/ private fun updateConnectionCount() { //connectionSubject.onNext(currentConnections.size() - 2*currentCalls.size()); } fun setIsComposing(accountId: String?, uri: String?, isComposing: Boolean) { mExecutor.execute { JamiService.setIsComposing(accountId, uri, isComposing) } } fun onConferenceInfoUpdated(confId: String, info: List<Map<String, String>>) { Log.w(TAG, "onConferenceInfoUpdated $confId $info") val conference = getConference(confId) var isModerator = false if (conference != null) { val newInfo: MutableList<ParticipantInfo> = ArrayList(info.size) val account = mAccountService.getAccount(conference.accountId) ?: return for (i in info) { val uri = i["uri"]!! val confInfo = if (uri.isEmpty()) { ParticipantInfo(null, mContactService.getLoadedContact(account.accountId, account.getContactFromCache(Uri.fromId(account.username!!))).blockingGet(), i) } else { val contactUri = Uri.fromString(uri) val call = conference.findCallByContact(contactUri) if (call != null) { ParticipantInfo(call, mContactService.getLoadedContact(call.account!!, call.contact!!).blockingGet(), i) } else { ParticipantInfo(null, mContactService.getLoadedContact(account.accountId, account.getContactFromCache(contactUri)).blockingGet(), i) } } if (confInfo.isEmpty) { Log.w(TAG, "onConferenceInfoUpdated: ignoring empty entry $i") continue } if (confInfo.contact.contact.isUser && confInfo.isModerator) { isModerator = true } newInfo.add(confInfo) } conference.isModerator = isModerator conference.setInfo(newInfo) } else { Log.w(TAG, "onConferenceInfoUpdated can't find conference $confId") } } fun setConfMaximizedParticipant(accountId: String, confId: String, uri: Uri) { mExecutor.execute { JamiService.setActiveParticipant(accountId, confId, uri.rawRingId) JamiService.setConferenceLayout(accountId, confId, 1) } } fun setConfGridLayout(accountId: String, confId: String) { mExecutor.execute { JamiService.setConferenceLayout(accountId, confId, 0) } } fun remoteRecordingChanged(callId: String, peerNumber: Uri, state: Boolean) { Log.w(TAG, "remoteRecordingChanged $callId $peerNumber $state") var conference = getConference(callId) val call: Call? if (conference == null) { call = getCurrentCallForId(callId) if (call != null) { conference = getConference(call) } } else { call = conference.firstCall } val account = if (call == null) null else mAccountService.getAccount(call.account!!) val contact = account?.getContactFromCache(peerNumber) if (conference != null && contact != null) { conference.setParticipantRecording(contact, state) } } private class ConferenceEntity internal constructor(var conference: Conference) fun getConfUpdates(call: Call): Observable<Conference> { return getConfUpdates(getConference(call)) } private fun getConfUpdates(conference: Conference): Observable<Conference> { Log.w(TAG, "getConfUpdates " + conference.id) val conferenceEntity = ConferenceEntity(conference) return conferenceSubject .startWithItem(conference) .filter { conf: Conference -> Log.w(TAG, "getConfUpdates filter " + conf.id + " " + conf.participants.size + " (tracked " + conferenceEntity.conference.id + " " + conferenceEntity.conference.participants.size + ")") if (conf == conferenceEntity.conference) { return@filter true } if (conf.contains(conferenceEntity.conference.id)) { Log.w(TAG, "Switching tracked conference (up) to " + conf.id) conferenceEntity.conference = conf return@filter true } if (conferenceEntity.conference.participants.size == 1 && conf.participants.size == 1 && conferenceEntity.conference.call == conf.call && conf.call!!.daemonIdString == conf.id) { Log.w(TAG, "Switching tracked conference (down) to " + conf.id) conferenceEntity.conference = conf return@filter true } false } .switchMap { conf: Conference -> getConfCallUpdates(conf) } } val callsUpdates: Observable<Call> get() = callSubject private fun getCallUpdates(call: Call): Observable<Call> { return callSubject.filter { c: Call -> c == call } .startWithItem(call) .takeWhile { c: Call -> c.callStatus !== CallStatus.OVER } } /*public Observable<SipCall> getCallUpdates(final String callId) { SipCall call = getCurrentCallForId(callId); return call == null ? Observable.error(new IllegalArgumentException()) : getCallUpdates(call); }*/ fun placeCallObservable(accountId: String, conversationUri: Uri?, number: Uri, hasVideo: Boolean): Observable<Call> { return placeCall(accountId, conversationUri, number, hasVideo) .flatMapObservable { call: Call -> getCallUpdates(call) } } fun placeCall(account: String, conversationUri: Uri?, number: Uri, hasVideo: Boolean): Single<Call> { return Single.fromCallable<Call> { Log.i(TAG, "placeCall() thread running... $number hasVideo: $hasVideo") val media = VectMap() media.reserve(if (hasVideo) 2L else 1L) media.add(Media.DEFAULT_AUDIO.toMap()) if (hasVideo) media.add(Media.DEFAULT_VIDEO.toMap()) val callId = JamiService.placeCallWithMedia(account, number.uri, media) if (callId == null || callId.isEmpty()) return@fromCallable null val call = addCall(account, callId, number, Call.Direction.OUTGOING, if (hasVideo) listOf(Media.DEFAULT_AUDIO, Media.DEFAULT_VIDEO) else listOf(Media.DEFAULT_AUDIO)) if (conversationUri != null && conversationUri.isSwarm) call.setSwarmInfo(conversationUri.rawRingId) updateConnectionCount() call }.subscribeOn(Schedulers.from(mExecutor)) } fun refuse(accountId:String, callId: String) { mExecutor.execute { Log.i(TAG, "refuse() running... $callId") JamiService.refuse(accountId, callId) JamiService.hangUp(accountId, callId) } } /* fun accept(callId: String) { mExecutor.execute { Log.i(TAG, "accept() running... $callId") JamiService.muteCapture(false) JamiService.accept(callId) } }*/ fun accept(accountId:String, callId: String, hasVideo: Boolean = false) { mExecutor.execute { Log.i(TAG, "accept() running... $callId") val call = currentCalls[callId] ?: return@execute val mediaList = call.mediaList ?: return@execute val vectMapMedia = mediaList.mapTo(VectMap().apply { reserve(mediaList.size.toLong()) }) { media -> if (!hasVideo && media.mediaType == Media.MediaType.MEDIA_TYPE_VIDEO) media.copy(isMuted = true).toMap() else media.toMap() } JamiService.acceptWithMedia(accountId, callId, vectMapMedia) } } fun hangUp(accountId:String, callId: String) { mExecutor.execute { Log.i(TAG, "hangUp() running... $callId") JamiService.hangUp(accountId, callId) } } fun muteParticipant(accountId:String, confId: String, peerId: String, mute: Boolean) { mExecutor.execute { Log.i(TAG, "mute participant... $peerId") JamiService.muteParticipant(accountId, confId, peerId, mute) } } fun hangupParticipant(accountId:String, confId: String?, peerId: String) { mExecutor.execute { Log.i(TAG, "hangup participant... $peerId") JamiService.hangupParticipant(accountId, confId, peerId) } } fun raiseParticipantHand(accountId: String, confId: String, peerId: String, state: Boolean){ mExecutor.execute { Log.i(TAG, "participant $peerId raise hand... ") JamiService.raiseParticipantHand(accountId, confId, peerId, state) } } fun hold(accountId:String, callId: String) { mExecutor.execute { Log.i(TAG, "hold() running... $callId") JamiService.hold(accountId, callId) } } fun unhold(accountId:String, callId: String) { mExecutor.execute { Log.i(TAG, "unhold() running... $callId") JamiService.unhold(accountId, callId) } } fun muteRingTone(mute: Boolean) { Log.d(TAG, (if (mute) "Muting." else "Unmuting.") + " ringtone.") JamiService.muteRingtone(mute) } fun restartAudioLayer() { mExecutor.execute { Log.i(TAG, "restartAudioLayer() running...") JamiService.setAudioPlugin(JamiService.getCurrentAudioOutputPlugin()) } } fun setAudioPlugin(audioPlugin: String) { mExecutor.execute { Log.i(TAG, "setAudioPlugin() running...") JamiService.setAudioPlugin(audioPlugin) } } val currentAudioOutputPlugin: String? get() { try { return mExecutor.submit<String> { Log.i(TAG, "getCurrentAudioOutputPlugin() running...") JamiService.getCurrentAudioOutputPlugin() }.get() } catch (e: Exception) { Log.e(TAG, "Error running getCallDetails()", e) } return null } fun playDtmf(key: String) { mExecutor.execute { Log.i(TAG, "playDTMF() running... $key") JamiService.playDTMF(key) } } fun setMuted(mute: Boolean) { mExecutor.execute { Log.i(TAG, "muteCapture() running...") JamiService.muteCapture(mute) } } fun setLocalMediaMuted(accountId:String, callId: String, mediaType: String, mute: Boolean) { mExecutor.execute { Log.i(TAG, "muteCapture() running...") JamiService.muteLocalMedia(accountId, callId, mediaType, mute) } } val isCaptureMuted: Boolean get() = JamiService.isCaptureMuted() fun transfer(accountId:String, callId: String, to: String) { mExecutor.execute { Log.i(TAG, "transfer() thread running...") if (JamiService.transfer(accountId, callId, to)) { Log.i(TAG, "OK") } else { Log.i(TAG, "NOT OK") } } } fun attendedTransfer(accountId:String, transferId: String, targetID: String) { mExecutor.execute { Log.i(TAG, "attendedTransfer() thread running...") if (JamiService.attendedTransfer(accountId, transferId, targetID)) { Log.i(TAG, "OK") } else { Log.i(TAG, "NOT OK") } } } var recordPath: String? get() { try { return mExecutor.submit<String> { JamiService.getRecordPath() }.get() } catch (e: Exception) { Log.e(TAG, "Error running isCaptureMuted()", e) } return null } set(path) { mExecutor.execute { JamiService.setRecordPath(path) } } fun toggleRecordingCall(accountId:String, callId: String): Boolean { mExecutor.execute { JamiService.toggleRecording(accountId, callId) } return false } fun startRecordedFilePlayback(filepath: String): Boolean { mExecutor.execute { JamiService.startRecordedFilePlayback(filepath) } return false } fun stopRecordedFilePlayback() { mExecutor.execute { JamiService.stopRecordedFilePlayback() } } fun sendTextMessage(accountId: String, callId: String, msg: String) { mExecutor.execute { Log.i(TAG, "sendTextMessage() thread running...") val messages = StringMap() messages.setRaw("text/plain", Blob.fromString(msg)) JamiService.sendTextMessage(accountId, callId, messages, "", false) } } fun sendAccountTextMessage(accountId: String, to: String, msg: String): Single<Long> { return Single.fromCallable { Log.i(TAG, "sendAccountTextMessage() running... $accountId $to $msg") val msgs = StringMap() msgs.setRaw("text/plain", Blob.fromString(msg)) JamiService.sendAccountTextMessage(accountId, to, msgs) }.subscribeOn(Schedulers.from(mExecutor)) } fun cancelMessage(accountId: String, messageID: Long): Completable { return Completable.fromAction { Log.i(TAG, "CancelMessage() running... Account ID: $accountId Message ID $messageID") JamiService.cancelMessage(accountId, messageID) }.subscribeOn(Schedulers.from(mExecutor)) } private fun getCurrentCallForId(callId: String): Call? { return currentCalls[callId] } private fun addCall(accountId: String, callId: String, from: Uri, direction: Call.Direction, mediaList: List<Media>): Call { synchronized(currentCalls) { var call = currentCalls[callId] if (call == null) { val account = mAccountService.getAccount(accountId)!! val contact = mContactService.findContact(account, from) val conversationUri = contact.conversationUri.blockingFirst() val conversation = if (conversationUri.equals(from)) account.getByUri(from) else account.getSwarm(conversationUri.rawRingId) call = Call(callId, from.uri, accountId, conversation, contact, direction, mediaList) currentCalls[callId] = call } else { Log.w(TAG, "Call already existed ! $callId $from") call.mediaList = mediaList } return call } } private fun addConference(call: Call): Conference { val confId = call.confId ?: call.daemonIdString!! var conference = currentConferences[confId] if (conference == null) { conference = Conference(call) currentConferences[confId] = conference conferenceSubject.onNext(conference) } return conference } private fun parseCallState(accountId:String, callId: String, newState: String): Call? { val callState = CallStatus.fromString(newState) var call = currentCalls[callId] if (call != null) { call.setCallState(callState) call.setDetails(JamiService.getCallDetails(accountId, callId).toNative()) } else if (callState !== CallStatus.OVER && callState !== CallStatus.FAILURE) { val callDetails: Map<String, String> = JamiService.getCallDetails(accountId, callId) call = Call(callId, callDetails) if (StringUtils.isEmpty(call.contactNumber)) { Log.w(TAG, "No number") return null } call.setCallState(callState) val account = mAccountService.getAccount(call.account!!)!! val contact = mContactService.findContact(account, Uri.fromString(call.contactNumber!!)) val registeredName = callDetails[Call.KEY_REGISTERED_NAME] /*if (registeredName != null && registeredName.isNotEmpty()) { contact.setUsername(registeredName) }*/ val conversation = account.getByUri(contact.conversationUri.blockingFirst()) call.contact = contact call.conversation = conversation Log.w(TAG, "parseCallState " + contact + " " + contact.conversationUri.blockingFirst() + " " + conversation + " " + conversation?.participant) currentCalls[callId] = call updateConnectionCount() } return call } fun connectionUpdate(id: String?, state: Int) { // Log.d(TAG, "connectionUpdate: " + id + " " + state); /*switch(state) { case 0: currentConnections.add(id); break; case 1: case 2: currentConnections.remove(id); break; } updateConnectionCount();*/ } fun callStateChanged(accountId: String, callId: String, newState: String, detailCode: Int) { Log.d(TAG, "call state changed: $callId, $newState, $detailCode") try { synchronized(currentCalls) { parseCallState(accountId, callId, newState)?.let { call -> callSubject.onNext(call) if (call.callStatus === CallStatus.OVER) { currentCalls.remove(call.daemonIdString) currentConferences.remove(call.daemonIdString) updateConnectionCount() } } } } catch (e: Exception) { Log.w(TAG, "Exception during state change: ", e) } } fun audioMuted(callId: String, muted: Boolean) { val call = currentCalls[callId] if (call != null) { call.isAudioMuted = muted callSubject.onNext(call) } else { currentConferences[callId]?.let { conf -> conf.isAudioMuted = muted conferenceSubject.onNext(conf) } } } fun videoMuted(callId: String, muted: Boolean) { currentCalls[callId]?.let { call -> call.isVideoMuted = muted callSubject.onNext(call) } currentConferences[callId]?.let { conf -> conf.isVideoMuted = muted conferenceSubject.onNext(conf) } } fun incomingCallWithMedia(accountId: String, callId: String, from: String, mediaList: VectMap?) { Log.d(TAG, "incoming call: $accountId, $callId, $from") val nMediaList = mediaList ?: emptyList() val medias = nMediaList.mapTo(ArrayList(nMediaList.size)) { mediaMap -> Media(mediaMap) } val call = addCall(accountId, callId, Uri.fromStringWithName(from).first, Call.Direction.INCOMING, medias) callSubject.onNext(call) updateConnectionCount() } fun mediaChangeRequested(accountId: String, callId: String, mediaList: VectMap) { currentCalls[callId]?.let { call -> if (!call.hasActiveMedia(Media.MediaType.MEDIA_TYPE_VIDEO)) { for (e in mediaList) if (e[Media.MEDIA_TYPE_KEY]!! == MEDIA_TYPE_VIDEO) e[Media.MUTED_KEY] = true.toString() } JamiService.answerMediaChangeRequest(accountId, callId, mediaList) } } fun mediaNegotiationStatus(callId: String, event: String, mediaList: VectMap) { synchronized(currentCalls) { currentCalls[callId]?.let { call -> call.mediaList = mediaList.mapTo(ArrayList(mediaList.size)) { media -> Media(media) } callSubject.onNext(call) } } } fun requestVideoMedia(conf: Conference, enable: Boolean) { if (conf.isConference || conf.hasVideo()) { JamiService.muteLocalMedia(conf.accountId, conf.id, Media.MediaType.MEDIA_TYPE_VIDEO.name, !enable) } else if (enable) { val call = conf.firstCall ?: return val mediaList = call.mediaList ?: return JamiService.requestMediaChange(call.account, call.daemonIdString, mediaList.mapTo(VectMap() .apply { reserve(mediaList.size.toLong() + 1L) } ) { media -> media.toMap() } .apply { add(Media.DEFAULT_VIDEO.toMap()) }) } } fun incomingMessage(accountId: String, callId: String, from: String, messages: Map<String, String>) { val call = currentCalls[callId] if (call == null) { Log.w(TAG, "incomingMessage: unknown call or no message: $callId $from") return } call.appendToVCard(messages)?.let { vcard -> mContactService.saveVCardContactData(call.contact!!, call.account!!, vcard) } if (messages.containsKey(MIME_TEXT_PLAIN)) { mAccountService.incomingAccountMessage(call.account!!, null, callId, from, messages) } } fun recordPlaybackFilepath(id: String, filename: String) { Log.d(TAG, "record playback filepath: $id, $filename") // todo needs more explanations on that } fun onRtcpReportReceived(callId: String) { Log.i(TAG, "on RTCP report received: $callId") } fun joinParticipant(accountId: String, selCallId: String, account2Id: String, dragCallId: String): Single<Boolean> { return Single.fromCallable { JamiService.joinParticipant(accountId, selCallId, account2Id, dragCallId) } .subscribeOn(Schedulers.from(mExecutor)) } fun addParticipant(accountId: String, callId: String, account2Id: String, confId: String) { mExecutor.execute { JamiService.addParticipant(accountId, callId, account2Id, confId) } } fun addMainParticipant(accountId: String, confId: String) { mExecutor.execute { JamiService.addMainParticipant(accountId, confId) } } fun detachParticipant(accountId: String, callId: String) { mExecutor.execute { JamiService.detachParticipant(accountId, callId) } } fun joinConference(accountId: String, selConfId: String, account2Id: String, dragConfId: String) { mExecutor.execute { JamiService.joinConference(accountId, selConfId, account2Id, dragConfId) } } fun hangUpConference(accountId: String, confId: String) { mExecutor.execute { JamiService.hangUpConference(accountId, confId) } } fun holdConference(accountId: String, confId: String) { mExecutor.execute { JamiService.holdConference(accountId, confId) } } fun unholdConference(accountId: String, confId: String) { mExecutor.execute { JamiService.unholdConference(accountId, confId) } } fun getConference(call: Call): Conference { return addConference(call) } fun getConference(id: String): Conference? { return currentConferences[id] } fun conferenceCreated(accountId: String, confId: String) { Log.d(TAG, "conference created: $confId") var conf = currentConferences[confId] if (conf == null) { conf = Conference(accountId, confId) currentConferences[confId] = conf } val participants = JamiService.getParticipantList(accountId, confId) val map = JamiService.getConferenceDetails(accountId, confId) conf.setState(map["STATE"]!!) for (callId in participants) { val call = getCurrentCallForId(callId) if (call != null) { Log.d(TAG, "conference created: adding participant " + callId + " " + call.contact) call.confId = confId conf.addParticipant(call) } val rconf = currentConferences.remove(callId) Log.d(TAG, "conference created: removing conference " + callId + " " + rconf + " now " + currentConferences.size) } conferenceSubject.onNext(conf) } fun conferenceRemoved(accountId: String, confId: String) { Log.d(TAG, "conference removed: $confId") currentConferences.remove(confId)?.let { conf -> for (call in conf.participants) { call.confId = null } conf.removeParticipants() conferenceSubject.onNext(conf) } } fun conferenceChanged(accountId: String, confId: String, state: String) { Log.d(TAG, "conference changed: $confId, $state") try { var conf = currentConferences[confId] if (conf == null) { conf = Conference(accountId, confId) currentConferences[confId] = conf } conf.setState(state) val participants: Set<String> = JamiService.getParticipantList(accountId, confId).toHashSet() // Add new participants for (callId in participants) { if (!conf.contains(callId)) { val call = getCurrentCallForId(callId) if (call != null) { Log.d(TAG, "conference changed: adding participant " + callId + " " + call.contact) call.confId = confId conf.addParticipant(call) } currentConferences.remove(callId) } } // Remove participants val calls = conf.participants var removed = false val i = calls.iterator() while (i.hasNext()) { val call = i.next() if (!participants.contains(call.daemonIdString)) { Log.d(TAG, "conference changed: removing participant " + call.daemonIdString + " " + call.contact) call.confId = null i.remove() removed = true } } conferenceSubject.onNext(conf) if (removed && conf.participants.size == 1) { val call = conf.participants[0] call.confId = null addConference(call) } } catch (e: Exception) { Log.w(TAG, "exception in conferenceChanged", e) } } companion object { private val TAG = CallService::class.simpleName!! const val MIME_TEXT_PLAIN = "text/plain" const val MIME_GEOLOCATION = "application/geo" const val MEDIA_TYPE_AUDIO = "MEDIA_TYPE_AUDIO" const val MEDIA_TYPE_VIDEO = "MEDIA_TYPE_VIDEO" } }
gpl-3.0
dc6628b31c36a0e1829f8176c34a470c
39.486559
201
0.603234
4.465678
false
false
false
false
proxer/ProxerLibAndroid
library/src/main/kotlin/me/proxer/library/enums/RelationshipStatus.kt
2
694
package me.proxer.library.enums import com.serjltt.moshi.adapters.FallbackEnum import com.squareup.moshi.Json import com.squareup.moshi.JsonClass /** * Enum holding the available relationship statuses. * * @author Ruben Gees */ @JsonClass(generateAdapter = false) @FallbackEnum(name = "UNKNOWN") enum class RelationshipStatus { @Json(name = "single") SINGLE, @Json(name = "in_relation") IN_RELATION, @Json(name = "engaged") ENGAGED, @Json(name = "complicated") COMPLICATED, @Json(name = "married") MARRIED, @Json(name = "searching") SEARCHING, @Json(name = "not-searching") NOT_SEARCHING, @Json(name = "") UNKNOWN }
gpl-3.0
1a0bbd43d83d425251d5ebae44f47de0
16.794872
52
0.658501
3.522843
false
false
false
false
RocketChat/Rocket.Chat.Android
app/src/main/java/chat/rocket/android/chatroom/ui/ActionSnackbar.kt
2
3320
package chat.rocket.android.chatroom.ui import android.text.Spannable import android.text.SpannableStringBuilder import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.TextView import androidx.core.content.ContextCompat import androidx.core.view.ViewCompat import androidx.core.view.setPadding import chat.rocket.android.R import chat.rocket.android.helper.MessageParser import chat.rocket.android.util.extensions.content import com.google.android.material.snackbar.BaseTransientBottomBar import kotlinx.android.synthetic.main.message_action_bar.view.* import ru.noties.markwon.Markwon class ActionSnackbar private constructor( parentViewGroup: ViewGroup, content: View, contentViewCallback: com.google.android.material.snackbar.ContentViewCallback ) : BaseTransientBottomBar<ActionSnackbar>(parentViewGroup, content, contentViewCallback) { companion object { fun make(parentViewGroup: ViewGroup, content: String = "", parser: MessageParser): ActionSnackbar { val context = parentViewGroup.context val view = LayoutInflater.from(context).inflate(R.layout.message_action_bar, parentViewGroup, false) val actionSnackbar = ActionSnackbar(parentViewGroup, view, CallbackImpl(view)) with(view) { actionSnackbar.getView().setPadding(0) actionSnackbar.getView().setBackgroundColor(ContextCompat.getColor(context, R.color.colorWhite)) actionSnackbar.parser = parser actionSnackbar.messageTextView = text_view_action_text actionSnackbar.titleTextView = text_view_action_title actionSnackbar.cancelView = image_view_action_cancel_quote actionSnackbar.duration = BaseTransientBottomBar.LENGTH_INDEFINITE val spannable = Markwon.markdown(context, content).trim() actionSnackbar.messageTextView.content = spannable } return actionSnackbar } } lateinit var parser: MessageParser lateinit var cancelView: View private lateinit var messageTextView: TextView private lateinit var titleTextView: TextView var text: String = "" set(value) { val spannable = SpannableStringBuilder.valueOf(value) messageTextView.content = spannable } var title: String = "" set(value) { val spannable = Markwon.markdown(this.context, value) as Spannable titleTextView.content = spannable } override fun dismiss() { super.dismiss() text = "" title = "" } class CallbackImpl(val content: View) : com.google.android.material.snackbar.ContentViewCallback { override fun animateContentOut(delay: Int, duration: Int) { content.scaleY = 1f ViewCompat.animate(content) .scaleY(0f) .setDuration(duration.toLong()) .startDelay = delay.toLong() } override fun animateContentIn(delay: Int, duration: Int) { content.scaleY = 0f ViewCompat.animate(content) .scaleY(1f) .setDuration(duration.toLong()) .startDelay = delay.toLong() } } }
mit
381e5eb512cbd7b338e779c75ceceeb9
37.616279
112
0.677108
4.940476
false
false
false
false
gradle/gradle
subprojects/kotlin-dsl/src/main/kotlin/org/gradle/kotlin/dsl/ObjectFactoryExtensions.kt
4
2525
/* * Copyright 2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.gradle.kotlin.dsl import org.gradle.api.Named import org.gradle.api.model.ObjectFactory import org.gradle.api.provider.ListProperty import org.gradle.api.provider.MapProperty import org.gradle.api.provider.Property import org.gradle.api.provider.SetProperty /** * Creates a simple immutable [Named] object of the given type and name. * * @param T The type of object to create * @param name The name of the created object * @return the created named object * * @see [ObjectFactory.named] */ inline fun <reified T : Named> ObjectFactory.named(name: String): T = named(T::class.java, name) /** * Create a new instance of `T`, using [parameters] as the construction parameters. * * @param T The type of object to create * @param parameters The construction parameters * @return the created named object * * @see [ObjectFactory.newInstance] */ inline fun <reified T> ObjectFactory.newInstance(vararg parameters: Any): T = newInstance(T::class.java, *parameters) /** * Creates a [Property] that holds values of the given type [T]. * * @see [ObjectFactory.property] */ inline fun <reified T> ObjectFactory.property(): Property<T> = property(T::class.java) /** * Creates a [SetProperty] that holds values of the given type [T]. * * @see [ObjectFactory.setProperty] */ inline fun <reified T> ObjectFactory.setProperty(): SetProperty<T> = setProperty(T::class.java) /** * Creates a [ListProperty] that holds values of the given type [T]. * * @see [ObjectFactory.listProperty] */ inline fun <reified T> ObjectFactory.listProperty(): ListProperty<T> = listProperty(T::class.java) /** * Creates a [MapProperty] that holds values of the given key type [K] and value type [V]. * * @see [ObjectFactory.mapProperty] */ inline fun <reified K, reified V> ObjectFactory.mapProperty(): MapProperty<K, V> = mapProperty(K::class.java, V::class.java)
apache-2.0
e57e469fbe7dfa268689093ea9a519b4
28.360465
90
0.722376
3.825758
false
false
false
false
gradle/gradle
subprojects/kotlin-dsl/src/main/kotlin/org/gradle/kotlin/dsl/execution/Lexer.kt
3
7753
/* * Copyright 2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.gradle.kotlin.dsl.execution import org.jetbrains.kotlin.lexer.KotlinLexer import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.lexer.KtTokens.COMMENTS import org.jetbrains.kotlin.lexer.KtTokens.IDENTIFIER import org.jetbrains.kotlin.lexer.KtTokens.LBRACE import org.jetbrains.kotlin.lexer.KtTokens.PACKAGE_KEYWORD import org.jetbrains.kotlin.lexer.KtTokens.RBRACE import org.jetbrains.kotlin.lexer.KtTokens.WHITE_SPACE internal abstract class UnexpectedBlock(message: String) : RuntimeException(message) { abstract val location: IntRange } internal class UnexpectedDuplicateBlock(val identifier: TopLevelBlockId, override val location: IntRange) : UnexpectedBlock("Unexpected `$identifier` block found. Only one `$identifier` block is allowed per script.") internal class UnexpectedBlockOrder(val identifier: TopLevelBlockId, override val location: IntRange, expectedFirstIdentifier: TopLevelBlockId) : UnexpectedBlock("Unexpected `$identifier` block found. `$identifier` can not appear before `$expectedFirstIdentifier`.") data class Packaged<T>( val packageName: String?, val document: T ) { fun <U> map(transform: (T) -> U): Packaged<U> = Packaged( packageName, document = transform(document) ) } internal data class LexedScript( val comments: List<IntRange>, val topLevelBlocks: List<TopLevelBlock> ) /** * Returns the comments and [top-level blocks][topLevelBlockIds] found in the given [script]. */ internal fun lex(script: String, vararg topLevelBlockIds: TopLevelBlockId): Packaged<LexedScript> { var packageName: String? = null val comments = mutableListOf<IntRange>() val topLevelBlocks = mutableListOf<TopLevelBlock>() var state = State.SearchingTopLevelBlock var inTopLevelBlock: TopLevelBlockId? = null var blockIdentifier: IntRange? = null var blockStart: Int? = null var depth = 0 fun reset() { state = State.SearchingTopLevelBlock inTopLevelBlock = null blockIdentifier = null blockStart = null } fun KotlinLexer.matchTopLevelIdentifier(): Boolean { if (depth == 0) { val identifier = tokenText for (topLevelBlock in topLevelBlockIds) { if (topLevelBlock.tokenText == identifier) { state = State.SearchingBlockStart inTopLevelBlock = topLevelBlock blockIdentifier = tokenStart until tokenEnd return true } } } return false } KotlinLexer().apply { start(script) while (tokenType != null) { when (tokenType) { WHITE_SPACE -> { // ignore } in COMMENTS -> { comments.add( tokenStart until tokenEnd ) } else -> { when (state) { State.SearchingTopLevelBlock -> { when (tokenType) { PACKAGE_KEYWORD -> { advance() skipWhiteSpaceAndComments() packageName = parseQualifiedName() } IDENTIFIER -> matchTopLevelIdentifier() LBRACE -> depth += 1 RBRACE -> depth -= 1 } } State.SearchingBlockStart -> { when (tokenType) { IDENTIFIER -> if (!matchTopLevelIdentifier()) reset() LBRACE -> { depth += 1 state = State.SearchingBlockEnd blockStart = tokenStart } else -> reset() } } State.SearchingBlockEnd -> { when (tokenType) { LBRACE -> depth += 1 RBRACE -> { depth -= 1 if (depth == 0) { topLevelBlocks.add( topLevelBlock( inTopLevelBlock!!, blockIdentifier!!, blockStart!!..tokenStart ) ) reset() } } } } } } } advance() } } return Packaged( packageName, LexedScript(comments, topLevelBlocks) ) } private enum class State { SearchingTopLevelBlock, SearchingBlockStart, SearchingBlockEnd } private fun KotlinLexer.parseQualifiedName(): String = StringBuilder().run { while (tokenType == IDENTIFIER || tokenType == KtTokens.DOT) { append(tokenText) advance() } toString() } private fun KotlinLexer.skipWhiteSpaceAndComments() { while (tokenType in KtTokens.WHITE_SPACE_OR_COMMENT_BIT_SET) { advance() } } internal fun topLevelBlock(identifier: TopLevelBlockId, identifierRange: IntRange, blockRange: IntRange) = TopLevelBlock(identifier, ScriptSection(identifierRange, blockRange)) internal data class TopLevelBlock(val identifier: TopLevelBlockId, val section: ScriptSection) { val range: IntRange get() = section.wholeRange } @Suppress("EnumEntryName") internal enum class TopLevelBlockId { buildscript, plugins, pluginManagement, initscript; val tokenText: String get() = name companion object { fun topLevelBlockIdFor(target: ProgramTarget) = when (target) { ProgramTarget.Project -> arrayOf(buildscript, plugins) ProgramTarget.Settings -> arrayOf(buildscript, pluginManagement, plugins) ProgramTarget.Gradle -> arrayOf(initscript) } fun buildscriptIdFor(target: ProgramTarget) = when (target) { ProgramTarget.Gradle -> initscript ProgramTarget.Settings -> buildscript ProgramTarget.Project -> buildscript } } } internal fun List<TopLevelBlock>.singleBlockSectionOrNull(): ScriptSection? = when (size) { 0 -> null 1 -> get(0).section else -> { val unexpectedBlock = get(1) throw UnexpectedDuplicateBlock(unexpectedBlock.identifier, unexpectedBlock.range) } }
apache-2.0
9c83df08e4df46cfee2c4ce2df642501
29.050388
136
0.540307
5.646759
false
false
false
false
luxons/seven-wonders
sw-ui/src/main/kotlin/org/luxons/sevenwonders/ui/components/game/Board.kt
1
6400
package org.luxons.sevenwonders.ui.components.game import kotlinx.css.* import kotlinx.css.properties.* import kotlinx.html.DIV import kotlinx.html.HTMLTag import kotlinx.html.IMG import kotlinx.html.title import org.luxons.sevenwonders.model.boards.Board import org.luxons.sevenwonders.model.boards.Military import org.luxons.sevenwonders.model.cards.TableCard import org.luxons.sevenwonders.model.wonders.ApiWonder import org.luxons.sevenwonders.model.wonders.ApiWonderStage import react.RBuilder import react.dom.* import styled.StyledDOMBuilder import styled.css import styled.styledDiv import styled.styledImg // card offsets in % of their size when displayed in columns private const val xOffset = 20 private const val yOffset = 21 fun RBuilder.boardComponent(board: Board, block: StyledDOMBuilder<DIV>.() -> Unit = {}) { styledDiv { block() tableCards(cardColumns = board.playedCards) wonderComponent(wonder = board.wonder, military = board.military) } } private fun RBuilder.tableCards(cardColumns: List<List<TableCard>>) { styledDiv { css { display = Display.flex justifyContent = JustifyContent.spaceAround height = 45.pct width = 100.pct } cardColumns.forEach { cards -> tableCardColumn(cards = cards) { attrs { key = cards.first().color.toString() } } } } } private fun RBuilder.tableCardColumn(cards: List<TableCard>, block: StyledDOMBuilder<DIV>.() -> Unit = {}) { styledDiv { css { height = 100.pct width = 13.pct marginRight = 4.pct position = Position.relative } block() cards.forEachIndexed { index, card -> tableCard(card = card, indexInColumn = index) { attrs { key = card.name } } } } } private fun RBuilder.tableCard(card: TableCard, indexInColumn: Int, block: StyledDOMBuilder<IMG>.() -> Unit = {}) { val highlightColor = if (card.playedDuringLastMove) Color.gold else null cardImage(card = card, highlightColor = highlightColor) { css { position = Position.absolute zIndex = indexInColumn + 2 // go above the board and the built wonder cards transform { translate( tx = (indexInColumn * xOffset).pct, ty = (indexInColumn * yOffset).pct, ) } maxWidth = 100.pct maxHeight = 70.pct } block() } } private fun RBuilder.wonderComponent(wonder: ApiWonder, military: Military) { styledDiv { css { position = Position.relative width = 100.pct height = 40.pct } styledDiv { css { position = Position.absolute left = 50.pct top = 0.px transform { translateX((-50).pct) } height = 100.pct maxWidth = 95.pct // same as wonder } styledImg(src = "/images/wonders/${wonder.image}") { css { declarations["border-radius"] = "0.5%/1.5%" boxShadow(color = Color.black, offsetX = 0.2.rem, offsetY = 0.2.rem, blurRadius = 0.5.rem) maxHeight = 100.pct maxWidth = 100.pct zIndex = 1 // go above the built wonder cards, but below the table cards } attrs { this.title = wonder.name this.alt = "Wonder ${wonder.name}" } } victoryPoints(military.victoryPoints) { css { position = Position.absolute top = 25.pct // below the wonder name left = 60.pct zIndex = 2 // go above the wonder, but below the table cards } } defeatTokenCount(military.nbDefeatTokens) { css { position = Position.absolute top = 25.pct // below the wonder name left = 80.pct zIndex = 2 // go above the wonder, but below the table cards } } wonder.stages.forEachIndexed { index, stage -> wonderStageElement(stage) { css { wonderCardStyle(index, wonder.stages.size) } } } } } } private fun RBuilder.victoryPoints(points: Int, block: StyledDOMBuilder<DIV>.() -> Unit = {}) { boardToken("military/victory1", points, block) } private fun RBuilder.defeatTokenCount(nbDefeatTokens: Int, block: StyledDOMBuilder<DIV>.() -> Unit = {}) { boardToken("military/defeat1", nbDefeatTokens, block) } private fun RBuilder.boardToken(tokenName: String, count: Int, block: StyledDOMBuilder<DIV>.() -> Unit) { tokenWithCount( tokenName = tokenName, count = count, countPosition = TokenCountPosition.RIGHT, brightText = true, ) { css { filter = "drop-shadow(0.2rem 0.2rem 0.5rem black)" height = 15.pct } block() } } private fun RBuilder.wonderStageElement(stage: ApiWonderStage, block: StyledDOMBuilder<HTMLTag>.() -> Unit) { val back = stage.cardBack if (back != null) { cardBackImage(back) { block() } } else { cardPlaceholderImage { block() } } } private fun CSSBuilder.wonderCardStyle(stageIndex: Int, nbStages: Int) { position = Position.absolute top = 60.pct // makes the cards stick out of the bottom of the wonder left = stagePositionPercent(stageIndex, nbStages).pct maxWidth = 24.pct // ratio of card width to wonder width maxHeight = 90.pct // ratio of card height to wonder height zIndex = -1 // below wonder (somehow 0 is not sufficient) } private fun stagePositionPercent(stageIndex: Int, nbStages: Int): Double = when (nbStages) { 2 -> 37.5 + stageIndex * 29.8 // 37.5 (29.8) 67.3 4 -> -1.5 + stageIndex * 26.7 // -1.5 (26.6) 25.1 (26.8) 51.9 (26.7) 78.6 else -> 7.9 + stageIndex * 30.0 }
mit
83df4cb54b76ff2416142a93f4aa29fa
32.333333
115
0.559531
4.362645
false
false
false
false
luxons/seven-wonders
sw-ui/src/main/kotlin/org/luxons/sevenwonders/ui/redux/sagas/SagasFramework.kt
1
4542
package org.luxons.sevenwonders.ui.redux.sagas import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.FlowPreview import kotlinx.coroutines.GlobalScope import kotlinx.coroutines.Job import kotlinx.coroutines.channels.BroadcastChannel import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.collect import kotlinx.coroutines.launch import redux.Middleware import redux.MiddlewareApi import redux.RAction @OptIn(ExperimentalCoroutinesApi::class) class SagaManager<S, A : RAction, R>( private val monitor: ((A) -> Unit)? = null, ) { private lateinit var context: SagaContext<S, A, R> private val actions = BroadcastChannel<A>(16) fun createMiddleware(): Middleware<S, A, R, A, R> = ::sagasMiddleware private fun sagasMiddleware(api: MiddlewareApi<S, A, R>): ((A) -> R) -> (A) -> R { context = SagaContext(api, actions) return { nextDispatch -> { action -> onActionDispatched(action) val result = nextDispatch(action) handleAction(action) result } } } private fun onActionDispatched(action: A) { monitor?.invoke(action) } private fun handleAction(action: A) { GlobalScope.launch { actions.send(action) } } fun launchSaga(coroutineScope: CoroutineScope, saga: suspend SagaContext<S, A, R>.() -> Unit): Job { checkMiddlewareApplied() return coroutineScope.launch { context.saga() } } suspend fun runSaga(saga: suspend SagaContext<S, A, R>.() -> Unit) { checkMiddlewareApplied() context.saga() } private fun checkMiddlewareApplied() { check(::context.isInitialized) { "Before running a Saga, you must mount the Saga middleware on the Store using applyMiddleware" } } } @OptIn(FlowPreview::class, ExperimentalCoroutinesApi::class) class SagaContext<S, A : RAction, R>( private val reduxApi: MiddlewareApi<S, A, R>, private val actions: BroadcastChannel<A>, ) { /** * Gets the current redux state. */ fun getState(): S = reduxApi.getState() /** * Dispatches the given redux [action]. */ fun dispatch(action: A) { reduxApi.dispatch(action) } /** * Dispatches all actions from this flow. */ suspend fun Flow<A>.dispatchAll() { collect { reduxApi.dispatch(it) } } /** * Dispatches all actions from this flow in the provided [scope]. */ fun Flow<A>.dispatchAllIn(scope: CoroutineScope): Job = scope.launch { dispatchAll() } /** * Executes [handle] on every action dispatched. This runs forever until the current coroutine is cancelled. */ suspend fun onEach(handle: suspend SagaContext<S, A, R>.(A) -> Unit) { val channel = actions.openSubscription() try { for (a in channel) { handle(a) } } finally { channel.cancel() } } /** * Executes [handle] on every action dispatched of the type [T]. This runs forever until the current coroutine is * cancelled. */ suspend inline fun <reified T : A> onEach( crossinline handle: suspend SagaContext<S, A, R>.(T) -> Unit, ) = onEach { if (it is T) { handle(it) } } /** * Launches a coroutine in the receiver scope that executes [handle] on every action dispatched of the type [T]. * The returned [Job] can be used to cancel that coroutine (just like a regular [launch]) */ inline fun <reified T : A> CoroutineScope.launchOnEach( crossinline handle: suspend SagaContext<S, A, R>.(T) -> Unit, ): Job = launch { onEach(handle) } /** * Suspends until the next action matching the given [predicate] is dispatched, and returns that action. */ suspend fun next(predicate: (A) -> Boolean): A { val channel = actions.openSubscription() try { for (a in channel) { if (predicate(a)) { return a } } } finally { channel.cancel() } error("Actions channel closed before receiving a matching action") } /** * Suspends until the next action of type [T] is dispatched, and returns that action. */ suspend inline fun <reified T : A> next(): T = next { it is T } as T }
mit
8659374cf3a1a012687ac5b5c3d31053
29.07947
117
0.608542
4.363112
false
false
false
false
signed/intellij-community
platform/configuration-store-impl/src/StateMap.kt
1
7459
/* * Copyright 2000-2015 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.configurationStore import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.util.JDOMUtil import com.intellij.openapi.util.io.BufferExposingByteArrayOutputStream import com.intellij.openapi.util.text.StringUtil import com.intellij.util.ArrayUtil import com.intellij.util.SystemProperties import gnu.trove.THashMap import org.iq80.snappy.SnappyFramedInputStream import org.iq80.snappy.SnappyFramedOutputStream import org.jdom.Element import java.io.ByteArrayInputStream import java.util.* import java.util.concurrent.atomic.AtomicReferenceArray fun archiveState(state: Element): BufferExposingByteArrayOutputStream { val byteOut = BufferExposingByteArrayOutputStream() SnappyFramedOutputStream(byteOut).use { serializeElementToBinary(state, it) } return byteOut } private fun unarchiveState(state: ByteArray) = SnappyFramedInputStream(ByteArrayInputStream(state), false).use { readElement(it) } fun getNewByteIfDiffers(key: String, newState: Any, oldState: ByteArray): ByteArray? { val newBytes: ByteArray if (newState is Element) { val byteOut = archiveState(newState) if (arrayEquals(byteOut.internalBuffer, oldState, byteOut.size())) { return null } newBytes = ArrayUtil.realloc(byteOut.internalBuffer, byteOut.size()) } else { newBytes = newState as ByteArray if (Arrays.equals(newBytes, oldState)) { return null } } val logChangedComponents = SystemProperties.getBooleanProperty("idea.log.changed.components", false) if (ApplicationManager.getApplication().isUnitTestMode || logChangedComponents ) { fun stateToString(state: Any) = JDOMUtil.write(state as? Element ?: unarchiveState(state as ByteArray), "\n") val before = stateToString(oldState) val after = stateToString(newState) if (before == after) { throw IllegalStateException("$key serialization error - serialized are different, but unserialized are equal") } else if (logChangedComponents) { LOG.info("$key ${StringUtil.repeat("=", 80 - key.length)}\nBefore:\n$before\nAfter:\n$after") } } return newBytes } fun stateToElement(key: String, state: Any?, newLiveStates: Map<String, Element>? = null): Element? { if (state is Element) { return state.clone() } else { return newLiveStates?.get(key) ?: (state as? ByteArray)?.let(::unarchiveState) } } class StateMap private constructor(private val names: Array<String>, private val states: AtomicReferenceArray<Any?>) { override fun toString() = if (this == EMPTY) "EMPTY" else states.toString() companion object { val EMPTY = StateMap(emptyArray(), AtomicReferenceArray(0)) fun fromMap(map: Map<String, Any>): StateMap { if (map.isEmpty()) { return EMPTY } val names = map.keys.toTypedArray() if (map !is TreeMap) { Arrays.sort(names) } val states = AtomicReferenceArray<Any?>(names.size) for (i in names.indices) { states.set(i, map[names[i]]) } return StateMap(names, states) } } fun toMutableMap(): MutableMap<String, Any> { val map = THashMap<String, Any>(names.size) for (i in names.indices) { map.put(names[i], states.get(i)) } return map } /** * Sorted by name. */ fun keys() = names fun get(key: String): Any? { val index = Arrays.binarySearch(names, key) return if (index < 0) null else states.get(index) } fun getElement(key: String, newLiveStates: Map<String, Element>? = null) = stateToElement(key, get(key), newLiveStates) fun isEmpty(): Boolean = names.isEmpty() fun hasState(key: String) = get(key) is Element fun hasStates(): Boolean { if (isEmpty()) { return false } for (i in names.indices) { if (states.get(i) is Element) { return true } } return false } fun compare(key: String, newStates: StateMap, diffs: MutableSet<String>) { val oldState = get(key) val newState = newStates.get(key) if (oldState is Element) { if (!JDOMUtil.areElementsEqual(oldState as Element?, newState as Element?)) { diffs.add(key) } } else if (oldState == null) { if (newState != null) { diffs.add(key) } } else if (newState == null || getNewByteIfDiffers(key, newState, oldState as ByteArray) != null) { diffs.add(key) } } fun getState(key: String, archive: Boolean = false): Element? { val index = Arrays.binarySearch(names, key) if (index < 0) { return null } val state = states.get(index) as? Element ?: return null if (!archive) { return state } return if (states.compareAndSet(index, state, archiveState(state).toByteArray())) state else getState(key, true) } fun archive(key: String, state: Element?) { val index = Arrays.binarySearch(names, key) if (index < 0) { return } states.set(index, state?.let { archiveState(state).toByteArray() }) } } fun setStateAndCloneIfNeed(key: String, newState: Element?, oldStates: StateMap, newLiveStates: MutableMap<String, Element>? = null): MutableMap<String, Any>? { val oldState = oldStates.get(key) if (newState == null || JDOMUtil.isEmpty(newState)) { if (oldState == null) { return null } val newStates = oldStates.toMutableMap() newStates.remove(key) return newStates } newLiveStates?.put(key, newState) var newBytes: ByteArray? = null if (oldState is Element) { if (JDOMUtil.areElementsEqual(oldState as Element?, newState)) { return null } } else if (oldState != null) { newBytes = getNewByteIfDiffers(key, newState, oldState as ByteArray) ?: return null } val newStates = oldStates.toMutableMap() newStates.put(key, newBytes ?: newState) return newStates } // true if updated (not equals to previous state) internal fun updateState(states: MutableMap<String, Any>, key: String, newState: Element?, newLiveStates: MutableMap<String, Element>? = null): Boolean { if (newState == null || JDOMUtil.isEmpty(newState)) { states.remove(key) return true } newLiveStates?.put(key, newState) val oldState = states.get(key) var newBytes: ByteArray? = null if (oldState is Element) { if (JDOMUtil.areElementsEqual(oldState as Element?, newState)) { return false } } else if (oldState != null) { newBytes = getNewByteIfDiffers(key, newState, oldState as ByteArray) ?: return false } states.put(key, newBytes ?: newState) return true } private fun arrayEquals(a: ByteArray, a2: ByteArray, aSize: Int = a.size): Boolean { if (a === a2) { return true } val length = aSize if (a2.size != length) { return false } for (i in 0..length - 1) { if (a[i] != a2[i]) { return false } } return true }
apache-2.0
9724c18bfd3480bb36ce24f82dc8ae05
28.027237
160
0.681459
3.946561
false
false
false
false
NoodleMage/tachiyomi
app/src/main/java/eu/kanade/tachiyomi/extension/api/ExtensionGithubApi.kt
4
1928
package eu.kanade.tachiyomi.extension.api import com.github.salomonbrys.kotson.fromJson import com.github.salomonbrys.kotson.get import com.github.salomonbrys.kotson.int import com.github.salomonbrys.kotson.string import com.google.gson.Gson import com.google.gson.JsonArray import eu.kanade.tachiyomi.extension.model.Extension import eu.kanade.tachiyomi.network.GET import eu.kanade.tachiyomi.network.NetworkHelper import eu.kanade.tachiyomi.network.asObservableSuccess import okhttp3.Response import rx.Observable import uy.kohesive.injekt.injectLazy internal class ExtensionGithubApi { private val network: NetworkHelper by injectLazy() private val client get() = network.client private val gson: Gson by injectLazy() private val repoUrl = "https://raw.githubusercontent.com/inorichi/tachiyomi-extensions/repo" fun findExtensions(): Observable<List<Extension.Available>> { val call = GET("$repoUrl/index.json") return client.newCall(call).asObservableSuccess() .map(::parseResponse) } private fun parseResponse(response: Response): List<Extension.Available> { val text = response.body()?.use { it.string() } ?: return emptyList() val json = gson.fromJson<JsonArray>(text) return json.map { element -> val name = element["name"].string.substringAfter("Tachiyomi: ") val pkgName = element["pkg"].string val apkName = element["apk"].string val versionName = element["version"].string val versionCode = element["code"].int val lang = element["lang"].string val icon = "$repoUrl/icon/${apkName.replace(".apk", ".png")}" Extension.Available(name, pkgName, versionName, versionCode, lang, apkName, icon) } } fun getApkUrl(extension: Extension.Available): String { return "$repoUrl/apk/${extension.apkName}" } }
apache-2.0
6c6b22eabc33db46a129045cb2ab8efe
34.054545
96
0.697614
4.422018
false
false
false
false
cketti/okhttp
okhttp/src/test/java/okhttp3/MultipartReaderTest.kt
1
13890
/* * Copyright (C) 2020 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 import java.io.EOFException import java.net.ProtocolException import okhttp3.Headers.Companion.headersOf import okhttp3.MediaType.Companion.toMediaType import okhttp3.RequestBody.Companion.toRequestBody import okhttp3.ResponseBody.Companion.toResponseBody import okio.Buffer import org.assertj.core.api.Assertions.assertThat import org.junit.Assert.fail import org.junit.Test class MultipartReaderTest { @Test fun `parse multipart`() { val multipart = """ |--simple boundary |Content-Type: text/plain; charset=utf-8 |Content-ID: abc | |abcd |efgh |--simple boundary |Content-Type: text/plain; charset=utf-8 |Content-ID: ijk | |ijkl |mnop | |--simple boundary-- """.trimMargin() .replace("\n", "\r\n") val parts = MultipartReader( boundary = "simple boundary", source = Buffer().writeUtf8(multipart) ) assertThat(parts.boundary).isEqualTo("simple boundary") val partAbc = parts.nextPart()!! assertThat(partAbc.headers).isEqualTo(headersOf( "Content-Type", "text/plain; charset=utf-8", "Content-ID", "abc" )) assertThat(partAbc.body.readUtf8()).isEqualTo("abcd\r\nefgh") val partIjk = parts.nextPart()!! assertThat(partIjk.headers).isEqualTo(headersOf( "Content-Type", "text/plain; charset=utf-8", "Content-ID", "ijk" )) assertThat(partIjk.body.readUtf8()).isEqualTo("ijkl\r\nmnop\r\n") assertThat(parts.nextPart()).isNull() } @Test fun `parse from response body`() { val multipart = """ |--simple boundary | |abcd |--simple boundary-- """.trimMargin() .replace("\n", "\r\n") val responseBody = multipart.toResponseBody( "application/multipart; boundary=\"simple boundary\"".toMediaType()) val parts = MultipartReader(responseBody) assertThat(parts.boundary).isEqualTo("simple boundary") val part = parts.nextPart()!! assertThat(part.body.readUtf8()).isEqualTo("abcd") assertThat(parts.nextPart()).isNull() } @Test fun `truncated multipart`() { val multipart = """ |--simple boundary | |abcd |efgh |""".trimMargin() .replace("\n", "\r\n") val parts = MultipartReader( boundary = "simple boundary", source = Buffer().writeUtf8(multipart) ) val part = parts.nextPart()!! try { assertThat(part.body.readUtf8()).isEqualTo("abcd\r\nefgh\r\n") fail() } catch (expected: EOFException) { } try { assertThat(parts.nextPart()).isNull() fail() } catch (expected: EOFException) { } } @Test fun `malformed headers`() { val multipart = """ |--simple boundary |abcd |""".trimMargin() .replace("\n", "\r\n") val parts = MultipartReader( boundary = "simple boundary", source = Buffer().writeUtf8(multipart) ) try { parts.nextPart() fail() } catch (expected: EOFException) { } } @Test fun `lf instead of crlf boundary is not honored`() { val multipart = """ |--simple boundary | |abcd |--simple boundary | |efgh |--simple boundary-- """.trimMargin() .replace("\n", "\r\n") .replace(Regex("(?m)abcd\r\n"), "abcd\n") val parts = MultipartReader( boundary = "simple boundary", source = Buffer().writeUtf8(multipart) ) val part = parts.nextPart()!! assertThat(part.body.readUtf8()).isEqualTo("abcd\n--simple boundary\r\n\r\nefgh") assertThat(parts.nextPart()).isNull() } @Test fun `partial boundary is not honored`() { val multipart = """ |--simple boundary | |abcd |--simple boundar | |efgh |--simple boundary-- """.trimMargin() .replace("\n", "\r\n") val parts = MultipartReader( boundary = "simple boundary", source = Buffer().writeUtf8(multipart) ) val part = parts.nextPart()!! assertThat(part.body.readUtf8()).isEqualTo("abcd\r\n--simple boundar\r\n\r\nefgh") assertThat(parts.nextPart()).isNull() } @Test fun `do not need to read entire part`() { val multipart = """ |--simple boundary | |abcd |efgh |ijkl |--simple boundary | |mnop |--simple boundary-- """.trimMargin() .replace("\n", "\r\n") val parts = MultipartReader( boundary = "simple boundary", source = Buffer().writeUtf8(multipart) ) parts.nextPart()!! val partMno = parts.nextPart()!! assertThat(partMno.body.readUtf8()).isEqualTo("mnop") assertThat(parts.nextPart()).isNull() } @Test fun `cannot read part after calling nextPart`() { val multipart = """ |--simple boundary | |abcd |efgh |ijkl |--simple boundary | |mnop |--simple boundary-- """.trimMargin() .replace("\n", "\r\n") val parts = MultipartReader( boundary = "simple boundary", source = Buffer().writeUtf8(multipart) ) val partAbc = parts.nextPart()!! val partMno = parts.nextPart()!! try { partAbc.body.request(20) fail() } catch (e: IllegalStateException) { assertThat(e).hasMessage("closed") } assertThat(partMno.body.readUtf8()).isEqualTo("mnop") assertThat(parts.nextPart()).isNull() } @Test fun `cannot read part after calling close`() { val multipart = """ |--simple boundary | |abcd |--simple boundary-- """.trimMargin() .replace("\n", "\r\n") val parts = MultipartReader( boundary = "simple boundary", source = Buffer().writeUtf8(multipart) ) val part = parts.nextPart()!! parts.close() try { part.body.request(10) fail() } catch (e: IllegalStateException) { assertThat(e).hasMessage("closed") } } @Test fun `cannot call nextPart after calling close`() { val parts = MultipartReader( boundary = "simple boundary", source = Buffer() ) parts.close() try { parts.nextPart() fail() } catch (e: IllegalStateException) { assertThat(e).hasMessage("closed") } } @Test fun `zero parts`() { val multipart = """ |--simple boundary-- """.trimMargin() .replace("\n", "\r\n") val parts = MultipartReader( boundary = "simple boundary", source = Buffer().writeUtf8(multipart) ) try { parts.nextPart() fail() } catch (expected: ProtocolException) { assertThat(expected).hasMessage("expected at least 1 part") } } @Test fun `skip preamble`() { val multipart = """ |this is the preamble! it is invisible to application code | |--simple boundary | |abcd |--simple boundary-- """.trimMargin() .replace("\n", "\r\n") val parts = MultipartReader( boundary = "simple boundary", source = Buffer().writeUtf8(multipart) ) val part = parts.nextPart()!! assertThat(part.headers).isEqualTo(headersOf()) assertThat(part.body.readUtf8()).isEqualTo("abcd") assertThat(parts.nextPart()).isNull() } @Test fun `skip epilogue`() { val multipart = """ |--simple boundary | |abcd |--simple boundary-- |this is the epilogue! it is also invisible to application code |""".trimMargin() .replace("\n", "\r\n") val parts = MultipartReader( boundary = "simple boundary", source = Buffer().writeUtf8(multipart) ) val part = parts.nextPart()!! assertThat(part.headers).isEqualTo(headersOf()) assertThat(part.body.readUtf8()).isEqualTo("abcd") assertThat(parts.nextPart()).isNull() } @Test fun `skip whitespace after boundary`() { val multipart = """ |--simple boundary | |abcd |--simple boundary-- """.trimMargin() .replace(Regex("(?m)simple boundary$"), "simple boundary \t \t") .replace("\n", "\r\n") val parts = MultipartReader( boundary = "simple boundary", source = Buffer().writeUtf8(multipart) ) val part = parts.nextPart()!! assertThat(part.headers).isEqualTo(headersOf()) assertThat(part.body.readUtf8()).isEqualTo("abcd") assertThat(parts.nextPart()).isNull() } @Test fun `skip whitespace after close delimiter`() { val multipart = """ |--simple boundary | |abcd |--simple boundary-- """.trimMargin() .replace(Regex("(?m)simple boundary--$"), "simple boundary-- \t \t") .replace("\n", "\r\n") val parts = MultipartReader( boundary = "simple boundary", source = Buffer().writeUtf8(multipart) ) val part = parts.nextPart()!! assertThat(part.headers).isEqualTo(headersOf()) assertThat(part.body.readUtf8()).isEqualTo("abcd") assertThat(parts.nextPart()).isNull() } @Test fun `other characters after boundary`() { val multipart = """ |--simple boundary hi """.trimMargin() .replace(Regex("(?m)simple boundary$"), "simple boundary ") .replace("\n", "\r\n") val parts = MultipartReader( boundary = "simple boundary", source = Buffer().writeUtf8(multipart) ) try { parts.nextPart() fail() } catch (expected: ProtocolException) { assertThat(expected).hasMessage("unexpected characters after boundary") } } @Test fun `whitespace before close delimiter`() { val multipart = """ |--simple boundary | |abcd |--simple boundary -- """.trimMargin() .replace("\n", "\r\n") val parts = MultipartReader( boundary = "simple boundary", source = Buffer().writeUtf8(multipart) ) parts.nextPart() try { parts.nextPart() fail() } catch (expected: ProtocolException) { assertThat(expected).hasMessage("unexpected characters after boundary") } } /** The documentation advises that '-' is the simplest boundary possible. */ @Test fun `dash boundary`() { val multipart = """ |--- |Content-ID: abc | |abcd |--- |Content-ID: efg | |efgh |----- """.trimMargin() .replace("\n", "\r\n") val parts = MultipartReader( boundary = "-", source = Buffer().writeUtf8(multipart) ) val partAbc = parts.nextPart()!! assertThat(partAbc.headers).isEqualTo(headersOf("Content-ID", "abc")) assertThat(partAbc.body.readUtf8()).isEqualTo("abcd") val partEfg = parts.nextPart()!! assertThat(partEfg.headers).isEqualTo(headersOf("Content-ID", "efg")) assertThat(partEfg.body.readUtf8()).isEqualTo("efgh") assertThat(parts.nextPart()).isNull() } @Test fun `no more parts is idempotent`() { val multipart = """ |--simple boundary | |abcd |--simple boundary-- | |efgh |--simple boundary-- """.trimMargin() .replace("\n", "\r\n") val parts = MultipartReader( boundary = "simple boundary", source = Buffer().writeUtf8(multipart) ) assertThat(parts.nextPart()).isNotNull() assertThat(parts.nextPart()).isNull() assertThat(parts.nextPart()).isNull() } @Test fun `empty source`() { val parts = MultipartReader( boundary = "simple boundary", source = Buffer() ) try { parts.nextPart() fail() } catch (expected: EOFException) { } } /** Confirm that [MultipartBody] and [MultipartReader] can work together. */ @Test fun `multipart round trip`() { val body = MultipartBody.Builder("boundary") .setType(MultipartBody.PARALLEL) .addPart("Quick".toRequestBody("text/plain".toMediaType())) .addFormDataPart("color", "Brown") .addFormDataPart("animal", "fox.txt", "Fox".toRequestBody()) .build() val bodyContent = Buffer() body.writeTo(bodyContent) val reader = MultipartReader(bodyContent, "boundary") val quickPart = reader.nextPart()!! assertThat(quickPart.headers).isEqualTo(headersOf( "Content-Type", "text/plain; charset=utf-8", "Content-Length", "5" )) assertThat(quickPart.body.readUtf8()).isEqualTo("Quick") val brownPart = reader.nextPart()!! assertThat(brownPart.headers).isEqualTo(headersOf( "Content-Disposition", "form-data; name=\"color\"", "Content-Length", "5" )) assertThat(brownPart.body.readUtf8()).isEqualTo("Brown") val foxPart = reader.nextPart()!! assertThat(foxPart.headers).isEqualTo(headersOf( "Content-Disposition", "form-data; name=\"animal\"; filename=\"fox.txt\"", "Content-Length", "3" )) assertThat(foxPart.body.readUtf8()).isEqualTo("Fox") assertThat(reader.nextPart()).isNull() } }
apache-2.0
ff633eba3d544ac1a861649cc477e9ec
24.674677
86
0.581641
4.24511
false
false
false
false
christophpickl/gadsu
src/main/kotlin/at/cpickl/gadsu/view/logic/doubleclick.kt
1
2008
package at.cpickl.gadsu.view.logic import at.cpickl.gadsu.global.GadsuException import at.cpickl.gadsu.view.components.MyTable import at.cpickl.gadsu.view.swing.elementAtPoint import at.cpickl.gadsu.view.swing.log import java.awt.event.InputEvent import java.awt.event.MouseAdapter import java.awt.event.MouseEvent import javax.swing.JList fun <E> JList<E>.registerDoubleClicked(listener: (Int, E) -> Unit) { val list = this addMouseListener(object : DoubleClickMouseListener() { override fun mouseDoubleClicked(event: MouseEvent) { val (row, entity) = elementAtPoint(event.point) ?: throw GadsuException("Impossible view state! Could not find element at point: ${event.point} (this: $list)") log.debug("List row at index {} double clicked: {}", row, entity) listener.invoke(row, entity) } }) } fun <E> MyTable<E>.registerDoubleClicked(listener: (Int, E) -> Unit) { val table = this addMouseListener(object : DoubleClickMouseListener() { override fun mouseDoubleClicked(event: MouseEvent) { val (row, entity) = elementAtPoint(event.point) ?: throw GadsuException("Impossible view state! Could not find element at point: ${event.point} (this: $table)") log.debug("Table row at index {} double clicked: {}", row, entity) listener.invoke(row, entity) } }) } abstract class DoubleClickMouseListener() : MouseAdapter() { private var previousWasRight = false abstract fun mouseDoubleClicked(event: MouseEvent) override fun mousePressed(event: MouseEvent) { if (!isProperDoubleClick(event)) return mouseDoubleClicked(event) } private fun isProperDoubleClick(event: MouseEvent): Boolean { val isRightButton = (event.modifiers and InputEvent.BUTTON3_MASK) == InputEvent.BUTTON3_MASK val result = event.clickCount == 2 && !previousWasRight && !isRightButton previousWasRight = isRightButton return result } }
apache-2.0
4f3858a5f7c9852be11453a1c80740a3
37.615385
172
0.695717
4.245243
false
false
false
false
kotlintest/kotlintest
kotest-core/src/commonMain/kotlin/io/kotest/core/spec/style/shouldSpec.kt
1
1699
package io.kotest.core.spec.style import io.kotest.core.config.Project import io.kotest.core.factory.TestFactory import io.kotest.core.factory.TestFactoryConfiguration import io.kotest.core.factory.build import io.kotest.core.spec.Spec import io.kotest.core.test.TestCaseConfig import io.kotest.matchers.Matcher import io.kotest.matchers.should as shouldBeMatcher /** * Creates a [TestFactory] from the given block. * * The receiver of the block is a [ShouldSpecTestFactoryConfiguration] which allows tests * to be defined using the 'should-spec' style. * * Example: * * "some test" { * "with context" { * should("do something") { * // test here * } * } * } * * or * * should("do something") { * // test here * } */ fun shouldSpec(block: ShouldSpecTestFactoryConfiguration.() -> Unit): TestFactory { val config = ShouldSpecTestFactoryConfiguration() config.block() return config.build() } class ShouldSpecTestFactoryConfiguration : TestFactoryConfiguration(), ShouldSpecDsl { override fun defaultConfig(): TestCaseConfig = defaultTestConfig ?: Project.testCaseConfig() override val addTest = ::addDynamicTest } abstract class ShouldSpec(body: ShouldSpec.() -> Unit = {}) : Spec(), ShouldSpecDsl { override fun defaultConfig(): TestCaseConfig = defaultTestConfig ?: defaultTestCaseConfig() ?: Project.testCaseConfig() override val addTest = ::addRootTestCase init { body() } // need to overload this so that when doing "string" should haveLength(5) in a word spec, we don't // clash with the other should method infix fun String.should(matcher: Matcher<String>) = this shouldBeMatcher matcher }
apache-2.0
78f551c379a3199a338e55b8aed7f66b
28.293103
101
0.716892
4.164216
false
true
false
false
jiangkang/KTools
app/src/main/java/com/jiangkang/ktools/effect/fragment/ShapePathViewFragment.kt
1
1640
package com.jiangkang.ktools.effect.fragment import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.fragment.app.Fragment import com.jiangkang.ktools.databinding.FragmentShapePathViewBinding import com.jiangkang.tools.extend.addOnChangeListener /** * 利用Path 绘图 */ class ShapePathViewFragment : Fragment() { private var _binding:FragmentShapePathViewBinding? = null private val binding get() = _binding!! override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { // Inflate the layout for this fragment _binding = FragmentShapePathViewBinding.inflate(layoutInflater,container, false) return binding.root } override fun onDestroyView() { super.onDestroyView() _binding = null } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) binding.seekBarSides.addOnChangeListener( onProgressChanged = { _, progress, _ -> binding.shapePathView.post { binding.shapePathView.updateSides(sides = progress) } } ) binding.seekBarProgress.addOnChangeListener( onProgressChanged = { _, progress, _ -> binding.shapePathView.post { binding.shapePathView.updateProgress(progress = progress.toFloat()) } } ) } }
mit
313031aea0b191b47a1f50bc810de833
29.222222
91
0.634804
5.164557
false
false
false
false
PizzaGames/emulio
core/src/main/com/github/emulio/runners/PlatformReader.kt
1
1879
package com.github.emulio.runners import com.github.emulio.Emulio import com.github.emulio.exceptions.ConfigNotFoundException import com.github.emulio.model.Platform import com.github.emulio.yaml.PlatformConfigYaml import mu.KotlinLogging import java.io.* class PlatformReader(val emulio: Emulio) : Function0<List<Platform>> { val logger = KotlinLogging.logger { } override fun invoke(): List<Platform> { val platformsFile = emulio.options.platformsFile logger.info { "Reading platforms file: ${platformsFile.absolutePath}" } if (!platformsFile.exists()) { logger.info { "Platforms file not found, initializing PlatformWizard" } createTemplateFileWizard(platformsFile) return emptyList() } return PlatformConfigYaml.read(platformsFile) } private fun createTemplateFileWizard(platformsFile: File) { val template = Emulio::class.java.getResourceAsStream("/initialsetup/emulio-platforms-template.yaml") val templateName = "${platformsFile.nameWithoutExtension}-template.yaml" val templateFile = File(platformsFile.parentFile, templateName) logger.debug { "Creating template file: ${templateFile.absolutePath}" } try { BufferedWriter(FileWriter(templateFile)).use { writer -> InputStreamReader(template).forEachLine { line -> writer.write(line) writer.newLine() } writer.flush() } } catch (e: IOException) { error("Error writing ${templateFile.absolutePath}. Check your permissions in this folder.") } throw ConfigNotFoundException("${platformsFile.canonicalPath} not found, a template ('${templateFile.name}') \n " + "file was created so you can change and rename it.") } }
gpl-3.0
ac0645c3ac33c9a72ac6e3917d5b4b24
36.58
123
0.664183
4.867876
false
true
false
false
Magneticraft-Team/Magneticraft
ignore/test/misc/tileentity/TraitElectricity.kt
2
13616
package misc.tileentity import com.cout970.magneticraft.api.energy.* import com.cout970.magneticraft.api.internal.energy.ElectricConnection import com.cout970.magneticraft.misc.energy.UnloadedElectricConnection import com.cout970.magneticraft.misc.world.isServer import com.cout970.magneticraft.registry.ELECTRIC_NODE_HANDLER import com.cout970.magneticraft.registry.fromTile import com.cout970.magneticraft.tileentity.TileBase import com.cout970.magneticraft.util.* import com.cout970.magneticraft.util.vector.length import com.cout970.magneticraft.util.vector.minus import com.cout970.magneticraft.util.vector.plus import com.google.common.base.Predicate import net.minecraft.nbt.NBTTagCompound import net.minecraft.tileentity.TileEntity import net.minecraft.util.EnumFacing import net.minecraft.util.math.BlockPos import net.minecraft.util.math.Vec3i import net.minecraft.world.World import net.minecraftforge.common.capabilities.Capability /** * Created by cout970 on 2017/02/26. */ class TraitElectricity( tile: TileBase, //all connectors val electricNodes: List<IElectricNode>, val canConnectAtSideImpl: (EnumFacing?) -> Boolean = { true }, val onWireChangeImpl: (EnumFacing?) -> Unit = {}, val onUpdateConnections: () -> Unit = {}, val canConnectImpl: (TraitElectricity, IElectricNode, IElectricNodeHandler, IElectricNode, EnumFacing?) -> Boolean = TraitElectricity::defaultCanConnectImpl, val maxWireDistance: Double = 16.0 ) : TileTrait(tile), IElectricNodeHandler { val inputNormalConnections = mutableListOf<IElectricConnection>() val outputNormalConnections = mutableListOf<IElectricConnection>() val inputWiredConnections = mutableListOf<IElectricConnection>() val outputWiredConnections = mutableListOf<IElectricConnection>() val unloadedConnections = mutableListOf<UnloadedElectricConnection>() private var firstTicks = 0 var autoConnectWires = false override fun update() { if (tile.shouldTick(40)) { updateConnections() } resolveUnloadedConnections() if (world.isServer) { //update to sync connections every 20 seconds if (tile.shouldTick(400)) { tile.sendUpdateToNearPlayers() } // when the world is loaded the player take some ticks to // load so this wait for the player to send an update if (firstTicks > 0) { firstTicks-- if (firstTicks % 20 == 0) { tile.sendUpdateToNearPlayers() } } iterate() } } fun iterate() { outputNormalConnections.forEach(IElectricConnection::iterate) outputWiredConnections.forEach(IElectricConnection::iterate) } fun resolveUnloadedConnections() { if (!unloadedConnections.isEmpty()) { val iterator = unloadedConnections.iterator() while (iterator.hasNext()) { val con = iterator.next() if (con.create(world, this)) { iterator.remove() } } if (world.isServer) { firstTicks = 60 } else { onWireChange(null) } } } fun updateConnections() { clearNormalConnections() for (thisNode in nodes.filter { it is IElectricNode }.map { it as IElectricNode }) { loop@ for (dir in NEGATIVE_DIRECTIONS) { val tile = world.getTileEntity(thisNode.pos.offset(dir)) ?: continue@loop if (tile === this.tile) continue@loop val handler = ELECTRIC_NODE_HANDLER!!.fromTile(tile, dir.opposite) as? IElectricNodeHandler ?: continue@loop for (otherNode in handler.nodes.filter { it is IElectricNode }.map { it as IElectricNode }) { if (this.canConnect(thisNode, handler, otherNode, dir) && handler.canConnect(otherNode, this, thisNode, dir.opposite)) { val connection = ElectricConnection(thisNode, otherNode) this.addConnection(connection, dir, true) handler.addConnection(connection, dir.opposite, false) } } } } updateWiredConnections() } fun updateWiredConnections() { onUpdateConnections() if (autoConnectWires) { val size = Vec3i(16, 5, 16) autoConnectWires(tile, this, world, pos - size, pos + size) } onWireChange(null) //remove invalid nodes in wiredConnections val iterator = outputWiredConnections.iterator() while (iterator.hasNext()) { val i = iterator.next() val handler = getHandler(i.secondNode) if (handler == null || !handler.nodes.contains(i.secondNode)) { iterator.remove() continue } } } fun clearNormalConnections() { val iterator = outputNormalConnections.iterator() while (iterator.hasNext()) { val con = iterator.next() val handler = getHandler(con.secondNode) handler?.removeConnection(con) iterator.remove() } } fun clearWireConnections() { val iterator = outputWiredConnections.iterator() while (iterator.hasNext()) { val con = iterator.next() val handler = getHandler(con.secondNode) handler?.removeConnection(con) iterator.remove() } } override fun canConnect(thisNode: IElectricNode, other: IElectricNodeHandler, otherNode: IElectricNode, side: EnumFacing?): Boolean = canConnectImpl(this, thisNode, other, otherNode, side) fun defaultCanConnectImpl(thisNode: IElectricNode, other: IElectricNodeHandler, otherNode: IElectricNode, side: EnumFacing?): Boolean { if (other == this || otherNode == thisNode) return false if (!canConnectAtSideImpl(side)) return false if (side == null) { if (thisNode !is IWireConnector || otherNode !is IWireConnector) return false if (thisNode.connectorsSize != otherNode.connectorsSize) return false if (inputWiredConnections.any { it.firstNode == otherNode }) { return false } if (outputWiredConnections.any { it.secondNode == otherNode }) { return false } val distance = (thisNode.pos - otherNode.pos).length if (distance > maxWireDistance) { return false } } return true } override fun addConnection(connection: IElectricConnection, side: EnumFacing?, output: Boolean) { if (side == null) { if (output) { outputWiredConnections.add(connection) } else { inputWiredConnections.add(connection) } } else { if (output) { outputNormalConnections.add(connection) } else { inputNormalConnections.add(connection) } } onWireChange(side) } override fun removeConnection(connection: IElectricConnection) { inputNormalConnections.remove(connection) outputNormalConnections.remove(connection) inputWiredConnections.remove(connection) outputWiredConnections.remove(connection) onWireChange(null) } fun onWireChange(side: EnumFacing?) = onWireChangeImpl(side) override fun onBreak() { super.onBreak() clearNormalConnections() clearWireConnections() this.let { val iterator = inputNormalConnections.iterator() while (iterator.hasNext()) { val con = iterator.next() val handler = getHandler(con.firstNode) handler?.removeConnection(con) iterator.remove() } } val iterator = inputWiredConnections.iterator() while (iterator.hasNext()) { val con = iterator.next() val handler = getHandler(con.firstNode) handler?.removeConnection(con) iterator.remove() } } override fun getNodes(): MutableList<INode> = electricNodes.toMutableList() override fun getInputConnections(): MutableList<IElectricConnection> { return inputNormalConnections with inputWiredConnections } override fun getOutputConnections(): MutableList<IElectricConnection> { return outputNormalConnections with outputWiredConnections } override fun deserialize(nbt: NBTTagCompound) { nbt.readList("ElectricNodes") { nodeList -> nodes.forEachIndexed { index, node -> node.deserializeNBT(nodeList.getTagCompound(index)) } } nbt.readList("ElectricConnections") { connectionList -> connectionList.forEach { unloadedConnections += UnloadedElectricConnection.load(it) } } } override fun serialize(): NBTTagCompound? { return newNbt { list("ElectricNodes") { nodes.forEach { appendTag(it.serializeNBT()) } } list("ElectricConnections") { for (i in outputWiredConnections) { appendTag(UnloadedElectricConnection.save(i)) } unloadedConnections .filter { it.isValid } .forEach { appendTag(UnloadedElectricConnection.save(it)) } } } } override fun hasCapability(capability: Capability<*>, enumFacing: EnumFacing?): Boolean { return capability == ELECTRIC_NODE_HANDLER } @Suppress("UNCHECKED_CAST") override fun <T : Any?> getCapability(capability: Capability<T>, enumFacing: EnumFacing?): T { return this as T } companion object { val NEGATIVE_DIRECTIONS = EnumFacing.values().filter { it.axisDirection == EnumFacing.AxisDirection.NEGATIVE } fun autoConnectWires(tile: TileEntity, thisHandler: IElectricNodeHandler, world: World, start: BlockPos, end: BlockPos, filter: (IWireConnector, IWireConnector) -> Boolean = { _, _ -> true }) { val predicate: Predicate<TileEntity> = Predicate { it != tile } getTileEntitiesIn(world, start, end, predicate) .map { ELECTRIC_NODE_HANDLER!!.fromTile(it) } .filterIsInstance<IElectricNodeHandler>() .forEach { connectHandlers(thisHandler, it, filter) } } fun connectHandlers(first: IElectricNodeHandler, second: IElectricNodeHandler, filter: (IWireConnector, IWireConnector) -> Boolean = { _, _ -> true }): Boolean { var result = false for (firstNode in first.nodes.filter { it is IWireConnector }.map { it as IWireConnector }) { second.nodes .filterIsInstance<IWireConnector>() .filter { filter.invoke(firstNode, it) && connectNodes(first, firstNode, second, it) } .forEach { result = true } } return result } fun connectNodes(first: IElectricNodeHandler, firstNode: IWireConnector, second: IElectricNodeHandler, secondNode: IWireConnector): Boolean { if (first.canConnect(firstNode, second, secondNode, null) && second.canConnect(secondNode, first, firstNode, null)) { val connection = ElectricConnection(firstNode, secondNode) first.addConnection(connection, null, true) second.addConnection(connection, null, false) return true } return false } @Suppress("LoopToCallChain") fun getTileEntitiesIn(world: World, start: BlockPos, end: BlockPos, filter: Predicate<TileEntity>): List<TileEntity> { val list = mutableListOf<TileEntity>() for (x in start.x..end.x step 16) { for (z in start.z..end.z step 16) { val chunk = world.getChunkFromChunkCoords(x shr 4, z shr 4) for ((pos, tile) in chunk.tileEntityMap) { if (!tile.isInvalid && pos in (start to end) && filter.apply(tile)) { list.add(tile) } } } } return list } fun getHandler(node: IElectricNode): IElectricNodeHandler? { val tile = node.world.getTileEntity(node.pos) if (tile != null) { val handler = ELECTRIC_NODE_HANDLER!!.fromTile(tile) if (handler is IElectricNodeHandler) { return handler } } return null } operator fun Pair<BlockPos, BlockPos>.contains(pos: BlockPos): Boolean { return pos.x >= first.x && pos.x <= second.x && pos.y >= first.y && pos.y <= second.y && pos.z >= first.z && pos.z <= second.z } } }
gpl-2.0
213d35c869ca61396e8ac0f26c2e5c9c
37.575071
165
0.583872
4.845552
false
false
false
false
epabst/kotlin-showcase
src/jsMain/kotlin/bootstrap/AccordionToggle.kt
1
742
@file:Suppress("INTERFACE_WITH_SUPERCLASS", "OVERRIDING_FINAL_MEMBER", "RETURN_TYPE_MISMATCH_ON_OVERRIDE", "CONFLICTING_OVERLOADS", "EXTERNAL_DELEGATION", "unused") @file:JsModule("react-bootstrap") package bootstrap import react.RProps external interface AccordionToggleProps : RProps { var `as`: String var eventKey: String var onClick: ((event: React.SyntheticEvent? /* = null */) -> Unit)? get() = definedExternally; set(value) = definedExternally } external fun useAccordionToggle(eventKey: String, onClick: (event: React.SyntheticEvent? /* = null */) -> Unit): (event: React.SyntheticEvent? /* = null */) -> Unit abstract external class AccordionToggle<As : React.ElementType> : BsPrefixComponent<As, AccordionToggleProps>
apache-2.0
f986b31898fe7249883e803511bf7ae2
56.153846
164
0.743935
3.989247
false
false
false
false
sharaquss/todo
app/src/main/java/com/android/szparag/todoist/presenters/implementations/TodoistFrontPresenter.kt
1
5052
package com.android.szparag.todoist.presenters.implementations import com.android.szparag.todoist.events.AnimationEvent.AnimationEventType.END import com.android.szparag.todoist.models.contracts.FrontModel import com.android.szparag.todoist.models.entities.RenderDay import com.android.szparag.todoist.presenters.contracts.FrontPresenter import com.android.szparag.todoist.utils.ReactiveList.ReactiveChangeType.INSERTED import com.android.szparag.todoist.utils.ReactiveListEvent import com.android.szparag.todoist.utils.ui import com.android.szparag.todoist.views.contracts.FrontView import io.reactivex.rxkotlin.subscribeBy import javax.inject.Inject private const val FRONT_LIST_LOADING_THRESHOLD = 4 //todo: change to constructor injection //todo: model should be FrontModel (presenter's own Model), not CalendarModel (Model of given feature) //todo: refactor to interactor, or some fancy naming shit like that class TodoistFrontPresenter @Inject constructor(frontModel: FrontModel) : TodoistBasePresenter<FrontView, FrontModel>(frontModel), FrontPresenter { override fun attach(view: FrontView) { logger.debug("attach, view: $view") super.attach(view) } override fun onAttached() { logger.debug("onAttached") super.onAttached() } override fun onBeforeDetached() { logger.debug("onBeforeDetached") super.onBeforeDetached() } override fun onViewReady() { logger.debug("onViewReady") super.onViewReady() view?.animateShowBackgroundImage() ?.ui() ?.filter { (eventType) -> eventType == END } ?.flatMap { view?.animateShowQuote()?.ui() } ?.filter { (eventType) -> eventType == END } ?.flatMap { view?.animatePeekCalendar()?.ui() } //todo: in submodelevents ?.filter { (eventType) -> eventType == END } ?.subscribe() ?.toViewDisposable() view?.subscribeDayListScrolls() ?.ui() ?.doOnEach { scrollEvent -> logger.debug("view?.subscribeDayListScrolls.onNext, scrollEvent: $scrollEvent") } ?.map { checkIfListOutOfRange(it.firstVisibleItemPos, it.lastVisibleItemPos, it.lastItemOnListPos) } ?.doOnEach { logger.debug("after filtering, directionInt: $it") } ?.filter { direction -> direction != 0 } ?.doOnSubscribe { // model.loadDaysFromCalendar(true, 2) //todo this should be in subscribeModelsEvents or something // model.loadDaysFromCalendar(false, 2) //todo or on attaching model to presenter model.fetchInitialCalendarData(2) } ?.subscribeBy(onNext = { direction -> logger.debug("view?.subscribeDayListScrolls.onNext, direction: $direction") onUserReachedListLoadThreshold(direction) }, onComplete = { logger.debug("view?.subscribeDayListScrolls.onComplete") }) .toViewDisposable() } override fun onUserReachedListLoadThreshold(direction: Int) { model.loadDaysFromCalendar(weekForward = direction > 0, weeksCount = 2) } //todo: why this shit is here private fun checkIfListOutOfRange(firstVisibleItemPos: Int, lastVisibleItemPos: Int, lastItemOnListPos: Int): Int { return when { FRONT_LIST_LOADING_THRESHOLD >= firstVisibleItemPos -> -1 lastVisibleItemPos >= lastItemOnListPos - FRONT_LIST_LOADING_THRESHOLD -> 1 else -> 0 }.also { logger.info("checkIfListOutOfRange, RESULT: $it (start: 0, firstVisible: $firstVisibleItemPos, lastVisible: " + "$lastVisibleItemPos, last: $lastItemOnListPos)") } } private fun onNewItemsToCalendarLoaded(event: ReactiveListEvent<RenderDay>) { if (event.eventType == INSERTED) { view?.appendRenderDays(event.affectedItems, event.fromIndexInclusive, event.affectedItems.size) } } override fun subscribeModelEvents() { logger.debug("subscribeModelEvents") model.subscribeForDaysList() .ui() .doOnSubscribe { logger.debug("calendarModel.subscribeForDaysListData.onSubscribe") } .subscribeBy( onNext = { event -> logger.debug("calendarModel.subscribeForDaysListData.onNext, list: $event") onNewItemsToCalendarLoaded(event) }, onComplete = { logger.debug("calendarModel.subscribeForDaysListData.onComplete") } ) .toModelDisposable() } override fun subscribeViewUserEvents() { logger.debug("subscribeViewUserEvents") //todo debug only, remove view?.subscribeBackgroundClicked() ?.ui() ?.subscribe { view?.randomizeContents() } .toViewDisposable() view?.subscribeDayClicked() ?.ui() ?.doOnDispose { logger.warn("view?.subscribeDayClicked(), DISPOSED")} ?.subscribe { logger.debug("view?.subscribeDayClicked(), ondayClicked") dayClicked(it) } .toViewDisposable() } private fun dayClicked(dayUnixTimestamp: Long) { logger.debug("dayClicked: $dayUnixTimestamp") view?.goToDayScreen(dayUnixTimestamp) } }
mit
fb2d46335d0b7e2e7d665605a0888e21
36.708955
136
0.691409
4.35893
false
false
false
false
FredJul/TaskGame
TaskGame/src/main/java/net/fred/taskgame/activities/SnoozeActivity.kt
1
2908
/* * Copyright (c) 2012-2017 Frederic Julian * * 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:></http:>//www.gnu.org/licenses/>. */ package net.fred.taskgame.activities import android.app.NotificationManager import android.content.Context import android.content.Intent import android.os.Bundle import android.support.v4.app.FragmentActivity import net.fred.taskgame.listeners.OnReminderPickedListener import net.fred.taskgame.models.Task import net.fred.taskgame.utils.Constants import net.fred.taskgame.utils.DbUtils import net.fred.taskgame.utils.PrefUtils import net.fred.taskgame.utils.date.ReminderPickers import java.util.* class SnoozeActivity : FragmentActivity(), OnReminderPickedListener { private var task: Task? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) task = DbUtils.getTask(intent.extras.getString(Constants.EXTRA_TASK_ID)) // If an alarm has been fired a notification must be generated if (Constants.ACTION_DONE == intent.action) { task?.let { DbUtils.finishTaskAsync(it) } finish() } else if (Constants.ACTION_SNOOZE == intent.action) { val snoozeDelay = PrefUtils.getString(PrefUtils.PREF_SETTINGS_NOTIFICATION_SNOOZE_DELAY, "10") task!!.alarmDate = Calendar.getInstance().timeInMillis + Integer.parseInt(snoozeDelay) * 60 * 1000 task!!.setupReminderAlarm(this) finish() } else if (Constants.ACTION_POSTPONE == intent.action) { ReminderPickers(this, this).pick(task!!.alarmDate) } else { val intent = Intent(this, MainActivity::class.java) intent.putExtra(Constants.EXTRA_TASK_ID, task!!.id) intent.action = Constants.ACTION_NOTIFICATION_CLICK startActivity(intent) } removeNotification(task!!) } private fun removeNotification(task: Task) { val manager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager manager.cancel(task.id!!.hashCode()) } override fun onReminderPicked(reminder: Long) { task!!.alarmDate = reminder task!!.setupReminderAlarm(this) finish() } override fun onReminderDismissed() { finish() } }
gpl-3.0
62f10959f746a20fd3c2bdb1dbf91214
35.810127
110
0.695667
4.366366
false
false
false
false
dya-tel/TSU-Schedule
src/main/kotlin/ru/dyatel/tsuschedule/layout/WeekPage.kt
1
3108
package ru.dyatel.tsuschedule.layout import android.content.Context import android.support.v4.view.PagerAdapter import android.support.v7.widget.LinearLayoutManager import android.view.View import android.view.ViewGroup import com.mikepenz.fastadapter.FastAdapter import com.mikepenz.fastadapter.adapters.ItemAdapter import org.jetbrains.anko.bottomPadding import org.jetbrains.anko.matchParent import org.jetbrains.anko.recyclerview.v7.recyclerView import org.jetbrains.anko.topPadding import ru.dyatel.tsuschedule.NORMAL_WEEKDAY_ORDER import ru.dyatel.tsuschedule.model.Lesson import ru.dyatel.tsuschedule.model.Parity class WeekPage<T : Lesson>(val parity: Parity) { val adapter = ItemAdapter<WeekdayItem<T>>() private val fastAdapter: FastAdapter<WeekdayItem<T>> = FastAdapter.with(adapter) fun createView(context: Context): View { return context.recyclerView { lparams(width = matchParent, height = matchParent) { topPadding = DIM_CARD_VERTICAL_MARGIN bottomPadding = DIM_CARD_VERTICAL_MARGIN } clipToPadding = false layoutManager = LinearLayoutManager(context) descendantFocusability = ViewGroup.FOCUS_BLOCK_DESCENDANTS adapter = fastAdapter } } } class WeekDataContainer<T : Lesson>(private val viewProvider: (Context) -> LessonView<T>) { val oddWeek = WeekPage<T>(Parity.ODD) val evenWeek = WeekPage<T>(Parity.EVEN) fun updateData(lessons: List<T>) { val (odd, even) = lessons.partition { it.parity == Parity.ODD } oddWeek.adapter.set(generateWeekdays(odd)) evenWeek.adapter.set(generateWeekdays(even)) } private fun generateWeekdays(lessons: List<T>): List<WeekdayItem<T>> { return lessons .groupBy { it.weekday.toLowerCase() } .toList() .sortedBy { NORMAL_WEEKDAY_ORDER.indexOf(it.first) } .map { (weekday, lessons) -> WeekdayItem(weekday, lessons, viewProvider) } } } class WeekPagerAdapter<T : Lesson>(private val context: Context, data: WeekDataContainer<T>) : PagerAdapter() { private val pages = listOf(data.oddWeek, data.evenWeek) private val views = mutableMapOf<Parity, View>() override fun isViewFromObject(view: View, obj: Any) = views[obj] == view override fun getCount() = pages.size override fun instantiateItem(container: ViewGroup, position: Int): Parity { val page = pages[position] page.createView(context).let { views[page.parity] = it container.addView(it) } return page.parity } override fun destroyItem(container: ViewGroup, position: Int, obj: Any) { container.removeView(views.remove(obj as Parity)) } override fun getPageTitle(position: Int) = pages[position].parity.toText(context) fun getPosition(parity: Parity) = pages.indexOfFirst { it.parity == parity }.takeUnless { it == -1 } ?: throw IllegalArgumentException("No pages with parity <$parity> exist") }
mit
ddf3236d7b06adbd7576f43cce3976e4
33.533333
111
0.682111
4.222826
false
false
false
false
AM5800/polyglot
app/src/main/kotlin/com/am5800/polyglot/app/sentenceGeneration/russian/RussianSentenceGenerator.kt
1
3136
package com.am5800.polyglot.app.sentenceGeneration.russian import com.am5800.polyglot.app.sentenceGeneration.* import com.am5800.polyglot.app.sentenceGeneration.english.Pronoun class RussianSentenceGenerator : SentenceGenerator { private class VisitResult(val str: String, val propagatedWord: Word?) private class GeneratorVisitor(private val words: List<Word>) : GeneratorRuleSetVisitor<VisitResult, Word?> { private val auxWill = RussianVerb.define { infinitive("быть") future("буду", "будешь", "будем", "будете", "будет", "будет", "будет", "будут") } override fun visitLeaf(leafNode: LeafRuleNode, data: Word?): VisitResult { val tag = leafNode.tag if (tag is PronounTag) { val pronoun = words.single { it is Pronoun } as Pronoun return VisitResult(pronoun.value, pronoun) } if (tag is VerbTag) { val verbFlags = tag.verbTagFlags if (verbFlags.contains(VerbTagFlag.Infinitive)) { val verb = words.single { it is RussianVerb } as RussianVerb return VisitResult(verb.infinitive, verb) } if (verbFlags.contains(VerbTagFlag.Present) && data is Pronoun) { val verb = words.single { it is RussianVerb } as RussianVerb return VisitResult(verbFormFromPronoun(verb, data, RussianTime.Present), verb) } if (verbFlags.contains(VerbTagFlag.Future) && data is Pronoun) { return VisitResult(verbFormFromPronoun(auxWill, data, RussianTime.Future), auxWill) } if (verbFlags.contains(VerbTagFlag.Past) && data is Pronoun) { val verb = words.single { it is RussianVerb } as RussianVerb return VisitResult(verbFormFromPronoun(verb, data, RussianTime.Past), verb) } } throw UnsupportedOperationException() } private fun verbFormFromPronoun(verb: RussianVerb, pronoun: Pronoun, time: RussianTime): String { return verb.by(pronoun.number, pronoun.person, time, pronoun.gender) } override fun visitBinaryNode(binaryNode: BinaryNode, data: Word?): VisitResult { val left = binaryNode.left val right = binaryNode.right var leftResult: String? = null var rightResult: String? = null val headResult = if (binaryNode.head == Head.IsLeft) { val result = left.visit(this, null) leftResult = result.str result } else { val result = right.visit(this, null) rightResult = result.str result } val propagated = data ?: headResult.propagatedWord if (binaryNode.head == Head.IsLeft) rightResult = right.visit(this, propagated).str else leftResult = left.visit(this, propagated).str val str = binaryNode.format.replace("%0", leftResult!!).replace("%1", rightResult!!) return VisitResult(str, headResult.propagatedWord) } } override fun generate(rules: GeneratorRuleSet, words: List<Word>): String { return rules.visit(GeneratorVisitor(words), null).str } }
gpl-3.0
cc0678551b7a2fe98bfdd66bde5d2ec5
38.139241
111
0.657392
4.009079
false
false
false
false
asarkar/spring
pinterest-client/src/test/kotlin/org/abhijitsarkar/spring/pinterest/PinterestJsonFormatSpec.kt
1
2096
package org.abhijitsarkar.spring.pinterest import com.fasterxml.jackson.databind.ObjectMapper import com.fasterxml.jackson.module.kotlin.readValue import com.fasterxml.jackson.module.kotlin.registerKotlinModule import io.kotlintest.matchers.shouldBe import io.kotlintest.specs.ShouldSpec import org.abhijitsarkar.spring.pinterest.client.Pinterest.PinterestJsonFormat.CreateBoardResponse import org.abhijitsarkar.spring.pinterest.client.Pinterest.PinterestJsonFormat.CreatePinResponse import org.abhijitsarkar.spring.pinterest.client.Pinterest.PinterestJsonFormat.FindBoardResponse import org.abhijitsarkar.spring.pinterest.client.Pinterest.PinterestJsonFormat.FindUserResponse import org.abhijitsarkar.spring.pinterest.client.Pinterest.PinterestJsonFormat.ResponseWrapper /** * @author Abhijit Sarkar */ class PinterestJsonFormatSpec : ShouldSpec() { val mapper: ObjectMapper = ObjectMapper() .registerKotlinModule() init { should("deserialize find board response") { val json = javaClass.getResourceAsStream("/find-board.json") val board = mapper.readValue<ResponseWrapper<FindBoardResponse>>(json) board.data.name shouldBe "test" } should("deserialize find user response") { val json = javaClass.getResourceAsStream("/find-user.json") val user = mapper.readValue<ResponseWrapper<FindUserResponse>>(json) user.data.url shouldBe "https://www.pinterest.com/test/" } should("deserialize create board response") { val json = javaClass.getResourceAsStream("/create-board.json") val user = mapper.readValue<ResponseWrapper<CreateBoardResponse>>(json) user.data.url shouldBe "https://www.pinterest.com/test/test/" } should("deserialize create pin response") { val json = javaClass.getResourceAsStream("/create-pin.json") val user = mapper.readValue<ResponseWrapper<CreatePinResponse>>(json) user.data.url shouldBe "https://www.pinterest.com/pin/123/" } } }
gpl-3.0
6a4da98240717d6a1cfecd2a6c0d55ca
39.326923
98
0.729962
4.710112
false
true
false
false
GreaseMonk/android-timetable
timetable/src/main/java/nl/greasemonk/timetable/BasePlanView.kt
1
11713
/* * Copyright (c) 2018 . * This file is released under the Apache-2.0 license and part of the TimeTable repository located at: * https://github.com/greasemonk/android-timetable-core * See the "LICENSE" file at the root of the repository or go to the address below for the full license details. * https://github.com/GreaseMonk/android-timetable-core/blob/develop/LICENSE */ package nl.greasemonk.timetable import android.content.Context import android.graphics.Canvas import android.graphics.Color import android.graphics.Paint import android.graphics.Typeface import android.graphics.drawable.Drawable import android.graphics.drawable.ShapeDrawable import android.graphics.drawable.shapes.RoundRectShape import android.util.AttributeSet import android.view.View import nl.greasemonk.timetable.enums.PlanViewMode import nl.greasemonk.timetable.interfaces.IPlannable import nl.greasemonk.timetable.models.TimeRange import nl.greasemonk.timetable.planning.PlanningDelegate import java.util.* import java.util.concurrent.TimeUnit import kotlin.math.roundToInt internal open class BasePlanView: View { constructor(context: Context) : super(context) { this.init(context, null) } constructor(context: Context, attrs: AttributeSet?) : super(context, attrs) { this.init(context, attrs) } constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr) { this.init(context, attrs) } var delegate: PlanningDelegate? = null protected lateinit var planViewMode: PlanViewMode lateinit var displayedRange: TimeRange // Drawable vars protected lateinit var drawable: ShapeDrawable protected lateinit var arrowLeftDrawable: Drawable protected lateinit var arrowRightDrawable: Drawable // Paint vars protected lateinit var gridLinePaint: Paint protected lateinit var diagonalLinesPaint: Paint protected lateinit var barPaint: Paint protected lateinit var barStrokePaint: Paint protected lateinit var textPaint: Paint protected lateinit var arrowPaint: Paint protected lateinit var todayPaint: Paint /** * An array of 8 radius values, for the outer roundrect. * The first two floats are for the top-left corner (remaining pairs correspond clockwise). * For no rounded corners on the outer rectangle, pass null. * * @see [RoundRectShape](https://developer.android.com/reference/android/graphics/drawable/shapes/RoundRectShape.html) */ protected lateinit var radii: FloatArray protected var scaleWithMultiplierSetting = false protected var columnCount: Int = 0 protected var rowCount: Int = 0 // Amount of rows since getRowItems() was last called protected var defaultRowHeight: Float = 48f protected var desiredRowHeight: Float = 48f protected var desiredVerticalBarPadding = 10f protected var verticalBarPadding = 0f protected var barStrokeSize = 4f protected var scaledDensity: Float = 0f protected var arrowHeight: Float = 0f protected var arrowWidth: Float = 0f open fun init(context: Context, attrs: AttributeSet?) { scaledDensity = context.resources.displayMetrics.scaledDensity barStrokeSize = 4f * scaledDensity * PlanningModule.instance.preferredBarHeightMultiplier desiredRowHeight = defaultRowHeight * scaledDensity verticalBarPadding = scaledDensity * desiredVerticalBarPadding * PlanningModule.instance.preferredBarHeightMultiplier gridLinePaint = Paint() gridLinePaint.color = Color.GRAY gridLinePaint.alpha = 125 diagonalLinesPaint = Paint() diagonalLinesPaint.color = Color.WHITE diagonalLinesPaint.alpha = 125 diagonalLinesPaint.isAntiAlias = true todayPaint = Paint() todayPaint.color = Color.RED todayPaint.alpha = 125 todayPaint.style = Paint.Style.STROKE todayPaint.strokeWidth = 4f barPaint = Paint() barPaint.color = Color.BLUE barPaint.style = Paint.Style.FILL barPaint.isAntiAlias = true barStrokePaint = Paint() barStrokePaint.color = Color.WHITE barStrokePaint.style = Paint.Style.STROKE barStrokePaint.strokeWidth = barStrokeSize barStrokePaint.strokeCap = Paint.Cap.ROUND barStrokePaint.isAntiAlias = true arrowPaint = Paint() arrowPaint.color = Color.BLUE arrowPaint.style = Paint.Style.FILL arrowPaint.isAntiAlias = true val typeface = Typeface.create(Typeface.SANS_SERIF, Typeface.NORMAL) textPaint = Paint() textPaint.color = Color.WHITE textPaint.textSize = scaledDensity * 12 textPaint.textAlign = Paint.Align.CENTER textPaint.typeface = typeface textPaint.isAntiAlias = true initBarDrawable(4f) arrowLeftDrawable = context.resources.getDrawable(R.drawable.arrow_left, context.theme) arrowRightDrawable = context.resources.getDrawable(R.drawable.arrow_right, context.theme) arrowHeight = scaledDensity * 12f arrowWidth = scaledDensity * 6f planViewMode = PlanningModule.instance.mode columnCount = when(planViewMode) { PlanViewMode.WEEK -> 7 PlanViewMode.MONTH -> Calendar.getInstance().getActualMaximum(Calendar.DAY_OF_MONTH) // View days } } /** * Set the bar's corner radius * * @param radius the radius to set */ private fun initBarDrawable(radius: Float) { val r = scaledDensity * radius + 0.5f this.radii = floatArrayOf(r, r, r, r, r, r, r, r) val roundRectShape = RoundRectShape(radii, null, null) drawable = ShapeDrawable(roundRectShape) } /** * Called to determine the size requirements for this view */ override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) { val heightMultiplier = PlanningModule.instance.preferredBarHeightMultiplier barStrokeSize = 4f * scaledDensity * heightMultiplier desiredRowHeight = defaultRowHeight * scaledDensity verticalBarPadding = scaledDensity * desiredVerticalBarPadding * heightMultiplier val desiredWidth = 100 val desiredHeight = desiredRowHeight * rowCount * heightMultiplier val widthMode = MeasureSpec.getMode(widthMeasureSpec) val widthSize = MeasureSpec.getSize(widthMeasureSpec) val heightMode = MeasureSpec.getMode(heightMeasureSpec) val heightSize = MeasureSpec.getSize(heightMeasureSpec) val width: Int val height: Int // Measure the width width = when (widthMode) { MeasureSpec.EXACTLY -> widthSize MeasureSpec.AT_MOST -> Math.min(desiredWidth, widthSize) MeasureSpec.UNSPECIFIED -> desiredWidth else -> desiredWidth } // Measure the height height = when (heightMode) { MeasureSpec.EXACTLY -> heightSize MeasureSpec.AT_MOST -> Math.min(desiredHeight.toInt(), heightSize) MeasureSpec.UNSPECIFIED -> desiredHeight.toInt() else -> desiredHeight.toInt() } setMeasuredDimension(width, height) } /** * Get the row height to use when drawing the rows * * @returns the row height */ protected fun getRowHeight(): Float { if (rowCount <= 0 || height <= 0) { return 0f } return height.toFloat() / rowCount } /** * Get the column width * * @return the column width */ protected fun getColumnWidth(): Float { val columnCount = columnCount if (columnCount <= 0) return 0f return width.toFloat() / columnCount } /** * Calculates the start and end column indexes for a given IPlanItem object * * @param item the IPlanItem to calculate the start and end column index for * @return the start and end column index as Pair<start column, end column> */ protected fun <T: IPlannable> getColumnIndexes(item: T): Pair<Int, Int> { val itemStartsBeforeLeftSide = item.timeRange.start < displayedRange.start val itemEndsAfterRightSide = item.timeRange.endInclusive > displayedRange.endInclusive val columnCount = columnCount -1 var start: Int var end: Int if(itemStartsBeforeLeftSide && itemEndsAfterRightSide) { start = 0 end = columnCount } else { val calendarStart = GregorianCalendar.getInstance() val calendarEnd = GregorianCalendar.getInstance() calendarStart.timeInMillis = if (item.timeRange.start < displayedRange.start) displayedRange.start else item.timeRange.start calendarEnd.timeInMillis = item.timeRange.endInclusive start = if (itemStartsBeforeLeftSide) 0 else { val difference = item.timeRange.start - displayedRange.start val hours = TimeUnit.HOURS.convert(Math.abs(difference), TimeUnit.MILLISECONDS) val days: Double = hours.toDouble() / 24 Math.floor(days).roundToInt() } end = if (itemEndsAfterRightSide) columnCount else { if (calendarStart.get(Calendar.YEAR) == calendarEnd.get(Calendar.YEAR)) { start + Math.abs(calendarStart.get(Calendar.DAY_OF_YEAR) - calendarEnd.get(Calendar.DAY_OF_YEAR)) } else { var extraDays = 0 val dayOneOriginalYearDays = calendarStart.get(Calendar.DAY_OF_YEAR) while (calendarStart.get(Calendar.YEAR) > calendarEnd.get(Calendar.YEAR)) { calendarStart.add(Calendar.YEAR, -1) extraDays += calendarStart.getActualMaximum(Calendar.DAY_OF_YEAR) } extraDays - calendarEnd.get(Calendar.DAY_OF_YEAR) + dayOneOriginalYearDays } } } end = Math.min(end, columnCount) start = Math.max(0, start) return Pair(start, end) } /** * Get the item rows * * @return a List of IPlanItems for each row, wrapped in another List */ protected fun <T: IPlannable> getRowItems(items: List<T>): List<List<T>> { val itemRows: MutableList<MutableList<T>> = mutableListOf() for (item in items) { var didInsertIntoRow = false // Find the row to insert this item into for (itemRow in itemRows) { var shouldInsertIntoRow = true // Make sure there is no conflicting planitem for (itemInRow in itemRow) { if(itemInRow.timeRange.overlaps(item.timeRange, true)) { shouldInsertIntoRow = false break } } if (shouldInsertIntoRow) { didInsertIntoRow = true itemRow.add(item) break } } // We can't find a row where this item fits, so make a new row if(!didInsertIntoRow) { itemRows.add(mutableListOf(item)) } } rowCount = itemRows.size return itemRows } /** * Draws lines to make a grid */ protected fun drawVerticalGridLines(canvas: Canvas) { for (i in 0..columnCount) { val x: Float = i * getColumnWidth() canvas.drawLine(x, 0f, x, height.toFloat(), gridLinePaint) } } }
apache-2.0
388b183f31ee9eca081e1e0805da05b9
35.266254
136
0.650047
4.726796
false
false
false
false
cemrich/zapp
app/src/main/java/de/christinecoenen/code/zapp/app/mediathek/controller/DownloadReceiver.kt
1
1967
package de.christinecoenen.code.zapp.app.mediathek.controller import android.annotation.SuppressLint import android.content.BroadcastReceiver import android.content.Context import android.content.Intent import de.christinecoenen.code.zapp.app.mediathek.ui.detail.MediathekDetailActivity import de.christinecoenen.code.zapp.models.shows.PersistedMediathekShow import de.christinecoenen.code.zapp.repositories.MediathekRepository import kotlinx.coroutines.GlobalScope import kotlinx.coroutines.flow.first import kotlinx.coroutines.launch import org.koin.core.component.KoinComponent import org.koin.core.component.inject class DownloadReceiver : BroadcastReceiver(), KoinComponent { companion object { private const val ACTION_NOTIFICATION_CLICKED = "de.christinecoenen.code.zapp.NOTIFICATION_CLICKED" private const val EXTRA_DOWNLOAD_ID = "EXTRA_DOWNLOAD_ID" fun getNotificationClickedIntent(context: Context?, downloadId: Int): Intent { return Intent(context, DownloadReceiver::class.java).apply { action = ACTION_NOTIFICATION_CLICKED putExtra(EXTRA_DOWNLOAD_ID, downloadId) } } } private val mediathekRepository: MediathekRepository by inject() @SuppressLint("CheckResult") override fun onReceive(context: Context, intent: Intent) { if (ACTION_NOTIFICATION_CLICKED != intent.action) { return } val downloadId = intent.getIntExtra(EXTRA_DOWNLOAD_ID, 0) GlobalScope.launch { val persistedShow = mediathekRepository .getPersistedShowByDownloadId(downloadId) .first() onShowLoaded(context, persistedShow) } } private fun onShowLoaded(context: Context, persistedMediathekShow: PersistedMediathekShow) { // launch MediathekDetailActivity val detailIntent = MediathekDetailActivity .getStartIntent(context, persistedMediathekShow.mediathekShow) .apply { addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP) addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) } context.startActivity(detailIntent) } }
mit
d776504ece572110877cf20ab3c8c284
30.222222
93
0.796645
4.106472
false
false
false
false
pdvrieze/ProcessManager
PE-common/src/jvmMain/kotlin/nl/adaptivity/util/xml/SimpleAdapter.kt
1
4094
/* * Copyright (c) 2018. * * This file is part of ProcessManager. * * ProcessManager is free software: you can redistribute it and/or modify it under the terms of version 3 of the * GNU Lesser General Public License as published by the Free Software Foundation. * * ProcessManager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even * the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License along with ProcessManager. If not, * see <http://www.gnu.org/licenses/>. */ package nl.adaptivity.util.xml import nl.adaptivity.util.kotlin.arrayMap import nl.adaptivity.xmlutil.IterableNamespaceContext import nl.adaptivity.xmlutil.SimpleNamespaceContext import nl.adaptivity.xmlutil.XmlUtilInternal import org.w3c.dom.Attr import org.w3c.dom.NamedNodeMap import java.lang.reflect.Method import java.util.logging.Level import java.util.logging.Logger import javax.xml.XMLConstants import javax.xml.bind.JAXBElement import javax.xml.bind.Unmarshaller import javax.xml.bind.annotation.* import javax.xml.namespace.QName /** * Created by pdvrieze on 11/04/16. */ @XmlAccessorType(XmlAccessType.PROPERTY) class SimpleAdapter { internal var name: QName? = null @OptIn(XmlUtilInternal::class) internal var namespaceContext: IterableNamespaceContext = SimpleNamespaceContext() private set @XmlAnyAttribute internal val attributes: MutableMap<QName, Any> = HashMap() @XmlAnyElement(lax = true, value = W3CDomHandler::class) internal val children: MutableList<Any> = ArrayList() fun getAttributes(): Map<QName, Any> { return attributes } fun setAttributes(attributes: NamedNodeMap) { for (i in attributes.length - 1 downTo 0) { val attr = attributes.item(i) as Attr val prefix = attr.prefix if (prefix == null) { this.attributes[QName(attr.localName)] = attr.value } else if (XMLConstants.XMLNS_ATTRIBUTE != prefix) { this.attributes[QName(attr.namespaceURI, attr.localName, prefix)] = attr.value } } } @OptIn(XmlUtilInternal::class) fun beforeUnmarshal(unmarshaller: Unmarshaller, parent: Any) { if (parent is JAXBElement<*>) { name = parent.name } if (_failedReflection) { return } val context: Any? try { if (_getContext == null) { synchronized(javaClass) { _getContext = unmarshaller.javaClass.getMethod("getContext") context = _getContext!!.invoke(unmarshaller) _getAllDeclaredPrefixes = context!!.javaClass.getMethod("getAllDeclaredPrefixes") _getNamespaceURI = context.javaClass.getMethod("getNamespaceURI", String::class.java) } } else { context = _getContext!!.invoke(unmarshaller) } val _getNamespaceURI = _getNamespaceURI!! val _getAllDeclaredPrefixes = _getAllDeclaredPrefixes!! if (context != null) { val prefixes = _getAllDeclaredPrefixes(context) as Array<String> if (prefixes.isNotEmpty()) { val namespaces = prefixes.arrayMap { _getNamespaceURI(context, it) as String } namespaceContext = SimpleNamespaceContext(prefixes, namespaces) } } } catch (e: Throwable) { Logger.getAnonymousLogger().log(Level.FINE, "Could not retrieve namespace context from marshaller", e) _failedReflection = true } } companion object { @Volatile private var _getContext: Method? = null @Volatile private var _failedReflection = false private var _getAllDeclaredPrefixes: Method? = null private var _getNamespaceURI: Method? = null } }
lgpl-3.0
600c026ee22338790e0ffac924276efc
33.694915
114
0.651441
4.66287
false
false
false
false
aleksey-zhidkov/jeb-k
src/main/kotlin/jeb/Backuper.kt
1
3692
package jeb import jeb.util.Try import java.io.File import java.nio.file.Path import java.time.LocalDateTime import java.time.ZoneId import java.time.format.DateTimeFormatter import java.util.* import kotlin.text.Regex class Backuper(private val storage: Storage, private val now: LocalDateTime) { private val log = jeb.log fun doBackup(state: State, force: Boolean, excludesFile: Path?): Try<State?> { if (!storage.fileExists(File(state.backupsDir))) { return Try.Failure("Backups directory ${state.backupsDir} does not exists") } if (!force && storage.fileExists(File(state.backupsDir), { isTape(it, state) && modifiedToday(it) })) { log.info("Tape modified today exists, so halt backup") return Try.Success(null) } val (newState, nextTapeNum) = state.selectTape() log.info("Next tape number = $nextTapeNum") val lastBackup = storage.lastModified(File(state.backupsDir), { isTape(it, state) }) val fromDir = state.source val lastTape = storage.findOne(File(state.backupsDir), fileForTape(state, state.lastTapeNumber)) ?: File(state.backupsDir, toFileName(state.lastTapeNumber)) val tape = File(state.backupsDir, toFileName(nextTapeNum)) val prevTape = storage.findOne(File(state.backupsDir), fileForTape(state, nextTapeNum)) val tmpTape = File(tape.parentFile, "${tape.name}-${now.toEpochMilli()}") log.debug(""" lastBackup=$lastBackup fromDir=$fromDir lastTape=$lastTape tape=$tape tmpTape=$tmpTape """.trimIndent()) createBackup(from = fromDir, excludesFile = excludesFile, base = lastBackup, to = tmpTape) if (prevTape != null) { prepareTape(tape = prevTape, lastTape = lastTape) } log.info("Moving backup from $tmpTape to $tape") storage.move(from = tmpTape, to = tape) return Try.Success(newState) } private fun createBackup(from: List<Source>, excludesFile: Path?, base: File?, to: File) { if (base == null) { log.info("Base backup not found, creating full backup") storage.fullBackup(from, excludesFile, to) } else { log.info("Base backup found at $base, creating incremental backup") storage.incBackup(from, excludesFile, base, to) } } private fun prepareTape(tape: File, lastTape: File) { if (storage.fileExists(lastTape)) { log.info("Last tape taken, so cleaning $tape") storage.remove(tape) } else { log.info("Last tape free, so moving $tape to $lastTape") storage.move(tape, lastTape) } } private fun modifiedToday(f: File) = Date(f.lastModified()).toLocalDate() == now.toLocalDate() private fun toFileName(tapeNum: Int) = "${now.format(DateTimeFormatter.BASIC_ISO_DATE)}-$tapeNum" } private fun Date.toLocalDate() = this.toInstant().atZone(ZoneId.systemDefault()).toLocalDate() private fun LocalDateTime.toEpochMilli() = this.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli() private fun isTape(f: File, state: State): Boolean { if (!f.isDirectory) { return false } val maxTapeDigits = state.lastTapeNumber.toString().length val pattern = """\d{8}-(\d{1,$maxTapeDigits})""" val tapeNum = Regex(pattern).matchEntire(f.name)?.groups?.get(1)?.value?.toInt() return tapeNum?.let { it > 0 && it <= state.lastTapeNumber } ?: false } private fun fileForTape(state: State, tape: Int): (File) -> Boolean = { isTape(it, state) && it.absolutePath.endsWith("-$tape") }
apache-2.0
bdc90370867b00762172da50cb9992ff
37.458333
164
0.642741
3.911017
false
false
false
false
commonsguy/cwac-netsecurity
demoSearch/src/main/java/com/commonsware/cwac/netsecurity/demo/search/MainMotor.kt
1
1592
/* Copyright (c) 2019 CommonsWare, LLC Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0. Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.commonsware.cwac.netsecurity.demo.search import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch sealed class MainViewState { object Initial : MainViewState() object Loading : MainViewState() data class Content(val items: List<SearchResultModel>) : MainViewState() data class Error(val throwable: Throwable) : MainViewState() } class MainMotor(private val repo: SearchRepository) : ViewModel() { private val _states = MutableLiveData<MainViewState>().apply { value = MainViewState.Initial } val states: LiveData<MainViewState> = _states fun search(expr: String) { _states.value = MainViewState.Loading viewModelScope.launch(Dispatchers.Main) { _states.value = try { MainViewState.Content(repo.search(expr)) } catch (t: Throwable) { MainViewState.Error(t) } } } }
apache-2.0
bc322229da79793d714429465b440b59
35.204545
79
0.755653
4.373626
false
false
false
false
ccomeaux/boardgamegeek4android
app/src/main/java/com/boardgamegeek/provider/SearchSuggestProvider.kt
1
3206
package com.boardgamegeek.provider import android.app.SearchManager import android.content.ContentResolver import android.database.Cursor import android.database.sqlite.SQLiteDatabase import android.database.sqlite.SQLiteQueryBuilder import android.net.Uri import android.provider.BaseColumns import com.boardgamegeek.provider.BggContract.Collection import com.boardgamegeek.provider.BggContract.Games import com.boardgamegeek.provider.BggContract.Companion.PATH_THUMBNAILS import com.boardgamegeek.provider.BggDatabase.Tables import java.util.* /** * Called from the search widget to populate the drop down list. * content://com.boardgamegeek/search_suggest_query/keyword?limit=50 */ open class SearchSuggestProvider : BaseProvider() { override fun getType(uri: Uri) = SearchManager.SUGGEST_MIME_TYPE override val path = SearchManager.SUGGEST_URI_PATH_QUERY override val defaultSortOrder = Collection.DEFAULT_SORT override fun query( resolver: ContentResolver, db: SQLiteDatabase, uri: Uri, projection: Array<String>?, selection: String?, selectionArgs: Array<String>?, sortOrder: String? ): Cursor? { val searchTerm = uri.lastPathSegment?.lowercase(Locale.getDefault()).orEmpty() val limit = uri.getQueryParameter(SearchManager.SUGGEST_PARAMETER_LIMIT) val qb = SQLiteQueryBuilder().apply { tables = Tables.COLLECTION_JOIN_GAMES projectionMap = suggestionProjectionMap appendWhere("(${Collection.Columns.COLLECTION_NAME} like '$searchTerm%%' OR ${Collection.Columns.COLLECTION_NAME} like '%% $searchTerm%%')") } return qb.query(db, projection, selection, selectionArgs, GROUP_BY, null, getSortOrder(sortOrder), limit).apply { setNotificationUri(resolver, uri) } } companion object { private const val GROUP_BY = "${Collection.Columns.COLLECTION_NAME}, ${Collection.Columns.COLLECTION_YEAR_PUBLISHED}" @Suppress("SpellCheckingInspection") val suggestionProjectionMap = mutableMapOf( BaseColumns._ID to "${Tables.GAMES}.${BaseColumns._ID}", SearchManager.SUGGEST_COLUMN_TEXT_1 to "${Collection.Columns.COLLECTION_NAME} AS ${SearchManager.SUGGEST_COLUMN_TEXT_1}", SearchManager.SUGGEST_COLUMN_TEXT_2 to "IFNULL(CASE WHEN ${Collection.Columns.COLLECTION_YEAR_PUBLISHED}=0 THEN NULL ELSE ${Collection.Columns.COLLECTION_YEAR_PUBLISHED} END, '?') AS ${SearchManager.SUGGEST_COLUMN_TEXT_2}", SearchManager.SUGGEST_COLUMN_ICON_2 to "'${Games.CONTENT_URI}/' || ${Tables.COLLECTION}.${Collection.Columns.GAME_ID} || '/$PATH_THUMBNAILS' AS ${SearchManager.SUGGEST_COLUMN_ICON_2}", SearchManager.SUGGEST_COLUMN_INTENT_DATA_ID to "${Tables.GAMES}.${Games.Columns.GAME_ID} AS ${SearchManager.SUGGEST_COLUMN_INTENT_DATA_ID}", SearchManager.SUGGEST_COLUMN_INTENT_EXTRA_DATA to "${Collection.Columns.COLLECTION_NAME} AS ${SearchManager.SUGGEST_COLUMN_INTENT_EXTRA_DATA}", SearchManager.SUGGEST_COLUMN_LAST_ACCESS_HINT to "${Games.Columns.LAST_VIEWED} AS ${SearchManager.SUGGEST_COLUMN_LAST_ACCESS_HINT}", ) } }
gpl-3.0
c7147057e7912f042c81b9c0c81c83c4
50.709677
235
0.72146
4.502809
false
false
false
false
Ruben-Sten/TeXiFy-IDEA
src/nl/hannahsten/texifyidea/editor/LatexCommenter.kt
1
447
package nl.hannahsten.texifyidea.editor import com.intellij.lang.Commenter /** * @author Sten Wessel */ open class LatexCommenter : Commenter { override fun getLineCommentPrefix() = "%" override fun getBlockCommentPrefix(): String? = null override fun getBlockCommentSuffix(): String? = null override fun getCommentedBlockCommentPrefix(): String? = null override fun getCommentedBlockCommentSuffix(): String? = null }
mit
5597b934f12205add8fc5c7578f23bc8
22.526316
65
0.738255
4.966667
false
false
false
false
aucd29/common
library/src/main/java/net/sarangnamu/common/BkContext.kt
1
5317
/* * Copyright 2016 Burke Choi All rights reserved. * http://www.sarangnamu.net * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ @file:Suppress("NOTHING_TO_INLINE", "unused") package net.sarangnamu.common import android.annotation.SuppressLint import android.app.Activity import android.app.ActivityManager import android.content.ClipData import android.content.ClipboardManager import android.content.Context import android.content.res.ColorStateList import android.graphics.Color import android.graphics.drawable.Drawable import android.net.ConnectivityManager import android.net.NetworkInfo import android.os.AsyncTask import android.os.Build import android.os.Environment import android.support.annotation.ColorRes import android.support.annotation.DrawableRes import android.support.annotation.IntegerRes import android.support.annotation.StringRes import android.support.v4.content.ContextCompat import android.view.View import android.view.Window import android.view.WindowManager import android.view.inputmethod.InputMethodManager /** * Created by <a href="mailto:[email protected]">Burke Choi</a> on 2017. 11. 30.. <p/> */ /** * pkgName 에 해당하는 앱이 foreground 인지 확인 */ inline fun Context.isForegroundApp(pkgName: String): Boolean { val manager = getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager return manager.runningAppProcesses.filter { it.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND && it.processName == pkgName }.size == 1 } /** * 현재 앱이 foreground 인지 확인 */ inline fun Context.isForegroundApp(): Boolean { return isForegroundApp(packageName) } /** * sdcard 내 app 경로 전달 */ inline fun Context.externalFilePath() = getExternalFilesDir(null).absolutePath /** * display density 반환 */ inline fun Context.displayDensity() = resources.displayMetrics.density /** * open keyboard */ inline fun Context.showKeyboard(view: View?) { view?.let { it.postDelayed({ it.requestFocus() val imm = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager imm.showSoftInput(it, InputMethodManager.SHOW_FORCED) }, 400) } } /** * hide keyboard */ inline fun Context.hideKeyboard(view: View?) { view?.let { val imm = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager imm.hideSoftInputFromWindow(it.windowToken, 0) } } /** * force hide keyboard */ inline fun Context.forceHideKeyboard(window: Window?) { window?.run { setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN) } } inline fun Context.string(@StringRes resid: Int): String? = getString(resid) inline fun Context.drawable(@DrawableRes resid: Int): Drawable? = ContextCompat.getDrawable(this, resid) //////////////////////////////////////////////////////////////////////////////////// // // ENVIRONMENT EXTENSION // //////////////////////////////////////////////////////////////////////////////////// /** sdcard 가 존재하는지 확인 */ inline fun Context.hasSd() = Environment.getExternalStorageState() == Environment.MEDIA_MOUNTED /** data directory 에 사이즈 반환 */ inline fun Context.dataDirSize() = BkSystem.blockSize(Environment.getDataDirectory()).toFileSizeString() /** sdcard 사이즈 반환 */ inline fun Context.sdSize() = BkSystem.blockSize(Environment.getExternalStorageDirectory()).toFileSizeString() /** sdcard 경로 반환 */ inline fun Context.sdPath() = Environment.getExternalStorageDirectory().getAbsolutePath() fun Context.async(background: (() -> Boolean)? = null, post: ((result: Boolean) -> Unit)? = null) { Async(background, post).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR) } fun Context.clipboard(key: String): String? { val manager = getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager return manager.primaryClip?.getItemAt(0)?.text.toString() } fun Context.clipboard(key: String, value: String?) { val manager = getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager manager.primaryClip = ClipData.newPlainText(key, value) } @SuppressLint("MissingPermission") fun Context.isNetworkConnected() : Boolean { val manager = getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { manager.allNetworks?.forEach { if (manager.getNetworkInfo(it).state == NetworkInfo.State.CONNECTED) { return true } } } else { manager.allNetworkInfo.forEach { if (it == NetworkInfo.State.CONNECTED) { return true } } } return false }
apache-2.0
8011880802fe6c59227a0082aecc5c3c
30.823171
104
0.702625
4.393098
false
false
false
false
SimonVT/cathode
trakt-api/src/main/java/net/simonvt/cathode/api/entity/ShowProgress.kt
1
1387
/* * Copyright (C) 2014 Simon Vig Therkildsen * * 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 net.simonvt.cathode.api.entity data class ShowProgress( val aired: Int, val completed: Int, val last_watched_at: IsoTime? = null, val last_collected_at: IsoTime? = null, val reset_at: IsoTime? = null, val seasons: List<ProgressSeason>, val hidden_seasons: List<ProgressSeason>, val next_episode: LastNextEpisode?, val last_episode: LastNextEpisode? ) data class ProgressSeason( val number: Int, val aired: Int? = null, val completed: Int? = null, val episodes: List<ProgressEpisode> ) data class ProgressEpisode( val number: Int, val completed: Boolean, val last_watched_at: IsoTime? = null, val collected_at: IsoTime? = null ) data class LastNextEpisode( val season: Int, val number: Int, val title: String, val ids: Ids )
apache-2.0
781d071c069539ab6dff637c634be275
26.74
75
0.723143
3.659631
false
false
false
false
debop/debop4k
debop4k-core/src/main/kotlin/debop4k/core/collections/ParallelIteratex.kt
1
8302
/* * Copyright (c) 2016. Sunghyouk Bae <[email protected]> * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ @file:JvmName("ParallelIteratex") package debop4k.core.collections import org.eclipse.collections.api.map.primitive.ObjectDoubleMap import org.eclipse.collections.api.map.primitive.ObjectLongMap import org.eclipse.collections.api.multimap.MutableMultimap import org.eclipse.collections.impl.parallel.ParallelIterate import org.eclipse.collections.impl.parallel.ParallelMapIterate import java.math.BigDecimal import java.math.BigInteger val DEFAULT_MIN_FORK_SIZE: Int = 10000 /** * 병렬 방식으로 filtering 을 수행합니다. */ @JvmOverloads inline fun <T> Iterable<T>.parFilter(reorder: Boolean = true, crossinline predicate: (T) -> Boolean): Collection<T> { return ParallelIterate.select(this, { predicate(it) }, reorder) } /** * 병렬 방식으로 [predicate] 가 false 인 요소들만 filtering 합니다. */ @JvmOverloads inline fun <T> Iterable<T>.parReject(reorder: Boolean = true, crossinline predicate: (T) -> Boolean): Collection<T> { return ParallelIterate.reject(this, { predicate(it) }, reorder) } /** * 병렬 방식으로 [predicate] 가 true 를 반환하는 요소의 수를 반환합니다. */ inline fun <T> Iterable<T>.parCount(crossinline predicate: (T) -> Boolean): Int { return ParallelIterate.count(this, { predicate(it) }) } /** * Parallel forEach */ @JvmOverloads inline fun <T> Iterable<T>.parForEach(batchSize: Int = DEFAULT_MIN_FORK_SIZE, crossinline action: (T) -> Unit): Unit { ParallelIterate.forEach(this, { action(it) }, batchSize) } /** * Parallel forEach with index */ inline fun <T> Iterable<T>.parForEachWithIndex(crossinline action: (T, Int) -> Unit): Unit { ParallelIterate.forEachWithIndex(this, { t, i -> action(t, i) }) } /** * Parallel Map */ @JvmOverloads inline fun <T, V> Iterable<T>.parMap(reorder: Boolean = true, crossinline mapper: (T) -> V): Collection<V> { return ParallelIterate.collect(this, { mapper(it) }, reorder) } /** * Parallel Flat Map */ @JvmOverloads inline fun <T, V> Iterable<T>.parFlatMap(reorder: Boolean = true, crossinline mapper: (T) -> Collection<V>): Collection<V> { return ParallelIterate.flatCollect(this, { mapper(it) }, reorder) } /** * Parallel Filter and Mapping */ @JvmOverloads inline fun <T, V> Iterable<T>.parFilterMap(crossinline predicate: (T) -> Boolean, crossinline mapper: (T) -> V, reorder: Boolean = true): Collection<V> { return ParallelIterate.collectIf(this, { predicate(it) }, { mapper(it) }, reorder) } /** * Parallel group by */ @JvmOverloads inline fun <K, V, R : MutableMultimap<K, V>> Iterable<V>.parGroupBy(batchSize: Int = DEFAULT_MIN_FORK_SIZE, crossinline function: (V) -> K): MutableMultimap<K, V> { return ParallelIterate.groupBy(this, { function(it) }, batchSize) } /** * Parallel aggregate by */ @JvmOverloads inline fun <T, K, V> Iterable<T>.parAggregateBy(crossinline groupBy: (T) -> K, crossinline zeroValueFactory: () -> V, crossinline nonMutatingAggregator: (V, T) -> V, batchSize: Int = DEFAULT_MIN_FORK_SIZE): MutableMap<K, V> { return ParallelIterate.aggregateBy(this, { groupBy(it) }, { zeroValueFactory() }, { v, t -> nonMutatingAggregator(v, t) }, batchSize) } /** * Parallel aggregate by */ @JvmOverloads inline fun <T, K, V> Iterable<T>.parAggregateInPlaceBy(crossinline groupBy: (T) -> K, crossinline zeroValueFactory: () -> V, crossinline mutatingAggregator: (V, T) -> Unit, batchSize: Int = DEFAULT_MIN_FORK_SIZE): MutableMap<K, V> { return ParallelIterate.aggregateInPlaceBy(this, { groupBy(it) }, { zeroValueFactory() }, { v, t -> mutatingAggregator(v, t) }, batchSize) } /** * Parallel sum by Double */ inline fun <T, V> Iterable<T>.parSumByDouble(crossinline groupBy: (T) -> V, crossinline doubleFunc: (T) -> Double): ObjectDoubleMap<V> { return ParallelIterate.sumByDouble(this, { groupBy(it) }, { doubleFunc(it) }) } /** * Parallel sum by Float */ inline fun <T, V> Iterable<T>.parSumByFloat(crossinline groupBy: (T) -> V, crossinline floatFunc: (T) -> Float): ObjectDoubleMap<V> { return ParallelIterate.sumByFloat(this, { groupBy(it) }, { floatFunc(it) }) } /** * Parallel sum by Long */ inline fun <T, V> Iterable<T>.parSumByLong(crossinline groupBy: (T) -> V, crossinline longFunc: (T) -> Long): ObjectLongMap<V> { return ParallelIterate.sumByLong(this, { groupBy(it) }, { longFunc(it) }) } /** * Parallel sum by Int */ inline fun <T, V> Iterable<T>.parSumByInt(crossinline groupBy: (T) -> V, crossinline longFunc: (T) -> Int): ObjectLongMap<V> { return ParallelIterate.sumByInt(this, { groupBy(it) }, { longFunc(it) }) } /** * Parallel sum by BigDecimal */ inline fun <T, V> Iterable<T>.parSumByBigDecimal(crossinline groupBy: (T) -> V, crossinline longFunc: (T) -> BigDecimal): MutableMap<V, BigDecimal> { return ParallelIterate.sumByBigDecimal(this, { groupBy(it) }, { longFunc(it) }) } /** * Parallel sum by BigInteger */ inline fun <T, V> Iterable<T>.parSumByBigInteger(crossinline groupBy: (T) -> V, crossinline longFunc: (T) -> BigInteger): MutableMap<V, BigInteger> { return ParallelIterate.sumByBigInteger(this, { groupBy(it) }, { longFunc(it) }) } /** * Map을 병렬로 procedure를 호출하여 작업을 수행합니다. */ inline fun <K, V> Map<K, V>.parForEach(crossinline procedure: (K, V) -> Unit): Unit { ParallelMapIterate.forEachKeyValue(this, { k, v -> procedure(k, v) }) } /** * Map을 병렬로 mapping 을 수행합니다 */ @JvmOverloads inline fun <K, V, R> Map<K, V>.parMap(reorder: Boolean = true, crossinline mapper: (K, V) -> R): Collection<R> { return this.toList().parMap(reorder) { mapper(it.first, it.second) } } /** * Map을 병렬로 flat mapping 을 수행합니다 */ @JvmOverloads inline fun <K, V, R> Map<K, V>.parFlatMap(reorder: Boolean = true, crossinline flatMapper: (K, V) -> Collection<R>): Collection<R> { return this.toList().parFlatMap(reorder) { flatMapper(it.first, it.second) } }
apache-2.0
43ff7986978737dd38ebb646b4dba8e9
34.819383
118
0.547478
4.154318
false
false
false
false
cfig/Android_boot_image_editor
bbootimg/src/main/kotlin/ota/Payload.kt
1
13140
// Copyright 2022 [email protected] // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package cc.cfig.droid.ota import cc.cfig.io.Struct import cfig.helper.CryptoHelper.Hasher import cfig.helper.Helper import cfig.helper.Dumpling import chromeos_update_engine.UpdateMetadata import com.fasterxml.jackson.annotation.JsonInclude import com.fasterxml.jackson.databind.ObjectMapper import com.google.protobuf.ByteString import org.apache.commons.exec.CommandLine import org.apache.commons.exec.DefaultExecutor import org.apache.commons.exec.PumpStreamHandler import org.slf4j.LoggerFactory import java.io.* import java.nio.file.Files import java.nio.file.Paths import java.time.Instant import java.time.ZoneId import java.time.format.DateTimeFormatter class Payload { var fileName: String = "" var header = PayloadHeader() var manifest: UpdateMetadata.DeltaArchiveManifest = UpdateMetadata.DeltaArchiveManifest.newBuilder().build() var metaSig: UpdateMetadata.Signatures = UpdateMetadata.Signatures.newBuilder().build() var metaSize: Int = 0 var dataOffset: Long = 0L var dataSig: UpdateMetadata.Signatures = UpdateMetadata.Signatures.newBuilder().build() companion object { private val log = LoggerFactory.getLogger(Payload::class.java) val workDir = Helper.prop("payloadDir") fun parse(inFileName: String): Payload { val ret = Payload() ret.fileName = inFileName FileInputStream(inFileName).use { fis -> ret.header = PayloadHeader(fis) ret.metaSize = ret.header.headerSize + ret.header.manifestLen.toInt() ret.dataOffset = (ret.metaSize + ret.header.metaSigLen).toLong() //manifest ret.manifest = ByteArray(ret.header.manifestLen.toInt()).let { buf -> fis.read(buf) UpdateMetadata.DeltaArchiveManifest.parseFrom(buf) } //meta sig ret.metaSig = ByteArray(ret.header.metaSigLen).let { buf2 -> fis.read(buf2) UpdateMetadata.Signatures.parseFrom(buf2) } //data sig if (ret.manifest.hasSignaturesOffset()) { log.debug("payload sig offset = " + ret.manifest.signaturesOffset) log.debug("payload sig size = " + ret.manifest.signaturesSize) fis.skip(ret.manifest.signaturesOffset) ret.dataSig = ByteArray(ret.manifest.signaturesSize.toInt()).let { buf -> fis.read(buf) UpdateMetadata.Signatures.parseFrom(buf) } } else { log.warn("payload has no signatures") } } //end-of-fis run {//CHECK_EQ(payload.size(), signatures_offset + manifest.signatures_size()) val calculatedSize = ret.header.headerSize + ret.header.manifestLen + ret.header.metaSigLen + ret.manifest.signaturesOffset + ret.manifest.signaturesSize if (File(inFileName).length() == calculatedSize) { log.info("payload.bin size info check PASS") } else { throw IllegalStateException("calculated payload size doesn't match file size") } } val calcMetadataHash = Hasher.hash(Dumpling(inFileName), listOf(Pair(0L, ret.metaSize.toLong())), "sha-256") log.info("calc meta hash: " + Helper.toHexString(calcMetadataHash)) val calcPayloadHash = Hasher.hash( Dumpling(inFileName), listOf( Pair(0L, ret.metaSize.toLong()), Pair(ret.metaSize.toLong() + ret.header.metaSigLen, ret.manifest.signaturesOffset) ), "sha-256" ) check(calcPayloadHash.size == 32) log.info("calc payload hash: " + Helper.toHexString(calcPayloadHash)) val readPayloadSignature = UpdateMetadata.Signatures.parseFrom( Helper.readFully( inFileName, ret.dataOffset + ret.manifest.signaturesOffset, ret.manifest.signaturesSize.toInt() ) ) log.info("Found sig count: " + readPayloadSignature.signaturesCount) readPayloadSignature.signaturesList.forEach { //pass log.info(it.data.toString()) log.info("sig_data size = " + it.data.toByteArray().size) log.info(Helper.toHexString(it.data.toByteArray())) Files.write(Paths.get("sig_data"), it.data.toByteArray()) } return ret } class PayloadVerifier { fun getRawHashFromSignature(sig_data: ByteString, pubkey: String, sigHash: ByteArray) { } } fun displaySignatureBlob(sigName: String, sig: UpdateMetadata.Signatures): String { return StringBuilder().let { sb -> sb.append(String.format("%s signatures: (%d entries)\n", sigName, sig.signaturesCount)) sig.signaturesList.forEach { sb.append(String.format(" hex_data: (%d bytes)\n", it.data.size())) sb.append(" Data: " + Helper.toHexString(it.data.toByteArray()) + "\n") } sb }.toString() } } fun printInfo() { val mi = ManifestInfo(blockSize = this.manifest.blockSize, minorVersion = this.manifest.minorVersion, maxTimeStamp = this.manifest.maxTimestamp, signatureOffset = this.manifest.signaturesOffset, signatureSize = this.manifest.signaturesSize, partialUpdate = this.manifest.hasPartialUpdate(), partsToUpdate = this.manifest.partitionsList.map { ManifestInfo.PartitionToUpdate( it.partitionName, it.operationsCount, if (it.hasRunPostinstall()) it.runPostinstall else null, if (it.hasPostinstallPath()) it.postinstallPath else null ) }, enableSnapshot = this.manifest.dynamicPartitionMetadata.hasSnapshotEnabled(), dynamicGroups = this.manifest.dynamicPartitionMetadata.groupsList.map { ManifestInfo.DynamicPartGroup(name = it.name, size = it.size, partName = it.partitionNamesList) }) ObjectMapper().writerWithDefaultPrettyPrinter().writeValue(File("$workDir/header.json"), this.header) log.info(" header info dumped to ${workDir}header.json") ObjectMapper().writerWithDefaultPrettyPrinter().writeValue(File("$workDir/manifest.json"), mi) log.info(" manifest info dumped to ${workDir}manifest.json") val signatureFile = "${workDir}signatures.txt" FileOutputStream(signatureFile, false).use { fos -> fos.writer().use { fWriter -> fWriter.write("<Metadata> signatures: offset=" + this.header.manifestLen + ", size=" + this.header.metaSigLen + "\n") fWriter.write(Payload.displaySignatureBlob("<Metadata>", this.metaSig)) fWriter.write("<Payload> signatures: base= offset=" + manifest.signaturesOffset + ", size=" + this.header.metaSigLen + "\n") fWriter.write((Payload.displaySignatureBlob("<Payload>", this.dataSig))) } } log.info("signature info dumped to $signatureFile") } private fun decompress(inBytes: ByteArray, opType: UpdateMetadata.InstallOperation.Type): ByteArray { val baosO = ByteArrayOutputStream() val baosE = ByteArrayOutputStream() val bais = ByteArrayInputStream(inBytes) DefaultExecutor().let { exec -> exec.streamHandler = PumpStreamHandler(baosO, baosE, bais) val cmd = when (opType) { UpdateMetadata.InstallOperation.Type.REPLACE_XZ -> CommandLine("xzcat") UpdateMetadata.InstallOperation.Type.REPLACE_BZ -> CommandLine("bzcat") UpdateMetadata.InstallOperation.Type.REPLACE -> return inBytes else -> throw IllegalArgumentException(opType.toString()) } cmd.addArgument("-") exec.execute(cmd) } return baosO.toByteArray() } private fun unpackInternal(ras: RandomAccessFile, pu: UpdateMetadata.PartitionUpdate, logPrefix: String = "") { log.info(String.format("[%s] extracting %13s.img (%d ops)", logPrefix, pu.partitionName, pu.operationsCount)) FileOutputStream("$workDir/${pu.partitionName}.img").use { outFile -> val ops = pu.operationsList.toMutableList().apply { sortBy { it.getDstExtents(0).startBlock } } ops.forEach { op -> log.debug(pu.partitionName + ": " + (op.getDstExtents(0).startBlock * this.manifest.blockSize) + ", size=" + op.dataLength) val piece = ByteArray(op.dataLength.toInt()).let { ras.seek(this.dataOffset + op.dataOffset) ras.read(it) it } outFile.write(decompress(piece, op.type)) } } } fun setUp() { File(workDir).let { if (it.exists()) { log.info("Removing $workDir") it.deleteRecursively() } log.info("Creating $workDir") it.mkdirs() } } fun unpack() { RandomAccessFile(this.fileName, "r").use { ras -> var currentNum = 1 val totalNum = this.manifest.partitionsCount val parts = this.manifest.partitionsList.map { it.partitionName } log.info("There are $totalNum partitions $parts") log.info("dumping images to $workDir") this.manifest.partitionsList.forEach { pu -> unpackInternal(ras, pu, String.format("%2d/%d", currentNum, totalNum)) currentNum++ } } } data class PayloadHeader( var version: Long = 0, var manifestLen: Long = 0, var metaSigLen: Int = 0, var headerSize: Int = 0 ) { private val magic = "CrAU" private val FORMAT_STRING = ">4sqq" //magic, version, manifestLen private val CHROMEOS_MAJOR_PAYLOAD_VERSION = 1L private val BRILLO_MAJOR_PAYLOAD_VERSION = 2L val typeOfVersion: String get() = when (version) { CHROMEOS_MAJOR_PAYLOAD_VERSION -> "chromeOs" BRILLO_MAJOR_PAYLOAD_VERSION -> "brillo" else -> throw IllegalArgumentException() } constructor(fis: InputStream) : this() { val info = Struct(FORMAT_STRING).unpack(fis) check((info[0] as String) == magic) { "${info[0]} is not payload magic" } version = info[1] as Long manifestLen = info[2] as Long headerSize = Struct(FORMAT_STRING).calcSize() if (version == BRILLO_MAJOR_PAYLOAD_VERSION) { headerSize += Int.SIZE_BYTES metaSigLen = Struct(">i").unpack(fis)[0] as Int } } } @JsonInclude(JsonInclude.Include.NON_NULL) data class ManifestInfo( var blockSize: Int? = null, var minorVersion: Int? = null, var maxTimeStamp: Long = 0L, var maxTimeReadable: String? = null, var partialUpdate: Boolean? = null, val signatureOffset: Long? = null, val signatureSize: Long? = null, var dynamicGroups: List<DynamicPartGroup> = listOf(), var enableSnapshot: Boolean? = null, var partsToUpdate: List<PartitionToUpdate> = listOf() ) { init { val ldt = Instant.ofEpochMilli(maxTimeStamp * 1000) .atZone(ZoneId.systemDefault()) .toLocalDateTime() maxTimeReadable = DateTimeFormatter.ISO_LOCAL_DATE_TIME.format(ldt) + " (${ZoneId.systemDefault()})" } @JsonInclude(JsonInclude.Include.NON_NULL) data class PartitionToUpdate( var name: String = "", var ops: Int = 0, var runPostInstall: Boolean? = null, var postInstallPath: String? = null ) data class DynamicPartGroup( var name: String = "", var size: Long = 0L, var partName: List<String> = listOf() ) } }
apache-2.0
eb2ad8884442cb995a2671bf1528ef3b
42.8
140
0.592542
4.551437
false
false
false
false
brayvqz/ejercicios_kotlin
par_impar/main.kt
1
355
package par_impar import java.util.* /** * Created by brayan on 15/04/2017. */ fun main(args: Array<String>){ var scan = Scanner(System.`in`) println("Ingrese el numero a evaluar : ") var num = scan.nextInt() println(par_impar(num)) } fun par_impar(num:Int = 0):String = if ((num%2) == 0) "El numero es par" else "El numero es impar"
mit
2a930f69dcbaa2ca9a5106b8aea75172
21.25
98
0.63662
2.886179
false
false
false
false
andrei-heidelbacher/metanalysis
analyzers/chronolens-coupling/src/main/kotlin/org/chronolens/coupling/FeatureEnvyCommand.kt
1
7239
/* * Copyright 2021 Andrei Heidelbacher <[email protected]> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.chronolens.coupling import org.chronolens.core.cli.Subcommand import org.chronolens.core.cli.restrictTo import org.chronolens.core.model.sourcePath import org.chronolens.core.repository.Transaction import org.chronolens.core.serialization.JsonModule import org.chronolens.coupling.FeatureEnvyCommand.FeatureEnvy import org.chronolens.coupling.Graph.Node import java.io.File internal class FeatureEnvyCommand : Subcommand() { override val help: String get() = """ Loads the persisted repository, builds the temporal coupling graphs for the analyzed source files, detects the Feature Envy instances, reports the results to the standard output and dumps the coupling graphs for each pair of source files in the '.chronolens/feature-envy' directory. """ private val maxChangeSet by option<Int>() .help("the maximum number of changed files in a revision") .defaultValue(100).restrictTo(min = 1) private val minRevisions by option<Int>().help( "the minimum number of revisions of a method or coupling relation" ).defaultValue(5).restrictTo(min = 1) private val minCoupling by option<Double>() .help("the minimum temporal coupling between two methods") .defaultValue(0.1).restrictTo(min = 0.0) private val minEnvyRatio by option<Double>() .help("the minimum ratio of coupling to another source file") .defaultValue(1.0).restrictTo(min = 0.0, max = 1.0) private val maxEnviedFiles by option<Int>().help( """the maximum number of files envied by a method that will be reported""" ).defaultValue(1).restrictTo(min = 1) private val minMetricValue by option<Int>().help( """ignore source files that have less Feature Envy instances than the specified limit""" ).defaultValue(1).restrictTo(min = 0) private fun TemporalContext.buildColoredGraphs( featureEnvyInstancesByFile: Map<String, List<FeatureEnvy>>, ): List<ColoredGraph> { val idsByFile = ids.groupBy(String::sourcePath) val graphs = featureEnvyInstancesByFile.map { (path, instances) -> val enviedFiles = instances.map(FeatureEnvy::enviedFile).toSet() val nodeIds = (enviedFiles + path).map(idsByFile::getValue).flatten().toSet() buildGraphFrom(path, nodeIds) } return graphs .map { graph -> graph.colorNodes(featureEnvyInstancesByFile) } } private fun TemporalContext.computeFunctionToFileCouplings(): SparseMatrix<String, Double> { val functionToFileCoupling = emptySparseHashMatrix<String, Double>() for ((id1, id2) in cells) { val function = id1 val file = id2.sourcePath val coupling = coupling(id1, id2) functionToFileCoupling[function, file] = (functionToFileCoupling[function, file] ?: 0.0) + coupling } return functionToFileCoupling } private fun findFeatureEnvyInstances( functionToFileCoupling: SparseMatrix<String, Double>, ): List<FeatureEnvy> { val featureEnvyInstances = arrayListOf<FeatureEnvy>() for ((function, fileCouplings) in functionToFileCoupling) { fun couplingWithFile(f: String): Double = fileCouplings[f] ?: 0.0 val file = function.sourcePath val selfCoupling = couplingWithFile(file) val couplingThreshold = selfCoupling * minEnvyRatio val enviedFiles = (fileCouplings - file).keys .sortedByDescending(::couplingWithFile) .takeWhile { f -> couplingWithFile(f) > couplingThreshold } featureEnvyInstances += enviedFiles.take(maxEnviedFiles).map { f -> FeatureEnvy(function, selfCoupling, f, couplingWithFile(f)) } } return featureEnvyInstances .sortedByDescending(FeatureEnvy::enviedCoupling) } private fun analyze(history: Sequence<Transaction>): Report { val analyzer = HistoryAnalyzer(maxChangeSet, minRevisions, minCoupling) val temporalContext = analyzer.analyze(history) val functionToFileCoupling = temporalContext.computeFunctionToFileCouplings() val featureEnvyInstancesByFile = findFeatureEnvyInstances(functionToFileCoupling) .groupBy(FeatureEnvy::file) val fileReports = featureEnvyInstancesByFile .map { (file, instances) -> FileReport(file, instances) } .sortedByDescending(FileReport::featureEnvyCount) val coloredGraphs = temporalContext.buildColoredGraphs(featureEnvyInstancesByFile) return Report(fileReports, coloredGraphs) } override fun run() { val repository = load() val report = analyze(repository.getHistory()) val files = report.files.filter { it.value >= minMetricValue } JsonModule.serialize(System.out, files) val directory = File(".chronolens", "feature-envy") for (coloredGraph in report.coloredGraphs) { val graphDirectory = File(directory, coloredGraph.graph.label) graphDirectory.mkdirs() val graphFile = File(graphDirectory, "graph.json") graphFile.outputStream().use { out -> JsonModule.serialize(out, coloredGraph) } } } data class Report( val files: List<FileReport>, val coloredGraphs: List<ColoredGraph>, ) data class FileReport( val file: String, val featureEnvyInstances: List<FeatureEnvy>, ) { val featureEnvyCount: Int = featureEnvyInstances.size val category: String = "Temporal Coupling Anti-Patterns" val name: String = "Feature Envy" val value: Int = featureEnvyCount } data class FeatureEnvy( val function: String, val coupling: Double, val enviedFile: String, val enviedCoupling: Double, ) { val file: String get() = function.sourcePath } } private fun Graph.colorNodes( featureEnvyInstancesByFile: Map<String, List<FeatureEnvy>>, ): ColoredGraph { val instances = featureEnvyInstancesByFile.getValue(label) .map(FeatureEnvy::function) .toSet() val fileGroups = nodes.map(Node::label).groupBy(String::sourcePath).values val groups = fileGroups + instances.map(::listOf) return colorNodes(groups) }
apache-2.0
7d4b9d49959561339a3f8f2fc3a6b414
38.994475
80
0.661694
4.443831
false
false
false
false
ken-kentan/student-portal-plus
app/src/main/java/jp/kentan/studentportalplus/ui/dashboard/DashboardViewModel.kt
1
2435
package jp.kentan.studentportalplus.ui.dashboard import androidx.lifecycle.LiveData import androidx.lifecycle.Transformations import androidx.lifecycle.ViewModel import jp.kentan.studentportalplus.data.PortalRepository import jp.kentan.studentportalplus.data.component.ClassWeek import jp.kentan.studentportalplus.data.component.PortalDataSet import jp.kentan.studentportalplus.data.model.MyClass import jp.kentan.studentportalplus.data.model.Notice import jp.kentan.studentportalplus.ui.SingleLiveData import java.util.* class DashboardViewModel( private val portalRepository: PortalRepository ) : ViewModel() { companion object { const val MAX_ITEM_SIZE = 3 } val portalDataSet: LiveData<PortalDataSet> = Transformations.map(portalRepository.portalDataSet) { set -> return@map PortalDataSet( myClassList = set.myClassList.toTodayTimetable(), lectureInfoList = set.lectureInfoList.filter { it.attend.isAttend() }, lectureCancelList = set.lectureCancelList.filter { it.attend.isAttend() }, noticeList = set.noticeList.take(MAX_ITEM_SIZE) ) } val startMyClassDetailActivity = SingleLiveData<Long>() val startLectureInfoActivity = SingleLiveData<Long>() val startLectureCancelActivity = SingleLiveData<Long>() val startNoticeDetailActivity = SingleLiveData<Long>() fun onMyClassClick(id: Long) { startMyClassDetailActivity.value = id } fun onLectureInfoClick(id: Long) { startLectureInfoActivity.value = id } fun onLectureCancelClick(id: Long) { startLectureCancelActivity.value = id } fun onNoticeItemClick(id: Long) { startNoticeDetailActivity.value = id } fun onNoticeFavoriteClick(data: Notice) { portalRepository.updateNotice(data.copy(isFavorite = !data.isFavorite)) } private fun List<MyClass>.toTodayTimetable(): List<MyClass> { val calender = Calendar.getInstance() val hour = calender.get(Calendar.HOUR_OF_DAY) var dayOfWeek = calender.get(Calendar.DAY_OF_WEEK) // 午後8時以降は明日の時間割 if (hour >= 20) { dayOfWeek++ } // 土、日は月に val week = if (dayOfWeek in Calendar.MONDAY..Calendar.FRIDAY) ClassWeek.valueOf(dayOfWeek - 1) else ClassWeek.MONDAY return filter { it.week == week } } }
gpl-3.0
12dd3950cf9ffe3c84e4f6b502bc492e
32.319444
124
0.702793
4.353902
false
false
false
false
free5ty1e/primestationone-control-android
app/src/main/java/com/chrisprime/primestationonecontrol/utilities/PreferenceStore.kt
1
8936
package com.chrisprime.primestationonecontrol.utilities import android.annotation.SuppressLint import android.content.SharedPreferences import android.content.res.Resources import android.support.annotation.BoolRes import android.support.annotation.IntegerRes import android.support.annotation.StringRes import com.chrisprime.primestationonecontrol.BuildConfig import com.chrisprime.primestationonecontrol.PrimeStationOneControlApplication import com.chrisprime.primestationonecontrol.dagger.Injector import javax.inject.Inject import timber.log.Timber class PreferenceStore { @Inject lateinit var mPreferences: SharedPreferences init { Injector.applicationComponent.inject(this) } private val resources: Resources get() = PrimeStationOneControlApplication.appResourcesContext.resources /** * Retrieves a boolean value. * @param key * * * @param defValue * * * @return */ fun getBoolean(@StringRes key: Int, @BoolRes defValue: Int): Boolean { return getBoolean(key, resources.getBoolean(defValue)) } /** * Retrieves a boolean value. * @param key * * * @param defValue * * * @return */ fun getBoolean(@StringRes key: Int, defValue: Boolean): Boolean { return getBoolean(resources.getString(key), defValue) } /** * Retrieves a boolean value. * @param key * * * @param defValue * * * @return */ fun getBoolean(key: String, defValue: Boolean): Boolean { return mPreferences.getBoolean(key, defValue) } /** * Saves a boolean value. * @param key * * * @param value */ fun putBoolean(@StringRes key: Int, @BoolRes value: Int) { putBoolean(key, resources.getBoolean(value)) } /** * Saves a boolean value. * @param key * * * @param value */ fun putBoolean(@StringRes key: Int, value: Boolean) { putBoolean(resources.getString(key), value) } /** * Saves a boolean value. * @param key * * * @param value */ fun putBoolean(key: String, value: Boolean) { val editor = mPreferences.edit() editor.putBoolean(key, value) editor.apply() } /** * Retrieves an int value. * @param key * * * @param defValue * * * @return */ fun getInt(@StringRes key: Int, @IntegerRes defValue: Int): Int { return getInt(resources.getString(key), resources.getInteger(defValue)) } /** * Retrieves an int value. * @param key * * * @param defValue * * * @return */ fun getInt(key: String, defValue: Int): Int { return mPreferences.getInt(key, defValue) } /** * Saves an int value. * @param key * * * @param value */ fun putInt(@StringRes key: Int, value: Int) { putInt(resources.getString(key), value) } /** * Saves an int value. * @param key * * * @param value */ fun putInt(key: String, value: Int) { val editor = mPreferences.edit() editor.putInt(key, value) editor.apply() } /** * Retrieves a long value. * @param key * * * @param defValue * * * @return */ fun getLong(@StringRes key: Int, @IntegerRes defValue: Int): Long { return getLong(resources.getString(key), resources.getInteger(defValue).toLong()) } fun getLong(@StringRes key: Int, defValue: Long): Long { return getLong(resources.getString(key), defValue) } /** * Retrieves a long value. * @param key * * * @param defValue * * * @return */ fun getLong(key: String, defValue: Long): Long { return mPreferences.getLong(key, defValue) } /** * Saves a long value. * @param key * * * @param value */ fun putLong(key: String, value: Long) { val editor = mPreferences.edit() editor.putLong(key, value) editor.apply() } /** * Saves a long value. * @param key * * * @param value */ fun putLong(@StringRes key: Int, value: Long) { putLong(resources.getString(key), value) } /** * Retrieves an encrypted String value. * @param key * * * @param defValue * * * @return */ fun getString(@StringRes key: Int, @StringRes defValue: Int): String { return getString(key, resources.getString(defValue)) } /** * Retrieves an encrypted String value. * @param key * * * @param defValue * * * @return */ fun getString(@StringRes key: Int, defValue: String?): String { return getString(resources.getString(key), defValue)!! } /** * Retrieves an encrypted String value. * @param key * * * @param defValue * * * @return */ fun getString(key: String, defValue: String?): String? { return mPreferences.getString(key, defValue) } /** * Encrypts & saves a String value. * @param key * * * @param value */ fun putString(@StringRes key: Int, @StringRes value: Int) { putString(key, resources.getString(value)) } /** * Encrypts & saves a String value. * @param key * * * @param value */ fun putString(@StringRes key: Int, value: String?) { putString(resources.getString(key), value) } /** * Encrypts & saves a String value. * @param key * * * @param value */ fun putString(key: String, value: String?) { mPreferences.edit().putString(key, value).apply() } /** * Retrieves an encrypted GSON-annotated Object. * @param key * * * @param defValue * * * @param type * * * @param * * * @return */ fun <T> getObject(@StringRes key: Int, defValue: T?, type: Class<T>): T { return getObject(resources.getString(key), defValue, type) } /** * Retrieves an encrypted GSON-annotated Object. * @param key * * * @param defValue * * * @param type * * * @param * * * @return */ fun <T> getObject(key: String, defValue: T?, type: Class<T>): T { val json = getString(key, null) if (BuildConfig.DEBUG) { Timber.d(".getObject(%s) retrieved json: %s", key, json) } return if (json == null) defValue!! else ParsingUtilities.safeFromJson(json, type)!! } fun <T> getObjectList(@StringRes key: Int, defValue: List<T>?, type: Class<T>): List<T> { return getObjectList(resources.getString(key), defValue, type) } fun <T> getObjectList(key: String, defValue: List<T>?, type: Class<T>): List<T> { val json = getString(key, null) if (BuildConfig.DEBUG) { Timber.d(".getObject(%s) retrieved json: %s", key, json) } return if (json == null) defValue!! else ParsingUtilities.safeListFromJson(json, type)!! } /** * Encrypts & stores an GSON-annotated object. * @param key * * * @param value * * * @param */ fun <T> putObject(@StringRes key: Int, value: T?) { putObject(resources.getString(key), value) } /** * Encrypts & stores an GSON-annotated object. * @param key * * * @param value * * * @param */ fun <T> putObject(key: String, value: T?) { putString(key, if (value == null) null else ParsingUtilities.safeToJson(value)) } /** * Encrypts & stores an GSON-annotated object. * @param key * * * @param value * * * @param */ fun <T> putObjectList(@StringRes key: Int, value: List<T>?, type: Class<T>) { putObjectList(resources.getString(key), value, type) } /** * Encrypts & stores an GSON-annotated object. * @param key * * * @param value * * * @param */ fun <T> putObjectList(key: String, value: List<T>?, type: Class<T>) { putString(key, if (value == null) null else ParsingUtilities.safeToJson(value, type)) } /** * Removes an stored value. * @param key */ fun remove(@StringRes key: Int) { remove(resources.getString(key)) } /** * Removes an stored value. * @param key */ fun remove(key: String) { mPreferences.edit().remove(key).apply() } /** * Removes all stored values. */ @SuppressLint("CommitPrefEdits") fun clear() { mPreferences.edit().clear().commit() } companion object { /** * Gets the Singleton instance. * @return */ val instance = PreferenceStore() } }
mit
05226a126b39d33a5e09be12429b5ffb
20.075472
96
0.558639
4.116076
false
false
false
false
cout970/Magneticraft
ignore/test/block/multiblock/BlockKiln.kt
2
6275
@file:Suppress("DEPRECATION", "OverridingDeprecatedMember") package block.multiblock import com.cout970.magneticraft.block.PROPERTY_ACTIVE import com.cout970.magneticraft.block.PROPERTY_CENTER import com.cout970.magneticraft.block.PROPERTY_DIRECTION import com.cout970.magneticraft.misc.block.get import com.cout970.magneticraft.misc.tileentity.getTile import com.cout970.magneticraft.misc.world.isServer import com.cout970.magneticraft.multiblock.MultiblockContext import com.cout970.magneticraft.multiblock.impl.MultiblockKiln import com.cout970.magneticraft.tileentity.multiblock.TileKiln import com.cout970.magneticraft.tileentity.multiblock.TileMultiblock import net.minecraft.block.Block import net.minecraft.block.ITileEntityProvider import net.minecraft.block.material.Material import net.minecraft.block.state.BlockStateContainer import net.minecraft.block.state.IBlockState import net.minecraft.client.renderer.block.model.ModelResourceLocation import net.minecraft.client.renderer.block.statemap.IStateMapper import net.minecraft.client.renderer.block.statemap.StateMap import net.minecraft.entity.Entity import net.minecraft.entity.EntityLivingBase import net.minecraft.entity.player.EntityPlayer import net.minecraft.item.ItemStack import net.minecraft.tileentity.TileEntity import net.minecraft.util.BlockRenderLayer import net.minecraft.util.EnumFacing import net.minecraft.util.EnumHand import net.minecraft.util.math.AxisAlignedBB import net.minecraft.util.math.BlockPos import net.minecraft.world.World /** * Created by cout970 on 17/08/2016. */ object BlockKiln : BlockMultiblockHeat(Material.IRON, "kiln"), ITileEntityProvider { init { defaultState = defaultState .withProperty(PROPERTY_CENTER, false) .withProperty(PROPERTY_ACTIVE, false) } override fun addCollisionBoxToList(state: IBlockState, worldIn: World, pos: BlockPos, entityBox: AxisAlignedBB?, collidingBoxes: MutableList<AxisAlignedBB>, entityIn: Entity?) { if (state[PROPERTY_ACTIVE] && entityBox != null) { return super.addCollisionBoxToList(state, worldIn, pos, entityBox, collidingBoxes, entityIn) } return addCollisionBoxToList(pos, entityBox, collidingBoxes, state.getCollisionBoundingBox(worldIn, pos)) } override fun getSelectedBoundingBox(state: IBlockState, worldIn: World, pos: BlockPos): AxisAlignedBB { if (state[PROPERTY_ACTIVE]) { return super.getSelectedBoundingBox(state, worldIn, pos) } return FULL_BLOCK_AABB.offset(pos) } override fun isOpaqueCube(state: IBlockState): Boolean = false override fun isFullCube(state: IBlockState): Boolean = false override fun isFullBlock(state: IBlockState?) = false override fun isVisuallyOpaque() = false override fun canRenderInLayer(state: IBlockState, layer: BlockRenderLayer?): Boolean { return state[PROPERTY_CENTER] && !state[PROPERTY_ACTIVE] && super.canRenderInLayer(state, layer) } override fun createNewTileEntity(worldIn: World, meta: Int): TileEntity? = createTileEntity(worldIn, getStateFromMeta(meta)) override fun createTileEntity(world: World, state: IBlockState): TileEntity? { if (state[PROPERTY_CENTER]) return TileKiln() return TileMultiblock() } override fun removedByPlayer(state: IBlockState?, world: World?, pos: BlockPos?, player: EntityPlayer?, willHarvest: Boolean): Boolean { if (state!![PROPERTY_ACTIVE] && world!!.isServer) { breakBlock(world, pos!!, state) return false } else { return super.removedByPlayer(state, world, pos, player, willHarvest) } } override fun getMetaFromState(state: IBlockState): Int { var meta = 0 if (state[PROPERTY_CENTER]) { meta = meta or 8 } if (state[PROPERTY_ACTIVE]) { meta = meta or 4 } val dir = state[PROPERTY_DIRECTION] meta = meta or ((dir.ordinal - 2) and 3) return meta } override fun getStateFromMeta(meta: Int): IBlockState = defaultState. withProperty(PROPERTY_CENTER, (meta and 8) != 0). withProperty(PROPERTY_ACTIVE, (meta and 4) != 0). withProperty(PROPERTY_DIRECTION, EnumFacing.getHorizontal(meta and 3)) override fun createBlockState(): BlockStateContainer { return BlockStateContainer(this, PROPERTY_CENTER, PROPERTY_ACTIVE, PROPERTY_DIRECTION) } override fun onBlockPlacedBy(worldIn: World, pos: BlockPos, state: IBlockState?, placer: EntityLivingBase, stack: ItemStack?) { worldIn.setBlockState(pos, defaultState .withProperty(PROPERTY_DIRECTION, placer.horizontalFacing.opposite) .withProperty(PROPERTY_CENTER, true) .withProperty(PROPERTY_ACTIVE, false)) } override fun onBlockActivated(worldIn: World, pos: BlockPos, state: IBlockState, playerIn: EntityPlayer, hand: EnumHand?, heldItem: ItemStack?, side: EnumFacing?, hitX: Float, hitY: Float, hitZ: Float): Boolean { if (worldIn.isServer && hand == EnumHand.MAIN_HAND && state[PROPERTY_CENTER]) { if (!state[PROPERTY_ACTIVE]) { activateMultiblock(MultiblockContext(MultiblockKiln, worldIn, pos, state[PROPERTY_DIRECTION], playerIn)) } else if (state[PROPERTY_CENTER]) { worldIn.getTile<TileKiln>(pos)?.doorOpen?.not() } else if (worldIn.getBlockState(pos.down())[PROPERTY_CENTER]) { worldIn.getTile<TileKiln>(pos.down())?.doorOpen?.not() } } return true } override fun breakBlock(worldIn: World, pos: BlockPos, state: IBlockState) { if (state[PROPERTY_ACTIVE]) { super.breakBlock(worldIn, pos, state) } } override val stateMapper: ((Block) -> Map<IBlockState, ModelResourceLocation>)? get() = { block -> StateMap.Builder().ignore(PROPERTY_ACTIVE, PROPERTY_CENTER).build().putStateModelLocations(block) } }
gpl-2.0
c9fe4517c11ebcbbce638bfee1a8cf26
41.693878
120
0.687012
4.547101
false
false
false
false
bailuk/AAT
aat-lib/src/main/java/ch/bailu/aat_lib/util/IndexedMap.kt
1
1006
package ch.bailu.aat_lib.util class IndexedMap<K, V> { private val keys = ArrayList<K>() private val map = HashMap<K, V>() fun put(key: K, value: V) { if (!map.containsKey(key)) { keys.add(key) } map[key] = value } fun getValue(key: K) : V? { return map[key] } fun getValueAt(index: Int) : V? { return map[keys[index]] } fun getKeyAt(index: Int) : K? { return keys[index] } fun size(): Int { return keys.size } fun remove(key: K) { map.remove(key) keys.remove(key) } fun forEach(function: (K, V) -> Unit) { keys.forEach { val value = getValue(it) if (value != null) { function(it, value) } } } fun indexOfKey(key: K): Int { keys.forEachIndexed { index, it -> if (it == key) { return index } } return -1 } }
gpl-3.0
1b6414bc5d5cd4691eb4c64bd2b02b68
18
43
0.454274
3.644928
false
false
false
false
nextcloud/android
app/src/androidTest/java/com/owncloud/android/ui/preview/pdf/PreviewPdfFragmentScreenshotIT.kt
1
2035
/* * Nextcloud Android client application * * @author Álvaro Brey Vilas * Copyright (C) 2022 Álvaro Brey Vilas * Copyright (C) 2022 Nextcloud GmbH * * 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 <https://www.gnu.org/licenses/>. */ package com.owncloud.android.ui.preview.pdf import androidx.lifecycle.Lifecycle import androidx.test.espresso.intent.rule.IntentsTestRule import com.nextcloud.client.TestActivity import com.owncloud.android.AbstractIT import com.owncloud.android.datamodel.OCFile import com.owncloud.android.utils.ScreenshotTest import org.junit.Rule import org.junit.Test class PreviewPdfFragmentScreenshotIT : AbstractIT() { companion object { private const val PDF_FILE_ASSET = "test.pdf" } @get:Rule val testActivityRule = IntentsTestRule(TestActivity::class.java, true, false) @Test @ScreenshotTest fun showPdf() { val activity = testActivityRule.launchActivity(null) val pdfFile = getFile(PDF_FILE_ASSET) val ocFile = OCFile("/test.pdf").apply { storagePath = pdfFile.absolutePath } val sut = PreviewPdfFragment.newInstance(ocFile) activity.addFragment(sut) while (!sut.lifecycle.currentState.isAtLeast(Lifecycle.State.RESUMED)) { shortSleep() } activity.runOnUiThread { sut.dismissSnack() } shortSleep() waitForIdleSync() screenshot(activity) } }
gpl-2.0
61e022c407fd9f2f9a17f66a8797ade4
28.897059
81
0.708313
4.344017
false
true
false
false
REBOOTERS/AndroidAnimationExercise
app/src/main/java/home/smart/fly/animations/recyclerview/fragments/StickListFragment.kt
1
3047
package home.smart.fly.animations.recyclerview.fragments import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.TextView import androidx.recyclerview.widget.DividerItemDecoration import androidx.recyclerview.widget.RecyclerView import home.smart.fly.animations.R import home.smart.fly.animations.recyclerview.DataFactory import home.smart.fly.animations.recyclerview.bean.StickBean import home.smart.fly.animations.recyclerview.customitemdecoration.sticky.StickyItemDecoration /** * @author rookie * @since 07-23-2019 */ class StickListFragment : BaseListFragment<StickBean>() { override fun loadDatas(): ArrayList<StickBean> { return DataFactory.initStickData() } override fun getCustomAdapter(): RecyclerView.Adapter<*> { return MyAdapter(datas) } override fun getLayoutResId(): Int { return R.layout.fragment_text_list_recycler_view } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) getRecyclerView().addItemDecoration(DividerItemDecoration(context, DividerItemDecoration.VERTICAL)) getRecyclerView().addItemDecoration(StickyItemDecoration()) } inner class MyAdapter(private var datas: ArrayList<StickBean>) : RecyclerView.Adapter<RecyclerView.ViewHolder>() { private val type_noraml = 0 private val type_stick = 11 override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder { if (viewType == type_stick) { val view = LayoutInflater.from(parent.context).inflate(R.layout.simple_bold_textview_item, parent, false) return StickHoler(view) } else { val view = LayoutInflater.from(parent.context).inflate(R.layout.simple_textview_item, parent, false) return MyHolder(view) } } override fun getItemCount(): Int { return datas.size } override fun getItemViewType(position: Int): Int { if (position % 6 == 0) { return type_stick } else { return type_noraml } } override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) { if (holder is StickHoler) { holder.tv.text = datas[position].content } else if (holder is MyHolder) { holder.tv.text = datas[position].content } } inner class MyHolder(view: View) : RecyclerView.ViewHolder(view) { var tv: TextView = view.findViewById(R.id.text) init { view.tag = false } } inner class StickHoler(view: View) : RecyclerView.ViewHolder(view) { var tv: TextView = view.findViewById(R.id.text) init { view.tag = true } } } }
apache-2.0
e5d70b140eab3ba8bd2a7db4c8cabc30
32.494505
121
0.64063
4.760938
false
false
false
false
panpf/sketch
sketch/src/main/java/com/github/panpf/sketch/stateimage/internal/SketchStateDrawable.kt
1
2982
/* * Copyright (C) 2022 panpf <[email protected]> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.panpf.sketch.stateimage.internal import android.annotation.SuppressLint import android.graphics.drawable.Animatable import android.graphics.drawable.Drawable import androidx.appcompat.graphics.drawable.DrawableWrapper import com.github.panpf.sketch.drawable.internal.AnimatableDrawableWrapper /** * Identify the Sketch state Drawable */ interface SketchStateDrawable internal fun Drawable.toSketchStateDrawable(): Drawable { return if (this is Animatable) { SketchStateAnimatableDrawable(this) } else { SketchStateNormalDrawable(this) } } @SuppressLint("RestrictedApi") open class SketchStateNormalDrawable constructor(drawable: Drawable) : DrawableWrapper(drawable), SketchStateDrawable { override fun mutate(): SketchStateNormalDrawable { val mutateDrawable = wrappedDrawable.mutate() return if (mutateDrawable !== wrappedDrawable) { SketchStateNormalDrawable(mutateDrawable) } else { this } } override fun equals(other: Any?): Boolean { if (this === other) return true if (other !is SketchStateNormalDrawable) return false if (wrappedDrawable != other.wrappedDrawable) return false return true } override fun hashCode(): Int { return wrappedDrawable.hashCode() } override fun toString(): String { return "SketchStateNormalDrawable($wrappedDrawable)" } } @SuppressLint("RestrictedApi") open class SketchStateAnimatableDrawable constructor(animatableDrawable: Drawable) : AnimatableDrawableWrapper(animatableDrawable), SketchStateDrawable { override fun mutate(): SketchStateAnimatableDrawable { val mutateDrawable = wrappedDrawable.mutate() return if (mutateDrawable !== wrappedDrawable) { SketchStateAnimatableDrawable(mutateDrawable) } else { this } } override fun equals(other: Any?): Boolean { if (this === other) return true if (other !is SketchStateAnimatableDrawable) return false if (wrappedDrawable != other.wrappedDrawable) return false return true } override fun hashCode(): Int { return wrappedDrawable.hashCode() } override fun toString(): String { return "SketchStateAnimatableDrawable($wrappedDrawable)" } }
apache-2.0
87ab6b677e18d93499e31a7a430e7ab4
31.075269
84
0.710262
4.856678
false
false
false
false
RocketChat/Rocket.Chat.Android.Lily
app/src/main/java/chat/rocket/android/directory/ui/DirectoryFragment.kt
2
9172
package chat.rocket.android.directory.ui import android.os.Bundle import android.view.LayoutInflater import android.view.Menu import android.view.MenuInflater import android.view.MenuItem import android.view.View import android.view.ViewGroup import androidx.appcompat.app.AppCompatActivity import androidx.appcompat.widget.SearchView import androidx.core.view.isVisible import androidx.fragment.app.Fragment import androidx.recyclerview.widget.DividerItemDecoration import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import chat.rocket.android.R import chat.rocket.android.analytics.AnalyticsManager import chat.rocket.android.analytics.event.ScreenViewEvent import chat.rocket.android.directory.adapter.DirectoryAdapter import chat.rocket.android.directory.adapter.Selector import chat.rocket.android.directory.presentation.DirectoryPresenter import chat.rocket.android.directory.presentation.DirectoryView import chat.rocket.android.directory.uimodel.DirectoryUiModel import chat.rocket.android.helper.EndlessRecyclerViewScrollListener import chat.rocket.android.util.extension.onQueryTextListener import chat.rocket.android.util.extensions.inflate import chat.rocket.android.util.extensions.isNotNullNorBlank import chat.rocket.android.util.extensions.showToast import chat.rocket.android.util.extensions.ui import dagger.android.support.AndroidSupportInjection import kotlinx.android.synthetic.main.app_bar.* import kotlinx.android.synthetic.main.fragment_directory.* import kotlinx.android.synthetic.main.fragment_settings.view_loading import javax.inject.Inject internal const val TAG_DIRECTORY_FRAGMENT = "DirectoryFragment" fun newInstance(): Fragment = DirectoryFragment() class DirectoryFragment : Fragment(), DirectoryView { @Inject lateinit var analyticsManager: AnalyticsManager @Inject lateinit var presenter: DirectoryPresenter private var isSortByChannels: Boolean = true private var isSearchForGlobalUsers: Boolean = false private val linearLayoutManager = LinearLayoutManager(context) private val directoryAdapter = DirectoryAdapter(object : Selector { override fun onChannelSelected(channelId: String, channelName: String) { presenter.toChannel(channelId, channelName) } override fun onUserSelected(username: String, name: String) { presenter.toDirectMessage(username, name) } override fun onGlobalUserSelected(username: String, name: String) { presenter.toDirectMessage(username, name) } }) private val hashtagDrawable by lazy { DrawableHelper.getDrawableFromId(R.drawable.ic_hashtag_16dp, text_sort_by.context) } private val userDrawable by lazy { DrawableHelper.getDrawableFromId(R.drawable.ic_user_16dp, text_sort_by.context) } private val arrowDownDrawable by lazy { DrawableHelper.getDrawableFromId(R.drawable.ic_arrow_down, text_sort_by.context) } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) AndroidSupportInjection.inject(this) setHasOptionsMenu(true) } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? = container?.inflate(R.layout.fragment_directory) override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) setupToolbar() setupRecyclerView() setupListeners() presenter.loadAllDirectoryChannels() analyticsManager.logScreenView(ScreenViewEvent.Directory) } override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) { super.onCreateOptionsMenu(menu, inflater) inflater.inflate(R.menu.directory, menu) val searchMenuItem = menu.findItem(R.id.action_search) val searchView = searchMenuItem?.actionView as SearchView with(searchView) { setIconifiedByDefault(false) maxWidth = Integer.MAX_VALUE onQueryTextListener { updateSorting(isSortByChannels, isSearchForGlobalUsers, it) } } searchMenuItem.setOnActionExpandListener(object : MenuItem.OnActionExpandListener { override fun onMenuItemActionCollapse(item: MenuItem): Boolean { updateSorting(isSortByChannels, isSearchForGlobalUsers, reload = true) return true } override fun onMenuItemActionExpand(item: MenuItem): Boolean { return true } }) } override fun showChannels(dataSet: List<DirectoryUiModel>) { ui { if (directoryAdapter.itemCount == 0) { directoryAdapter.prependData(dataSet) if (dataSet.size >= 60) { recycler_view.addOnScrollListener(object : EndlessRecyclerViewScrollListener(linearLayoutManager) { override fun onLoadMore( page: Int, totalItemsCount: Int, recyclerView: RecyclerView ) { presenter.loadAllDirectoryChannels() } }) } } else { directoryAdapter.appendData(dataSet) } } } override fun showUsers(dataSet: List<DirectoryUiModel>) { ui { if (directoryAdapter.itemCount == 0) { directoryAdapter.prependData(dataSet) if (dataSet.size >= 60) { recycler_view.addOnScrollListener(object : EndlessRecyclerViewScrollListener(linearLayoutManager) { override fun onLoadMore( page: Int, totalItemsCount: Int, recyclerView: RecyclerView ) { presenter.loadAllDirectoryUsers(isSearchForGlobalUsers) } }) } } else { directoryAdapter.appendData(dataSet) } } } override fun showMessage(resId: Int) { ui { showToast(resId) } } override fun showMessage(message: String) { ui { showToast(message) } } override fun showGenericErrorMessage() = showMessage(getString(R.string.msg_generic_error)) override fun showLoading() { ui { view_loading.isVisible = true } } override fun hideLoading() { ui { view_loading.isVisible = false } } fun updateSorting( isSortByChannels: Boolean, isSearchForGlobalUsers: Boolean, query: String? = null, reload: Boolean = false ) { if (query.isNotNullNorBlank() || reload) { directoryAdapter.clearData() presenter.updateSorting(isSortByChannels, isSearchForGlobalUsers, query) } if (this.isSortByChannels != isSortByChannels || this.isSearchForGlobalUsers != isSearchForGlobalUsers ) { this.isSortByChannels = isSortByChannels this.isSearchForGlobalUsers = isSearchForGlobalUsers updateSortByTitle() with(directoryAdapter) { clearData() setSorting(isSortByChannels, isSearchForGlobalUsers) } presenter.updateSorting(isSortByChannels, isSearchForGlobalUsers, query) } } private fun setupToolbar() { with((activity as AppCompatActivity)) { with(toolbar) { setSupportActionBar(this) title = getString(R.string.msg_directory) setNavigationIcon(R.drawable.ic_arrow_back_white_24dp) setNavigationOnClickListener { activity?.onBackPressed() } } } } private fun setupRecyclerView() { ui { with(recycler_view) { layoutManager = linearLayoutManager addItemDecoration(DividerItemDecoration(it, DividerItemDecoration.HORIZONTAL)) adapter = directoryAdapter } } } private fun setupListeners() { text_sort_by.setOnClickListener { activity?.supportFragmentManager?.let { showDirectorySortingBottomSheetFragment(isSortByChannels, isSearchForGlobalUsers, it) } } } private fun updateSortByTitle() { if (isSortByChannels) { text_sort_by.text = getString(R.string.msg_channels) DrawableHelper.compoundStartAndEndDrawable( text_sort_by, hashtagDrawable, arrowDownDrawable ) } else { text_sort_by.text = getString(R.string.msg_users) DrawableHelper.compoundStartAndEndDrawable( text_sort_by, userDrawable, arrowDownDrawable ) } } }
mit
7bae99d4422e3ad0fc75d542b2ab216b
35.692
101
0.644461
5.332558
false
false
false
false
ffc-nectec/FFC
ffc/src/main/kotlin/ffc/app/setting/LegalViewActivity.kt
1
1273
package ffc.app.setting import android.os.Bundle import ffc.android.observe import ffc.android.viewModel import ffc.app.FamilyFolderActivity import ffc.app.R import ffc.app.util.SimpleViewModel import kotlinx.android.synthetic.main.legal_view_activity.content import kotlinx.android.synthetic.main.legal_view_activity.progress import java.net.URL import kotlin.concurrent.thread class LegalViewActivity : FamilyFolderActivity() { private val viewModel by lazy { viewModel<SimpleViewModel<String>>() } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.legal_view_activity) supportActionBar?.setDisplayHomeAsUpEnabled(true) observe(viewModel.content) { docContent -> docContent?.let { content.markdown = it viewModel.loading.value = false } } observe(viewModel.loading) { if (it == true) progress.show() else progress.hide() } viewModel.loading.value = true thread { URL(intent.data.toString()).openStream().reader().use { it.readText() }.let { runOnUiThread { viewModel.content.value = it.trim() } } } } }
apache-2.0
f6b80f12b89db312c23c074a044eadc1
30.825
89
0.667714
4.530249
false
false
false
false
simia-tech/epd-kotlin
src/main/kotlin/com/anyaku/epd/structure/LockedDocument.kt
1
723
package com.anyaku.epd.structure import com.anyaku.crypt.PasswordEncryptedKey import com.anyaku.crypt.asymmetric.Key import com.anyaku.crypt.asymmetric.Signature /** * Contains all the data of a locked document. This includes an id, the public key, the locked contacts and sections * and optionally an encrypted private key. */ public open class LockedDocument( id: String, publicKey: Key, privateKey: PasswordEncryptedKey?, val factory: Factory ) : Contactable { override val id: String = id override val publicKey: Key = publicKey val privateKey: PasswordEncryptedKey? = privateKey val contacts = LockedContactsMap(this) val sections = LockedSectionsMap() }
lgpl-3.0
f35cffaa9686e07e8ed072a059310da9
24.821429
116
0.73029
4.381818
false
false
false
false
calebprior/Android-Boilerplate
app/src/main/kotlin/com/calebprior/boilerplate/ui/CustomProgressBar.kt
1
1112
package com.calebprior.boilerplate.ui import android.app.Dialog import android.content.Context import android.content.DialogInterface import android.view.Window import android.widget.TextView import com.calebprior.boilerplate.R import com.pawegio.kandroid.inflateLayout import org.jetbrains.anko.find class CustomProgressBar { var dialog: Dialog? = null private set fun stop() { dialog?.cancel() dialog = null } fun show(context: Context, title: CharSequence? = null, cancelable: Boolean = false, cancelListener: DialogInterface.OnCancelListener? = null ) { val view = context.inflateLayout(R.layout.progress_bar) title?.let { view.find<TextView>(R.id.id_title).text = it } dialog = Dialog(context, R.style.ProgressBarDialog) dialog?.let { it.requestWindowFeature(Window.FEATURE_NO_TITLE) it.setContentView(view) it.setCancelable(cancelable) it.setOnCancelListener(cancelListener) it.show() } } }
mit
8ef44266651a1d92bc203b6bca6a9f68
24.295455
69
0.645683
4.520325
false
false
false
false
matejdro/WearMusicCenter
mobile/src/main/java/com/matejdro/wearmusiccenter/notifications/NotificationProvider.kt
1
1924
package com.matejdro.wearmusiccenter.notifications import androidx.lifecycle.LiveData import android.content.ComponentName import android.content.Context import android.content.Intent import android.content.ServiceConnection import android.os.IBinder import com.matejdro.wearvibrationcenter.notificationprovider.INotificationListener import com.matejdro.wearvibrationcenter.notificationprovider.INotificationProvider import com.matejdro.wearvibrationcenter.notificationprovider.NotificationProviderConstants import com.matejdro.wearvibrationcenter.notificationprovider.ReceivedNotification import timber.log.Timber import javax.inject.Inject class NotificationProvider @Inject constructor(private val context: Context) : LiveData<ReceivedNotification>() { var providerService: INotificationProvider? = null override fun onActive() { val intent = Intent() intent.component = NotificationProviderConstants.TARGET_COMPONENT intent.action = NotificationProviderConstants.ACTION_NOTIFICATION_PROVIDER try { context.bindService(intent, notificationServiceConnection, 0) } catch (e: Exception) { Timber.e(e, "Notification binding error") } } override fun onInactive() { context.unbindService(notificationServiceConnection) } private val notificationServiceConnection = object : ServiceConnection { override fun onServiceDisconnected(name: ComponentName?) { } override fun onServiceConnected(name: ComponentName, service: IBinder) { providerService = INotificationProvider.Stub.asInterface(service) providerService!!.startSendingNotifications(listener) } } private val listener = object : INotificationListener.Stub() { override fun onNotificationReceived(notification: ReceivedNotification) { postValue(notification) } } }
gpl-3.0
613346cb07b0539fc54fdc424d51ec92
37.48
113
0.760915
5.359331
false
false
false
false
codeka/wwmmo
client/src/main/kotlin/au/com/codeka/warworlds/client/game/solarsystem/SolarSystemScreen.kt
1
4603
package au.com.codeka.warworlds.client.game.solarsystem import android.text.SpannableStringBuilder import android.view.ViewGroup import au.com.codeka.warworlds.client.App import au.com.codeka.warworlds.client.R import au.com.codeka.warworlds.client.concurrency.Threads import au.com.codeka.warworlds.client.game.build.BuildScreen import au.com.codeka.warworlds.client.game.fleets.FleetsScreen import au.com.codeka.warworlds.client.game.starsearch.StarRecentHistoryManager import au.com.codeka.warworlds.client.game.world.ImageHelper import au.com.codeka.warworlds.client.game.world.StarManager import au.com.codeka.warworlds.client.ui.Screen import au.com.codeka.warworlds.client.ui.ScreenContext import au.com.codeka.warworlds.client.ui.SharedViews import au.com.codeka.warworlds.client.ui.ShowInfo import au.com.codeka.warworlds.client.ui.ShowInfo.Companion.builder import au.com.codeka.warworlds.client.util.Callback import au.com.codeka.warworlds.client.util.eventbus.EventHandler import au.com.codeka.warworlds.common.Log import au.com.codeka.warworlds.common.proto.Star /** * A screen which shows a view of the solar system (star, planets, etc) and is the launching point * for managing builds, planet focus, launching fleets and so on. */ class SolarSystemScreen(private var star: Star, private val planetIndex: Int) : Screen() { private lateinit var context: ScreenContext private lateinit var layout: SolarSystemLayout private var isCreated = false override fun onCreate(context: ScreenContext, container: ViewGroup) { super.onCreate(context, container) isCreated = true this.context = context layout = SolarSystemLayout(context.activity, layoutCallbacks, star, planetIndex) App.taskRunner.runTask({ doRefresh() }, Threads.BACKGROUND, 100) App.eventBus.register(eventHandler) } override fun onShow(): ShowInfo { StarRecentHistoryManager.addToLastStars(star) return builder().view(layout).build() } override fun onDestroy() { isCreated = false App.eventBus.unregister(eventHandler) } /* TODO: redraw callback */ override val title: CharSequence get() { val ssb = SpannableStringBuilder() ssb.append("○ ") ssb.append(star.name) ImageHelper.bindStarIcon( ssb, 0, 1, context.activity, star, 24, object : Callback<SpannableStringBuilder> { override fun run(param: SpannableStringBuilder) { // TODO: handle this } }) return ssb } private fun refreshStar(star: Star) { layout.refreshStar(star) this.star = star } private val eventHandler: Any = object : Any() { @EventHandler fun onStarUpdated(s: Star) { if (star.id == s.id) { refreshStar(s) } } } /** * Called on a background thread, we'll simulate the star so that it gets update with correct * energy, minerals, etc. We'll schedule it to run every 5 seconds we're on this screen. */ private fun doRefresh() { StarManager.simulateStarSync(star) if (isCreated) { App.taskRunner.runTask({ doRefresh() }, Threads.BACKGROUND, 5000) } } private val layoutCallbacks: SolarSystemLayout.Callbacks = object : SolarSystemLayout.Callbacks { override fun onBuildClick(planetIndex: Int) { context.pushScreen( BuildScreen(star, planetIndex), SharedViews.Builder() .addSharedView(layout.getPlanetView(planetIndex), R.id.planet_icon) .addSharedView(R.id.bottom_pane) .build()) } override fun onFocusClick(planetIndex: Int) { log.info("focus click: %d", planetIndex) context.pushScreen( PlanetDetailsScreen(star, star.planets[planetIndex]), SharedViews.Builder() .addSharedView(layout.getPlanetView(planetIndex), R.id.planet_icon) .addSharedView(R.id.bottom_pane) .build()) } override fun onSitrepClick() {} override fun onViewColonyClick(planetIndex: Int) { context.pushScreen( PlanetDetailsScreen(star, star.planets[planetIndex]), SharedViews.Builder() .addSharedView(layout.getPlanetView(planetIndex), R.id.planet_icon) .addSharedView(R.id.bottom_pane) .build()) } override fun onFleetClick(fleetId: Long) { context.pushScreen( FleetsScreen(star, fleetId), SharedViews.Builder() .addSharedView(R.id.bottom_pane) .build()) } } companion object { private val log = Log("SolarSystemScreen") } }
mit
2fe73b6406b90ae4b9fa61ea414a5d4d
33.343284
99
0.695718
3.99046
false
false
false
false
Undin/intellij-rust
src/main/kotlin/org/rust/cargo/util/RustCrateUtil.kt
3
2590
/* * Use of this source code is governed by the MIT license that can be * found in the LICENSE file. */ package org.rust.cargo.util import com.intellij.openapi.module.Module import com.intellij.openapi.roots.ModuleRootManager import com.intellij.openapi.vfs.VirtualFile import org.rust.cargo.CargoConstants enum class StdLibType { /** * An indispensable part of the stdlib */ ROOT, /** * A crate that can be used as a dependency if a corresponding feature is turned on */ FEATURE_GATED, /** * A dependency that is not visible outside of the stdlib */ DEPENDENCY } data class StdLibInfo( val name: String, val type: StdLibType, val dependencies: List<String> = emptyList() ) object AutoInjectedCrates { const val STD: String = "std" const val CORE: String = "core" const val TEST: String = "test" val stdlibCrates = listOf( // Roots StdLibInfo(CORE, StdLibType.ROOT), StdLibInfo(STD, StdLibType.ROOT, dependencies = listOf("alloc", "panic_unwind", "panic_abort", CORE, "libc", "compiler_builtins", "profiler_builtins", "unwind")), StdLibInfo("alloc", StdLibType.ROOT, dependencies = listOf(CORE, "compiler_builtins")), StdLibInfo("proc_macro", type = StdLibType.ROOT, dependencies = listOf(STD)), StdLibInfo(TEST, type = StdLibType.ROOT, dependencies = listOf(STD, CORE, "libc", "getopts", "term")), // Feature gated StdLibInfo("libc", StdLibType.FEATURE_GATED), StdLibInfo("panic_unwind", type = StdLibType.FEATURE_GATED, dependencies = listOf(CORE, "libc", "alloc", "unwind", "compiler_builtins")), StdLibInfo("compiler_builtins", StdLibType.FEATURE_GATED, dependencies = listOf(CORE)), StdLibInfo("profiler_builtins", StdLibType.FEATURE_GATED, dependencies = listOf(CORE, "compiler_builtins")), StdLibInfo("panic_abort", StdLibType.FEATURE_GATED, dependencies = listOf(CORE, "libc", "compiler_builtins")), StdLibInfo("unwind", StdLibType.FEATURE_GATED, dependencies = listOf(CORE, "libc", "compiler_builtins")), StdLibInfo("term", StdLibType.FEATURE_GATED, dependencies = listOf(STD, CORE)), StdLibInfo("getopts", StdLibType.FEATURE_GATED, dependencies = listOf(STD, CORE)), ) } /** * Extracts Cargo based project's root-path (the one containing `Cargo.toml`) */ val Module.cargoProjectRoot: VirtualFile? get() = ModuleRootManager.getInstance(this).contentRoots.firstOrNull { it.findChild(CargoConstants.MANIFEST_FILE) != null }
mit
b1b42d52cde59939a326244b07a1a5b8
37.656716
118
0.679537
3.918306
false
false
false
false
Undin/intellij-rust
src/main/kotlin/org/rust/ide/refactoring/RsRenameProcessor.kt
2
10261
/* * Use of this source code is governed by the MIT license that can be * found in the LICENSE file. */ package org.rust.ide.refactoring import com.intellij.openapi.editor.Editor import com.intellij.openapi.project.Project import com.intellij.openapi.util.Pass import com.intellij.psi.PsiElement import com.intellij.psi.PsiNameIdentifierOwner import com.intellij.psi.PsiReference import com.intellij.psi.impl.RenameableFakePsiElement import com.intellij.psi.search.SearchScope import com.intellij.psi.util.parentOfType import com.intellij.refactoring.listeners.RefactoringElementListener import com.intellij.refactoring.rename.RenameDialog import com.intellij.refactoring.rename.RenamePsiElementProcessor import com.intellij.usageView.UsageInfo import com.intellij.usageView.UsageViewUtil import com.intellij.util.containers.MultiMap import org.rust.lang.core.macros.findElementExpandedFrom import org.rust.lang.core.psi.* import org.rust.lang.core.psi.ext.* import org.rust.lang.core.resolve.processLocalVariables import org.rust.lang.core.resolve.ref.RsReferenceBase import javax.swing.Icon class RsRenameProcessor : RenamePsiElementProcessor() { override fun createRenameDialog( project: Project, element: PsiElement, nameSuggestionContext: PsiElement?, editor: Editor? ): RenameDialog { return object : RenameDialog(project, element, nameSuggestionContext, editor) { override fun getFullName(): String { val mod = (element as? RsFile)?.modName ?: return super.getFullName() return "module $mod" } } } override fun canProcessElement(element: PsiElement): Boolean = element is RsNamedElement || element is RsFakeMacroExpansionRenameablePsiElement override fun findExistingNameConflicts( element: PsiElement, newName: String, conflicts: MultiMap<PsiElement, String> ) { val binding = element as? RsPatBinding ?: return val function = binding.parentOfType<RsFunction>() ?: return val functionName = function.name ?: return val foundConflicts = mutableListOf<String>() val scope = if (binding.parentOfType<RsValueParameter>() != null) { function.block?.rbrace?.getPrevNonCommentSibling() as? RsElement } else { binding } scope?.let { s -> processLocalVariables(s) { if (it.name == newName) { val type = when (it.parent) { is RsPatIdent -> { if (it.parentOfType<RsValueParameter>() != null) { "Parameter" } else { "Variable" } } else -> "Binding" } foundConflicts.add("$type `$newName` is already declared in function `$functionName`") } } } if (foundConflicts.isNotEmpty()) { conflicts.put(element, foundConflicts) } } override fun renameElement( element: PsiElement, newName: String, usages: Array<out UsageInfo>, listener: RefactoringElementListener? ) { val psiFactory = RsPsiFactory(element.project) if (element !is RsNamedFieldDecl) { for (usage in usages) { val field = usage.element?.ancestorOrSelf<RsStructLiteralField>(RsBlock::class.java) ?: continue when { field.isShorthand -> { val newPatField = psiFactory.createStructLiteralField(field.referenceName, newName) field.replace(newPatField) } field.referenceName == newName && (field.expr as? RsPathExpr)?.path == usage.element -> { field.expr?.delete() field.colon?.delete() } } } } val newRenameElement = if (element is RsPatBinding && element.parent.parent is RsPatStruct) { val newPatField = psiFactory.createPatFieldFull(element.identifier.text, element.text) element.replace(newPatField).descendantOfTypeStrict<RsPatBinding>()!! } else element super.renameElement(newRenameElement, newName, usages, listener) } override fun prepareRenaming( element: PsiElement, newName: String, allRenames: MutableMap<PsiElement, String>, scope: SearchScope ) { val semanticElement = if (element is RsFakeMacroExpansionRenameablePsiElement) { element.expandedElement } else { element } val rename = if ( semanticElement is RsLifetime || semanticElement is RsLifetimeParameter || semanticElement is RsLabel || semanticElement is RsLabelDecl ) { newName.ensureQuote() } else { newName.trimStart('\'') } allRenames[element] = rename } override fun substituteElementToRename(element: PsiElement, editor: Editor?): PsiElement { val superElement = (element as? RsAbstractable)?.superItem ?: element return superElement.findFakeElementForRenameInMacroBody() ?: superElement } private fun PsiElement.findFakeElementForRenameInMacroBody(): PsiElement? { if (this is RsNameIdentifierOwner) { val identifier = nameIdentifier val sourceIdentifier = identifier?.findElementExpandedFrom() if (sourceIdentifier != null) { when (val sourceIdentifierParent = sourceIdentifier.parent) { is RsNameIdentifierOwner -> if (sourceIdentifierParent.name == name) { return RsFakeMacroExpansionRenameablePsiElement.AttrMacro(this, sourceIdentifierParent) } is RsMacroBodyIdent -> if (sourceIdentifierParent.referenceName == name) { return RsFakeMacroExpansionRenameablePsiElement.BangMacro(this, sourceIdentifierParent) } is RsMacroBodyQuoteIdent -> if (sourceIdentifierParent.referenceName == name) { return RsFakeMacroExpansionRenameablePsiElement.BangMacro(this, sourceIdentifierParent) } is RsPath -> if (sourceIdentifierParent.referenceName == name) { return RsFakeMacroExpansionRenameablePsiElement.AttrPath(this, sourceIdentifier) } } } } return null } override fun substituteElementToRename(element: PsiElement, editor: Editor, renameCallback: Pass<PsiElement>) = renameCallback.pass(substituteElementToRename(element, editor)) override fun findReferences(element: PsiElement, searchScope: SearchScope, searchInCommentsAndStrings: Boolean): Collection<PsiReference> { val refinedElement = if (element is RsFakeMacroExpansionRenameablePsiElement) { element.expandedElement } else { element } return super.findReferences(refinedElement, searchScope, searchInCommentsAndStrings) } override fun prepareRenaming(element: PsiElement, newName: String, allRenames: MutableMap<PsiElement, String>) { super.prepareRenaming(element, newName, allRenames) val semanticElement = if (element is RsFakeMacroExpansionRenameablePsiElement) { element.expandedElement } else { element } when (semanticElement) { is RsAbstractable -> { val trait = (semanticElement.owner as? RsAbstractableOwner.Trait)?.trait ?: return trait.searchForImplementations() .mapNotNull { it.findCorrespondingElement(semanticElement) } .forEach { allRenames[it.findFakeElementForRenameInMacroBody() ?: it] = newName } } is RsMod -> { if (semanticElement is RsFile && semanticElement.declaration == null) return if (semanticElement.pathAttribute != null) return val ownedDir = semanticElement.getOwnedDirectory() ?: return allRenames[ownedDir] = newName } } } private fun String.ensureQuote(): String = if (startsWith('\'')) this else "'$this" } private sealed class RsFakeMacroExpansionRenameablePsiElement( val expandedElement: RsNameIdentifierOwner, parent: PsiElement ) : RenameableFakePsiElement(parent), PsiNameIdentifierOwner { override fun getIcon(): Icon? = expandedElement.getIcon(0) override fun getName(): String? = expandedElement.name override fun getTypeName(): String = UsageViewUtil.getType(expandedElement) class AttrMacro( semantic: RsNameIdentifierOwner, val sourceElement: RsNameIdentifierOwner, ) : RsFakeMacroExpansionRenameablePsiElement(semantic, sourceElement.parent) { override fun getNameIdentifier(): PsiElement? = sourceElement.nameIdentifier override fun setName(name: String): PsiElement { sourceElement.setName(name) return this } } class BangMacro( semantic: RsNameIdentifierOwner, val sourceElement: RsReferenceElementBase, ) : RsFakeMacroExpansionRenameablePsiElement(semantic, sourceElement.parent) { override fun getNameIdentifier(): PsiElement? = sourceElement.referenceNameElement override fun setName(name: String): PsiElement { sourceElement.reference!!.handleElementRename(name) return this } } class AttrPath( semantic: RsNameIdentifierOwner, val sourceElement: PsiElement, ) : RsFakeMacroExpansionRenameablePsiElement(semantic, sourceElement.parent) { override fun getNameIdentifier(): PsiElement = sourceElement override fun setName(name: String): PsiElement { RsReferenceBase.doRename(sourceElement, name) return this } } }
mit
5d86c22b21aea7b8d175e3b9b775787d
39.718254
143
0.633954
5.409067
false
false
false
false
Undin/intellij-rust
src/main/kotlin/org/rust/ide/formatter/processors/RsTrailingCommaFormatProcessor.kt
3
4218
/* * Use of this source code is governed by the MIT license that can be * found in the LICENSE file. */ package org.rust.ide.formatter.processors import com.intellij.openapi.util.TextRange import com.intellij.psi.PsiElement import com.intellij.psi.PsiFile import com.intellij.psi.PsiRecursiveElementWalkingVisitor import com.intellij.psi.codeStyle.CodeStyleSettings import com.intellij.psi.impl.source.codeStyle.PostFormatProcessor import com.intellij.psi.impl.source.codeStyle.PostFormatProcessorHelper import org.rust.ide.formatter.impl.CommaList import org.rust.ide.formatter.rust import org.rust.lang.RsLanguage import org.rust.lang.core.psi.RsBlockFields import org.rust.lang.core.psi.RsElementTypes.COMMA import org.rust.lang.core.psi.RsPsiFactory import org.rust.lang.core.psi.RsStructItem import org.rust.lang.core.psi.ext.* import org.rust.openapiext.document class RsTrailingCommaFormatProcessor : PostFormatProcessor { override fun processElement(source: PsiElement, settings: CodeStyleSettings): PsiElement { doProcess(source, settings, null) return source } override fun processText(source: PsiFile, rangeToReformat: TextRange, settings: CodeStyleSettings): TextRange { return doProcess(source, settings, rangeToReformat).resultTextRange } private fun doProcess(source: PsiElement, settings: CodeStyleSettings, range: TextRange? = null): PostFormatProcessorHelper { val helper = PostFormatProcessorHelper(settings.getCommonSettings(RsLanguage)) helper.resultTextRange = range if (settings.rust.PRESERVE_PUNCTUATION) return helper source.accept(object : PsiRecursiveElementWalkingVisitor() { override fun visitElement(element: PsiElement) { super.visitElement(element) if (!helper.isElementFullyInRange(element)) return val commaList = CommaList.forElement(element.elementType) ?: return when { commaList.removeTrailingComma(element) -> helper.updateResultRange(1, 0) commaList.addTrailingCommaForElement(element) -> helper.updateResultRange(0, 1) } } }) return helper } } /** * Delete trailing comma in one-line blocks */ fun CommaList.removeTrailingComma(list: PsiElement): Boolean { check(list.elementType == this.list) if (PostFormatProcessorHelper.isMultiline(list)) return false val rbrace = list.lastChild if (rbrace.elementType != closingBrace) return false val comma = rbrace.getPrevNonCommentSibling() ?: return false return if (comma.elementType == COMMA) { comma.delete() true } else { false } } fun CommaList.addTrailingCommaForElement(list: PsiElement): Boolean { check(list.elementType == this.list) if (!PostFormatProcessorHelper.isMultiline(list)) return false val rbrace = list.lastChild if (rbrace.elementType != closingBrace) return false val lastElement = rbrace.getPrevNonCommentSibling() ?: return false if (!isElement(lastElement)) return false val trailingSpace = list.node.chars.subSequence( lastElement.startOffsetInParent + lastElement.textLength, rbrace.startOffsetInParent ) if (!trailingSpace.contains('\n')) return false if (list.firstChild.getNextNonCommentSibling() == lastElement) { // allow trailing comma only for struct block fields with a single item if (list !is RsBlockFields || list.parent !is RsStructItem) { return false } } val comma = RsPsiFactory(list.project).createComma() list.addAfter(comma, lastElement) return true } fun CommaList.isOnSameLineAsLastElement(list: PsiElement, element: PsiElement): Boolean { check(list.elementType == this.list && isElement(element)) val rbrace = list.lastChild if (rbrace.elementType != closingBrace) return false val lastElement = rbrace.getPrevNonCommentSibling()?.takeIf(isElement) ?: return false return element == lastElement || element.containingFile.document?.let { it.getLineNumber(element.endOffset) == it.getLineNumber(lastElement.endOffset) } == true }
mit
4ce29e3a5017230a45396ac83113786d
37.697248
129
0.72238
4.718121
false
false
false
false
mightyfrog/S4FD
app/src/main/java/org/mightyfrog/android/s4fd/data/AppDatabase.kt
1
309
package org.mightyfrog.android.s4fd.data import com.raizlabs.android.dbflow.annotation.Database /** * @author Shigehiro Soejima */ @Database(name = AppDatabase.NAME, version = AppDatabase.VERSION, generatedClassSeparator = "_") object AppDatabase { const val NAME = "s4fd" const val VERSION = 1 }
apache-2.0
9f915a5cae81d37c63028807914786c8
24.75
96
0.7411
3.635294
false
false
false
false
androidx/androidx
compose/integration-tests/macrobenchmark-target/src/main/java/androidx/compose/integration/macrobenchmark/target/LazyBoxWithConstraintsActivity.kt
3
2953
/* * Copyright 2022 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.compose.integration.macrobenchmark.target import android.os.Bundle import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.compose.foundation.horizontalScroll import androidx.compose.foundation.layout.BoxWithConstraints import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.items import androidx.compose.foundation.rememberScrollState import androidx.compose.material.Card import androidx.compose.material.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.semantics.contentDescription import androidx.compose.ui.semantics.semantics import androidx.compose.ui.unit.dp class LazyBoxWithConstraintsActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) val itemCount = intent.getIntExtra(EXTRA_ITEM_COUNT, 3000) val items = List(itemCount) { entryIndex -> NestedListEntry( buildList { repeat(10) { add("${entryIndex}x$it") } } ) } setContent { LazyColumn( modifier = Modifier .fillMaxWidth() .semantics { contentDescription = "IamLazy" } ) { items(items) { entry -> NonLazyRow(entry) } } } launchIdlenessTracking() } companion object { const val EXTRA_ITEM_COUNT = "ITEM_COUNT" } } @Composable private fun NonLazyRow(entry: NestedListEntry) { BoxWithConstraints { Row( Modifier .padding(16.dp) .horizontalScroll(rememberScrollState()) ) { entry.list.forEach { Card(Modifier.size(80.dp)) { Text(text = it) } Spacer(Modifier.size(16.dp)) } } } }
apache-2.0
0d16e58cf7f29d4e747820ba04720945
31.097826
75
0.657636
4.848933
false
false
false
false
codebutler/odyssey
retrograde-app-tv/src/main/java/com/codebutler/retrograde/app/feature/search/GamesSearchFragment.kt
1
4909
/* * SearchFragment.kt * * Copyright (C) 2017 Retrograde Project * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.codebutler.retrograde.app.feature.search import android.content.Context import android.os.Bundle import androidx.leanback.app.SearchSupportFragment import androidx.leanback.widget.ArrayObjectAdapter import androidx.leanback.widget.HeaderItem import androidx.leanback.widget.ListRow import androidx.leanback.widget.ListRowPresenter import androidx.leanback.widget.ObjectAdapter import androidx.leanback.widget.OnItemViewClickedListener import androidx.leanback.widget.Presenter import androidx.leanback.widget.Row import androidx.leanback.widget.RowPresenter import androidx.lifecycle.Observer import androidx.paging.LivePagedListBuilder import com.codebutler.retrograde.R import com.codebutler.retrograde.app.feature.main.MainActivity import com.codebutler.retrograde.app.shared.GameInteractionHandler import com.codebutler.retrograde.app.shared.GamePresenter import com.codebutler.retrograde.app.shared.ui.PagedListObjectAdapter import com.codebutler.retrograde.lib.injection.PerFragment import com.codebutler.retrograde.lib.library.db.RetrogradeDatabase import com.codebutler.retrograde.lib.library.db.entity.Game import com.jakewharton.rxrelay2.PublishRelay import com.uber.autodispose.android.lifecycle.scope import com.uber.autodispose.autoDisposable import dagger.Provides import dagger.android.support.AndroidSupportInjection import io.reactivex.android.schedulers.AndroidSchedulers import java.util.concurrent.TimeUnit import javax.inject.Inject class GamesSearchFragment : SearchSupportFragment(), SearchSupportFragment.SearchResultProvider, OnItemViewClickedListener { companion object { fun create(): GamesSearchFragment = GamesSearchFragment() } private val queryTextChangeRelay = PublishRelay.create<String>() private val rowsAdapter = ArrayObjectAdapter(ListRowPresenter()) private var lastQuery: String? = null @Inject lateinit var retrogradeDb: RetrogradeDatabase @Inject lateinit var gameInteractionHandler: GameInteractionHandler override fun onAttach(context: Context?) { AndroidSupportInjection.inject(this) super.onAttach(context) } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setSearchResultProvider(this) queryTextChangeRelay .debounce(1, TimeUnit.SECONDS) .observeOn(AndroidSchedulers.mainThread()) .autoDisposable(scope()) .subscribe(this::search) setOnItemViewClickedListener(this) gameInteractionHandler.onRefreshListener = cb@{ search(lastQuery ?: return@cb) } } override fun getResultsAdapter(): ObjectAdapter = rowsAdapter override fun onItemClicked( itemViewHolder: Presenter.ViewHolder, item: Any, rowViewHolder: RowPresenter.ViewHolder, row: Row ) { when (item) { is Game -> gameInteractionHandler.onItemClick(item) } } override fun onQueryTextChange(newQuery: String): Boolean { queryTextChangeRelay.accept(newQuery) return true } override fun onQueryTextSubmit(query: String): Boolean { search(query) return true } private fun search(query: String) { lastQuery = query rowsAdapter.clear() LivePagedListBuilder(retrogradeDb.gameSearchDao().search(query), 50) .build() .observe(this, Observer { pagedList -> val header = HeaderItem(getString(R.string.search_results, query)) val adapter = PagedListObjectAdapter( GamePresenter(requireActivity(), gameInteractionHandler), Game.DIFF_CALLBACK ) adapter.pagedList = pagedList rowsAdapter.add(ListRow(header, adapter)) }) } @dagger.Module class Module { @Provides @PerFragment fun gameInteractionHandler(activity: MainActivity, retrogradeDb: RetrogradeDatabase) = GameInteractionHandler(activity, retrogradeDb) } }
gpl-3.0
b0ba8685b8b4a70109aa2e5a9c080e4c
34.572464
94
0.719495
4.958586
false
false
false
false
bsmr-java/lwjgl3
modules/templates/src/main/kotlin/org/lwjgl/vulkan/templates/NV_glsl_shader.kt
1
1397
/* * Copyright LWJGL. All rights reserved. * License terms: https://www.lwjgl.org/license */ package org.lwjgl.vulkan.templates import org.lwjgl.generator.* import org.lwjgl.vulkan.* val NV_glsl_shader = "NVGLSLShader".nativeClassVK("NV_glsl_shader", postfix = NV) { documentation = """ This extension allows GLSL shaders written to the {@code GL_KHR_vulkan_glsl} extension specification to be used instead of SPIR-V. The implementation will automatically detect which the shader is SPIR-V or GLSL and compile it appropriatly. <h3>Passing in GLSL code example</h3> ${codeBlock(""" char const vss[] = "\#version 450 core\n" "layout(location = 0) in vec2 aVertex;\n" "layout(location = 1) in vec4 aColor;\n" "out vec4 vColor;\n" "void main()\n" "{\n" " vColor = aColor;\n" " gl_Position = vec4(aVertex, 0, 1);\n" "}\n" ; VkShaderModuleCreateInfo vertexShaderInfo = { VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO }; vertexShaderInfo.codeSize = sizeof vss; vertexShaderInfo.pCode = vss; VkShaderModule vertexShader; vkCreateShaderModule(device, &vertexShaderInfo, 0, &vertexShader);""")} """ IntConstant( "The extension specification version.", "NV_GLSL_SHADER_SPEC_VERSION".."1" ) StringConstant( "The extension name.", "NV_GLSL_SHADER_EXTENSION_NAME".."VK_NV_glsl_shader" ) IntConstant( "VkResult", "ERROR_INVALID_SHADER_NV".."-1000012000" ) }
bsd-3-clause
be6b96985f2db6a817c9ba5e94555462
24.888889
151
0.710093
3.153499
false
false
false
false
mikrobi/TransitTracker_android
app/src/main/java/de/jakobclass/transittracker/models/VehicleType.kt
1
1080
package de.jakobclass.transittracker.models import android.graphics.Color enum class VehicleType(val code: Int) { SuburbanTrain(1), Subway(2), StreetCar(4), Bus(8), Ferry(16), LongDistanceTrain(32), RegionalTrain(64); companion object { fun fromCode(code: Int): VehicleType? = VehicleType.values().first { it.code == code } } val color: Int get() = when (this) { SuburbanTrain -> Color.argb(255, 16, 196, 0) Subway -> Color.argb(255, 0, 135, 232) StreetCar -> Color.argb(255, 224, 0, 0) Bus -> Color.argb(255, 152, 0, 175) Ferry -> Color.argb(255, 249, 237, 0) LongDistanceTrain -> Color.argb(255, 0, 0, 0) RegionalTrain -> Color.argb(255, 0, 0, 0) } val abbreviation: String get() = when (this) { SuburbanTrain -> "S" Subway -> "U" StreetCar -> "T" Bus -> "B" Ferry -> "F" LongDistanceTrain -> "Z" RegionalTrain -> "R" } }
gpl-3.0
796c8978250e9a2d06727ccda1796013
26.717949
94
0.52037
3.495146
false
false
false
false
wealthfront/magellan
magellan-sample-advanced/src/main/java/com/wealthfront/magellan/sample/advanced/designcereal/DesignCerealStyleStep.kt
1
1739
package com.wealthfront.magellan.sample.advanced.designcereal import android.content.Context import com.wealthfront.magellan.core.Step import com.wealthfront.magellan.sample.advanced.R import com.wealthfront.magellan.sample.advanced.databinding.DesignCerealStyleBinding import com.wealthfront.magellan.sample.advanced.designcereal.CerealPieceColor.NATURAL import com.wealthfront.magellan.sample.advanced.designcereal.CerealPieceColor.RAINBOW import com.wealthfront.magellan.sample.advanced.designcereal.CerealPieceStyle.FROSTED import com.wealthfront.magellan.sample.advanced.designcereal.CerealPieceStyle.PLAIN class DesignCerealStyleStep( private val goToConfirmation: (CerealPieceStyle, CerealPieceColor) -> Unit ) : Step<DesignCerealStyleBinding>(DesignCerealStyleBinding::inflate) { private var pieceStyle: CerealPieceStyle? = null private var pieceColor: CerealPieceColor? = null override fun onShow(context: Context, binding: DesignCerealStyleBinding) { binding.styleSelection.setOnCheckedChangeListener { _, checkedId -> if (checkedId == R.id.plain) { pieceStyle = PLAIN } else if (checkedId == R.id.frosted) { pieceStyle = FROSTED } updateNextButton(binding) } binding.colorSelection.setOnCheckedChangeListener { _, checkedId -> if (checkedId == R.id.natural) { pieceColor = NATURAL } else if (checkedId == R.id.rainbow) { pieceColor = RAINBOW } updateNextButton(binding) } binding.next.setOnClickListener { goToConfirmation(pieceStyle!!, pieceColor!!) } } private fun updateNextButton(binding: DesignCerealStyleBinding) { binding.next.isEnabled = (pieceStyle != null && pieceColor != null) } }
apache-2.0
b5aca1cad1ebad96070e3212ab015c28
36.804348
85
0.757332
4.170264
false
false
false
false
wealthfront/magellan
magellan-rx/src/main/java/com/wealthfront/magellan/rx/RxUnsubscriber.kt
1
763
package com.wealthfront.magellan.rx import android.content.Context import com.wealthfront.magellan.lifecycle.LifecycleAware import rx.Subscription import rx.subscriptions.CompositeSubscription import javax.inject.Inject public class RxUnsubscriber @Inject constructor() : LifecycleAware { private var subscriptions: CompositeSubscription? = null public fun autoUnsubscribe(subscription: Subscription) { if (subscriptions == null) { subscriptions = CompositeSubscription() } subscriptions!!.add(subscription) } public fun autoUnsubscribe(vararg subscription: Subscription) { subscription.forEach { autoUnsubscribe(it) } } override fun hide(context: Context) { subscriptions?.unsubscribe() subscriptions = null } }
apache-2.0
c4530d1957973082f2ff5563b4f6431c
26.25
68
0.769332
4.986928
false
false
false
false
vitorsalgado/android-boilerplate
utils/src/main/kotlin/br/com/vitorsalgado/example/utils/RxBus.kt
1
808
package br.com.vitorsalgado.example.utils import io.reactivex.Observable import io.reactivex.disposables.CompositeDisposable import io.reactivex.subjects.PublishSubject object RxBus { val disposables = mutableMapOf<Any, List<CompositeDisposable>>() val publisher: PublishSubject<Any> = PublishSubject.create() fun publish(event: Any) = publisher.onNext(event) fun <T> subscribe(eventType: Class<T>): Observable<T> = publisher.ofType(eventType) fun <T> register(eventType: Class<T>, subscription: CompositeDisposable) { val list = getDisposablesByEvent(eventType).apply { add(subscription) } disposables[eventType] = list } private fun <T> getDisposablesByEvent(eventType: Class<T>): MutableList<CompositeDisposable> = disposables[eventType].orEmpty().toMutableList() }
apache-2.0
aeb58a9a4e09736863a62e2fbaef0728
32.666667
145
0.764851
4.415301
false
false
false
false
CruGlobal/android-gto-support
gto-support-material-components/src/main/kotlin/org/ccci/gto/android/common/material/tabs/TabLayout.kt
2
971
package org.ccci.gto.android.common.material.tabs import android.graphics.drawable.Drawable import androidx.annotation.ColorInt import androidx.core.graphics.drawable.DrawableCompat import com.google.android.material.tabs.TabLayout import com.google.android.material.tabs.baseBackgroundDrawableCompat import com.google.android.material.tabs.populateFromPagerAdapterCompat fun TabLayout.notifyPagerAdapterChanged() = populateFromPagerAdapterCompat() var TabLayout.Tab.background: Drawable? get() = view.baseBackgroundDrawableCompat set(value) { view.baseBackgroundDrawableCompat = value view.invalidate() parent?.invalidate() } fun TabLayout.Tab.setBackgroundTint(@ColorInt tint: Int) { background = background?.let { DrawableCompat.wrap(it).mutate() } ?.apply { DrawableCompat.setTint(this, tint) } } var TabLayout.Tab.visibility: Int get() = view.visibility set(value) { view.visibility = value }
mit
26e25403c737daea220ed739e2415ca9
32.482759
76
0.762101
4.29646
false
false
false
false
ThomasVadeSmileLee/cyls
src/main/kotlin/com/scienjus/smartqq/constant/ApiURL.kt
1
5483
package com.scienjus.smartqq.constant /** * Api的请求地址和Referer * @author ScienJus * * * @date 2015/12/19 */ class ApiURL(val url: String, val referer: String?) { fun buildUrl(vararg params: Any): String { var i = 1 var url = this.url for (param in params) { url = url.replace("{${i++}}", param.toString()) } return url } val origin: String get() = this.url.substring(0, url.lastIndexOf("/")) companion object { @JvmStatic val USER_AGENT = "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 " + "(KHTML, like Gecko) Chrome/45.0.2454.101 Safari/537.36" @JvmStatic val GET_QR_CODE = ApiURL( "https://ssl.ptlogin2.qq.com/ptqrshow?appid=501004106&e=0&l=M&s=5&d=72&v=4&t=0.1", "" ) @JvmStatic val VERIFY_QR_CODE = ApiURL( "https://ssl.ptlogin2.qq.com/ptqrlogin?" + "ptqrtoken={1}&webqq_type=10&remember_uin=1&login2qq=1&aid=501004106&" + "u1=http%3A%2F%2Fw.qq.com%2Fproxy.html%3Flogin2qq%3D1%26webqq_type%3D10&" + "ptredirect=0&ptlang=2052&daid=164&from_ui=1&pttype=1&dumy=&fp=loginerroralert&0-0-157510&" + "mibao_css=m_webqq&t=undefined&g=1&js_type=0&js_ver=10184&login_sig=&pt_randsalt=3", "https://ui.ptlogin2.qq.com/cgi-bin/login?" + "daid=164&target=self&style=16&mibao_css=m_webqq&" + "appid=501004106&enable_qlogin=0&no_verifyimg=1&" + "s_url=http%3A%2F%2Fw.qq.com%2Fproxy.html&f_url=loginerroralert&" + "strong_login=1&login_state=10&t=20131024001" ) @JvmStatic val GET_PTWEBQQ = ApiURL( "{1}", null ) @JvmStatic val GET_VFWEBQQ = ApiURL( "http://s.web2.qq.com/api/getvfwebqq?ptwebqq={1}&clientid=53999199&psessionid=&t=0.1", "http://s.web2.qq.com/proxy.html?v=20130916001&callback=1&id=1" ) @JvmStatic val GET_UIN_AND_PSESSIONID = ApiURL( "http://d1.web2.qq.com/channel/login2", "http://d1.web2.qq.com/proxy.html?v=20151105001&callback=1&id=2" ) @JvmStatic val GET_GROUP_LIST = ApiURL( "http://s.web2.qq.com/api/get_group_name_list_mask2", "http://d1.web2.qq.com/proxy.html?v=20151105001&callback=1&id=2" ) @JvmStatic val POLL_MESSAGE = ApiURL( "http://d1.web2.qq.com/channel/poll2", "http://d1.web2.qq.com/proxy.html?v=20151105001&callback=1&id=2" ) @JvmStatic val SEND_MESSAGE_TO_GROUP = ApiURL( "http://d1.web2.qq.com/channel/send_qun_msg2", "http://d1.web2.qq.com/proxy.html?v=20151105001&callback=1&id=2" ) @JvmStatic val GET_FRIEND_LIST = ApiURL( "http://s.web2.qq.com/api/get_user_friends2", "http://s.web2.qq.com/proxy.html?v=20130916001&callback=1&id=1" ) @JvmStatic val SEND_MESSAGE_TO_FRIEND = ApiURL( "http://d1.web2.qq.com/channel/send_buddy_msg2", "http://d1.web2.qq.com/proxy.html?v=20151105001&callback=1&id=2" ) @JvmStatic val GET_DISCUSS_LIST = ApiURL( "http://s.web2.qq.com/api/get_discus_list?clientid=53999199&psessionid={1}&vfwebqq={2}&t=0.1", "http://s.web2.qq.com/proxy.html?v=20130916001&callback=1&id=1" ) @JvmStatic val SEND_MESSAGE_TO_DISCUSS = ApiURL( "http://d1.web2.qq.com/channel/send_discu_msg2", "http://d1.web2.qq.com/proxy.html?v=20151105001&callback=1&id=2" ) @JvmStatic val GET_ACCOUNT_INFO = ApiURL( "http://s.web2.qq.com/api/get_self_info2?t=0.1", "http://s.web2.qq.com/proxy.html?v=20130916001&callback=1&id=1" ) @JvmStatic val GET_RECENT_LIST = ApiURL( "http://d1.web2.qq.com/channel/get_recent_list2", "http://d1.web2.qq.com/proxy.html?v=20151105001&callback=1&id=2" ) @JvmStatic val GET_FRIEND_STATUS = ApiURL( "http://d1.web2.qq.com/channel/get_online_buddies2?vfwebqq={1}&clientid=53999199&psessionid={2}&t=0.1", "http://d1.web2.qq.com/proxy.html?v=20151105001&callback=1&id=2" ) @JvmStatic val GET_GROUP_INFO = ApiURL( "http://s.web2.qq.com/api/get_group_info_ext2?gcode={1}&vfwebqq={2}&t=0.1", "http://s.web2.qq.com/proxy.html?v=20130916001&callback=1&id=1" ) @JvmStatic val GET_QQ_BY_ID = ApiURL( "http://s.web2.qq.com/api/get_friend_uin2?tuin={1}&type=1&vfwebqq={2}&t=0.1", "http://s.web2.qq.com/proxy.html?v=20130916001&callback=1&id=1" ) @JvmStatic val GET_DISCUSS_INFO = ApiURL( "http://d1.web2.qq.com/channel/get_discu_info?did={1}&vfwebqq={2}&clientid=53999199&psessionid={3}&t=0.1", "http://d1.web2.qq.com/proxy.html?v=20151105001&callback=1&id=2" ) @JvmStatic val GET_FRIEND_INFO = ApiURL( "http://s.web2.qq.com/api/get_friend_info2?tuin={1}&vfwebqq={2}&clientid=53999199&psessionid={3}&t=0.1", "http://s.web2.qq.com/proxy.html?v=20130916001&callback=1&id=1" ) } }
mit
327f31ca89b3d4dd1045a2b9ff0ec280
47.415929
122
0.553646
2.824471
false
false
false
false
Shockah/Godwit
core/src/pl/shockah/godwit/node/gesture/TapGestureRecognizer.kt
1
1953
package pl.shockah.godwit.node.gesture import com.badlogic.gdx.Gdx import com.badlogic.gdx.utils.Timer import pl.shockah.godwit.geom.Vec2 class TapGestureRecognizer( val tapsRequired: Int = 1, val delay: Float = 0f, val delegate: (recognizer: TapGestureRecognizer, touch: Touch) -> Unit ) : GestureRecognizer() { var touch: Touch? = null private var timerTask: Timer.Task? = null private var taps = 0 override var state: State get() = super.state set(value) { super.state = value if (finished) { touch = null taps = 0 timerTask?.cancel() timerTask = null } } override fun toString(): String { return "[${this::class.simpleName}:$tapsRequired]" } override fun onRequiredFailFailed(recognizer: GestureRecognizer) { val touch = touch if (touch != null && taps >= tapsRequired) { if (!requiredRecognizersFailed) return if (touch.recognizer != null) { state = State.Failed return } touch.recognizer = this state = State.Ended delegate(this, touch) } } override fun handleTouchDown(touch: Touch, point: Vec2) { if (state == State.Possible || inProgress) { if (inProgress) { state = State.Changed taps++ } else { state = State.Began taps = 1 } this.touch = touch timerTask?.cancel() if (delay > 0f) { timerTask = Timer.schedule(object : Timer.Task() { override fun run() { Gdx.app.postRunnable { state = State.Failed [email protected] = null taps = 0 timerTask = null } } }, delay) } else { timerTask = null } } } override fun handleTouchUp(touch: Touch, point: Vec2) { if (inProgress && this.touch == touch && taps >= tapsRequired) { if (!requiredRecognizersFailed) return if (touch.recognizer != null) { state = State.Failed return } touch.recognizer = this state = State.Ended delegate(this, touch) } } }
apache-2.0
f498bdc1860b0d1ef1e3a04a25d6b8ea
20.010753
72
0.637993
3.304569
false
false
false
false
PassionateWsj/YH-Android
app/src/main/java/com/intfocus/template/dashboard/feedback/list/FeedbackListAdapter.kt
1
2762
package com.intfocus.template.dashboard.feedback.list import android.content.Context import android.support.v7.widget.RecyclerView import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.ImageView import android.widget.TextView import com.bumptech.glide.Glide import com.intfocus.template.R import com.intfocus.template.dashboard.feedback.EventFeedbackContent import com.intfocus.template.model.response.mine_page.FeedbackList import org.greenrobot.eventbus.EventBus /** * @author liuruilin * @data 2017/12/5 * @describe */ class FeedbackListAdapter(var context: Context?) : RecyclerView.Adapter<RecyclerView.ViewHolder>() { private var mData: MutableList<FeedbackList.FeedbackListItemData>? = null override fun getItemCount(): Int = mData?.size ?: 0 fun setData(data: List<FeedbackList.FeedbackListItemData>) { if (mData == null) { mData = mutableListOf() } mData?.clear() mData?.addAll(data) notifyDataSetChanged() } override fun onCreateViewHolder(parent: ViewGroup?, viewType: Int): RecyclerView.ViewHolder { val contentView = LayoutInflater.from(context).inflate(R.layout.item_feedback_list, parent, false) return FeedbackListViewHolder(contentView) } override fun onBindViewHolder(holder: RecyclerView.ViewHolder?, position: Int) { when (holder) { is FeedbackListViewHolder -> { mData?.let { val itemData = it[position] if (itemData.images != null && itemData.images!!.isNotEmpty()) { holder.ivFeedbackListItem.visibility = View.VISIBLE Glide.with(context) .load(itemData.images!![0]) .placeholder(R.drawable.default_icon) .into(holder.ivFeedbackListItem) } else { holder.ivFeedbackListItem.visibility = View.INVISIBLE } holder.tvFeedbackListItemContent.text = itemData.content holder.tvFeedbackListItemTime.text = itemData.created_at holder.itemView.setOnClickListener { EventBus.getDefault().post(EventFeedbackContent(itemData.id)) } } } } } class FeedbackListViewHolder(view: View) : RecyclerView.ViewHolder(view) { var ivFeedbackListItem: ImageView = view.findViewById(R.id.iv_feedback_list) var tvFeedbackListItemContent: TextView = view.findViewById(R.id.tv_feedback_list_content) var tvFeedbackListItemTime: TextView = view.findViewById(R.id.tv_feedback_list_time) } }
gpl-3.0
747906cb9b13bd25e02b638f4cf5008d
39.617647
120
0.653512
4.795139
false
false
false
false
rhdunn/xquery-intellij-plugin
src/plugin-saxon/main/uk/co/reecedunn/intellij/plugin/saxon/lang/SaxonEE.kt
1
2297
/* * Copyright (C) 2020 Reece H. Dunn * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package uk.co.reecedunn.intellij.plugin.saxon.lang import com.intellij.navigation.ItemPresentation import uk.co.reecedunn.intellij.plugin.saxon.resources.SaxonIcons import uk.co.reecedunn.intellij.plugin.xpm.lang.XpmProductType import uk.co.reecedunn.intellij.plugin.xpm.lang.XpmProductVersion import javax.swing.Icon object SaxonEE : ItemPresentation, XpmProductType { // region ItemPresentation override fun getPresentableText(): String = "Saxon Enterprise Edition" override fun getLocationString(): String? = null override fun getIcon(unused: Boolean): Icon = SaxonIcons.Product // endregion // region XpmProductType override val id: String = "saxon/EE" override val presentation: ItemPresentation get() = this // endregion // region Language Versions val VERSION_9_4: XpmProductVersion = SaxonVersion(this, 9, 4, "map") val VERSION_9_5: XpmProductVersion = SaxonVersion(this, 9, 5, "XQuery 3.0 REC") // 9.6 for HE val VERSION_9_7: XpmProductVersion = SaxonVersion(this, 9, 7, "XQuery 3.1 REC") val VERSION_9_8: XpmProductVersion = SaxonVersion( this, 9, 8, "tuple(), union(), declare type, orElse, andAlso, fn{...}" ) val VERSION_9_9: XpmProductVersion = SaxonVersion(this, 9, 9, "calling java functions with '\$o?f()'") val VERSION_10_0: XpmProductVersion = SaxonVersion( this, 10, 0, ".{...}, _{$1}, otherwise, type(c), element(*:test), for member" ) @Suppress("unused") val languageVersions: List<XpmProductVersion> = listOf( VERSION_9_4, VERSION_9_5, VERSION_9_7, VERSION_9_8, VERSION_9_9, VERSION_10_0 ) // endregion }
apache-2.0
0119202b6e35486edc87eb5e5ec46b5a
33.80303
106
0.694384
3.939966
false
false
false
false
StepicOrg/stepic-android
app/src/main/java/org/stepic/droid/storage/structure/DbStructureCourse.kt
1
6327
package org.stepic.droid.storage.structure import android.database.sqlite.SQLiteDatabase import androidx.sqlite.db.SupportSQLiteDatabase object DbStructureCourse { const val TABLE_NAME = "course" object Columns { const val ID = "id" const val TITLE = "title" const val DESCRIPTION = "description" const val COVER = "cover" const val CERTIFICATE = "certificate" const val REQUIREMENTS = "requirements" const val SUMMARY = "summary" const val WORKLOAD = "workload" const val INTRO = "intro" const val INTRO_VIDEO_ID = "intro_video_id" const val LANGUAGE = "language" const val AUTHORS = "authors" const val INSTRUCTORS = "instructors" const val SECTIONS = "sections" const val COURSE_FORMAT = "course_format" const val TARGET_AUDIENCE = "target_audience" const val CERTIFICATE_FOOTER = "certificate_footer" const val CERTIFICATE_COVER_ORG = "certificate_cover_org" const val TOTAL_UNITS = "total_units" const val ENROLLMENT = "enrollment" const val PROGRESS = "progress" const val OWNER = "owner" const val READINESS = "readiness" const val IS_CONTEST = "is_contest" const val IS_FEATURED = "is_featured" const val IS_ACTIVE = "is_active" const val IS_PUBLIC = "is_public" const val IS_ARCHIVED = "is_archived" const val IS_FAVORITE = "is_favorite" const val CERTIFICATE_DISTINCTION_THRESHOLD = "certificate_distinction_threshold" const val CERTIFICATE_REGULAR_THRESHOLD = "certificate_regular_threshold" const val CERTIFICATE_LINK = "certificate_link" const val IS_CERTIFICATE_AUTO_ISSUED = "is_certificate_auto_issued" const val IS_CERTIFICATE_ISSUED = "is_certificate_issued" const val WITH_CERTIFICATE = "with_certificate" const val LAST_DEADLINE = "last_deadline" const val BEGIN_DATE = "begin_date" const val END_DATE = "end_date" const val SLUG = "slug" const val SCHEDULE_LINK = "schedule_link" const val SCHEDULE_LONG_LINK = "schedule_long_link" const val SCHEDULE_TYPE = "schedule_type" const val LAST_STEP = "last_step" const val LEARNERS_COUNT = "learners_count" const val REVIEW_SUMMARY = "review_summary" const val TIME_TO_COMPLETE = "time_to_complete" const val OPTIONS = "options" const val ACTIONS = "actions" const val IS_PAID = "is_paid" const val PRICE = "price" const val CURRENCY_CODE = "currency_code" const val DISPLAY_PRICE = "display_price" const val PRICE_TIER = "price_tier" const val IS_PROCTORED = "is_proctored" const val DEFAULT_PROMO_CODE_NAME = "default_promo_code_name" const val DEFAULT_PROMO_CODE_PRICE = "default_promo_code_price" const val DEFAULT_PROMO_CODE_DISCOUNT = "default_promo_code_discount" const val DEFAULT_PROMO_CODE_EXPIRE_DATE = "default_promo_code_expire_date" } fun createTable(db: SupportSQLiteDatabase) { db.execSQL(""" CREATE TABLE IF NOT EXISTS ${DbStructureCourse.TABLE_NAME} ( ${DbStructureCourse.Columns.ID} LONG PRIMARY KEY, ${DbStructureCourse.Columns.TITLE} TEXT, ${DbStructureCourse.Columns.DESCRIPTION} TEXT, ${DbStructureCourse.Columns.COVER} TEXT, ${DbStructureCourse.Columns.CERTIFICATE} TEXT, ${DbStructureCourse.Columns.REQUIREMENTS} TEXT, ${DbStructureCourse.Columns.SUMMARY} TEXT, ${DbStructureCourse.Columns.WORKLOAD} TEXT, ${DbStructureCourse.Columns.INTRO} TEXT, ${DbStructureCourse.Columns.INTRO_VIDEO_ID} LONG, ${DbStructureCourse.Columns.LANGUAGE} TEXT, ${DbStructureCourse.Columns.AUTHORS} TEXT, ${DbStructureCourse.Columns.INSTRUCTORS} TEXT, ${DbStructureCourse.Columns.SECTIONS} TEXT, ${DbStructureCourse.Columns.COURSE_FORMAT} TEXT, ${DbStructureCourse.Columns.TARGET_AUDIENCE} TEXT, ${DbStructureCourse.Columns.CERTIFICATE_FOOTER} TEXT, ${DbStructureCourse.Columns.CERTIFICATE_COVER_ORG} TEXT, ${DbStructureCourse.Columns.TOTAL_UNITS} LONG, ${DbStructureCourse.Columns.ENROLLMENT} LONG, ${DbStructureCourse.Columns.PROGRESS} TEXT, ${DbStructureCourse.Columns.OWNER} LONG, ${DbStructureCourse.Columns.READINESS} REAL, ${DbStructureCourse.Columns.IS_CONTEST} INTEGER, ${DbStructureCourse.Columns.IS_FEATURED} INTEGER, ${DbStructureCourse.Columns.IS_ACTIVE} INTEGER, ${DbStructureCourse.Columns.IS_PUBLIC} INTEGER, ${DbStructureCourse.Columns.CERTIFICATE_DISTINCTION_THRESHOLD} INTEGER, ${DbStructureCourse.Columns.CERTIFICATE_REGULAR_THRESHOLD} INTEGER, ${DbStructureCourse.Columns.CERTIFICATE_LINK} TEXT, ${DbStructureCourse.Columns.IS_CERTIFICATE_AUTO_ISSUED} INTEGER, ${DbStructureCourse.Columns.LAST_DEADLINE} TEXT, ${DbStructureCourse.Columns.BEGIN_DATE} TEXT, ${DbStructureCourse.Columns.END_DATE} TEXT, ${DbStructureCourse.Columns.SLUG} TEXT, ${DbStructureCourse.Columns.SCHEDULE_LINK} TEXT, ${DbStructureCourse.Columns.SCHEDULE_LONG_LINK} TEXT, ${DbStructureCourse.Columns.SCHEDULE_TYPE} TEXT, ${DbStructureCourse.Columns.LAST_STEP} TEXT, ${DbStructureCourse.Columns.LEARNERS_COUNT} LONG, ${DbStructureCourse.Columns.REVIEW_SUMMARY} LONG, ${DbStructureCourse.Columns.TIME_TO_COMPLETE} LONG, ${DbStructureCourse.Columns.IS_PAID} INTEGER, ${DbStructureCourse.Columns.PRICE} TEXT, ${DbStructureCourse.Columns.CURRENCY_CODE} TEXT, ${DbStructureCourse.Columns.DISPLAY_PRICE} TEXT, ${DbStructureCourse.Columns.PRICE_TIER} TEXT ) """.trimIndent()) } }
apache-2.0
dd751640216ec17a4bfe2401b484c430
45.189781
89
0.627628
4.690141
false
false
false
false
jiaminglu/kotlin-native
runtime/src/main/kotlin/kotlin/text/Indent.kt
1
3952
package kotlin.text /** * Trims leading whitespace characters followed by [marginPrefix] from every line of a source string and removes * the first and the last lines if they are blank (notice difference blank vs empty). * * Doesn't affect a line if it doesn't contain [marginPrefix] except the first and the last blank lines. * * Doesn't preserve the original line endings. * * @param marginPrefix non-blank string, which is used as a margin delimiter. Default is `|` (pipe character). * * @sample samples.text.Strings.trimMargin * @see trimIndent * @see kotlin.text.isWhitespace */ public fun String.trimMargin(marginPrefix: String = "|"): String = replaceIndentByMargin("", marginPrefix) /** * Detects indent by [marginPrefix] as it does [trimMargin] and replace it with [newIndent]. * * @param marginPrefix non-blank string, which is used as a margin delimiter. Default is `|` (pipe character). */ public fun String.replaceIndentByMargin(newIndent: String = "", marginPrefix: String = "|"): String { require(marginPrefix.isNotBlank()) { "marginPrefix must be non-blank string." } val lines = lines() return lines.reindent(length + newIndent.length * lines.size, getIndentFunction(newIndent), { line -> val firstNonWhitespaceIndex = line.indexOfFirst { !it.isWhitespace() } when { firstNonWhitespaceIndex == -1 -> null line.startsWith(marginPrefix, firstNonWhitespaceIndex) -> line.substring(firstNonWhitespaceIndex + marginPrefix.length) else -> null } }) } /** * Detects a common minimal indent of all the input lines, removes it from every line and also removes the first and the last * lines if they are blank (notice difference blank vs empty). * * Note that blank lines do not affect the detected indent level. * * In case if there are non-blank lines with no leading whitespace characters (no indent at all) then the * common indent is 0, and therefore this function doesn't change the indentation. * * Doesn't preserve the original line endings. * * @sample samples.text.Strings.trimIndent * @see trimMargin * @see kotlin.text.isBlank */ public fun String.trimIndent(): String = replaceIndent("") /** * Detects a common minimal indent like it does [trimIndent] and replaces it with the specified [newIndent]. */ public fun String.replaceIndent(newIndent: String = ""): String { val lines = lines() val minCommonIndent = lines .filter(String::isNotBlank) .map(String::indentWidth) .min() ?: 0 return lines.reindent(length + newIndent.length * lines.size, getIndentFunction(newIndent), { line -> line.drop(minCommonIndent) }) } /** * Prepends [indent] to every line of the original string. * * Doesn't preserve the original line endings. */ public fun String.prependIndent(indent: String = " "): String = lineSequence() .map { when { it.isBlank() -> { when { it.length < indent.length -> indent else -> it } } else -> indent + it } } .joinToString("\n") private fun String.indentWidth(): Int = indexOfFirst { !it.isWhitespace() }.let { if (it == -1) length else it } private fun getIndentFunction(indent: String) = when { indent.isEmpty() -> { line: String -> line } else -> { line: String -> indent + line } } private inline fun List<String>.reindent(resultSizeEstimate: Int, indentAddFunction: (String) -> String, indentCutFunction: (String) -> String?): String { val lastIndex = lastIndex return mapIndexedNotNull { index, value -> if ((index == 0 || index == lastIndex) && value.isBlank()) null else indentCutFunction(value)?.let(indentAddFunction) ?: value } .joinTo(StringBuilder(resultSizeEstimate), "\n") .toString() }
apache-2.0
52d7dfd2596a1656e4c9a13aaa9bf1e3
35.592593
154
0.659666
4.267819
false
false
false
false
Saketme/JRAW
lib/src/main/kotlin/net/dean/jraw/RedditClient.kt
1
20780
package net.dean.jraw import com.squareup.moshi.Types import net.dean.jraw.databind.Enveloped import net.dean.jraw.http.* import net.dean.jraw.models.* import net.dean.jraw.models.internal.RedditExceptionStub import net.dean.jraw.models.internal.SubredditSearchResultContainer import net.dean.jraw.oauth.* import net.dean.jraw.pagination.BarebonesPaginator import net.dean.jraw.pagination.DefaultPaginator import net.dean.jraw.pagination.SearchPaginator import net.dean.jraw.pagination.SubredditSearchPaginator import net.dean.jraw.ratelimit.LeakyBucketRateLimiter import net.dean.jraw.ratelimit.RateLimiter import net.dean.jraw.references.* import okhttp3.HttpUrl import okhttp3.WebSocket import okhttp3.WebSocketListener import java.util.concurrent.TimeUnit /** * Specialized class for sending requests to [oauth.reddit.com](https://www.reddit.com/dev/api/oauth). * * RedditClients cannot be instantiated directly through the public API. See the * [OAuthHelper][net.dean.jraw.oauth.OAuthHelper] class. * * This class can also be used to send HTTP requests to other domains, but it is recommended to just use an * [NetworkAdapter] to do that since all requests made using this class are rate limited using [rateLimiter]. * * By default, all network activity that originates from this class are logged with [logger]. You can provide your own * [HttpLogger] implementation or turn it off entirely by setting [logHttp] to `false`. * * Any requests sent by RedditClients are rate-limited on a per-instance basis. That means that it is possible to * consume your app's quota of 60 requests per second using more than one RedditClient authenticated under the same * OAuth2 app credentials operating independently of each other. For that reason, it is recommended to have only one * instance of the RedditClient per application. * * By default, any request that responds with a server error code (5XX) will be retried up to five times. You can change * this by changing [retryLimit]. */ class RedditClient internal constructor( /** How this client will send HTTP requests */ val http: NetworkAdapter, initialOAuthData: OAuthData, creds: Credentials, /** The TokenStore to assign to [AuthManager.tokenStore] */ tokenStore: TokenStore = NoopTokenStore(), /** A non-null value will prevent a request to /api/v1/me to figure out the authenticated username */ overrideUsername: String? = null ) { /** Every HTTP request/response will be logged with this, unless [logHttp] is false */ var logger: HttpLogger = SimpleHttpLogger() /** Whether or not to log HTTP requests */ var logHttp = true /** * How many times this client will retry requests that result in 5XX erorr codes. Defaults to 5. Set to a number * less than 1 to disable this functionality. */ var retryLimit: Int = DEFAULT_RETRY_LIMIT /** * How this client will determine when it can send a request. * * By default, this RateLimiter is a [LeakyBucketRateLimiter] with a capacity of 5 permits and refills them at a * rate of 1 token per second. */ var rateLimiter: RateLimiter = LeakyBucketRateLimiter(BURST_LIMIT, RATE_LIMIT, TimeUnit.SECONDS) /** If true, any time a request is made, the access token will be renewed if necessary. */ var autoRenew = true internal var forceRenew = false /** How this client manages (re)authentication */ var authManager = AuthManager(http, creds) /** The type of OAuth2 app used to authenticate this client */ val authMethod: AuthMethod = creds.authMethod /** * If true, this client shouldn't be used any more. Any attempts to send requests while this is true will throw an * IllegalStateException. */ internal var loggedOut: Boolean = false init { // Use overrideUsername if available, otherwise try to fetch the name from the API. We can't use // me().about().name since that would require a valid access token (we have to call authManager.update after // we have a valid username so TokenStores get the proper name once it gets updated). Instead we directly // make the request and parse the response. authManager.currentUsername = overrideUsername ?: try { val me = request(HttpRequest.Builder() .url("https://oauth.reddit.com/api/v1/me") .header("Authorization", "bearer ${initialOAuthData.accessToken}") .build()).deserialize<Map<*, *>>() // Avoid deserializing an Account because it's harder to mock an response to Account while testing me["name"] as? String ?: throw IllegalArgumentException("Expected a name") } catch (e: ApiException) { // Delay throwing an exception until `requireAuthenticatedUser()` is called null } authManager.tokenStore = tokenStore authManager.update(initialOAuthData) } /** * Creates a [HttpRequest.Builder], setting `secure(true)`, `host("oauth.reddit.com")`, and the Authorization header */ fun requestStub(): HttpRequest.Builder { return HttpRequest.Builder() .secure(true) .host("oauth.reddit.com") .header("Authorization", "bearer ${authManager.accessToken}") } @Throws(NetworkException::class) private fun request(r: HttpRequest, retryCount: Int = 0): HttpResponse { if (loggedOut) throw IllegalStateException("This client is logged out and should not be used anymore") var req = r if (forceRenew || (autoRenew && authManager.needsRenewing() && authManager.canRenew())) { authManager.renew() // forceRenew is a one-time thing, usually used when given an OAuthData that only contains valid refresh // token and a made-up access token, expiration, etc. forceRenew = false // The request was intended to be sent with the previous access token. Since we've renewed it, we have to // modify that header. req = req.newBuilder().header("Authorization", "bearer ${authManager.accessToken}").build() } // Add the raw_json=1 query parameter if requested if (req.rawJson) { val url = HttpUrl.parse(req.url)!! // Make sure we specify a value for raw_json exactly once var newUrl = url.newBuilder() if (url.queryParameterValues("raw_json") != listOf("1")) { // Make sure to remove all previously specified values of raw_json if more than one existed or given a // different value. newUrl = newUrl.removeAllQueryParameters("raw_json") .addQueryParameter("raw_json", "1") } req = req.newBuilder().url(newUrl.build()).build() } // Only ratelimit on the first try if (retryCount == 0) rateLimiter.acquire() val res = if (logHttp) { // Log the request and response, returning 'res' val tag = logger.request(req) val res = http.execute(req) logger.response(tag, res) res } else { http.execute(req) } if (res.code in 500..599 && retryCount < retryLimit) { return request(req, retryCount + 1) } val type = res.raw.body()?.contentType() // Try to find any API errors embedded in the JSON document if (type != null && type.type() == "application" && type.subtype() == "json") { // Make the adapter lenient so we're not required to read the entire body val adapter = JrawUtils.adapter<RedditExceptionStub<*>>().lenient() val stub = if (res.body == "") null else adapter.fromJson(res.body) // Reddit has some legacy endpoints that return 200 OK even though the JSON contains errors if (stub != null) { val ex = stub.create(NetworkException(res)) if (ex != null) throw ex } } // Make sure we're still failing on non-success status codes if we couldn't find an API error in the JSON if (!res.successful) throw NetworkException(res) return res } /** * Attempts to open a WebSocket connection at the given URL. */ fun websocket(url: String, listener: WebSocketListener): WebSocket { return http.connect(url, listener) } /** * Uses the [NetworkAdapter] to execute a synchronous HTTP request * * ``` * val response = reddit.request(reddit.requestStub() * .path("/api/v1/me") * .build()) * ``` * * @throws NetworkException If the response's code is out of the range of 200..299. * @throws RedditException if an API error if the response comes back unsuccessful and a typical error structure is * detected in the response. */ @Throws(NetworkException::class, RedditException::class) fun request(r: HttpRequest): HttpResponse = request(r, retryCount = 0) /** * Adds a little syntactic sugar to the vanilla `request` method. * * The [configure] function will be passed the return value of [requestStub], and that [HttpRequest.Builder] will be * built and send to `request()`. While this may seem a little complex, it's probably easier to understand through * an example: * * ``` * val json = reddit.request { * it.path("/api/v1/foo") * .header("X-Foo", "Bar") * .post(mapOf( * "baz" to "qux" * )) * } * ``` * * This will execute `POST https://oauth.reddit.com/api/v1/foo` with the headers 'X-Foo: Bar' and * 'Authorization: bearer $accessToken' and a form body of `baz=qux`. * * For reference, this same request can be executed like this: * * ``` * val json = reddit.request(reddit.requestStub() * .path("/api/v1/me") * .header("X-Foo", "Bar") * .post(mapOf( * "baz" to "qux" * )).build()) * ``` * * @see requestStub */ @Throws(NetworkException::class, RedditException::class) fun request(configure: (stub: HttpRequest.Builder) -> HttpRequest.Builder) = request(configure(requestStub()).build()) /** * Creates a UserReference for the currently logged in user. * * @throws IllegalStateException If there is no authenticated user */ @Throws(IllegalStateException::class) fun me() = SelfUserReference(this) /** * Creates a UserReference for any user * * @see me */ fun user(name: String) = OtherUserReference(this, name) /** * Returns a Paginator builder that will iterate user subreddits. See [here](https://www.reddit.com/comments/6bqemt) * for more info. * * Possible `where` values: * * - `new` * - `popular` */ @EndpointImplementation(Endpoint.GET_USERS_WHERE, type = MethodType.NON_BLOCKING_CALL) fun userSubreddits(where: String) = BarebonesPaginator.Builder.create<Subreddit>(this, "/users/${JrawUtils.urlEncode(where)}") /** Creates a [DefaultPaginator.Builder] to iterate posts on the front page */ fun frontPage() = DefaultPaginator.Builder.create<Submission, SubredditSort>(this, baseUrl = "", sortingAlsoInPath = true) /** Creates a SearchPaginator.Builder to search for submissions in every subreddit */ fun search(): SearchPaginator.Builder = SearchPaginator.everywhere(this) /** * Allows searching reddit for various communities. Recommended sorting here is "relevance," which is also the * default. * * Note that this is different from [search], which searches for submissions compared to this method, which searches * for subreddits. This is also different from [searchSubredditsByName] since this returns a Paginator and the other * returns a simple list. */ @EndpointImplementation(Endpoint.GET_SUBREDDITS_SEARCH) fun searchSubreddits(): SubredditSearchPaginator.Builder = SubredditSearchPaginator.Builder(this) /** * Convenience function equivalent to * * ```java * searchSubredditsByName(new SubredditSearchQuery(queryString)) * ``` */ fun searchSubredditsByName(query: String) = searchSubredditsByName(SubredditSearchQuery(query)) /** * Searches for subreddits by name alone. A more general search for subreddits can be done using [searchSubreddits]. */ @EndpointImplementation(Endpoint.POST_SEARCH_SUBREDDITS) fun searchSubredditsByName(query: SubredditSearchQuery): List<SubredditSearchResult> { val container = request { it.endpoint(Endpoint.POST_SEARCH_SUBREDDITS) .post(mapOf( "query" to query.query, "exact" to query.exact?.toString(), "include_over_18" to query.includeNsfw?.toString(), "include_unadvertisable" to query.includeUnadvertisable?.toString() ).filterValuesNotNull()) }.deserialize<SubredditSearchResultContainer>() return container.subreddits } /** * Creates a [SubredditReference] * * Reddit has some special subreddits: * * - /r/all - posts from every subreddit * - /r/popular - includes posts from subreddits that have opted out of /r/all. Guaranteed to not have NSFW content. * - /r/mod - submissions from subreddits the logged-in user moderates * - /r/friends - submissions from the user's friends * * Trying to use [SubredditReference.about], [SubredditReference.submit], or the like for these subreddits will * likely result in an API-side error. */ fun subreddit(name: String) = SubredditReference(this, name) /** * Creates a [SubredditReference] to a "compound subreddit." This reference will be limited in some ways (for * example, you can't submit a post to a compound subreddit). * * This works by using a useful little-known trick. You can view multiple subreddits at one time by joining them * together with a `+`, like "/r/redditdev+programming+kotlin" * * Here's how to fetch 50 posts from /r/pics and /r/funny as a quick example: * * ```kotlin * val paginator = redditClient.subreddits("pics", "funny").posts().limit(50).build() * val posts = paginator.next() * ``` */ fun subreddits(first: String, second: String, vararg others: String) = SubredditReference(this, arrayOf(first, second, *others).joinToString("+")) /** * Tests if the client has the ability to access the given API endpoint. This method always returns true for script * apps. */ fun canAccess(e: Endpoint): Boolean { val scopes = authManager.current?.scopes ?: return false // A '*' means all scopes, only used for scripts if (scopes.contains("*")) return true return scopes.contains(e.scope) } /** * Creates a SubredditReference for a random subreddit. Although this method is decorated with * [EndpointImplementation], it does not execute an HTTP request and is not a blocking call. This method is * equivalent to * * ```kotlin * reddit.subreddit("random") * ``` * * @see SubredditReference.randomSubmission */ @EndpointImplementation(Endpoint.GET_RANDOM, type = MethodType.NON_BLOCKING_CALL) fun randomSubreddit() = subreddit("random") /** * Creates either [SubmissionReference] or [CommentReference] depending on provided fullname. * Fullname format is defined as ${kind}_${id} (e.g. t3_6afe8u or t1_2bad4u). * * @see KindConstants * @throws IllegalArgumentException if the provided fullname doesn't match that format or the prefix is not * one of [KindConstants.COMMENT] or [KindConstants.SUBREDDIT] */ fun publicContribution(fullname: String): PublicContributionReference { val parts = fullname.split('_') if (parts.size != 2) throw IllegalArgumentException("Fullname doesn't match the pattern KIND_ID") return when (parts[0]) { KindConstants.COMMENT -> comment(parts[1]) KindConstants.SUBMISSION -> submission(parts[1]) else -> throw IllegalArgumentException("Provided kind '${parts[0]}' is not a public contribution") } } /** * Creates a SubmissionReference. Note that `id` is NOT a full name (like `t3_6afe8u`), but rather an ID * (like `6afe8u`) */ fun submission(id: String) = SubmissionReference(this, id) /** * Creates a CommentReference. Note that `id` is NOT a full name (like `t1_6afe8u`), but rather an ID * (like `6afe8u`) */ fun comment(id: String) = CommentReference(this, id) /** * Creates a BarebonesPaginator.Builder that will iterate over the latest comments from the given subreddits when * built. If no subreddits are given, comments will be from any subreddit. */ fun latestComments(vararg subreddits: String): BarebonesPaginator.Builder<Comment> { val prefix = if (subreddits.isEmpty()) "" else "/r/" + subreddits.joinToString("+") return BarebonesPaginator.Builder.create(this, "$prefix/comments") } /** * Creates a [BarebonesPaginator.Builder] that will iterate over gilded public contributions (i.e. posts and * comments) in the given subreddits when built. * * If no subreddits are given, contributions will be from logged-in user's frontpage subreddits. * * @see PublicContribution */ fun gildedContributions(vararg subreddits: String): BarebonesPaginator.Builder<PublicContribution<*>> { val prefix = if (subreddits.isEmpty()) "" else "/r/" + subreddits.joinToString("+") return BarebonesPaginator.Builder.create(this, "$prefix/gilded") } /** * Returns the name of the logged-in user * * @throws IllegalStateException If there is no logged-in user */ fun requireAuthenticatedUser(): String { if (authMethod.isUserless) throw IllegalStateException("Expected the RedditClient to have an active user, was authenticated with " + authMethod) return authManager.currentUsername ?: throw IllegalStateException("Expected an authenticated user") } /** * varargs version of `lookup` provided for convenience. */ fun lookup(vararg fullNames: String) = lookup(listOf(*fullNames)) /** * Attempts to find information for the given full names. Only the full names of submissions, comments, and * subreddits are accepted. */ @EndpointImplementation(Endpoint.GET_INFO) fun lookup(fullNames: List<String>): Listing<Any> { if (fullNames.isEmpty()) return Listing.empty() val type = Types.newParameterizedType(Listing::class.java, Any::class.java) val adapter = JrawUtils.moshi.adapter<Listing<Any>>(type, Enveloped::class.java) return request { it.endpoint(Endpoint.GET_INFO, null) .query(mapOf("id" to fullNames.joinToString(","))) }.deserializeWith(adapter) } /** * Creates a reference to a live thread with the given ID. * * To create a live thread, use [SelfUserReference.createLiveThread]: * * ```kt * val ref: LiveThreadReference = redditClient.me().createLiveThread(LiveThread.Builder() * ... * .build()) * ``` */ fun liveThread(id: String) = LiveThreadReference(this, id) /** * Returns the live thread currently being featured by reddit, or null if there is none. On the website, this * appears above all posts on the front page. */ @EndpointImplementation(Endpoint.GET_LIVE_HAPPENING_NOW) fun happeningNow(): LiveThread? { val res = request { it.endpoint(Endpoint.GET_LIVE_HAPPENING_NOW) } // A 204 response means there's nothing happening right now if (res.code == 204) return null return res.deserialize() } /** @inheritDoc */ override fun toString(): String { return "RedditClient(username=${authManager.currentUsername()})" } /** Defines some static properties */ companion object { /** Amount of requests per second reddit allows for OAuth2 apps (equal to 1) */ const val RATE_LIMIT = 1L private const val BURST_LIMIT = 5L private const val DEFAULT_RETRY_LIMIT = 5 } }
mit
0bc8ccb07d2eb83b1241ecb8eed392c7
39.585938
130
0.649952
4.502709
false
false
false
false
prt2121/android-workspace
Section/app/src/main/kotlin/com/prt2121/capstone/ListActivity.kt
1
1856
package com.prt2121.capstone import android.os.Bundle import android.support.v7.app.AppCompatActivity import android.support.v7.widget.LinearLayoutManager import android.support.v7.widget.RecyclerView import android.view.View import com.invite.Invite import com.invite.InviteApi import com.prt2121.sectionlist.SectionRecyclerViewAdapter import com.prt2121.sectionlist.SectionRecyclerViewAdapter.Section import rx.android.schedulers.AndroidSchedulers import rx.schedulers.Schedulers /** * Created by pt2121 on 2/6/16. */ class ListActivity : AppCompatActivity(), InviteAdapter.ClickListener { override fun onItemViewClick(view: View, invite: Invite) { println("invite._id clicked ${invite.id}") } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_list) val listView = findViewById(R.id.recycler_view) as RecyclerView listView.layoutManager = LinearLayoutManager(this) val baseAdapter = InviteAdapter(this, arrayListOf(), this) val sections = emptyArray<SectionRecyclerViewAdapter.Section>() val sectionAdapter = SectionRecyclerViewAdapter(this, R.layout.section, R.id.section_text, baseAdapter) sectionAdapter.update(sections) listView.adapter = sectionAdapter InviteApi.instance.getInvitesFrom("6466445321") .map { it.sortedByDescending { it.createAt } } .subscribeOn(Schedulers.newThread()) .observeOn(AndroidSchedulers.mainThread()) .subscribe( { baseAdapter.update(it) val active = it.filter { it.isActive() }.size sectionAdapter.update( arrayOf(Section(0, "Active"), Section(active, "Archive")) ) }, { println("${it.message}") }, { println("completed") } ) } }
apache-2.0
667c9eaedf7b53961ddd880ffba08a60
35.411765
107
0.710668
4.483092
false
false
false
false
zachdeibert/operation-manipulation
operation-missing-android/app/src/main/java/com/zachdeibert/operationmissing/math/Vector.kt
1
1907
package com.zachdeibert.operationmissing.math import java.lang.IllegalArgumentException import kotlin.math.sqrt class Vector(data: FloatArray) { var data: FloatArray = data val size: Int get() = data.size fun magnitude(): Float { var mag2 = 0f for (v in data) { mag2 += v * v } return sqrt(mag2) } fun normalize(): Vector { return this / magnitude() } fun dot(other: Vector): Float { if (size != other.size) { throw IllegalArgumentException("Vectors must have the same dimensionality") } var res = 0f for (i in 0..size-1) { res += data[i] * other.data[i] } return res } fun projectOnto(dir: Vector): Vector { val d = dir.normalize() return d * dot(d) } operator fun plus(other: Vector): Vector { if (size != other.size) { throw IllegalArgumentException("Vectors must have the same dimensionality") } val new = FloatArray(size) for (i in 0..size-1) { new[i] = data[i] + other.data[i] } return Vector(new) } operator fun minus(other: Vector): Vector { if (size != other.size) { throw IllegalArgumentException("Vectors must have the same dimensionality") } val new = FloatArray(size) for (i in 0..size-1) { new[i] = data[i] - other.data[i] } return Vector(new) } operator fun times(scalar: Float): Vector { val new = FloatArray(size) for (i in 0..size-1) { new[i] = data[i] * scalar } return Vector(new) } operator fun div(scalar: Float): Vector { val new = FloatArray(size) for (i in 0..size-1) { new[i] = data[i] / scalar } return Vector(new) } }
mit
5dca509b6d0e3e1db9382127f1383e80
24.105263
87
0.529103
3.940083
false
false
false
false
Maccimo/intellij-community
plugins/kotlin/groovy/src/org/jetbrains/kotlin/idea/groovy/inspections/DifferentKotlinGradleVersionInspection.kt
3
4093
// 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.groovy.inspections import org.jetbrains.annotations.TestOnly import org.jetbrains.kotlin.config.LanguageVersion import org.jetbrains.kotlin.idea.compiler.configuration.IdeKotlinVersion import org.jetbrains.kotlin.idea.compiler.configuration.KotlinPluginLayout import org.jetbrains.kotlin.idea.groovy.KotlinGroovyBundle import org.jetbrains.kotlin.idea.inspections.PluginVersionDependentInspection import org.jetbrains.kotlin.psi.psiUtil.getStrictParentOfType import org.jetbrains.plugins.groovy.codeInspection.BaseInspection import org.jetbrains.plugins.groovy.codeInspection.BaseInspectionVisitor import org.jetbrains.plugins.groovy.lang.psi.GroovyFileBase import org.jetbrains.plugins.groovy.lang.psi.GroovyPsiElement import org.jetbrains.plugins.groovy.lang.psi.api.statements.blocks.GrClosableBlock import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrMethodCall import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.path.GrCallExpression class DifferentKotlinGradleVersionInspection : BaseInspection(), PluginVersionDependentInspection { override var testVersionMessage: String? = null @TestOnly set override fun buildVisitor(): BaseInspectionVisitor = MyVisitor() override fun getGroupDisplayName() = getProbableBugs() override fun buildErrorString(vararg args: Any): String = KotlinGroovyBundle.message("error.text.different.kotlin.gradle.version", args[0], args[1]) private abstract class VersionFinder : KotlinGradleInspectionVisitor() { protected abstract fun onFound(kotlinPluginVersion: IdeKotlinVersion, kotlinPluginStatement: GrCallExpression) override fun visitClosure(closure: GrClosableBlock) { super.visitClosure(closure) val dependenciesCall = closure.getStrictParentOfType<GrMethodCall>() ?: return if (dependenciesCall.invokedExpression.text != "dependencies") return val buildScriptCall = dependenciesCall.getStrictParentOfType<GrMethodCall>() ?: return if (buildScriptCall.invokedExpression.text != "buildscript") return val kotlinPluginStatement = GradleHeuristicHelper.findStatementWithPrefix(closure, "classpath").firstOrNull { it.text.contains(KOTLIN_PLUGIN_CLASSPATH_MARKER) } ?: return val kotlinPluginVersion = GradleHeuristicHelper.getHeuristicVersionInBuildScriptDependency(kotlinPluginStatement) ?: findResolvedKotlinGradleVersion(closure.containingFile) ?: return onFound(kotlinPluginVersion, kotlinPluginStatement) } } private inner class MyVisitor : VersionFinder() { override fun onFound(kotlinPluginVersion: IdeKotlinVersion, kotlinPluginStatement: GrCallExpression) { val latestSupportedLanguageVersion = KotlinPluginLayout.ideCompilerVersion.languageVersion val projectLanguageVersion = kotlinPluginVersion.languageVersion if (latestSupportedLanguageVersion < projectLanguageVersion || projectLanguageVersion < LanguageVersion.FIRST_SUPPORTED) { registerError(kotlinPluginStatement, kotlinPluginVersion, testVersionMessage ?: latestSupportedLanguageVersion) } } } companion object { fun getKotlinPluginVersion(gradleFile: GroovyFileBase): IdeKotlinVersion? { var version: IdeKotlinVersion? = null val visitor = object : VersionFinder() { override fun visitElement(element: GroovyPsiElement) { element.acceptChildren(this) } override fun onFound(kotlinPluginVersion: IdeKotlinVersion, kotlinPluginStatement: GrCallExpression) { version = kotlinPluginVersion } } gradleFile.accept(visitor) return version } } }
apache-2.0
340f05b5d034edc342d147b788622b91
48.926829
158
0.744686
5.568707
false
true
false
false
bajdcc/jMiniLang
src/main/kotlin/com/bajdcc/LALR1/grammar/Grammar.kt
1
19128
package com.bajdcc.LALR1.grammar import com.bajdcc.LALR1.grammar.codegen.Codegen import com.bajdcc.LALR1.grammar.error.LostHandler import com.bajdcc.LALR1.grammar.runtime.RuntimeCodePage import com.bajdcc.LALR1.grammar.semantic.ISemanticRecorder import com.bajdcc.LALR1.grammar.semantic.SemanticHandler import com.bajdcc.LALR1.grammar.semantic.SemanticRecorder import com.bajdcc.LALR1.grammar.symbol.IManageSymbol import com.bajdcc.LALR1.grammar.symbol.IQuerySymbol import com.bajdcc.LALR1.grammar.symbol.SymbolTable import com.bajdcc.LALR1.semantic.Semantic import com.bajdcc.LALR1.syntax.Syntax import com.bajdcc.LALR1.syntax.handler.SyntaxException import com.bajdcc.LALR1.syntax.handler.SyntaxException.SyntaxError import com.bajdcc.util.lexer.error.RegexException import com.bajdcc.util.lexer.token.KeywordType import com.bajdcc.util.lexer.token.OperatorType import com.bajdcc.util.lexer.token.TokenType /** * **语法分析器** * * * 基于文法与语义动作 * * * @author bajdcc */ class Grammar @Throws(RegexException::class, SyntaxException::class) constructor(context: String) : Semantic(context) { /** * 语义处理 */ private val handler = SemanticHandler() /** * 符号表 */ private val symbol = SymbolTable() /** * 代码生成 */ private var code: Codegen? = null /** * 语义错误表 */ private val recorder = SemanticRecorder() override val querySymbolService: IQuerySymbol? get() = symbol override val manageSymbolService: IManageSymbol? get() = symbol override val semanticRecorderService: ISemanticRecorder? get() = recorder /** * 获得语义错误描述 * * @return 语义错误描述 */ private val semanticError: String get() = recorder.toString(tokenFactory) /** * 获得中间代码描述 * * @return 中间代码描述 */ override val inst: String get() = code!!.toString() /** * 生成目标代码 * * @return 目标代码页 * @throws SyntaxException 词法错误 */ val codePage: RuntimeCodePage @Throws(SyntaxException::class) get() { if (!recorder.correct) { System.err.println(semanticError) throw SyntaxException(SyntaxError.COMPILE_ERROR, recorder.error[0].position.position, semanticError) } return code!!.genCodePage() } init { initialize() } /** * 初始化 * * @throws SyntaxException 词法错误 */ @Throws(SyntaxException::class) private fun initialize() { if (Syntax.npa == null) { // 为避免多次构造NPA,这里采用单例模式 declareTerminal() declareNonTerminal() declareErrorHandler() declareActionHandler() infer() npaDesc = npaMarkdownString } parse() check() gencode() } /** * 声明终结符 * * @throws SyntaxException 词法错误 */ @Throws(SyntaxException::class) private fun declareTerminal() { addTerminal("ID", TokenType.ID, null) addTerminal("BOOLEAN", TokenType.BOOL, null) addTerminal("LITERAL", TokenType.STRING, null) addTerminal("CHARACTER", TokenType.CHARACTER, null) addTerminal("INTEGER", TokenType.INTEGER, null) addTerminal("DECIMAL", TokenType.DECIMAL, null) for (keywordType in KeywordType.values()) { addTerminal(keywordType.name, TokenType.KEYWORD, keywordType) } addTerminal("ELLIPSIS", TokenType.OPERATOR, OperatorType.ELLIPSIS) addTerminal("PTR_OP", TokenType.OPERATOR, OperatorType.POINTER) addTerminal("INC_OP", TokenType.OPERATOR, OperatorType.PLUS_PLUS) addTerminal("DEC_OP", TokenType.OPERATOR, OperatorType.MINUS_MINUS) addTerminal("LEFT_OP", TokenType.OPERATOR, OperatorType.LEFT_SHIFT) addTerminal("RIGHT_OP", TokenType.OPERATOR, OperatorType.RIGHT_SHIFT) addTerminal("LE_OP", TokenType.OPERATOR, OperatorType.LESS_THAN_OR_EQUAL) addTerminal("GE_OP", TokenType.OPERATOR, OperatorType.GREATER_THAN_OR_EQUAL) addTerminal("EQ_OP", TokenType.OPERATOR, OperatorType.EQUAL) addTerminal("NE_OP", TokenType.OPERATOR, OperatorType.NOT_EQUAL) addTerminal("AND_OP", TokenType.OPERATOR, OperatorType.LOGICAL_AND) addTerminal("OR_OP", TokenType.OPERATOR, OperatorType.LOGICAL_OR) addTerminal("MUL_ASSIGN", TokenType.OPERATOR, OperatorType.TIMES_ASSIGN) addTerminal("DIV_ASSIGN", TokenType.OPERATOR, OperatorType.DIV_ASSIGN) addTerminal("MOD_ASSIGN", TokenType.OPERATOR, OperatorType.MOD_ASSIGN) addTerminal("ADD_ASSIGN", TokenType.OPERATOR, OperatorType.PLUS_ASSIGN) addTerminal("SUB_ASSIGN", TokenType.OPERATOR, OperatorType.MINUS_ASSIGN) addTerminal("LEFT_ASSIGN", TokenType.OPERATOR, OperatorType.LEFT_SHIFT_ASSIGN) addTerminal("RIGHT_ASSIGN", TokenType.OPERATOR, OperatorType.RIGHT_SHIFT_ASSIGN) addTerminal("AND_ASSIGN", TokenType.OPERATOR, OperatorType.AND_ASSIGN) addTerminal("XOR_ASSIGN", TokenType.OPERATOR, OperatorType.XOR_ASSIGN) addTerminal("OR_ASSIGN", TokenType.OPERATOR, OperatorType.OR_ASSIGN) addTerminal("EQ_ASSIGN", TokenType.OPERATOR, OperatorType.EQ_ASSIGN) addTerminal("ADD", TokenType.OPERATOR, OperatorType.PLUS) addTerminal("SUB", TokenType.OPERATOR, OperatorType.MINUS) addTerminal("MUL", TokenType.OPERATOR, OperatorType.TIMES) addTerminal("DIV", TokenType.OPERATOR, OperatorType.DIVIDE) addTerminal("MOD", TokenType.OPERATOR, OperatorType.MOD) addTerminal("AND", TokenType.OPERATOR, OperatorType.BIT_AND) addTerminal("OR", TokenType.OPERATOR, OperatorType.BIT_OR) addTerminal("XOR", TokenType.OPERATOR, OperatorType.BIT_XOR) addTerminal("NOT", TokenType.OPERATOR, OperatorType.BIT_NOT) addTerminal("NOT_OP", TokenType.OPERATOR, OperatorType.LOGICAL_NOT) addTerminal("LT", TokenType.OPERATOR, OperatorType.LESS_THAN) addTerminal("GT", TokenType.OPERATOR, OperatorType.GREATER_THAN) addTerminal("QUERY", TokenType.OPERATOR, OperatorType.QUERY) addTerminal("COMMA", TokenType.OPERATOR, OperatorType.COMMA) addTerminal("SEMI", TokenType.OPERATOR, OperatorType.SEMI) addTerminal("DOT", TokenType.OPERATOR, OperatorType.DOT) addTerminal("ASSIGN", TokenType.OPERATOR, OperatorType.ASSIGN) addTerminal("COLON", TokenType.OPERATOR, OperatorType.COLON) addTerminal("LPA", TokenType.OPERATOR, OperatorType.LPARAN) addTerminal("RPA", TokenType.OPERATOR, OperatorType.RPARAN) addTerminal("LSQ", TokenType.OPERATOR, OperatorType.LSQUARE) addTerminal("RSQ", TokenType.OPERATOR, OperatorType.RSQUARE) addTerminal("LBR", TokenType.OPERATOR, OperatorType.LBRACE) addTerminal("RBR", TokenType.OPERATOR, OperatorType.RBRACE) addTerminal("PROPERTY", TokenType.OPERATOR, OperatorType.PROPERTY) } /** * 声明非终结符 * * @throws SyntaxException 词法错误 */ @Throws(SyntaxException::class) private fun declareNonTerminal() { val nonTerminals = arrayOf("program", "stmt_list", "stmt", "stmt_stmt", "stmt_ctrl", "stmt_exp", "func", "lambda", "var", "var_list", "exp_list", "exp", "exp0", "exp1", "exp2", "exp3", "exp4", "exp5", "exp6", "exp7", "exp8", "exp9", "exp10", "type", "block", "call_exp", "call", "ret", "doc_list", "port", "if", "for", "while", "foreach", "cycle_ctrl", "block_stmt", "array", "map", "set", "invoke", "exp01", "try", "throw", "map_list", "scope") for (string in nonTerminals) { addNonTerminal(string) } } /** * 进行推导 * * @throws SyntaxException 词法错误 */ @Throws(SyntaxException::class) private fun infer() { /* 起始符号就是main函数 */ infer(handler.getSemanticHandler("main"), "program -> stmt_list[0]{lost_stmt}") /* Block语句 */ infer(handler.getSemanticHandler("block"), "block -> @LBR#do_enter_scope# [stmt_list[0]] @RBR#do_leave_scope#{lost_rbr}") infer(handler.getSemanticHandler("block_stmt"), "block_stmt -> block[0]") /* 当前块(Block)全部由语句组成 */ infer(handler.getSemanticHandler("stmt_list"), "stmt_list -> stmt[0]{lost_stmt} [stmt_list[1]]") /* 语句分为变量定义(赋值)、调用语句 */ infer(handler.getSemanticHandler("copy"), "stmt_exp -> var[0] | call[0] | cycle_ctrl[0] | exp[0]") infer(handler.getSemanticHandler("copy"), "stmt -> stmt_stmt[0] | stmt_ctrl[0] | block_stmt[0]") infer(handler.getSemanticHandler("stmt_exp"), "stmt_stmt -> [stmt_exp[0]] @SEMI#clear_catch#{lost_semi}") infer(handler.getSemanticHandler("copy"), "stmt_ctrl -> ret[0] | port[0] | if[0] | for[0] | foreach[0] | while[0] | try[0] | throw[0]") /* 返回语句 */ infer(handler.getSemanticHandler("return"), "ret -> (@YIELD[1] | @RETURN) [exp[0]] @SEMI{lost_semi}") /* 变量定义(赋值)语句(由于支持Lambda,函数定义皆为Lambda形式) */ infer(handler.getSemanticHandler("var"), "var -> (@VARIABLE[11] | @LET[12]) @ID[0]#declear_variable#{lost_token} [@ASSIGN{lost_assign} (func[1]{lost_func} | exp[2]{lost_exp})]") /* 类属性赋值语句 */ infer(handler.getSemanticHandler("set"), "set -> @SET exp[3]{lost_exp} @PROPERTY{lost_property} exp[4]{lost_exp} @ASSIGN{lost_assign} exp[2]{lost_exp}") /* 类方法调用语句 */ infer(handler.getSemanticHandler("invoke"), "invoke -> @INVOKE[0] exp[1]{lost_exp} @PROPERTY{lost_property} exp[2]{lost_exp} @PROPERTY{lost_property} @LPA{lost_lpa} [exp_list[3]] @RPA{lost_rpa}") /* 导入与导出语句 */ infer(handler.getSemanticHandler("port"), "port -> (@IMPORT[1] | @EXPORT[2]) @LITERAL[0]{lost_string} @SEMI{lost_semi}") /* 表达式(算符文法) */ val exp_handler = handler.getSemanticHandler("exp") infer(handler.getSemanticHandler("scope"), "scope -> exp[0]") infer(exp_handler, "exp -> exp01[0] [@INTEGER[10] | @DECIMAL[10]]") infer(exp_handler, "exp01 -> [exp01[1] (@EQ_ASSIGN[2] | @ADD_ASSIGN[2] | @SUB_ASSIGN[2] | @MUL_ASSIGN[2] | @DIV_ASSIGN[2] | @AND_ASSIGN[2] | @OR_ASSIGN[2] | @XOR_ASSIGN[2] | @MOD_ASSIGN[2])] exp0[0]") infer(exp_handler, "exp0 -> exp1[0] [@QUERY[4] exp0[6] @COLON[5]{lost_colon} exp0[7]]") infer(exp_handler, "exp1 -> [exp1[1] (@AND_OP[2] | @OR_OP[2])] exp2[0]") infer(exp_handler, "exp2 -> [exp2[1] (@OR[2] | @XOR[2] | @AND[2])] exp3[0]") infer(exp_handler, "exp3 -> [exp3[1] (@EQ_OP[2] | @NE_OP[2])] exp4[0]") infer(exp_handler, "exp4 -> [exp4[1] (@LT[2] | @GT[2] | @LE_OP[2] | @GE_OP[2])] exp5[0]") infer(exp_handler, "exp5 -> [exp5[1] (@LEFT_OP[2] | @RIGHT_OP[2])] exp6[0]") infer(exp_handler, "exp6 -> [exp6[1] (@ADD[2] | @SUB[2])] exp7[0]") infer(exp_handler, "exp7 -> [exp7[1] (@MUL[2] | @DIV[2] | @MOD[2])] exp8[0]") infer(exp_handler, "exp8 -> (@NOT_OP[3] | @NOT[3]) exp8[1] | exp9[0]") infer(exp_handler, "exp9 -> (@INC_OP[3] | @DEC_OP[3]) exp9[1] | exp9[1] (@INC_OP[3] | @DEC_OP[3] | @LSQ exp[5]{lost_exp} @RSQ{lost_rpa}) | exp10[0]") infer(exp_handler, "exp10 -> [exp10[1] @DOT[2]] type[0]") /* 调用语句 */ infer(handler.getSemanticHandler("call_exp"), "call -> @CALL[4] (@LPA{lost_lpa} (func[0]{lost_call} | exp[3]{lost_exp}) @RPA{lost_rpa} | @ID[1]{lost_call}) @LPA{lost_lpa} [exp_list[2]] @RPA{lost_rpa}") /* 函数定义 */ infer(handler.getSemanticHandler("token_list"), "var_list -> @ID[0]#declear_param#{lost_token} [@COMMA var_list[1]{lost_token}]") infer(handler.getSemanticHandler("exp_list"), "exp_list -> exp[0] [@COMMA exp_list[1]{lost_exp}]") infer(handler.getSemanticHandler("token_list"), "doc_list -> @LITERAL[0] [@COMMA doc_list[1]]") /* 函数主体 */ infer(handler.getSemanticHandler("func"), "func -> (@FUNCTION[10]#func_clearargs# | @YIELD#func_clearargs#) [@LSQ doc_list[0]{lost_doc} @RSQ] (@ID[1]#predeclear_funcname#{lost_func_name} | @NOT[1]#predeclear_funcname#{lost_func_name}) @LPA{lost_lpa} [var_list[2]] @RPA{lost_rpa} (@PTR_OP#do_enter_scope#{lost_func_body} scope[3]#do_leave_scope#{lost_exp} | block[4]{lost_func_body})") /* 匿名主体 */ infer(handler.getSemanticHandler("lambda"), "lambda -> @LAMBDA[1]#lambda# @LPA{lost_lpa} [var_list[2]] @RPA{lost_rpa} (@PTR_OP#do_enter_scope#{lost_func_body} scope[3]#do_leave_scope#{lost_exp} | block[4]{lost_func_body})") /* 基本数据类型 */ infer(handler.getSemanticHandler("type"), "type -> @ID[0] [@LPA[3] [exp_list[4]] @RPA{lost_rpa}] | @INTEGER[0] | @DECIMAL[0] | @LITERAL[0] [@LPA[3] [exp_list[4]] @RPA{lost_rpa}] | @CHARACTER[0] | @BOOLEAN[0] | @LPA exp[1]{lost_exp} @RPA{lost_rpa} | call[1] | lambda[2] | set[1] | invoke[1] | array[1] | map[1]") /* 条件语句 */ infer(handler.getSemanticHandler("if"), "if -> @IF @LPA{lost_lpa} exp[0]{lost_exp} @RPA{lost_rpa} block[1]{lost_block} [@ELSE (block[2]{lost_block} | if[3]{lost_block})]") /* 循环语句 */ infer(handler.getSemanticHandler("for"), "for -> @FOR#do_enter_cycle# @LPA{lost_lpa} [var[0]] @SEMI{lost_semi} [exp[1]] @SEMI{lost_semi} [exp[2] | var[2]] @RPA{lost_rpa} block[3]{lost_block}") infer(handler.getSemanticHandler("while"), "while -> @WHILE#do_enter_cycle# @LPA{lost_lpa} exp[0] @RPA{lost_rpa} block[1]{lost_block}") /* 循环语句 */ infer(handler.getSemanticHandler("foreach"), "foreach -> @FOREACH#do_enter_cycle# @LPA{lost_lpa} @VARIABLE{lost_var} @ID[0]#declear_variable#{lost_token} @COLON{lost_colon} exp[1]{lost_exp} @RPA{lost_rpa} block[2]{lost_block}") /* 循环控制语句 */ infer(handler.getSemanticHandler("cycle"), "cycle_ctrl -> @BREAK[0] | @CONTINUE[0]") /* 数组初始化 */ infer(handler.getSemanticHandler("array"), "array -> @LSQ [exp_list[0]] @RSQ{lost_rsq}") /* 字典初始化 */ infer(handler.getSemanticHandler("map_list"), "map_list -> @LITERAL[1] @COLON[3]{lost_colon} exp[2]{lost_exp} [@COMMA#clear_catch# map_list[0]]") infer(handler.getSemanticHandler("map"), "map -> @LBR [map_list[0]] @RBR{lost_rbr}") /* 异常处理 */ infer(handler.getSemanticHandler("try"), "try -> @TRY block[1]{lost_block} @CATCH{lost_catch} [@LPA{lost_lpa} @ID[0]#declear_param#{lost_token} @RPA{lost_rpa}] block[2]{lost_block}") infer(handler.getSemanticHandler("throw"), "throw -> @THROW exp[0]{lost_exp} @SEMI{lost_semi}") initialize("program") } /** * 声明错误处理器 * * @throws SyntaxException 词法错误 */ @Throws(SyntaxException::class) private fun declareErrorHandler() { addErrorHandler("lost_exp", LostHandler("表达式")) addErrorHandler("lost_func", LostHandler("函数")) addErrorHandler("lost_token", LostHandler("标识符")) addErrorHandler("lost_func_name", LostHandler("函数名")) addErrorHandler("lost_func_body", LostHandler("函数体")) addErrorHandler("lost_block", LostHandler("块")) addErrorHandler("lost_stmt", LostHandler("语句")) addErrorHandler("lost_string", LostHandler("字符串")) addErrorHandler("lost_assign", LostHandler("等号'='")) addErrorHandler("lost_call", LostHandler("调用主体")) addErrorHandler("lost_lpa", LostHandler("左圆括号'('")) addErrorHandler("lost_rpa", LostHandler("右圆括号')'")) addErrorHandler("lost_lsq", LostHandler("左方括号'['")) addErrorHandler("lost_rsq", LostHandler("右方括号']'")) addErrorHandler("lost_lbr", LostHandler("左花括号'{'")) addErrorHandler("lost_rbr", LostHandler("右花括号'}'")) addErrorHandler("lost_colon", LostHandler("冒号':'")) addErrorHandler("lost_semi", LostHandler("分号';'")) addErrorHandler("lost_doc", LostHandler("文档")) addErrorHandler("lost_var", LostHandler("赋值")) addErrorHandler("lost_array", LostHandler("数组'[]'")) addErrorHandler("lost_map", LostHandler("字典'{}'")) addErrorHandler("lost_dot", LostHandler("点号'.'")) addErrorHandler("lost_property", LostHandler("属性连接符'::'")) addErrorHandler("lost_try", LostHandler("属性连接符'::'")) addErrorHandler("lost_catch", LostHandler("'catch'")) } /** * 声明动作处理器 * * @throws SyntaxException 词法错误 */ @Throws(SyntaxException::class) private fun declareActionHandler() { val actionNames = arrayOf("do_enter_scope", "do_leave_scope", "predeclear_funcname", "declear_variable", "declear_param", "func_clearargs", "do_enter_cycle", "lambda", "clear_catch") for (string in actionNames) { addActionHandler(string, handler.getActionHandler(string)) } } /** * 语法树建成之后的详细语义检查 * * @throws SyntaxException 词法错误 */ @Throws(SyntaxException::class) private fun check() { if (recorder.correct) { symbol.check(recorder) } else { val error = semanticError System.err.println(error) throw SyntaxException(SyntaxError.COMPILE_ERROR, recorder.error[0].position.position, error) } } /** * 产生中间代码 */ private fun gencode() { if (recorder.correct) { code = Codegen(symbol) code!!.gencode() } } override fun toString(): String { val sb = StringBuilder() // sb.append(getNGAString()); // sb.append(getNPAString()); sb.append(trackerError) sb.append(semanticError) sb.append(tokenList) if (recorder.correct) { sb.append(symbol.toString()) sb.append(inst) } return sb.toString() } companion object { var npaDesc: String? = null } }
mit
e66b184e837b918102e2e69ef5581346
43.726829
453
0.602356
3.515721
false
false
false
false
Hexworks/zircon
zircon.core/src/commonMain/kotlin/org/hexworks/zircon/internal/behavior/impl/DefaultScrollable3D.kt
1
4461
package org.hexworks.zircon.internal.behavior.impl import org.hexworks.cobalt.databinding.api.extension.toProperty import org.hexworks.zircon.api.behavior.Scrollable3D import org.hexworks.zircon.api.data.Position import org.hexworks.zircon.api.data.Position3D import org.hexworks.zircon.api.data.Size3D import kotlin.math.max import kotlin.math.min class DefaultScrollable3D( initialVisibleSize: Size3D, initialActualSize: Size3D ) : Scrollable3D { private val scrollable2D = DefaultScrollable( visibleSize = initialVisibleSize.to2DSize(), initialActualSize = initialActualSize.to2DSize() ) override val visibleSize = initialVisibleSize override val actualSize = initialActualSize init { checkSizes(initialActualSize) } override val visibleOffsetValue = Position3D.from2DPosition(Position.defaultPosition()).toProperty() override var visibleOffset by visibleOffsetValue.asDelegate() override fun scrollOneRight() = Position3D.from2DPosition( position = scrollable2D.scrollOneRight(), z = visibleOffset.z ).apply { visibleOffset = this } override fun scrollOneLeft() = Position3D.from2DPosition( position = scrollable2D.scrollOneLeft(), z = visibleOffset.z ).apply { visibleOffset = this } override fun scrollOneForward() = Position3D.from2DPosition( position = scrollable2D.scrollOneDown(), z = visibleOffset.z ).apply { visibleOffset = this } override fun scrollOneBackward() = Position3D.from2DPosition( position = scrollable2D.scrollOneUp(), z = visibleOffset.z ).apply { visibleOffset = this } override fun scrollOneUp(): Position3D { if (visibleSize.zLength + visibleOffset.z < actualSize.zLength) { this.visibleOffset = visibleOffset.withRelativeZ(1) } return visibleOffset } override fun scrollOneDown(): Position3D { if (visibleOffset.z > 0) { visibleOffset = visibleOffset.withRelativeZ(-1) } return visibleOffset } override fun scrollRightBy(x: Int) = Position3D.from2DPosition( position = scrollable2D.scrollRightBy(x), z = visibleOffset.z ).apply { visibleOffset = this } override fun scrollLeftBy(x: Int) = Position3D.from2DPosition( position = scrollable2D.scrollLeftBy(x), z = visibleOffset.z ).apply { visibleOffset = this } override fun scrollForwardBy(y: Int) = Position3D.from2DPosition( position = scrollable2D.scrollDownBy(y), z = visibleOffset.z ).apply { visibleOffset = this } override fun scrollBackwardBy(y: Int) = Position3D.from2DPosition( position = scrollable2D.scrollUpBy(y), z = visibleOffset.z ).apply { visibleOffset = this } override fun scrollUpBy(z: Int): Position3D { require(z >= 0) { "You can only scroll up by a positive amount!" } val levelToScrollTo = visibleOffset.z + z val lastScrollableLevel = actualSize.zLength - visibleSize.zLength visibleOffset = visibleOffset.copy(z = min(levelToScrollTo, lastScrollableLevel)) return visibleOffset } override fun scrollDownBy(z: Int): Position3D { require(z >= 0) { "You can only scroll down by a positive amount!" } val levelToScrollTo = visibleOffset.z - z visibleOffset = visibleOffset.copy(z = max(0, levelToScrollTo)) return visibleOffset } override fun scrollTo(position3D: Position3D) { require(actualSize.containsPosition(position3D)) { "new position $position3D has to be within the actual size $actualSize" } visibleOffset = position3D } private fun checkSizes(newSize: Size3D) { require(newSize.xLength >= visibleSize.xLength) { "Can't have a virtual space (${newSize.xLength}, ${newSize.zLength})" + " with less xLength than the visible space (${visibleSize.xLength}, ${visibleSize.zLength})!" } require(newSize.zLength >= visibleSize.zLength) { "Can't have a virtual space (${newSize.xLength}, ${newSize.zLength})" + " with less yLength than the visible space (${visibleSize.xLength}, ${visibleSize.zLength})!" } } }
apache-2.0
f799467dbb7ebfb888294248ac9e219c
31.326087
113
0.655907
4.085165
false
false
false
false
mdaniel/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/createFromUsage/createVariable/CreateParameterFromUsageFix.kt
1
6387
// 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.quickfix.createFromUsage.createVariable import com.intellij.openapi.editor.Editor import com.intellij.openapi.project.Project import com.intellij.psi.PsiElement import org.jetbrains.kotlin.descriptors.ClassDescriptor import org.jetbrains.kotlin.descriptors.ClassKind import org.jetbrains.kotlin.idea.base.resources.KotlinBundle import org.jetbrains.kotlin.idea.caches.resolve.resolveToDescriptorIfAny import org.jetbrains.kotlin.idea.quickfix.createFromUsage.CreateFromUsageFixBase import org.jetbrains.kotlin.idea.quickfix.createFromUsage.callableBuilder.* import org.jetbrains.kotlin.idea.refactoring.CompositeRefactoringRunner import org.jetbrains.kotlin.idea.refactoring.canRefactor import org.jetbrains.kotlin.idea.refactoring.changeSignature.* import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.getStrictParentOfType import org.jetbrains.kotlin.resolve.source.getPsi import org.jetbrains.kotlin.utils.addToStdlib.safeAs import java.lang.ref.WeakReference class CreateParameterFromUsageFix<E : KtElement>( originalExpression: E, private val dataProvider: (E) -> CreateParameterData<E>? ) : CreateFromUsageFixBase<E>(originalExpression) { private var parameterInfoReference: WeakReference<KotlinParameterInfo>? = null private fun parameterInfo(): KotlinParameterInfo? = parameterInfoReference?.get() ?: parameterData()?.parameterInfo?.also { parameterInfoReference = WeakReference(it) } private val calculatedText: String by lazy { element?.let { _ -> parameterInfo()?.run { if (valOrVar != KotlinValVar.None) KotlinBundle.message("create.property.0.as.constructor.parameter", name) else KotlinBundle.message("create.parameter.0", name) } } ?: "" } private val calculatedAvailable: Boolean by lazy { element != null && parameterInfo() != null } override fun isAvailable(project: Project, editor: Editor?, file: KtFile): Boolean = element?.run { calculatedAvailable } ?: false override fun getText(): String = element?.run { calculatedText } ?: "" override fun startInWriteAction() = false private fun runChangeSignature(project: Project, editor: Editor?) { val originalExpression = element ?: return val parameterInfo = parameterInfo() ?: return val config = object : KotlinChangeSignatureConfiguration { override fun configure(originalDescriptor: KotlinMethodDescriptor): KotlinMethodDescriptor { return originalDescriptor.modify { it.addParameter(parameterInfo) } } override fun performSilently(affectedFunctions: Collection<PsiElement>): Boolean = parameterData()?.createSilently ?: false } runChangeSignature(project, editor, parameterInfo.callableDescriptor, config, originalExpression, text) } private fun parameterData() = element?.let { dataProvider(it) } override fun invoke(project: Project, editor: Editor?, file: KtFile) { val onComplete = parameterData()?.onComplete if (onComplete == null) { runChangeSignature(project, editor) } else { object : CompositeRefactoringRunner(project, "refactoring.changeSignature") { override fun runRefactoring() { runChangeSignature(project, editor) } override fun onRefactoringDone() { onComplete(editor) } }.run() } } companion object { fun <E : KtElement> createFixForPrimaryConstructorPropertyParameter( element: E, callableInfosFactory: (E) -> List<CallableInfo>? ): CreateParameterFromUsageFix<E> = CreateParameterFromUsageFix(element, dataProvider = fun(element): CreateParameterData<E>? { val info = callableInfosFactory.invoke(element)?.singleOrNull().safeAs<PropertyInfo>() ?: return null if (info.receiverTypeInfo.staticContextRequired) return null val builder = CallableBuilderConfiguration(listOf(info), element).createBuilder() val receiverTypeCandidate = builder.computeTypeCandidates(info.receiverTypeInfo).firstOrNull() val receiverClassDescriptor: ClassDescriptor = if (receiverTypeCandidate != null) { builder.placement = CallablePlacement.WithReceiver(receiverTypeCandidate) receiverTypeCandidate.theType.constructor.declarationDescriptor as? ClassDescriptor ?: return null } else { if (element !is KtSimpleNameExpression) return null val classOrObject = element.getStrictParentOfType<KtClassOrObject>() ?: return null val classDescriptor = classOrObject.resolveToDescriptorIfAny() ?: return null val paramInfo = CreateParameterByRefActionFactory.extractFixData(element)?.parameterInfo if (paramInfo?.callableDescriptor == classDescriptor.unsubstitutedPrimaryConstructor) return null classDescriptor } if (receiverClassDescriptor.kind != ClassKind.CLASS) return null receiverClassDescriptor.source.getPsi().safeAs<KtClass>()?.takeIf { it.canRefactor() } ?: return null val constructorDescriptor = receiverClassDescriptor.unsubstitutedPrimaryConstructor ?: return null val paramType = info.returnTypeInfo.getPossibleTypes(builder).firstOrNull() if (paramType != null && paramType.hasTypeParametersToAdd(constructorDescriptor, builder.currentFileContext)) return null return CreateParameterData( parameterInfo = KotlinParameterInfo( callableDescriptor = constructorDescriptor, name = info.name, originalTypeInfo = KotlinTypeInfo(false, paramType), valOrVar = if (info.writable) KotlinValVar.Var else KotlinValVar.Val ), originalExpression = element ) }) } }
apache-2.0
66467e280a99a62a5df4510a82d70272
46.318519
158
0.683733
5.859633
false
false
false
false
SimpleMobileTools/Simple-Music-Player
app/src/main/kotlin/com/simplemobiletools/musicplayer/receivers/HeadsetPlugReceiver.kt
1
866
package com.simplemobiletools.musicplayer.receivers import android.content.BroadcastReceiver import android.content.Context import android.content.Intent import android.media.AudioManager import com.simplemobiletools.musicplayer.extensions.sendIntent import com.simplemobiletools.musicplayer.helpers.PAUSE class HeadsetPlugReceiver : BroadcastReceiver() { override fun onReceive(context: Context, intent: Intent) { if (!isInitialStickyBroadcast && intent.action == Intent.ACTION_HEADSET_PLUG) { val state = intent.getIntExtra("state", -1) // we care only about the case where the headphone gets unplugged if (state == 0) { context.sendIntent(PAUSE) } } else if (intent.action == AudioManager.ACTION_AUDIO_BECOMING_NOISY) { context.sendIntent(PAUSE) } } }
gpl-3.0
3cc8a10b1ea2d6b1079e115a08de801f
36.652174
87
0.704388
4.706522
false
false
false
false
johnjohndoe/Umweltzone
Umweltzone/src/main/java/de/avpptr/umweltzone/zones/viewholders/OneZoneViewHolder.kt
1
1945
/* * Copyright (C) 2020 Tobias Preuss * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package de.avpptr.umweltzone.zones.viewholders import android.graphics.drawable.GradientDrawable import android.graphics.drawable.LayerDrawable import android.view.View import androidx.annotation.LayoutRes import de.avpptr.umweltzone.R import de.avpptr.umweltzone.zones.viewmodels.ZoneViewModel import kotlinx.android.synthetic.main.zones_list_item_one_zone.view.* class OneZoneViewHolder( val view: View, private val onItemClick: (view: View) -> Unit ) : ZoneViewHolder<ZoneViewModel.OneZoneViewModel>(view) { private val zoneShapeView: GradientDrawable init { val badgeBackground = view.zoneOneZoneBadgeView.background as LayerDrawable zoneShapeView = badgeBackground.findDrawableByLayerId(R.id.zone_shape) as GradientDrawable } override fun bind(viewModel: ZoneViewModel.OneZoneViewModel) = with(view) { tag = viewModel setOnClickListener(onItemClick) zoneOneZoneNameView.text = viewModel.name zoneOneZoneNameView.setTextColor(viewModel.nameTextColor) zoneOneZoneBadgeView.setBadge(zoneShapeView, viewModel.badgeViewModel) } companion object { @LayoutRes const val layout = R.layout.zones_list_item_one_zone } }
gpl-3.0
73bb868fb816fba3870d2e8b8e8d3cde
34.363636
98
0.745501
4.200864
false
false
false
false
square/picasso
picasso/src/test/java/com/squareup/picasso3/DeferredRequestCreatorTest.kt
1
5389
/* * Copyright (C) 2013 Square, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.squareup.picasso3 import com.google.common.truth.Truth.assertThat import com.squareup.picasso3.TestUtils.argumentCaptor import com.squareup.picasso3.TestUtils.mockCallback import com.squareup.picasso3.TestUtils.mockFitImageViewTarget import com.squareup.picasso3.TestUtils.mockPicasso import com.squareup.picasso3.TestUtils.mockRequestCreator import org.junit.Test import org.junit.runner.RunWith import org.mockito.Mockito.`when` import org.mockito.Mockito.never import org.mockito.Mockito.spy import org.mockito.Mockito.verify import org.mockito.Mockito.verifyNoMoreInteractions import org.robolectric.RobolectricTestRunner import org.robolectric.RuntimeEnvironment @RunWith(RobolectricTestRunner::class) class DeferredRequestCreatorTest { private val picasso = mockPicasso(RuntimeEnvironment.application) @Test fun initWhileAttachedAddsAttachAndPreDrawListener() { val target = mockFitImageViewTarget(true) val observer = target.viewTreeObserver val request = DeferredRequestCreator(mockRequestCreator(picasso), target, null) verify(observer).addOnPreDrawListener(request) } @Test fun initWhileDetachedAddsAttachListenerWhichDefersPreDrawListener() { val target = mockFitImageViewTarget(true) `when`(target.windowToken).thenReturn(null) val observer = target.viewTreeObserver val request = DeferredRequestCreator(mockRequestCreator(picasso), target, null) verify(target).addOnAttachStateChangeListener(request) verifyNoMoreInteractions(observer) // Attach and ensure we defer to the pre-draw listener. request.onViewAttachedToWindow(target) verify(observer).addOnPreDrawListener(request) // Detach and ensure we remove the pre-draw listener from the original VTO. request.onViewDetachedFromWindow(target) verify(observer).removeOnPreDrawListener(request) } @Test fun cancelWhileAttachedRemovesAttachListener() { val target = mockFitImageViewTarget(true) val request = DeferredRequestCreator(mockRequestCreator(picasso), target, null) verify(target).addOnAttachStateChangeListener(request) request.cancel() verify(target).removeOnAttachStateChangeListener(request) } @Test fun cancelClearsCallback() { val target = mockFitImageViewTarget(true) val callback = mockCallback() val request = DeferredRequestCreator(mockRequestCreator(picasso), target, callback) assertThat(request.callback).isNotNull() request.cancel() assertThat(request.callback).isNull() } @Test fun cancelClearsTag() { val target = mockFitImageViewTarget(true) val creator = mockRequestCreator(picasso).tag("TAG") val request = DeferredRequestCreator(creator, target, null) assertThat(creator.tag).isNotNull() request.cancel() assertThat(creator.tag).isNull() } @Test fun onLayoutSkipsIfViewIsAttachedAndViewTreeObserverIsDead() { val target = mockFitImageViewTarget(false) val creator = mockRequestCreator(picasso) val request = DeferredRequestCreator(creator, target, null) val viewTreeObserver = target.viewTreeObserver request.onPreDraw() verify(viewTreeObserver).addOnPreDrawListener(request) verify(viewTreeObserver).isAlive verifyNoMoreInteractions(viewTreeObserver) } @Test fun waitsForAnotherLayoutIfWidthOrHeightIsZero() { val target = mockFitImageViewTarget(true) `when`(target.width).thenReturn(0) `when`(target.height).thenReturn(0) val creator = mockRequestCreator(picasso) val request = DeferredRequestCreator(creator, target, null) request.onPreDraw() verify(target.viewTreeObserver, never()).removeOnPreDrawListener(request) } @Test fun cancelSkipsIfViewTreeObserverIsDead() { val target = mockFitImageViewTarget(false) val creator = mockRequestCreator(picasso) val request = DeferredRequestCreator(creator, target, null) request.cancel() verify(target.viewTreeObserver, never()).removeOnPreDrawListener(request) } @Test fun preDrawSubmitsRequestAndCleansUp() { val spyPicasso = spy(picasso) // ugh val creator = RequestCreator(spyPicasso, TestUtils.URI_1, 0) val target = mockFitImageViewTarget(true) `when`(target.width).thenReturn(100) `when`(target.height).thenReturn(100) val observer = target.viewTreeObserver val request = DeferredRequestCreator(creator, target, null) request.onPreDraw() verify(observer).removeOnPreDrawListener(request) val actionCaptor = argumentCaptor<ImageViewAction>() verify(spyPicasso).enqueueAndSubmit(actionCaptor.capture()) val value = actionCaptor.value assertThat(value).isInstanceOf(ImageViewAction::class.java) assertThat(value.request.targetWidth).isEqualTo(100) assertThat(value.request.targetHeight).isEqualTo(100) } }
apache-2.0
9222d25ba4dde49a5074e2b37cd78593
37.492857
87
0.774726
4.555368
false
true
false
false
GunoH/intellij-community
platform/webSymbols/src/com/intellij/webSymbols/query/WebSymbolMatch.kt
2
9438
// 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.webSymbols.query import com.intellij.lang.documentation.DocumentationTarget import com.intellij.model.Pointer import com.intellij.navigation.NavigationTarget import com.intellij.openapi.project.Project import com.intellij.psi.PsiElement import com.intellij.webSymbols.* import com.intellij.webSymbols.WebSymbol.Priority import com.intellij.webSymbols.documentation.WebSymbolDocumentation import com.intellij.webSymbols.documentation.WebSymbolDocumentationTarget import com.intellij.webSymbols.html.WebSymbolHtmlAttributeValue import com.intellij.webSymbols.utils.merge import javax.swing.Icon open class WebSymbolMatch private constructor(override val matchedName: String, override val nameSegments: List<WebSymbolNameSegment>, override val namespace: SymbolNamespace, override val kind: SymbolKind, override val origin: WebSymbolOrigin, private val explicitPriority: Priority?, private val explicitProximity: Int?) : WebSymbol { protected fun reversedSegments() = Sequence { ReverseListIterator(nameSegments) } override val psiContext: PsiElement? get() = reversedSegments().flatMap { it.symbols.asSequence() } .mapNotNull { it.psiContext }.firstOrNull() override val documentation: WebSymbolDocumentation? get() = reversedSegments().flatMap { it.symbols.asSequence() } .mapNotNull { it.documentation }.firstOrNull() override val name: String get() = matchedName.substring(nameSegments.firstOrNull()?.start ?: 0, nameSegments.lastOrNull()?.end ?: 0) override val description: String? get() = nameSegments.takeIf { it.size == 1 } ?.get(0)?.symbols?.asSequence()?.map { it.description }?.firstOrNull() override val docUrl: String? get() = nameSegments.takeIf { it.size == 1 } ?.get(0)?.symbols?.asSequence()?.map { it.docUrl }?.firstOrNull() override val descriptionSections: Map<String, String> get() = nameSegments.takeIf { it.size == 1 } ?.get(0)?.symbols?.asSequence() ?.flatMap { it.descriptionSections.asSequence() } ?.distinct() ?.associateBy({ it.key }, { it.value }) ?: emptyMap() override val virtual: Boolean get() = nameSegments.any { segment -> segment.symbols.any { it.virtual } } override val extension: Boolean get() = nameSegments.isNotEmpty() && nameSegments.all { segment -> segment.symbols.isNotEmpty() && segment.symbols.all { it.extension } } override val priority: Priority? get() = explicitPriority ?: reversedSegments().mapNotNull { it.priority }.firstOrNull() override val proximity: Int? get() = explicitProximity ?: reversedSegments().mapNotNull { it.proximity }.firstOrNull() override val completeMatch: Boolean get() = (nameSegments.all { segment -> segment.problem == null && segment.symbols.all { it.completeMatch } } && (nameSegments.lastOrNull()?.end ?: 0) == matchedName.length) override val queryScope: Sequence<WebSymbolsScope> get() = nameSegments.asSequence() .flatMap { it.symbols } .flatMap { it.queryScope } override val type: Any? get() = reversedSegments().flatMap { it.symbols } .mapNotNull { it.type }.firstOrNull() override val attributeValue: WebSymbolHtmlAttributeValue? get() = reversedSegments().flatMap { it.symbols }.mapNotNull { it.attributeValue }.merge() override val required: Boolean? get() = reversedSegments().flatMap { it.symbols }.mapNotNull { it.required }.firstOrNull() override val experimental: Boolean get() = reversedSegments().flatMap { it.symbols }.map { it.experimental }.firstOrNull() ?: false override val deprecated: Boolean get() = reversedSegments().map { it.deprecated }.firstOrNull() ?: false override val icon: Icon? get() = reversedSegments().flatMap { it.symbols }.mapNotNull { it.icon }.firstOrNull() override val properties: Map<String, Any> get() = nameSegments.asSequence().flatMap { it.symbols } .flatMap { it.properties.entries } .filter { it.key != WebSymbol.PROP_HIDE_FROM_COMPLETION } .map { Pair(it.key, it.value) } .toMap() override fun createPointer(): Pointer<WebSymbolMatch> = WebSymbolMatchPointer(this) override fun getNavigationTargets(project: Project): Collection<NavigationTarget> = if (nameSegments.size == 1) nameSegments[0].symbols.asSequence() .flatMap { it.getNavigationTargets(project) } .toList() else emptyList() override fun getDocumentationTarget(): DocumentationTarget = reversedSegments() .flatMap { it.symbols.asSequence() } .map { if (it === this) super.getDocumentationTarget() else it.documentationTarget } .filter { it !is WebSymbolDocumentationTarget || it.symbol.documentation?.isNotEmpty() == true } .firstOrNull() ?: super.getDocumentationTarget() override fun equals(other: Any?): Boolean = other is WebSymbolMatch && other.name == name && other.origin == origin && other.namespace == namespace && other.kind == kind && other.nameSegments.equalsIgnoreOffset(nameSegments) override fun hashCode(): Int = name.hashCode() class ReverseListIterator<T>(list: List<T>) : Iterator<T> { private val iterator = list.listIterator(list.size) override operator fun hasNext(): Boolean { return iterator.hasPrevious() } override operator fun next(): T { return iterator.previous() } } companion object { @JvmStatic @JvmOverloads fun create(matchedName: String, nameSegments: List<WebSymbolNameSegment>, namespace: SymbolNamespace, kind: SymbolKind, origin: WebSymbolOrigin, explicitPriority: Priority? = null, explicitProximity: Int? = null): WebSymbolMatch = if (nameSegments.any { it.symbols.any { symbol -> symbol is PsiSourcedWebSymbol } }) PsiSourcedWebSymbolMatch(matchedName, nameSegments, namespace, kind, origin, explicitPriority, explicitProximity) else WebSymbolMatch(matchedName, nameSegments, namespace, kind, origin, explicitPriority, explicitProximity) private fun List<WebSymbolNameSegment>.equalsIgnoreOffset(other: List<WebSymbolNameSegment>): Boolean { if (size != other.size) return false if (this.isEmpty()) return true val startOffset1 = this[0].start val startOffset2 = other[0].start for (i in indices) { val segment1 = this[i] val segment2 = other[i] if (segment1.start - startOffset1 != segment2.start - startOffset2 || segment1.end - startOffset1 != segment2.end - startOffset2 || segment1.deprecated != segment2.deprecated || segment1.symbols != segment2.symbols || segment1.problem != segment2.problem || segment1.displayName != segment2.displayName || segment1.priority != segment2.priority || segment1.proximity != segment2.proximity) { return false } } return true } } class PsiSourcedWebSymbolMatch(matchedName: String, nameSegments: List<WebSymbolNameSegment>, namespace: SymbolNamespace, kind: SymbolKind, origin: WebSymbolOrigin, explicitPriority: Priority?, explicitProximity: Int?) : WebSymbolMatch(matchedName, nameSegments, namespace, kind, origin, explicitPriority, explicitProximity), PsiSourcedWebSymbol { override val psiContext: PsiElement? get() = super<PsiSourcedWebSymbol>.psiContext override val source: PsiElement? get() = reversedSegments().flatMap { it.symbols.asSequence() } .mapNotNull { it.psiContext }.firstOrNull() override fun getNavigationTargets(project: Project): Collection<NavigationTarget> = super<WebSymbolMatch>.getNavigationTargets(project) } private class WebSymbolMatchPointer(webSymbolMatch: WebSymbolMatch) : Pointer<WebSymbolMatch> { private val matchedName = webSymbolMatch.matchedName private val nameSegments = webSymbolMatch.nameSegments .map { it.createPointer() } private val namespace = webSymbolMatch.namespace private val kind = webSymbolMatch.kind private val origin = webSymbolMatch.origin private val explicitPriority = webSymbolMatch.explicitPriority private val explicitProximity = webSymbolMatch.explicitProximity override fun dereference(): WebSymbolMatch? = nameSegments.map { it.dereference() } .takeIf { it.all { segment -> segment != null } } ?.let { @Suppress("UNCHECKED_CAST") (create(matchedName, it as List<WebSymbolNameSegment>, namespace, kind, origin, explicitPriority, explicitProximity)) } } }
apache-2.0
95c93925fc081532358061bab67bb653
39.681034
141
0.655435
4.854938
false
false
false
false
GunoH/intellij-community
platform/vcs-impl/src/com/intellij/openapi/vcs/changes/ui/vcsToolWindowFactories.kt
2
4203
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.openapi.vcs.changes.ui import com.intellij.ide.IdeBundle import com.intellij.ide.actions.ToolWindowEmptyStateAction.rebuildContentUi import com.intellij.ide.impl.isTrusted import com.intellij.openapi.actionSystem.ActionGroup import com.intellij.openapi.actionSystem.ActionManager import com.intellij.openapi.actionSystem.ActionToolbar import com.intellij.openapi.project.Project import com.intellij.openapi.util.registry.Registry import com.intellij.openapi.vcs.ProjectLevelVcsManager import com.intellij.openapi.vcs.VcsBundle.message import com.intellij.openapi.vcs.changes.ui.ChangesViewContentManager.Companion.COMMIT_TOOLWINDOW_ID import com.intellij.openapi.wm.ToolWindow import com.intellij.openapi.wm.ToolWindowManager import com.intellij.openapi.wm.ex.ToolWindowEx import com.intellij.util.ui.StatusText private class ChangeViewToolWindowFactory : VcsToolWindowFactory() { private val shouldShowWithoutActiveVcs = Registry.get("vcs.empty.toolwindow.show") override fun init(window: ToolWindow) { super.init(window) window.setAdditionalGearActions(ActionManager.getInstance().getAction("LocalChangesView.GearActions") as ActionGroup) } override fun setEmptyState(project: Project, state: StatusText) { setChangesViewEmptyState(state, project) } override fun createToolWindowContent(project: Project, toolWindow: ToolWindow) { super.createToolWindowContent(project, toolWindow) if (toolWindow.contentManager.isEmpty) { // to show id label rebuildContentUi(toolWindow) } } override fun updateState(toolWindow: ToolWindow) { super.updateState(toolWindow) if (shouldShowWithoutActiveVcs.asBoolean().not()) { toolWindow.isShowStripeButton = showInStripeWithoutActiveVcs(toolWindow.project) } toolWindow.stripeTitle = ProjectLevelVcsManager.getInstance(toolWindow.project).allActiveVcss.singleOrNull()?.displayName ?: IdeBundle.message("toolwindow.stripe.Version_Control") } override fun isAvailable(project: Project) = project.isTrusted() private fun showInStripeWithoutActiveVcs(project: Project): Boolean { return shouldShowWithoutActiveVcs.asBoolean() || ProjectLevelVcsManager.getInstance(project).hasAnyMappings() } } private class CommitToolWindowFactory : VcsToolWindowFactory() { override fun init(window: ToolWindow) { super.init(window) window.setAdditionalGearActions(ActionManager.getInstance().getAction("CommitView.GearActions") as ActionGroup) } override fun setEmptyState(project: Project, state: StatusText) { setCommitViewEmptyState(state, project) } override fun isAvailable(project: Project): Boolean { return ProjectLevelVcsManager.getInstance(project).hasAnyMappings() && ChangesViewContentManager.isCommitToolWindowShown(project) && project.isTrusted() } override fun createToolWindowContent(project: Project, toolWindow: ToolWindow) { super.createToolWindowContent(project, toolWindow) hideIdLabelIfNotEmptyState(toolWindow) // to show id label if (toolWindow.contentManager.isEmpty) { rebuildContentUi(toolWindow) } } } internal class SwitchToCommitDialogHint(toolWindow: ToolWindowEx, toolbar: ActionToolbar) : ChangesViewContentManagerListener { private val actionToolbarTooltip = ActionToolbarGotItTooltip("changes.view.toolwindow", message("switch.to.commit.dialog.hint.text"), toolWindow.disposable, toolbar, gearButtonOrToolbar) init { toolWindow.project.messageBus.connect(actionToolbarTooltip.tooltipDisposable).subscribe(ChangesViewContentManagerListener.TOPIC, this) } override fun toolWindowMappingChanged() = actionToolbarTooltip.hideHint(true) companion object { fun install(project: Project) { val toolWindow = ToolWindowManager.getInstance(project).getToolWindow(COMMIT_TOOLWINDOW_ID) as? ToolWindowEx ?: return val toolbar = toolWindow.decorator.headerToolbar ?: return SwitchToCommitDialogHint(toolWindow, toolbar) } } }
apache-2.0
0dcdba9ea28ab0146e88c211c6bd384c
37.559633
138
0.780633
4.836594
false
false
false
false
GunoH/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/intentions/branchedTransformations/BranchedFoldingUtils.kt
3
11446
// 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.intentions.branchedTransformations import org.jetbrains.kotlin.cfg.WhenChecker import org.jetbrains.kotlin.diagnostics.Errors import org.jetbrains.kotlin.idea.caches.resolve.analyze import org.jetbrains.kotlin.idea.caches.resolve.safeAnalyzeNonSourceRootCode import org.jetbrains.kotlin.idea.base.psi.replaced import org.jetbrains.kotlin.idea.intentions.branches import org.jetbrains.kotlin.idea.references.mainReference import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.anyDescendantOfType import org.jetbrains.kotlin.psi.psiUtil.getNonStrictParentOfType import org.jetbrains.kotlin.psi.psiUtil.getStrictParentOfType import org.jetbrains.kotlin.psi.psiUtil.lastBlockStatementOrThis import org.jetbrains.kotlin.resolve.calls.util.getType import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode import org.jetbrains.kotlin.types.KotlinType import org.jetbrains.kotlin.types.TypeConstructor import org.jetbrains.kotlin.types.typeUtil.isNothing import org.jetbrains.kotlin.types.typeUtil.isSubtypeOf object BranchedFoldingUtils { private fun getFoldableBranchedAssignment(branch: KtExpression?): KtBinaryExpression? { fun checkAssignment(expression: KtBinaryExpression): Boolean { if (expression.operationToken !in KtTokens.ALL_ASSIGNMENTS) return false val left = expression.left as? KtNameReferenceExpression ?: return false if (expression.right == null) return false val parent = expression.parent if (parent is KtBlockExpression) { return !KtPsiUtil.checkVariableDeclarationInBlock(parent, left.text) } return true } return (branch?.lastBlockStatementOrThis() as? KtBinaryExpression)?.takeIf(::checkAssignment) } fun getFoldableBranchedReturn(branch: KtExpression?): KtReturnExpression? = (branch?.lastBlockStatementOrThis() as? KtReturnExpression)?.takeIf { it.returnedExpression != null && it.returnedExpression !is KtLambdaExpression && it.getTargetLabel() == null } private fun KtBinaryExpression.checkAssignmentsMatch( other: KtBinaryExpression, leftType: KotlinType, rightTypeConstructor: TypeConstructor ): Boolean { val left = this.left ?: return false val otherLeft = other.left ?: return false if (left.text != otherLeft.text || operationToken != other.operationToken || left.mainReference?.resolve() != otherLeft.mainReference?.resolve() ) return false val rightType = other.rightType() ?: return false return rightType.constructor == rightTypeConstructor || (operationToken == KtTokens.EQ && rightType.isSubtypeOf(leftType)) } private fun KtBinaryExpression.rightType(): KotlinType? { val right = this.right ?: return null val context = this.analyze() val diagnostics = context.diagnostics fun hasTypeMismatchError(e: KtExpression) = diagnostics.forElement(e).any { it.factory == Errors.TYPE_MISMATCH } if (hasTypeMismatchError(this) || hasTypeMismatchError(right)) return null return right.getType(context) } internal fun getFoldableAssignmentNumber(expression: KtExpression?): Int { expression ?: return -1 val assignments = linkedSetOf<KtBinaryExpression>() fun collectAssignmentsAndCheck(e: KtExpression?): Boolean = when (e) { is KtWhenExpression -> { val entries = e.entries !e.hasMissingCases() && entries.isNotEmpty() && entries.all { entry -> val assignment = getFoldableBranchedAssignment(entry.expression)?.run { assignments.add(this) } assignment != null || collectAssignmentsAndCheck(entry.expression?.lastBlockStatementOrThis()) } } is KtIfExpression -> { val branches = e.branches val elseBranch = branches.lastOrNull()?.getStrictParentOfType<KtIfExpression>()?.`else` branches.size > 1 && elseBranch != null && branches.all { branch -> val assignment = getFoldableBranchedAssignment(branch)?.run { assignments.add(this) } assignment != null || collectAssignmentsAndCheck(branch?.lastBlockStatementOrThis()) } } is KtTryExpression -> { e.tryBlockAndCatchBodies().all { val assignment = getFoldableBranchedAssignment(it)?.run { assignments.add(this) } assignment != null || collectAssignmentsAndCheck(it?.lastBlockStatementOrThis()) } } is KtCallExpression -> { e.analyze().getType(e)?.isNothing() ?: false } is KtBreakExpression, is KtContinueExpression, is KtThrowExpression, is KtReturnExpression -> true else -> false } if (!collectAssignmentsAndCheck(expression)) return -1 val firstAssignment = assignments.firstOrNull { !it.right.isNullExpression() } ?: assignments.firstOrNull() ?: return 0 val leftType = firstAssignment.left?.let { it.getType(it.analyze(BodyResolveMode.PARTIAL)) } ?: return 0 val rightTypeConstructor = firstAssignment.rightType()?.constructor ?: return -1 if (assignments.any { !firstAssignment.checkAssignmentsMatch(it, leftType, rightTypeConstructor) }) { return -1 } if (expression.anyDescendantOfType<KtBinaryExpression>( predicate = { if (it.operationToken in KtTokens.ALL_ASSIGNMENTS) if (it.getNonStrictParentOfType<KtFinallySection>() != null) firstAssignment.checkAssignmentsMatch(it, leftType, rightTypeConstructor) else it !in assignments else false } ) ) { return -1 } return assignments.size } private fun getFoldableReturns(branches: List<KtExpression?>): List<KtReturnExpression>? = branches.fold<KtExpression?, MutableList<KtReturnExpression>?>(mutableListOf()) { prevList, branch -> if (prevList == null) return@fold null val foldableBranchedReturn = getFoldableBranchedReturn(branch) if (foldableBranchedReturn != null) { prevList.add(foldableBranchedReturn) } else { val currReturns = getFoldableReturns(branch?.lastBlockStatementOrThis()) ?: return@fold null prevList += currReturns } prevList } internal fun getFoldableReturns(expression: KtExpression?): List<KtReturnExpression>? = when (expression) { is KtWhenExpression -> { val entries = expression.entries when { expression.hasMissingCases() -> null entries.isEmpty() -> null else -> getFoldableReturns(entries.map { it.expression }) } } is KtIfExpression -> { val branches = expression.branches when { branches.isEmpty() -> null branches.lastOrNull()?.getStrictParentOfType<KtIfExpression>()?.`else` == null -> null else -> getFoldableReturns(branches) } } is KtTryExpression -> { if (expression.finallyBlock?.finalExpression?.let { getFoldableReturns(listOf(it)) }?.isNotEmpty() == true) null else getFoldableReturns(expression.tryBlockAndCatchBodies()) } is KtCallExpression -> { if (expression.analyze().getType(expression)?.isNothing() == true) emptyList() else null } is KtBreakExpression, is KtContinueExpression, is KtThrowExpression -> emptyList() else -> null } private fun getFoldableReturnNumber(expression: KtExpression?) = getFoldableReturns(expression)?.size ?: -1 fun canFoldToReturn(expression: KtExpression?): Boolean = getFoldableReturnNumber(expression) > 0 fun tryFoldToAssignment(expression: KtExpression) { var lhs: KtExpression? = null var op: String? = null val psiFactory = KtPsiFactory(expression) fun KtBinaryExpression.replaceWithRHS() { if (lhs == null || op == null) { lhs = left!!.copy() as KtExpression op = operationReference.text } val rhs = right!! if (rhs is KtLambdaExpression && this.parent !is KtBlockExpression) { replace(psiFactory.createSingleStatementBlock(rhs)) } else { replace(rhs) } } fun lift(e: KtExpression?) { when (e) { is KtWhenExpression -> e.entries.forEach { entry -> getFoldableBranchedAssignment(entry.expression)?.replaceWithRHS() ?: lift(entry.expression?.lastBlockStatementOrThis()) } is KtIfExpression -> e.branches.forEach { branch -> getFoldableBranchedAssignment(branch)?.replaceWithRHS() ?: lift(branch?.lastBlockStatementOrThis()) } is KtTryExpression -> e.tryBlockAndCatchBodies().forEach { getFoldableBranchedAssignment(it)?.replaceWithRHS() ?: lift(it?.lastBlockStatementOrThis()) } } } lift(expression) if (lhs != null && op != null) { expression.replace(psiFactory.createExpressionByPattern("$0 $1 $2", lhs!!, op!!, expression)) } } fun foldToReturn(expression: KtExpression): KtExpression { fun KtReturnExpression.replaceWithReturned() { replace(returnedExpression!!) } fun lift(e: KtExpression?) { when (e) { is KtWhenExpression -> e.entries.forEach { entry -> val entryExpr = entry.expression getFoldableBranchedReturn(entryExpr)?.replaceWithReturned() ?: lift(entryExpr?.lastBlockStatementOrThis()) } is KtIfExpression -> e.branches.forEach { branch -> getFoldableBranchedReturn(branch)?.replaceWithReturned() ?: lift(branch?.lastBlockStatementOrThis()) } is KtTryExpression -> e.tryBlockAndCatchBodies().forEach { getFoldableBranchedReturn(it)?.replaceWithReturned() ?: lift(it?.lastBlockStatementOrThis()) } } } lift(expression) return expression.replaced(KtPsiFactory(expression).createExpressionByPattern("return $0", expression)) } private fun KtTryExpression.tryBlockAndCatchBodies(): List<KtExpression?> = listOf(tryBlock) + catchClauses.map { it.catchBody } private fun KtWhenExpression.hasMissingCases(): Boolean = !KtPsiUtil.checkWhenExpressionHasSingleElse(this) && WhenChecker.getMissingCases(this, safeAnalyzeNonSourceRootCode()).isNotEmpty() }
apache-2.0
e33e19fb19cef0c052483b94c0651725
46.493776
158
0.632099
5.774975
false
false
false
false
walleth/kethereum
bip44/src/main/kotlin/org/kethereum/bip44/BIP44.kt
1
1431
package org.kethereum.bip44 /* BIP44 as in https://github.com/bitcoin/bips/blob/master/bip-0044.mediawiki */ const val BIP44_HARDENING_FLAG = 0x80000000.toInt() private fun getEnsuredCleanPath(path: String): String { if (!path.trim().startsWith("m/")) { throw (IllegalArgumentException("Must start with m/")) } return path.replace("m/", "").replace(" ", "") } data class BIP44Element(val hardened: Boolean, val number: Int) { val numberWithHardeningFlag = if (hardened) number or BIP44_HARDENING_FLAG else number } data class BIP44(val path: List<BIP44Element>) { constructor(path: String) : this(getEnsuredCleanPath(path).split("/") .asSequence() .filter { it.isNotEmpty() } .map { BIP44Element( hardened = it.contains("'"), number = it.replace("'", "").toIntOrNull() ?: throw IllegalArgumentException("not a number $it") ) } .toList()) override fun equals(other: Any?) = (other as? BIP44)?.path == path override fun hashCode() = path.hashCode() override fun toString() = "m/" + path.joinToString("/") { if (it.hardened) "${it.number}'" else "${it.number}" } fun increment() = BIP44(path.subList(0, path.size - 1) + path.last().let { BIP44Element(it.hardened, it.number + 1) }) }
mit
a2efcde1fb52b30b21eba38a5d089523
32.27907
90
0.580014
3.846774
false
false
false
false
ktorio/ktor
ktor-http/common/src/io/ktor/http/URLParser.kt
1
8637
/* * Copyright 2014-2021 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. */ package io.ktor.http import io.ktor.util.* internal val ROOT_PATH = listOf("") /** * Take url parts from [urlString] * throws [URLParserException] */ public fun URLBuilder.takeFrom(urlString: String): URLBuilder { if (urlString.isBlank()) return this return try { takeFromUnsafe(urlString) } catch (cause: Throwable) { throw URLParserException(urlString, cause) } } /** * Thrown when failed to parse URL */ public class URLParserException(urlString: String, cause: Throwable) : IllegalStateException( "Fail to parse url: $urlString", cause ) internal fun URLBuilder.takeFromUnsafe(urlString: String): URLBuilder { var startIndex = urlString.indexOfFirst { !it.isWhitespace() } val endIndex = urlString.indexOfLast { !it.isWhitespace() } + 1 val schemeLength = findScheme(urlString, startIndex, endIndex) if (schemeLength > 0) { val scheme = urlString.substring(startIndex, startIndex + schemeLength) protocol = URLProtocol.createOrDefault(scheme) startIndex += schemeLength + 1 } // Auth & Host val slashCount = count(urlString, startIndex, endIndex, '/') startIndex += slashCount if (protocol.name == "file") { parseFile(urlString, startIndex, endIndex, slashCount) return this } if (protocol.name == "mailto") { require(slashCount == 0) parseMailto(urlString, startIndex, endIndex) return this } if (slashCount >= 2) { loop@ while (true) { val delimiter = urlString.indexOfAny("@/\\?#".toCharArray(), startIndex).takeIf { it > 0 } ?: endIndex if (delimiter < endIndex && urlString[delimiter] == '@') { // user and password check val passwordIndex = urlString.indexOfColonInHostPort(startIndex, delimiter) if (passwordIndex != -1) { encodedUser = urlString.substring(startIndex, passwordIndex) encodedPassword = urlString.substring(passwordIndex + 1, delimiter) } else { encodedUser = urlString.substring(startIndex, delimiter) } startIndex = delimiter + 1 } else { fillHost(urlString, startIndex, delimiter) startIndex = delimiter break@loop } } } // Path if (startIndex >= endIndex) { encodedPathSegments = if (urlString[endIndex - 1] == '/') ROOT_PATH else emptyList() return this } encodedPathSegments = if (slashCount == 0) { // Relative path // last item is either file name or empty string for directories encodedPathSegments.dropLast(1) } else { emptyList() } val pathEnd = urlString.indexOfAny("?#".toCharArray(), startIndex).takeIf { it > 0 } ?: endIndex if (pathEnd > startIndex) { val rawPath = urlString.substring(startIndex, pathEnd) val basePath = when { encodedPathSegments.size == 1 && encodedPathSegments.first().isEmpty() -> emptyList() else -> encodedPathSegments } val rawChunks = if (rawPath == "/") ROOT_PATH else rawPath.split('/') val relativePath = when (slashCount) { 1 -> ROOT_PATH else -> emptyList() } + rawChunks encodedPathSegments = basePath + relativePath startIndex = pathEnd } // Query if (startIndex < endIndex && urlString[startIndex] == '?') { startIndex = parseQuery(urlString, startIndex, endIndex) } // Fragment parseFragment(urlString, startIndex, endIndex) return this } private fun URLBuilder.parseFile(urlString: String, startIndex: Int, endIndex: Int, slashCount: Int) { when (slashCount) { 2 -> { val nextSlash = urlString.indexOf('/', startIndex) if (nextSlash == -1 || nextSlash == endIndex) { host = urlString.substring(startIndex, endIndex) return } host = urlString.substring(startIndex, nextSlash) encodedPath = urlString.substring(nextSlash, endIndex) } 3 -> { host = "" encodedPath = "/" + urlString.substring(startIndex, endIndex) } else -> throw IllegalArgumentException("Invalid file url: $urlString") } } private fun URLBuilder.parseMailto(urlString: String, startIndex: Int, endIndex: Int) { val delimiter = urlString.indexOf("@", startIndex) if (delimiter == -1) { throw IllegalArgumentException("Invalid mailto url: $urlString, it should contain '@'.") } user = urlString.substring(startIndex, delimiter).decodeURLPart() host = urlString.substring(delimiter + 1, endIndex) } private fun URLBuilder.parseQuery(urlString: String, startIndex: Int, endIndex: Int): Int { if (startIndex + 1 == endIndex) { trailingQuery = true return endIndex } val fragmentStart = urlString.indexOf('#', startIndex + 1).takeIf { it > 0 } ?: endIndex val rawParameters = parseQueryString(urlString.substring(startIndex + 1, fragmentStart), decode = false) rawParameters.forEach { key, values -> encodedParameters.appendAll(key, values) } return fragmentStart } private fun URLBuilder.parseFragment(urlString: String, startIndex: Int, endIndex: Int) { if (startIndex < endIndex && urlString[startIndex] == '#') { encodedFragment = urlString.substring(startIndex + 1, endIndex) } } private fun URLBuilder.fillHost(urlString: String, startIndex: Int, endIndex: Int) { val colonIndex = urlString.indexOfColonInHostPort(startIndex, endIndex).takeIf { it > 0 } ?: endIndex host = urlString.substring(startIndex, colonIndex) if (colonIndex + 1 < endIndex) { port = urlString.substring(colonIndex + 1, endIndex).toInt() } else { port = DEFAULT_PORT } } /** * Finds scheme in the given [urlString]. If there is no scheme found the function returns -1. If the scheme contains * illegal characters an [IllegalArgumentException] will be thrown. If the scheme is present and it doesn't contain * illegal characters the function returns the length of the scheme. */ private fun findScheme(urlString: String, startIndex: Int, endIndex: Int): Int { var current = startIndex // Incorrect scheme position is used to identify the first position at which the character is not allowed in the // scheme or the part of the scheme. This number is reported in the exception message. var incorrectSchemePosition = -1 val firstChar = urlString[current] if (firstChar !in 'a'..'z' && firstChar !in 'A'..'Z') { incorrectSchemePosition = current } while (current < endIndex) { val char = urlString[current] // Character ':' means the end of the scheme and at this point the length of the scheme should be returned or // the exception should be thrown in case the scheme contains illegal characters. if (char == ':') { if (incorrectSchemePosition != -1) { throw IllegalArgumentException("Illegal character in scheme at position $incorrectSchemePosition") } return current - startIndex } // If character '/' or '?' or '#' found this is not a scheme. if (char == '/' || char == '?' || char == '#') return -1 // Update incorrect scheme position is current char is illegal. if (incorrectSchemePosition == -1 && char !in 'a'..'z' && char !in 'A'..'Z' && char !in '0'..'9' && char != '.' && char != '+' && char != '-' ) { incorrectSchemePosition = current } ++current } return -1 } private fun count(urlString: String, startIndex: Int, endIndex: Int, char: Char): Int { var result = 0 while (startIndex + result < endIndex) { if (urlString[startIndex + result] != char) break result++ } return result } private fun String.indexOfColonInHostPort(startIndex: Int, endIndex: Int): Int { var skip = false for (index in startIndex until endIndex) { when (this[index]) { '[' -> skip = true ']' -> skip = false ':' -> if (!skip) return index } } return -1 } private fun Char.isLetter(): Boolean = lowercaseChar() in 'a'..'z'
apache-2.0
cf6644f5dfc05c38c8288b064ffa9c25
31.965649
118
0.61526
4.636071
false
false
false
false
airbnb/lottie-android
sample-compose/src/main/java/com/airbnb/lottie/sample/compose/examples/TextExamplesPage.kt
1
3014
package com.airbnb.lottie.sample.compose.examples import android.graphics.Typeface import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.verticalScroll import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Modifier import androidx.compose.ui.platform.LocalContext import com.airbnb.lottie.LottieProperty import com.airbnb.lottie.compose.LottieAnimation import com.airbnb.lottie.compose.LottieCompositionSpec import com.airbnb.lottie.compose.rememberLottieComposition import com.airbnb.lottie.compose.rememberLottieDynamicProperties import com.airbnb.lottie.compose.rememberLottieDynamicProperty import com.airbnb.lottie.sample.compose.R import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext @Composable fun TextExamplesPage() { UsageExamplePageScaffold { Column( modifier = Modifier .fillMaxWidth() .verticalScroll(rememberScrollState()) ) { ExampleCard("Default", "Loading fonts using default asset paths") { Example1() } ExampleCard("Dynamic Properties", "Replace fonts with custom typefaces") { Example2() } } } } @Composable private fun Example1() { // Lottie will automatically look for fonts in src/main/assets/fonts. // It will find font files based on the font family specified in the Lottie Json file. // You can specify a different assets subfolder by using the fontAssetsFolder parameter. // By default, it will look for ttf files. // You can specify a different file extension by using the fontFileExtension parameter. val composition by rememberLottieComposition(LottieCompositionSpec.RawRes(R.raw.name)) LottieAnimation( composition, progress = { 0f }, ) } @Composable private fun Example2() { val composition by rememberLottieComposition(LottieCompositionSpec.RawRes(R.raw.name)) val typeface = rememberTypeface("fonts/Roboto.ttf") val dynamicProperties = rememberLottieDynamicProperties( rememberLottieDynamicProperty(LottieProperty.TYPEFACE, typeface, "NAME") ) LottieAnimation( composition, progress = { 0f }, dynamicProperties = dynamicProperties, ) } @Composable private fun rememberTypeface(path: String): Typeface? { var typeface: Typeface? by remember { mutableStateOf(null) } val context = LocalContext.current LaunchedEffect(path) { typeface = null withContext(Dispatchers.IO) { typeface = Typeface.createFromAsset(context.assets, "fonts/Roboto.ttf") } } return typeface }
apache-2.0
52607000f9e664aa211b07e5c4676977
34.892857
92
0.740212
4.845659
false
false
false
false
code-disaster/lwjgl3
modules/generator/src/main/kotlin/org/lwjgl/generator/JNI.kt
4
12520
/* * Copyright LWJGL. All rights reserved. * License terms: https://www.lwjgl.org/license */ package org.lwjgl.generator import java.io.* import java.util.concurrent.* /** Deduplicates JNI signatures from bindings and generates the org.lwjgl.system.JNI class. */ object JNI : GeneratorTargetNative(Module.CORE, "JNI") { private val signatures = ConcurrentHashMap<Signature, Unit>() private val signaturesArray = ConcurrentHashMap<SignatureArray, Unit>() init { // Force generation of signatures that are not used by any binding, but are required for // bootstrapping or other internal functionality. // invokePPV(NSView, setWantsBestResolutionOpenGLSurface, true/false, objc_msgSend); signatures[Signature(CallingConvention.DEFAULT, void, listOf(opaque_p, opaque_p, bool))] = Unit } private val sortedSignatures by lazy(LazyThreadSafetyMode.NONE) { signatures.keys.sorted() } private val sortedSignaturesArray by lazy(LazyThreadSafetyMode.NONE) { signaturesArray.keys.sorted() } internal fun register(function: Func) = signatures.put(Signature(function), Unit) internal fun registerArray(function: Func) = signaturesArray.put(SignatureArray(function), Unit) internal fun register(function: CallbackFunction) = signatures.put(Signature(function), Unit) init { documentation = """ This class contains native methods that can be used to call dynamically loaded functions. It is used internally by the LWJGL bindings, but can also be used to call other dynamically loaded functions. Not all possible signatures are available, only those needed by the LWJGL bindings. To call a function that does not have a matching JNI method, {@link org.lwjgl.system.libffi.LibFFI LibFFI} can used. All JNI methods in this class take an extra parameter, called {@code $FUNCTION_ADDRESS}. This must be a valid pointer to a native function with a matching signature. Due to overloading, method names are partially mangled: ${ul( """ {@code call} or {@code invoke} Methods with the {@code invoke} prefix will invoke the native function with the default calling convention. Methods with the {@code call} prefix will invoke the native function with the {@code __stdcall} calling convention on Windows and the default calling convention on other systems. """, """ a {@code J} or a {@code P} for each {@code long} parameter {@code J} parameters represent 64-bit integer values. {@code P} parameters represent pointer addresses. A pointer address is a 32-bit value on 32-bit architectures and a 64-bit value on 64-bit architectures. """, """ the return value <a href="http://docs.oracle.com/javase/8/docs/technotes/guides/jni/spec/types.html\#type_signatures">JNI type signature</a> """ )} """ javaImport("javax.annotation.*") } override fun PrintWriter.generateJava() { generateJavaPreamble() print("""public final class JNI { static { Library.initialize(); } private JNI() {} // Pointer API """) sortedSignatures.forEach { print("${t}public static native ${it.returnType.nativeMethodType} ${it.signature}(") if (it.arguments.isNotEmpty()) print(it.arguments.asSequence() .mapIndexed { i, param -> "${param.nativeMethodType} param$i" } .joinToString(", ", postfix = ", ")) println("long $FUNCTION_ADDRESS);") } println("\n$t// Array API\n") sortedSignaturesArray.forEach { print("${t}public static native ${it.returnType.nativeMethodType} ${it.signature}(") if (it.arguments.isNotEmpty()) print(it.arguments.asSequence() .mapIndexed { i, param -> if (param is ArrayType<*>) "@Nullable ${param.mapping.primitive}[] param$i" else "${param.nativeMethodType} param$i" } .joinToString(", ", postfix = ", ")) println("long $FUNCTION_ADDRESS);") } println("\n}") } private val NativeType.nativeType get() = if (this.isPointer) "uintptr_t" else if (this.mapping == PrimitiveMapping.CLONG) "long" else this.jniFunctionType private val NativeType.jniFunctionTypeArray get() = if (this is ArrayType<*>) "j${this.mapping.primitive}Array" else this.jniFunctionType override fun PrintWriter.generateNative() { nativeDirective(""" #ifdef LWJGL_WINDOWS #define APIENTRY __stdcall #else #define APIENTRY #endif """) print(HEADER) preamble.printNative(this) sortedSignatures.forEach { print("JNIEXPORT ${it.returnType.jniFunctionType} JNICALL Java_org_lwjgl_system_JNI_${it.signatureNative}(JNIEnv *$JNIENV, jclass clazz, ") if (it.arguments.isNotEmpty()) print(it.arguments.asSequence() .mapIndexed { i, param -> "${param.jniFunctionType} param$i" } .joinToString(", ", postfix = ", ")) print("""jlong $FUNCTION_ADDRESS) { UNUSED_PARAMS($JNIENV, clazz) """) if (it.returnType.mapping !== TypeMapping.VOID) { print("return ") if (it.returnType.isPointer || it.returnType.mapping === PrimitiveMapping.CLONG) print("(jlong)") } print("((${it.returnType.nativeType} (${if (it.callingConvention === CallingConvention.STDCALL) "APIENTRY " else ""}*) ") print(it.arguments.asSequence() .joinToString(", ", prefix = "(", postfix = ")") { arg -> arg.nativeType }) print(")(uintptr_t)$FUNCTION_ADDRESS)(") print(it.arguments.asSequence() .mapIndexed { i, param -> if (param.isPointer) "(uintptr_t)param$i" else if (param.mapping === PrimitiveMapping.CLONG) "(long)param$i" else "param$i" } .joinToString(", ")) print("""); } """) } println() sortedSignaturesArray.forEach { print( """JNIEXPORT ${it.returnType.jniFunctionType} JNICALL Java_org_lwjgl_system_JNI_${it.signatureArray}(JNIEnv *$JNIENV, jclass clazz, ${ if (it.arguments.isEmpty()) "" else it.arguments .mapIndexed { i, param -> "${param.jniFunctionTypeArray} param$i" } .joinToString(", ") }, jlong $FUNCTION_ADDRESS) { UNUSED_PARAMS($JNIENV, clazz) ${it.arguments.asSequence() .mapIndexedNotNull { i, type -> if (type !is ArrayType<*>) null else "void *paramArray$i = param$i == NULL ? NULL : (*$JNIENV)->Get${type.mapping.box}ArrayElements($JNIENV, param$i, NULL);" } .joinToString("\n$t")} """) if (it.returnType.mapping !== TypeMapping.VOID) { print("${it.returnType.jniFunctionType} $RESULT = ") if (it.returnType.isPointer || it.returnType.mapping === PrimitiveMapping.CLONG) print("(jlong)") } print("((${it.returnType.nativeType} (${if (it.callingConvention === CallingConvention.STDCALL) "APIENTRY " else ""}*) ") print(it.arguments.asSequence() .joinToString(", ", prefix = "(", postfix = ")") { arg -> arg.nativeType }) print(")(uintptr_t)$FUNCTION_ADDRESS)(") print(it.arguments.asSequence() .mapIndexed { i, param -> if (param is ArrayType<*>) "(uintptr_t)paramArray$i" else if (param.isPointer) "(uintptr_t)param$i" else if (param.mapping === PrimitiveMapping.CLONG) "(long)param$i" else "param$i" } .joinToString(", ")) println("""); ${it.arguments.asSequence() .withIndex() .sortedByDescending { (index) -> index } .mapNotNull { (index, type) -> if (type !is ArrayType<*>) null else "if (param$index != NULL) { (*$JNIENV)->Release${type.mapping.box}ArrayElements($JNIENV, param$index, paramArray$index, 0); }" } .joinToString("\n$t")}${if (it.returnType.mapping === TypeMapping.VOID) "" else """ return $RESULT;"""} }""") } println("\nEXTERN_C_EXIT") } } private open class Signature constructor( val callingConvention: CallingConvention, val returnType: NativeType, val arguments: List<NativeType> ) : Comparable<Signature> { val key = "${callingConvention.method}${arguments.asSequence().joinToString("") { it.jniSignature }}${returnType.jniSignature}" val signature = "${callingConvention.method}${arguments.asSequence().joinToString("") { it.jniSignatureJava }}${returnType.jniSignature}" val signatureNative = "${signature}__${arguments.asSequence().joinToString("") { it.jniSignatureStrict }}J" constructor(function: Func) : this( function.nativeClass.callingConvention, function.returns.nativeType, function.parameters.asSequence() .filter { it !== EXPLICIT_FUNCTION_ADDRESS } .map { it.nativeType } .toList() ) constructor(function: CallbackFunction) : this( function.module.callingConvention, function.returns, function.signature.asSequence() .map { it.nativeType } .toList() ) override fun equals(other: Any?) = other is Signature && this.signatureNative == other.signatureNative override fun hashCode(): Int = signatureNative.hashCode() override fun compareTo(other: Signature): Int { this.callingConvention.ordinal.compareTo(other.callingConvention.ordinal).let { if (it != 0) return it } this.returnType.jniSignature.compareTo(other.returnType.jniSignature).let { if (it != 0) return it } val javaSignature0 = this.arguments.asSequence().joinToString("") { it.jniSignatureJava } val javaSignature1 = other.arguments.asSequence().joinToString("") { it.jniSignatureJava } javaSignature0.length.compareTo(javaSignature1.length).let { if (it != 0) return it } this.arguments.size.compareTo(other.arguments.size).let { if (it != 0) return it } javaSignature0.compareTo(javaSignature1).let { if (it != 0) return it } return this.signatureNative.compareTo(other.signatureNative) } } private class SignatureArray constructor( callingConvention: CallingConvention, returnType: NativeType, arguments: List<NativeType> ) : Signature(callingConvention, returnType, arguments) { val signatureArray = "${signature}__${arguments.asSequence().joinToString("") { if (it is ArrayType<*>) it.jniSignatureArray else it.jniSignatureStrict }}J" constructor(function: Func) : this( function.nativeClass.callingConvention, function.returns.nativeType, function.parameters.asSequence() .filter { it !== EXPLICIT_FUNCTION_ADDRESS } .map { it.nativeType } .toList() ) override fun equals(other: Any?) = other is SignatureArray && this.signatureArray == other.signatureArray override fun hashCode(): Int = signatureArray.hashCode() override fun compareTo(other: Signature): Int { this.callingConvention.ordinal.compareTo(other.callingConvention.ordinal).let { if (it != 0) return it } this.returnType.jniSignature.compareTo(other.returnType.jniSignature).let { if (it != 0) return it } val javaSignature0 = this.arguments.asSequence().joinToString("") { it.jniSignatureJava } val javaSignature1 = other.arguments.asSequence().joinToString("") { it.jniSignatureJava } javaSignature0.length.compareTo(javaSignature1.length).let { if (it != 0) return it } this.arguments.size.compareTo(other.arguments.size).let { if (it != 0) return it } javaSignature0.compareTo(javaSignature1).let { if (it != 0) return it } return this.signatureArray.compareTo((other as SignatureArray).signatureArray) } }
bsd-3-clause
4107eabb844b1f12ca6e78b20dbb955a
42.627178
199
0.613339
4.652546
false
false
false
false
dahlstrom-g/intellij-community
platform/lang-impl/src/com/intellij/openapi/roots/impl/DumpWatchedRootsAction.kt
7
2012
// 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.openapi.roots.impl import com.intellij.openapi.actionSystem.ActionUpdateThread import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.project.DumbAwareAction import com.intellij.openapi.project.Project import com.intellij.openapi.project.ProjectManager import com.intellij.openapi.roots.ProjectRootManager import com.intellij.openapi.ui.popup.JBPopupFactory import com.intellij.openapi.ui.popup.util.BaseListPopupStep import com.intellij.openapi.util.text.StringUtil import com.intellij.util.containers.MultiMap internal class DumpWatchedRootsAction : DumbAwareAction() { @Suppress("HardCodedStringLiteral") override fun actionPerformed(e: AnActionEvent) { val projects = ProjectManager.getInstance().openProjects val roots2Project = MultiMap<String, Project>() for (project in projects) { val roots = (ProjectRootManager.getInstance(project) as ProjectRootManagerComponent).rootsToWatch.map { it.rootPath } for (root in roots) { roots2Project.putValue(root, project) } } val roots = roots2Project.entrySet().map { Root(it.key, it.value.map { p -> p.name + "-" + p.locationHash }.sorted()) }.sortedBy { it.path } val baseListPopupStep = object : BaseListPopupStep<Root>("Registered Roots", roots) { override fun isSpeedSearchEnabled() = true override fun getTextFor(value: Root?): String { return "${StringUtil.shortenPathWithEllipsis("${value?.path}", 100)} (${value?.projects?.joinToString(separator = ",")})" } } val popup = JBPopupFactory.getInstance().createListPopup(baseListPopupStep) popup.showInBestPositionFor(e.dataContext) } override fun getActionUpdateThread(): ActionUpdateThread { return ActionUpdateThread.BGT } private data class Root(val path: String, val projects: List<String>) }
apache-2.0
5805e684656fccae1d4fa26f39df2c74
40.9375
140
0.752982
4.562358
false
false
false
false
dahlstrom-g/intellij-community
plugins/kotlin/uast/uast-kotlin-base/src/org/jetbrains/uast/kotlin/expressions/KotlinLocalFunctionULambdaExpression.kt
4
1482
// 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.uast.kotlin import com.intellij.psi.PsiType import org.jetbrains.annotations.ApiStatus import org.jetbrains.kotlin.psi.KtFunction import org.jetbrains.uast.* import org.jetbrains.uast.kotlin.psi.UastKotlinPsiParameter @ApiStatus.Internal class KotlinLocalFunctionULambdaExpression( override val sourcePsi: KtFunction, givenParent: UElement? ) : KotlinAbstractUExpression(givenParent), ULambdaExpression { override val functionalInterfaceType: PsiType? = null override val body by lz { sourcePsi.bodyExpression?.let { wrapExpressionBody(this, it) } ?: UastEmptyExpression(this) } override val valueParameters by lz { sourcePsi.valueParameters.mapIndexed { i, p -> KotlinUParameter(UastKotlinPsiParameter.create(p, sourcePsi, this, i), p, this) } } override fun asRenderString(): String { val renderedValueParameters = valueParameters.joinToString( prefix = "(", postfix = ")", transform = KotlinUParameter::asRenderString ) val expressions = (body as? UBlockExpression)?.expressions?.joinToString("\n") { it.asRenderString().withMargin } ?: body.asRenderString() return "fun $renderedValueParameters {\n${expressions.withMargin}\n}" } }
apache-2.0
73de3b8286828941c9dc8cc88c6d4dd3
38
158
0.709177
5.006757
false
false
false
false
dahlstrom-g/intellij-community
plugins/github/src/org/jetbrains/plugins/github/pullrequest/comment/ui/GHPRReviewThreadComponent.kt
4
13000
// 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.comment.ui import com.intellij.collaboration.async.CompletableFutureUtil.handleOnEdt import com.intellij.collaboration.async.CompletableFutureUtil.successOnEdt import com.intellij.collaboration.ui.SingleValueModel import com.intellij.collaboration.ui.codereview.InlineIconButton import com.intellij.collaboration.ui.codereview.ToggleableContainer import com.intellij.collaboration.ui.codereview.comment.RoundedPanel import com.intellij.icons.AllIcons import com.intellij.openapi.fileTypes.FileTypeRegistry import com.intellij.openapi.progress.EmptyProgressIndicator import com.intellij.openapi.project.Project import com.intellij.ui.ClickListener import com.intellij.ui.IdeBorderFactory import com.intellij.ui.SideBorder import com.intellij.ui.components.JBLabel import com.intellij.ui.components.labels.LinkLabel import com.intellij.ui.components.panels.HorizontalBox import com.intellij.ui.components.panels.NonOpaquePanel import com.intellij.ui.components.panels.VerticalLayout import com.intellij.ui.scale.JBUIScale import com.intellij.util.PathUtil import com.intellij.util.ui.JBUI import com.intellij.util.ui.UIUtil import net.miginfocom.layout.CC import net.miginfocom.layout.LC import net.miginfocom.swing.MigLayout import org.jetbrains.plugins.github.api.data.GHUser import org.jetbrains.plugins.github.api.data.pullrequest.GHPullRequestReviewCommentState import org.jetbrains.plugins.github.i18n.GithubBundle import org.jetbrains.plugins.github.pullrequest.data.provider.GHPRReviewDataProvider import org.jetbrains.plugins.github.pullrequest.ui.changes.GHPRSuggestedChangeHelper import org.jetbrains.plugins.github.pullrequest.ui.timeline.GHPRReviewThreadDiffComponentFactory import org.jetbrains.plugins.github.pullrequest.ui.timeline.GHPRSelectInToolWindowHelper import org.jetbrains.plugins.github.ui.avatars.GHAvatarIconsProvider import org.jetbrains.plugins.github.ui.util.GHUIUtil import java.awt.Cursor import java.awt.event.ActionListener import java.awt.event.MouseEvent import javax.swing.* import kotlin.properties.Delegates object GHPRReviewThreadComponent { fun create(project: Project, thread: GHPRReviewThreadModel, reviewDataProvider: GHPRReviewDataProvider, avatarIconsProvider: GHAvatarIconsProvider, suggestedChangeHelper: GHPRSuggestedChangeHelper, currentUser: GHUser): JComponent { val panel = JPanel(VerticalLayout(12)).apply { isOpaque = false } panel.add(GHPRReviewThreadCommentsPanel.create(thread, GHPRReviewCommentComponent.factory(project, thread, reviewDataProvider, avatarIconsProvider, suggestedChangeHelper))) if (reviewDataProvider.canComment()) { panel.add(getThreadActionsComponent(project, reviewDataProvider, thread, avatarIconsProvider, currentUser)) } return panel } fun createWithDiff(project: Project, thread: GHPRReviewThreadModel, reviewDataProvider: GHPRReviewDataProvider, avatarIconsProvider: GHAvatarIconsProvider, diffComponentFactory: GHPRReviewThreadDiffComponentFactory, selectInToolWindowHelper: GHPRSelectInToolWindowHelper, suggestedChangeHelper: GHPRSuggestedChangeHelper, currentUser: GHUser): JComponent { val collapseButton = InlineIconButton(AllIcons.General.CollapseComponent, AllIcons.General.CollapseComponentHover, tooltip = GithubBundle.message("pull.request.timeline.review.thread.collapse")) val expandButton = InlineIconButton(AllIcons.General.ExpandComponent, AllIcons.General.ExpandComponentHover, tooltip = GithubBundle.message("pull.request.timeline.review.thread.expand")) val contentPanel = RoundedPanel(VerticalLayout(4), 8).apply { isOpaque = false add(createFileName(thread, selectInToolWindowHelper, collapseButton, expandButton)) } val commentPanel = JPanel(VerticalLayout(4)).apply { isOpaque = false } object : CollapseController(thread, contentPanel, commentPanel, collapseButton, expandButton) { override fun createDiffAndCommentsPanels(): Pair<JComponent, JComponent> { val diffComponent = diffComponentFactory.createComponent(thread.diffHunk, thread.startLine).apply { border = IdeBorderFactory.createBorder(SideBorder.TOP) } val commentsComponent = JPanel(VerticalLayout(12)).apply { isOpaque = false val reviewCommentComponent = GHPRReviewCommentComponent.factory(project, thread, reviewDataProvider, avatarIconsProvider, suggestedChangeHelper, false) add(GHPRReviewThreadCommentsPanel.create(thread, reviewCommentComponent)) if (reviewDataProvider.canComment()) { add(getThreadActionsComponent(project, reviewDataProvider, thread, avatarIconsProvider, currentUser)) } } return diffComponent to commentsComponent } } return JPanel(VerticalLayout(4)).apply { isOpaque = false add(contentPanel) add(commentPanel) } } private abstract class CollapseController(private val thread: GHPRReviewThreadModel, private val contentPanel: JPanel, private val commentPanel: JPanel, private val collapseButton: InlineIconButton, private val expandButton: InlineIconButton) { private val collapseModel = SingleValueModel(true) private var childPanels by Delegates.observable<Pair<JComponent, JComponent>?>(null) { _, oldValue, newValue -> var revalidate = false if (oldValue != null) { contentPanel.remove(oldValue.first) commentPanel.remove(oldValue.second) revalidate = true } if (newValue != null) { contentPanel.add(newValue.first) commentPanel.add(newValue.second) } if (revalidate) { contentPanel.revalidate() commentPanel.revalidate() } else { contentPanel.validate() commentPanel.validate() } contentPanel.repaint() commentPanel.repaint() } init { collapseButton.actionListener = ActionListener { collapseModel.value = true } expandButton.actionListener = ActionListener { collapseModel.value = false } collapseModel.addListener { update() } thread.addAndInvokeStateChangeListener(::update) } private fun update() { val shouldBeVisible = !thread.isResolved || !collapseModel.value if (shouldBeVisible) { if (childPanels == null) { childPanels = createDiffAndCommentsPanels() } } else { childPanels = null } collapseButton.isVisible = thread.isResolved && !collapseModel.value expandButton.isVisible = thread.isResolved && collapseModel.value } abstract fun createDiffAndCommentsPanels(): Pair<JComponent, JComponent> } private fun createFileName(thread: GHPRReviewThreadModel, selectInToolWindowHelper: GHPRSelectInToolWindowHelper, collapseButton: InlineIconButton, expandButton: InlineIconButton): JComponent { val name = PathUtil.getFileName(thread.filePath) val path = PathUtil.getParentPath(thread.filePath) val fileType = FileTypeRegistry.getInstance().getFileTypeByFileName(name) val nameLabel = JLabel(name, fileType.icon, SwingConstants.LEFT).apply { cursor = Cursor.getPredefinedCursor(Cursor.HAND_CURSOR) object : ClickListener() { override fun onClick(event: MouseEvent, clickCount: Int): Boolean { selectInToolWindowHelper.selectChange(thread.commit?.oid, thread.filePath) return true } }.installOn(this) } val outdatedLabel = JBLabel(" ${GithubBundle.message("pull.request.review.thread.outdated")} ", UIUtil.ComponentStyle.SMALL).apply { foreground = UIUtil.getContextHelpForeground() background = UIUtil.getPanelBackground() }.andOpaque() val resolvedLabel = JBLabel(" ${GithubBundle.message("pull.request.review.comment.resolved")} ", UIUtil.ComponentStyle.SMALL).apply { foreground = UIUtil.getContextHelpForeground() background = UIUtil.getPanelBackground() }.andOpaque() thread.addAndInvokeStateChangeListener { outdatedLabel.isVisible = thread.isOutdated resolvedLabel.isVisible = thread.isResolved } return NonOpaquePanel(MigLayout(LC().insets("0").gridGap("${JBUIScale.scale(5)}", "0").fill().noGrid())).apply { border = JBUI.Borders.empty(10) add(nameLabel) if (!path.isBlank()) add(JLabel(path).apply { foreground = UIUtil.getContextHelpForeground() }) add(outdatedLabel, CC().hideMode(3)) add(resolvedLabel, CC().hideMode(3)) add(collapseButton, CC().hideMode(3)) add(expandButton, CC().hideMode(3)) } } private fun getThreadActionsComponent( project: Project, reviewDataProvider: GHPRReviewDataProvider, thread: GHPRReviewThreadModel, avatarIconsProvider: GHAvatarIconsProvider, currentUser: GHUser ): JComponent { val toggleModel = SingleValueModel(false) val textFieldModel = GHCommentTextFieldModel(project) { text -> reviewDataProvider.addComment(EmptyProgressIndicator(), thread.getElementAt(0).id, text).successOnEdt { thread.addComment(GHPRReviewCommentModel.convert(it)) toggleModel.value = false } } val toggleReplyLink = LinkLabel<Any>(GithubBundle.message("pull.request.review.thread.reply"), null) { _, _ -> toggleModel.value = true }.apply { isFocusable = true } val resolveLink = LinkLabel<Any>(GithubBundle.message("pull.request.review.thread.resolve"), null).apply { isFocusable = true }.also { it.setListener({ _, _ -> it.isEnabled = false reviewDataProvider.resolveThread(EmptyProgressIndicator(), thread.id).handleOnEdt { _, _ -> it.isEnabled = true } }, null) } val unresolveLink = LinkLabel<Any>(GithubBundle.message("pull.request.review.thread.unresolve"), null).apply { isFocusable = true }.also { it.setListener({ _, _ -> it.isEnabled = false reviewDataProvider.unresolveThread(EmptyProgressIndicator(), thread.id).handleOnEdt { _, _ -> it.isEnabled = true } }, null) } val content = ToggleableContainer.create( toggleModel, { createThreadActionsComponent(thread, toggleReplyLink, resolveLink, unresolveLink) }, { GHCommentTextFieldFactory(textFieldModel).create(avatarIconsProvider, currentUser, GithubBundle.message( "pull.request.review.thread.reply"), onCancel = { toggleModel.value = false }) } ) return JPanel().apply { isOpaque = false layout = MigLayout(LC().insets("0")) add(content, CC().width("${GHUIUtil.getPRTimelineWidth() + JBUIScale.scale(GHUIUtil.AVATAR_SIZE)}")) } } private fun createThreadActionsComponent(model: GHPRReviewThreadModel, toggleReplyLink: LinkLabel<Any>, resolveLink: LinkLabel<Any>, unresolveLink: LinkLabel<Any>): JComponent { fun update() { resolveLink.isVisible = model.state != GHPullRequestReviewCommentState.PENDING && !model.isResolved unresolveLink.isVisible = model.state != GHPullRequestReviewCommentState.PENDING && model.isResolved } model.addAndInvokeStateChangeListener(::update) return HorizontalBox().apply { isOpaque = false border = JBUI.Borders.empty(6, 34, 6, 0) add(toggleReplyLink) add(Box.createHorizontalStrut(JBUIScale.scale(8))) add(resolveLink) add(unresolveLink) } } }
apache-2.0
c36e3fb6fbc2b2fe54690e2d2c9e55aa
41.486928
140
0.660077
5.358615
false
false
false
false
hkokocin/androidKit
library/src/main/java/com/github/hkokocin/androidkit/app/Fragment.kt
1
1562
package com.github.hkokocin.androidkit.app import android.app.Activity import android.app.Fragment import android.content.Intent import android.content.res.Resources import com.github.hkokocin.androidkit.AndroidKit // ============================================================================== // resources // ============================================================================== inline fun <reified T : Any> Fragment.extra(name: String, default: T) = lazy { AndroidKit.instance.getExtra(activity.intent, name, T::class) ?: default } inline fun <reified T : Any> Fragment.resource(resourcesId: Int) = lazy { AndroidKit.instance.getResource(resources, resourcesId, T::class) } @Suppress("UNCHECKED_CAST") fun Fragment.colorResource(resourcesId: Int, theme: Resources.Theme? = null) = lazy { AndroidKit.instance.getColorInt(resources, resourcesId, theme) } @Suppress("UNCHECKED_CAST") fun Fragment.dimensionInPixels(resourcesId: Int) = lazy { AndroidKit.instance.dimensionInPixels(resources, resourcesId) } // ============================================================================== // intents // ============================================================================== inline fun <reified T : Activity> Fragment.start(noinline init: Intent.() -> Unit = {}) { AndroidKit.instance.start(activity, T::class, init) } inline fun <reified T : Activity> Fragment.startForResult(requestCode: Int, noinline init: Intent.() -> Unit = {}) { AndroidKit.instance.startForResult(activity, T::class, requestCode, init) }
mit
8186eb3d7fd04bd052a00181e20e01b1
37.097561
116
0.595391
4.553936
false
false
false
false
dahlstrom-g/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/MainFunctionReturnUnitInspection.kt
1
2914
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package org.jetbrains.kotlin.idea.inspections import com.intellij.codeInspection.LocalQuickFix import com.intellij.codeInspection.ProblemDescriptor import com.intellij.codeInspection.ProblemHighlightType import com.intellij.codeInspection.ProblemsHolder import com.intellij.openapi.project.Project import com.intellij.psi.PsiElementVisitor import org.jetbrains.kotlin.builtins.KotlinBuiltIns import org.jetbrains.kotlin.builtins.StandardNames import org.jetbrains.kotlin.descriptors.FunctionDescriptor import org.jetbrains.kotlin.idea.KotlinBundle import org.jetbrains.kotlin.idea.MainFunctionDetector import org.jetbrains.kotlin.idea.base.projectStructure.languageVersionSettings import org.jetbrains.kotlin.idea.caches.resolve.resolveToDescriptorIfAny import org.jetbrains.kotlin.idea.core.setType import org.jetbrains.kotlin.idea.search.usagesSearch.descriptor import org.jetbrains.kotlin.psi.KtNamedFunction import org.jetbrains.kotlin.psi.namedFunctionVisitor import org.jetbrains.kotlin.psi.psiUtil.getNonStrictParentOfType class MainFunctionReturnUnitInspection : AbstractKotlinInspection() { override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean): PsiElementVisitor { return namedFunctionVisitor(fun(function: KtNamedFunction) { if (function.name != "main") return val descriptor = function.descriptor as? FunctionDescriptor ?: return val mainFunctionDetector = MainFunctionDetector(function.languageVersionSettings) { it.resolveToDescriptorIfAny() } if (!mainFunctionDetector.isMain(descriptor, checkReturnType = false)) return if (descriptor.returnType?.let { KotlinBuiltIns.isUnit(it) } == true) return holder.registerProblem( function.nameIdentifier ?: function, KotlinBundle.message("0.should.return.unit", "main"), ProblemHighlightType.GENERIC_ERROR_OR_WARNING, ChangeMainFunctionReturnTypeToUnitFix(function.typeReference != null) ) }) } } private class ChangeMainFunctionReturnTypeToUnitFix(private val hasExplicitReturnType: Boolean) : LocalQuickFix { override fun getName() = if (hasExplicitReturnType) KotlinBundle.message("change.main.function.return.type.to.unit.fix.text2") else KotlinBundle.message("change.main.function.return.type.to.unit.fix.text") override fun getFamilyName() = name override fun applyFix(project: Project, descriptor: ProblemDescriptor) { val function = descriptor.psiElement.getNonStrictParentOfType<KtNamedFunction>() ?: return if (function.hasBlockBody()) { function.typeReference = null } else { function.setType(StandardNames.FqNames.unit.asString()) } } }
apache-2.0
08b5528a07762df55003676c6f8f499e
49.241379
127
0.761839
5.059028
false
false
false
false
ben-manes/gradle-versions-plugin
gradle-versions-plugin/src/main/kotlin/com/github/benmanes/gradle/versions/reporter/HtmlReporter.kt
1
15525
package com.github.benmanes.gradle.versions.reporter import com.github.benmanes.gradle.versions.reporter.result.Result import com.github.benmanes.gradle.versions.reporter.result.VersionAvailable import com.github.benmanes.gradle.versions.updates.gradle.GradleReleaseChannel.CURRENT import com.github.benmanes.gradle.versions.updates.gradle.GradleReleaseChannel.NIGHTLY import com.github.benmanes.gradle.versions.updates.gradle.GradleReleaseChannel.RELEASE_CANDIDATE import org.gradle.api.Project import java.io.OutputStream /** * A HTML reporter for the dependency updates results. */ class HtmlReporter( override val project: Project, override val revision: String, override val gradleReleaseChannel: String, ) : AbstractReporter(project, revision, gradleReleaseChannel) { override fun write(printStream: OutputStream, result: Result) { writeHeader(printStream) if (result.count == 0) { printStream.println("<P>No dependencies found.</P>") } else { writeUpToDate(printStream, result) writeExceedLatestFound(printStream, result) writeUpgrades(printStream, result) writeUndeclared(printStream, result) writeUnresolved(printStream, result) } writeGradleUpdates(printStream, result) } private fun writeHeader(printStream: OutputStream) { printStream.println(header.trimMargin()) } private fun writeUpToDate(printStream: OutputStream, result: Result) { val versions = result.current.dependencies if (versions.isNotEmpty()) { printStream.println("<H2>Current dependencies</H2>") printStream .println("<p>The following dependencies are using the latest $revision version:<p>") printStream.println("<table class=\"currentInfo\">") for (it in getCurrentRows(result)) { printStream.println(it) } printStream.println("</table>") printStream.println("<br>") } } private fun writeExceedLatestFound(printStream: OutputStream, result: Result) { val versions = result.exceeded.dependencies if (versions.isNotEmpty()) { // The following dependencies exceed the version found at the " // + revision + " revision level: printStream.println("<H2>Exceeded dependencies</H2>") printStream.println( "<p>The following dependencies exceed the version found at the $revision revision level:<p>" ) printStream.println("<table class=\"warningInfo\">") for (it in getExceededRows(result)) { printStream.println(it) } printStream.println("</table>") printStream.println("<br>") } } private fun writeUpgrades(printStream: OutputStream, result: Result) { val versions = result.outdated.dependencies if (versions.isNotEmpty()) { printStream.println("<H2>Later dependencies</H2>") printStream.println("<p>The following dependencies have later $revision versions:<p>") printStream.println("<table class=\"warningInfo\">") for (it in getUpgradesRows(result)) { printStream.println(it) } printStream.println("</table>") printStream.println("<br>") } } private fun writeUndeclared(printStream: OutputStream, result: Result) { val versions = result.undeclared.dependencies if (versions.isNotEmpty()) { printStream.println("<H2>Undeclared dependencies</H2>") printStream.println( "<p>Failed to compare versions for the following dependencies because they were declared without version:<p>" ) printStream.println("<table class=\"warningInfo\">") for (row in getUndeclaredRows(result)) { printStream.println(row) } printStream.println("</table>") printStream.println("<br>") } } private fun writeUnresolved(printStream: OutputStream, result: Result) { val versions = result.unresolved.dependencies if (versions.isNotEmpty()) { printStream.println("<H2>Unresolved dependencies</H2>") printStream .println("<p>Failed to determine the latest version for the following dependencies:<p>") printStream.println("<table class=\"warningInfo\">") for (it in getUnresolvedRows(result)) { printStream.println(it) } printStream.println("</table>") printStream.println("<br>") } } private fun writeGradleUpdates(printStream: OutputStream, result: Result) { if (!result.gradle.enabled) { return } printStream.println("<H2>Gradle $gradleReleaseChannel updates</H2>") printStream.println("Gradle $gradleReleaseChannel updates:") // Log Gradle update checking failures. if (result.gradle.current.isFailure) { printStream.println( "<P>[ERROR] [release channel: ${CURRENT.id}] " + result.gradle.current.reason + "</P>" ) } if ((gradleReleaseChannel == RELEASE_CANDIDATE.id || gradleReleaseChannel == NIGHTLY.id) && result.gradle.releaseCandidate.isFailure ) { printStream.println( "<P>[ERROR] [release channel: ${RELEASE_CANDIDATE.id}] " + result .gradle.releaseCandidate.reason + "</P>" ) } if (gradleReleaseChannel == NIGHTLY.id && result.gradle.nightly.isFailure) { printStream.println( "<P>[ERROR] [release channel: ${NIGHTLY.id}] " + result.gradle.nightly.reason + "</P>" ) } // print Gradle updates in breadcrumb format printStream.print("<P>Gradle: [" + getGradleVersionUrl(result.gradle.running.version)) var updatePrinted = false if (result.gradle.current.isUpdateAvailable && result.gradle.current > result.gradle.running) { updatePrinted = true printStream.print(" -> " + getGradleVersionUrl(result.gradle.current.version)) } if ((gradleReleaseChannel == RELEASE_CANDIDATE.id || gradleReleaseChannel == NIGHTLY.id) && result.gradle.releaseCandidate.isUpdateAvailable && result.gradle.releaseCandidate > result.gradle.current ) { updatePrinted = true printStream.print(" -> " + getGradleVersionUrl(result.gradle.releaseCandidate.version)) } if (gradleReleaseChannel == NIGHTLY.id && result.gradle.nightly.isUpdateAvailable && result.gradle.nightly > result.gradle.current ) { updatePrinted = true printStream.print(" -> " + getGradleVersionUrl(result.gradle.nightly.version)) } if (!updatePrinted) { printStream.print(": UP-TO-DATE") } printStream.println("]<P>") printStream.println(getGradleUrl()) } private fun getUpgradesRows(result: Result): List<String> { val rows = mutableListOf<String>() val list = result.outdated rows.add( "<tr class=\"header\"><th colspan=\"5\"><b>Later dependencies<span>(Click to collapse)</span></b></th></tr>" ) rows.add( "<tr><td><b>Name</b></td><td><b>Group</b></td><td><b>URL</b></td><td><b>Current Version</b></td><td><b>Latest Version</b></td><td><b>Reason</b></td></tr>" ) for (dependency in list.dependencies) { val rowStringFmt = "<tr><td>%s</td><td>%s</td><td>%s</td><td>%s</td><td>%s</td><td>%s</td></tr>" val rowString = String.format( rowStringFmt, dependency.name.orEmpty(), dependency.group.orEmpty(), getUrlString(dependency.projectUrl), getVersionString(dependency.group.orEmpty(), dependency.name.orEmpty(), dependency.version), getVersionString( dependency.group.orEmpty(), dependency.name.orEmpty(), getDisplayableVersion(dependency.available) ), dependency.userReason.orEmpty() ) rows.add(rowString) } return rows } private fun getDisplayableVersion(versionAvailable: VersionAvailable): String? { if (revision.equals("milestone", ignoreCase = true)) { return versionAvailable.milestone } else if (revision.equals("release", ignoreCase = true)) { return versionAvailable.release } else if (revision.equals("integration", ignoreCase = true)) { return versionAvailable.integration } return "" } override fun getFileExtension(): String { return "html" } companion object { private const val header = """ <!DOCTYPE html> <HEAD><TITLE>Project Dependency Updates Report</TITLE></HEAD> <style type=\"text/css\"> .body { font:100% verdana, arial, sans-serif; background-color:#fff } .currentInfo { border-collapse: collapse; } .currentInfo header { cursor:pointer; padding: 12px 15px; } .currentInfo td { border: 1px solid black; padding: 12px 15px; border-collapse: collapse; } .currentInfo tr:nth-child(even) { background-color: #E4FFB7; padding: 12px 15px; border-collapse: collapse; } .currentInfo tr:nth-child(odd) { background-color: #EFFFD2; padding: 12px 15px; border-collapse: collapse; } .warningInfo { border-collapse: collapse; } .warningInfo header { cursor:pointer; padding: 12px 15px; } .warningInfo td { border: 1px solid black; padding: 12px 15px; border-collapse: collapse; } .warningInfo tr:nth-child(even) { background-color: #FFFF66; padding: 12px 15px; border-collapse: collapse; } .warningInfo tr:nth-child(odd) { background-color: #FFFFCC; padding: 12px 15px; border-collapse: collapse; } </style> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js\"></script> <script type="text/javascript"> \$(document).ready(function(){ /* set current to collapsed initially */ \$('#currentId').nextUntil('tr.header').slideToggle(100, function(){}); /* click callback to toggle tables */ \$('tr.header').click(function(){ \$(this).find('span').text(function(_, value){return value=='(Click to collapse)'?'(Click to expand)':'(Click to collapse)'}); \$(this).nextUntil('tr.header').slideToggle(100, function(){ }); }); }); </script> """ private fun getCurrentRows(result: Result): List<String> { val rows = mutableListOf<String>() // The following dependencies are using the latest milestone version: val list = result.current rows.add( "<tr class=\"header\" id = \"currentId\" ><th colspan=\"4\"><b>Current dependencies<span>(Click to expand)</span></b></th></tr>" ) rows.add( "<tr><td><b>Name</b></td><td><b>Group</b></td><td><b>URL</b></td><td><b>Current Version</b></td><td><b>Reason</b></td></tr>" ) for (dependency in list.dependencies) { val rowStringFmt = "<tr><td>%s</td><td>%s</td><td>%s</td><td>%s</td><td>%s</td></tr>" val rowString = String.format( rowStringFmt, dependency.name, dependency.group, getUrlString(dependency.projectUrl), // TODO nullness getVersionString( dependency.group.orEmpty(), dependency.name.orEmpty(), dependency.version ), dependency.userReason.orEmpty() ) rows.add(rowString) } return rows } private fun getExceededRows(result: Result): List<String> { val rows = mutableListOf<String>() // The following dependencies are using the latest milestone version: val list = result.exceeded rows.add( "<tr class=\"header\"><th colspan=\"5\"><b>Exceeded dependencies<span>(Click to collapse)</span></b></th></tr>" ) rows.add( "<tr><td><b>Name</b></td><td><b>Group</b></td><td><b>URL</b></td><td><b>Current Version</b></td><td><b>Latest Version</b></td><td><b>Reason</b></td></tr>" ) for (dependency in list.dependencies) { val rowStringFmt = "<tr><td>%s</td><td>%s</td><td>%s</td><td>%s</td><td>%s</td><td>%s</td></tr>" val rowString = String.format( rowStringFmt, dependency.name, dependency.group, getUrlString(dependency.projectUrl), getVersionString( dependency.group.orEmpty(), dependency.name.orEmpty(), dependency.version ), getVersionString( dependency.group.orEmpty(), dependency.name.orEmpty(), dependency.version ), dependency.userReason.orEmpty() ) rows.add(rowString) } return rows } private fun getUndeclaredRows(result: Result): List<String> { val rows = mutableListOf<String>() rows.add( "<tr class=\"header\"><th colspan=\"2\"><b>Undeclared dependencies<span>(Click to collapse)</span></b></th></tr>" ) rows.add("<tr><td><b>Name</b></td><td><b>Group</b></td></tr>") for (dependency in result.undeclared.dependencies) { val rowString = String.format("<tr><td>%s</td><td>%s</td></tr>", dependency.name, dependency.group) rows.add(rowString) } return rows } private fun getUnresolvedRows(result: Result): List<String> { val rows = mutableListOf<String>() val list = result.unresolved rows.add( "<tr class=\"header\"><th colspan=\"4\"><b>Unresolved dependencies<span>(Click to collapse)</span></b></th></tr>" ) rows.add( "<tr><td><b>Name</b></td><td><b>Group</b></td><td><b>URL</b></td><td><b>Current Version</b></td><td>Reason</td></tr>" ) for (dependency in list.dependencies) { val rowStringFmt = "<tr><td>%s</td><td>%s</td><td>%s</td><td>%s</td><td>%s</td></tr>" val rowString = String.format( rowStringFmt, dependency.name, dependency.group, getUrlString(dependency.projectUrl), getVersionString( dependency.group.orEmpty(), dependency.name.orEmpty(), dependency.version ), dependency.userReason.orEmpty() ) rows.add(rowString) } return rows } private fun getGradleUrl(): String { return "<P>For information about Gradle releases click <a target=\"_blank\" href=\"https://gradle.org/releases/\">here</a>." } private fun getGradleVersionUrl(version: String?): String { if (version == null) { return "https://gradle.org/releases/" } return String .format( "<a target=\"_blank\" href=\"https://docs.gradle.org/%s/release-notes.html\">%s</a>", version, version ) } private fun getUrlString(url: String?): String { if (url == null) { return "" } return String.format("<a target=\"_blank\" href=\"%s\">%s</a>", url, url) } private fun getVersionString(group: String, name: String, version: String?): String { val mvn = getMvnVersionString(group, name, version) return String.format("%s %s", version, mvn) } private fun getMvnVersionString(group: String, name: String, version: String?): String { // https://search.maven.org/artifact/com.azure/azure-core-http-netty/1.5.4 if (version == null) { return "" } val versionUrl = String .format("https://search.maven.org/artifact/%s/%s/%s/bundle", group, name, version) return String.format("<a target=\"_blank\" href=\"%s\">%s</a>", versionUrl, "Sonatype") } } }
apache-2.0
d4744b06e3c108388d1d4006e1724f14
35.273364
162
0.621192
4.10823
false
false
false
false