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
kibotu/AndroidBase
app/src/main/kotlin/net/kibotu/base/ui/BaseFragment.kt
1
4846
package net.kibotu.base.ui import android.os.Bundle import android.support.annotation.CallSuper import android.support.annotation.ColorRes import android.support.v4.app.Fragment import android.support.v4.app.FragmentManager import android.view.LayoutInflater import android.view.MotionEvent import android.view.View import android.view.ViewGroup import butterknife.ButterKnife import butterknife.Unbinder import com.common.android.utils.extensions.FragmentExtensions.currentFragment import com.common.android.utils.extensions.ViewExtensions.changeStatusBarColorRes import com.common.android.utils.extensions.ViewExtensions.hideOnLostFocus import com.common.android.utils.interfaces.Backpress import com.common.android.utils.interfaces.DispatchTouchEvent import com.common.android.utils.interfaces.LogTag import com.common.android.utils.misc.UIDGenerator import net.kibotu.base.R /** * Created by jan.rabe on 19/07/16. * * * */ abstract class BaseFragment : Fragment(), LogTag, DispatchTouchEvent, Backpress, FragmentManager.OnBackStackChangedListener { private var unbinder: Unbinder? = null /** * [Restoring instance state after fragment transactions.](http://stackoverflow.com/a/15314508) */ private var savedState: Bundle? = null protected val uid = UIDGenerator.newUID() protected abstract val layout: Int @ColorRes open fun onEnterStatusBarColor(): Int { return R.color.primary } override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View? { val rootView = inflater!!.inflate(layout, container, false) unbinder = ButterKnife.bind(this, rootView) /** * If the Fragment was destroyed in between (screen rotation), we need to recover the savedState first. * However, if it was not, it stays in the instance from the last onDestroyView() and we don't want to overwrite it. */ if (savedInstanceState != null && savedState == null) { savedState = savedInstanceState.getBundle(tag()) } if (savedState != null) { onRestoreSavedState(savedState!!) } savedState = null return rootView } override fun onSaveInstanceState(outState: Bundle?) { /** * If onDestroyView() is called first, we can use the previously onSaveInstanceState but we can't call onSaveInstanceState() anymore * If onSaveInstanceState() is called first, we don't have onSaveInstanceState, so we need to call onSaveInstanceState() * => (?:) operator inevitable! */ outState!!.putBundle(tag(), if (savedState != null) savedState else onSaveInstanceState()) super.onSaveInstanceState(outState) } override fun onResume() { super.onResume() activity.supportFragmentManager.addOnBackStackChangedListener(this) changeStatusBarColorRes(onEnterStatusBarColor()) } override fun onPause() { super.onPause() activity.supportFragmentManager.removeOnBackStackChangedListener(this) } override fun onDestroyView() { savedState = onSaveInstanceState() super.onDestroyView() unbinder!!.unbind() } /** * Called either from [.onDestroyView] or [.onSaveInstanceState] */ @CallSuper protected fun onSaveInstanceState(): Bundle { // save state return Bundle() } /** * Called from [.onCreateView] * @param savedInstanceState */ protected fun onRestoreSavedState(savedInstanceState: Bundle) { // restore saved state } override fun dispatchTouchEvent(event: MotionEvent): Boolean { val views = viewsThatHideKeyboardWhenLostFocus() if (views != null) hideOnLostFocus(event, *views) return false } protected fun viewsThatHideKeyboardWhenLostFocus(): Array<View>? { return null } override fun onBackPressed(): Boolean { return false } override fun tag(): String { return javaClass.simpleName + "[" + uid + "]" } fun setArgument(bundle: Bundle): BaseFragment { arguments = bundle return this } /** * Returned to this fragment after BackStack changes. */ protected fun onActiveAfterBackStackChanged() { colorizeStatusBar() } protected fun colorizeStatusBar() { changeStatusBarColorRes(onEnterStatusBarColor()) } protected val isCurrentFragment: Boolean get() { val fragment = currentFragment() return fragment is BaseFragment && fragment.tag() == tag() } override fun onBackStackChanged() { if (isCurrentFragment) onActiveAfterBackStackChanged() } }
apache-2.0
3548706974a945b08de0e23e35a12208
28.919753
140
0.677672
5.047917
false
false
false
false
exercism/xkotlin
exercises/practice/robot-simulator/.meta/src/reference/kotlin/Robot.kt
1
1249
fun Orientation.turnLeft() = Orientation.values()[Math.floorMod(ordinal - 1, Orientation.values().size)] fun Orientation.turnRight() = Orientation.values()[Math.floorMod(ordinal + 1, Orientation.values().size)] class Robot(var gridPosition: GridPosition = GridPosition(0, 0), var orientation: Orientation = Orientation.NORTH) { private fun advance() { gridPosition = when (orientation) { Orientation.NORTH -> gridPosition.copy(y = gridPosition.y + 1) Orientation.EAST -> gridPosition.copy(x = gridPosition.x + 1) Orientation.SOUTH -> gridPosition.copy(y = gridPosition.y - 1) Orientation.WEST -> gridPosition.copy(x = gridPosition.x - 1) } } private fun turnLeft() { orientation = orientation.turnLeft() } private fun turnRight() { orientation = orientation.turnRight() } fun simulate(instructions: String) { for (instruction in instructions) { when (instruction) { 'A' -> advance() 'R' -> turnRight() 'L' -> turnLeft() else -> throw IllegalArgumentException(String.format("Invalid instruction: '%s'", instruction)) } } } }
mit
023a4d2636b20aee94d4b6b0980780f7
35.735294
116
0.604484
4.367133
false
false
false
false
genonbeta/TrebleShot
zxing/src/main/java/org/monora/android/codescanner/Utils.kt
1
14707
/* * MIT License * * Copyright (c) 2017 Yuriy Budiyev [[email protected]] * Copyright (c) 2021 Veli Tasalı [[email protected]] * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.monora.android.codescanner import android.content.Context import android.graphics.Rect import android.hardware.Camera import android.hardware.Camera.CameraInfo import android.hardware.Camera.Parameters.PREVIEW_FPS_MAX_INDEX import android.hardware.Camera.Parameters.PREVIEW_FPS_MIN_INDEX import android.view.Surface import android.view.WindowManager import com.google.zxing.BinaryBitmap import com.google.zxing.LuminanceSource import com.google.zxing.MultiFormatReader import com.google.zxing.NotFoundException import com.google.zxing.ReaderException import com.google.zxing.Result import com.google.zxing.common.HybridBinarizer import java.util.* import kotlin.math.max import kotlin.math.min import kotlin.math.roundToInt object Utils { private const val MIN_DISTORTION = 0.3f private const val MAX_DISTORTION = 3f private const val DISTORTION_STEP = 0.1f private const val MIN_PREVIEW_PIXELS = 589824 private const val MIN_FPS = 10000 private const val MAX_FPS = 30000 fun findSuitableImageSize( parameters: Camera.Parameters, frameWidth: Int, frameHeight: Int, ): CartesianCoordinate { val sizes = parameters.supportedPreviewSizes if (sizes != null && sizes.isNotEmpty()) { Collections.sort(sizes, CameraSizeComparator()) val frameRatio = frameWidth.toFloat() / frameHeight.toFloat() var distortion = MIN_DISTORTION while (distortion <= MAX_DISTORTION) { for (size in sizes) { val width = size.width val height = size.height if (width * height >= MIN_PREVIEW_PIXELS && Math.abs(frameRatio - width.toFloat() / height.toFloat()) <= distortion ) { return CartesianCoordinate(width, height) } } distortion += DISTORTION_STEP } } val defaultSize = parameters.previewSize ?: throw CodeScannerException("Unable to configure camera preview size") return CartesianCoordinate(defaultSize.width, defaultSize.height) } fun configureFpsRange(parameters: Camera.Parameters) { val supportedFpsRanges = parameters.supportedPreviewFpsRange if (supportedFpsRanges == null || supportedFpsRanges.isEmpty()) { return } Collections.sort(supportedFpsRanges, FpsRangeComparator()) for (fpsRange in supportedFpsRanges) { if (fpsRange[PREVIEW_FPS_MIN_INDEX] >= MIN_FPS && fpsRange[PREVIEW_FPS_MAX_INDEX] <= MAX_FPS ) { parameters.setPreviewFpsRange(fpsRange[PREVIEW_FPS_MIN_INDEX], fpsRange[PREVIEW_FPS_MAX_INDEX]) return } } } fun configureSceneMode(parameters: Camera.Parameters) { if (Camera.Parameters.SCENE_MODE_BARCODE != parameters.sceneMode) { val supportedSceneModes = parameters.supportedSceneModes if (supportedSceneModes != null && supportedSceneModes.contains(Camera.Parameters.SCENE_MODE_BARCODE) ) { parameters.sceneMode = Camera.Parameters.SCENE_MODE_BARCODE } } } fun configureFocusArea( parameters: Camera.Parameters, area: Rect, width: Int, height: Int, orientation: Int, ) { val areas: MutableList<Camera.Area> = ArrayList(1) val rotatedArea = area.rotate( -orientation.toFloat(), width / 2f, height / 2f ).bound(0, 0, width, height) areas.add(Camera.Area(Rect(mapCoordinate(rotatedArea.left, width), mapCoordinate(rotatedArea.top, height), mapCoordinate(rotatedArea.right, width), mapCoordinate(rotatedArea.bottom, height)), 1000)) if (parameters.maxNumFocusAreas > 0) { parameters.focusAreas = areas } if (parameters.maxNumMeteringAreas > 0) { parameters.meteringAreas = areas } } fun configureDefaultFocusArea( parameters: Camera.Parameters, frameRect: Rect, previewSize: CartesianCoordinate, viewSize: CartesianCoordinate, width: Int, height: Int, orientation: Int, ) { val portrait = isPortrait(orientation) val rotatedWidth = if (portrait) height else width val rotatedHeight = if (portrait) width else height configureFocusArea( parameters, getImageFrameRect(rotatedWidth, rotatedHeight, frameRect, previewSize, viewSize), rotatedWidth, rotatedHeight, orientation ) } fun configureDefaultFocusArea( parameters: Camera.Parameters, decoderWrapper: DecoderWrapper, frameRect: Rect, ) { val imageSize = decoderWrapper.imageSize configureDefaultFocusArea( parameters, frameRect, decoderWrapper.previewSize, decoderWrapper.viewSize, imageSize.x, imageSize.y, decoderWrapper.displayOrientation ) } fun configureFocusModeForTouch(parameters: Camera.Parameters) { if (Camera.Parameters.FOCUS_MODE_AUTO == parameters.focusMode) { return } val focusModes = parameters.supportedFocusModes if (focusModes != null && focusModes.contains(Camera.Parameters.FOCUS_MODE_AUTO)) { parameters.focusMode = Camera.Parameters.FOCUS_MODE_AUTO } } fun disableAutoFocus(parameters: Camera.Parameters) { val focusModes = parameters.supportedFocusModes if (focusModes == null || focusModes.isEmpty()) { return } val focusMode = parameters.focusMode if (focusModes.contains(Camera.Parameters.FOCUS_MODE_FIXED)) { if (Camera.Parameters.FOCUS_MODE_FIXED == focusMode) { return } else { parameters.focusMode = Camera.Parameters.FOCUS_MODE_FIXED return } } if (focusModes.contains(Camera.Parameters.FOCUS_MODE_AUTO)) { if (Camera.Parameters.FOCUS_MODE_AUTO != focusMode) { parameters.focusMode = Camera.Parameters.FOCUS_MODE_AUTO } } } fun setAutoFocusMode( parameters: Camera.Parameters, autoFocusMode: AutoFocusMode, ) { val focusModes = parameters.supportedFocusModes if (focusModes == null || focusModes.isEmpty()) { return } if (autoFocusMode === AutoFocusMode.CONTINUOUS) { if (Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE == parameters.focusMode) { return } if (focusModes.contains(Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE)) { parameters.focusMode = Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE return } } if (Camera.Parameters.FOCUS_MODE_AUTO == parameters.focusMode) { return } if (focusModes.contains(Camera.Parameters.FOCUS_MODE_AUTO)) { parameters.focusMode = Camera.Parameters.FOCUS_MODE_AUTO } } fun setFlashMode( parameters: Camera.Parameters, flashMode: String, ) { if (flashMode == parameters.flashMode) { return } val flashModes = parameters.supportedFlashModes if (flashModes != null && flashModes.contains(flashMode)) { parameters.flashMode = flashMode } } fun setZoom(parameters: Camera.Parameters, zoom: Int) { if (parameters.isZoomSupported) { if (parameters.zoom != zoom) { val maxZoom = parameters.maxZoom if (zoom <= maxZoom) { parameters.zoom = zoom } else { parameters.zoom = maxZoom } } } } fun getDisplayOrientation( context: Context, cameraInfo: CameraInfo, ): Int { val windowManager = context.getSystemService(Context.WINDOW_SERVICE) as WindowManager? ?: throw CodeScannerException("Unable to access window manager") val degrees: Int val rotation = windowManager.defaultDisplay.rotation degrees = when (rotation) { Surface.ROTATION_0 -> 0 Surface.ROTATION_90 -> 90 Surface.ROTATION_180 -> 180 Surface.ROTATION_270 -> 270 else -> if (rotation % 90 == 0) { (360 + rotation) % 360 } else { throw CodeScannerException("Invalid display rotation") } } return ((if (cameraInfo.facing == CameraInfo.CAMERA_FACING_FRONT) 180 else 360) + cameraInfo.orientation - degrees) % 360 } fun isPortrait(orientation: Int): Boolean { return orientation == 90 || orientation == 270 } fun getPreviewSize( imageWidth: Int, imageHeight: Int, frameWidth: Int, frameHeight: Int, ): CartesianCoordinate { if (imageWidth == frameWidth && imageHeight == frameHeight) { return CartesianCoordinate(frameWidth, frameHeight) } val resultWidth = imageWidth * frameHeight / imageHeight return if (resultWidth < frameWidth) { CartesianCoordinate(frameWidth, imageHeight * frameWidth / imageWidth) } else { CartesianCoordinate(resultWidth, frameHeight) } } fun getImageFrameRect( imageWidth: Int, imageHeight: Int, viewFrameRect: Rect, previewSize: CartesianCoordinate, viewSize: CartesianCoordinate, ): Rect { val previewWidth: Int = previewSize.x val previewHeight: Int = previewSize.y val viewWidth: Int = viewSize.x val viewHeight: Int = viewSize.y val wD = (previewWidth - viewWidth) / 2 val hD = (previewHeight - viewHeight) / 2 val wR = imageWidth.toFloat() / previewWidth.toFloat() val hR = imageHeight.toFloat() / previewHeight.toFloat() return Rect( max(((viewFrameRect.left + wD) * wR).roundToInt(), 0), max(((viewFrameRect.top + hD) * hR).roundToInt(), 0), min(((viewFrameRect.right + wD) * wR).roundToInt(), imageWidth), min(((viewFrameRect.bottom + hD) * hR).roundToInt(), imageHeight) ) } fun rotateYuv( source: ByteArray, width: Int, height: Int, rotation: Int, ): ByteArray { if (rotation == 0 || rotation == 360) return source require(!(rotation % 90 != 0 || rotation < 0 || rotation > 270)) { "Invalid rotation (valid: 0, 90, 180, 270)" } val output = ByteArray(source.size) val frameSize = width * height val swap = rotation % 180 != 0 val flipX = rotation % 270 != 0 val flipY = rotation >= 180 for (j in 0 until height) { for (i in 0 until width) { val yIn = j * width + i val uIn = frameSize + (j shr 1) * width + (i and 1.inv()) val vIn = uIn + 1 val wOut = if (swap) height else width val hOut = if (swap) width else height val iSwapped = if (swap) j else i val jSwapped = if (swap) i else j val iOut = if (flipX) wOut - iSwapped - 1 else iSwapped val jOut = if (flipY) hOut - jSwapped - 1 else jSwapped val yOut = jOut * wOut + iOut val uOut = frameSize + (jOut shr 1) * wOut + (iOut and 1.inv()) val vOut = uOut + 1 output[yOut] = (0xff and source[yIn].toInt()).toByte() output[uOut] = (0xff and source[uIn].toInt()).toByte() output[vOut] = (0xff and source[vIn].toInt()).toByte() } } return output } @Throws(ReaderException::class) fun decodeLuminanceSource( reader: MultiFormatReader, luminanceSource: LuminanceSource, ): Result? { return try { reader.decodeWithState(BinaryBitmap(HybridBinarizer(luminanceSource))) } catch (e: NotFoundException) { reader.decodeWithState( BinaryBitmap(HybridBinarizer(luminanceSource.invert()))) } finally { reader.reset() } } private fun mapCoordinate(value: Int, size: Int): Int { return 2000 * value / size - 1000 } class SuppressErrorCallback : ErrorCallback { override fun onError(error: Exception) { // Do nothing } } private class CameraSizeComparator : Comparator<Camera.Size> { override fun compare(a: Camera.Size, b: Camera.Size): Int { return (b.height * b.width).compareTo(a.height * a.width) } } private class FpsRangeComparator : Comparator<IntArray> { override fun compare(a: IntArray, b: IntArray): Int { var comparison = b[PREVIEW_FPS_MAX_INDEX].compareTo(a[PREVIEW_FPS_MAX_INDEX]) if (comparison == 0) { comparison = b[PREVIEW_FPS_MIN_INDEX].compareTo(a[PREVIEW_FPS_MIN_INDEX]) } return comparison } } }
gpl-2.0
8a7dddbacec39a649e8fc91028f52450
35.7675
107
0.604311
4.615819
false
false
false
false
code-helix/slatekit
src/apps/kotlin/slatekit-examples/src/main/kotlin/slatekit/examples/common/User.kt
1
2068
/** * <slate_header> * url: www.slatekit.com * git: www.github.com/code-helix/slatekit * org: www.codehelix.co * author: Kishore Reddy * copyright: 2016 CodeHelix Solutions Inc. * license: refer to website and/or github * about: A tool-kit, utility library and server-backend * mantra: Simplicity above all else * </slate_header> */ package slatekit.examples.common import slatekit.common.DateTime import slatekit.common.Field import slatekit.common.Id import slatekit.entities.EntityWithId data class User( override val id:Long = 0L, @property:Field(required = true, length = 30) val email:String = "", @property:Field(required = true, length = 30) val firstName:String = "", @property:Field(required = true, length =30) val lastName:String = "", @property:Field(required = true) val isMale:Boolean = false, @property:Field(required = true) val age:Int = 35 ) : EntityWithId<Long> { override fun isPersisted(): Boolean = id > 0 fun fullname():String = firstName + " " + lastName override fun toString():String { return "$email, $firstName, $lastName, $isMale, $age" } } data class User2( @property:Id() override val id:Long = 0L, @property:Field(length = 30) val email:String = "", @property:Field(length = 30) val first:String = "", @property:Field(length = 30) val last:String = "", @property:Field() val isMale:Boolean = false, @property:Field() val age:Int = 35, @property:Field() val active:Boolean = false, @property:Field() val salary:Double = 100.00, @property:Field() val registered:DateTime? = null ) : EntityWithId<Long> { override fun isPersisted(): Boolean = id > 0 fun fullname():String = first + " " + last override fun toString():String { return "$email, $first, $last, $isMale, $age" } }
apache-2.0
94a0e7f9e04e6efcdd1e7c8a28d97c27
20.112245
57
0.59236
3.931559
false
false
false
false
leafclick/intellij-community
platform/platform-impl/src/com/intellij/ide/actions/RecentLocationsDataModel.kt
1
12221
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.ide.actions import com.intellij.codeInsight.breadcrumbs.FileBreadcrumbsCollector import com.intellij.codeInsight.daemon.impl.DaemonCodeAnalyzerEx import com.intellij.ide.actions.RecentLocationsAction.getEmptyFileText import com.intellij.ide.ui.UISettings import com.intellij.lang.annotation.HighlightSeverity import com.intellij.openapi.editor.* import com.intellij.openapi.editor.colors.EditorColorsManager import com.intellij.openapi.editor.colors.EditorColorsScheme import com.intellij.openapi.editor.ex.EditorEx import com.intellij.openapi.editor.highlighter.EditorHighlighterFactory import com.intellij.openapi.editor.highlighter.LightHighlighterClient import com.intellij.openapi.editor.markup.HighlighterLayer import com.intellij.openapi.editor.markup.HighlighterTargetArea import com.intellij.openapi.fileEditor.ex.IdeDocumentHistory import com.intellij.openapi.fileEditor.impl.IdeDocumentHistoryImpl import com.intellij.openapi.fileEditor.impl.IdeDocumentHistoryImpl.RecentPlacesListener import com.intellij.openapi.project.Project import com.intellij.openapi.util.TextRange import com.intellij.openapi.util.registry.Registry import com.intellij.openapi.util.text.StringUtil import com.intellij.util.DocumentUtil import com.intellij.util.concurrency.SynchronizedClearableLazy import com.intellij.util.containers.ContainerUtil import java.util.* import java.util.stream.Collectors import javax.swing.ScrollPaneConstants data class RecentLocationsDataModel(val project: Project, val editorsToRelease: ArrayList<Editor> = arrayListOf()) { val projectConnection = project.messageBus.connect() init { projectConnection.subscribe(RecentPlacesListener.TOPIC, object : RecentPlacesListener { override fun recentPlaceAdded(changePlace: IdeDocumentHistoryImpl.PlaceInfo, isChanged: Boolean) = resetPlaces(isChanged) override fun recentPlaceRemoved(changePlace: IdeDocumentHistoryImpl.PlaceInfo, isChanged: Boolean) { resetPlaces(isChanged) } private fun resetPlaces(isChanged: Boolean) { if (isChanged) changedPlaces.drop() else navigationPlaces.drop() } }) } private val navigationPlaces: SynchronizedClearableLazy<List<RecentLocationItem>> = calculateItems(project, false) private val changedPlaces: SynchronizedClearableLazy<List<RecentLocationItem>> = calculateItems(project, true) private val navigationPlacesBreadcrumbsMap: Map<IdeDocumentHistoryImpl.PlaceInfo, String> by lazy { collectBreadcrumbs(project, navigationPlaces.value) } private val changedPlacedBreadcrumbsMap: Map<IdeDocumentHistoryImpl.PlaceInfo, String> by lazy { collectBreadcrumbs(project, changedPlaces.value) } fun getPlaces(changed: Boolean): List<RecentLocationItem> { return if (changed) changedPlaces.value else navigationPlaces.value } fun getBreadcrumbsMap(changed: Boolean): Map<IdeDocumentHistoryImpl.PlaceInfo, String> { return if (changed) changedPlacedBreadcrumbsMap else navigationPlacesBreadcrumbsMap } private fun collectBreadcrumbs(project: Project, items: List<RecentLocationItem>): Map<IdeDocumentHistoryImpl.PlaceInfo, String> { return items.stream() .map(RecentLocationItem::info) .collect(Collectors.toMap({ it }, { getBreadcrumbs(project, it) })) } private fun getBreadcrumbs(project: Project, placeInfo: IdeDocumentHistoryImpl.PlaceInfo): String { val rangeMarker = placeInfo.caretPosition val fileName = placeInfo.file.name if (rangeMarker == null) { return fileName } val collector = FileBreadcrumbsCollector.findBreadcrumbsCollector(project, placeInfo.file) ?: return fileName val crumbs = collector.computeCrumbs(placeInfo.file, rangeMarker.document, rangeMarker.startOffset, true) if (!crumbs.iterator().hasNext()) { return fileName } return crumbs.joinToString(" > ") { it.text } } private fun calculateItems(project: Project, changed: Boolean): SynchronizedClearableLazy<List<RecentLocationItem>> { return SynchronizedClearableLazy { val items = createPlaceLinePairs(project, changed) editorsToRelease.addAll(ContainerUtil.map(items) { item -> item.editor }) items } } private fun createPlaceLinePairs(project: Project, changed: Boolean): List<RecentLocationItem> { return getPlaces(project, changed) .mapNotNull { RecentLocationItem(createEditor(project, it) ?: return@mapNotNull null, it) } .take(UISettings.instance.recentLocationsLimit) } private fun getPlaces(project: Project, changed: Boolean): List<IdeDocumentHistoryImpl.PlaceInfo> { val infos = ContainerUtil.reverse( if (changed) IdeDocumentHistory.getInstance(project).changePlaces else IdeDocumentHistory.getInstance(project).backPlaces) val infosCopy = arrayListOf<IdeDocumentHistoryImpl.PlaceInfo>() for (info in infos) { if (infosCopy.stream().noneMatch { info1 -> IdeDocumentHistoryImpl.isSame(info, info1) }) { infosCopy.add(info) } } return infosCopy } private fun createEditor(project: Project, placeInfo: IdeDocumentHistoryImpl.PlaceInfo): EditorEx? { val positionOffset = placeInfo.caretPosition if (positionOffset == null || !positionOffset.isValid) { return null } assert(positionOffset.startOffset == positionOffset.endOffset) val fileDocument = positionOffset.document val lineNumber = fileDocument.getLineNumber(positionOffset.startOffset) val actualTextRange = getTrimmedRange(fileDocument, lineNumber) var documentText = fileDocument.getText(actualTextRange) if (actualTextRange.isEmpty) { documentText = getEmptyFileText() } val editorFactory = EditorFactory.getInstance() val editorDocument = editorFactory.createDocument(documentText) val editor = editorFactory.createEditor(editorDocument, project) as EditorEx val gutterComponentEx = editor.gutterComponentEx val linesShift = fileDocument.getLineNumber(actualTextRange.startOffset) gutterComponentEx.setLineNumberConverter(LineNumberConverter.Increasing { _, line -> line + linesShift }) gutterComponentEx.setPaintBackground(false) val scrollPane = editor.scrollPane scrollPane.horizontalScrollBarPolicy = ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER scrollPane.verticalScrollBarPolicy = ScrollPaneConstants.VERTICAL_SCROLLBAR_NEVER fillEditorSettings(editor.settings) setHighlighting(project, editor, fileDocument, placeInfo, actualTextRange) return editor } private fun fillEditorSettings(settings: EditorSettings) { settings.isLineNumbersShown = true settings.isCaretRowShown = false settings.isLineMarkerAreaShown = false settings.isFoldingOutlineShown = false settings.additionalColumnsCount = 0 settings.additionalLinesCount = 0 settings.isRightMarginShown = false settings.isUseSoftWraps = false settings.isAdditionalPageAtBottom = false } private fun setHighlighting(project: Project, editor: EditorEx, document: Document, placeInfo: IdeDocumentHistoryImpl.PlaceInfo, textRange: TextRange) { val colorsScheme = EditorColorsManager.getInstance().globalScheme applySyntaxHighlighting(project, editor, document, colorsScheme, textRange, placeInfo) applyHighlightingPasses(project, editor, document, colorsScheme, textRange) } private fun applySyntaxHighlighting(project: Project, editor: EditorEx, document: Document, colorsScheme: EditorColorsScheme, textRange: TextRange, placeInfo: IdeDocumentHistoryImpl.PlaceInfo) { val editorHighlighter = EditorHighlighterFactory.getInstance().createEditorHighlighter(placeInfo.file, colorsScheme, project) editorHighlighter.setEditor(LightHighlighterClient(document, project)) editorHighlighter.setText(document.getText(TextRange.create(0, textRange.endOffset))) val startOffset = textRange.startOffset val iterator = editorHighlighter.createIterator(startOffset) while (!iterator.atEnd() && iterator.end <= textRange.endOffset) { if (iterator.start >= startOffset) { editor.markupModel.addRangeHighlighter(iterator.start - startOffset, iterator.end - startOffset, HighlighterLayer.SYNTAX - 1, iterator.textAttributes, HighlighterTargetArea.EXACT_RANGE) } iterator.advance() } } private fun applyHighlightingPasses(project: Project, editor: EditorEx, document: Document, colorsScheme: EditorColorsScheme, rangeMarker: TextRange) { val startOffset = rangeMarker.startOffset val endOffset = rangeMarker.endOffset DaemonCodeAnalyzerEx.processHighlights(document, project, null, startOffset, endOffset) { info -> if (info.startOffset < startOffset || info.endOffset > endOffset) { return@processHighlights true } when (info.severity) { HighlightSeverity.ERROR, HighlightSeverity.WARNING, HighlightSeverity.WEAK_WARNING, HighlightSeverity.GENERIC_SERVER_ERROR_OR_WARNING -> return@processHighlights true } val textAttributes = if (info.forcedTextAttributes != null) info.forcedTextAttributes else colorsScheme.getAttributes(info.forcedTextAttributesKey) editor.markupModel.addRangeHighlighter( info.actualStartOffset - rangeMarker.startOffset, info.actualEndOffset - rangeMarker.startOffset, HighlighterLayer.SYNTAX, textAttributes, HighlighterTargetArea.EXACT_RANGE) true } } private fun getTrimmedRange(document: Document, lineNumber: Int): TextRange { val range = getLinesRange(document, lineNumber) val text = document.getText(TextRange.create(range.startOffset, range.endOffset)) val newLinesBefore = StringUtil.countNewLines( Objects.requireNonNull<String>(StringUtil.substringBefore(text, StringUtil.trimLeading(text)))) val newLinesAfter = StringUtil.countNewLines( Objects.requireNonNull<String>(StringUtil.substringAfter(text, StringUtil.trimTrailing(text)))) val firstLine = document.getLineNumber(range.startOffset) val firstLineAdjusted = firstLine + newLinesBefore val lastLine = document.getLineNumber(range.endOffset) val lastLineAdjusted = lastLine - newLinesAfter val startOffset = document.getLineStartOffset(firstLineAdjusted) val endOffset = document.getLineEndOffset(lastLineAdjusted) return TextRange.create(startOffset, endOffset) } private fun getLinesRange(document: Document, line: Int): TextRange { val lineCount = document.lineCount if (lineCount == 0) { return TextRange.EMPTY_RANGE } val beforeAfterLinesCount = Registry.intValue("recent.locations.lines.before.and.after", 2) val before = Math.min(beforeAfterLinesCount, line) val after = Math.min(beforeAfterLinesCount, lineCount - line) val linesBefore = before + beforeAfterLinesCount - after val linesAfter = after + beforeAfterLinesCount - before val startLine = Math.max(line - linesBefore, 0) val endLine = Math.min(line + linesAfter, lineCount - 1) val startOffset = document.getLineStartOffset(startLine) val endOffset = document.getLineEndOffset(endLine) return if (startOffset <= endOffset) TextRange.create(startOffset, endOffset) else TextRange.create(DocumentUtil.getLineTextRange(document, line)) } } data class RecentLocationItem(val editor: EditorEx, val info: IdeDocumentHistoryImpl.PlaceInfo)
apache-2.0
685ae19c2687583059f54f207a7fba8d
42.494662
140
0.733492
5.025082
false
false
false
false
JuliusKunze/kotlin-native
backend.native/tests/external/codegen/box/evaluate/minus.kt
2
1274
// TODO: muted automatically, investigate should it be ran for JS or not // IGNORE_BACKEND: JS, NATIVE // WITH_RUNTIME @Retention(AnnotationRetention.RUNTIME) annotation class Ann( val p1: Byte, val p2: Short, val p3: Int, val p4: Long, val p5: Double, val p6: Float ) val prop1: Byte = 1 - 1 val prop2: Short = 1 - 1 val prop3: Int = 1 - 1 val prop4: Long = 1 - 1 val prop5: Double = 1.0 - 1.0 val prop6: Float = 1.0.toFloat() - 1.0.toFloat() @Ann(1 - 1, 1 - 1, 1 - 1, 1 - 1, 1.0 - 1.0, 1.0.toFloat() - 1.0.toFloat()) class MyClass fun box(): String { val annotation = MyClass::class.java.getAnnotation(Ann::class.java)!! if (annotation.p1 != prop1) return "fail 1, expected = ${prop1}, actual = ${annotation.p1}" if (annotation.p2 != prop2) return "fail 2, expected = ${prop2}, actual = ${annotation.p2}" if (annotation.p3 != prop3) return "fail 3, expected = ${prop3}, actual = ${annotation.p3}" if (annotation.p4 != prop4) return "fail 4, expected = ${prop4}, actual = ${annotation.p4}" if (annotation.p5 != prop5) return "fail 5, expected = ${prop5}, actual = ${annotation.p5}" if (annotation.p6 != prop6) return "fail 6, expected = ${prop6}, actual = ${annotation.p6}" return "OK" }
apache-2.0
faf5a44c307b9952713f3712ec5a5814
36.470588
95
0.618524
3.040573
false
false
false
false
samirma/MeteoriteLandings
app/src/main/java/com/antonio/samir/meteoritelandingsspots/di/AppInjector.kt
1
3965
package com.antonio.samir.meteoritelandingsspots.di import android.content.Context import android.location.Geocoder import com.antonio.samir.meteoritelandingsspots.R import com.antonio.samir.meteoritelandingsspots.data.local.MeteoriteDaoFactory import com.antonio.samir.meteoritelandingsspots.data.local.MeteoriteLocalRepository import com.antonio.samir.meteoritelandingsspots.data.local.MeteoriteLocalRepositoryImpl import com.antonio.samir.meteoritelandingsspots.data.remote.MeteoriteRemoteRepository import com.antonio.samir.meteoritelandingsspots.data.remote.NasaNetworkService import com.antonio.samir.meteoritelandingsspots.data.remote.NasaServerEndPoint import com.antonio.samir.meteoritelandingsspots.data.repository.MeteoriteRepository import com.antonio.samir.meteoritelandingsspots.data.repository.MeteoriteRepositoryImpl import com.antonio.samir.meteoritelandingsspots.features.detail.MeteoriteDetailViewModel import com.antonio.samir.meteoritelandingsspots.features.list.MeteoriteListViewModel import com.antonio.samir.meteoritelandingsspots.service.AddressService import com.antonio.samir.meteoritelandingsspots.service.AddressServiceInterface import com.antonio.samir.meteoritelandingsspots.util.* import io.nodle.sdk.android.Nodle import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.FlowPreview import okhttp3.OkHttpClient import okhttp3.logging.HttpLoggingInterceptor import org.koin.android.ext.koin.androidContext import org.koin.androidx.viewmodel.dsl.viewModel import org.koin.dsl.module import retrofit2.Retrofit import retrofit2.converter.gson.GsonConverterFactory import java.util.concurrent.TimeUnit private val retrofit: Retrofit = Retrofit.Builder() .baseUrl(NasaServerEndPoint.URL) .addConverterFactory(GsonConverterFactory.create()) .client( OkHttpClient.Builder() .addInterceptor(run { val httpLoggingInterceptor = HttpLoggingInterceptor() httpLoggingInterceptor.apply { httpLoggingInterceptor.level = HttpLoggingInterceptor.Level.BODY } }) .readTimeout(30, TimeUnit.SECONDS) .writeTimeout(30, TimeUnit.SECONDS).build() ) .build() val localRepositoryModule = module { single<MeteoriteLocalRepository> { MeteoriteLocalRepositoryImpl(get(), get()) } } val networkModule = module { single { retrofit.create(NasaServerEndPoint::class.java) } single<NetworkUtilInterface> { NetworkUtil(get()) } single<MeteoriteRemoteRepository> { NasaNetworkService(get()) } } val databaseModule = module { single { MeteoriteDaoFactory.getMeteoriteDao(context = get()) } } @ExperimentalCoroutinesApi @FlowPreview val businessModule = module { single<DispatcherProvider> { DefaultDispatcherProvider() } single { Geocoder(get()) } single<GeoLocationUtilInterface> { GeoLocationUtil(get()) } single<GPSTrackerInterface> { GPSTracker(context = get()) } single<AddressServiceInterface> { AddressService(get(), get()) } single<MeteoriteRepository> { MeteoriteRepositoryImpl(get(), get(), get()) } single<MarketingInterface> { val context = get<Context>() val nodleKey = context.getString(R.string.nodle_key) MarketingImpl( context = context, nodleKey = nodleKey ).apply { init() setNodle(Nodle.Nodle()) } } } @ExperimentalCoroutinesApi @FlowPreview val viewModelModule = module { viewModel { MeteoriteDetailViewModel(get(), get()) } viewModel { MeteoriteListViewModel( stateHandle = get(), meteoriteRepository = get(), gpsTracker = get(), addressService = get(), dispatchers = get() ) } } @ExperimentalCoroutinesApi @FlowPreview val appModules = listOf(viewModelModule, localRepositoryModule, networkModule, databaseModule, businessModule)
mit
520edde401e332195387a4d5af0f24bb
37.134615
97
0.751828
4.859069
false
false
false
false
AndroidX/androidx
compose/ui/ui/samples/src/main/java/androidx/compose/ui/samples/SoftwareKeyboardControllerSample.kt
3
2769
/* * Copyright 2021 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.compose.ui.samples import androidx.annotation.Sampled import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.text.BasicTextField import androidx.compose.foundation.text.KeyboardActions import androidx.compose.foundation.text.KeyboardOptions import androidx.compose.material.Button import androidx.compose.material.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.ui.ExperimentalComposeUiApi import androidx.compose.ui.Modifier import androidx.compose.ui.focus.FocusRequester import androidx.compose.ui.focus.focusRequester import androidx.compose.ui.platform.LocalSoftwareKeyboardController import androidx.compose.ui.text.input.ImeAction import androidx.compose.ui.unit.dp @ExperimentalComposeUiApi @Sampled @Composable fun SoftwareKeyboardControllerSample() { val keyboardController = LocalSoftwareKeyboardController.current // used to ensure a TextField is focused when showing keyboard val focusRequester = remember { FocusRequester() } var (text, setText) = remember { mutableStateOf("Close keyboard on done ime action (blue ✔️)") } Column(Modifier.padding(16.dp)) { BasicTextField( text, setText, keyboardOptions = KeyboardOptions(imeAction = ImeAction.Done), keyboardActions = KeyboardActions( onDone = { keyboardController?.hide() } ), modifier = Modifier .focusRequester(focusRequester) .fillMaxWidth() ) Spacer(Modifier.height(16.dp)) Button( onClick = { focusRequester.requestFocus() keyboardController?.show() }, modifier = Modifier.fillMaxWidth() ) { Text("Show software keyboard.") } } }
apache-2.0
c7963afdd2ca959cc39032ecedc7fe53
35.88
75
0.727667
4.928699
false
false
false
false
pacmancoder/krayser
src/main/kotlin/org/krayser/core/GObjectManager.kt
1
813
package org.krayser.core import org.krayser.util.Vec3D class GObjectManager { private var objects: List<GObject> = listOf() fun addObject(obj: GObject) { objects += obj } fun intersect(ray: Ray): Pair<GObject, Vec3D>? { var robj: GObject? = null var rpoint: Vec3D? = null var minLen = 10000f for (obj in objects) { val point = obj.intersect(ray) if (point != null) { if ((point - ray.pos).len() < minLen) { robj = obj rpoint = point minLen = (point - ray.pos).len() } } } if (robj == null || rpoint == null) { return null } else { return Pair(robj, rpoint) } } }
mit
8695d29674dab582be66078e7ad36698
22.941176
55
0.466175
3.781395
false
false
false
false
smmribeiro/intellij-community
plugins/kotlin/j2k/old/src/org/jetbrains/kotlin/j2k/ConstructorConverter.kt
3
13453
// 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.j2k import com.intellij.psi.* import com.intellij.psi.util.PsiUtil import org.jetbrains.kotlin.j2k.ast.* class ConstructorConverter( private val psiClass: PsiClass, private val converter: Converter, private val fieldToPropertyInfo: (PsiField) -> PropertyInfo, private val overloadReducer: OverloadReducer ) { private val constructors = psiClass.constructors.asList() private val toTargetConstructorMap = buildToTargetConstructorMap() private val primaryConstructor: PsiMethod? = when (constructors.size) { 0 -> null 1 -> constructors.single() else -> choosePrimaryConstructor() } private fun choosePrimaryConstructor(): PsiMethod? { val candidates = constructors.filter { it !in toTargetConstructorMap } if (candidates.size != 1) return null // there should be only one constructor which does not call other constructor val primary = candidates.single() if (toTargetConstructorMap.values.any() { it != primary }) return null // all other constructors call our candidate (directly or indirectly) return primary } private fun buildToTargetConstructorMap(): Map<PsiMethod, PsiMethod> { val toTargetConstructorMap = HashMap<PsiMethod, PsiMethod>() for (constructor in constructors) { val firstStatement = constructor.body?.statements?.firstOrNull() val methodCall = (firstStatement as? PsiExpressionStatement)?.expression as? PsiMethodCallExpression if (methodCall != null) { val refExpr = methodCall.methodExpression if (refExpr.canonicalText == "this") { val target = refExpr.resolve() as? PsiMethod if (target != null && target.isConstructor) { val finalTarget = toTargetConstructorMap[target] ?: target toTargetConstructorMap[constructor] = finalTarget for (entry in toTargetConstructorMap.entries) { if (entry.value == constructor) { entry.setValue(finalTarget) } } } } } } return toTargetConstructorMap } var baseClassParams: List<DeferredElement<Expression>>? = if (constructors.isEmpty()) emptyList() else null private set fun convertConstructor(constructor: PsiMethod, annotations: Annotations, modifiers: Modifiers, fieldsToDrop: MutableSet<PsiField>, postProcessBody: (Block) -> Block): Constructor? { return if (constructor == primaryConstructor) { convertPrimaryConstructor(annotations, modifiers, fieldsToDrop, postProcessBody) } else { if (overloadReducer.shouldDropMethod(constructor)) return null val params = converter.convertParameterList(constructor, overloadReducer) val thisOrSuper = findThisOrSuperCall(constructor) val thisOrSuperDeferred = if (thisOrSuper != null) converter.deferredElement { it.convertExpression(thisOrSuper.expression) } else null fun convertBody(codeConverter: CodeConverter): Block { return postProcessBody(codeConverter.withSpecialExpressionConverter(object: SpecialExpressionConverter { override fun convertExpression(expression: PsiExpression, codeConverter: CodeConverter): Expression? { if (expression.isThisConstructorCall() || expression.isSuperConstructorCall()) { return Expression.Empty // skip it } return null } }).convertBlock(constructor.body)) } SecondaryConstructor(annotations, modifiers, params, converter.deferredElement(::convertBody), thisOrSuperDeferred) } } private fun findThisOrSuperCall(constructor: PsiMethod): PsiExpressionStatement? { val statement = constructor.body?.statements?.firstOrNull() as? PsiExpressionStatement ?: return null val methodCall = statement.expression as? PsiMethodCallExpression ?: return null val text = methodCall.methodExpression.text return if (text == "this" || text == "super") statement else null } private fun convertPrimaryConstructor(annotations: Annotations, modifiers: Modifiers, fieldsToDrop: MutableSet<PsiField>, postProcessBody: (Block) -> Block): PrimaryConstructor { val params = primaryConstructor!!.parameterList.parameters val parameterToField = HashMap<PsiParameter, Pair<PsiField, Type>>() val body = primaryConstructor.body val parameterUsageReplacementMap = HashMap<String, String>() val bodyGenerator: (CodeConverter) -> Block = if (body != null) { val statementsToRemove = HashSet<PsiStatement>() for (parameter in params) { val (field, initializationStatement) = findBackingFieldForConstructorParameter(parameter, primaryConstructor) ?: continue val fieldType = converter.typeConverter.convertVariableType(field) val parameterType = converter.typeConverter.convertVariableType(parameter) // types can be different only in nullability val type = if (fieldType == parameterType) { fieldType } else if (fieldType.toNotNullType() == parameterType.toNotNullType()) { if (fieldType.isNullable) fieldType else parameterType // prefer nullable one } else { continue } val propertyInfo = fieldToPropertyInfo(field) if (propertyInfo.needExplicitGetter || propertyInfo.needExplicitSetter) continue parameterToField.put(parameter, field to type) statementsToRemove.add(initializationStatement) fieldsToDrop.add(field) val fieldName = propertyInfo.name if (fieldName != parameter.name) { parameterUsageReplacementMap.put(parameter.name!!, fieldName) } } { codeConverter -> val bodyConverter = codeConverter.withSpecialExpressionConverter( object : ReplacingExpressionConverter(parameterUsageReplacementMap) { override fun convertExpression(expression: PsiExpression, codeConverter: CodeConverter): Expression? { if (expression.isSuperConstructorCall()) { return Expression.Empty // skip it } return super.convertExpression(expression, codeConverter) } }) postProcessBody(bodyConverter.convertBlock(body, false) { !statementsToRemove.contains(it) }) } } else { { Block.Empty } } // we need to replace renamed parameter usages in base class constructor arguments and in default values fun CodeConverter.correct() = withSpecialExpressionConverter(ReplacingExpressionConverter(parameterUsageReplacementMap)) val statement = primaryConstructor.body?.statements?.firstOrNull() val methodCall = (statement as? PsiExpressionStatement)?.expression as? PsiMethodCallExpression baseClassParams = if (methodCall != null && methodCall.isSuperConstructorCall()) { methodCall.argumentList.expressions.map { converter.deferredElement { codeConverter -> codeConverter.correct().convertExpression(it) } } } else { emptyList() } val parameterList = converter.convertParameterList( primaryConstructor, overloadReducer, { parameter, default -> if (!parameterToField.containsKey(parameter)) { converter.convertParameter(parameter, defaultValue = default) } else { val (field, type) = parameterToField[parameter]!! val propertyInfo = fieldToPropertyInfo(field) var paramAnnotations = converter.convertAnnotations(parameter, AnnotationUseTarget.Param) + converter.convertAnnotations(field, AnnotationUseTarget.Field) if (propertyInfo.getMethod != null) { paramAnnotations += converter.convertAnnotations(propertyInfo.getMethod, AnnotationUseTarget.Get) } if (propertyInfo.setMethod != null) { paramAnnotations += converter.convertAnnotations(propertyInfo.setMethod, AnnotationUseTarget.Set) } FunctionParameter( propertyInfo.identifier, type, if (propertyInfo.isVar) FunctionParameter.VarValModifier.Var else FunctionParameter.VarValModifier.Val, paramAnnotations, propertyInfo.modifiers, default ).assignPrototypes( PrototypeInfo(parameter, CommentsAndSpacesInheritance.LINE_BREAKS), PrototypeInfo(field, CommentsAndSpacesInheritance.NO_SPACES) ) } }, correctCodeConverter = { correct() }) return PrimaryConstructor(annotations, modifiers, parameterList, converter.deferredElement(bodyGenerator)).assignPrototype(primaryConstructor) } private fun findBackingFieldForConstructorParameter(parameter: PsiParameter, constructor: PsiMethod): Pair<PsiField, PsiStatement>? { val body = constructor.body ?: return null val refs = converter.referenceSearcher.findVariableUsages(parameter, body) if (refs.any { PsiUtil.isAccessedForWriting(it) }) return null for (ref in refs) { val assignment = ref.parent as? PsiAssignmentExpression ?: continue if (assignment.operationSign.tokenType != JavaTokenType.EQ) continue val assignee = assignment.lExpression as? PsiReferenceExpression ?: continue if (!assignee.isQualifierEmptyOrThis()) continue val field = assignee.resolve() as? PsiField ?: continue if (field.containingClass != constructor.containingClass) continue if (field.hasModifierProperty(PsiModifier.STATIC)) continue if (field.initializer != null) continue // assignment should be a top-level statement val statement = assignment.parent as? PsiExpressionStatement ?: continue if (statement.parent != body) continue // and no other assignments to field should exist in the constructor if (converter.referenceSearcher.findVariableUsages(field, body).any { it != assignee && PsiUtil.isAccessedForWriting(it) && it.isQualifierEmptyOrThis() }) continue //TODO: check access to field before assignment return field to statement } return null } private fun PsiExpression.isSuperConstructorCall() = (this as? PsiMethodCallExpression)?.methodExpression?.text == "super" private fun PsiExpression.isThisConstructorCall() = (this as? PsiMethodCallExpression)?.methodExpression?.text == "this" private inner open class ReplacingExpressionConverter(val parameterUsageReplacementMap: Map<String, String>) : SpecialExpressionConverter { override fun convertExpression(expression: PsiExpression, codeConverter: CodeConverter): Expression? { if (expression is PsiReferenceExpression && expression.qualifier == null) { val replacement = parameterUsageReplacementMap[expression.referenceName] if (replacement != null) { val target = expression.resolve() if (target is PsiParameter) { val scope = target.declarationScope // we do not check for exactly this constructor because default values reference parameters in other constructors if (scope is PsiMember && scope.isConstructor() && scope.parent == psiClass) { return Identifier(replacement, codeConverter.typeConverter.variableNullability(target).isNullable(codeConverter.settings)) } } } } return null } } }
apache-2.0
2dc6a0aa0c11b84c3504d6cd12fbc092
49.958333
175
0.603137
6.185287
false
false
false
false
google/intellij-community
plugins/kotlin/j2k/new/src/org/jetbrains/kotlin/nj2k/conversions/JavaAnnotationsConversion.kt
2
6448
// 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.nj2k.conversions import com.intellij.psi.search.GlobalSearchScope import com.intellij.psi.search.ProjectScope import org.jetbrains.kotlin.config.ApiVersion.Companion.KOTLIN_1_6 import org.jetbrains.kotlin.idea.stubindex.KotlinTopLevelTypeAliasFqNameIndex import org.jetbrains.kotlin.load.java.JvmAnnotationNames.* import org.jetbrains.kotlin.nj2k.NewJ2kConverterContext import org.jetbrains.kotlin.nj2k.tree.* import org.jetbrains.kotlin.utils.addToStdlib.safeAs import org.jetbrains.kotlin.utils.ifEmpty class JavaAnnotationsConversion(context: NewJ2kConverterContext) : RecursiveApplicableConversionBase(context) { override fun applyToElement(element: JKTreeElement): JKTreeElement { if (element !is JKAnnotationList) return recurse(element) element.annotations.forEach { when (it.classSymbol.fqName) { DEPRECATED_ANNOTATION.asString() -> it.convertDeprecatedAnnotation() TARGET_ANNOTATION.asString() -> it.convertTargetAnnotation() RETENTION_ANNOTATION.asString() -> it.convertRetentionAnnotation() REPEATABLE_ANNOTATION.asString() -> it.convertRepeatableAnnotation() DOCUMENTED_ANNOTATION.asString() -> it.convertDocumentedAnnotation() "java.lang.SuppressWarnings" -> { if (!it.convertSuppressAnnotation()) { element.annotations -= it } } } } return recurse(element) } private fun JKAnnotation.convertDeprecatedAnnotation() { classSymbol = symbolProvider.provideClassSymbol("kotlin.Deprecated") arguments = listOf(JKAnnotationParameterImpl(JKLiteralExpression("\"\"", JKLiteralExpression.LiteralType.STRING))) } private fun JKAnnotation.convertDocumentedAnnotation() { classSymbol = symbolProvider.provideClassSymbol("kotlin.annotation.MustBeDocumented") } private fun JKAnnotation.convertTargetAnnotation() { classSymbol = symbolProvider.provideClassSymbol("kotlin.annotation.Target") val javaTargets: List<JKAnnotationMemberValue> = arguments.singleOrNull()?.values() ?: return val kotlinTargets: List<JKFieldAccessExpression> = javaTargets.flatMap { target -> val javaFqName = target.fieldAccessFqName() ?: return val kotlinFqNames = targetMappings[javaFqName] ?: return kotlinFqNames.map { JKFieldAccessExpression(symbolProvider.provideFieldSymbol(it)) } } arguments = kotlinTargets.distinctBy { it.identifier.fqName }.map { JKAnnotationParameterImpl(it) } } private fun JKAnnotation.convertRetentionAnnotation() { classSymbol = symbolProvider.provideClassSymbol("kotlin.annotation.Retention") val javaRetention = arguments.singleOrNull()?.value ?: return val javaFqName = javaRetention.fieldAccessFqName() ?: return val kotlinFqName = retentionMappings[javaFqName] ?: return val kotlinRetention = JKAnnotationParameterImpl(JKFieldAccessExpression(symbolProvider.provideFieldSymbol(kotlinFqName))) arguments = listOf(kotlinRetention) } private fun JKAnnotation.convertRepeatableAnnotation() { if (moduleApiVersion < KOTLIN_1_6) return val jvmRepeatable = "kotlin.jvm.JvmRepeatable" KotlinTopLevelTypeAliasFqNameIndex .get( jvmRepeatable, context.project, context.converter.targetModule?.let { GlobalSearchScope.moduleWithLibrariesScope(it) } ?: ProjectScope.getLibrariesScope(context.project) ).ifEmpty { return } classSymbol = symbolProvider.provideClassSymbol(jvmRepeatable) } private fun JKAnnotation.convertSuppressAnnotation(): Boolean { val javaDiagnosticNames = arguments.singleOrNull()?.values() ?: return false val commonDiagnosticNames = javaDiagnosticNames.filter { it.safeAs<JKLiteralExpression>()?.literal?.trim('"') in commonDiagnosticNames } if (commonDiagnosticNames.isEmpty()) return false classSymbol = symbolProvider.provideClassSymbol("kotlin.Suppress") arguments = commonDiagnosticNames.map { JKAnnotationParameterImpl(it.copyTreeAndDetach()) } return true } private fun JKAnnotationParameter.values(): List<JKAnnotationMemberValue> = when (val value = value) { is JKKtAnnotationArrayInitializerExpression -> value.initializers else -> listOf(value) } private fun JKAnnotationMemberValue.fieldAccessFqName(): String? = (safeAs<JKQualifiedExpression>()?.selector ?: this) .safeAs<JKFieldAccessExpression>() ?.identifier ?.fqName companion object { private val commonDiagnosticNames: Set<String> = setOf( "deprecation", "unused", "SpellCheckingInspection", "HardCodedStringLiteral" ) private val targetMappings: Map<String, List<String>> = listOf( "ANNOTATION_TYPE" to listOf("ANNOTATION_CLASS"), "CONSTRUCTOR" to listOf("CONSTRUCTOR"), "FIELD" to listOf("FIELD"), "LOCAL_VARIABLE" to listOf("LOCAL_VARIABLE"), "METHOD" to listOf("FUNCTION", "PROPERTY_GETTER", "PROPERTY_SETTER"), "PACKAGE" to listOf("FILE"), "PARAMETER" to listOf("VALUE_PARAMETER"), "TYPE_PARAMETER" to listOf("TYPE_PARAMETER"), "TYPE" to listOf("CLASS"), "TYPE_USE" to listOf("CLASS", "TYPE", "TYPE_PARAMETER") ).associate { (java, kotlin) -> "java.lang.annotation.ElementType.$java" to kotlin.map { "kotlin.annotation.AnnotationTarget.$it" } } private val retentionMappings: Map<String, String> = listOf( "SOURCE" to "SOURCE", "CLASS" to "BINARY", "RUNTIME" to "RUNTIME", ).associate { (java, kotlin) -> "java.lang.annotation.RetentionPolicy.$java" to "kotlin.annotation.AnnotationRetention.$kotlin" } } }
apache-2.0
7fdf8783af4c0adaf938f578b0065abb
46.411765
129
0.656638
5.391304
false
false
false
false
cout970/Modeler
src/main/kotlin/com/cout970/modeler/core/helpers/DeletionHelper.kt
1
2639
package com.cout970.modeler.core.helpers import com.cout970.modeler.api.model.IModel import com.cout970.modeler.api.model.`object`.IObject import com.cout970.modeler.api.model.selection.* import com.cout970.modeler.core.model.`object`.Object import com.cout970.modeler.core.model.`object`.ObjectCube import com.cout970.modeler.core.model.mesh.Mesh import com.cout970.modeler.core.model.objects object DeletionHelper { fun delete(source: IModel, selection: ISelection): IModel { if (selection.selectionTarget != SelectionTarget.MODEL) return source return when (selection.selectionType) { SelectionType.OBJECT -> { source.removeObjects(selection.objects) } SelectionType.FACE -> { val toRemove = mutableListOf<IObjectRef>() val edited = mutableMapOf<IObjectRef, IObject>() source.objectMap.forEach { objIndex, obj -> if (obj is Object) { val modifyMesh = obj.mesh.let { val newFaces = it.faces.mapIndexedNotNull { index, iFaceIndex -> val ref = objIndex.toFaceRef(index) if (selection.isSelected(ref)) null else iFaceIndex } if (newFaces == it.faces) it else Mesh(it.pos, it.tex, newFaces) } if (modifyMesh.faces.isNotEmpty()) { edited += objIndex to obj.copy(mesh = modifyMesh) } else { toRemove += objIndex } } else if (obj is ObjectCube) { val modifyMesh = obj.mesh.let { val newFaces = it.faces.mapIndexedNotNull { index, iFaceIndex -> val ref = objIndex.toFaceRef(index) if (selection.isSelected(ref)) null else iFaceIndex } if (newFaces == it.faces) it else Mesh(it.pos, it.tex, newFaces) } if (modifyMesh.faces.isNotEmpty()) { edited += objIndex to obj.withMesh(modifyMesh) } else { toRemove += objIndex } } } source.modifyObjects(edited.keys) { ref, _ -> edited[ref]!! } } SelectionType.EDGE, SelectionType.VERTEX -> source } } }
gpl-3.0
5d5020d8433e3ef505f5d2acb92960c7
43
92
0.500189
5.045889
false
false
false
false
kohesive/kohesive-iac
model-aws/src/generated/kotlin/uy/kohesive/iac/model/aws/clients/DeferredAmazonElasticFileSystem.kt
1
2288
package uy.kohesive.iac.model.aws.clients import com.amazonaws.services.elasticfilesystem.AbstractAmazonElasticFileSystem import com.amazonaws.services.elasticfilesystem.AmazonElasticFileSystem import com.amazonaws.services.elasticfilesystem.model.* import uy.kohesive.iac.model.aws.IacContext import uy.kohesive.iac.model.aws.proxy.makeProxy open class BaseDeferredAmazonElasticFileSystem(val context: IacContext) : AbstractAmazonElasticFileSystem(), AmazonElasticFileSystem { override fun createFileSystem(request: CreateFileSystemRequest): CreateFileSystemResult { return with (context) { request.registerWithAutoName() makeProxy<CreateFileSystemRequest, CreateFileSystemResult>( context = this@with, sourceName = getNameStrict(request), requestObject = request, copyFromReq = mapOf( CreateFileSystemRequest::getCreationToken to CreateFileSystemResult::getCreationToken, CreateFileSystemRequest::getPerformanceMode to CreateFileSystemResult::getPerformanceMode ) ) } } override fun createMountTarget(request: CreateMountTargetRequest): CreateMountTargetResult { return with (context) { request.registerWithAutoName() makeProxy<CreateMountTargetRequest, CreateMountTargetResult>( context = this@with, sourceName = getNameStrict(request), requestObject = request, copyFromReq = mapOf( CreateMountTargetRequest::getFileSystemId to CreateMountTargetResult::getFileSystemId, CreateMountTargetRequest::getSubnetId to CreateMountTargetResult::getSubnetId, CreateMountTargetRequest::getIpAddress to CreateMountTargetResult::getIpAddress ) ) } } override fun createTags(request: CreateTagsRequest): CreateTagsResult { return with (context) { request.registerWithAutoName() CreateTagsResult().registerWithSameNameAs(request) } } } class DeferredAmazonElasticFileSystem(context: IacContext) : BaseDeferredAmazonElasticFileSystem(context)
mit
f191c3020d1ca2bec07f3bc3a35cfec7
43
134
0.686189
5.649383
false
false
false
false
fabmax/kool
kool-demo/src/commonMain/kotlin/de/fabmax/kool/demo/physics/terrain/PlayerController.kt
1
5059
package de.fabmax.kool.demo.physics.terrain import de.fabmax.kool.KoolContext import de.fabmax.kool.math.* import de.fabmax.kool.physics.RigidActor import de.fabmax.kool.physics.RigidDynamic import de.fabmax.kool.physics.character.* import de.fabmax.kool.scene.Scene import de.fabmax.kool.util.WalkAxes import kotlin.math.abs import kotlin.math.atan2 import kotlin.math.max class PlayerController(private val physicsObjects: PhysicsObjects, mainScene: Scene, ctx: KoolContext) : OnHitActorListener, HitActorBehaviorCallback { val controller: CharacterController private val charManager: CharacterControllerManager val position: Vec3d get() = controller.position var frontHeading = 0f var moveHeading = 0f private set var moveSpeed = 0f private set val playerTransform = Mat4d() private val axes: WalkAxes var pushForceFac = 0.75f private val tmpForce = MutableVec3f() private var bridgeSegment: RigidDynamic? = null private val bridgeHitPt = MutableVec3f() private val bridgeHitForce = MutableVec3f() private var bridgeHitTime = 0.0f val tractorGun = TractorGun(physicsObjects, mainScene) init { // create character controller charManager = CharacterControllerManager(physicsObjects.world) controller = charManager.createController() controller.onHitActorListeners += this controller.hitActorBehaviorCallback = this // create user input listener (wasd / cursor keys) axes = WalkAxes(ctx) } fun release(ctx: KoolContext) { // apparently character controller is released automatically when the scene is destroyed //controller.release() //charManager.release() axes.dispose(ctx) } fun onPhysicsUpdate(timeStep: Float) { updateMovement() tractorGun.onPhysicsUpdate(timeStep) bridgeSegment?.let { it.addForceAtPos(bridgeHitForce, bridgeHitPt, isLocalForce = false, isLocalPos = true) bridgeHitTime -= timeStep if (bridgeHitTime < 0f) { bridgeSegment = null } } } private fun updateMovement() { moveHeading = frontHeading val walkDir = Vec2f(-axes.leftRight, axes.forwardBackward) if (walkDir.length() > 0f) { moveHeading += atan2(walkDir.x, walkDir.y).toDeg() } val speedFactor = max(abs(axes.forwardBackward), abs(axes.leftRight)) val runFactor = 1f - axes.runFactor moveSpeed = walkSpeed * speedFactor if (runFactor > 0f) { moveSpeed = moveSpeed * (1f - runFactor) + runSpeed * speedFactor * runFactor controller.jumpSpeed = 6f } else { controller.jumpSpeed = 4f } if (axes.crouchFactor > 0f) { moveSpeed = moveSpeed * (1f - axes.crouchFactor) + crouchSpeed * speedFactor * axes.crouchFactor } // set controller.movement according to user input controller.movement.set(0f, 0f, -moveSpeed) controller.movement.rotate(moveHeading, Vec3f.Y_AXIS) controller.jump = axes.isJump playerTransform .setIdentity() .translate(position) .rotate(moveHeading.toDouble(), Vec3d.Y_AXIS) } override fun hitActorBehavior(actor: RigidActor): HitActorBehavior { return if (physicsObjects.chainBridge.isBridge(actor)) { HitActorBehavior.RIDE } else { HitActorBehavior.DEFAULT } } override fun onHitActor(actor: RigidActor, hitWorldPos: Vec3f, hitWorldNormal: Vec3f) { if (actor is RigidDynamic) { if (physicsObjects.chainBridge.isBridge(actor)) { updateBridgeForce(actor, hitWorldPos) } else { bridgeSegment = null applyBoxForce(actor, hitWorldPos, hitWorldNormal) } } } private fun updateBridgeForce(actor: RigidDynamic, hitWorldPos: Vec3f) { // apply some force (100 kg / 150 kg) to the bridge segment in straight down direction val force = if (axes.isRun) -1500f else -1000f bridgeHitForce.set(0f, force, 0f) // force is cached and applied in onPhysicsUpdate to reduce jitter actor.toLocal(bridgeHitPt.set(hitWorldPos)) bridgeHitPt.y = 0f bridgeHitPt.z = 0f bridgeSegment = actor bridgeHitTime = 0.2f } private fun applyBoxForce(actor: RigidDynamic, hitWorldPos: Vec3f, hitWorldNormal: Vec3f) { // apply some fixed force to the hit actor val force = if (axes.isRun) -4000f else -2000f tmpForce.set(hitWorldNormal).scale(force * pushForceFac) actor.addForceAtPos(tmpForce, hitWorldPos, isLocalForce = false, isLocalPos = false) } companion object { // movement speeds, tuned to roughly match the model animation speed const val walkSpeed = 1.3f const val crouchSpeed = 0.5f const val runSpeed = 5f } }
apache-2.0
8cc5d04b59542cae7b690a080504e142
33.189189
151
0.653093
4.143325
false
false
false
false
siosio/intellij-community
plugins/markdown/src/org/intellij/plugins/markdown/fileActions/utils/MarkdownFileEditorUtils.kt
9
2487
// 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.intellij.plugins.markdown.fileActions.utils import com.intellij.openapi.fileEditor.FileEditor import com.intellij.openapi.fileEditor.FileEditorManager import com.intellij.openapi.project.Project import com.intellij.openapi.vfs.VirtualFile import org.intellij.plugins.markdown.ui.preview.MarkdownEditorWithPreview import org.intellij.plugins.markdown.ui.preview.MarkdownPreviewFileEditor import org.intellij.plugins.markdown.ui.preview.MarkdownPreviewFileEditor.PREVIEW_BROWSER import org.jetbrains.annotations.ApiStatus @ApiStatus.Experimental object MarkdownFileEditorUtils { @JvmStatic fun findMarkdownPreviewEditor(editor: FileEditor): MarkdownPreviewFileEditor? { return when (editor) { is MarkdownEditorWithPreview -> editor.previewEditor as? MarkdownPreviewFileEditor is MarkdownPreviewFileEditor -> editor else -> editor.getUserData(MarkdownEditorWithPreview.PARENT_SPLIT_EDITOR_KEY)?.previewEditor as? MarkdownPreviewFileEditor } } @JvmStatic fun findMarkdownPreviewEditor(project: Project, file: VirtualFile, requireOpenedPreview: Boolean): MarkdownPreviewFileEditor? { val editor = findEditor(project, file, MarkdownFileEditorUtils::findMarkdownPreviewEditor) if (requireOpenedPreview && editor?.getUserData(PREVIEW_BROWSER) == null) { return null } return editor } @JvmStatic fun findMarkdownSplitEditor(editor: FileEditor): MarkdownEditorWithPreview? { return when (editor) { is MarkdownEditorWithPreview -> editor else -> editor.getUserData(MarkdownEditorWithPreview.PARENT_SPLIT_EDITOR_KEY) } } @JvmStatic fun findMarkdownSplitEditor(project: Project, file: VirtualFile): MarkdownEditorWithPreview? { return findEditor(project, file, ::findMarkdownSplitEditor) } private fun <T: FileEditor> findEditor(project: Project, file: VirtualFile, predicate: (FileEditor) -> T?): T? { val editorManager = FileEditorManager.getInstance(project) val selectedEditor = editorManager.getSelectedEditor(file)?.let(predicate) if (selectedEditor != null) { return selectedEditor } val editors = editorManager.getEditors(file) for (editor in editors) { val previewEditor = predicate.invoke(editor) if (previewEditor != null) { return previewEditor } } return null } }
apache-2.0
6ef52dfb33c1e20820eb2f6adcaa8ffa
39.770492
140
0.769602
4.701323
false
false
false
false
siosio/intellij-community
plugins/kotlin/gradle/gradle-idea/src/org/jetbrains/kotlin/idea/scripting/gradle/roots/GradleBuildRootIndex.kt
1
3618
// 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.scripting.gradle.roots import com.intellij.openapi.diagnostic.logger import com.intellij.openapi.project.Project import org.jetbrains.kotlin.idea.scripting.gradle.settings.StandaloneScriptsStorage class GradleBuildRootIndex(private val project: Project) : StandaloneScriptsUpdater { private val log = logger<GradleBuildRootIndex>() private inner class StandaloneScriptRootsCache { private val standaloneScripts: MutableSet<String> get() = StandaloneScriptsStorage.getInstance(project)?.files ?: hashSetOf() private val standaloneScriptRoots = mutableMapOf<String, GradleBuildRoot?>() init { standaloneScripts.forEach(::updateRootsCache) } fun all(): List<String> = standaloneScripts.toList() fun get(path: String): GradleBuildRoot? = standaloneScriptRoots[path] fun add(path: String) { standaloneScripts.add(path) updateRootsCache(path) } fun remove(path: String): GradleBuildRoot? { standaloneScripts.remove(path) return standaloneScriptRoots.remove(path) } fun updateRootsCache(path: String) { standaloneScriptRoots[path] = findNearestRoot(path) } } private val standaloneScriptRoots by lazy { StandaloneScriptRootsCache() } private val byWorkingDir = HashMap<String, GradleBuildRoot>() private val byProjectDir = HashMap<String, GradleBuildRoot>() val list: Collection<GradleBuildRoot> get() = byWorkingDir.values @Synchronized fun rebuildProjectRoots() { byProjectDir.clear() byWorkingDir.values.forEach { buildRoot -> buildRoot.projectRoots.forEach { byProjectDir[it] = buildRoot } } standaloneScriptRoots.all().forEach(standaloneScriptRoots::updateRootsCache) } @Synchronized fun getBuildByRootDir(dir: String) = byWorkingDir[dir] @Synchronized fun findNearestRoot(path: String): GradleBuildRoot? { var max: Pair<String, GradleBuildRoot>? = null byWorkingDir.entries.forEach { if (path.startsWith(it.key) && (max == null || it.key.length > max!!.first.length)) { max = it.key to it.value } } return max?.second } @Synchronized fun getBuildByProjectDir(projectDir: String) = byProjectDir[projectDir] @Synchronized fun isStandaloneScript(path: String) = path in standaloneScriptRoots.all() @Synchronized fun getStandaloneScriptRoot(path: String) = standaloneScriptRoots.get(path) @Synchronized fun add(value: GradleBuildRoot): GradleBuildRoot? { val prefix = value.pathPrefix val old = byWorkingDir.put(prefix, value) rebuildProjectRoots() log.info("$prefix: $old -> $value") return old } @Synchronized fun remove(prefix: String) = byWorkingDir.remove(prefix)?.also { rebuildProjectRoots() log.info("$prefix: removed") } @Synchronized override fun addStandaloneScript(path: String) { standaloneScriptRoots.add(path) } @Synchronized override fun removeStandaloneScript(path: String): GradleBuildRoot? { return standaloneScriptRoots.remove(path) } override val standaloneScripts: Collection<String> @Synchronized get() = standaloneScriptRoots.all() }
apache-2.0
94bd5a13dc8de7b86d013286c13b6c75
31.9
158
0.675235
4.741809
false
false
false
false
JetBrains/kotlin-native
runtime/src/main/kotlin/generated/_DigitChars.kt
1
1468
/* * Copyright 2010-2021 JetBrains s.r.o. and Kotlin Programming Language contributors. * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package kotlin.text // // NOTE: THIS FILE IS AUTO-GENERATED by the GenerateUnicodeData.kt // See: https://github.com/JetBrains/kotlin/tree/master/libraries/stdlib // // 37 ranges totally @SharedImmutable private val rangeStart = intArrayOf( 0x0030, 0x0660, 0x06f0, 0x07c0, 0x0966, 0x09e6, 0x0a66, 0x0ae6, 0x0b66, 0x0be6, 0x0c66, 0x0ce6, 0x0d66, 0x0de6, 0x0e50, 0x0ed0, 0x0f20, 0x1040, 0x1090, 0x17e0, 0x1810, 0x1946, 0x19d0, 0x1a80, 0x1a90, 0x1b50, 0x1bb0, 0x1c40, 0x1c50, 0xa620, 0xa8d0, 0xa900, 0xa9d0, 0xa9f0, 0xaa50, 0xabf0, 0xff10, ) internal fun binarySearchRange(array: IntArray, needle: Int): Int { var bottom = 0 var top = array.size - 1 var middle = -1 var value = 0 while (bottom <= top) { middle = (bottom + top) / 2 value = array[middle] if (needle > value) bottom = middle + 1 else if (needle == value) return middle else top = middle - 1 } return middle - (if (needle < value) 1 else 0) } /** * Returns `true` if this character is a digit. */ internal fun Char.isDigitImpl(): Boolean { val ch = this.toInt() val index = binarySearchRange(rangeStart, ch) val high = rangeStart[index] + 9 return ch <= high }
apache-2.0
737a2ef70d702b089f1a736df9a0e6b3
30.913043
164
0.656676
2.856031
false
false
false
false
Wicpar/ArtusLang
src/main/kotlin/com/artuslang/Processing.kt
1
22764
/* * Copyright 2018 - present Frederic Artus Nieto * * 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.artuslang import com.google.common.collect.Iterators import org.apache.commons.jexl3.JexlBuilder import org.apache.commons.jexl3.JexlContext import org.apache.commons.jexl3.internal.Closure import org.apache.commons.jexl3.introspection.JexlSandbox import org.apache.commons.lang.StringEscapeUtils import org.intellij.lang.annotations.Language import org.reflections.Reflections import org.reflections.scanners.SubTypesScanner import java.io.File import java.nio.Buffer import java.nio.ByteBuffer import java.nio.charset.Charset import kotlin.math.min /** * Created on 22/01/2018 by Frederic */ open class NamedType(val name: String) { override fun equals(other: Any?): Boolean { if (this === other) return true if (other !is NamedType) return false if (name != other.name) return false if (this.javaClass != other.javaClass) return false return true } override fun hashCode(): Int { return name.hashCode() } } data class ArtusLocation(val origin: String, val range: IntRange) class TokenType(name: String, val properties: HashMap<String, Any?>) : NamedType(name) data class Token(val location: ArtusLocation, val text: String, val type: TokenType) data class TokenMatcher(val type: TokenType, @Language("RegExp") val pattern: String, val group: Int = 1) { val regex = Regex("\\A($pattern)", setOf(RegexOption.MULTILINE, RegexOption.DOT_MATCHES_ALL, RegexOption.UNIX_LINES)) override fun toString(): String { return "TokenMatcher(type=$type, pattern='$pattern', group=$group)" } } class ContextMatcher(val matcher: TokenMatcher, val event: (Token, Context) -> Context) { override fun toString(): String { return "ContextMatcher(matcher=$matcher)" } } class ContextType(name: String, private val matchers: ArrayList<ContextMatcher>, private val parents: ArrayList<ContextType> = arrayListOf()) : NamedType(name) { private val parentStacks: ArrayList<LayeredIterable<ContextMatcher>> = ArrayList(parents.map { it.stack }) private val stack: LayeredIterable<ContextMatcher> = LayeredIterable(matchers, parentStacks) private val classTypes: HashSet<ContextType> = HashSet(parents.map { it.classTypes }.flatten() + this) private val stringTypes: HashSet<String> = HashSet(classTypes.map { it.name }) @JvmOverloads fun addParent(ctx: ContextType, idx: Int = 0) { val i = if (idx < 0) idx + matchers.size + 1 else idx parents.add(i, ctx) parentStacks.add(i, ctx.stack) classTypes.addAll(ctx.classTypes) stringTypes.addAll(ctx.stringTypes) } @JvmOverloads fun addMatcher(ctx: ContextMatcher, idx: Int = 0) { val i = if (idx < 0) idx + matchers.size + 1 else idx matchers.add(i, ctx) } fun getStack(): Iterable<ContextMatcher> { return stack } fun isType(contextType: ContextType): Boolean { return classTypes.contains(contextType) } fun isType(contextType: String): Boolean { return stringTypes.contains(contextType) } override fun toString(): String { return "ContextType(matchers=$matchers, parents=$parents)" } } class Context(val type: ContextType, val parent: Context? = null) { val children = HashMap<ContextType, ArrayList<Context>>() val properties = HashMap<String, Any?>() val tokens = ArrayList<Token>() init { if (parent != null) properties.putAll(parent.properties) } fun pushToken(token: Token) { tokens.add(token) parent?.pushToken(token) } fun child(contextType: ContextType): Context { val ctx = Context(contextType, this) children.getOrPut(contextType, { arrayListOf() }).add(ctx) return ctx } @JvmOverloads fun parent(type: ContextType, deep: Boolean = true): Context? { var parent = parent if (deep) { while (parent != null && !parent.type.isType(type)) parent = parent.parent } else { while (parent != null && parent.type != type) parent = parent.parent } return parent } @JvmOverloads fun parent(type: String, deep: Boolean = true): Context? { var parent = parent if (deep) { while (parent != null && !parent.type.isType(type)) parent = parent.parent } else { while (parent != null && parent.type.name != type) parent = parent.parent } return parent } override fun toString(): String { return "Context(type=$type, parent=$parent, children=$children, properties=$properties)" } } class ScriptContext : JexlContext, JexlContext.NamespaceResolver { private val fixedNamespaces = mapOf(Pair("this", this), Pair("lang", LangUtils(this)), Pair("log", Log)) private val namespaces = hashMapOf<String?, Any?>() private val map = hashMapOf<String?, Any?>() override fun has(name: String?): Boolean { return map.containsKey(name) } override fun get(name: String?): Any? { return map[name] } override fun set(name: String?, value: Any?) { if (value == null) map.remove(name) else map[name] = value } fun put(name: String, value: Any?): Any? { return if (value == null) map.remove(name) else map.put(name, value) } override fun resolveNamespace(name: String?): Any? { return fixedNamespaces[name] ?: namespaces[name] } fun registerNamespace(str: String, obj: Any?) { namespaces[str] = obj } } class LangUtils(private val ctx: ScriptContext) { @JvmOverloads fun tokenType(name: String, properties: HashMap<String, Any?> = HashMap()) = TokenType(name, properties) @JvmOverloads fun tokenMatcher(type: TokenType, @Language("RegExp") pattern: String, group: Int = 1) = TokenMatcher(type, pattern, group) fun contextMatcher(matcher: TokenMatcher, event: Closure) = ContextMatcher(matcher, { token, context -> val ret = event.execute(ctx, token, context) as? Context ret ?: context }) fun contextMatcherPush(matcher: TokenMatcher, type: ContextType) = ContextMatcher(matcher, { _, context -> context.child(type) }) fun contextMatcherPop(matcher: TokenMatcher) = ContextMatcher(matcher, { _, context -> context.parent!! }) fun contextMatcherPopWith(matcher: TokenMatcher, closure: Closure) = ContextMatcher(matcher, { token, context -> closure.execute(ctx, token, context) val ret = context.parent!! ret }) @JvmOverloads fun contextMatcherSwitch(matcher: TokenMatcher, type: ContextType, inherit: Boolean = true) = ContextMatcher(matcher, { _, context -> val ret = context.parent?.child(type) ?: Context(type) if (inherit) { ret.properties.putAll(context.properties) } ret }) @JvmOverloads fun contextMatcherSwitchWith(matcher: TokenMatcher, type: ContextType, closure: Closure, inherit: Boolean = true) = ContextMatcher(matcher, { token, context -> val ret = context.parent?.child(type) ?: Context(type) if (inherit) { ret.properties.putAll(context.properties) } closure.execute(ctx, token, context, ret) ret }) fun contextMatcherNop(matcher: TokenMatcher) = ContextMatcher(matcher, { _, context -> context }) @JvmOverloads fun contextType(name: String, matchers: ArrayList<ContextMatcher>, parents: ArrayList<ContextType> = ArrayList()) = ContextType(name, matchers, parents) fun context(type: ContextType) = Context(type) @JvmOverloads fun readFile(path: String, charset: String = Charset.defaultCharset().name()): ArtusReader { return FileArtusReader(File(path), charset) } fun writeFile(path: String, buffer: ByteBuffer) { val file = File(path) val dir = File(".") if (!file.canonicalPath.contains(dir.canonicalPath + File.separator)) { throw RuntimeException("illegal file access, only children of local folder allowed") } val arr = ByteArray(buffer.remaining()) buffer.get(arr) file.parentFile?.mkdirs() file.createNewFile() file.writeBytes(arr) } fun readString(str: String, name: String): ArtusReader { return StringArtusReader(str, name) } fun eval(code: String, vararg v: Pair<String, Any?>): Any? { val tmp = v.map { Pair(it.first, ctx.put(it.first, it.second)) } val ret = jexl.createScript(code).execute(ctx) tmp.forEach { ctx.put(it.first, it.second) } return ret } private val imported = HashMap<Pair<File, ContextType>, Context?>() private fun ctxFilePath(path: String): File { val ret = File(path).let { fs -> val fpath = (this.ctx.get("folder") as? String) if (!fs.isAbsolute && fpath != null) { val folder = File(fpath) folder.resolve(fs) } else { fs } }.canonicalFile return ret } /** * loads once in separate context, if recursion occurs it is ignored */ @JvmOverloads fun import(path: String, ctx: ContextType = (this.ctx.get("context") as Context).type, charset: String = Charset.defaultCharset().name()): Context { val fs = ctxFilePath(path) val access = Pair(fs, ctx) if (imported.containsKey(access)) imported[access]?.let { return it } else imported.put(access, null) val file = this.ctx.put("file", fs.path) val folder = this.ctx.put("folder", fs.parentFile.path) try { val ret = readFile(fs.path, charset).build(Context(ctx)) imported.put(access, ret) return ret } catch (t: Throwable) { System.err.println("error: $fs: $t") throw t } finally { this.ctx.put("file", file) this.ctx.put("folder", folder) } } /** * loads into specified context, useful for fragments */ @JvmOverloads fun include(path: String, ctx: Context = this.ctx.get("context") as Context, charset: String = Charset.defaultCharset().name()): Context { val fs = ctxFilePath(path) val file = this.ctx.put("file", fs.path) val folder = this.ctx.put("folder", fs.parentFile.path) try { return readFile(fs.path, charset).build(ctx) } catch (t: Throwable) { System.err.println("error: $fs: $t") throw t } finally { this.ctx.put("file", file) this.ctx.put("folder", folder) } } fun data() = Data() fun tree() = NDefTree() fun node(features: List<Any>, filters: List<Any>) = NDefTree.NDefNode(features.toHashSet(), filters.toHashSet()) fun genNode(features: List<Any>, filters: List<Any>, ordinal: Double, couldGen: Closure, gen: Closure) = object : NDefTree.NDefNodeGen(features.toHashSet(), filters.toHashSet(), ordinal) { override fun couldGen(elem: Any, features: List<Any>, filters: List<Any>): Boolean { return couldGen.execute(ctx, elem, features, filters) as Boolean? ?: false } override fun gen(elem: Any, features: List<Any>, filters: List<Any>): NDefTree.NDefNode? { return gen.execute(ctx, elem, features, filters) as? NDefTree.NDefNode } } fun nodeBuilder(fn: Closure): (Any, List<Any>, List<Any>) -> NDefTree.NDefNode? = { a, b, c -> fn.execute(ctx, a, b, c) as NDefTree.NDefNode? } @JvmOverloads fun pathOf(path: List<Any>, features: List<Any> = kotlin.collections.listOf(), filters: List<Any> = kotlin.collections.listOf()) = NDefPath(path, features, filters) /** * easy constructors for allowed types */ fun listOf(vararg any: Any?) = listOf<Any?>(*any) fun arrayListOf(vararg any: Any?) = arrayListOf<Any?>(*any) fun mapOf(vararg any: Pair<Any?, Any?>) = mapOf<Any?, Any?>(*any) fun hashMapOf(vararg any: Pair<Any?, Any?>) = hashMapOf<Any?, Any?>(*any) fun pairOf(a: Any?, b: Any?) = Pair(a, b) fun heritableMapOf(vararg parents: HeritableMap<Any?, Any?>) = HeritableMap<Any?, Any?>() fun unescape(str: String): String { return StringEscapeUtils.unescapeJava(str) } fun `is`(a: Any?, b: Any?): Boolean { return a?.javaClass == b?.javaClass } var idx: Long = 0 fun uid(): Long { return idx++ } fun getOrPut(map: HashMap<Any?, Any?>, key: Any?, value: Any?): Any? { return map.getOrPut(key, {value}) } } object Log { fun println(any: Any) = kotlin.io.println(any) fun tokenErr(token: Token, msg: Any) = "${token.location.origin}:${token.location.range}: token \"${token.text}\" error: $msg" fun `throw`(msg: String): Unit = throw RuntimeException(msg) } interface ArtusReader { val name: String fun build(ctx: Context): Context } class FileArtusReader(file: File, charset: String = Charset.defaultCharset().name()) : StringArtusReader({ val dir = File(".") if (!file.canonicalPath.contains(dir.canonicalPath + File.separator)) { throw RuntimeException("$file: illegal file access, only children of local folder allowed") } file.readText(Charset.forName(charset)) }(), file.path) open class StringArtusReader(str: String, override val name: String) : ArtusReader { private var data = str private var offset = 0 override fun build(ctx: Context): Context { var ctx: Context = ctx while (data.isNotEmpty()) { val stack = ctx.type.getStack().toList() ctx = stack.fold(null as Context?, { acc, contextMatcher -> acc ?: { val matched = contextMatcher.matcher.regex.find(data) matched?.groups?.get(contextMatcher.matcher.group)?.let { val off = it.range.endInclusive + 1 data = data.substring(off) val token = Token(ArtusLocation(name, IntRange(offset, offset + off - 1)), it.value, contextMatcher.matcher.type) offset += off ctx.pushToken(token) contextMatcher.event(token, ctx) } }() }) ?: throw RuntimeException("no Context in source $name at $offset: \"${data.subSequence(0, min(80, data.lastIndex))}...\"") } return ctx } } val jexl = JexlBuilder().sandbox({ val sandbox = JexlSandbox(false) Reflections("com.artuslang", SubTypesScanner(false)).getSubTypesOf(Object::class.java).forEach { sandbox.white(it.name) } sandbox.white(String::class.java.name) sandbox.white(Map::class.java.name) sandbox.white(List::class.java.name) sandbox.white(HashMap::class.java.name) sandbox.white(ArrayList::class.java.name) sandbox.white(HashSet::class.java.name) sandbox.white(Pair::class.java.name) Reflections("java.nio").getSubTypesOf(Buffer::class.java).forEach { sandbox.white(it.name) } sandbox }()).create() /** * use like ByteBuffer but flexible size, bytebuffers are based on capacity and not limit */ class Data { private val buf = arrayListOf<ByteGroup>() private var size = 0 fun allocate(size: Int): ByteBuffer { val ret = ByteBuffer.allocate(size) add(ret) return ret } fun add(buffer: ByteBuffer) { val group = ArrayByteGroup(buffer, size) buf.add(group) size += group.size } fun toByteBuffer(): ByteBuffer { val ret = ByteBuffer.allocate(size) buf.forEach { val dat = it.dat dat.clear() ret.put(dat) } ret.clear() return ret } } interface ByteGroup { val size: Int val offset: Int val dat: ByteBuffer } class ArrayByteGroup(override val dat: ByteBuffer, override val offset: Int) : ByteGroup { override val size = dat.capacity() } class NDefTree { val root = NDefNode(hashSetOf(), hashSetOf()) open class NDefNode(val features: HashSet<Any>, val filters: HashSet<Any>) { protected val map = HashMap<Any, HashSet<NDefNode>>() protected val genMap = HashMap<Class<*>, HashSet<NDefNodeGen>>() val properties = HashMap<Any?, Any?>() override fun equals(other: Any?): Boolean { if (this === other) return true if (other !is NDefNodeGen) return false return true } override fun hashCode(): Int { return javaClass.hashCode() } fun get(elem: Any, features: List<Any>, filters: List<Any>): NDefNode? { var nodes: List<NDefNode> = map[elem]?.let { ArrayList(it) } ?: listOf() if (filters.isNotEmpty()) { nodes = nodes.filter { it.filters.containsAll(filters) } } if (features.isNotEmpty()) { nodes = nodes.filter { HashSet(features).containsAll(it.features) } } nodes = nodes.sortedWith(Comparator { o1, o2 -> val featureSize = o1.features.size - o2.features.size if (featureSize != 0) return@Comparator featureSize if (o1.features != o2.features) { features.forEach { val h1 = if (o1.features.contains(it)) 1 else 0 val h2 = if (o2.features.contains(it)) 1 else 0 val res = h1 - h2 if (res != 0) return@Comparator res } } o1.filters.size - o2.filters.size }) // generate if needed, first non null is valid return if (nodes.isEmpty()) { genMap[elem.javaClass]?.filter { it.couldGen(elem, features, filters) }?.sortedBy { it.ordinal }?.fold(null as NDefNode?, { acc, it -> acc ?: it.gen(elem, features, filters) }) } else nodes.firstOrNull() } fun put(elem: Any, node: NDefNode): NDefNode? { val nodes = map[elem] val nd = nodes?.find { it.features == node.features && it.filters == node.filters } ?: node if (nd.javaClass != node.javaClass) { return null } nd.features.addAll(features) nd.filters.addAll(filters) nodes?.add(nd) ?: map.getOrPut(elem, { hashSetOf() }).add(nd) return nd } fun put(classes: HashSet<Class<*>>, gen: NDefNodeGen) { classes.forEach { genMap.getOrPut(it, { hashSetOf() }).add(gen) } } fun getAllNodes(): HashSet<NDefNode> { return (map.values + genMap.values).flatten().toHashSet() // hashset because there can be duplicates on different classes (eg. a namespace can be bound to a string and ID) } /** * useful for buffering nodes, with different properties */ fun copyWith(features: Array<Any>, filters: Array<Any>): NDefNode { val ret = NDefNode(features.toHashSet(), filters.toHashSet()) ret.genMap.putAll(genMap) ret.map.putAll(map) ret.properties.putAll(properties) return ret } } abstract class NDefNodeGen(features: HashSet<Any>, filters: HashSet<Any>, val ordinal: Double) : NDefNode(features, filters) { /** * fast elimination check, false if cannot possibly generate, gen must not be called if return is false */ abstract fun couldGen(elem: Any, features: List<Any>, filters: List<Any>): Boolean /** * attempt to generate, if fail return null, not buffered, it has to be handled by the implementation for speed */ abstract fun gen(elem: Any, features: List<Any>, filters: List<Any>): NDefNode? } fun findNode(path: NDefPath): NDefNode? { return path.path.fold(root as NDefNode?, { acc, it -> acc?.get(it, path.features, path.filters) }) } fun findNodeOrBuild(path: NDefPath, builders: HashMap<Class<*>, (Any, List<Any>, List<Any>) -> NDefNode?>): NDefNode? { return path.path.fold(root as NDefNode?, { acc, it -> if (acc == null) { return null } acc.get(it, path.features, path.filters) ?: builders[it.javaClass]?.invoke(it, path.features, path.filters)?.let { node -> acc.put(it, node) } }) } } /** * [path] the path to follow nodes * [features] the path will priorize ambiguities with the most matching features, features defined with lower indexes have priority * [filters] the path will not follow any node that is missing a filter, if features are not discernable, it will take the one with closest filter match */ class NDefPath(val path: List<Any>, val features: List<Any> = listOf(), val filters: List<Any> = listOf()) class LayeredIterable<out T>(val base: Iterable<T>, val depth: Iterable<Iterable<T>>): Iterable<T> { override fun iterator(): Iterator<T> { return Iterators.concat(base.iterator(), Iterators.concat(depth.map { it.iterator() }.iterator())) } } class HeritableMap<T, U>(parents: List<HeritableMap<T, U>> = listOf()) { val parents = ArrayList<HeritableMap<T, U>>(parents) private val map = HashMap<T, U>() operator fun get(key: T): U? { var value = map[key] if (value == null) { parents.forEach { value = it[key] if (value != null) return value } } return value } fun put(key: T, value: U): U? { return map.put(key, value) } }
apache-2.0
f175fcde3ddb66fd1ed1f3a3e20dd2f1
34.294574
192
0.607363
4.072272
false
false
false
false
JetBrains/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/ChangeSuperTypeListEntryTypeArgumentFix.kt
1
4809
// 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.quickfix import com.intellij.codeInsight.intention.IntentionAction import com.intellij.openapi.editor.Editor import com.intellij.openapi.project.Project import org.jetbrains.kotlin.descriptors.ClassDescriptor import org.jetbrains.kotlin.diagnostics.Diagnostic import org.jetbrains.kotlin.diagnostics.Errors import org.jetbrains.kotlin.idea.base.resources.KotlinBundle import org.jetbrains.kotlin.idea.caches.resolve.resolveToCall import org.jetbrains.kotlin.idea.codeinsight.api.classic.quickfixes.KotlinQuickFixAction import org.jetbrains.kotlin.idea.quickfix.createFromUsage.callableBuilder.getReturnTypeReference import org.jetbrains.kotlin.idea.references.mainReference import org.jetbrains.kotlin.idea.search.usagesSearch.descriptor import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.containingClass import org.jetbrains.kotlin.resolve.DescriptorToSourceUtils class ChangeSuperTypeListEntryTypeArgumentFix( element: KtSuperTypeListEntry, private val type: String, private val typeArgumentIndex: Int ) : KotlinQuickFixAction<KtSuperTypeListEntry>(element) { override fun getText() = KotlinBundle.message("fix.change.type.argument", type) override fun getFamilyName() = text override fun invoke(project: Project, editor: Editor?, file: KtFile) { val superTypeListEntry = element ?: return val typeArgumentList = superTypeListEntry.typeAsUserType?.typeArgumentList?.arguments?.mapIndexed { index, typeProjection -> if (index == typeArgumentIndex) type else typeProjection.text }?.joinToString(prefix = "<", postfix = ">", separator = ", ") { it } ?: return val psiFactory = KtPsiFactory(project) val newElement = when (superTypeListEntry) { is KtSuperTypeEntry -> { val classReference = superTypeListEntry.typeAsUserType?.referenceExpression?.text ?: return psiFactory.createSuperTypeEntry("$classReference$typeArgumentList") } is KtSuperTypeCallEntry -> { val classReference = superTypeListEntry.calleeExpression.constructorReferenceExpression?.text ?: return val valueArgumentList = superTypeListEntry.valueArgumentList?.text ?: return psiFactory.createSuperTypeCallEntry("$classReference$typeArgumentList$valueArgumentList") } else -> return } superTypeListEntry.replace(newElement) } companion object : KotlinSingleIntentionActionFactory() { override fun createAction(diagnostic: Diagnostic): IntentionAction? { val (casted, declaration) = when (diagnostic.factory) { Errors.RETURN_TYPE_MISMATCH_ON_OVERRIDE -> { val casted = Errors.RETURN_TYPE_MISMATCH_ON_OVERRIDE.cast(diagnostic) casted to casted.b.declaration } Errors.PROPERTY_TYPE_MISMATCH_ON_OVERRIDE -> { val casted = Errors.PROPERTY_TYPE_MISMATCH_ON_OVERRIDE.cast(diagnostic) casted to casted.b } else -> null } ?: return null val type = casted.a.returnType?.toString() ?: return null val superClassDescriptor = declaration.containingDeclaration as? ClassDescriptor ?: return null val superDeclaration = DescriptorToSourceUtils.descriptorToDeclaration(declaration) as? KtNamedDeclaration ?: return null val superTypeReference = superDeclaration.getReturnTypeReference()?.text ?: return null val typeParameterIndex = superClassDescriptor.declaredTypeParameters.map { it.name.asString() }.indexOf(superTypeReference) if (typeParameterIndex < 0) return null val containingClass = casted.psiElement.containingClass() ?: return null val superTypeListEntry = containingClass.superTypeListEntries.find { when (it) { is KtSuperTypeEntry -> { (it.typeAsUserType?.referenceExpression?.mainReference?.resolve() as? KtClass)?.descriptor == superClassDescriptor } is KtSuperTypeCallEntry -> { it.calleeExpression.resolveToCall()?.resultingDescriptor?.returnType?.constructor ?.declarationDescriptor == superClassDescriptor } else -> false } } ?: return null return ChangeSuperTypeListEntryTypeArgumentFix(superTypeListEntry, type, typeParameterIndex) } } }
apache-2.0
82279254c0ad7c809bd781eb9614fdf9
50.72043
158
0.688085
5.725
false
false
false
false
DSteve595/Put.io
app/src/main/java/com/stevenschoen/putionew/AboutFragment.kt
1
2286
package com.stevenschoen.putionew import android.content.Intent import android.content.pm.PackageManager import android.net.Uri import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.TextView import androidx.core.app.NavUtils import androidx.fragment.app.Fragment import com.stevenschoen.putionew.R class AboutFragment : Fragment() { override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View { val view = inflater.inflate(R.layout.about, container, false) val backView: View = view.findViewById(R.id.about_back) backView.setOnClickListener { NavUtils.navigateUpFromSameTask(activity!!) } val versionView: TextView = view.findViewById(R.id.about_version) try { val version = activity!!.packageManager.getPackageInfo(activity!!.packageName, 0).versionName versionView.text = getString(R.string.version_x, version) } catch (e: PackageManager.NameNotFoundException) { e.printStackTrace() } val githubView: View = view.findViewById(R.id.about_github) githubView.setOnClickListener { startActivity( Intent(Intent.ACTION_VIEW) .setData(Uri.parse("https://github.com/DSteve595/Put.io")) ) } val emailView: View = view.findViewById(R.id.about_email) emailView.setOnClickListener { val sendEmailIntent = Intent(Intent.ACTION_SENDTO, Uri.parse("mailto:[email protected]")) .putExtra(Intent.EXTRA_EMAIL, arrayOf("[email protected]")) .putExtra(Intent.EXTRA_SUBJECT, "Put.io for Android") startActivity(Intent.createChooser(sendEmailIntent, getString(R.string.email_the_developer))) } val translateView: View = view.findViewById(R.id.about_translate) translateView.setOnClickListener { startActivity( Intent(Intent.ACTION_VIEW) .setData(Uri.parse("https://crowdin.com/project/putio-for-android")) ) } val visitView: View = view.findViewById(R.id.about_visit) visitView.setOnClickListener { startActivity( Intent(Intent.ACTION_VIEW) .setData(Uri.parse("https://put.io/")) ) } return view } }
mit
2ca44137f8e46fdb6d2795b8aa731774
33.119403
113
0.710849
4.163934
false
false
false
false
elect86/oglDevTutorials
src/main/kotlin/ogl_dev/helper.kt
1
4399
package ogl_dev import glm.vec._2.Vec2i import org.lwjgl.glfw.Callbacks.glfwFreeCallbacks import org.lwjgl.glfw.GLFW.* import org.lwjgl.glfw.GLFWErrorCallback import org.lwjgl.glfw.GLFWVidMode import org.lwjgl.system.MemoryUtil.NULL import uno.buffer.destroyBuffers import uno.buffer.intBufferBig /** * Created by elect on 22/04/17. */ object glfw { fun init() { GLFWErrorCallback.createPrint(System.err).set() if (!glfwInit()) throw IllegalStateException("Unable to initialize GLFW") } fun windowHint(block: WindowHint.() -> Unit) = WindowHint.block() val primaryMonitor get() = glfwGetPrimaryMonitor() val videoMode: GLFWVidMode get() = glfwGetVideoMode(primaryMonitor) fun videoMode(monitor: Long): GLFWVidMode = glfwGetVideoMode(monitor) val resolution get() = Vec2i(videoMode.width(), videoMode.height()) var swapInterval = 0 set(value) = glfwSwapInterval(value) fun terminate() { glfwTerminate() glfwSetErrorCallback(null).free() } fun pollEvents() = glfwPollEvents() } object WindowHint { fun default() = glfwDefaultWindowHints() var resizable = true set(value) { glfwWindowHint(GLFW_RESIZABLE, if (value) GLFW_TRUE else GLFW_FALSE) field = value } var visible = true set(value) { glfwWindowHint(GLFW_VISIBLE, if (value) GLFW_TRUE else GLFW_FALSE) field = value } var srgb = true set(value) { glfwWindowHint(GLFW_SRGB_CAPABLE, if (value) GLFW_TRUE else GLFW_FALSE) field = value } var decorated = true set(value) { glfwWindowHint(GLFW_DECORATED, if (value) GLFW_TRUE else GLFW_FALSE) field = value } var api = "" set(value) { glfwWindowHint(GLFW_CLIENT_API, when (value) { "gl" -> GLFW_OPENGL_API "es" -> GLFW_OPENGL_ES_API else -> GLFW_NO_API }) field = value } var major = 0 set(value) { glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, value) field = value } var minor = 0 set(value) { glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, value) field = value } var profile = "" set(value) { glfwWindowHint(GLFW_OPENGL_PROFILE, when (value) { "core" -> GLFW_OPENGL_CORE_PROFILE "compat" -> GLFW_OPENGL_COMPAT_PROFILE else -> GLFW_OPENGL_ANY_PROFILE }) field = value } var forwardComp = true set(value) { glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, if (value) GLFW_TRUE else GLFW_FALSE) field = value } var debug = true set(value) { glfwWindowHint(GLFW_OPENGL_DEBUG_CONTEXT, if (value) GLFW_TRUE else GLFW_FALSE) field = value } var doubleBuffer = true set(value) { glfwWindowHint(GLFW_DOUBLEBUFFER, if (value) GLFW_TRUE else GLFW_FALSE) field = value } } class GlfwWindow(width: Int, height: Int, title: String) { constructor(windowSize: Vec2i, title: String) : this(windowSize.x, windowSize.y, title) constructor(x: Int, title: String) : this(x, x, title) private val x = intBufferBig(1) private val y = intBufferBig(1) val handle = glfwCreateWindow(width, height, title, 0L, 0L) var shouldClose = false get() = glfwWindowShouldClose(handle) init { if (handle == NULL) throw RuntimeException("Failed to create the GLFW window") } var pos = Vec2i() get() { glfwGetWindowPos(handle, x, y) return field.put(x[0], y[0]) } set(value) = glfwSetWindowPos(handle, value.x, value.y) val size: Vec2i get() { glfwGetWindowSize(handle, x, y) return Vec2i(x[0], y[0]) } fun makeContextCurrent() = glfwMakeContextCurrent(handle) fun dispose() { destroyBuffers(x, y) // Free the window callbacks and destroy the window glfwFreeCallbacks(handle) glfwDestroyWindow(handle) } fun show() = glfwShowWindow(handle) fun swapBuffers() = glfwSwapBuffers(handle) }
mit
18b3d81007bed32d627412df5d8b70b5
26.329193
92
0.584451
4.181559
false
false
false
false
GunoH/intellij-community
plugins/github/src/org/jetbrains/plugins/github/extensions/GithubYamlIconProvider.kt
4
1076
// 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.extensions import com.intellij.icons.AllIcons import com.intellij.ide.FileIconProvider import com.intellij.openapi.components.service import com.intellij.openapi.project.Project import com.intellij.openapi.vfs.VirtualFile import com.jetbrains.jsonSchema.ide.JsonSchemaService import javax.swing.Icon internal class GithubYamlIconProvider : FileIconProvider { private val GITHUB_SCHEMA_NAMES: Set<String> = setOf("github-workflow", "github-action") override fun getIcon(file: VirtualFile, flags: Int, project: Project?): Icon? { if (project == null) return null val extension = file.extension if (extension != "yml" && extension != "yaml") return null val schemaFiles = project.service<JsonSchemaService>().getSchemaFilesForFile(file) if (schemaFiles.any { GITHUB_SCHEMA_NAMES.contains(it.name) }) { return AllIcons.Vcs.Vendors.Github } return null } }
apache-2.0
1dbb1bd8a6df403241fd636cf8a70060
37.428571
140
0.762082
4.029963
false
false
false
false
GunoH/intellij-community
platform/platform-impl/src/com/intellij/openapi/updateSettings/impl/pluginsAdvertisement/PluginAdvertiserService.kt
1
14751
// 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.updateSettings.impl.pluginsAdvertisement import com.intellij.ide.IdeBundle import com.intellij.ide.plugins.* import com.intellij.ide.plugins.advertiser.PluginData import com.intellij.ide.plugins.advertiser.PluginFeatureCacheService import com.intellij.ide.plugins.advertiser.PluginFeatureMap import com.intellij.ide.plugins.marketplace.MarketplaceRequests import com.intellij.ide.plugins.org.PluginManagerFilters import com.intellij.ide.ui.PluginBooleanOptionDescriptor import com.intellij.notification.NotificationAction import com.intellij.notification.NotificationType import com.intellij.notification.SingletonNotificationManager import com.intellij.openapi.Disposable import com.intellij.openapi.actionSystem.AnAction import com.intellij.openapi.application.EDT import com.intellij.openapi.components.service import com.intellij.openapi.extensions.PluginId import com.intellij.openapi.project.Project import com.intellij.openapi.updateSettings.impl.PluginDownloader import com.intellij.openapi.util.NlsContexts.NotificationContent import com.intellij.util.concurrency.annotations.RequiresBackgroundThread import com.intellij.util.containers.MultiMap import kotlinx.coroutines.* import org.jetbrains.annotations.ApiStatus import kotlin.coroutines.coroutineContext sealed interface PluginAdvertiserService { companion object { @JvmStatic fun getInstance(project: Project): PluginAdvertiserService = project.service() } suspend fun run( customPlugins: List<PluginNode>, unknownFeatures: Collection<UnknownFeature>, includeIgnored: Boolean = false, ) @ApiStatus.Internal fun collectDependencyUnknownFeatures(includeIgnored: Boolean = false) @ApiStatus.Internal fun rescanDependencies(block: suspend CoroutineScope.() -> Unit = {}) } open class PluginAdvertiserServiceImpl(private val project: Project) : PluginAdvertiserService, Disposable { companion object { private val notificationManager = SingletonNotificationManager(notificationGroup.displayId, NotificationType.INFORMATION) } private val coroutineScope = CoroutineScope(SupervisorJob()) override suspend fun run( customPlugins: List<PluginNode>, unknownFeatures: Collection<UnknownFeature>, includeIgnored: Boolean, ) { val featuresMap = MultiMap.createSet<PluginId, UnknownFeature>() val plugins = mutableSetOf<PluginData>() val dependencies = PluginFeatureCacheService.getInstance().dependencies val ignoredPluginSuggestionState = GlobalIgnoredPluginSuggestionState.getInstance() for (feature in unknownFeatures) { coroutineContext.ensureActive() val featureType = feature.featureType val implementationName = feature.implementationName val featurePluginData = PluginFeatureService.instance.getPluginForFeature(featureType, implementationName) val installedPluginData = featurePluginData?.pluginData fun putFeature(data: PluginData) { val pluginId = data.pluginId if (ignoredPluginSuggestionState.isIgnored(pluginId) && !includeIgnored) { // globally ignored LOG.info("Plugin is ignored by user, suggestion will not be shown: $pluginId") return } plugins += data featuresMap.putValue(pluginId, featurePluginData?.displayName?.let { feature.withImplementationDisplayName(it) } ?: feature) } if (installedPluginData != null) { putFeature(installedPluginData) } else if (featureType == DEPENDENCY_SUPPORT_FEATURE && dependencies != null) { dependencies.get(implementationName).forEach(::putFeature) } else { MarketplaceRequests.getInstance() .getFeatures(featureType, implementationName) .asSequence() .mapNotNull { it.toPluginData() } .forEach { putFeature(it) } } } val descriptorsById = PluginManagerCore.buildPluginIdMap() val pluginManagerFilters = PluginManagerFilters.getInstance() val disabledDescriptors = plugins.asSequence() .map { it.pluginId } .mapNotNull { descriptorsById[it] } .filterNot { it.isEnabled } .filter { pluginManagerFilters.allowInstallingPlugin(it) } .filterNot { it.isOnDemand } .toList() val suggestToInstall = if (plugins.isEmpty()) emptyList() else fetchPluginSuggestions( pluginIds = plugins.asSequence().map { it.pluginId }.toSet(), customPlugins = customPlugins, org = pluginManagerFilters, ) coroutineScope.launch(Dispatchers.EDT) { notifyUser( bundledPlugins = getBundledPluginToInstall(plugins, descriptorsById), suggestionPlugins = suggestToInstall, disabledDescriptors = disabledDescriptors, customPlugins = customPlugins, featuresMap = featuresMap, allUnknownFeatures = unknownFeatures, dependencies = dependencies, includeIgnored = includeIgnored, ) } } override fun dispose() { coroutineScope.cancel() } private fun fetchPluginSuggestions( pluginIds: Set<PluginId>, customPlugins: List<PluginNode>, org: PluginManagerFilters, ): List<PluginDownloader> { return RepositoryHelper.mergePluginsFromRepositories( MarketplaceRequests.loadLastCompatiblePluginDescriptors(pluginIds), customPlugins, true, ).asSequence() .filter { pluginIds.contains(it.pluginId) } .filterNot { PluginManagerCore.isDisabled(it.pluginId) } .filterNot { PluginManagerCore.isBrokenPlugin(it) } .filter { loadedPlugin -> when (val installedPlugin = PluginManagerCore.getPluginSet().findInstalledPlugin(loadedPlugin.pluginId)) { null -> true else -> (!installedPlugin.isBundled || installedPlugin.allowBundledUpdate()) && PluginDownloader.compareVersionsSkipBrokenAndIncompatible(loadedPlugin.version, installedPlugin) > 0 } }.filter { org.allowInstallingPlugin(it) } .map { PluginDownloader.createDownloader(it) } .toList() } private fun notifyUser( bundledPlugins: List<String>, suggestionPlugins: List<PluginDownloader>, disabledDescriptors: List<IdeaPluginDescriptorImpl>, customPlugins: List<PluginNode>, featuresMap: MultiMap<PluginId, UnknownFeature>, allUnknownFeatures: Collection<UnknownFeature>, dependencies: PluginFeatureMap?, includeIgnored: Boolean, ) { val (notificationMessage, notificationActions) = if (suggestionPlugins.isNotEmpty() || disabledDescriptors.isNotEmpty()) { val action = if (disabledDescriptors.isEmpty()) { NotificationAction.createSimpleExpiring(IdeBundle.message("plugins.advertiser.action.configure.plugins")) { FUSEventSource.NOTIFICATION.logConfigurePlugins(project) PluginsAdvertiserDialog(project, suggestionPlugins, customPlugins).show() } } else { val title = if (disabledDescriptors.size == 1) IdeBundle.message("plugins.advertiser.action.enable.plugin") else IdeBundle.message("plugins.advertiser.action.enable.plugins") NotificationAction.createSimpleExpiring(title) { coroutineScope.launch(Dispatchers.EDT) { FUSEventSource.NOTIFICATION.logEnablePlugins( disabledDescriptors.map { it.pluginId.idString }, project, ) PluginBooleanOptionDescriptor.togglePluginState(disabledDescriptors, true) } } } val notificationActions = listOf( action, createIgnoreUnknownFeaturesAction(suggestionPlugins, disabledDescriptors, allUnknownFeatures, dependencies), ) val messagePresentation = getAddressedMessagePresentation(suggestionPlugins, disabledDescriptors, featuresMap) Pair(messagePresentation, notificationActions) } else if (bundledPlugins.isNotEmpty() && !isIgnoreIdeSuggestion) { IdeBundle.message( "plugins.advertiser.ultimate.features.detected", bundledPlugins.joinToString() ) to listOf( NotificationAction.createSimpleExpiring( IdeBundle.message("plugins.advertiser.action.try.ultimate", PluginAdvertiserEditorNotificationProvider.ideaUltimate.name)) { FUSEventSource.NOTIFICATION.openDownloadPageAndLog(project, PluginAdvertiserEditorNotificationProvider.ideaUltimate.downloadUrl) }, NotificationAction.createSimpleExpiring(IdeBundle.message("plugins.advertiser.action.ignore.ultimate")) { FUSEventSource.NOTIFICATION.doIgnoreUltimateAndLog(project) }, ) } else { if (includeIgnored) { notificationGroup.createNotification(IdeBundle.message("plugins.advertiser.no.suggested.plugins"), NotificationType.INFORMATION) .setDisplayId("advertiser.no.plugins") .notify(project) } return } notificationManager.notify("", notificationMessage, project) { it.setSuggestionType(true).addActions(notificationActions as Collection<AnAction>) } } private fun createIgnoreUnknownFeaturesAction( plugins: Collection<PluginDownloader>, disabledPlugins: Collection<IdeaPluginDescriptor>, unknownFeatures: Collection<UnknownFeature>, dependencyPlugins: PluginFeatureMap?, ): NotificationAction { val ids = plugins.mapTo(LinkedHashSet()) { it.id } + disabledPlugins.map { it.pluginId } val message = IdeBundle.message( if (ids.size > 1) "plugins.advertiser.action.ignore.unknown.features" else "plugins.advertiser.action.ignore.unknown.feature") return NotificationAction.createSimpleExpiring(message) { FUSEventSource.NOTIFICATION.logIgnoreUnknownFeatures(project) val collector = UnknownFeaturesCollector.getInstance(project) for (unknownFeature in unknownFeatures) { if (unknownFeature.featureType != DEPENDENCY_SUPPORT_FEATURE || dependencyPlugins?.get(unknownFeature.implementationName)?.isNotEmpty() == true) { collector.ignoreFeature(unknownFeature) } } val globalIgnoredState = GlobalIgnoredPluginSuggestionState.getInstance() for (pluginIdToIgnore in ids) { globalIgnoredState.ignoreFeature(pluginIdToIgnore) } } } open fun getAddressedMessagePresentation( plugins: Collection<PluginDownloader>, disabledPlugins: Collection<IdeaPluginDescriptor>, features: MultiMap<PluginId, UnknownFeature>, ): @NotificationContent String { val ids = plugins.mapTo(LinkedHashSet()) { it.id } + disabledPlugins.map { it.pluginId } val pluginNames = (plugins.map { it.pluginName } + disabledPlugins.map { it.name }) .sorted() .joinToString(", ") val addressedFeatures = collectFeaturesByName(ids, features) val pluginsNumber = ids.size val repoPluginsNumber = plugins.size val entries = addressedFeatures.entrySet() return if (entries.size == 1) { val feature = entries.single() if (feature.key != "dependency") { IdeBundle.message( "plugins.advertiser.missing.feature", pluginsNumber, feature.key, feature.value.joinToString(), repoPluginsNumber, pluginNames ) } else { if (feature.value.size <= 1) { IdeBundle.message( "plugins.advertiser.missing.feature.dependency", pluginsNumber, feature.value.joinToString(), pluginNames ) } else { IdeBundle.message( "plugins.advertiser.missing.features.dependency", pluginsNumber, feature.value.joinToString(), pluginNames ) } } } else { if (entries.all { it.key == "dependency" }) { IdeBundle.message( "plugins.advertiser.missing.features.dependency", pluginsNumber, entries.joinToString(separator = "; ") { it.value.joinToString(prefix = it.key + ": ") }, pluginNames ) } else { IdeBundle.message( "plugins.advertiser.missing.features", pluginsNumber, entries.joinToString(separator = "; ") { it.value.joinToString(prefix = it.key + ": ") }, repoPluginsNumber, pluginNames ) } } } override fun collectDependencyUnknownFeatures(includeIgnored: Boolean) { val featuresCollector = UnknownFeaturesCollector.getInstance(project) featuresCollector.getUnknownFeaturesOfType(DEPENDENCY_SUPPORT_FEATURE) .forEach { featuresCollector.unregisterUnknownFeature(it) } DependencyCollectorBean.EP_NAME.extensions .asSequence() .flatMap { dependencyCollectorBean -> dependencyCollectorBean.instance.collectDependencies(project).map { coordinate -> UnknownFeature( DEPENDENCY_SUPPORT_FEATURE, IdeBundle.message("plugins.advertiser.feature.dependency"), dependencyCollectorBean.kind + ":" + coordinate, null, ) } }.forEach { featuresCollector.registerUnknownFeature(it) } } private fun collectFeaturesByName( ids: Set<PluginId>, features: MultiMap<PluginId, UnknownFeature>, ): MultiMap<String, String> { val result = MultiMap.createSet<String, String>() ids .flatMap { features[it] } .forEach { result.putValue(it.featureDisplayName, it.implementationDisplayName) } return result } override fun rescanDependencies(block: suspend CoroutineScope.() -> Unit) { coroutineScope.launch(Dispatchers.IO) { rescanDependencies() block() } } @RequiresBackgroundThread private suspend fun rescanDependencies() { collectDependencyUnknownFeatures() val dependencyUnknownFeatures = UnknownFeaturesCollector.getInstance(project).unknownFeatures if (dependencyUnknownFeatures.isNotEmpty()) { run( customPlugins = loadPluginsFromCustomRepositories(), unknownFeatures = dependencyUnknownFeatures, ) } } } open class HeadlessPluginAdvertiserServiceImpl : PluginAdvertiserService { final override suspend fun run( customPlugins: List<PluginNode>, unknownFeatures: Collection<UnknownFeature>, includeIgnored: Boolean, ) { } final override fun collectDependencyUnknownFeatures(includeIgnored: Boolean) {} final override fun rescanDependencies(block: suspend CoroutineScope.() -> Unit) {} }
apache-2.0
b2a8dbf5e25f3c8e4296a1aceb37a462
35.605459
138
0.704088
5.287097
false
false
false
false
GunoH/intellij-community
plugins/kotlin/base/psi/src/org/jetbrains/kotlin/idea/base/psi/fileTypes/KotlinJavaScriptMetaFileType.kt
4
914
// 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.base.psi.fileTypes import com.intellij.openapi.fileTypes.FileType import com.intellij.openapi.vfs.VirtualFile import org.jetbrains.kotlin.idea.base.psi.KotlinBasePsiBundle import org.jetbrains.kotlin.serialization.js.KotlinJavascriptSerializationUtil object KotlinJavaScriptMetaFileType : FileType { override fun getName() = "KJSM" override fun getDescription() = KotlinBasePsiBundle.message("kotlin.javascript.meta.file") override fun getDefaultExtension() = KotlinJavascriptSerializationUtil.CLASS_METADATA_FILE_EXTENSION override fun getIcon() = null override fun isBinary() = true override fun isReadOnly() = true override fun getCharset(file: VirtualFile, content: ByteArray) = null }
apache-2.0
fe88f0efd194e19f690b5ea1a7578421
49.777778
158
0.795405
4.480392
false
false
false
false
siosio/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/createFromUsage/createCallable/CreateCallableFromUsageFix.kt
1
10807
// 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.createCallable import com.intellij.codeInsight.intention.LowPriorityAction import com.intellij.codeInsight.navigation.NavigationUtil import com.intellij.ide.util.EditorHelper import com.intellij.openapi.editor.Editor import com.intellij.openapi.project.Project import com.intellij.psi.PsiClass import com.intellij.psi.PsiElement import com.intellij.psi.PsiFile import org.jetbrains.kotlin.builtins.functions.FunctionClassDescriptor import org.jetbrains.kotlin.descriptors.ClassifierDescriptor import org.jetbrains.kotlin.idea.KotlinBundle import org.jetbrains.kotlin.idea.codeInsight.DescriptorToSourceUtilsIde import org.jetbrains.kotlin.idea.quickfix.KotlinCrossLanguageQuickFixAction import org.jetbrains.kotlin.idea.quickfix.createFromUsage.callableBuilder.* import org.jetbrains.kotlin.idea.refactoring.canRefactor import org.jetbrains.kotlin.idea.refactoring.chooseContainerElementIfNecessary import org.jetbrains.kotlin.idea.util.IdeDescriptorRenderers import org.jetbrains.kotlin.idea.util.application.executeCommand import org.jetbrains.kotlin.idea.util.isAbstract import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.getElementTextWithContext import org.jetbrains.kotlin.types.typeUtil.isTypeParameter open class CreateCallableFromUsageFix<E : KtElement>( originalExpression: E, callableInfos: List<CallableInfo> ) : CreateCallableFromUsageFixBase<E>(originalExpression, callableInfos, false) class CreateExtensionCallableFromUsageFix<E : KtElement>( originalExpression: E, callableInfos: List<CallableInfo> ) : CreateCallableFromUsageFixBase<E>(originalExpression, callableInfos, true), LowPriorityAction abstract class CreateCallableFromUsageFixBase<E : KtElement>( originalExpression: E, protected val callableInfos: List<CallableInfo>, val isExtension: Boolean ) : KotlinCrossLanguageQuickFixAction<E>(originalExpression) { init { assert(callableInfos.isNotEmpty()) { "No CallableInfos: ${originalExpression.getElementTextWithContext()}" } if (callableInfos.size > 1) { val receiverSet = callableInfos.mapTo(HashSet()) { it.receiverTypeInfo } if (receiverSet.size > 1) throw AssertionError("All functions must have common receiver: $receiverSet") val possibleContainerSet = callableInfos.mapTo(HashSet()) { it.possibleContainers } if (possibleContainerSet.size > 1) throw AssertionError("All functions must have common containers: $possibleContainerSet") } } private fun getDeclaration(descriptor: ClassifierDescriptor, project: Project): PsiElement? { if (descriptor is FunctionClassDescriptor) { val psiFactory = KtPsiFactory(project) val syntheticClass = psiFactory.createClass(IdeDescriptorRenderers.SOURCE_CODE_SHORT_NAMES_NO_ANNOTATIONS.render(descriptor)) return psiFactory.createAnalyzableFile("${descriptor.name.asString()}.kt", "", element!!).add(syntheticClass) } return DescriptorToSourceUtilsIde.getAnyDeclaration(project, descriptor) } private fun getDeclarationIfApplicable(project: Project, candidate: TypeCandidate): PsiElement? { val descriptor = candidate.theType.constructor.declarationDescriptor ?: return null val declaration = getDeclaration(descriptor, project) ?: return null if (declaration !is KtClassOrObject && declaration !is KtTypeParameter && declaration !is PsiClass) return null return if (isExtension || declaration.canRefactor()) declaration else null } override fun getFamilyName(): String = KotlinBundle.message("fix.create.from.usage.family") override fun getText(): String { val element = element ?: return "" val receiverTypeInfo = callableInfos.first().receiverTypeInfo val renderedCallables = callableInfos.map { buildString { if (it.isAbstract) { append(KotlinBundle.message("text.abstract")) append(' ') } val kind = when (it.kind) { CallableKind.FUNCTION -> KotlinBundle.message("text.function") CallableKind.PROPERTY -> KotlinBundle.message("text.property") CallableKind.CONSTRUCTOR -> KotlinBundle.message("text.secondary.constructor") else -> throw AssertionError("Unexpected callable info: $it") } append(kind) if (it.name.isNotEmpty()) { append(" '") val receiverType = if (!receiverTypeInfo.isOfThis) { CallableBuilderConfiguration(callableInfos, element, isExtension = isExtension) .createBuilder() .computeTypeCandidates(receiverTypeInfo) .firstOrNull { candidate -> if (it.isAbstract) candidate.theType.isAbstract() else true } ?.theType } else null if (receiverType != null) { if (isExtension) { val receiverTypeText = IdeDescriptorRenderers.SOURCE_CODE_SHORT_NAMES_NO_ANNOTATIONS.renderType(receiverType) val isFunctionType = receiverType.constructor.declarationDescriptor is FunctionClassDescriptor append(if (isFunctionType) "($receiverTypeText)" else receiverTypeText).append('.') } else { receiverType.constructor.declarationDescriptor?.let { append(IdeDescriptorRenderers.SOURCE_CODE_SHORT_NAMES_NO_ANNOTATIONS.renderClassifierName(it)).append('.') } } } append("${it.name}'") } } } return StringBuilder().apply { append(KotlinBundle.message("text.create")) append(' ') if (!callableInfos.any { it.isAbstract }) { if (isExtension) { append(KotlinBundle.message("text.extension")) append(' ') } else if (receiverTypeInfo != TypeInfo.Empty) { append(KotlinBundle.message("text.member")) append(' ') } } renderedCallables.joinTo(this) }.toString() } override fun isAvailableImpl(project: Project, editor: Editor?, file: PsiFile): Boolean { val element = element ?: return false val receiverInfo = callableInfos.first().receiverTypeInfo if (receiverInfo == TypeInfo.Empty) { if (callableInfos.any { it is PropertyInfo && it.possibleContainers.isEmpty() }) return false return !isExtension } // TODO: Remove after companion object extensions are supported if (isExtension && receiverInfo.staticContextRequired) return false val callableBuilder = CallableBuilderConfiguration(callableInfos, element, isExtension = isExtension).createBuilder() val receiverTypeCandidates = callableBuilder.computeTypeCandidates(callableInfos.first().receiverTypeInfo) val propertyInfo = callableInfos.firstOrNull { it is PropertyInfo } as PropertyInfo? val isFunction = callableInfos.any { it.kind == CallableKind.FUNCTION } return receiverTypeCandidates.any { val declaration = getDeclarationIfApplicable(project, it) val insertToJavaInterface = declaration is PsiClass && declaration.isInterface when { !isExtension && propertyInfo != null && insertToJavaInterface && (!receiverInfo.staticContextRequired || propertyInfo.writable) -> false isFunction && insertToJavaInterface && receiverInfo.staticContextRequired -> false !isExtension && declaration is KtTypeParameter -> false propertyInfo != null && !propertyInfo.isAbstract && declaration is KtClass && declaration.isInterface() -> false else -> declaration != null } } } override fun invokeImpl(project: Project, editor: Editor?, file: PsiFile) { val element = element ?: return val callableInfo = callableInfos.first() val fileForBuilder = element.containingKtFile val editorForBuilder = EditorHelper.openInEditor(element) if (editorForBuilder != editor) { NavigationUtil.activateFileWithPsiElement(element) } val callableBuilder = CallableBuilderConfiguration(callableInfos, element as KtElement, fileForBuilder, editorForBuilder, isExtension).createBuilder() fun runBuilder(placement: CallablePlacement) { callableBuilder.placement = placement project.executeCommand(text) { callableBuilder.build() } } if (callableInfo is ConstructorInfo) { runBuilder(CallablePlacement.NoReceiver(callableInfo.targetClass)) return } val popupTitle = KotlinBundle.message("choose.target.class.or.interface") val receiverTypeInfo = callableInfo.receiverTypeInfo val receiverTypeCandidates = callableBuilder.computeTypeCandidates(receiverTypeInfo).let { if (callableInfo.isAbstract) it.filter { it.theType.isAbstract() } else if (!isExtension && receiverTypeInfo != TypeInfo.Empty) it.filter { !it.theType.isTypeParameter() } else it } if (receiverTypeCandidates.isNotEmpty()) { val containers = receiverTypeCandidates .mapNotNull { candidate -> getDeclarationIfApplicable(project, candidate)?.let { candidate to it } } chooseContainerElementIfNecessary(containers, editorForBuilder, popupTitle, false, { it.second }) { runBuilder(CallablePlacement.WithReceiver(it.first)) } } else { assert(receiverTypeInfo == TypeInfo.Empty) { "No receiver type candidates: ${element.text} in ${file.text}" } chooseContainerElementIfNecessary(callableInfo.possibleContainers, editorForBuilder, popupTitle, true) { val container = if (it is KtClassBody) it.parent as KtClassOrObject else it runBuilder(CallablePlacement.NoReceiver(container)) } } } }
apache-2.0
017e8cf6ddd1b49113e9a9cd2b4145fb
48.122727
158
0.658462
5.684903
false
false
false
false
siosio/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/createFromUsage/createClass/CreateClassFromTypeReferenceActionFactory.kt
2
5077
// 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.createClass import org.jetbrains.kotlin.diagnostics.Diagnostic import org.jetbrains.kotlin.idea.caches.resolve.analyzeAndGetResult import org.jetbrains.kotlin.idea.core.quickfix.QuickFixUtil import org.jetbrains.kotlin.idea.quickfix.createFromUsage.callableBuilder.TypeInfo import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.getParentOfTypeAndBranch import org.jetbrains.kotlin.psi.psiUtil.getStrictParentOfType import org.jetbrains.kotlin.resolve.BindingContext import org.jetbrains.kotlin.resolve.calls.callUtil.getResolvedCall import org.jetbrains.kotlin.types.KotlinType import org.jetbrains.kotlin.types.TypeIntersector import org.jetbrains.kotlin.types.Variance import org.jetbrains.kotlin.utils.ifEmpty import java.util.* object CreateClassFromTypeReferenceActionFactory : CreateClassFromUsageFactory<KtUserType>() { override fun getElementOfInterest(diagnostic: Diagnostic): KtUserType? { return QuickFixUtil.getParentElementOfType(diagnostic, KtUserType::class.java) } override fun getPossibleClassKinds(element: KtUserType, diagnostic: Diagnostic): List<ClassKind> { val typeRefParent = element.parent.parent if (typeRefParent is KtConstructorCalleeExpression) return Collections.emptyList() val isQualifier = (element.parent as? KtUserType)?.let { it.qualifier == element } ?: false val typeReference = element.parent as? KtTypeReference val isUpperBound = typeReference?.getParentOfTypeAndBranch<KtTypeParameter> { extendsBound } != null || typeReference?.getParentOfTypeAndBranch<KtTypeConstraint> { boundTypeReference } != null return when (typeRefParent) { is KtSuperTypeEntry -> listOfNotNull( ClassKind.INTERFACE, if (typeRefParent.classExpected()) ClassKind.PLAIN_CLASS else null ) else -> ClassKind.values().filter { val noTypeArguments = element.typeArgumentsAsTypes.isEmpty() when (it) { ClassKind.OBJECT -> noTypeArguments && isQualifier ClassKind.ANNOTATION_CLASS -> noTypeArguments && !isQualifier && !isUpperBound ClassKind.ENUM_ENTRY -> false ClassKind.ENUM_CLASS -> noTypeArguments && !isUpperBound else -> true } } } } private fun KtSuperTypeEntry.classExpected(): Boolean { val containingClass = getStrictParentOfType<KtClass>() ?: return false return !containingClass.hasModifier(KtTokens.ANNOTATION_KEYWORD) && !containingClass.hasModifier(KtTokens.ENUM_KEYWORD) && !containingClass.hasModifier(KtTokens.INLINE_KEYWORD) } private fun getExpectedUpperBound(element: KtUserType, context: BindingContext): KotlinType? { val projection = (element.parent as? KtTypeReference)?.parent as? KtTypeProjection ?: return null val argumentList = projection.parent as? KtTypeArgumentList ?: return null val index = argumentList.arguments.indexOf(projection) val callElement = argumentList.parent as? KtCallElement ?: return null val resolvedCall = callElement.getResolvedCall(context) ?: return null val typeParameterDescriptor = resolvedCall.candidateDescriptor.typeParameters.getOrNull(index) ?: return null if (typeParameterDescriptor.upperBounds.isEmpty()) return null return TypeIntersector.getUpperBoundsAsType(typeParameterDescriptor) } override fun extractFixData(element: KtUserType, diagnostic: Diagnostic): ClassInfo? { val name = element.referenceExpression?.getReferencedName() ?: return null val typeRefParent = element.parent.parent if (typeRefParent is KtConstructorCalleeExpression) return null val (context, module) = element.analyzeAndGetResult() val qualifier = element.qualifier?.referenceExpression val qualifierDescriptor = qualifier?.let { context[BindingContext.REFERENCE_TARGET, it] } val targetParents = getTargetParentsByQualifier(element, qualifier != null, qualifierDescriptor).ifEmpty { return null } val expectedUpperBound = getExpectedUpperBound(element, context) val anyType = module.builtIns.anyType return ClassInfo( name = name, targetParents = targetParents, expectedTypeInfo = expectedUpperBound?.let { TypeInfo.ByType(it, Variance.INVARIANT) } ?: TypeInfo.Empty, open = typeRefParent is KtSuperTypeEntry && typeRefParent.classExpected(), typeArguments = element.typeArgumentsAsTypes.map { if (it != null) TypeInfo(it, Variance.INVARIANT) else TypeInfo(anyType, Variance.INVARIANT) } ) } }
apache-2.0
86fa1fb1019bbbfffc48ec83da6609b8
51.885417
185
0.718338
5.470905
false
false
false
false
TachiWeb/TachiWeb-Server
TachiServer/src/main/java/xyz/nulldev/ts/api/http/manga/MangaFlag.kt
1
3471
/* * Copyright 2016 Andy Bao * * 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 xyz.nulldev.ts.api.http.manga import eu.kanade.tachiyomi.data.database.models.Manga import java.util.* /** * Project: TachiServer * Author: nulldev * Creation Date: 30/09/16 */ enum class MangaFlag constructor(private val flagMask: Int, vararg val flagStates: MangaFlag.FlagState) { SORT_DIRECTION(Manga.SORT_MASK, FlagState("DESCENDING", Manga.SORT_DESC), FlagState("ASCENDING", Manga.SORT_ASC)), DISPLAY_MODE(Manga.DISPLAY_MASK, FlagState("NAME", Manga.DISPLAY_NAME), FlagState("NUMBER", Manga.DISPLAY_NUMBER)), READ_FILTER(Manga.READ_MASK, FlagState("READ",Manga.SHOW_READ), FlagState("UNREAD", Manga.SHOW_UNREAD), FlagState("ALL", Manga.SHOW_ALL)), DOWNLOADED_FILTER(Manga.DOWNLOADED_MASK, FlagState("DOWNLOADED", Manga.SHOW_DOWNLOADED), FlagState("NOT_DOWNLOADED", Manga.SHOW_NOT_DOWNLOADED), FlagState("ALL", Manga.SHOW_ALL)), SORT_TYPE(Manga.SORTING_MASK, FlagState("SOURCE", Manga.SORTING_SOURCE), FlagState("NUMBER", Manga.SORTING_NUMBER)); fun findFlagState(name: String): FlagState? { for (state in flagStates) { if (state.name == name) { return state } } return null } fun findFlagState(value: Int): FlagState? { for (state in flagStates) { if (state.value == value) { return state } } return null } operator fun set(manga: Manga, state: FlagState) { setFlag(manga, state.value, flagMask) } private fun setFlag(manga: Manga, flag: Int, mask: Int) { manga.chapter_flags = manga.chapter_flags and mask.inv() or (flag and mask) } operator fun get(manga: Manga): FlagState? { return findFlagState(manga.chapter_flags and flagMask) } override fun toString(): String { return "MangaFlag{" + "flagMask=" + flagMask + ", flagStates=" + Arrays.toString(flagStates) + '}' } class FlagState internal constructor(val name: String?, val value: Int) { override fun equals(other: Any?): Boolean { if (this === other) return true if (other == null || javaClass != other.javaClass) return false val flagState = other as FlagState? return value == flagState!!.value && if (name != null) name == flagState.name else flagState.name == null } override fun hashCode(): Int { var result = if (name != null) name.hashCode() else 0 result = 31 * result + value return result } override fun toString(): String { return "FlagState{name='$name', value=$value}" } } }
apache-2.0
363d2866035f1a265591ba3fa011193c
32.057143
117
0.603572
4.212379
false
false
false
false
joaomneto/TitanCompanion
src/main/java/pt/joaomneto/titancompanion/adventurecreation/impl/AWFAdventureCreation.kt
1
1409
package pt.joaomneto.titancompanion.adventurecreation.impl import android.view.View import java.io.BufferedWriter import java.io.IOException import pt.joaomneto.titancompanion.R import pt.joaomneto.titancompanion.adventurecreation.AdventureCreation import pt.joaomneto.titancompanion.adventurecreation.impl.fragments.VitalStatisticsFragment import pt.joaomneto.titancompanion.adventurecreation.impl.fragments.awf.AWFAdventureCreationSuperpowerFragment import pt.joaomneto.titancompanion.util.AdventureFragmentRunner class AWFAdventureCreation : AdventureCreation( arrayOf( AdventureFragmentRunner(R.string.title_adventure_creation_vitalstats, VitalStatisticsFragment::class), AdventureFragmentRunner( R.string.title_adventure_creation_superpower, AWFAdventureCreationSuperpowerFragment::class ) ) ) { var superPower: String? = null @Throws(IOException::class) override fun storeAdventureSpecificValuesInFile(bw: BufferedWriter) { bw.write("heroPoints=0\n") bw.write("superPower=\n") } override fun validateCreationSpecificParameters(): String? { val sb = StringBuilder() if (this.superPower == null || this.superPower!!.isEmpty()) { sb.append(getString(R.string.aodSuperpower)) } return sb.toString() } override fun rollGamebookSpecificStats(view: View) {} }
lgpl-3.0
79289988a3f8e08f22ab3bc3d455d091
35.128205
110
0.750887
4.744108
false
false
false
false
vector-im/vector-android
vector/src/main/java/im/vector/webview/VectorWebViewClient.kt
2
2880
/* * Copyright 2018 New Vector Ltd * * 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 im.vector.webview import android.annotation.TargetApi import android.graphics.Bitmap import android.os.Build import android.webkit.WebResourceError import android.webkit.WebResourceRequest import android.webkit.WebView import android.webkit.WebViewClient /** * This class inherits from WebViewClient. It has to be used with a WebView. * It's responsible for dispatching events to the WebViewEventListener */ class VectorWebViewClient(private val eventListener: WebViewEventListener) : WebViewClient() { private var mInError: Boolean = false @TargetApi(Build.VERSION_CODES.N) override fun shouldOverrideUrlLoading(view: WebView, request: WebResourceRequest): Boolean { return shouldOverrideUrl(request.url.toString()) } override fun shouldOverrideUrlLoading(view: WebView, url: String): Boolean { return shouldOverrideUrl(url) } override fun onPageStarted(view: WebView, url: String, favicon: Bitmap?) { super.onPageStarted(view, url, favicon) mInError = false eventListener.onPageStarted(url) } override fun onPageFinished(view: WebView, url: String) { super.onPageFinished(view, url) if (!mInError) { eventListener.onPageFinished(url) } } override fun onReceivedError(view: WebView, errorCode: Int, description: String, failingUrl: String) { super.onReceivedError(view, errorCode, description, failingUrl) if (!mInError) { mInError = true eventListener.onPageError(failingUrl, errorCode, description) } } @TargetApi(Build.VERSION_CODES.N) override fun onReceivedError(view: WebView, request: WebResourceRequest, error: WebResourceError) { super.onReceivedError(view, request, error) if (!mInError) { mInError = true eventListener.onPageError(request.url.toString(), error.errorCode, error.description.toString()) } } private fun shouldOverrideUrl(url: String): Boolean { mInError = false val shouldOverrideUrlLoading = eventListener.shouldOverrideUrlLoading(url) if (!shouldOverrideUrlLoading) { eventListener.pageWillStart(url) } return shouldOverrideUrlLoading } }
apache-2.0
da3368786523086fee86dce23bb90f6a
33.710843
108
0.709722
4.721311
false
false
false
false
sg26565/hott-transmitter-config
HoTT-Util/src/main/kotlin/de/treichels/hott/util/StreamSupport.kt
1
10065
package de.treichels.hott.util import java.io.InputStream import java.io.OutputStream enum class ByteOrder { LittleEndian, BigEndian } // readByte fun InputStream.readByte() = read().toByte() fun ByteArray.readByte(offset: Int = 0) = this[offset] fun UByteArray.readByte(offset: Int = 0) = this[offset].toByte() // readUByte fun InputStream.readUByte() = read().toUByte() fun ByteArray.readUByte(offset: Int = 0) = this[offset].toUByte() fun UByteArray.readUByte(offset: Int = 0) = this[offset] // readShort fun InputStream.readShort(byteOrder: ByteOrder = ByteOrder.LittleEndian) = readUShort(byteOrder).toShort() fun ByteArray.readShort(offset: Int = 0, byteOrder: ByteOrder = ByteOrder.LittleEndian) = readUShort(offset, byteOrder).toShort() fun UByteArray.readShort(offset: Int = 0, byteOrder: ByteOrder = ByteOrder.LittleEndian) = readUShort(offset, byteOrder).toShort() // readUShort fun InputStream.readUShort(byteOrder: ByteOrder = ByteOrder.LittleEndian) = when (byteOrder) { ByteOrder.LittleEndian -> (readUByte() + (readUByte().toUShort() shl 8)).toUShort() ByteOrder.BigEndian -> ((readUByte().toUShort() shl 8) + readUByte()).toUShort() } fun ByteArray.readUShort(offset: Int = 0, byteOrder: ByteOrder = ByteOrder.LittleEndian) = when (byteOrder) { ByteOrder.LittleEndian -> (readUByte(offset) + (readUByte(offset + 1).toUShort() shl 8)).toUShort() ByteOrder.BigEndian -> ((readUByte(offset).toUShort() shl 8) + readUByte(offset + 1)).toUShort() } fun UByteArray.readUShort(offset: Int = 0, byteOrder: ByteOrder = ByteOrder.LittleEndian) = when (byteOrder) { ByteOrder.LittleEndian -> (readUByte(offset) + (readUByte(offset + 1).toUShort() shl 8)).toUShort() ByteOrder.BigEndian -> ((readUByte(offset).toUShort() shl 8) + readUByte(offset + 1)).toUShort() } // readInt fun InputStream.readInt(byteOrder: ByteOrder = ByteOrder.LittleEndian) = readUInt(byteOrder).toInt() fun ByteArray.readInt(offset: Int = 0, byteOrder: ByteOrder = ByteOrder.LittleEndian) = readUInt(offset, byteOrder).toInt() fun UByteArray.readInt(offset: Int = 0, byteOrder: ByteOrder = ByteOrder.LittleEndian) = readUInt(offset, byteOrder).toInt() // readUInt fun InputStream.readUInt(byteOrder: ByteOrder = ByteOrder.LittleEndian) = when (byteOrder) { ByteOrder.LittleEndian -> readUShort() + (readUShort().toUInt() shl 16) ByteOrder.BigEndian -> (readUShort().toUInt() shl 16) + readUShort() } fun ByteArray.readUInt(offset: Int = 0, byteOrder: ByteOrder = ByteOrder.LittleEndian) = when (byteOrder) { ByteOrder.LittleEndian -> readUShort(offset) + (readUShort(offset + 2).toUInt() shl 16) ByteOrder.BigEndian -> (readUShort(offset).toUInt() shl 16) + readUShort(offset + 2) } fun UByteArray.readUInt(offset: Int = 0, byteOrder: ByteOrder = ByteOrder.LittleEndian) = when (byteOrder) { ByteOrder.LittleEndian -> readUShort(offset) + (readUShort(offset + 2).toUInt() shl 16) ByteOrder.BigEndian -> (readUShort(offset).toUInt() shl 16) + readUShort(offset + 2) } // readLong fun InputStream.readLong(byteOrder: ByteOrder = ByteOrder.LittleEndian) = readULong(byteOrder).toLong() fun ByteArray.readLong(offset: Int = 0, byteOrder: ByteOrder = ByteOrder.LittleEndian) = readULong(offset, byteOrder).toLong() fun UByteArray.readLong(offset: Int = 0, byteOrder: ByteOrder = ByteOrder.LittleEndian) = readULong(offset, byteOrder).toLong() // readULong fun InputStream.readULong(byteOrder: ByteOrder = ByteOrder.LittleEndian) = when (byteOrder) { ByteOrder.LittleEndian -> readUInt() + (readUInt().toULong() shl 32) ByteOrder.BigEndian -> (readUInt().toULong() shl 32) + readUInt() } fun ByteArray.readULong(offset: Int = 0, byteOrder: ByteOrder = ByteOrder.LittleEndian) = when (byteOrder) { ByteOrder.LittleEndian -> readUInt(offset) + (readUInt(offset + 4).toULong() shl 32) ByteOrder.BigEndian -> (readUInt(offset).toULong() shl 32) + readUInt(offset + 4) } fun UByteArray.readULong(offset: Int = 0, byteOrder: ByteOrder = ByteOrder.LittleEndian) = when (byteOrder) { ByteOrder.LittleEndian -> readUInt(offset) + (readUInt(offset + 4).toULong() shl 32) ByteOrder.BigEndian -> (readUInt(offset).toULong() shl 32) + readUInt(offset + 4) } // writeByte fun OutputStream.writeByte(byte: Byte) = writeUByte(byte.toUByte()) fun ByteArray.writeByte(byte: Byte, offset: Int = 0) { this[offset] = byte } fun UByteArray.writeByte(byte: Byte, offset: Int = 0) { this[offset] = byte.toUByte() } // writeUByte fun OutputStream.writeUByte(ubyte: UByte) = write(ubyte.toInt()) fun ByteArray.writeUByte(ubyte: UByte, offset: Int = 0) { this[offset] = ubyte.toByte() } fun UByteArray.writeUByte(ubyte: UByte, offset: Int = 0) { this[offset] = ubyte } // writeShort fun OutputStream.writeShort(short: Short, byteOrder: ByteOrder = ByteOrder.LittleEndian) = writeUShort(short.toUShort(), byteOrder) fun ByteArray.writeShort(short: Short, offset: Int = 0, byteOrder: ByteOrder = ByteOrder.LittleEndian) = writeUShort(short.toUShort(), offset, byteOrder) fun UByteArray.writeShort(short: Short, offset: Int = 0, byteOrder: ByteOrder = ByteOrder.LittleEndian) = writeUShort(short.toUShort(), offset, byteOrder) // writeUShort fun OutputStream.writeUShort(short: UShort, byteOrder: ByteOrder = ByteOrder.LittleEndian) { when (byteOrder) { ByteOrder.LittleEndian -> { writeUByte(short.toUByte()) writeUByte((short shr 8).toUByte()) } ByteOrder.BigEndian -> { writeUByte((short shr 8).toUByte()) writeUByte(short.toUByte()) } } } fun ByteArray.writeUShort(ushort: UShort, offset: Int = 0, byteOrder: ByteOrder = ByteOrder.LittleEndian) { when (byteOrder) { ByteOrder.LittleEndian -> { writeUByte(ushort.toUByte(), offset) writeUByte((ushort shr 8).toUByte(), offset + 1) } ByteOrder.BigEndian -> { writeUByte((ushort shr 8).toUByte(), offset) writeUByte(ushort.toUByte(), offset + 1) } } } fun UByteArray.writeUShort(ushort: UShort, offset: Int = 0, byteOrder: ByteOrder = ByteOrder.LittleEndian) { when (byteOrder) { ByteOrder.LittleEndian -> { writeUByte(ushort.toUByte(), offset) writeUByte((ushort shr 8).toUByte(), offset + 1) } ByteOrder.BigEndian -> { writeUByte((ushort shr 8).toUByte(), offset) writeUByte(ushort.toUByte(), offset + 1) } } } // writeInt fun OutputStream.writeInt(int: Int, byteOrder: ByteOrder = ByteOrder.LittleEndian) = writeUInt(int.toUInt(), byteOrder) fun ByteArray.writeInt(int: Int, offset: Int = 0, byteOrder: ByteOrder = ByteOrder.LittleEndian) = writeUInt(int.toUInt(), offset, byteOrder) fun UByteArray.writeInt(int: Int, offset: Int = 0, byteOrder: ByteOrder = ByteOrder.LittleEndian) = writeUInt(int.toUInt(), offset, byteOrder) // writeUInt fun OutputStream.writeUInt(uint: UInt, byteOrder: ByteOrder = ByteOrder.LittleEndian) { when (byteOrder) { ByteOrder.LittleEndian -> { writeUShort(uint.toUShort()) writeUShort((uint shr 16).toUShort()) } ByteOrder.BigEndian -> { writeUShort((uint shr 16).toUShort()) writeUShort(uint.toUShort()) } } } fun ByteArray.writeUInt(uint: UInt, offset: Int = 0, byteOrder: ByteOrder = ByteOrder.LittleEndian) { when (byteOrder) { ByteOrder.LittleEndian -> { writeUShort(uint.toUShort(), offset) writeUShort((uint shr 16).toUShort(), offset + 2) } ByteOrder.BigEndian -> { writeUShort((uint shr 16).toUShort(), offset) writeUShort(uint.toUShort(), offset + 2) } } } fun UByteArray.writeUInt(uint: UInt, offset: Int = 0, byteOrder: ByteOrder = ByteOrder.LittleEndian) { when (byteOrder) { ByteOrder.LittleEndian -> { writeUShort(uint.toUShort(), offset) writeUShort((uint shr 16).toUShort(), offset + 2) } ByteOrder.BigEndian -> { writeUShort((uint shr 16).toUShort(), offset) writeUShort(uint.toUShort(), offset + 2) } } } // writeLong fun OutputStream.writeLong(long: Long, byteOrder: ByteOrder = ByteOrder.LittleEndian) = writeULong(long.toULong(), byteOrder) fun ByteArray.writeLong(long: Long, offset: Int = 0, byteOrder: ByteOrder = ByteOrder.LittleEndian) = writeULong(long.toULong(), offset, byteOrder) fun UByteArray.writeLong(long: Long, offset: Int = 0, byteOrder: ByteOrder = ByteOrder.LittleEndian) = writeULong(long.toULong(), offset, byteOrder) // writeULong fun OutputStream.writeULong(ulong: ULong, byteOrder: ByteOrder = ByteOrder.LittleEndian) { when (byteOrder) { ByteOrder.LittleEndian -> { writeUInt(ulong.toUInt()) writeUInt((ulong shr 32).toUInt()) } ByteOrder.BigEndian -> { writeUInt((ulong shr 32).toUInt()) writeUInt(ulong.toUInt()) } } } fun ByteArray.writeULong(ulong: ULong, offset: Int = 0, byteOrder: ByteOrder = ByteOrder.LittleEndian) { when (byteOrder) { ByteOrder.LittleEndian -> { writeUInt(ulong.toUInt(), offset) writeUInt((ulong shr 32).toUInt(), offset + 4) } ByteOrder.BigEndian -> { writeUInt((ulong shr 32).toUInt(), offset) writeUInt(ulong.toUInt(), offset + 4) } } } fun UByteArray.writeULong(ulong: ULong, offset: Int = 0, byteOrder: ByteOrder = ByteOrder.LittleEndian) { when (byteOrder) { ByteOrder.LittleEndian -> { writeUInt(ulong.toUInt(), offset) writeUInt((ulong shr 32).toUInt(), offset + 4) } ByteOrder.BigEndian -> { writeUInt((ulong shr 32).toUInt(), offset) writeUInt(ulong.toUInt(), offset + 4) } } } infix fun UShort.shl(bits: Int) = this.toUInt().shl(bits).toUShort() infix fun UShort.shr(bits: Int) = this.toUInt().shr(bits).toUShort()
lgpl-3.0
a3bb68e546f2a654dac5e7a31474ef0c
38.011628
154
0.67541
3.961039
false
false
false
false
fossasia/rp15
app/src/main/java/org/fossasia/openevent/general/attendees/AttendeeFragment.kt
1
38370
package org.fossasia.openevent.general.attendees import androidx.appcompat.app.AlertDialog import android.content.Context import android.os.Bundle import android.os.CountDownTimer import android.telephony.TelephonyManager import android.text.Editable import android.text.Spannable import android.text.SpannableStringBuilder import android.text.TextPaint import android.text.method.LinkMovementMethod import android.text.style.ClickableSpan import android.text.TextWatcher import android.view.LayoutInflater import android.view.MenuItem import android.view.View import android.view.ViewGroup import android.widget.AdapterView import android.widget.ArrayAdapter import androidx.core.view.isVisible import androidx.fragment.app.Fragment import androidx.lifecycle.Observer import androidx.recyclerview.widget.LinearLayoutManager import androidx.navigation.Navigation.findNavController import androidx.navigation.fragment.navArgs import com.stripe.android.Stripe import com.stripe.android.TokenCallback import com.stripe.android.model.Card import com.stripe.android.model.Token import kotlinx.android.synthetic.main.fragment_attendee.view.cvc import kotlinx.android.synthetic.main.fragment_attendee.view.email import kotlinx.android.synthetic.main.fragment_attendee.view.firstName import kotlinx.android.synthetic.main.fragment_attendee.view.helloUser import kotlinx.android.synthetic.main.fragment_attendee.view.lastName import kotlinx.android.synthetic.main.fragment_attendee.view.billingPostalCode import kotlinx.android.synthetic.main.fragment_attendee.view.attendeeScrollView import kotlinx.android.synthetic.main.fragment_attendee.view.accept import kotlinx.android.synthetic.main.fragment_attendee.view.amount import kotlinx.android.synthetic.main.fragment_attendee.view.attendeeRecycler import kotlinx.android.synthetic.main.fragment_attendee.view.eventName import kotlinx.android.synthetic.main.fragment_attendee.view.offlinePayment import kotlinx.android.synthetic.main.fragment_attendee.view.offlinePaymentDescription import kotlinx.android.synthetic.main.fragment_attendee.view.month import kotlinx.android.synthetic.main.fragment_attendee.view.monthText import kotlinx.android.synthetic.main.fragment_attendee.view.paymentSelector import kotlinx.android.synthetic.main.fragment_attendee.view.paymentSelectorContainer import kotlinx.android.synthetic.main.fragment_attendee.view.qty import kotlinx.android.synthetic.main.fragment_attendee.view.register import kotlinx.android.synthetic.main.fragment_attendee.view.signOut import kotlinx.android.synthetic.main.fragment_attendee.view.stripePayment import kotlinx.android.synthetic.main.fragment_attendee.view.ticketDetails import kotlinx.android.synthetic.main.fragment_attendee.view.ticketsRecycler import kotlinx.android.synthetic.main.fragment_attendee.view.time import kotlinx.android.synthetic.main.fragment_attendee.view.ticketTableDetails import kotlinx.android.synthetic.main.fragment_attendee.view.year import kotlinx.android.synthetic.main.fragment_attendee.view.yearText import kotlinx.android.synthetic.main.fragment_attendee.view.cardNumber import kotlinx.android.synthetic.main.fragment_attendee.view.acceptCheckbox import kotlinx.android.synthetic.main.fragment_attendee.view.countryPicker import kotlinx.android.synthetic.main.fragment_attendee.view.billingInfoContainer import kotlinx.android.synthetic.main.fragment_attendee.view.billingCity import kotlinx.android.synthetic.main.fragment_attendee.view.billingCompany import kotlinx.android.synthetic.main.fragment_attendee.view.taxId import kotlinx.android.synthetic.main.fragment_attendee.view.billingAddress import kotlinx.android.synthetic.main.fragment_attendee.view.firstNameLayout import kotlinx.android.synthetic.main.fragment_attendee.view.lastNameLayout import kotlinx.android.synthetic.main.fragment_attendee.view.emailLayout import kotlinx.android.synthetic.main.fragment_attendee.view.billingCompanyLayout import kotlinx.android.synthetic.main.fragment_attendee.view.billingAddressLayout import kotlinx.android.synthetic.main.fragment_attendee.view.cvcLayout import kotlinx.android.synthetic.main.fragment_attendee.view.billingCityLayout import kotlinx.android.synthetic.main.fragment_attendee.view.billingPostalCodeLayout import kotlinx.android.synthetic.main.fragment_attendee.view.cardNumberLayout import kotlinx.android.synthetic.main.fragment_attendee.view.sameBuyerCheckBox import kotlinx.android.synthetic.main.fragment_attendee.view.timeoutTextView import kotlinx.android.synthetic.main.fragment_attendee.view.timeoutCounterLayout import kotlinx.android.synthetic.main.fragment_attendee.view.timeoutInfoTextView import kotlinx.android.synthetic.main.fragment_attendee.view.signInPasswordLayout import kotlinx.android.synthetic.main.fragment_attendee.view.signInPassword import kotlinx.android.synthetic.main.fragment_attendee.view.loginButton import kotlinx.android.synthetic.main.fragment_attendee.view.cancelButton import kotlinx.android.synthetic.main.fragment_attendee.view.signInEmailLayout import kotlinx.android.synthetic.main.fragment_attendee.view.signInEmail import kotlinx.android.synthetic.main.fragment_attendee.view.signInEditLayout import kotlinx.android.synthetic.main.fragment_attendee.view.signInText import kotlinx.android.synthetic.main.fragment_attendee.view.signInTextLayout import kotlinx.android.synthetic.main.fragment_attendee.view.signInLayout import kotlinx.android.synthetic.main.fragment_attendee.view.signOutLayout import kotlinx.android.synthetic.main.fragment_attendee.view.paymentTitle import org.fossasia.openevent.general.BuildConfig import org.fossasia.openevent.general.R import org.fossasia.openevent.general.auth.User import org.fossasia.openevent.general.event.Event import org.fossasia.openevent.general.event.EventId import org.fossasia.openevent.general.event.EventUtils import org.fossasia.openevent.general.order.Charge import org.fossasia.openevent.general.ticket.TicketDetailsRecyclerAdapter import org.fossasia.openevent.general.ticket.TicketId import org.fossasia.openevent.general.utils.Utils import org.fossasia.openevent.general.utils.Utils.isNetworkConnected import org.fossasia.openevent.general.utils.extensions.nonNull import org.fossasia.openevent.general.utils.nullToEmpty import org.koin.androidx.viewmodel.ext.android.viewModel import org.fossasia.openevent.general.ComplexBackPressFragment import org.fossasia.openevent.general.utils.StringUtils.getTermsAndPolicyText import org.fossasia.openevent.general.utils.Utils.setToolbar import org.fossasia.openevent.general.utils.Utils.show import org.fossasia.openevent.general.utils.setRequired import org.fossasia.openevent.general.utils.checkEmpty import org.fossasia.openevent.general.utils.checkValidEmail import org.jetbrains.anko.design.longSnackbar import org.jetbrains.anko.design.snackbar import java.util.Calendar import java.util.Currency import kotlin.collections.ArrayList class AttendeeFragment : Fragment(), ComplexBackPressFragment { private lateinit var rootView: View private val attendeeViewModel by viewModel<AttendeeViewModel>() private val ticketsRecyclerAdapter: TicketDetailsRecyclerAdapter = TicketDetailsRecyclerAdapter() private val attendeeRecyclerAdapter: AttendeeRecyclerAdapter = AttendeeRecyclerAdapter() private val safeArgs: AttendeeFragmentArgs by navArgs() private lateinit var timer: CountDownTimer private lateinit var card: Card private var showBillingInfoLayout = false override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) if (attendeeViewModel.ticketIdAndQty == null) { attendeeViewModel.ticketIdAndQty = safeArgs.ticketIdAndQty?.value attendeeViewModel.singleTicket = safeArgs.ticketIdAndQty?.value?.map { it.second }?.sum() == 1 } showBillingInfoLayout = safeArgs.hasPaidTickets || safeArgs.amount > 0 attendeeRecyclerAdapter.setEventId(safeArgs.eventId) if (attendeeViewModel.paymentCurrency.isNotBlank()) ticketsRecyclerAdapter.setCurrency(attendeeViewModel.paymentCurrency) safeArgs.ticketIdAndQty?.value?.let { val quantities = it.map { pair -> pair.second }.filter { it != 0 } val donations = it.filter { it.second != 0 }.map { pair -> pair.third * pair.second } ticketsRecyclerAdapter.setQuantity(quantities) ticketsRecyclerAdapter.setDonations(donations) attendeeRecyclerAdapter.setQuantity(quantities) } attendeeViewModel.forms.value?.let { attendeeRecyclerAdapter.setCustomForm(it) } } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { rootView = inflater.inflate(R.layout.fragment_attendee, container, false) setToolbar(activity, getString(R.string.attendee_details)) setHasOptionsMenu(true) attendeeViewModel.message .nonNull() .observe(viewLifecycleOwner, Observer { rootView.longSnackbar(it) }) val progressDialog = Utils.progressDialog(context, getString(R.string.creating_order_message)) attendeeViewModel.progress .nonNull() .observe(viewLifecycleOwner, Observer { progressDialog.show(it) }) rootView.sameBuyerCheckBox.setOnCheckedChangeListener { _, isChecked -> if (isChecked) { val firstName = rootView.firstName.text.toString() val lastName = rootView.lastName.text.toString() if (firstName.isEmpty() || lastName.isEmpty()) { rootView.longSnackbar(getString(R.string.fill_required_fields_message)) rootView.sameBuyerCheckBox.isChecked = false return@setOnCheckedChangeListener } attendeeRecyclerAdapter.setFirstAttendee( Attendee(firstname = firstName, lastname = lastName, email = rootView.email.text.toString(), id = attendeeViewModel.getId()) ) } else { attendeeRecyclerAdapter.setFirstAttendee(null) } } setupEventInfo() setupPendingOrder() setupTicketDetailTable() setupSignOutLogIn() setupAttendeeDetails() setupCustomForms() setupBillingInfo() setupCountryOptions() setupCardNumber() setupMonthOptions() setupYearOptions() setupTermsAndCondition() setupRegisterOrder() return rootView } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) val attendeeDetailChangeListener = object : AttendeeDetailChangeListener { override fun onAttendeeDetailChanged(attendee: Attendee, position: Int) { attendeeViewModel.attendees[position] = attendee } } attendeeRecyclerAdapter.apply { attendeeChangeListener = attendeeDetailChangeListener } } override fun onResume() { super.onResume() if (!isNetworkConnected(context)) { rootView.attendeeScrollView.longSnackbar(getString(R.string.no_internet_connection_message)) } } override fun onDestroyView() { super.onDestroyView() attendeeRecyclerAdapter.attendeeChangeListener = null } override fun onDestroy() { super.onDestroy() if (this::timer.isInitialized) timer.cancel() } override fun handleBackPress() { AlertDialog.Builder(requireContext()) .setTitle(getString(R.string.cancel_order)) .setMessage(getString(R.string.cancel_order_message)) .setPositiveButton(getString(R.string.cancel_order_button)) { _, _ -> findNavController(rootView).popBackStack() }.setNeutralButton(getString(R.string.continue_order_button)) { dialog, _ -> dialog.cancel() }.create() .show() } private fun setupEventInfo() { attendeeViewModel.event .nonNull() .observe(viewLifecycleOwner, Observer { loadEventDetailsUI(it) setupPaymentOptions(it) }) attendeeViewModel.getSettings() attendeeViewModel.orderExpiryTime .nonNull() .observe(viewLifecycleOwner, Observer { setupCountDownTimer(it) }) val currentEvent = attendeeViewModel.event.value if (currentEvent == null) attendeeViewModel.loadEvent(safeArgs.eventId) else { setupPaymentOptions(currentEvent) loadEventDetailsUI(currentEvent) } rootView.register.text = if (safeArgs.amount > 0) getString(R.string.pay_now) else getString(R.string.register) } private fun setupPendingOrder() { val currentPendingOrder = attendeeViewModel.pendingOrder.value if (currentPendingOrder == null) { attendeeViewModel.initializeOrder(safeArgs.eventId) } } private fun setupCountDownTimer(orderExpiryTime: Int) { rootView.timeoutCounterLayout.isVisible = true rootView.timeoutInfoTextView.text = getString(R.string.ticket_timeout_info_message, orderExpiryTime.toString()) val timeLeft: Long = if (attendeeViewModel.timeout == -1L) orderExpiryTime * 60 * 1000L else attendeeViewModel.timeout timer = object : CountDownTimer(timeLeft, 1000) { override fun onFinish() { findNavController(rootView).navigate(AttendeeFragmentDirections .actionAttendeeToTicketPop(safeArgs.eventId, safeArgs.currency, true)) } override fun onTick(millisUntilFinished: Long) { attendeeViewModel.timeout = millisUntilFinished val minutes = millisUntilFinished / 1000 / 60 val seconds = millisUntilFinished / 1000 % 60 rootView.timeoutTextView.text = "$minutes:$seconds" } } timer.start() } private fun setupTicketDetailTable() { attendeeViewModel.ticketIdAndQty?.map { it.second }?.sum()?.let { rootView.qty.text = resources.getQuantityString(R.plurals.order_quantity_item, it, it) } rootView.ticketsRecycler.layoutManager = LinearLayoutManager(activity) rootView.ticketsRecycler.adapter = ticketsRecyclerAdapter rootView.ticketsRecycler.isNestedScrollingEnabled = false rootView.ticketTableDetails.setOnClickListener { attendeeViewModel.ticketDetailsVisible = !attendeeViewModel.ticketDetailsVisible loadTicketDetailsTableUI(attendeeViewModel.ticketDetailsVisible) } loadTicketDetailsTableUI(attendeeViewModel.ticketDetailsVisible) attendeeViewModel.totalAmount.value = safeArgs.amount rootView.paymentSelectorContainer.isVisible = safeArgs.amount > 0 attendeeViewModel.tickets .nonNull() .observe(viewLifecycleOwner, Observer { tickets -> ticketsRecyclerAdapter.addAll(tickets) attendeeRecyclerAdapter.addAllTickets(tickets) }) val currentTickets = attendeeViewModel.tickets.value if (currentTickets != null) { rootView.paymentSelector.isVisible = safeArgs.amount > 0 ticketsRecyclerAdapter.addAll(currentTickets) attendeeRecyclerAdapter.addAllTickets(currentTickets) } else { attendeeViewModel.getTickets() } } private fun setupSignOutLogIn() { rootView.signInEmailLayout.setRequired() rootView.signInPasswordLayout.setRequired() rootView.firstNameLayout.setRequired() rootView.lastNameLayout.setRequired() rootView.emailLayout.setRequired() setupSignInLayout() setupUser() setupLoginSignoutClickListener() attendeeViewModel.signedIn .nonNull() .observe(viewLifecycleOwner, Observer { signedIn -> rootView.signInLayout.isVisible = !signedIn rootView.signOutLayout.isVisible = signedIn if (signedIn) { rootView.sameBuyerCheckBox.isVisible = true attendeeViewModel.loadUser() } else { attendeeViewModel.isShowingSignInText = true handleSignedOut() } }) if (attendeeViewModel.isLoggedIn()) { rootView.signInLayout.isVisible = false rootView.signOutLayout.isVisible = true rootView.sameBuyerCheckBox.isVisible = true val currentUser = attendeeViewModel.user.value if (currentUser == null) attendeeViewModel.loadUser() else loadUserUI(currentUser) } else { handleSignedOut() } } private fun handleSignedOut() { rootView.signInEditLayout.isVisible = !attendeeViewModel.isShowingSignInText rootView.signInTextLayout.isVisible = attendeeViewModel.isShowingSignInText rootView.email.setText("") rootView.firstName.setText("") rootView.lastName.setText("") rootView.sameBuyerCheckBox.isChecked = false rootView.sameBuyerCheckBox.isVisible = false } private fun setupSignInLayout() { val stringBuilder = SpannableStringBuilder() val signIn = getString(R.string.sign_in) val signInForOrderText = getString(R.string.sign_in_order_text) stringBuilder.append(signIn) stringBuilder.append(" $signInForOrderText") val signInSpan = object : ClickableSpan() { override fun onClick(widget: View) { rootView.signInTextLayout.isVisible = false rootView.signInEditLayout.isVisible = true attendeeViewModel.isShowingSignInText = false } override fun updateDrawState(ds: TextPaint) { super.updateDrawState(ds) ds.isUnderlineText = false } } stringBuilder.setSpan(signInSpan, 0, signIn.length + 1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE) rootView.signInText.text = stringBuilder rootView.signInText.movementMethod = LinkMovementMethod.getInstance() } private fun setupLoginSignoutClickListener() { rootView.cancelButton.setOnClickListener { rootView.signInTextLayout.isVisible = true rootView.signInEditLayout.isVisible = false attendeeViewModel.isShowingSignInText = true } rootView.loginButton.setOnClickListener { if (rootView.signInEmail.checkEmpty() && rootView.signInEmail.checkValidEmail() && rootView.signInPassword.checkEmpty()) attendeeViewModel.login(rootView.signInEmail.text.toString(), rootView.signInPassword.text.toString()) } rootView.signOut.setOnClickListener { if (!isNetworkConnected(context)) { rootView.snackbar(getString(R.string.no_internet_connection_message)) return@setOnClickListener } attendeeViewModel.logOut() } } private fun setupUser() { attendeeViewModel.user .nonNull() .observe(viewLifecycleOwner, Observer { user -> loadUserUI(user) if (attendeeViewModel.singleTicket) { val pos = attendeeViewModel.ticketIdAndQty?.map { it.second }?.indexOf(1) val ticket = pos?.let { it1 -> attendeeViewModel.ticketIdAndQty?.get(it1)?.first?.toLong() } ?: -1 val attendee = Attendee(id = attendeeViewModel.getId(), firstname = rootView.firstName.text.toString(), lastname = rootView.lastName.text.toString(), email = rootView.email.text.toString(), ticket = TicketId(ticket), event = EventId(safeArgs.eventId)) attendeeViewModel.attendees.clear() attendeeViewModel.attendees.add(attendee) } }) } private fun setupAttendeeDetails() { rootView.attendeeRecycler.layoutManager = LinearLayoutManager(activity) rootView.attendeeRecycler.adapter = attendeeRecyclerAdapter rootView.attendeeRecycler.isNestedScrollingEnabled = false if (attendeeViewModel.attendees.isEmpty()) { attendeeViewModel.ticketIdAndQty?.let { it.forEach { pair -> repeat(pair.second) { attendeeViewModel.attendees.add(Attendee( id = attendeeViewModel.getId(), firstname = "", lastname = "", email = "", ticket = TicketId(pair.first.toLong()), event = EventId(safeArgs.eventId) )) } } } } attendeeRecyclerAdapter.addAllAttendees(attendeeViewModel.attendees) } private fun setupCustomForms() { attendeeViewModel.forms .nonNull() .observe(viewLifecycleOwner, Observer { attendeeRecyclerAdapter.setCustomForm(it) }) val currentForms = attendeeViewModel.forms.value if (currentForms == null) { attendeeViewModel.getCustomFormsForAttendees(safeArgs.eventId) } else { attendeeRecyclerAdapter.setCustomForm(currentForms) } } private fun setupBillingInfo() { rootView.billingInfoContainer.isVisible = showBillingInfoLayout attendeeViewModel.billingEnabled = showBillingInfoLayout rootView.billingCompanyLayout.setRequired() rootView.billingAddressLayout.setRequired() rootView.billingCityLayout.setRequired() rootView.billingPostalCodeLayout.setRequired() } private fun setupCountryOptions() { ArrayAdapter.createFromResource( requireContext(), R.array.country_arrays, android.R.layout.simple_spinner_dropdown_item ).also { adapter -> rootView.countryPicker.adapter = adapter if (attendeeViewModel.countryPosition == -1) autoSetCurrentCountry() else rootView.countryPicker.setSelection(attendeeViewModel.countryPosition) } rootView.countryPicker.onItemSelectedListener = object : AdapterView.OnItemSelectedListener { override fun onNothingSelected(parent: AdapterView<*>?) { /*Do nothing*/ } override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) { attendeeViewModel.countryPosition = position } } } private fun setupPaymentOptions(event: Event) { val paymentOptions = ArrayList<String>() if (event.canPayByPaypal) paymentOptions.add(getString(R.string.paypal)) if (event.canPayByStripe) paymentOptions.add(getString(R.string.stripe)) if (event.canPayOnsite) paymentOptions.add(getString(R.string.on_site)) if (event.canPayByBank) paymentOptions.add(getString(R.string.bank_transfer)) if (event.canPayByCheque) paymentOptions.add(getString(R.string.cheque)) rootView.paymentSelector.adapter = ArrayAdapter(requireContext(), android.R.layout.simple_spinner_dropdown_item, paymentOptions) rootView.paymentSelector.onItemSelectedListener = object : AdapterView.OnItemSelectedListener { override fun onNothingSelected(p0: AdapterView<*>?) { /*Do nothing*/ } override fun onItemSelected(p0: AdapterView<*>?, p1: View?, position: Int, p3: Long) { attendeeViewModel.selectedPaymentOption = position when (position) { paymentOptions.indexOf(getString(R.string.stripe)) -> { rootView.stripePayment.isVisible = true rootView.offlinePayment.isVisible = false } paymentOptions.indexOf(getString(R.string.on_site)) -> { rootView.offlinePayment.isVisible = true rootView.stripePayment.isVisible = false rootView.offlinePaymentDescription.text = event.onsiteDetails } paymentOptions.indexOf(getString(R.string.bank_transfer)) -> { rootView.offlinePayment.isVisible = true rootView.stripePayment.isVisible = false rootView.offlinePaymentDescription.text = event.bankDetails } paymentOptions.indexOf(getString(R.string.cheque)) -> { rootView.offlinePayment.isVisible = true rootView.stripePayment.isVisible = false rootView.offlinePaymentDescription.text = event.chequeDetails } else -> { rootView.stripePayment.isVisible = false rootView.offlinePayment.isVisible = false } } } } if (attendeeViewModel.selectedPaymentOption != -1) rootView.paymentSelector.setSelection(attendeeViewModel.selectedPaymentOption) if (paymentOptions.size == 1) { rootView.paymentSelector.isVisible = false rootView.paymentTitle.text = "${getString(R.string.payment)} ${paymentOptions[0]}" } } private fun setupCardNumber() { rootView.cardNumberLayout.setRequired() rootView.cvcLayout.setRequired() rootView.cardNumber.addTextChangedListener(object : TextWatcher { override fun afterTextChanged(s: Editable?) { /*Do Nothing*/ } override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) { /*Do Nothing*/ } override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) { if (s != null) { val cardType = Utils.getCardType(s.toString()) if (cardType == Utils.cardType.NONE) { rootView.cardNumber.error = getString(R.string.invalid_card_number_message) return } } rootView.cardNumber.error = null } }) attendeeViewModel.stripeOrderMade .nonNull() .observe(viewLifecycleOwner, Observer { if (it && this::card.isInitialized) sendToken(card) }) } private fun setupMonthOptions() { val month = mutableListOf( getString(R.string.month_string), getString(R.string.january), getString(R.string.february), getString(R.string.march), getString(R.string.april), getString(R.string.may), getString(R.string.june), getString(R.string.july), getString(R.string.august), getString(R.string.september), getString(R.string.october), getString(R.string.november), getString(R.string.december) ) rootView.month.adapter = ArrayAdapter(requireContext(), android.R.layout.simple_spinner_dropdown_item, month) rootView.month.onItemSelectedListener = object : AdapterView.OnItemSelectedListener { override fun onNothingSelected(p0: AdapterView<*>?) { /* Do nothing */ } override fun onItemSelected(p0: AdapterView<*>?, p1: View?, p2: Int, p3: Long) { attendeeViewModel.monthSelectedPosition = p2 rootView.monthText.text = month[p2] } } rootView.monthText.setOnClickListener { rootView.month.performClick() } rootView.month.setSelection(attendeeViewModel.monthSelectedPosition) } private fun setupYearOptions() { val year = ArrayList<String>() val currentYear = Calendar.getInstance().get(Calendar.YEAR) val a = currentYear + 20 for (i in currentYear..a) { year.add(i.toString()) } rootView.year.adapter = ArrayAdapter(requireContext(), android.R.layout.simple_spinner_dropdown_item, year) rootView.year.onItemSelectedListener = object : AdapterView.OnItemSelectedListener { override fun onNothingSelected(p0: AdapterView<*>?) { /* Do nothing */ } override fun onItemSelected(p0: AdapterView<*>?, p1: View?, pos: Int, p3: Long) { attendeeViewModel.yearSelectedPosition = pos rootView.yearText.text = year[pos] } } rootView.yearText.setOnClickListener { rootView.year.performClick() } rootView.year.setSelection(attendeeViewModel.yearSelectedPosition) } private fun setupTermsAndCondition() { rootView.accept.text = getTermsAndPolicyText(requireContext(), resources) rootView.accept.movementMethod = LinkMovementMethod.getInstance() } private fun checkPaymentOptions(): Boolean = when (rootView.paymentSelector.selectedItem.toString()) { getString(R.string.paypal) -> { rootView.attendeeScrollView.longSnackbar(getString(R.string.paypal_payment_not_available)) false } getString(R.string.stripe) -> { card = Card.create(rootView.cardNumber.text.toString(), attendeeViewModel.monthSelectedPosition, rootView.year.selectedItem.toString().toInt(), rootView.cvc.text.toString()) if (!card.validateCard()) { rootView.snackbar(getString(R.string.invalid_card_data_message)) false } else { true } } else -> true } private fun checkRequiredFields(): Boolean { val checkBasicInfo = rootView.firstName.checkEmpty() && rootView.lastName.checkEmpty() && rootView.email.checkEmpty() var checkBillingInfo = true if (showBillingInfoLayout) { checkBillingInfo = rootView.billingCompany.checkEmpty() && rootView.billingAddress.checkEmpty() && rootView.billingCity.checkEmpty() && rootView.billingPostalCode.checkEmpty() } var checkStripeInfo = true if (safeArgs.amount != 0F && rootView.paymentSelector.selectedItem.toString() == getString(R.string.stripe)) { checkStripeInfo = rootView.cardNumber.checkEmpty() && rootView.cvc.checkEmpty() } return checkBasicInfo && checkBillingInfo && checkAttendeesInfo() && checkStripeInfo } private fun checkAttendeesInfo(): Boolean { var valid = true for (pos in 0..attendeeRecyclerAdapter.itemCount) { val viewHolderItem = rootView.attendeeRecycler.findViewHolderForAdapterPosition(pos) if (viewHolderItem is AttendeeViewHolder) { if (!viewHolderItem.checkValidFields()) valid = false } } return valid } private fun setupRegisterOrder() { rootView.register.setOnClickListener { val currentUser = attendeeViewModel.user.value if (currentUser == null) { rootView.longSnackbar(getString(R.string.sign_in_to_order_ticket)) return@setOnClickListener } if (!isNetworkConnected(context)) { rootView.attendeeScrollView.longSnackbar(getString(R.string.no_internet_connection_message)) return@setOnClickListener } if (!rootView.acceptCheckbox.isChecked) { rootView.attendeeScrollView.longSnackbar(getString(R.string.term_and_conditions)) return@setOnClickListener } if (!checkRequiredFields()) { rootView.snackbar(R.string.fill_required_fields_message) return@setOnClickListener } if (attendeeViewModel.totalAmount.value != 0F && !checkPaymentOptions()) return@setOnClickListener val attendees = attendeeViewModel.attendees if (attendeeViewModel.areAttendeeEmailsValid(attendees)) { val country = rootView.countryPicker.selectedItem.toString() val paymentOption = if (safeArgs.amount != 0F) getPaymentMode(rootView.paymentSelector.selectedItem.toString()) else PAYMENT_MODE_FREE val company = rootView.billingCompany.text.toString() val city = rootView.billingCity.text.toString() val taxId = rootView.taxId.text.toString() val address = rootView.billingAddress.text.toString() val postalCode = rootView.billingPostalCode.text.toString() attendeeViewModel.createAttendees(attendees, country, company, taxId, address, city, postalCode, paymentOption) } else { rootView.attendeeScrollView.longSnackbar(getString(R.string.invalid_email_address_message)) } } attendeeViewModel.ticketSoldOut .nonNull() .observe(this, Observer { showTicketSoldOutDialog(it) }) attendeeViewModel.orderCompleted .nonNull() .observe(viewLifecycleOwner, Observer { if (it) openOrderCompletedFragment() }) } private fun getPaymentMode(paymentSelectedItem: String): String = when (paymentSelectedItem) { getString(R.string.cheque) -> PAYMENT_MODE_CHEQUE getString(R.string.bank_transfer) -> PAYMENT_MODE_BANK getString(R.string.stripe) -> PAYMENT_MODE_STRIPE getString(R.string.paypal) -> PAYMENT_MODE_PAYPAL getString(R.string.on_site) -> PAYMENT_MODE_ONSITE else -> PAYMENT_MODE_FREE } private fun showTicketSoldOutDialog(show: Boolean) { if (show) { val builder = AlertDialog.Builder(requireContext()) builder.setMessage(getString(R.string.tickets_sold_out)) .setPositiveButton(getString(R.string.ok)) { dialog, _ -> dialog.cancel() } builder.show() } } private fun sendToken(card: Card) { Stripe(requireContext()) .createToken(card, BuildConfig.STRIPE_API_KEY, object : TokenCallback { override fun onSuccess(token: Token) { val charge = Charge(attendeeViewModel.getId().toInt(), token.id, null) attendeeViewModel.chargeOrder(charge) } override fun onError(error: Exception) { rootView.snackbar(error.localizedMessage.toString()) } }) } private fun loadEventDetailsUI(event: Event) { val startsAt = EventUtils.getEventDateTime(event.startsAt, event.timezone) val endsAt = EventUtils.getEventDateTime(event.endsAt, event.timezone) attendeeViewModel.paymentCurrency = Currency.getInstance(event.paymentCurrency).symbol ticketsRecyclerAdapter.setCurrency(attendeeViewModel.paymentCurrency) rootView.eventName.text = event.name val total = if (safeArgs.amount > 0) "${attendeeViewModel.paymentCurrency} ${"%.2f".format(safeArgs.amount)}" else getString(R.string.free) rootView.amount.text = getString(R.string.total_amount, total) rootView.time.text = EventUtils.getFormattedDateTimeRangeDetailed(startsAt, endsAt) } private fun loadUserUI(user: User) { rootView.helloUser.text = getString(R.string.hello_user, user.firstName.nullToEmpty()) rootView.firstName.text = SpannableStringBuilder(user.firstName.nullToEmpty()) rootView.lastName.text = SpannableStringBuilder(user.lastName.nullToEmpty()) rootView.email.text = SpannableStringBuilder(user.email.nullToEmpty()) rootView.firstName.isEnabled = user.firstName.isNullOrEmpty() rootView.lastName.isEnabled = user.lastName.isNullOrEmpty() rootView.email.isEnabled = false } private fun loadTicketDetailsTableUI(show: Boolean) { if (show) { rootView.ticketDetails.isVisible = true rootView.ticketTableDetails.text = context?.getString(R.string.hide) } else { rootView.ticketDetails.isVisible = false rootView.ticketTableDetails.text = context?.getString(R.string.view) } } private fun openOrderCompletedFragment() { attendeeViewModel.orderCompleted.value = false findNavController(rootView).navigate(AttendeeFragmentDirections .actionAttendeeToOrderCompleted(safeArgs.eventId)) } override fun onOptionsItemSelected(item: MenuItem): Boolean { return when (item.itemId) { android.R.id.home -> { activity?.onBackPressed() true } else -> super.onOptionsItemSelected(item) } } private fun autoSetCurrentCountry() { val telephonyManager: TelephonyManager = activity?.getSystemService(Context.TELEPHONY_SERVICE) as TelephonyManager val currentCountryCode = telephonyManager.networkCountryIso val countryCodes = resources.getStringArray(R.array.country_code_arrays) val countryIndex = countryCodes.indexOf(currentCountryCode.toUpperCase()) if (countryIndex != -1) rootView.countryPicker.setSelection(countryIndex) } }
apache-2.0
2293a9735024c5cf57effc609e771693
43.461182
120
0.665468
5.315141
false
false
false
false
elpassion/el-abyrinth-android
core/src/main/java/pl/elpassion/elabyrinth/core/LabyrinthSocket.kt
1
1464
package pl.elpassion.elabyrinth.core import com.fasterxml.jackson.databind.JsonNode import org.phoenixframework.channels.Socket import java.util.* class LabyrinthSocket { // private val endpoint = "wss://stark-refuge-21372.herokuapp.com/socket/websocket" private val endpoint = "ws://192.168.1.143:4000/socket/websocket" val socket = Socket(endpoint) val channel by lazy { socket.connect() socket.chan("games:lobby", null).apply { this.join().receive("ok", { id = it.payload.get("response").get("id").asText() }) } } var id = "" fun move(direction: Direction) { channel.push("move_player", direction.toJsonNode()) } fun onGame(onGame: (Game) -> Unit) { channel.on("game", { onGame(Game( it.payload.get("map").map { row -> row.map { cell -> Cell.Companion.fromInt(cell.intValue()) } }, it.payload.get("players").fields().map { playerFromNode(it, id) }.sortedBy { it.self })) }) } private fun playerFromNode(entry: MutableMap.MutableEntry<String, JsonNode>, id: String): Player { return Player(entry.value.get("x").intValue(), entry.value.get("y").intValue(), entry.key == id) } } fun <T, R> Iterator<T>.map(transform: (T) -> R): List<R> { val list = ArrayList<R>() while (this.hasNext()) { list.add(transform(this.next())) } return list }
mit
1278f5f9d097f401ee69031af2dc48f0
30.847826
117
0.596995
3.641791
false
false
false
false
CALlanoR/virtual_environments
medical_etls/part3/kotlin-users-service-api/src/main/kotlin/com/puj/admincenter/service/UserService.kt
1
2839
package com.puj.admincenter.service import com.puj.admincenter.domain.users.User import com.puj.admincenter.dto.users.UserDto import com.puj.admincenter.dto.users.CreateUserDto import com.puj.admincenter.dto.IdResponseDto import com.puj.admincenter.repository.users.UserRepository import org.springframework.data.domain.Pageable import org.springframework.data.domain.Page import org.springframework.security.crypto.bcrypt.BCrypt import org.springframework.stereotype.Service import org.springframework.http.ResponseEntity import org.springframework.http.HttpStatus import org.springframework.web.bind.annotation.* import org.slf4j.LoggerFactory import java.io.Serializable import java.util.* @Service class UserService(private val userRepository: UserRepository) { companion object { val LOG = LoggerFactory.getLogger(UserService::class.java)!! } fun count(): Long { return userRepository.count() } fun getAllUsers(pageable: Pageable, authorization: String): ResponseEntity<*> { return ResponseEntity.ok(userRepository.findAll(pageable)) } fun getById(userId: Int, authorization: String): ResponseEntity<*> { val user = userRepository.findById(userId) // Hace solo el query return if (user.isPresent()) { ResponseEntity.ok(UserDto.convert(user.get())) } else { ResponseEntity<Any>(HttpStatus.NOT_FOUND) } } fun create(createUserDto: CreateUserDto): ResponseEntity<*> { if (userRepository.existsByEmail(createUserDto.email)) { val messageError = "User with email: ${createUserDto.email} already exists." LOG.error(messageError) return ResponseEntity<Any>(messageError, HttpStatus.CONFLICT) } val user = User(email = createUserDto.email, name = createUserDto.name, password = createUserDto.password, username = createUserDto.username) val userSaved = userRepository.save(user) LOG.info("User ${createUserDto.email} created with id ${userSaved.id}") val responseDto = IdResponseDto(userSaved.id.toLong()) return ResponseEntity<IdResponseDto>(responseDto, HttpStatus.CREATED) } fun delete(userId: Int): ResponseEntity<*> { val currentUser = userRepository.findById(userId); return if(currentUser.isPresent()) { userRepository.deleteUserById(userId) LOG.info("User with id $userId was deleted successfully") ResponseEntity<Any>(HttpStatus.OK) } else { LOG.error("User not found") ResponseEntity<Any>(HttpStatus.NOT_FOUND) } } }
apache-2.0
4fc2d0c059f8361ede83697caf3f04c5
35.883117
88
0.660444
4.723794
false
false
false
false
EMResearch/EvoMaster
core/src/main/kotlin/org/evomaster/core/search/gene/datetime/DateTimeGene.kt
1
6770
package org.evomaster.core.search.gene.datetime import org.evomaster.core.logging.LoggingUtil import org.evomaster.core.output.OutputFormat import org.evomaster.core.search.gene.* import org.evomaster.core.search.gene.interfaces.ComparableGene import org.evomaster.core.search.gene.root.CompositeFixedGene import org.evomaster.core.search.gene.string.StringGene import org.evomaster.core.search.gene.utils.GeneUtils import org.evomaster.core.search.impact.impactinfocollection.GeneImpact import org.evomaster.core.search.impact.impactinfocollection.value.date.DateTimeGeneImpact import org.evomaster.core.search.service.Randomness import org.evomaster.core.search.service.mutator.MutationWeightControl import org.evomaster.core.search.service.mutator.genemutation.AdditionalGeneMutationInfo import org.evomaster.core.search.service.mutator.genemutation.SubsetGeneMutationSelectionStrategy import org.slf4j.Logger import org.slf4j.LoggerFactory /** * Using RFC3339 * * https://xml2rfc.tools.ietf.org/public/rfc/html/rfc3339.html#anchor14 */ open class DateTimeGene( name: String, val date: DateGene = DateGene("date"), val time: TimeGene = TimeGene("time"), val dateTimeGeneFormat: DateTimeGeneFormat = DateTimeGeneFormat.ISO_LOCAL_DATE_TIME_FORMAT ) : ComparableGene, CompositeFixedGene(name, listOf(date, time)) { enum class DateTimeGeneFormat { // YYYY-MM-DDTHH:SS:MM ISO_LOCAL_DATE_TIME_FORMAT, // YYYY-MM-DD HH:SS:MM DEFAULT_DATE_TIME } companion object { val log: Logger = LoggerFactory.getLogger(DateTimeGene::class.java) val DATE_TIME_GENE_COMPARATOR = compareBy<DateTimeGene> { it.date } .thenBy { it.time } } override fun isLocallyValid() : Boolean{ return getViewOfChildren().all { it.isLocallyValid() } } override fun copyContent(): Gene = DateTimeGene( name, date.copy() as DateGene, time.copy() as TimeGene, dateTimeGeneFormat = this.dateTimeGeneFormat ) override fun randomize(randomness: Randomness, tryToForceNewValue: Boolean) { /** * If forceNewValue==true both date and time * get a new value, but it only might need * one to be different to get a new value. * * Shouldn't this method decide randomly if * date, time or both get a new value? */ date.randomize(randomness, tryToForceNewValue) time.randomize(randomness, tryToForceNewValue) } override fun adaptiveSelectSubsetToMutate( randomness: Randomness, internalGenes: List<Gene>, mwc: MutationWeightControl, additionalGeneMutationInfo: AdditionalGeneMutationInfo ): List<Pair<Gene, AdditionalGeneMutationInfo?>> { if (additionalGeneMutationInfo.impact != null && additionalGeneMutationInfo.impact is DateTimeGeneImpact) { val maps = mapOf<Gene, GeneImpact>( date to additionalGeneMutationInfo.impact.dateGeneImpact , time to additionalGeneMutationInfo.impact.timeGeneImpact ) return mwc.selectSubGene( internalGenes, adaptiveWeight = true, targets = additionalGeneMutationInfo.targets, impacts = internalGenes.map { i -> maps.getValue(i) }, individual = null, evi = additionalGeneMutationInfo.evi ).map { it to additionalGeneMutationInfo.copyFoInnerGene(maps.getValue(it), it) } } throw IllegalArgumentException("impact is null or not DateTimeGeneImpact") } override fun getValueAsPrintableString( previousGenes: List<Gene>, mode: GeneUtils.EscapeMode?, targetFormat: OutputFormat?, extraCheck: Boolean ): String { return "\"${getValueAsRawString()}\"" } override fun getValueAsRawString(): String { val formattedDate = GeneUtils.let { "${GeneUtils.padded(date.year.value, 4)}-${ GeneUtils.padded( date.month.value, 2 ) }-${GeneUtils.padded(date.day.value, 2)}" } val formattedTime = GeneUtils.let { "${GeneUtils.padded(time.hour.value, 2)}:${ GeneUtils.padded( time.minute.value, 2 ) }:${GeneUtils.padded(time.second.value, 2)}" } return when (dateTimeGeneFormat) { DateTimeGeneFormat.ISO_LOCAL_DATE_TIME_FORMAT -> { "${formattedDate}T${formattedTime}" } DateTimeGeneFormat.DEFAULT_DATE_TIME -> { "${formattedDate} ${formattedTime}" } } } override fun copyValueFrom(other: Gene) { if (other !is DateTimeGene) { throw IllegalArgumentException("Invalid gene type ${other.javaClass}") } this.date.copyValueFrom(other.date) this.time.copyValueFrom(other.time) } override fun containsSameValueAs(other: Gene): Boolean { if (other !is DateTimeGene) { throw IllegalArgumentException("Invalid gene type ${other.javaClass}") } return this.date.containsSameValueAs(other.date) && this.time.containsSameValueAs(other.time) } override fun bindValueBasedOn(gene: Gene): Boolean { return when { gene is DateTimeGene -> { date.bindValueBasedOn(gene.date) && time.bindValueBasedOn(gene.time) } gene is DateGene -> date.bindValueBasedOn(gene) gene is TimeGene -> time.bindValueBasedOn(gene) gene is StringGene && gene.getSpecializationGene() != null -> { bindValueBasedOn(gene.getSpecializationGene()!!) } gene is SeededGene<*> -> this.bindValueBasedOn(gene.getPhenotype()as Gene) else -> { LoggingUtil.uniqueWarn(log, "cannot bind DateTimeGene with ${gene::class.java.simpleName}") false } } } override fun compareTo(other: ComparableGene): Int { if (other !is DateTimeGene) { throw ClassCastException("Instance of DateTimeGene was expected but ${other::javaClass} was found") } return DATE_TIME_GENE_COMPARATOR.compare(this, other) } override fun customShouldApplyShallowMutation( randomness: Randomness, selectionStrategy: SubsetGeneMutationSelectionStrategy, enableAdaptiveGeneMutation: Boolean, additionalGeneMutationInfo: AdditionalGeneMutationInfo? ): Boolean { return false } }
lgpl-3.0
3a290e77625767efc42bc25e30021743
34.825397
115
0.639734
4.877522
false
false
false
false
SofteamOuest/referentiel-personnes-api
src/main/kotlin/com/softeam/referentielpersonnes/query/PersonnesQueryResource.kt
1
2342
package com.softeam.referentielpersonnes.query import com.softeam.referentielpersonnes.domain.Personne import org.slf4j.LoggerFactory import org.springframework.beans.factory.annotation.Autowired import org.springframework.data.domain.Pageable import org.springframework.http.MediaType import org.springframework.web.bind.annotation.* @RestController class PersonnesQueryResource @Autowired constructor( private val personnesQueryService: PersonnesQueryService ) { private val logger = LoggerFactory.getLogger(PersonnesQueryResource::class.java) @RequestMapping( value = ["/personnes/{id}"], method = arrayOf(RequestMethod.GET), produces = arrayOf(MediaType.APPLICATION_JSON_VALUE)) private fun get(@PathVariable id: String): Personne? { logger.info("Getting Personne #$id") return personnesQueryService.get(id) } @RequestMapping( value = ["/personnes"], method = arrayOf(RequestMethod.GET), produces = arrayOf(MediaType.APPLICATION_JSON_VALUE)) @ResponseBody private fun list(pageable: Pageable): Iterable<Personne> { logger.info("Getting all Personnes, $pageable.toString()") val list = personnesQueryService.list(pageable) logger.debug("List of Personnes $list.content.toString()") return list.content } @PutMapping(path = arrayOf("/personnes/add"), produces = arrayOf(MediaType.APPLICATION_JSON_UTF8_VALUE)) fun ajouterPersonne(@RequestBody personne: Personne): Personne { logger.info("ajouterPersonne new $personne.toString()") return personnesQueryService.create(personne) } @PostMapping(path = arrayOf("/personnes/update"), produces = arrayOf(MediaType.APPLICATION_JSON_UTF8_VALUE)) fun modifierPersonne(@RequestBody personne: Personne): Personne { logger.info("modifierPersonne new $personne.toString()") return personnesQueryService.update(personne) } @RequestMapping(value = ["/personnes/delete/{id}"], method = arrayOf(RequestMethod.DELETE)) fun supprimerPersonneById(@PathVariable id: String) { logger.debug("C de Personnes $id") return personnesQueryService.delete(id) } }
apache-2.0
8812a816bd95c633bd965c511f3688dc
41.407407
116
0.683604
4.418868
false
false
false
false
BlueBoxWare/LibGDXPlugin
src/main/kotlin/com/gmail/blueboxware/libgdxplugin/filetypes/json/formatting/GdxJsonFormattingBuilderModel.kt
1
3067
package com.gmail.blueboxware.libgdxplugin.filetypes.json.formatting import com.gmail.blueboxware.libgdxplugin.filetypes.json.GdxJsonElementTypes.* import com.intellij.formatting.* import com.intellij.json.JsonLanguage import com.intellij.json.formatter.JsonCodeStyleSettings import com.intellij.lang.ASTNode import com.intellij.openapi.util.TextRange import com.intellij.psi.PsiFile import com.intellij.psi.codeStyle.CodeStyleSettings import com.intellij.psi.tree.TokenSet /* * * Adapted from https://github.com/JetBrains/intellij-community/blob/171.2152/json/src/com/intellij/json/formatter/JsonFormattingBuilderModel.java * */ class GdxJsonFormattingBuilderModel : FormattingModelBuilder { override fun getRangeAffectingIndent(file: PsiFile?, offset: Int, elementAtOffset: ASTNode?): TextRange? = null override fun createModel(formattingContext: FormattingContext): FormattingModel { val element = formattingContext.psiElement val settings = formattingContext.codeStyleSettings val customSettings = settings.getCustomSettings(JsonCodeStyleSettings::class.java) val spacingBuilder = createSpacingBuilder(settings) val block = GdxJsonBlock( null, element.node, customSettings, null, Indent.getSmartIndent(Indent.Type.CONTINUATION), null, spacingBuilder ) return FormattingModelProvider.createFormattingModelForPsiFile(element.containingFile, block, settings) } companion object { private val STRUCTURAL_ELEMENTS = TokenSet.create(ARRAY, JOBJECT, PROPERTY) private fun createSpacingBuilder(settings: CodeStyleSettings): SpacingBuilder { val jsonSettings = settings.getCustomSettings(JsonCodeStyleSettings::class.java) val commonSettings = settings.getCommonSettings(JsonLanguage.INSTANCE) val spacesBeforeComma = if (commonSettings.SPACE_BEFORE_COMMA) 1 else 0 val spacesBeforeColon = if (jsonSettings.SPACE_BEFORE_COLON) 1 else 0 val spacesAfterColon = if (jsonSettings.SPACE_AFTER_COLON) 1 else 0 return SpacingBuilder(settings, JsonLanguage.INSTANCE) .beforeInside(COLON, STRUCTURAL_ELEMENTS).spacing(spacesBeforeColon, spacesBeforeColon, 0, false, 0) .afterInside(COLON, STRUCTURAL_ELEMENTS).spacing(spacesAfterColon, spacesAfterColon, 0, false, 0) .apply { for (parent in STRUCTURAL_ELEMENTS.types) { withinPairInside(L_BRACKET, R_BRACKET, parent).spaceIf( commonSettings.SPACE_WITHIN_BRACKETS, true ) withinPairInside(L_CURLY, R_CURLY, parent).spaceIf(commonSettings.SPACE_WITHIN_BRACES, true) } } .beforeInside(COMMA, STRUCTURAL_ELEMENTS).spacing(spacesBeforeComma, spacesBeforeComma, 0, false, 0) .afterInside(COMMA, STRUCTURAL_ELEMENTS).spaceIf(commonSettings.SPACE_AFTER_COMMA) } } }
apache-2.0
5bf588e18ff54916203116008a11a116
48.467742
146
0.705249
4.829921
false
false
false
false
jrenner/kotlin-voxel
core/src/main/kotlin/org/jrenner/learngl/utils/SimpleTimer.kt
1
1060
package org.jrenner.learngl.utils import com.badlogic.gdx.utils.TimeUtils import com.badlogic.gdx.utils.GdxRuntimeException class SimpleTimer(val name: String) { var total = 0L var count = 0 var active = false private var startTime = 0L fun start() { if (active) throw GdxRuntimeException("already started!") active = true startTime = TimeUtils.nanoTime() } fun stop() { if (!active) throw GdxRuntimeException("not started!") active = false val elapsed = TimeUtils.nanoTime() - startTime total += elapsed count++ } private fun Long.fmt(): String { return "%.2f ms".format(this.toDouble() / 1000000.0) } fun report() { val avg: Long if (count == 0) { avg = -1L } else { avg = total / count } println("Timer [$name]: count: $count, total: ${total.fmt()}, average: ${avg.fmt()}") } fun reset() { total = 0L count = 0 active = false } }
apache-2.0
e9ec8dfb7cd8f108a876c7329ddab76d
20.632653
93
0.551887
4.156863
false
false
false
false
gradle/gradle
build-logic/dependency-modules/src/main/kotlin/gradlebuild/modules/extension/ExternalModulesExtension.kt
2
12522
/* * Copyright 2020 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package gradlebuild.modules.extension import gradlebuild.modules.model.License abstract class ExternalModulesExtension { val groovyVersion = "3.0.13" val configurationCacheReportVersion = "1.2" val kotlinVersion = "1.7.10" fun futureKotlin(module: String) = "org.jetbrains.kotlin:kotlin-$module:$kotlinVersion" val ansiControlSequenceUtil = "net.rubygrapefruit:ansi-control-sequence-util" val ant = "org.apache.ant:ant" val antLauncher = "org.apache.ant:ant-launcher" val asm = "org.ow2.asm:asm" val asmAnalysis = "org.ow2.asm:asm-analysis" val asmCommons = "org.ow2.asm:asm-commons" val asmTree = "org.ow2.asm:asm-tree" val asmUtil = "org.ow2.asm:asm-util" val assertj = "org.assertj:assertj-core" val awsS3Core = "com.amazonaws:aws-java-sdk-core" val awsS3Kms = "com.amazonaws:aws-java-sdk-kms" val awsS3S3 = "com.amazonaws:aws-java-sdk-s3" val awsS3Sts = "com.amazonaws:aws-java-sdk-sts" val bouncycastlePgp = "org.bouncycastle:bcpg-jdk15on" val bouncycastlePkix = "org.bouncycastle:bcpkix-jdk15on" val bouncycastleProvider = "org.bouncycastle:bcprov-jdk15on" val bsh = "org.apache-extras.beanshell:bsh" val capsule = "io.usethesource:capsule" val commonsCodec = "commons-codec:commons-codec" val commonsCompress = "org.apache.commons:commons-compress" val commonsHttpclient = "org.apache.httpcomponents:httpclient" val commonsIo = "commons-io:commons-io" val commonsLang = "commons-lang:commons-lang" val commonsLang3 = "org.apache.commons:commons-lang3" val commonsMath = "org.apache.commons:commons-math3" val configurationCacheReport = "org.gradle.buildtool.internal:configuration-cache-report:$configurationCacheReportVersion" val fastutil = "it.unimi.dsi:fastutil" val gcs = "com.google.apis:google-api-services-storage" val googleApiClient = "com.google.api-client:google-api-client" val googleHttpClient = "com.google.http-client:google-http-client" val googleHttpClientGson = "com.google.http-client:google-http-client-gson" val googleHttpClientApacheV2 = "com.google.http-client:google-http-client-apache-v2" val googleOauthClient = "com.google.oauth-client:google-oauth-client" val gradleProfiler = "org.gradle.profiler:gradle-profiler" val gradleEnterpriseTestAnnotation = "com.gradle:gradle-enterprise-testing-annotations" val groovy = "org.codehaus.groovy:groovy" val groovyAnt = "org.codehaus.groovy:groovy-ant" val groovyAstbuilder = "org.codehaus.groovy:groovy-astbuilder" val groovyConsole = "org.codehaus.groovy:groovy-console" val groovyDateUtil = "org.codehaus.groovy:groovy-dateutil" val groovyDatetime = "org.codehaus.groovy:groovy-datetime" val groovyDoc = "org.codehaus.groovy:groovy-groovydoc" val groovyJson = "org.codehaus.groovy:groovy-json" val groovyNio = "org.codehaus.groovy:groovy-nio" val groovySql = "org.codehaus.groovy:groovy-sql" val groovyTemplates = "org.codehaus.groovy:groovy-templates" val groovyTest = "org.codehaus.groovy:groovy-test" val groovyXml = "org.codehaus.groovy:groovy-xml" val gson = "com.google.code.gson:gson" val guava = "com.google.guava:guava" val hamcrest = "org.hamcrest:hamcrest-core" val httpcore = "org.apache.httpcomponents:httpcore" val inject = "javax.inject:javax.inject" val ivy = "org.apache.ivy:ivy" val jacksonAnnotations = "com.fasterxml.jackson.core:jackson-annotations" val jacksonCore = "com.fasterxml.jackson.core:jackson-core" val jacksonDatabind = "com.fasterxml.jackson.core:jackson-databind" val jakartaActivation = "com.sun.activation:jakarta.activation" val jakartaXmlBind = "jakarta.xml.bind:jakarta.xml.bind-api" val jansi = "org.fusesource.jansi:jansi" val jatl = "com.googlecode.jatl:jatl" val jaxbCore = "com.sun.xml.bind:jaxb-core" val jaxbImpl = "com.sun.xml.bind:jaxb-impl" val jcifs = "jcifs:jcifs" val jclToSlf4j = "org.slf4j:jcl-over-slf4j" val jcommander = "com.beust:jcommander" val jetbrainsAnnotations = "org.jetbrains:annotations" val jgit = "org.eclipse.jgit:org.eclipse.jgit" val joda = "joda-time:joda-time" val jsch = "com.jcraft:jsch" val jsr305 = "com.google.code.findbugs:jsr305" val julToSlf4j = "org.slf4j:jul-to-slf4j" val junit = "junit:junit" val junit5Vintage = "org.junit.vintage:junit-vintage-engine" val junit5JupiterApi = "org.junit.jupiter:junit-jupiter-api" val junitPlatform = "org.junit.platform:junit-platform-launcher" val jzlib = "com.jcraft:jzlib" val kryo = "com.esotericsoftware.kryo:kryo" val log4jToSlf4j = "org.slf4j:log4j-over-slf4j" val maven3BuilderSupport = "org.apache.maven:maven-builder-support" val maven3Model = "org.apache.maven:maven-model" val maven3RepositoryMetadata = "org.apache.maven:maven-repository-metadata" val maven3Settings = "org.apache.maven:maven-settings" val maven3SettingsBuilder = "org.apache.maven:maven-settings-builder" val minlog = "com.esotericsoftware.minlog:minlog" val nativePlatform = "net.rubygrapefruit:native-platform" val nativePlatformFileEvents = "net.rubygrapefruit:file-events" val objenesis = "org.objenesis:objenesis" val plexusCipher = "org.sonatype.plexus:plexus-cipher" val plexusInterpolation = "org.codehaus.plexus:plexus-interpolation" val plexusSecDispatcher = "org.codehaus.plexus:plexus-sec-dispatcher" val plexusUtils = "org.codehaus.plexus:plexus-utils" val plist = "com.googlecode.plist:dd-plist" val pmavenCommon = "org.sonatype.pmaven:pmaven-common" val pmavenGroovy = "org.sonatype.pmaven:pmaven-groovy" val slf4jApi = "org.slf4j:slf4j-api" val snakeyaml = "org.yaml:snakeyaml" val testng = "org.testng:testng" val tomlj = "org.tomlj:tomlj" val trove4j = "org.jetbrains.intellij.deps:trove4j" val jna = "net.java.dev.jna:jna" val agp = "com.android.tools.build:gradle" val xbeanReflect = "org.apache.xbean:xbean-reflect" val xmlApis = "xml-apis:xml-apis" // Compile only dependencies (dynamically downloaded if needed) val maven3Compat = "org.apache.maven:maven-compat" val maven3PluginApi = "org.apache.maven:maven-plugin-api" // Test classpath only libraries val aircompressor = "io.airlift:aircompressor" val archunit = "com.tngtech.archunit:archunit" val archunitJunit5 = "com.tngtech.archunit:archunit-junit5" val awaitility = "org.awaitility:awaitility-kotlin" val bytebuddy = "net.bytebuddy:byte-buddy" val bytebuddyAgent = "net.bytebuddy:byte-buddy-agent" val cglib = "cglib:cglib" val equalsverifier = "nl.jqno.equalsverifier:equalsverifier" val hikariCP = "com.zaxxer:HikariCP" val guice = "com.google.inject:guice" val httpmime = "org.apache.httpcomponents:httpmime" val jacksonKotlin = "com.fasterxml.jackson.module:jackson-module-kotlin" val javaParser = "com.github.javaparser:javaparser-core" val jetty = "org.eclipse.jetty:jetty-http" val jettySecurity = "org.eclipse.jetty:jetty-security" val jettyWebApp = "org.eclipse.jetty:jetty-webapp" val joptSimple = "net.sf.jopt-simple:jopt-simple" val jsoup = "org.jsoup:jsoup" val jtar = "org.kamranzafar:jtar" val kotlinCoroutines = "org.jetbrains.kotlinx:kotlinx-coroutines-core" val kotlinCoroutinesDebug = "org.jetbrains.kotlinx:kotlinx-coroutines-debug" val littleproxy = "xyz.rogfam:littleproxy" val mina = "org.apache.mina:mina-core" val mockitoCore = "org.mockito:mockito-core" val mockitoKotlin = "com.nhaarman:mockito-kotlin" val mockitoKotlin2 = "com.nhaarman.mockitokotlin2:mockito-kotlin" val mySqlConnector = "mysql:mysql-connector-java" val samplesCheck = "org.gradle.exemplar:samples-check" val snappy = "org.iq80.snappy:snappy" val servletApi = "javax.servlet:javax.servlet-api" val socksProxy = "com.github.bbottema:java-socks-proxy-server" val spock = "org.spockframework:spock-core" val spockJUnit4 = "org.spockframework:spock-junit4" val sshdCore = "org.apache.sshd:sshd-core" val sshdScp = "org.apache.sshd:sshd-scp" val sshdSftp = "org.apache.sshd:sshd-sftp" val testcontainersSpock = "org.testcontainers:spock" val typesafeConfig = "com.typesafe:config" val xerces = "xerces:xercesImpl" val xmlunit = "xmlunit:xmlunit" val licenses = mapOf( ansiControlSequenceUtil to License.Apache2, ant to License.Apache2, antLauncher to License.Apache2, asm to License.BSD3, asmAnalysis to License.BSD3, asmCommons to License.BSD3, asmTree to License.BSD3, asmUtil to License.BSD3, assertj to License.Apache2, awsS3Core to License.Apache2, awsS3Kms to License.Apache2, awsS3S3 to License.Apache2, awsS3Sts to License.Apache2, bouncycastlePgp to License.MIT, bouncycastleProvider to License.MIT, bsh to License.Apache2, capsule to License.BSDStyle, commonsCodec to License.Apache2, commonsCompress to License.Apache2, commonsHttpclient to License.Apache2, commonsIo to License.Apache2, commonsLang to License.Apache2, commonsLang3 to License.Apache2, commonsMath to License.Apache2, configurationCacheReport to License.Apache2, fastutil to License.Apache2, gcs to License.Apache2, googleApiClient to License.Apache2, googleHttpClient to License.Apache2, googleHttpClientGson to License.Apache2, googleHttpClientApacheV2 to License.Apache2, googleOauthClient to License.Apache2, gradleProfiler to License.Apache2, groovy to License.Apache2, gson to License.Apache2, guava to License.Apache2, hamcrest to License.BSD3, httpcore to License.Apache2, hikariCP to License.Apache2, inject to License.Apache2, ivy to License.Apache2, jacksonAnnotations to License.Apache2, jacksonCore to License.Apache2, jacksonDatabind to License.Apache2, jakartaActivation to License.EDL, jakartaXmlBind to License.EDL, jansi to License.Apache2, jatl to License.Apache2, jaxbCore to License.EDL, jaxbImpl to License.EDL, jcifs to License.LGPL21, jclToSlf4j to License.MIT, jcommander to License.Apache2, jetbrainsAnnotations to License.Apache2, jgit to License.EDL, joda to License.Apache2, jsch to License.BSDStyle, jsr305 to License.BSD3, julToSlf4j to License.MIT, junit to License.EPL, junit5Vintage to License.EPL, junit5JupiterApi to License.EPL, junitPlatform to License.EPL, jzlib to License.BSDStyle, kryo to License.BSD3, log4jToSlf4j to License.MIT, maven3BuilderSupport to License.Apache2, maven3Model to License.Apache2, maven3RepositoryMetadata to License.Apache2, maven3Settings to License.Apache2, maven3SettingsBuilder to License.Apache2, minlog to License.BSD3, nativePlatform to License.Apache2, nativePlatformFileEvents to License.Apache2, objenesis to License.Apache2, plexusCipher to License.Apache2, plexusInterpolation to License.Apache2, plexusSecDispatcher to License.Apache2, plexusUtils to License.Apache2, plist to License.MIT, pmavenCommon to License.Apache2, pmavenGroovy to License.Apache2, slf4jApi to License.MIT, snakeyaml to License.Apache2, testng to License.Apache2, tomlj to License.Apache2, trove4j to License.LGPL21, xbeanReflect to License.Apache2, xmlApis to License.Apache2 ) }
apache-2.0
d7a884f015e39e9581d7b22dddaabf4f
45.206642
126
0.712666
3.44011
false
false
false
false
google/private-compute-libraries
javatests/com/google/android/libraries/pcc/chronicle/analysis/impl/PolicyContextVerificationTest.kt
1
2720
/* * Copyright 2022 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.libraries.pcc.chronicle.analysis.impl import com.google.android.libraries.pcc.chronicle.analysis.impl.testdata.PERSON_DESCRIPTOR import com.google.android.libraries.pcc.chronicle.api.policy.StorageMedium import com.google.android.libraries.pcc.chronicle.api.policy.UsageType import com.google.android.libraries.pcc.chronicle.api.policy.builder.policy import com.google.android.libraries.pcc.chronicle.api.policy.contextrules.PolicyContextRule import com.google.android.libraries.pcc.chronicle.util.Key import com.google.android.libraries.pcc.chronicle.util.MutableTypedMap import com.google.android.libraries.pcc.chronicle.util.TypedMap import com.google.common.truth.Truth.assertThat import java.time.Duration import org.junit.Test import org.junit.runner.RunWith import org.junit.runners.JUnit4 @RunWith(JUnit4::class) class PolicyContextVerificationTest { object NameKey : Key<String> object NamePolicy : PolicyContextRule { override val name: String = "NamePolicy" override val operands: List<PolicyContextRule> = emptyList() override fun invoke(context: TypedMap): Boolean { return "test" == context[NameKey] } } val TEST_POLICY = policy( "Test", "TestingEgress", ) { allowedContext = NamePolicy target(PERSON_DESCRIPTOR, maxAge = Duration.ZERO) { retention(StorageMedium.RAM, true) "name" { rawUsage(UsageType.EGRESS) } "age" { rawUsage(UsageType.EGRESS) } } } @Test fun verifyContext_succeeds() { val mutableTypedMap = MutableTypedMap() mutableTypedMap[NameKey] = "test" val context = TypedMap(mutableTypedMap) assertThat(TEST_POLICY.verifyContext(context)).isEmpty() } @Test fun verifyContext_fails() { val mutableTypedMap = MutableTypedMap() mutableTypedMap[NameKey] = "other name" val context = TypedMap(mutableTypedMap) val policyChecks = TEST_POLICY.verifyContext(context) assertThat(policyChecks).isNotEmpty() assertThat(policyChecks[0].check) .isEqualTo("Connection context fails to meet required policy conditions") } }
apache-2.0
2bb0c4584738484a05d7301010325b10
33.871795
91
0.747794
3.976608
false
true
false
false
UweTrottmann/SeriesGuide
app/src/main/java/com/battlelancer/seriesguide/extensions/ExtensionsAdapter.kt
1
3675
package com.battlelancer.seriesguide.extensions import android.content.Context import android.graphics.drawable.Drawable import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.ArrayAdapter import android.widget.Button import androidx.appcompat.content.res.AppCompatResources import com.battlelancer.seriesguide.R import com.battlelancer.seriesguide.databinding.ItemExtensionBinding /** * Creates views for a list of [Extension]. */ class ExtensionsAdapter( context: Context, private val onItemClickListener: OnItemClickListener ) : ArrayAdapter<Extension?>(context, 0) { interface OnItemClickListener { fun onExtensionMenuButtonClick(anchor: View, extension: Extension, position: Int) fun onAddExtensionClick(anchor: View) } override fun getCount(): Int { // extra row for add button return super.getCount() + 1 } override fun getItemViewType(position: Int): Int { // last row is an add button return if (position == count - 1) VIEW_TYPE_ADD else VIEW_TYPE_EXTENSION } override fun getViewTypeCount(): Int = 2 override fun getView( position: Int, convertView: View?, parent: ViewGroup ): View { if (getItemViewType(position) == VIEW_TYPE_ADD) { val view = convertView ?: LayoutInflater.from(parent.context).inflate( R.layout.item_extension_add, parent, false )!! val buttonAdd = view.findViewById<Button>(R.id.button_item_extension_add) buttonAdd.setOnClickListener { onItemClickListener.onAddExtensionClick(buttonAdd) } return view } else { val view = if (convertView != null) { convertView } else { val binding = ItemExtensionBinding .inflate(LayoutInflater.from(parent.context), parent, false) binding.root.tag = ViewHolder(binding, onItemClickListener) binding.root } val extension = getItem(position) if (extension != null) { val viewHolder = view.tag as ViewHolder viewHolder.bindTo(extension, position) } return view } } internal class ViewHolder( private val binding: ItemExtensionBinding, onItemClickListener: OnItemClickListener ) { private val drawableIcon: Drawable? private var extension: Extension? = null var position = 0 init { binding.imageViewSettings.setOnClickListener { extension?.let { onItemClickListener.onExtensionMenuButtonClick( binding.imageViewSettings, it, position ) } } drawableIcon = AppCompatResources.getDrawable( binding.root.context, R.drawable.ic_extension_black_24dp ) } fun bindTo(extension: Extension, position: Int) { this.extension = extension this.position = position binding.textViewTitle.text = extension.label binding.textViewDescription.text = extension.description if (extension.icon != null) { binding.imageViewIcon.setImageDrawable(extension.icon) } else { binding.imageViewIcon.setImageDrawable(drawableIcon) } } } companion object { private const val VIEW_TYPE_EXTENSION = 0 private const val VIEW_TYPE_ADD = 1 } }
apache-2.0
a16fbac417d24ae4f5ce4ffa92ef02b4
30.965217
89
0.614694
5.280172
false
false
false
false
joseph-roque/BowlingCompanion
app/src/main/java/ca/josephroque/bowlingcompanion/statistics/impl/average/Game10AverageStatistic.kt
1
1018
package ca.josephroque.bowlingcompanion.statistics.impl.average import android.os.Parcel import android.os.Parcelable import ca.josephroque.bowlingcompanion.R import ca.josephroque.bowlingcompanion.common.interfaces.parcelableCreator /** * Copyright (C) 2018 Joseph Roque * * Average score in the 10th game of a series. */ class Game10AverageStatistic(total: Int = 0, divisor: Int = 0) : PerGameAverageStatistic(total, divisor) { // MARK: Overrides override val gameNumber = 10 override val titleId = Id override val id = Id.toLong() // MARK: Parcelable companion object { /** Creator, required by [Parcelable]. */ @Suppress("unused") @JvmField val CREATOR = parcelableCreator(::Game10AverageStatistic) /** Unique ID for the statistic. */ const val Id = R.string.statistic_average_10 } /** * Construct this statistic from a [Parcel]. */ private constructor(p: Parcel): this(total = p.readInt(), divisor = p.readInt()) }
mit
542112543178c64322fbc199fcced664
27.277778
106
0.687623
4.295359
false
false
false
false
kishmakov/Kitchen
server/src/io/magnaura/server/util.kt
1
1333
package io.magnaura.server import com.intellij.openapi.vfs.CharsetToolkit import com.intellij.psi.PsiFileFactory import com.intellij.psi.impl.PsiFileFactoryImpl import com.intellij.testFramework.LightVirtualFile import io.magnaura.server.compiler.KotlinEnvironment import org.jetbrains.kotlin.idea.KotlinLanguage import org.jetbrains.kotlin.psi.KtFile import java.nio.charset.StandardCharsets import java.security.MessageDigest object Properties { const val COMPILER_JARS = "magnaura.jvm.kotlinCompilerJars" const val LIBRARIES_JARS = "magnaura.jvm.librariesJars" } private val DIGESTER = MessageDigest.getInstance("MD5") fun String.md5(): String { val hashBytes = DIGESTER.digest(toByteArray(StandardCharsets.UTF_8)) return hashBytes.fold("", { str, it -> str + "%02x".format(it) }) } fun text(): String { return "Label text" } fun kotlinFile(name: String, content: String): KtFile = (PsiFileFactory.getInstance(KotlinEnvironment.coreEnvironment().project) as PsiFileFactoryImpl) .trySetupPsiForFile( LightVirtualFile( if (name.endsWith(".kt")) name else "$name.kt", KotlinLanguage.INSTANCE, content ).apply { charset = CharsetToolkit.UTF8_CHARSET }, KotlinLanguage.INSTANCE, true, false ) as KtFile
gpl-3.0
1584356423f13cc05971959ddc7831ad
32.325
99
0.724681
4.272436
false
false
false
false
android/user-interface-samples
Haptics/app/src/main/java/com/example/android/haptics/samples/ui/resist/ResistViewModel.kt
1
2691
/* * Copyright (C) 2022 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.android.haptics.samples.ui.resist import android.app.Application import android.os.Build import android.os.VibrationEffect import android.os.Vibrator import androidx.core.content.ContextCompat import androidx.lifecycle.ViewModel import androidx.lifecycle.ViewModelProvider import com.example.android.haptics.samples.R /** * ViewModel that handles state logic for Resist route. */ class ResistViewModel( val messageToUser: String, val isLowTickSupported: Boolean, ) : ViewModel() { /** * Factory for ResistViewModel. */ companion object { fun provideFactory( application: Application, ): ViewModelProvider.Factory = object : ViewModelProvider.Factory { @Suppress("UNCHECKED_CAST") override fun <T : ViewModel> create(modelClass: Class<T>): T { val vibrator = ContextCompat.getSystemService(application, Vibrator::class.java)!! val isTickSupported = Build.VERSION.SDK_INT >= Build.VERSION_CODES.R && vibrator.areAllPrimitivesSupported( VibrationEffect.Composition.PRIMITIVE_TICK ) val isLowTickSupported = Build.VERSION.SDK_INT >= Build.VERSION_CODES.S && vibrator.areAllPrimitivesSupported( VibrationEffect.Composition.PRIMITIVE_LOW_TICK ) // The message to display to user if we detect designed experience will // not work at all or will be degraded. var messageToUser = "" if (!isTickSupported && !isLowTickSupported) { messageToUser = application.getString(R.string.message_not_supported) } else if (!isLowTickSupported) { messageToUser = application.getString(R.string.message_degraded_experience) } return ResistViewModel( messageToUser = messageToUser, isLowTickSupported = isLowTickSupported ) as T } } } }
apache-2.0
4edd82ab567466d7d75dee79b986c250
38
126
0.657376
4.762832
false
false
false
false
jitsi/jibri
src/main/kotlin/org/jitsi/jibri/selenium/status_checks/StateTransitionTimeTracker.kt
1
1562
/* * Copyright @ 2018 - present 8x8, 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 org.jitsi.jibri.selenium.status_checks import java.time.Clock import java.time.Duration import java.time.Instant /** * Track the most recent timestamp at which we transitioned from * an event having not occurred to when it did occur. Note this * tracks the timestamp of that *transition*, not the most recent * time the event itself occurred. */ class StateTransitionTimeTracker(private val clock: Clock) { var timestampTransitionOccured: Instant? = null private set fun maybeUpdate(eventOccurred: Boolean) { if (eventOccurred && timestampTransitionOccured == null) { timestampTransitionOccured = clock.instant() } else if (!eventOccurred) { timestampTransitionOccured = null } } fun exceededTimeout(timeout: Duration): Boolean { return timestampTransitionOccured?.let { Duration.between(it, clock.instant()) > timeout } ?: false } }
apache-2.0
793b04f5cb4ad4168d90b7e53e426270
32.956522
75
0.706146
4.244565
false
false
false
false
NoodleMage/tachiyomi
app/src/main/java/eu/kanade/tachiyomi/ui/catalogue/filter/SectionItems.kt
3
2538
package eu.kanade.tachiyomi.ui.catalogue.filter import eu.davidea.flexibleadapter.items.ISectionable import eu.kanade.tachiyomi.source.model.Filter class TriStateSectionItem(filter: Filter.TriState) : TriStateItem(filter), ISectionable<TriStateItem.Holder, GroupItem> { private var head: GroupItem? = null override fun getHeader(): GroupItem? = head override fun setHeader(header: GroupItem?) { head = header } override fun equals(other: Any?): Boolean { if (this === other) return true if (javaClass != other?.javaClass) return false return filter == (other as TriStateSectionItem).filter } override fun hashCode(): Int { return filter.hashCode() } } class TextSectionItem(filter: Filter.Text) : TextItem(filter), ISectionable<TextItem.Holder, GroupItem> { private var head: GroupItem? = null override fun getHeader(): GroupItem? = head override fun setHeader(header: GroupItem?) { head = header } override fun equals(other: Any?): Boolean { if (this === other) return true if (javaClass != other?.javaClass) return false return filter == (other as TextSectionItem).filter } override fun hashCode(): Int { return filter.hashCode() } } class CheckboxSectionItem(filter: Filter.CheckBox) : CheckboxItem(filter), ISectionable<CheckboxItem.Holder, GroupItem> { private var head: GroupItem? = null override fun getHeader(): GroupItem? = head override fun setHeader(header: GroupItem?) { head = header } override fun equals(other: Any?): Boolean { if (this === other) return true if (javaClass != other?.javaClass) return false return filter == (other as CheckboxSectionItem).filter } override fun hashCode(): Int { return filter.hashCode() } } class SelectSectionItem(filter: Filter.Select<*>) : SelectItem(filter), ISectionable<SelectItem.Holder, GroupItem> { private var head: GroupItem? = null override fun getHeader(): GroupItem? = head override fun setHeader(header: GroupItem?) { head = header } override fun equals(other: Any?): Boolean { if (this === other) return true if (javaClass != other?.javaClass) return false return filter == (other as SelectSectionItem).filter } override fun hashCode(): Int { return filter.hashCode() } }
apache-2.0
3d6bdf77e580b958126b1a0a052aadba
26.840909
121
0.639086
4.484099
false
false
false
false
eugeis/ee
ee-design/src/main/kotlin/ee/design/gen/swagger/DesignSwaggerContextFactory.kt
1
855
package ee.design.gen.swagger import ee.design.CompI import ee.lang.* import ee.lang.gen.common.LangCommonContextFactory open class DesignSwaggerContextFactory : LangCommonContextFactory() { override fun contextBuilder(derived: DerivedController): ContextBuilder<StructureUnitI<*>> { return ContextBuilder(CONTEXT_COMMON, macroController){ val structureUnit = this val compOrStructureUnit = this.findThisOrParentUnsafe(CompI::class.java) ?: structureUnit GenerationContext(moduleFolder = "${compOrStructureUnit.artifact()}/${compOrStructureUnit.artifact()}", genFolder = "src-gen/main/swagger", genFolderDeletable = true, namespace = structureUnit.namespace().toLowerCase(), derivedController = derived, macroController = macroController) } } }
apache-2.0
a30820972be4484edbbb4e8837e5c2c0
46.5
115
0.711111
4.776536
false
false
false
false
danrien/projectBlue
projectBlueWater/src/main/java/com/lasthopesoftware/bluewater/client/browsing/BrowserEntryActivity.kt
2
14501
package com.lasthopesoftware.bluewater.client.browsing import android.content.BroadcastReceiver import android.content.Context import android.content.Intent import android.content.IntentFilter import android.content.res.Configuration import android.os.Bundle import android.os.Handler import android.view.Menu import android.view.MenuItem import android.view.View import android.widget.AdapterView.OnItemClickListener import android.widget.ListView import android.widget.ProgressBar import android.widget.RelativeLayout import android.widget.ViewAnimator import androidx.appcompat.app.ActionBarDrawerToggle import androidx.appcompat.app.AppCompatActivity import androidx.core.view.GravityCompat import androidx.drawerlayout.widget.DrawerLayout import androidx.fragment.app.Fragment import androidx.localbroadcastmanager.content.LocalBroadcastManager import com.lasthopesoftware.bluewater.R import com.lasthopesoftware.bluewater.client.browsing.items.list.IItemListViewContainer import com.lasthopesoftware.bluewater.client.browsing.items.list.menus.changes.handlers.ItemListMenuChangeHandler import com.lasthopesoftware.bluewater.client.browsing.items.menu.LongClickViewAnimatorListener import com.lasthopesoftware.bluewater.client.browsing.items.playlists.PlaylistListFragment import com.lasthopesoftware.bluewater.client.browsing.library.access.LibraryRepository import com.lasthopesoftware.bluewater.client.browsing.library.access.session.* import com.lasthopesoftware.bluewater.client.browsing.library.repository.Library import com.lasthopesoftware.bluewater.client.browsing.library.repository.Library.ViewType import com.lasthopesoftware.bluewater.client.browsing.library.views.* import com.lasthopesoftware.bluewater.client.browsing.library.views.access.CachedLibraryViewsProvider import com.lasthopesoftware.bluewater.client.browsing.library.views.access.SelectedLibraryViewProvider import com.lasthopesoftware.bluewater.client.browsing.library.views.adapters.SelectStaticViewAdapter import com.lasthopesoftware.bluewater.client.browsing.library.views.adapters.SelectViewAdapter import com.lasthopesoftware.bluewater.client.connection.HandleViewIoException import com.lasthopesoftware.bluewater.client.connection.selected.InstantiateSelectedConnectionActivity import com.lasthopesoftware.bluewater.client.connection.selected.SelectedConnectionSettingsChangeReceiver import com.lasthopesoftware.bluewater.client.playback.view.nowplaying.NowPlayingFloatingActionButton import com.lasthopesoftware.bluewater.client.stored.library.items.files.fragment.ActiveFileDownloadsFragment import com.lasthopesoftware.bluewater.settings.ApplicationSettingsActivity import com.lasthopesoftware.bluewater.settings.repository.access.CachingApplicationSettingsRepository.Companion.getApplicationSettingsRepository import com.lasthopesoftware.bluewater.shared.MagicPropertyBuilder import com.lasthopesoftware.bluewater.shared.android.view.LazyViewFinder import com.lasthopesoftware.bluewater.shared.android.view.ViewUtils import com.lasthopesoftware.bluewater.shared.exceptions.UnexpectedExceptionToasterResponse import com.lasthopesoftware.bluewater.shared.promises.extensions.LoopedInPromise.Companion.response import com.lasthopesoftware.bluewater.shared.promises.extensions.keepPromise import org.slf4j.LoggerFactory import java.util.* class BrowserEntryActivity : AppCompatActivity(), IItemListViewContainer, Runnable { private var connectionRestoreCode: Int? = null private val browseLibraryContainerRelativeLayout = LazyViewFinder<RelativeLayout>(this, R.id.browseLibraryContainer) private val selectViewsListView = LazyViewFinder<ListView>(this, R.id.lvLibraryViewSelection) private val specialLibraryItemsListView = LazyViewFinder<ListView>(this, R.id.specialLibraryItemsListView) private val drawerLayout = LazyViewFinder<DrawerLayout>(this, R.id.drawer_layout) private val loadingViewsProgressBar = LazyViewFinder<ProgressBar>(this, R.id.pbLoadingViews) private val libraryRepository by lazy { LibraryRepository(this) } private val libraryViewsProvider by lazy { CachedLibraryViewsProvider.getInstance(this) } private val selectedLibraryViews by lazy { SelectedLibraryViewProvider(selectedBrowserLibraryProvider, libraryViewsProvider, libraryRepository) } private val applicationSettings by lazy { getApplicationSettingsRepository() } private val selectedBrowserLibraryProvider by lazy { SelectedBrowserLibraryProvider( SelectedBrowserLibraryIdentifierProvider(applicationSettings), libraryRepository) } private val messageHandler by lazy { Handler(mainLooper) } private val lazyLocalBroadcastManager = lazy { LocalBroadcastManager.getInstance(this) } private val drawerToggle = lazy { val selectViewTitle = getText(R.string.select_view_title) object : ActionBarDrawerToggle( this@BrowserEntryActivity, /* host Activity */ drawerLayout.findView(), /* DrawerLayout object */ R.string.drawer_open, /* "open drawer" description */ R.string.drawer_close /* "close drawer" description */ ) { /** Called when a drawer has settled in a completely closed state. */ override fun onDrawerClosed(view: View) { super.onDrawerClosed(view) supportActionBar?.title = oldTitle invalidateOptionsMenu() // creates resultFrom to onPrepareOptionsMenu() } /** Called when a drawer has settled in a completely open state. */ override fun onDrawerOpened(drawerView: View) { super.onDrawerOpened(drawerView) oldTitle = supportActionBar?.title supportActionBar?.title = selectViewTitle invalidateOptionsMenu() // creates resultFrom to onPrepareOptionsMenu() } } } private val connectionSettingsUpdatedReceiver = object : BroadcastReceiver() { override fun onReceive(context: Context, intent: Intent) { finishAffinity() } } private lateinit var nowPlayingFloatingActionButton: NowPlayingFloatingActionButton private var viewAnimator: ViewAnimator? = null private var activeFragment: Fragment? = null private var oldTitle = title private var isStopped = false public override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) // Ensure that this task is only started when it's the task root. A workaround for an Android bug. // See http://stackoverflow.com/a/7748416 if (!isTaskRoot) { val intent = intent if (Intent.ACTION_MAIN == intent.action && intent.hasCategory(Intent.CATEGORY_LAUNCHER)) { val className = BrowserEntryActivity::class.java.name LoggerFactory.getLogger(javaClass).info("$className is not the root. Finishing $className instead of launching.") finish() return } } setContentView(R.layout.activity_browse_library) setSupportActionBar(findViewById(R.id.browseLibraryToolbar)) val connectionSettingsChangedFilter = IntentFilter() connectionSettingsChangedFilter.addAction(BrowserLibrarySelection.libraryChosenEvent) connectionSettingsChangedFilter.addAction(SelectedConnectionSettingsChangeReceiver.connectionSettingsUpdated) lazyLocalBroadcastManager.value.registerReceiver( connectionSettingsUpdatedReceiver, connectionSettingsChangedFilter) nowPlayingFloatingActionButton = NowPlayingFloatingActionButton.addNowPlayingFloatingActionButton(findViewById(R.id.browseLibraryRelativeLayout)) setTitle(R.string.title_activity_library) supportActionBar?.run { setDisplayHomeAsUpEnabled(true) setHomeButtonEnabled(true) } val drawerLayout = drawerLayout.findView() drawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START) drawerLayout.addDrawerListener(drawerToggle.value) specialLibraryItemsListView.findView().onItemClickListener = OnItemClickListener { _, _, _, _ -> updateSelectedView(ViewType.DownloadView, 0) } } override fun onStart() { super.onStart() InstantiateSelectedConnectionActivity.restoreSelectedConnection(this).eventually(response({ connectionRestoreCode = it if (it == null) startLibrary() }, messageHandler)) } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { if (requestCode == connectionRestoreCode) startLibrary() super.onActivityResult(requestCode, resultCode, data) } override fun onNewIntent(intent: Intent) { super.onNewIntent(intent) if (showDownloadsAction == intent.action) updateSelectedView(ViewType.DownloadView, 0) } private fun startLibrary() { isStopped = false if (selectViewsListView.findView().adapter != null) return showProgressBar() selectedBrowserLibraryProvider .browserLibrary .eventually(response({ library -> when { library == null -> { // No library, must bail out finish() } showDownloadsAction == intent.action -> { library.setSelectedView(0) library.setSelectedViewType(ViewType.DownloadView) libraryRepository.saveLibrary(library) .eventually(response(::displayLibrary, messageHandler)) // Clear the action intent.action = null } else -> { displayLibrary(library) } } }, messageHandler)) } private fun displayLibrary(library: Library?) { if (library == null) return specialLibraryItemsListView.findView().adapter = SelectStaticViewAdapter(this, specialViews, library.selectedViewType, library.selectedView) run() } override fun run() { selectedLibraryViews .promiseSelectedOrDefaultView() .eventually { selectedView -> selectedView ?.let { lv -> selectedBrowserLibraryProvider.browserLibrary .eventually { l -> l?.libraryId ?.let { libraryId -> libraryViewsProvider .promiseLibraryViews(libraryId) .eventually(response({ items -> updateLibraryView(lv, items) }, messageHandler)) } .keepPromise(Unit) } } .keepPromise(Unit) } .excuse(HandleViewIoException(this, this)) .eventuallyExcuse(response(UnexpectedExceptionToasterResponse(this), this)) .then { ApplicationSettingsActivity.launch(this) finish() } } private fun updateLibraryView(selectedView: ViewItem, items: Collection<ViewItem>) { if (isStopped) return LongClickViewAnimatorListener.tryFlipToPreviousView(viewAnimator) selectViewsListView.findView().adapter = SelectViewAdapter(this, items, selectedView.key) selectViewsListView.findView().onItemClickListener = getOnSelectViewClickListener(items) hideAllViews() if (selectedView is DownloadViewItem) { oldTitle = specialViews[0] supportActionBar?.title = oldTitle val activeFileDownloadsFragment = ActiveFileDownloadsFragment() swapFragments(activeFileDownloadsFragment) return } for (item in items) { if (item.key != selectedView.key) continue oldTitle = item.value supportActionBar?.title = oldTitle break } if (selectedView is PlaylistViewItem) { val playlistListFragment = PlaylistListFragment() playlistListFragment.setOnItemListMenuChangeHandler(ItemListMenuChangeHandler(this)) swapFragments(playlistListFragment) return } val browseLibraryViewsFragment = BrowseLibraryViewsFragment() browseLibraryViewsFragment.setOnItemListMenuChangeHandler(ItemListMenuChangeHandler(this)) swapFragments(browseLibraryViewsFragment) } private fun getOnSelectViewClickListener(items: Collection<ViewItem>): OnItemClickListener { return OnItemClickListener { _, _, position, _ -> val selectedItem = (if (items is List<*>) items as List<ViewItem> else ArrayList(items))[position] updateSelectedView( if (KnownViews.Playlists == selectedItem.value) ViewType.PlaylistView else ViewType.StandardServerView, selectedItem.key) } } private fun updateSelectedView(selectedViewType: ViewType, selectedViewKey: Int) { drawerLayout.findView().closeDrawer(GravityCompat.START) drawerToggle.value.syncState() selectedBrowserLibraryProvider .browserLibrary .then { library -> library ?.takeUnless { selectedViewType === it.selectedViewType && it.selectedView == selectedViewKey } ?.run { setSelectedView(selectedViewKey) setSelectedViewType(selectedViewType) libraryRepository .saveLibrary(this) .eventually(response(::displayLibrary, messageHandler)) } } } override fun onCreateOptionsMenu(menu: Menu): Boolean = ViewUtils.buildStandardMenu(this, menu) override fun onOptionsItemSelected(item: MenuItem): Boolean = drawerToggle.isInitialized() && drawerToggle.value.onOptionsItemSelected(item) || ViewUtils.handleMenuClicks(this, item) override fun onPostCreate(savedInstanceState: Bundle?) { super.onPostCreate(savedInstanceState) // Sync the toggle state after onRestoreInstanceState has occurred. if (drawerToggle.isInitialized()) drawerToggle.value.syncState() } override fun onConfigurationChanged(newConfig: Configuration) { super.onConfigurationChanged(newConfig) if (drawerToggle.isInitialized()) drawerToggle.value.onConfigurationChanged(newConfig) } private fun showProgressBar() { showContainerView(loadingViewsProgressBar.findView()) } private fun showContainerView(view: View) { hideAllViews() view.visibility = View.VISIBLE } private fun hideAllViews() { for (i in 0 until browseLibraryContainerRelativeLayout.findView().childCount) browseLibraryContainerRelativeLayout.findView().getChildAt(i).visibility = View.INVISIBLE } @Synchronized private fun swapFragments(newFragment: Fragment) { val ft = supportFragmentManager.beginTransaction() try { activeFragment?.also { ft.remove(it) } ft.add(R.id.browseLibraryContainer, newFragment) } finally { ft.commit() activeFragment = newFragment } } public override fun onStop() { isStopped = true super.onStop() } override fun onBackPressed() { if (LongClickViewAnimatorListener.tryFlipToPreviousView(viewAnimator)) return super.onBackPressed() } override fun updateViewAnimator(viewAnimator: ViewAnimator) { this.viewAnimator = viewAnimator } override fun getNowPlayingFloatingActionButton(): NowPlayingFloatingActionButton = nowPlayingFloatingActionButton override fun onDestroy() { if (lazyLocalBroadcastManager.isInitialized()) lazyLocalBroadcastManager.value.unregisterReceiver(connectionSettingsUpdatedReceiver) super.onDestroy() } companion object { @JvmField val showDownloadsAction = MagicPropertyBuilder.buildMagicPropertyName(BrowserEntryActivity::class.java, "showDownloadsAction") private val specialViews = listOf("Active Downloads") } }
lgpl-3.0
a9491dd37bc2674af3cde60b31d86710
37.464191
147
0.79629
4.511823
false
false
false
false
EyeSeeTea/QAApp
app/src/main/java/org/eyeseetea/malariacare/presentation/viewmodels/observations/ObservationViewModel.kt
1
1662
package org.eyeseetea.malariacare.presentation.viewmodels.observations import org.eyeseetea.malariacare.domain.entity.ObservationStatus data class ObservationViewModel(val surveyUid: String) { var status = ObservationStatus.IN_PROGRESS var provider = "" var action1: ActionViewModel var action2: ActionViewModel var action3: ActionViewModel init { action1 = ActionViewModel("", null, "", null) action2 = ActionViewModel("", null, "", null) action3 = ActionViewModel("", null, "", null) } constructor( surveyUid: String, provider: String, action1: ActionViewModel, action2: ActionViewModel, action3: ActionViewModel, status: ObservationStatus ) : this(surveyUid) { this.provider = provider this.action1 = action1 this.action2 = action2 this.action3 = action3 this.status = status } val isValid: Boolean get() { val atLeastOneFilled = !(action1.isEmpty && action2.isEmpty && action3.isEmpty) return atLeastOneFilled && (action1.isValid || action1.isEmpty) && (action2.isValid || action2.isEmpty) && (action3.isValid || action3.isEmpty) } val allActionsCompleted: Boolean get() { val atLeastOneFilled = !(action1.isEmpty && action2.isEmpty && action3.isEmpty) return atLeastOneFilled && (action1.isCompleted || action1.isEmpty) && (action2.isCompleted || action2.isEmpty) && (action3.isCompleted || action3.isEmpty) } }
gpl-3.0
7123145d9118941eb669760ceab5007b
30.358491
91
0.61071
4.553425
false
false
false
false
spark/photon-tinker-android
mesh/src/main/java/io/particle/mesh/setup/flow/setupsteps/StepControlPanelDetermineFlowAfterPreflow.kt
1
4112
package io.particle.mesh.setup.flow.setupsteps import androidx.annotation.WorkerThread import io.particle.firmwareprotos.ctrl.Network.InterfaceEntry import io.particle.firmwareprotos.ctrl.Network.InterfaceType import io.particle.mesh.common.android.livedata.nonNull import io.particle.mesh.common.android.livedata.runBlockOnUiThreadAndAwaitUpdate import io.particle.mesh.setup.flow.* import io.particle.mesh.setup.flow.context.NetworkSetupType import io.particle.mesh.setup.flow.context.NetworkSetupType.AS_GATEWAY import io.particle.mesh.setup.flow.context.NetworkSetupType.NODE_JOINER import io.particle.mesh.setup.flow.context.SetupContexts import io.particle.mesh.setup.flow.context.SetupDevice import mu.KotlinLogging class StepControlPanelDetermineFlowAfterPreflow( private val flowUi: FlowUiDelegate ) : MeshSetupStep() { private val log = KotlinLogging.logger {} @WorkerThread override suspend fun doRunStep(ctxs: SetupContexts, scopes: Scopes) { if (ctxs.meshNetworkFlowAdded) { // we've already completed all this; bail! return } ctxs.currentFlow = determineRemainingFlow(ctxs, scopes) throw ExpectedFlowException("Restarting flow to run new steps") } private suspend fun determineRemainingFlow( ctxs: SetupContexts, scopes: Scopes ): List<FlowType> { ensureHasEthernetChecked(ctxs) val meshOnly = (ctxs.targetDevice.connectivityType == Gen3ConnectivityType.MESH_ONLY && !ctxs.hasEthernet!!) if (meshOnly) { ctxs.meshNetworkFlowAdded = true return listOf(FlowType.CONTROL_PANEL_PREFLOW, FlowType.CONTROL_PANEL_MESH_JOINER_FLOW) } ctxs.mesh.showNewNetworkOptionInScanner = true // // if (!ctxs.currentFlow.contains(FlowType.INTERNET_CONNECTED_PREFLOW)) { // // we're in an internet connected flow. Run through that flow and come back here. // return listOf(FlowType.PREFLOW, FlowType.INTERNET_CONNECTED_PREFLOW) // } // if we get here, it's time to add the correct mesh network flow type & interface setup type return addInterfaceSetupAndMeshNetworkFlows(ctxs, scopes) } private suspend fun addInterfaceSetupAndMeshNetworkFlows( ctxs: SetupContexts, scopes: Scopes ): List<FlowType> { determineNetworkSetupType(ctxs, scopes) val networkSetupType = ctxs.device.networkSetupTypeLD.value!! if (networkSetupType == NetworkSetupType.NODE_JOINER) { ctxs.meshNetworkFlowAdded = true return listOf(FlowType.CONTROL_PANEL_PREFLOW, FlowType.CONTROL_PANEL_MESH_JOINER_FLOW) } val flows = mutableListOf(FlowType.CONTROL_PANEL_PREFLOW) flows.add( when (networkSetupType) { AS_GATEWAY -> FlowType.CONTROL_PANEL_MESH_CREATE_NETWORK_FLOW NODE_JOINER -> FlowType.CONTROL_PANEL_MESH_JOINER_FLOW else -> throw IllegalStateException("Invalid value") } ) ctxs.meshNetworkFlowAdded = true return flows } private suspend fun ensureHasEthernetChecked(ctxs: SetupContexts) { if (ctxs.hasEthernet != null) { return } suspend fun fetchInterfaceList(targetDevice: SetupDevice): List<InterfaceEntry> { val xceiver = targetDevice.transceiverLD.value!! val reply = xceiver.sendGetInterfaceList().throwOnErrorOrAbsent() return reply.interfacesList } val interfaces = fetchInterfaceList(ctxs.targetDevice) ctxs.hasEthernet = null != interfaces.firstOrNull { it.type == InterfaceType.ETHERNET } } private suspend fun determineNetworkSetupType(ctxs: SetupContexts, scopes: Scopes) { if (ctxs.device.networkSetupTypeLD.value != null) { return } ctxs.device.networkSetupTypeLD.nonNull(scopes).runBlockOnUiThreadAndAwaitUpdate(scopes) { flowUi.getNetworkSetupType() } flowUi.showGlobalProgressSpinner(true) } }
apache-2.0
13802b277dc4f5c97c14f6bb9fb5d78c
36.054054
101
0.691877
4.543646
false
false
false
false
anton-okolelov/intellij-rust
src/main/kotlin/org/rust/ide/inspections/RsNamingInspection.kt
2
10897
/* * Use of this source code is governed by the MIT license that can be * found in the LICENSE file. */ package org.rust.ide.inspections import com.intellij.codeInspection.ProblemsHolder import com.intellij.psi.PsiElement import com.intellij.psi.PsiNamedElement import com.intellij.psi.util.PsiTreeUtil import org.rust.ide.inspections.fixes.RenameFix import org.rust.lang.core.psi.* import org.rust.lang.core.psi.ext.* /** * Base class for naming inspections. Implements the core logic of checking names * and registering problems. */ abstract class RsNamingInspection( val elementType: String, val styleName: String, val lint: RsLint, elementTitle: String = elementType ) : RsLocalInspectionTool() { val dispName = elementTitle + " naming convention" override fun getDisplayName() = dispName fun inspect(id: PsiElement?, holder: ProblemsHolder, fix: Boolean = true) { if (id == null) return val (isOk, suggestedName) = checkName(id.text) if (isOk || suggestedName == null || lint.levelFor(id) == RsLintLevel.ALLOW) return val fixEl = id.parent val fixes = if (fix && fixEl is PsiNamedElement) arrayOf(RenameFix(fixEl, suggestedName)) else emptyArray() holder.registerProblem( id, "$elementType `${id.text}` should have $styleName case name such as `$suggestedName`", *fixes) } abstract fun checkName(name: String): Pair<Boolean, String?> } /** * Checks if the name is CamelCase. */ open class RsCamelCaseNamingInspection( elementType: String, elementTitle: String = elementType ) : RsNamingInspection(elementType, "a camel", RsLint.NonCamelCaseTypes, elementTitle) { override fun checkName(name: String): Pair<Boolean, String?> { val str = name.trim('_') if (!str.isEmpty() && str[0].canStartWord && '_' !in str) { return Pair(true, null) } return Pair(false, if (str.isEmpty()) "CamelCase" else suggestName(name)) } private fun suggestName(name: String): String { val result = StringBuilder(name.length) var wasUnderscore = true var startWord = true for (char in name) { when { char == '_' -> wasUnderscore = true wasUnderscore || startWord && char.canStartWord -> { result.append(char.toUpperCase()) wasUnderscore = false startWord = false } else -> { startWord = char.isLowerCase() result.append(char.toLowerCase()) } } } return if (result.isEmpty()) "CamelCase" else result.toString() } private val Char.canStartWord: Boolean get() = isUpperCase() || isDigit() } /** * Checks if the name is snake_case. */ open class RsSnakeCaseNamingInspection(elementType: String) : RsNamingInspection(elementType, "a snake", RsLint.NonSnakeCase) { override fun checkName(name: String): Pair<Boolean, String?> { val str = name.trim('_') if (!str.isEmpty() && str.all { !it.isLetter() || it.isLowerCase() }) { return Pair(true, null) } return Pair(false, if (str.isEmpty()) "snake_case" else name.toSnakeCase(false)) } } /** * Checks if the name is UPPER_CASE. */ open class RsUpperCaseNamingInspection(elementType: String) : RsNamingInspection(elementType, "an upper", RsLint.NonUpperCaseGlobals) { override fun checkName(name: String): Pair<Boolean, String?> { val str = name.trim('_') if (!str.isEmpty() && str.all { !it.isLetter() || it.isUpperCase() }) { return Pair(true, null) } return Pair(false, if (str.isEmpty()) "UPPER_CASE" else name.toSnakeCase(true)) } } fun String.toSnakeCase(upper: Boolean): String { val result = StringBuilder(length + 3) // 3 is a reasonable margin for growth when `_`s are added result.append(takeWhile { it == '_' || it == '\'' }) // Preserve prefix var firstPart = true drop(result.length).splitToSequence('_').forEach pit@ { part -> if (part.isEmpty()) return@pit if (!firstPart) { result.append('_') } firstPart = false var newWord = false var firstWord = true part.forEach { char -> if (newWord && char.isUpperCase()) { if (!firstWord) { result.append('_') } newWord = false } else { newWord = char.isLowerCase() } result.append(if (upper) char.toUpperCase() else char.toLowerCase()) firstWord = false } } return result.toString() } // // Concrete inspections // class RsArgumentNamingInspection : RsSnakeCaseNamingInspection("Argument") { override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean) = object : RsVisitor() { override fun visitPatBinding(el: RsPatBinding) { if (el.parent?.parent is RsValueParameter) { inspect(el.identifier, holder) } } } } class RsConstNamingInspection : RsUpperCaseNamingInspection("Constant") { override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean) = object : RsVisitor() { override fun visitConstant(el: RsConstant) { if (el.kind == RsConstantKind.CONST) { inspect(el.identifier, holder) } } } } class RsStaticConstNamingInspection : RsUpperCaseNamingInspection("Static constant") { override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean) = object : RsVisitor() { override fun visitConstant(el: RsConstant) { if (el.kind != RsConstantKind.CONST) { inspect(el.identifier, holder) } } } } class RsEnumNamingInspection : RsCamelCaseNamingInspection("Type", "Enum") { override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean) = object : RsVisitor() { override fun visitEnumItem(el: RsEnumItem) = inspect(el.identifier, holder) } } class RsEnumVariantNamingInspection : RsCamelCaseNamingInspection("Enum variant") { override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean) = object : RsVisitor() { override fun visitEnumVariant(el: RsEnumVariant) = inspect(el.identifier, holder) } } class RsFunctionNamingInspection : RsSnakeCaseNamingInspection("Function") { override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean) = object : RsVisitor() { override fun visitFunction(el: RsFunction) { if (el.owner is RsAbstractableOwner.Free) { inspect(el.identifier, holder) } } } } class RsMethodNamingInspection : RsSnakeCaseNamingInspection("Method") { override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean) = object : RsVisitor() { override fun visitFunction(el: RsFunction) = when (el.owner) { is RsAbstractableOwner.Trait, is RsAbstractableOwner.Impl -> inspect(el.identifier, holder) else -> Unit } } } class RsLifetimeNamingInspection : RsSnakeCaseNamingInspection("Lifetime") { override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean) = object : RsVisitor() { override fun visitLifetimeParameter(el: RsLifetimeParameter) = inspect(el.quoteIdentifier, holder) } } class RsMacroNamingInspection : RsSnakeCaseNamingInspection("Macro") { override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean) = object : RsVisitor() { override fun visitMacroDefinition(el: RsMacroDefinition) = inspect(el.nameIdentifier, holder) } } class RsModuleNamingInspection : RsSnakeCaseNamingInspection("Module") { override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean) = object : RsVisitor() { override fun visitModDeclItem(el: RsModDeclItem) = inspect(el.identifier, holder) override fun visitModItem(el: RsModItem) = inspect(el.identifier, holder) } } class RsStructNamingInspection : RsCamelCaseNamingInspection("Type", "Struct") { override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean) = object : RsVisitor() { override fun visitStructItem(el: RsStructItem) = inspect(el.identifier, holder) } } class RsFieldNamingInspection : RsSnakeCaseNamingInspection("Field") { override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean) = object : RsVisitor() { override fun visitFieldDecl(el: RsFieldDecl) = inspect(el.identifier, holder) } } class RsTraitNamingInspection : RsCamelCaseNamingInspection("Trait") { override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean) = object : RsVisitor() { override fun visitTraitItem(el: RsTraitItem) = inspect(el.identifier, holder) } } class RsTypeAliasNamingInspection : RsCamelCaseNamingInspection("Type", "Type alias") { override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean) = object : RsVisitor() { override fun visitTypeAlias(el: RsTypeAlias) { if (el.owner is RsAbstractableOwner.Free) { inspect(el.identifier, holder) } } } } class RsAssocTypeNamingInspection : RsCamelCaseNamingInspection("Type", "Associated type") { override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean) = object : RsVisitor() { override fun visitTypeAlias(el: RsTypeAlias) { if (el.owner is RsAbstractableOwner.Trait) { inspect(el.identifier, holder, false) } } } } class RsTypeParameterNamingInspection : RsCamelCaseNamingInspection("Type parameter") { override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean) = object : RsVisitor() { override fun visitTypeParameter(el: RsTypeParameter) = inspect(el.identifier, holder) } } class RsVariableNamingInspection : RsSnakeCaseNamingInspection("Variable") { override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean) = object : RsVisitor() { override fun visitPatBinding(el: RsPatBinding) { val pattern = PsiTreeUtil.getTopmostParentOfType(el, RsPat::class.java) ?: return when (pattern.parent) { is RsLetDecl -> inspect(el.identifier, holder) } } } }
mit
31cee7e26917f7c6c0827c04a2b3992c
36.064626
135
0.62898
4.866905
false
false
false
false
albertoruibal/karballo
karballo-common/src/main/kotlin/karballo/evaluation/SimplifiedEvaluator.kt
1
6138
package karballo.evaluation import karballo.Board import karballo.bitboard.AttacksInfo /** * Piece square values from Tomasz Michniewski, got from: * http://chessprogramming.wikispaces.com/Simplified+evaluation+function * @author rui */ class SimplifiedEvaluator : Evaluator() { override fun evaluate(b: Board, ai: AttacksInfo): Int { val all = b.all val materialValue = intArrayOf(0, 0) val pawnMaterialValue = intArrayOf(0, 0) val pcsqValue = intArrayOf(0, 0) val pcsqOpeningValue = intArrayOf(0, 0) val pcsqEndgameValue = intArrayOf(0, 0) val noQueen = booleanArrayOf(true, true) var square: Long = 1 var index = 0 while (square != 0L) { val isWhite = b.whites and square != 0L val color = if (isWhite) 0 else 1 val pcsqIndex: Int = if (isWhite) 63 - index else index if (square and all != 0L) { if (square and b.pawns != 0L) { pawnMaterialValue[color] += PAWN pcsqValue[color] += pawnSquare[pcsqIndex] } else if (square and b.knights != 0L) { materialValue[color] += KNIGHT pcsqValue[color] += knightSquare[pcsqIndex] } else if (square and b.bishops != 0L) { materialValue[color] += BISHOP pcsqValue[color] += bishopSquare[pcsqIndex] } else if (square and b.rooks != 0L) { materialValue[color] += ROOK pcsqValue[color] += rookSquare[pcsqIndex] } else if (square and b.queens != 0L) { pcsqValue[color] += queenSquare[pcsqIndex] materialValue[color] += QUEEN noQueen[color] = false } else if (square and b.kings != 0L) { pcsqOpeningValue[color] += kingSquareOpening[pcsqIndex] pcsqEndgameValue[color] += kingSquareEndGame[pcsqIndex] } } square = square shl 1 index++ } var value = 0 value += pawnMaterialValue[0] - pawnMaterialValue[1] value += materialValue[0] - materialValue[1] value += pcsqValue[0] - pcsqValue[1] // Endgame // 1. Both sides have no queens or // 2. Every side which has a queen has additionally no other pieces or one minorpiece maximum. if ((noQueen[0] || materialValue[0] <= QUEEN + BISHOP) && (noQueen[1] || materialValue[1] <= QUEEN + BISHOP)) { value += pcsqEndgameValue[0] - pcsqEndgameValue[1] } else { value += pcsqOpeningValue[0] - pcsqOpeningValue[1] } return value } companion object { internal val PAWN = 100 internal val KNIGHT = 320 internal val BISHOP = 330 internal val ROOK = 500 internal val QUEEN = 900 // Values are rotated for whites, so when white is playing is like shown in the code TODO at the moment must be symmetric val pawnSquare = intArrayOf( 0, 0, 0, 0, 0, 0, 0, 0, 50, 50, 50, 50, 50, 50, 50, 50, 10, 10, 20, 30, 30, 20, 10, 10, 5, 5, 10, 25, 25, 10, 5, 5, 0, 0, 0, 20, 20, 0, 0, 0, 5, -5, -10, 0, 0, -10, -5, 5, 5, 10, 10, -20, -20, 10, 10, 5, 0, 0, 0, 0, 0, 0, 0, 0 ) val knightSquare = intArrayOf( -50, -40, -30, -30, -30, -30, -40, -50, -40, -20, 0, 0, 0, 0, -20, -40, -30, 0, 10, 15, 15, 10, 0, -30, -30, 5, 15, 20, 20, 15, 5, -30, -30, 0, 15, 20, 20, 15, 0, -30, -30, 5, 10, 15, 15, 10, 5, -30, -40, -20, 0, 5, 5, 0, -20, -40, -50, -40, -30, -30, -30, -30, -40, -50) val bishopSquare = intArrayOf( -20, -10, -10, -10, -10, -10, -10, -20, -10, 0, 0, 0, 0, 0, 0, -10, -10, 0, 5, 10, 10, 5, 0, -10, -10, 5, 5, 10, 10, 5, 5, -10, -10, 0, 10, 10, 10, 10, 0, -10, -10, 10, 10, 10, 10, 10, 10, -10, -10, 5, 0, 0, 0, 0, 5, -10, -20, -10, -10, -10, -10, -10, -10, -20) val rookSquare = intArrayOf( 0, 0, 0, 0, 0, 0, 0, 0, 5, 10, 10, 10, 10, 10, 10, 5, -5, 0, 0, 0, 0, 0, 0, -5, -5, 0, 0, 0, 0, 0, 0, -5, -5, 0, 0, 0, 0, 0, 0, -5, -5, 0, 0, 0, 0, 0, 0, -5, -5, 0, 0, 0, 0, 0, 0, -5, 0, 0, 0, 5, 5, 0, 0, 0 ) val queenSquare = intArrayOf( -20, -10, -10, -5, -5, -10, -10, -20, -10, 0, 0, 0, 0, 0, 0, -10, -10, 0, 5, 5, 5, 5, 0, -10, -5, 0, 5, 5, 5, 5, 0, -5, 0, 0, 5, 5, 5, 5, 0, -5, -10, 5, 5, 5, 5, 5, 0, -10, -10, 0, 5, 0, 0, 0, 0, -10, -20, -10, -10, -5, -5, -10, -10, -20 ) val kingSquareOpening = intArrayOf( -30, -40, -40, -50, -50, -40, -40, -30, -30, -40, -40, -50, -50, -40, -40, -30, -30, -40, -40, -50, -50, -40, -40, -30, -30, -40, -40, -50, -50, -40, -40, -30, -20, -30, -30, -40, -40, -30, -30, -20, -10, -20, -20, -20, -20, -20, -20, -10, 20, 20, 0, 0, 0, 0, 20, 20, 20, 30, 10, 0, 0, 10, 30, 20 ) val kingSquareEndGame = intArrayOf( -50, -40, -30, -20, -20, -30, -40, -50, -30, -20, -10, 0, 0, -10, -20, -30, -30, -10, 20, 30, 30, 20, -10, -30, -30, -10, 30, 40, 40, 30, -10, -30, -30, -10, 30, 40, 40, 30, -10, -30, -30, -10, 20, 30, 30, 20, -10, -30, -30, -30, 0, 0, 0, 0, -30, -30, -50, -30, -30, -30, -30, -30, -30, -50 ) } }
mit
802423ce6df9e2d1b3a7921f8b94304a
36.206061
129
0.427827
3.103134
false
false
false
false
GoogleCloudPlatform/bigquery-utils
tools/sql_extraction/src/main/kotlin/Cli.kt
1
3888
package com.google.cloud.sqlecosystem.sqlextraction import com.github.ajalt.clikt.core.CliktCommand import com.github.ajalt.clikt.parameters.arguments.argument import com.github.ajalt.clikt.parameters.arguments.multiple import com.github.ajalt.clikt.parameters.options.default import com.github.ajalt.clikt.parameters.options.flag import com.github.ajalt.clikt.parameters.options.multiple import com.github.ajalt.clikt.parameters.options.option import com.github.ajalt.clikt.parameters.types.double import com.github.ajalt.clikt.parameters.types.path import com.google.gson.Gson import com.google.gson.GsonBuilder import mu.KotlinLogging import org.slf4j.impl.SimpleLogger import java.nio.file.Path fun main(args: Array<String>) = Cli( FilesExpander(), SqlExtractor( DataFlowSolver( listOf( JavaFrontEnd(), PythonFrontEnd() ) ), ConfidenceRater() ) ).main(args) private class Cli( private val filesExpander: FilesExpander, private val sqlExtractor: SqlExtractor ) : CliktCommand( name = "sql_extraction", printHelpOnEmptyArgs = true, help = """ Command line application to extract raw SQL query strings and their usage within code. Sample Usages: ``` > sql_extraction path/to/file.java > sql_extraction -r path/to/directory path/to/another/directory path/to/file.java > sql_extraction --include="*.java" path/to/directory > sql_extraction -r --include="*.java" --include="*.cs" . > sql_extraction -r --exclude="*.cs" / ``` """ ) { private val filePaths: List<Path> by argument( help = "File and directory paths to analyze" ).path( mustExist = true, canBeDir = true, canBeFile = true ).multiple() private val recursive: Boolean by option( "-R", "-r", "--recursive", help = "Scan files in subdirectories recursively" ).flag() private val includes: List<String> by option( "--include", metavar = "GLOB", help = "Search only files whose base name matches GLOB" ).multiple() private val excludes: List<String> by option( "--exclude", metavar = "GLOB", help = "Skip files whose base name matches GLOB" ).multiple() private val prettyPrint: Boolean by option( "--pretty", help = "Pretty-print output JSON" ).flag() private val showProgress: Boolean by option( "--progress", help = "Print progress to STDERR" ).flag() private val confidenceThreshold: Double by option( "--threshold", help = "Minimum confidence value (inclusive between 0 and 1) " + "required for a detected query to be included in final " + "output (default is 0.5)" ).double().default(0.5) private val parallelize: Boolean by option( "--parallel", help = "Analyze multiple files in parallel" ).flag() private val debug: Boolean by option( "--debug", "--verbose", help = "Print debug logs to STDERR" ).flag() override fun run() { if (debug) { System.setProperty(SimpleLogger.DEFAULT_LOG_LEVEL_KEY, "Debug") } val logger = KotlinLogging.logger { } logger.debug("Starting SQL Extraction from command line") val files = filesExpander.expandAndFilter(filePaths, recursive, includes, excludes) if (showProgress) { System.err.println("0.0% Analyzing files...") } val output = sqlExtractor.process(files, confidenceThreshold, showProgress, parallelize) logger.debug { "output: ${Gson().toJson(output)}" } val builder = GsonBuilder() if (prettyPrint) { builder.setPrettyPrinting() } val json = builder.create().toJson(output) println(json) } }
apache-2.0
ddd7f078e5b735275610a096ebab9a50
31.132231
96
0.641204
4.239913
false
false
false
false
jmesserli/discord-bernbot
discord-bot/src/main/kotlin/nu/peg/discord/service/internal/DefaultChannelService.kt
1
902
package nu.peg.discord.service.internal import nu.peg.discord.service.ChannelService import nu.peg.discord.util.DiscordClientListener import org.slf4j.LoggerFactory import org.springframework.stereotype.Service import sx.blah.discord.api.IDiscordClient import sx.blah.discord.handle.obj.IChannel @Service class DefaultChannelService : ChannelService, DiscordClientListener { companion object { private val LOGGER = LoggerFactory.getLogger(DefaultChannelService::class.java) } private var client: IDiscordClient? = null override fun discordClientAvailable(client: IDiscordClient) { this.client = client } override fun findByName(name: String): IChannel? { if (client == null) { LOGGER.info("Client not set, not searching channel") return null } return client!!.channels.firstOrNull { it.name == name } } }
mit
f198b7135477226185ea3fed86095207
29.1
87
0.723947
4.51
false
false
false
false
Shynixn/BlockBall
blockball-bukkit-plugin/src/main/java/com/github/shynixn/blockball/bukkit/logic/business/service/ProtocolServiceImpl.kt
1
6009
package com.github.shynixn.blockball.bukkit.logic.business.service import com.github.shynixn.blockball.api.bukkit.event.PacketEvent import com.github.shynixn.blockball.api.business.enumeration.Version import com.github.shynixn.blockball.api.business.proxy.PluginProxy import com.github.shynixn.blockball.api.business.service.ProtocolService import com.github.shynixn.blockball.core.logic.business.extension.accessible import com.google.inject.Inject import io.netty.channel.Channel import io.netty.channel.ChannelDuplexHandler import io.netty.channel.ChannelHandlerContext import org.bukkit.Bukkit import org.bukkit.entity.Player import org.bukkit.plugin.Plugin import java.util.* import java.util.logging.Level class ProtocolServiceImpl @Inject constructor(private val plugin: PluginProxy, private val internalPlugin: Plugin) : ProtocolService { private val handlerName = "BlockBall" + "-" + UUID.randomUUID().toString() private val playerToNmsPlayer by lazy { plugin.findClazz("org.bukkit.craftbukkit.VERSION.entity.CraftPlayer") .getDeclaredMethod("getHandle") } private val playerConnectionField by lazy { try { plugin.findClazz("net.minecraft.server.level.EntityPlayer") .getDeclaredField("b") } catch (e: Exception) { plugin.findClazz("net.minecraft.server.VERSION.EntityPlayer") .getDeclaredField("playerConnection") } } private val networkManagerField by lazy { try { if(plugin.getServerVersion().isVersionSameOrGreaterThan(Version.VERSION_1_19_R1)){ plugin.findClazz("net.minecraft.server.network.PlayerConnection") .getDeclaredField("b") .accessible(true) }else{ plugin.findClazz("net.minecraft.server.network.PlayerConnection") .getDeclaredField("a") } } catch (e: Exception) { plugin.findClazz("net.minecraft.server.VERSION.PlayerConnection") .getDeclaredField("networkManager") } } private val channelField by lazy { try { if (plugin.getServerVersion().isVersionSameOrGreaterThan(Version.VERSION_1_18_R2)) { plugin.findClazz("net.minecraft.network.NetworkManager") .getDeclaredField("m") .accessible(true) } else if (plugin.getServerVersion().isVersionSameOrGreaterThan(Version.VERSION_1_17_R1)) { plugin.findClazz("net.minecraft.network.NetworkManager") .getDeclaredField("k") .accessible(true) } else { throw RuntimeException("Impl not found!") } } catch (e1: Exception) { e1.printStackTrace() plugin.findClazz("net.minecraft.server.VERSION.NetworkManager") .getDeclaredField("channel") } } private val cachedPlayerChannels = HashMap<Player, Channel>() private val registeredPackets = HashSet<Class<*>>() /** * Registers the following packets classes for events. */ override fun registerPackets(packets: List<Class<*>>) { registeredPackets.addAll(packets) } /** * Registers the player. */ override fun <P> register(player: P) { require(player is Player) if (cachedPlayerChannels.containsKey(player)) { return } val nmsPlayer = playerToNmsPlayer .invoke(player) val connection = playerConnectionField .get(nmsPlayer) val netWorkManager = networkManagerField.get(connection) val channel = channelField .get(netWorkManager) as Channel val internalInterceptor = PacketInterceptor(player, this) channel.pipeline().addBefore("packet_handler", handlerName, internalInterceptor) cachedPlayerChannels[player] = channel } /** * Clears the player cache. */ override fun <P> unRegister(player: P) { require(player is Player) if (!cachedPlayerChannels.containsKey(player)) { return } val channel = cachedPlayerChannels[player] channel!!.eventLoop().execute { try { channel.pipeline().remove(handlerName) } catch (e: Exception) { // Ignored } } cachedPlayerChannels.remove(player) } /** * Disposes the protocol service. */ override fun dispose() { for (player in cachedPlayerChannels.keys.toTypedArray()) { unRegister(player) } registeredPackets.clear() } /** * On Message receive. */ private fun onMessageReceive(player: Player, packet: Any): Boolean { if (!plugin.isEnabled()) { return false } if (cachedPlayerChannels.isEmpty()) { return false } if (!this.registeredPackets.contains(packet.javaClass)) { return false } internalPlugin.server.scheduler.runTask(internalPlugin, Runnable { val packetEvent = PacketEvent(player, packet) Bukkit.getPluginManager().callEvent(packetEvent) }) return false } private class PacketInterceptor( private val player: Player, private val protocolServiceImpl: ProtocolServiceImpl ) : ChannelDuplexHandler() { /** * Incoming packet. */ override fun channelRead(ctx: ChannelHandlerContext, msg: Any) { val cancelled = try { protocolServiceImpl.onMessageReceive(player, msg) } catch (e: Exception) { Bukkit.getServer().logger.log(Level.SEVERE, "Failed to read packet.", e) false } if (!cancelled) { super.channelRead(ctx, msg) } } } }
apache-2.0
df12e3d93977d7f34404f8fa0817e68e
32.569832
116
0.61358
4.913328
false
false
false
false
actions-on-google/actions-on-google-java
src/main/kotlin/com/google/actions/api/response/helperintent/Confirmation.kt
1
2657
/* * Copyright 2018 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.actions.api.response.helperintent import com.google.api.services.actions_fulfillment.v2.model.ConfirmationValueSpecConfirmationDialogSpec /** * Helper intent response to ask user for confirmation. * * ``` Java * @ForIntent("askForConfirmation") * public CompletableFuture<ActionResponse> askForConfirmation(ActionRequest request) { * ResponseBuilder responseBuilder = getResponseBuilder(); * responseBuilder * .add("Placeholder for confirmation text") * .add(new Confirmation().setConfirmationText("Are you sure?")); * return CompletableFuture.completedFuture(responseBuilder.build()); * } * ``` * * The following code demonstrates how to handle the confirmation response from * the user. * * ``` Java * @ForIntent("actions_intent_confirmation") * public CompletableFuture<ActionResponse> handleConfirmationResponse( * ActionRequest request) { * boolean userResponse = request.getUserConfirmation() != null && * request.getUserConfirmation().booleanValue(); * ResponseBuilder responseBuilder = getResponseBuilder(); * responseBuilder.add( * userResponse ? "Thank you for confirming" : * "No problem. We won't bother you"); * return CompletableFuture.completedFuture(responseBuilder.build()); * } * ``` */ class Confirmation : HelperIntent { private var confirmationText: String? = null private val map = HashMap<String, Any>() fun setConfirmationText(confirmationText: String): Confirmation { this.confirmationText = confirmationText return this } override val name: String get() = "actions.intent.CONFIRMATION" override val parameters: Map<String, Any> get() { prepareMap() return map } private fun prepareMap() { map.put("@type", "type.googleapis.com/google.actions.v2.ConfirmationValueSpec") map.put("dialogSpec", ConfirmationValueSpecConfirmationDialogSpec() .setRequestConfirmationText(confirmationText)) } }
apache-2.0
98a69308e7261253ac5657d073b59339
33.960526
103
0.712081
4.549658
false
false
false
false
paronos/tachiyomi
app/src/main/java/eu/kanade/tachiyomi/data/database/tables/TrackTable.kt
2
1374
package eu.kanade.tachiyomi.data.database.tables object TrackTable { const val TABLE = "manga_sync" const val COL_ID = "_id" const val COL_MANGA_ID = "manga_id" const val COL_SYNC_ID = "sync_id" const val COL_REMOTE_ID = "remote_id" const val COL_TITLE = "title" const val COL_LAST_CHAPTER_READ = "last_chapter_read" const val COL_STATUS = "status" const val COL_SCORE = "score" const val COL_TOTAL_CHAPTERS = "total_chapters" const val COL_TRACKING_URL = "remote_url" val createTableQuery: String get() = """CREATE TABLE $TABLE( $COL_ID INTEGER NOT NULL PRIMARY KEY, $COL_MANGA_ID INTEGER NOT NULL, $COL_SYNC_ID INTEGER NOT NULL, $COL_REMOTE_ID INTEGER NOT NULL, $COL_TITLE TEXT NOT NULL, $COL_LAST_CHAPTER_READ INTEGER NOT NULL, $COL_TOTAL_CHAPTERS INTEGER NOT NULL, $COL_STATUS INTEGER NOT NULL, $COL_SCORE FLOAT NOT NULL, $COL_TRACKING_URL TEXT NOT NULL, UNIQUE ($COL_MANGA_ID, $COL_SYNC_ID) ON CONFLICT REPLACE, FOREIGN KEY($COL_MANGA_ID) REFERENCES ${MangaTable.TABLE} (${MangaTable.COL_ID}) ON DELETE CASCADE )""" val addTrackingUrl: String get() = "ALTER TABLE $TABLE ADD COLUMN $COL_TRACKING_URL TEXT DEFAULT ''" }
apache-2.0
00d21130314aa61c5a6f44f0867e407d
28.869565
92
0.604076
3.837989
false
false
false
false
blackbbc/Tucao
app/src/main/kotlin/me/sweetll/tucao/business/home/fragment/RecommendFragment.kt
1
7020
package me.sweetll.tucao.business.home.fragment import android.annotation.TargetApi import androidx.databinding.DataBindingUtil import android.os.Build import android.os.Bundle import androidx.core.app.ActivityOptionsCompat import androidx.core.util.Pair import android.transition.ArcMotion import android.transition.ChangeBounds import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.recyclerview.widget.LinearLayoutManager import androidx.transition.TransitionManager import com.bigkoo.convenientbanner.ConvenientBanner import com.chad.library.adapter.base.BaseQuickAdapter import com.chad.library.adapter.base.listener.OnItemChildClickListener import me.sweetll.tucao.R import me.sweetll.tucao.base.BaseFragment import me.sweetll.tucao.business.channel.ChannelDetailActivity import me.sweetll.tucao.business.home.adapter.BannerHolder import me.sweetll.tucao.business.home.adapter.RecommendAdapter import me.sweetll.tucao.business.home.viewmodel.RecommendViewModel import me.sweetll.tucao.business.video.VideoActivity import me.sweetll.tucao.databinding.FragmentRecommendBinding import me.sweetll.tucao.extension.logD import me.sweetll.tucao.model.raw.Banner import me.sweetll.tucao.model.raw.Index class RecommendFragment : BaseFragment() { lateinit var binding: FragmentRecommendBinding lateinit var headerView: View val viewModel = RecommendViewModel(this) val recommendAdapter = RecommendAdapter(null) var isLoad = false override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { binding = DataBindingUtil.inflate(inflater, R.layout.fragment_recommend, container, false) binding.loading.show() binding.viewModel = viewModel return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) binding.swipeRefresh.isEnabled = false binding.swipeRefresh.setColorSchemeResources(R.color.colorPrimary) binding.swipeRefresh.setOnRefreshListener { viewModel.loadData() } binding.errorStub.setOnInflateListener { _, inflated -> inflated.setOnClickListener { viewModel.loadData() } } setupRecyclerView() loadWhenNeed() if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { initTransition() } } fun setupRecyclerView() { headerView = LayoutInflater.from(activity).inflate(R.layout.header_banner, binding.root as ViewGroup, false) recommendAdapter.addHeaderView(headerView) binding.recommendRecycler.layoutManager = LinearLayoutManager(activity) binding.recommendRecycler.adapter = recommendAdapter // Item子控件点击 binding.recommendRecycler.addOnItemTouchListener(object: OnItemChildClickListener() { override fun onSimpleItemChildClick(adapter: BaseQuickAdapter<*, *>, view: View, position: Int) { when (view.id) { R.id.img_rank -> { viewModel.onClickRank(view) } R.id.card_more -> { ChannelDetailActivity.intentTo(activity!!, view.tag as Int) } R.id.card1, R.id.card2, R.id.card3, R.id.card4 -> { if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { val coverImg = (((view as ViewGroup).getChildAt(0) as ViewGroup).getChildAt(0) as ViewGroup).getChildAt(0) val titleText = (view.getChildAt(0) as ViewGroup).getChildAt(1) val p1: Pair<View, String> = Pair.create(coverImg, "cover") val p2: Pair<View, String> = Pair.create(titleText, "bg") val cover = titleText.tag as String val options = ActivityOptionsCompat .makeSceneTransitionAnimation(activity!!, p1, p2) VideoActivity.intentTo(activity!!, view.tag as String, cover, options.toBundle()) } else { VideoActivity.intentTo(activity!!, view.tag as String) } } } } }) } @TargetApi(Build.VERSION_CODES.LOLLIPOP) fun initTransition() { val changeBounds = ChangeBounds() val arcMotion = ArcMotion() changeBounds.pathMotion = arcMotion activity!!.window.sharedElementExitTransition = changeBounds activity!!.window.sharedElementReenterTransition = null } override fun setUserVisibleHint(isVisibleToUser: Boolean) { super.setUserVisibleHint(isVisibleToUser) loadWhenNeed() } fun loadWhenNeed() { if (isVisible && userVisibleHint && !isLoad && !binding.swipeRefresh.isRefreshing) { viewModel.loadData() } } fun loadIndex(index: Index) { if (!isLoad) { isLoad = true TransitionManager.beginDelayedTransition(binding.swipeRefresh) binding.swipeRefresh.isEnabled = true binding.loading.visibility = View.GONE if (binding.errorStub.isInflated) { binding.errorStub.root.visibility = View.GONE } binding.recommendRecycler.visibility = View.VISIBLE } (headerView as ConvenientBanner<Banner>).setPages({ BannerHolder() }, index.banners) .setPageIndicator(intArrayOf(R.drawable.indicator_white_circle, R.drawable.indicator_pink_circle)) .setPageIndicatorAlign(ConvenientBanner.PageIndicatorAlign.CENTER_HORIZONTAL) .startTurning(3000) recommendAdapter.setNewData(index.recommends) } fun loadError() { if (!isLoad) { TransitionManager.beginDelayedTransition(binding.swipeRefresh) binding.loading.visibility = View.GONE if (!binding.errorStub.isInflated) { binding.errorStub.viewStub!!.visibility = View.VISIBLE } else { binding.errorStub.root.visibility = View.VISIBLE } } } fun setRefreshing(isRefreshing: Boolean) { if (isLoad) { binding.swipeRefresh.isRefreshing = isRefreshing } else { TransitionManager.beginDelayedTransition(binding.swipeRefresh) binding.loading.visibility = if (isRefreshing) View.VISIBLE else View.GONE if (isRefreshing) { if (!binding.errorStub.isInflated) { binding.errorStub.viewStub!!.visibility = View.GONE } else { binding.errorStub.root.visibility = View.GONE } } } } }
mit
7bb8169954f9195c374bc62a2bbdb044
39.526012
134
0.643367
5.05772
false
false
false
false
valich/intellij-markdown
src/commonMain/kotlin/org/intellij/markdown/parser/markerblocks/providers/AtxHeaderProvider.kt
1
2701
package org.intellij.markdown.parser.markerblocks.providers import org.intellij.markdown.parser.LookaheadText import org.intellij.markdown.parser.MarkerProcessor import org.intellij.markdown.parser.ProductionHolder import org.intellij.markdown.parser.constraints.MarkdownConstraints import org.intellij.markdown.parser.markerblocks.MarkerBlock import org.intellij.markdown.parser.markerblocks.MarkerBlockProvider import org.intellij.markdown.parser.markerblocks.impl.AtxHeaderMarkerBlock class AtxHeaderProvider : MarkerBlockProvider<MarkerProcessor.StateInfo> { override fun createMarkerBlocks(pos: LookaheadText.Position, productionHolder: ProductionHolder, stateInfo: MarkerProcessor.StateInfo): List<MarkerBlock> { val headerRange = matches(pos) if (headerRange != null) { return listOf(AtxHeaderMarkerBlock(stateInfo.currentConstraints, productionHolder, headerRange, calcTailStartPos(pos, headerRange.last), pos.nextLineOrEofOffset)) } else { return emptyList() } } private fun calcTailStartPos(pos: LookaheadText.Position, headerSize: Int): Int { val line = pos.currentLineFromPosition var offset = line.length - 1 while (offset > headerSize && line[offset].isWhitespace()) { offset-- } while (offset > headerSize && line[offset] == '#' && line[offset - 1] != '\\') { offset-- } if (offset + 1 < line.length && line[offset].isWhitespace() && line[offset + 1] == '#') { return pos.offset + offset + 1 } else { return pos.offset + line.length } } override fun interruptsParagraph(pos: LookaheadText.Position, constraints: MarkdownConstraints): Boolean { return matches(pos) != null } private fun matches(pos: LookaheadText.Position): IntRange? { if (pos.offsetInCurrentLine != -1) { val text = pos.currentLineFromPosition var offset = MarkerBlockProvider.passSmallIndent(text) if (offset >= text.length || text[offset] != '#') { return null } val start = offset repeat(6) { if (offset < text.length && text[offset] == '#') { offset++ } } if (offset < text.length && text[offset] !in listOf(' ', '\t')) { return null } return IntRange(start, offset - 1) } return null } }
apache-2.0
5a5b56b67c3edf5b68d4964e4552917e
37.6
110
0.590152
5.10586
false
false
false
false
Stuie/papercut
papercut-compiler/src/main/java/ie/stu/papercut/compiler/AnnotationProcessor.kt
1
8908
/* * Copyright (C) 2020 Stuart Gilbert * * 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 ie.stu.papercut.compiler import com.github.zafarkhaja.semver.Version import javax.lang.model.SourceVersion import com.google.auto.service.AutoService import ie.stu.papercut.Debt import javax.lang.model.element.TypeElement import ie.stu.papercut.Milestone import net.ltgt.gradle.incap.IncrementalAnnotationProcessor import net.ltgt.gradle.incap.IncrementalAnnotationProcessorType import java.time.LocalDate import javax.tools.Diagnostic import java.time.format.DateTimeFormatter import java.time.format.DateTimeParseException import javax.annotation.processing.AbstractProcessor import javax.annotation.processing.Messager import javax.annotation.processing.ProcessingEnvironment import javax.annotation.processing.Processor import javax.annotation.processing.RoundEnvironment import javax.annotation.processing.SupportedAnnotationTypes import javax.annotation.processing.SupportedOptions import javax.annotation.processing.SupportedSourceVersion import javax.lang.model.element.Element @SupportedAnnotationTypes( "ie.stu.papercut.Debt", "ie.stu.papercut.Milestone" ) @SupportedSourceVersion(SourceVersion.RELEASE_8) @SupportedOptions(OPTION_VERSION_CODE, OPTION_VERSION_NAME) @AutoService(Processor::class) @IncrementalAnnotationProcessor(IncrementalAnnotationProcessorType.ISOLATING) class AnnotationProcessor : AbstractProcessor() { private val milestones = mutableSetOf<String>() private lateinit var messager: Messager private var versionCode: String? = null private var versionName: String? = null @Synchronized override fun init(processingEnv: ProcessingEnvironment) { super.init(processingEnv) versionCode = processingEnv.options[OPTION_VERSION_CODE] versionName = processingEnv.options[OPTION_VERSION_NAME] messager = processingEnv.messager } override fun process(annotations: Set<TypeElement?>, roundEnv: RoundEnvironment): Boolean { buildMilestoneList(roundEnv.getElementsAnnotatedWith(Milestone::class.java)) parseTechDebtElements(roundEnv.getElementsAnnotatedWith(Debt::class.java)) return true } override fun getSupportedSourceVersion(): SourceVersion { return SourceVersion.latest() } private fun buildMilestoneList(elements: Set<Element>) { for (element in elements) { val milestone = element.getAnnotation(Milestone::class.java) val milestoneName: String = milestone.value milestones.add(milestoneName) } } private fun parseTechDebtElements(elements: Set<Element>) { elements.forEach { element -> element.getAnnotation(Debt::class.java)?.let { debtAnnotation -> val value = debtAnnotation.value val description = debtAnnotation.description val reason = debtAnnotation.reason val addedDate = debtAnnotation.addedDate val stopShip = debtAnnotation.stopShip val milestone = debtAnnotation.milestone val removalDate = debtAnnotation.removalDate val versionCode: Int = debtAnnotation.versionCode val versionName = debtAnnotation.versionName val messageKind = if (stopShip) { Diagnostic.Kind.ERROR } else { Diagnostic.Kind.WARNING } val dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd") val parsedRemovalDate: LocalDate? = try { if (removalDate.isNotEmpty()) { LocalDate.parse(removalDate, dateTimeFormatter) } else { null } } catch (e: DateTimeParseException) { messager.printMessage( Diagnostic.Kind.ERROR, String.format( "Unrecognized date format in Papercut annotation '%1\$s'. Please use yyyy-MM-dd format " + "for removalDate (e.g. 2020-01-31): %2\$s", removalDate, e.localizedMessage ), element ) null } val breakConditionMet = noConditionsSet(parsedRemovalDate, milestone, versionCode, versionName) || dateConditionMet(parsedRemovalDate) || milestoneConditionMet(milestone) || versionCodeConditionMet(versionCode) || versionNameConditionMet(versionName, element) if (breakConditionMet) { printDebtMessage(messager, messageKind, value, description, addedDate, reason, milestone, element) } } } } private fun noConditionsSet(date: LocalDate?, milestone: String, versionCode: Int, versionName: String): Boolean { return date == null && milestone.isEmpty() && versionCode == Int.MAX_VALUE && versionName.isEmpty() } private fun dateConditionMet(date: LocalDate?): Boolean { return date != null && (date.isBefore(LocalDate.now()) || date == LocalDate.now()) } private fun milestoneConditionMet(milestone: String): Boolean { return milestone.isNotEmpty() && !milestones.contains(milestone) } private fun versionCodeConditionMet(versionCode: Int): Boolean { return this.versionCode?.let { it.isNotEmpty() && versionCode != Int.MAX_VALUE && versionCode <= it.toInt() } ?: false } private fun versionNameConditionMet(versionName: String, element: Element): Boolean { // Drop out quickly if there's no versionName set otherwise the try/catch below is doomed to fail. if (versionName.isEmpty()) return false val comparison = try { val conditionVersion = Version.valueOf(versionName) val currentVersion = Version.valueOf(this.versionName) Version.BUILD_AWARE_ORDER.compare(conditionVersion, currentVersion) } catch (e: Exception) { messager.printMessage( Diagnostic.Kind.ERROR, String.format( "Failed to parse version name: %1\$s or %2\$s. Please use a versionName that matches the " + "specification on http://semver.org/", versionName, this.versionName ), element ) // Assume the break condition is met if the versionName is invalid. return true } return versionName.isNotEmpty() && comparison <= 0 } private fun printDebtMessage( messager: Messager, messageKind: Diagnostic.Kind, value: String, description: String, addedDate: String, reason: String, milestone: String, element: Element, ) { val messageBuilder = StringBuilder(DEBT_FOUND) messageBuilder.append(if (value.isNotEmpty()) { " $VALUE '%1\$s'," } else { "%1\$s" }) if (addedDate.isNotEmpty()) { messageBuilder.append(" $ADDED_DATE '%2\$s',") } else { messageBuilder.append("%2\$s") } if (reason.isNotEmpty()) { messageBuilder.append(" $DEBT_REASON '%3\$s',") } else { messageBuilder.append("%3\$s") } if (milestone.isNotEmpty()) { messageBuilder.append(" $MILESTONE '%4\$s',") } else { messageBuilder.append("%4\$s") } if (description.isNotEmpty()) { messageBuilder.append(" $WITH_DESCRIPTION '%5\$s',") } else { messageBuilder.append("%5\$s") } messageBuilder.append(" at: ") messager.printMessage( messageKind, String.format( messageBuilder.toString(), value, addedDate, reason, milestone, description ), element ) } }
apache-2.0
bdc924c25027c97fb38416163045dbe5
36.745763
118
0.61282
5.137255
false
false
false
false
tokenbrowser/token-android-client
app/src/main/java/com/toshi/manager/transaction/UpdateTransactionManager.kt
1
6512
/* * Copyright (c) 2017. Toshi Inc * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.toshi.manager.transaction import android.util.Pair import com.toshi.exception.UnknownTransactionException import com.toshi.manager.store.PendingTransactionStore import com.toshi.model.local.PendingTransaction import com.toshi.model.local.Recipient import com.toshi.model.local.User import com.toshi.model.sofa.PaymentRequest import com.toshi.model.sofa.SofaAdapters import com.toshi.model.sofa.SofaMessage import com.toshi.model.sofa.SofaType import com.toshi.model.sofa.payment.Payment import com.toshi.util.logging.LogUtil import com.toshi.view.BaseApplication import rx.Observable import rx.Subscription import rx.schedulers.Schedulers import rx.subjects.PublishSubject import rx.subscriptions.CompositeSubscription import java.io.IOException class UpdateTransactionManager(private val pendingTransactionStore: PendingTransactionStore) { private val chatManager by lazy { BaseApplication.get().chatManager } private val balanceManager by lazy { BaseApplication.get().balanceManager } private val updatePaymentQueue by lazy { PublishSubject.create<Payment>() } private val subscriptions by lazy { CompositeSubscription() } private var updatePaymentSub: Subscription? = null fun attachUpdatePaymentSubscriber() { // Explicitly clear first to avoid double subscription clearSubscription() updatePaymentSub = updatePaymentQueue .filter { it != null } .subscribeOn(Schedulers.io()) .subscribe( { processUpdatedPayment(it) }, { LogUtil.exception("Error when updating payment $it") } ) subscriptions.add(updatePaymentSub) } private fun processUpdatedPayment(payment: Payment) { val sub = pendingTransactionStore .loadTransaction(payment.txHash) .subscribeOn(Schedulers.io()) .subscribe( { updatePendingTransaction(it, payment) }, { LogUtil.exception("Error while handling pending transactions $it") } ) subscriptions.add(sub) } fun updatePendingTransactions() { val sub = pendingTransactionStore .loadAllTransactions() .toObservable() .flatMapIterable { it } .filter { isUnconfirmed(it) } .flatMap { Observable.zip( Observable.just(it), getTransactionStatus(it), { first, second -> Pair(first, second) } ) } .onErrorReturn { Pair(null, null) } .subscribeOn(Schedulers.io()) .subscribe( { updatePendingTransaction(it.first, it.second) }, { LogUtil.exception("Error during updating pending transaction $it") } ) subscriptions.add(sub) } private fun getTransactionStatus(pendingTransaction: PendingTransaction): Observable<Payment> { return balanceManager .getTransactionStatus(pendingTransaction.txHash) .toObservable() } // Returns false if this is a new transaction that the app is unaware of. // Returns true if the transaction was correctly updated. private fun updatePendingTransaction(pendingTransaction: PendingTransaction?, updatedPayment: Payment?): Boolean { if (pendingTransaction == null || updatedPayment == null) return false return try { val updatedMessage = updateStatusFromPendingTransaction(pendingTransaction, updatedPayment) val updatedPendingTransaction = PendingTransaction() .setTxHash(pendingTransaction.txHash) .setSofaMessage(updatedMessage) pendingTransactionStore.save(updatedPendingTransaction) true } catch (ex: IOException) { LogUtil.exception("Unable to update pending transaction $ex") false } } @Throws(IOException::class, UnknownTransactionException::class) private fun updateStatusFromPendingTransaction(pendingTransaction: PendingTransaction, updatedPayment: Payment): SofaMessage { val sofaMessage = pendingTransaction.sofaMessage val existingPayment = SofaAdapters.get().paymentFrom(sofaMessage.payload) existingPayment.status = updatedPayment.status val messageBody = SofaAdapters.get().toJson(existingPayment) return sofaMessage.setPayload(messageBody) } private fun isUnconfirmed(pendingTransaction: PendingTransaction): Boolean { return try { val sofaMessage = pendingTransaction.sofaMessage val payment = SofaAdapters.get().paymentFrom(sofaMessage.payload) payment.status == SofaType.UNCONFIRMED } catch (ex: IOException) { false } } fun updatePaymentRequestState(remoteUser: User, sofaMessage: SofaMessage, @PaymentRequest.State newState: Int) { try { val paymentRequest = SofaAdapters.get() .txRequestFrom(sofaMessage.payload) .setState(newState) val recipient = Recipient(remoteUser) val updatedPayload = SofaAdapters.get().toJson(paymentRequest) sofaMessage.payload = updatedPayload chatManager.updateMessage(recipient, sofaMessage) } catch (ex: IOException) { LogUtil.exception("Error changing Payment Request state $ex") } } fun updatePayment(payment: Payment) = updatePaymentQueue.onNext(payment) fun clearSubscription() = updatePaymentSub?.unsubscribe() }
gpl-3.0
e99b61b461c7be761d03448625a25cff
41.019355
130
0.658477
5.071651
false
false
false
false
JetBrains/anko
anko/library/static/commons/src/main/java/Logging.kt
4
9252
/* * Copyright 2016 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ @file:Suppress("unused", "NOTHING_TO_INLINE") @file:JvmName("Logging") package org.jetbrains.anko import android.util.Log /** * Interface for the Anko logger. * Normally you should pass the logger tag to the [Log] methods, such as [Log.d] or [Log.e]. * This can be inconvenient because you should store the tag somewhere or hardcode it, * which is considered to be a bad practice. * * Instead of hardcoding tags, Anko provides an [AnkoLogger] interface. You can just add the interface to * any of your classes, and use any of the provided extension functions, such as * [AnkoLogger.debug] or [AnkoLogger.error]. * * The tag is the simple class name by default, but you can change it to anything you want just * by overriding the [loggerTag] property. */ interface AnkoLogger { /** * The logger tag used in extension functions for the [AnkoLogger]. * Note that the tag length should not be more than 23 symbols. */ val loggerTag: String get() = getTag(javaClass) } fun AnkoLogger(clazz: Class<*>): AnkoLogger = object : AnkoLogger { override val loggerTag = getTag(clazz) } fun AnkoLogger(tag: String): AnkoLogger = object : AnkoLogger { init { assert(tag.length <= 23) { "The maximum tag length is 23, got $tag" } } override val loggerTag = tag } inline fun <reified T: Any> AnkoLogger(): AnkoLogger = AnkoLogger(T::class.java) /** * Send a log message with the [Log.VERBOSE] severity. * Note that the log message will not be written if the current log level is above [Log.VERBOSE]. * The default log level is [Log.INFO]. * * @param message the message text to log. `null` value will be represent as "null", for any other value * the [Any.toString] will be invoked. * @param thr an exception to log (optional). * * @see [Log.v]. */ fun AnkoLogger.verbose(message: Any?, thr: Throwable? = null) { log(this, message, thr, Log.VERBOSE, { tag, msg -> Log.v(tag, msg) }, { tag, msg, thr -> Log.v(tag, msg, thr) }) } /** * Send a log message with the [Log.DEBUG] severity. * Note that the log message will not be written if the current log level is above [Log.DEBUG]. * The default log level is [Log.INFO]. * * @param message the message text to log. `null` value will be represent as "null", for any other value * the [Any.toString] will be invoked. * @param thr an exception to log (optional). * * @see [Log.d]. */ fun AnkoLogger.debug(message: Any?, thr: Throwable? = null) { log(this, message, thr, Log.DEBUG, { tag, msg -> Log.d(tag, msg) }, { tag, msg, thr -> Log.d(tag, msg, thr) }) } /** * Send a log message with the [Log.INFO] severity. * Note that the log message will not be written if the current log level is above [Log.INFO] * (it is the default level). * * @param message the message text to log. `null` value will be represent as "null", for any other value * the [Any.toString] will be invoked. * @param thr an exception to log (optional). * * @see [Log.i]. */ fun AnkoLogger.info(message: Any?, thr: Throwable? = null) { log(this, message, thr, Log.INFO, { tag, msg -> Log.i(tag, msg) }, { tag, msg, thr -> Log.i(tag, msg, thr) }) } /** * Send a log message with the [Log.WARN] severity. * Note that the log message will not be written if the current log level is above [Log.WARN]. * The default log level is [Log.INFO]. * * @param message the message text to log. `null` value will be represent as "null", for any other value * the [Any.toString] will be invoked. * @param thr an exception to log (optional). * * @see [Log.w]. */ fun AnkoLogger.warn(message: Any?, thr: Throwable? = null) { log(this, message, thr, Log.WARN, { tag, msg -> Log.w(tag, msg) }, { tag, msg, thr -> Log.w(tag, msg, thr) }) } /** * Send a log message with the [Log.ERROR] severity. * Note that the log message will not be written if the current log level is above [Log.ERROR]. * The default log level is [Log.INFO]. * * @param message the message text to log. `null` value will be represent as "null", for any other value * the [Any.toString] will be invoked. * @param thr an exception to log (optional). * * @see [Log.e]. */ fun AnkoLogger.error(message: Any?, thr: Throwable? = null) { log(this, message, thr, Log.ERROR, { tag, msg -> Log.e(tag, msg) }, { tag, msg, thr -> Log.e(tag, msg, thr) }) } /** * Send a log message with the "What a Terrible Failure" severity. * Report an exception that should never happen. * * @param message the message text to log. `null` value will be represent as "null", for any other value * the [Any.toString] will be invoked. * @param thr an exception to log (optional). * * @see [Log.wtf]. */ fun AnkoLogger.wtf(message: Any?, thr: Throwable? = null) { if (thr != null) { Log.wtf(loggerTag, message?.toString() ?: "null", thr) } else { Log.wtf(loggerTag, message?.toString() ?: "null") } } /** * Send a log message with the [Log.VERBOSE] severity. * Note that the log message will not be written if the current log level is above [Log.VERBOSE]. * The default log level is [Log.INFO]. * * @param message the function that returns message text to log. * `null` value will be represent as "null", for any other value the [Any.toString] will be invoked. * * @see [Log.v]. */ inline fun AnkoLogger.verbose(message: () -> Any?) { val tag = loggerTag if (Log.isLoggable(tag, Log.VERBOSE)) { Log.v(tag, message()?.toString() ?: "null") } } /** * Send a log message with the [Log.DEBUG] severity. * Note that the log message will not be written if the current log level is above [Log.DEBUG]. * The default log level is [Log.INFO]. * * @param message the function that returns message text to log. * `null` value will be represent as "null", for any other value the [Any.toString] will be invoked. * * @see [Log.d]. */ inline fun AnkoLogger.debug(message: () -> Any?) { val tag = loggerTag if (Log.isLoggable(tag, Log.DEBUG)) { Log.d(tag, message()?.toString() ?: "null") } } /** * Send a log message with the [Log.INFO] severity. * Note that the log message will not be written if the current log level is above [Log.INFO]. * The default log level is [Log.INFO]. * * @param message the function that returns message text to log. * `null` value will be represent as "null", for any other value the [Any.toString] will be invoked. * * @see [Log.i]. */ inline fun AnkoLogger.info(message: () -> Any?) { val tag = loggerTag if (Log.isLoggable(tag, Log.INFO)) { Log.i(tag, message()?.toString() ?: "null") } } /** * Send a log message with the [Log.WARN] severity. * Note that the log message will not be written if the current log level is above [Log.WARN]. * The default log level is [Log.INFO]. * * @param message the function that returns message text to log. * `null` value will be represent as "null", for any other value the [Any.toString] will be invoked. * * @see [Log.w]. */ inline fun AnkoLogger.warn(message: () -> Any?) { val tag = loggerTag if (Log.isLoggable(tag, Log.WARN)) { Log.w(tag, message()?.toString() ?: "null") } } /** * Send a log message with the [Log.ERROR] severity. * Note that the log message will not be written if the current log level is above [Log.ERROR]. * The default log level is [Log.INFO]. * * @param message the function that returns message text to log. * `null` value will be represent as "null", for any other value the [Any.toString] will be invoked. * * @see [Log.e]. */ inline fun AnkoLogger.error(message: () -> Any?) { val tag = loggerTag if (Log.isLoggable(tag, Log.ERROR)) { Log.e(tag, message()?.toString() ?: "null") } } /** * Return the stack trace [String] of a throwable. */ inline fun Throwable.getStackTraceString(): String = Log.getStackTraceString(this) private inline fun log( logger: AnkoLogger, message: Any?, thr: Throwable?, level: Int, f: (String, String) -> Unit, fThrowable: (String, String, Throwable) -> Unit) { val tag = logger.loggerTag if (Log.isLoggable(tag, level)) { if (thr != null) { fThrowable(tag, message?.toString() ?: "null", thr) } else { f(tag, message?.toString() ?: "null") } } } private fun getTag(clazz: Class<*>): String { val tag = clazz.simpleName return if (tag.length <= 23) { tag } else { tag.substring(0, 23) } }
apache-2.0
16df96c4c91b8c2d71386ea535505946
32.647273
105
0.646563
3.542113
false
false
false
false
songzhw/Hello-kotlin
KotlinPlayground/src/main/kotlin/ca/six/rxjava/FlatMapDemo.kt
1
1326
package ca.six.kplay.rxjava import io.reactivex.Observable fun demo1() { Observable.just(1, 2, 3) .flatMap { if (it % 2 == 0) { Observable.error(RuntimeException("even number")) } else { Observable.just("szw $it") } } .subscribe( { println("next = ${it.substring(0)}") }, { println("error = $it") } ) // 1. 没有flatMap()时。正常打印, 结果分别是: next = 1,next = 2,next = 3, 一共走三次 // 2. 有flatMap()后, 结果分别是: next = 1, error = RuntimeException。 "3"的结果就不走了! } // 写成Observable.onError<Exception>(exp), 那subscribe中第一参Consumer onNext就会不知道it的类型是什么! fun demo2() { val ob = Observable.create<String> { emitter -> emitter.onNext("Test") } ob.flatMap { if (it.length > 2) { Observable.error(RuntimeException("too long")) } else { Observable.just("szw $it") } } .subscribe( { println("next = ${it.substring(0)}") }, { println("error = $it") } ) } fun main(args: Array<String>) { demo2() }
apache-2.0
eeed5d38fe8ef60e71b0707dbfe2597a
25.8
84
0.474295
3.699387
false
false
false
false
songzhw/Hello-kotlin
KotlinPlayground/src/main/kotlin/ca/six/kex/delegate/DelegateDemo.kt
1
663
package ca.six.kex.delegate import kotlin.properties.Delegates val lazyValue: String by lazy{ println("computed") "lazy value name" } // getter没有observe的必要. 所以这里只涉及到setter var id : String by Delegates.observable("initialValue") { property, oldValue, newValue -> println("$property : $oldValue --> $newValue") } fun main(args: Array<String>) { println(lazyValue) //=> computed; lazy value name println(lazyValue) //=> lazy value name id = "97" //=> property id (Kotlin reflection is not available) : initialValue --> 97 id = "be" //=> property id (Kotlin reflection is not available) : 97 --> be }
apache-2.0
292ac96b635a72786499ab7b55bd44ec
28
90
0.676609
3.769231
false
false
false
false
ak-sahli/kata-bank-kotlin
src/main/kotlin/io/aksahli/kata/bank/Account.kt
1
1107
package io.aksahli.kata.bank import io.aksahli.kata.bank.TransactionType.* class Account(val owner: String, initialAmount: Double = 0.0) { val ledger = Ledger() init { deposit(initialAmount) } fun deposit(amount: Double, from: String = "") { ledger.record(Deposit(amount, from)) } fun withdraw(requestedAmount: Double, to: String = "") { if (requestedAmount > this.balance()) { throw InsufficientBalanceException(requestedAmount, this.balance()) } ledger.record(Withdraw(requestedAmount, to)) } fun transfer(amount: Double, payeeAccount: Account) { withdraw(requestedAmount = amount, to = payeeAccount.owner) payeeAccount.deposit(amount = amount, from = owner) } fun balance() = ledger.balance() fun transactions() = ledger.transactions() fun transactionsTo(toAccount: String) = ledger.transactions(WITHDRAW, toAccount) fun transactionsFrom(fromAccount: String) = ledger.transactions(DEPOSIT, fromAccount) override fun toString() = "account {owner: $owner, balance: ${balance()}}" }
mit
3a53ff7635ae806249e9dbf76ef17eb6
29.75
89
0.6757
3.953571
false
false
false
false
raatiniemi/worker
core/src/test/java/me/raatiniemi/worker/domain/model/HoursMinutesAccumulatedTest.kt
1
2577
/* * Copyright (C) 2018 Tobias Raatiniemi * * 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, version 2 of the License. * * 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 me.raatiniemi.worker.domain.model import org.junit.Assert.assertEquals import org.junit.Test import org.junit.runner.RunWith import org.junit.runners.Parameterized import org.junit.runners.Parameterized.Parameters @RunWith(Parameterized::class) class HoursMinutesAccumulatedTest( private val message: String, private val expected: HoursMinutes, private val values: List<HoursMinutes> ) { companion object { @JvmStatic @Parameters fun data(): Collection<Array<Any>> { return listOf( arrayOf( "With empty list of items", HoursMinutes.empty, listOf<HoursMinutes>() ), arrayOf( "With single item", HoursMinutes(hours = 1, minutes = 0), listOf(HoursMinutes(hours = 1, minutes = 0)) ), arrayOf( "With multiple items", HoursMinutes(hours = 2, minutes = 0), listOf( HoursMinutes(hours = 1, minutes = 0), HoursMinutes(hours = 1, minutes = 0) ) ), arrayOf( "With overflowing minutes", HoursMinutes(hours = 3, minutes = 15), listOf( HoursMinutes(hours = 1, minutes = 30), HoursMinutes(hours = 1, minutes = 45) ) ) ) } } @Test fun sum() { val actual = values.accumulated() assertEquals(message, expected, actual) } }
gpl-2.0
81910f9e02d71339148509190df94d03
34.791667
74
0.511835
5.391213
false
false
false
false
ageery/kwicket
kwicket-wicket-core/src/main/kotlin/org/kwicket/wicket/core/markup/html/link/KBookmarkablePageLink.kt
1
1815
package org.kwicket.wicket.core.markup.html.link import org.apache.wicket.Page import org.apache.wicket.behavior.Behavior import org.apache.wicket.markup.html.link.BookmarkablePageLink import org.apache.wicket.markup.html.link.PopupSettings import org.apache.wicket.request.mapper.parameter.PageParameters import org.kwicket.component.init import kotlin.reflect.KClass /** * [BookmarkablePageLink] with named and default constructor arguments. */ open class KBookmarkablePageLink<C : Page>( id: String, page: KClass<C>, params: PageParameters? = null, outputMarkupId: Boolean? = null, outputMarkupPlaceholderTag: Boolean? = null, visible: Boolean? = null, enabled: Boolean? = null, popupSettings: PopupSettings? = null, behaviors: List<Behavior>? = null ) : BookmarkablePageLink<C>(id, page.java, params) { constructor( id: String, page: KClass<C>, params: PageParameters? = null, outputMarkupId: Boolean? = null, outputMarkupPlaceholderTag: Boolean? = null, visible: Boolean? = null, enabled: Boolean? = null, popupSettings: PopupSettings? = null, behavior: Behavior ) : this( id = id, page = page, params = params, outputMarkupId = outputMarkupId, outputMarkupPlaceholderTag = outputMarkupPlaceholderTag, visible = visible, enabled = enabled, popupSettings = popupSettings, behaviors = listOf(behavior) ) init { init( outputMarkupId = outputMarkupId, outputMarkupPlaceholderTag = outputMarkupPlaceholderTag, visible = visible, enabled = enabled, behaviors = behaviors ) popupSettings?.let { this.popupSettings = it } } }
apache-2.0
fb1f20d49a501566167bb0e6d18cfd1d
29.25
71
0.658953
4.571788
false
false
false
false
debop/debop4k
debop4k-examples/src/test/kotlin/debop4k/examples/delegates/CloseableDelegate.kt
1
1938
/* * 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. * */ package debop4k.examples.delegates import java.io.Closeable import kotlin.properties.ReadOnlyProperty import kotlin.reflect.KProperty fun main(args: Array<String>) { val foo = Foo() foo.access() foo.close() } class CloseableTest : Closeable { override fun close() { println("Closing $this") } } fun <T : Closeable> closeableLazy(initializer: () -> T) = CloseableLazyVal(initializer) class CloseableLazyVal<T : Closeable>(private val initializer: () -> T) : ReadOnlyProperty<CloseableDelegateHost, T> { private var mValue: T? = null override fun getValue(thisRef: CloseableDelegateHost, property: KProperty<*>): T { var value = mValue if (value == null) { value = initializer() thisRef.registerCloseable(value) } return value } } interface CloseableDelegateHost : Closeable { fun registerCloseable(prop: Closeable) } class ClosableDelegateHostImpl : CloseableDelegateHost { val closeables = arrayListOf<Closeable>() override fun registerCloseable(prop: Closeable) { closeables.add(prop) } override fun close() = closeables.forEach { it.close() } } class Foo : CloseableDelegateHost by ClosableDelegateHostImpl() { private val stream by closeableLazy { CloseableTest() } fun access() { println("Accessing ${stream}") } }
apache-2.0
4c57388f83c7bfb9c7673dfafc0992fe
24.513158
87
0.719814
4.045929
false
false
false
false
tasks/tasks
app/src/main/java/org/tasks/data/AlarmDao.kt
1
1405
package org.tasks.data import androidx.room.Dao import androidx.room.Delete import androidx.room.Insert import androidx.room.Query import com.todoroo.astrid.data.Task import org.tasks.data.Alarm.Companion.TYPE_SNOOZE @Dao interface AlarmDao { @Query(""" SELECT alarms.* FROM alarms INNER JOIN tasks ON tasks._id = alarms.task WHERE tasks.completed = 0 AND tasks.deleted = 0 """) suspend fun getActiveAlarms(): List<Alarm> @Query(""" SELECT alarms.* FROM alarms INNER JOIN tasks ON tasks._id = alarms.task WHERE tasks._id = :taskId AND tasks.completed = 0 AND tasks.deleted = 0 """) suspend fun getActiveAlarms(taskId: Long): List<Alarm> @Query("SELECT * FROM alarms WHERE type = $TYPE_SNOOZE AND task IN (:taskIds)") suspend fun getSnoozed(taskIds: List<Long>): List<Alarm> @Query("SELECT * FROM alarms WHERE task = :taskId") suspend fun getAlarms(taskId: Long): List<Alarm> @Query("DELETE FROM alarms WHERE _id IN(:alarmIds)") suspend fun deleteByIds(alarmIds: List<Long>) @Delete suspend fun delete(alarm: Alarm) @Delete suspend fun delete(alarms: List<Alarm>) @Insert suspend fun insert(alarm: Alarm): Long @Insert suspend fun insert(alarms: Iterable<Alarm>) suspend fun getAlarms(task: Task) = ArrayList(if (task.isNew) { emptyList() } else { getAlarms(task.id) }) }
gpl-3.0
cbc5ea97f6655b7b214ef78981dfc525
23.666667
83
0.682562
3.766756
false
false
false
false
cout970/Magneticraft
src/main/kotlin/com/cout970/magneticraft/features/fluid_machines/TileRenderers.kt
2
5477
package com.cout970.magneticraft.features.fluid_machines import com.cout970.magneticraft.Debug import com.cout970.magneticraft.Sprite import com.cout970.magneticraft.misc.RegisterRenderer import com.cout970.magneticraft.misc.resource import com.cout970.magneticraft.misc.vector.lowercaseName import com.cout970.magneticraft.misc.vector.vec3Of import com.cout970.magneticraft.systems.tilemodules.ModulePipe import com.cout970.magneticraft.systems.tilerenderers.* import net.minecraft.client.Minecraft import net.minecraft.client.renderer.texture.TextureMap import net.minecraft.util.EnumFacing import net.minecraftforge.client.MinecraftForgeClient import net.minecraftforge.fluids.FluidStack import org.lwjgl.opengl.GL11 /** * Created by cout970 on 2017/08/28. */ @RegisterRenderer(TileSmallTank::class) object TileRendererSmallTank : BaseTileRenderer<TileSmallTank>() { override fun init() { createModel(Blocks.smallTank, ModelSelector("shell", FilterNot(FilterString("base"))) ) createModelWithoutTexture(Blocks.smallTank, ModelSelector("base", FilterString("base")) ) } override fun render(te: TileSmallTank) { if (MinecraftForgeClient.getRenderPass() == 0) { val loc = if (te.toggleExportModule.enable) "out" else "in" bindTexture(resource("textures/blocks/fluid_machines/small_tank_$loc.png")) renderModel("base") renderModel("shell") } else { if (te.tank.isNonEmpty()) { val fluidStack = te.tank.fluid ?: return val fillPercent = fluidStack.amount / te.tank.capacity.toDouble() val color = fluidStack.fluid.getColor(fluidStack) bindTexture(TextureMap.LOCATION_BLOCKS_TEXTURE) te.fluidRenderer.sprites = listOf(getFluidSprite(fluidStack)) te.fluidRenderer.size = vec3Of(16.px - 0.002, 15.px * fillPercent - 0.002, 16.px - 0.002) te.fluidRenderer.pos = vec3Of(0.px + 0.001, 1.px + 0.001, 0.px + 0.001) Utilities.setColor(color) te.fluidRenderer.render() GL11.glColor4f(1.0f, 1.0f, 1.0f, 1.0f) } } } fun getFluidSprite(fluidStack: FluidStack): Sprite { val loc = fluidStack.fluid.getStill(fluidStack) return Minecraft.getMinecraft().textureMapBlocks.getAtlasSprite(loc.toString()) } } @RegisterRenderer(TileIronPipe::class) object TileRendererIronPipe : BaseTileRenderer<TileIronPipe>() { override fun init() { val parts = listOf( "center", "up", "down", "north", "south", "east", "west", "wt", "wb", "et", "eb", "nt", "nb", "st", "sb", "nw", "sw", "ne", "se", "cdown", "cup", "cnorth", "csouth", "cwest", "ceast" ) createModel(Blocks.ironPipe, parts.map { ModelSelector(it, FilterString(it)) }) } override fun render(te: TileIronPipe) { if (Debug.DEBUG) { Utilities.renderFloatingLabel("${te.tank.fluidAmount}", vec3Of(0, 1, 0)) Utilities.setColor((te.pipeModule.pipeNetwork?.hashCode() ?: 0) or 0xFF000000.toInt()) } val pipeMap = enumValues<EnumFacing>().map { te.pipeModule.getConnectionType(it, true) } renderModel("center") if (Debug.DEBUG) GL11.glColor4f(1f, 1f, 1f, 1f) enumValues<EnumFacing>().forEach { facing -> when (pipeMap[facing.ordinal]) { ModulePipe.ConnectionType.PIPE -> renderModel(facing.lowercaseName) ModulePipe.ConnectionType.NONE -> Unit ModulePipe.ConnectionType.TANK -> { renderModel(facing.lowercaseName) val state = te.pipeModule.connectionStates[facing.ordinal] val color = when (state) { ModulePipe.ConnectionState.DISABLE -> return@forEach ModulePipe.ConnectionState.PASSIVE -> -1 ModulePipe.ConnectionState.ACTIVE -> Utilities.colorFromRGB(1f, 0.6f, 0.0f) } Utilities.setColor(color) renderModel("c" + facing.lowercaseName) Utilities.setColor(-1) } } } val count = pipeMap.count { it != ModulePipe.ConnectionType.NONE } if (count == 2) { val none = ModulePipe.ConnectionType.NONE if (pipeMap[0] != none && pipeMap[1] != none) { renderModel("nw") renderModel("sw") renderModel("ne") renderModel("se") return } else if (pipeMap[2] != none && pipeMap[3] != none) { renderModel("wt") renderModel("wb") renderModel("et") renderModel("eb") return } else if (pipeMap[4] != none && pipeMap[5] != none) { renderModel("nt") renderModel("nb") renderModel("st") renderModel("sb") return } } renderModel("wt") renderModel("wb") renderModel("et") renderModel("eb") renderModel("nt") renderModel("nb") renderModel("st") renderModel("sb") renderModel("nw") renderModel("sw") renderModel("ne") renderModel("se") } }
gpl-2.0
6c81bdd2812a3cd5216b1f5cc45f482c
35.039474
106
0.584261
4.282252
false
false
false
false
nemerosa/ontrack
ontrack-extension-general/src/main/java/net/nemerosa/ontrack/extension/general/ReleasePropertyMutationProvider.kt
1
1048
package net.nemerosa.ontrack.extension.general import graphql.schema.GraphQLInputObjectField import net.nemerosa.ontrack.graphql.schema.MutationInput import net.nemerosa.ontrack.graphql.schema.PropertyMutationProvider import net.nemerosa.ontrack.graphql.schema.requiredStringInputField import net.nemerosa.ontrack.model.structure.ProjectEntity import net.nemerosa.ontrack.model.structure.PropertyType import org.springframework.stereotype.Component import kotlin.reflect.KClass @Component class ReleasePropertyMutationProvider : PropertyMutationProvider<ReleaseProperty> { override val propertyType: KClass<out PropertyType<ReleaseProperty>> = ReleasePropertyType::class override val mutationNameFragment: String = "Release" override val inputFields: List<GraphQLInputObjectField> = listOf( requiredStringInputField("release", "Name of the release/version tag to set") ) override fun readInput(entity: ProjectEntity, input: MutationInput) = ReleaseProperty( name = input.getRequiredInput("release") ) }
mit
fead9f5e08030f694dcf04a71c07d824
39.346154
101
0.816794
4.763636
false
false
false
false
nemerosa/ontrack
ontrack-ui-graphql/src/main/java/net/nemerosa/ontrack/graphql/schema/links/GQLBuildGraphFieldContributor.kt
1
880
package net.nemerosa.ontrack.graphql.schema.links import net.nemerosa.ontrack.model.links.BranchLinksService import net.nemerosa.ontrack.model.structure.Build import net.nemerosa.ontrack.model.structure.ProjectEntityType import org.springframework.stereotype.Component @Component class GQLBuildGraphFieldContributor( gqlEnumBranchLinksDirection: GQLEnumBranchLinksDirection, gqlTypeBranchLinksNode: GQLTypeBranchLinksNode, branchLinksService: BranchLinksService ) : AbstractGQLGraphFieldContributor<Build>( projectEntityType = ProjectEntityType.BUILD, description = "Graph of dependencies for this build", fetcher = { build, direction -> branchLinksService.getBuildLinks(build, direction) }, gqlEnumBranchLinksDirection = gqlEnumBranchLinksDirection, gqlTypeBranchLinksNode = gqlTypeBranchLinksNode, branchLinksService = branchLinksService )
mit
b7b29a0f09fc8cfd002808a5ecfa07f4
43
89
0.830682
4.559585
false
false
false
false
d9n/intellij-rust
src/main/kotlin/org/rust/ide/formatter/blocks/RsMultilineStringLiteralBlock.kt
1
2601
package org.rust.ide.formatter.blocks import com.intellij.formatting.* import com.intellij.lang.ASTNode import com.intellij.openapi.util.TextRange import com.intellij.psi.formatter.common.AbstractBlock import java.util.* /** * Rust has multiline string literals, and whitespace inside them is actually significant. * * By default, the formatter will add and remove indentation **inside** string literals * without a moment of hesitation. To handle this situation, we create a separate FmtBlock * for each line of the string literal, and forbid messing with whitespace between them. */ class RsMultilineStringLiteralBlock( private val node: ASTNode, private val alignment: Alignment?, private val indent: Indent?, private val wrap: Wrap? ) : ASTBlock { override fun getNode(): ASTNode = node override fun getAlignment(): Alignment? = alignment override fun getIndent(): Indent? = indent override fun getWrap(): Wrap? = wrap override fun getTextRange(): TextRange = node.textRange override fun isIncomplete(): Boolean = false override fun isLeaf(): Boolean = false override fun getChildAttributes(newChildIndex: Int): ChildAttributes = ChildAttributes(null, null) override fun getSubBlocks(): List<Block> { val result = ArrayList<Block>() var startOffset = 0 val chars = node.chars for ((idx, c) in chars.withIndex()) { if (c == '\n') { result += RsLineBlock(node, TextRange(startOffset, idx)) startOffset = idx } } if (startOffset < chars.length) { result += RsLineBlock(node, TextRange(startOffset, chars.length)) } return result } override fun getSpacing(child1: Block?, child2: Block): Spacing = Spacing.getReadOnlySpacing() } private class RsLineBlock( node: ASTNode, rangeInParent: TextRange ) : AbstractBlock(node, null, null) { private val textRange = rangeInParent.shiftRight(node.startOffset) override fun getTextRange(): TextRange = textRange override fun isLeaf(): Boolean = true override fun buildChildren(): List<Block> = emptyList() override fun getSpacing(child1: Block?, child2: Block): Spacing? = null override fun toString(): String { val text = node.chars[textRange.shiftRight(-node.startOffset)].toString() return '"' + text.replace("\n", "\\n").replace("\"", "\\\"") + '"' } } private operator fun CharSequence.get(range: TextRange): CharSequence = subSequence(range.startOffset until range.endOffset)
mit
c90c14b236a05449cbd537ee69dcfa96
32.346154
98
0.681661
4.579225
false
false
false
false
LarsKrogJensen/graphql-kotlin
src/test/groovy/graphql/RelaySchema.kt
1
1395
package graphql import graphql.relay.connectionType import graphql.relay.edgeType import graphql.relay.nodeField import graphql.relay.nodeInterface import graphql.schema.GraphQLNonNull import graphql.schema.newObject import graphql.schema.newSchema import java.util.concurrent.CompletableFuture val NodeInterface = nodeInterface { null } val STUFF = "Stuff" val StuffConnectionType = connectionType<Any> { baseName = STUFF edgeType = edgeType<Any> { baseName = STUFF nodeType = newObject { name = STUFF field<String> { name = "id" isField = true } } } } val ThingType = newObject { name = "Thing" field<String> { name = "id" isField = true } field<String> { name = "stuffs" type = StuffConnectionType } } val RelayQueryType = newObject { name = "RelayQuery" field(nodeField(NodeInterface) { CompletableFuture.completedFuture<String>(null as String?) }) field<String> { name = "thing" type = ThingType argument { name = "id" description = "id of the thing" type = GraphQLNonNull(GraphQLString) } fetcher = { CompletableFuture.completedFuture(null) } } } val Schema = newSchema { query = RelayQueryType }
mit
dc782691936a148b3767698adb948000
20.796875
66
0.605018
4.292308
false
false
false
false
openHPI/android-app
app/src/main/java/de/xikolo/network/jobs/ListCoursesJob.kt
1
1602
package de.xikolo.network.jobs import android.util.Log import de.xikolo.config.Config import de.xikolo.managers.UserManager import de.xikolo.models.Course import de.xikolo.models.Enrollment import de.xikolo.network.ApiService import de.xikolo.network.jobs.base.NetworkJob import de.xikolo.network.jobs.base.NetworkStateLiveData import de.xikolo.network.sync.Sync import io.realm.kotlin.where import ru.gildor.coroutines.retrofit.awaitResponse class ListCoursesJob(networkState: NetworkStateLiveData, userRequest: Boolean) : NetworkJob(networkState, userRequest) { companion object { val TAG: String = ListCoursesJob::class.java.simpleName } override suspend fun onRun() { val response = if (UserManager.isAuthorized) { ApiService.instance.listCoursesWithEnrollments().awaitResponse() } else { ApiService.instance.listCourses().awaitResponse() } if (response.isSuccessful && response.body() != null) { if (Config.DEBUG) Log.i(TAG, "Courses received") Sync.Included.with<Enrollment>(response.body()!!) .run() Sync.Data.with(response.body()!!) .setBeforeCommitCallback { realm, model -> val course = realm.where<Course>().equalTo("id", model.id).findFirst() if (course != null) model.description = course.description } .run() success() } else { if (Config.DEBUG) Log.e(TAG, "Error while fetching courses list") error() } } }
bsd-3-clause
0124f939bfc1ff99f8f3666a166aa683
33.085106
120
0.646692
4.401099
false
true
false
false
vanita5/twittnuker
twittnuker/src/main/kotlin/de/vanita5/twittnuker/util/api/TwitterMacExtraHeaders.kt
1
2125
/* * Twittnuker - Twitter client for Android * * Copyright (C) 2013-2017 vanita5 <[email protected]> * * This program incorporates a modified version of Twidere. * Copyright (C) 2012-2017 Mariotaku Lee <[email protected]> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package de.vanita5.twittnuker.util.api import android.os.Build import org.mariotaku.ktextension.bcp47Tag import org.mariotaku.restfu.http.MultiValueMap import de.vanita5.twittnuker.extension.restfu.contains import de.vanita5.twittnuker.util.MicroBlogAPIFactory.ExtraHeaders import java.util.* object TwitterMacExtraHeaders : ExtraHeaders { const val clientName = "Twitter-Mac" const val versionName = "6.41.0" const val platformName = "Mac" const val platformVersion = "10.12.3" const val platformArchitecture = "x86_64" const val internalVersionName = "5002734" override fun get(headers: MultiValueMap<String>): List<Pair<String, String>> { val result = ArrayList<Pair<String, String>>() val language = Locale.getDefault().bcp47Tag if ("User-Agent" !in headers) { result.add(Pair("User-Agent", userAgent)) } result.add(Pair("Accept-Language", language)) result.add(Pair("X-Twitter-Client", clientName)) result.add(Pair("X-Twitter-Client-Version", versionName)) return result } val userAgent: String get() { return "$clientName/($internalVersionName) $platformName/$platformVersion (;$platformArchitecture)" } }
gpl-3.0
c9a39cf47a0ea0f17478d25d11e7f6ea
36.298246
107
0.718588
4.024621
false
false
false
false
Devifish/ReadMe
app/src/main/java/cn/devifish/readme/view/module/stack/StackFragment.kt
1
1689
package cn.devifish.readme.view.module.stack import android.support.v7.widget.LinearLayoutManager import android.view.View import cn.devifish.readme.R import cn.devifish.readme.entity.Stack import cn.devifish.readme.entity.bean.Gender import cn.devifish.readme.entity.bean.Major import cn.devifish.readme.provider.BookProvider import cn.devifish.readme.service.RankService import cn.devifish.readme.view.adapter.StackRecyclerAdapter import cn.devifish.readme.view.base.MainPageFragment import kotlinx.android.synthetic.main.page_stack_main.view.* /** * Created by zhang on 2017/6/3. * 书库Fragment */ class StackFragment : MainPageFragment() { private val title = "书库" private val rankService = BookProvider.getInstance().create(RankService::class.java) private val stackList = ArrayList<Stack>(); private val adapter = StackRecyclerAdapter(); override fun bindLayout(): Int = R.layout.page_stack_main override fun getTitle(): String = this.title override fun initVar() {} override fun initView(view: View) { view.rv_stack.layoutManager = LinearLayoutManager(context, LinearLayoutManager.VERTICAL, false) view.rv_stack.adapter = adapter Major.values().forEach { item -> stackList.add( Stack(item.value, rankService.getBooksByCats(Gender.MALE, "hot", item.value, "", 0, 50))) } adapter.data = stackList adapter.setOnItemClickListener(this) adapter.activity = activity } override fun onRefresh() { stackList.clear() } override fun onItemClick(view: View, position: Int) { } override fun onItemLongClick(view: View, position: Int) { } }
apache-2.0
9e48481be473538c5c138d7705fd29fa
30.735849
116
0.722784
4.021531
false
false
false
false
stripe/stripe-android
financial-connections-example/src/main/java/com/stripe/android/financialconnections/example/FinancialConnectionsExampleViewModel.kt
1
5205
package com.stripe.android.financialconnections.example import android.app.Application import androidx.lifecycle.AndroidViewModel import androidx.lifecycle.viewModelScope import com.stripe.android.financialconnections.FinancialConnectionsSheetForTokenResult import com.stripe.android.financialconnections.FinancialConnectionsSheet import com.stripe.android.financialconnections.FinancialConnectionsSheetResult import com.stripe.android.financialconnections.example.FinancialConnectionsExampleViewEffect.OpenFinancialConnectionsSheetExample import com.stripe.android.financialconnections.example.data.BackendRepository import com.stripe.android.financialconnections.example.data.Settings import kotlinx.coroutines.flow.MutableSharedFlow import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.SharedFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.update import kotlinx.coroutines.launch class FinancialConnectionsExampleViewModel(application: Application) : AndroidViewModel(application) { private val repository = BackendRepository(Settings(application)) private val _state = MutableStateFlow(FinancialConnectionsExampleState()) val state: StateFlow<FinancialConnectionsExampleState> = _state private val _viewEffect = MutableSharedFlow<FinancialConnectionsExampleViewEffect>() val viewEffect: SharedFlow<FinancialConnectionsExampleViewEffect> = _viewEffect fun startFinancialConnectionsSessionForData() { viewModelScope.launch { showLoadingWithMessage("Fetching link account session from example backend!") kotlin.runCatching { repository.createLinkAccountSession() } // Success creating session: open the financial connections sheet with received secret .onSuccess { showLoadingWithMessage("Session created, opening FinancialConnectionsSheet.") _viewEffect.emit( OpenFinancialConnectionsSheetExample( configuration = FinancialConnectionsSheet.Configuration( it.clientSecret, it.publishableKey ) ) ) } // Error retrieving session: display error. .onFailure(::showError) } } fun startFinancialConnectionsSessionForToken() { viewModelScope.launch { showLoadingWithMessage("Fetching link account session from example backend!") kotlin.runCatching { repository.createLinkAccountSessionForToken() } // Success creating session: open the financial connections sheet with received secret .onSuccess { showLoadingWithMessage("Session created, opening FinancialConnectionsSheet.") _viewEffect.emit( OpenFinancialConnectionsSheetExample( configuration = FinancialConnectionsSheet.Configuration( financialConnectionsSessionClientSecret = it.clientSecret, publishableKey = it.publishableKey ) ) ) } // Error retrieving session: display error. .onFailure(::showError) } } private fun showError(error: Throwable) { _state.update { it.copy( loading = false, status = "Error starting linked account session: $error" ) } } private fun showLoadingWithMessage(message: String) { _state.update { it.copy( loading = true, status = message ) } } fun onFinancialConnectionsSheetResult(result: FinancialConnectionsSheetResult) { val statusText = when (result) { is FinancialConnectionsSheetResult.Completed -> { val accountList = result.financialConnectionsSession.accounts accountList.data.joinToString("\n") { "${it.institutionName} - ${it.displayName} - ${it.last4} - ${it.category}/${it.subcategory}" } } is FinancialConnectionsSheetResult.Failed -> "Failed! ${result.error}" is FinancialConnectionsSheetResult.Canceled -> "Cancelled!" } _state.update { it.copy(loading = false, status = statusText) } } fun onFinancialConnectionsSheetForBankAccountTokenResult( result: FinancialConnectionsSheetForTokenResult ) { val statusText = when (result) { is FinancialConnectionsSheetForTokenResult.Completed -> { "Token ${result.token.id} generated for bank account ${result.token.bankAccount?.last4}" } is FinancialConnectionsSheetForTokenResult.Failed -> "Failed! ${result.error}" is FinancialConnectionsSheetForTokenResult.Canceled -> "Cancelled!" } _state.update { it.copy(loading = false, status = statusText) } } }
mit
0ef083a81057ee1173b66ef50cc38cd2
44.26087
129
0.647839
6.152482
false
false
false
false
exponent/exponent
packages/expo-camera/android/src/main/java/expo/modules/camera/CameraModule.kt
2
7170
package expo.modules.camera import android.Manifest import android.content.Context import android.os.Build import com.google.android.cameraview.AspectRatio import expo.modules.camera.tasks.ResolveTakenPictureAsyncTask import expo.modules.core.ExportedModule import expo.modules.core.ModuleRegistry import expo.modules.core.interfaces.ExpoMethod import expo.modules.core.ModuleRegistryDelegate import expo.modules.core.Promise import expo.modules.core.interfaces.services.UIManager import expo.modules.interfaces.permissions.Permissions import java.lang.Exception class CameraModule( context: Context, private val moduleRegistryDelegate: ModuleRegistryDelegate = ModuleRegistryDelegate() ) : ExportedModule(context) { private inline fun <reified T> moduleRegistry() = moduleRegistryDelegate.getFromModuleRegistry<T>() private val permissionsManager: Permissions by moduleRegistry() private val uIManager: UIManager by moduleRegistry() override fun onCreate(moduleRegistry: ModuleRegistry) { moduleRegistryDelegate.onCreate(moduleRegistry) } override fun getName() = TAG override fun getConstants() = mapOf( "Type" to typeConstants, "FlashMode" to flashModeConstants, "AutoFocus" to autoFocusConstants, "WhiteBalance" to whiteBalanceConstants, "VideoQuality" to videoQualityConstants, "FaceDetection" to emptyMap<String, Any>(), ) @ExpoMethod fun pausePreview(viewTag: Int, promise: Promise) { addUIBlock( viewTag, object : UIManager.UIBlock<ExpoCameraView> { override fun resolve(view: ExpoCameraView) { try { if (view.isCameraOpened) { view.pausePreview() } } catch (e: Exception) { promise.reject(ERROR_TAG, "pausePreview -- exception occurred -- " + e.message, e) } } override fun reject(throwable: Throwable) = promise.reject(ERROR_TAG, throwable) } ) } @ExpoMethod fun resumePreview(viewTag: Int, promise: Promise) { addUIBlock( viewTag, object : UIManager.UIBlock<ExpoCameraView> { override fun resolve(view: ExpoCameraView) { try { if (view.isCameraOpened) { view.resumePreview() } } catch (e: Exception) { promise.reject(ERROR_TAG, "resumePreview -- exception occurred -- " + e.message, e) } } override fun reject(throwable: Throwable) = promise.reject(ERROR_TAG, throwable) } ) } @ExpoMethod fun takePicture(options: Map<String, Any>, viewTag: Int, promise: Promise) { val cacheDirectory = context.cacheDir addUIBlock( viewTag, object : UIManager.UIBlock<ExpoCameraView> { override fun resolve(view: ExpoCameraView) { if (!Build.FINGERPRINT.contains("generic")) { if (view.isCameraOpened) { view.takePicture(options, promise, cacheDirectory) } else { promise.reject("E_CAMERA_UNAVAILABLE", "Camera is not running") } } else { val image = CameraViewHelper.generateSimulatorPhoto(view.width, view.height) ResolveTakenPictureAsyncTask(image, promise, options, cacheDirectory, view).execute() } } override fun reject(throwable: Throwable) = promise.reject(ERROR_TAG, throwable) } ) } @ExpoMethod fun record(options: Map<String?, Any?>, viewTag: Int, promise: Promise) { if (permissionsManager.hasGrantedPermissions(Manifest.permission.RECORD_AUDIO)) { val cacheDirectory = context.cacheDir addUIBlock( viewTag, object : UIManager.UIBlock<ExpoCameraView> { override fun resolve(view: ExpoCameraView) { if (view.isCameraOpened) { view.record(options, promise, cacheDirectory) } else { promise.reject("E_CAMERA_UNAVAILABLE", "Camera is not running") } } override fun reject(throwable: Throwable) = promise.reject(ERROR_TAG, throwable) } ) } else { promise.reject(SecurityException("User rejected audio permissions")) } } @ExpoMethod fun stopRecording(viewTag: Int, promise: Promise) { addUIBlock( viewTag, object : UIManager.UIBlock<ExpoCameraView> { override fun resolve(view: ExpoCameraView) { if (view.isCameraOpened) { view.stopRecording() promise.resolve(true) } else { promise.reject(ERROR_TAG, "Camera is not open") } } override fun reject(throwable: Throwable) = promise.reject(ERROR_TAG, throwable) } ) } @ExpoMethod fun getSupportedRatios(viewTag: Int, promise: Promise) { addUIBlock( viewTag, object : UIManager.UIBlock<ExpoCameraView> { override fun resolve(view: ExpoCameraView) { if (view.isCameraOpened) { promise.resolve(view.supportedAspectRatios.map { it.toString() }) } else { promise.reject(ERROR_TAG, "Camera is not running") } } override fun reject(throwable: Throwable) = promise.reject(ERROR_TAG, throwable) } ) } @ExpoMethod fun getAvailablePictureSizes(ratio: String?, viewTag: Int, promise: Promise) { addUIBlock( viewTag, object : UIManager.UIBlock<ExpoCameraView> { override fun resolve(view: ExpoCameraView) { if (view.isCameraOpened) { try { val sizes = view.getAvailablePictureSizes(AspectRatio.parse(ratio)) promise.resolve(sizes.map { it.toString() }) } catch (e: Exception) { promise.reject(ERROR_TAG, "getAvailablePictureSizes -- unexpected error -- " + e.message, e) } } else { promise.reject(ERROR_TAG, "Camera is not running") } } override fun reject(throwable: Throwable) = promise.reject(ERROR_TAG, throwable) } ) } private fun addUIBlock(viewTag: Int, block: UIManager.UIBlock<ExpoCameraView>) { uIManager.addUIBlock(viewTag, block, ExpoCameraView::class.java) } @ExpoMethod fun requestPermissionsAsync(promise: Promise) { permissionsManager.askForPermissionsWithPromise(promise, Manifest.permission.CAMERA) } @ExpoMethod fun requestCameraPermissionsAsync(promise: Promise) { permissionsManager.askForPermissionsWithPromise(promise, Manifest.permission.CAMERA) } @ExpoMethod fun requestMicrophonePermissionsAsync(promise: Promise) { permissionsManager.askForPermissionsWithPromise(promise, Manifest.permission.RECORD_AUDIO) } @ExpoMethod fun getPermissionsAsync(promise: Promise) { permissionsManager.getPermissionsWithPromise(promise, Manifest.permission.CAMERA) } @ExpoMethod fun getCameraPermissionsAsync(promise: Promise) { permissionsManager.getPermissionsWithPromise(promise, Manifest.permission.CAMERA) } @ExpoMethod fun getMicrophonePermissionsAsync(promise: Promise) { permissionsManager.getPermissionsWithPromise(promise, Manifest.permission.RECORD_AUDIO) } }
bsd-3-clause
0ef94e9c8d51a7691d6a4988bc993c94
32.041475
106
0.666667
4.492481
false
false
false
false
exponent/exponent
packages/expo-screen-capture/android/src/main/java/expo/modules/screencapture/ScreenCaptureModule.kt
2
2006
package expo.modules.screencapture import android.app.Activity import android.content.Context import android.view.WindowManager import expo.modules.core.ExportedModule import expo.modules.core.ModuleRegistry import expo.modules.core.Promise import expo.modules.core.errors.CurrentActivityNotFoundException import expo.modules.core.interfaces.ActivityProvider import expo.modules.core.interfaces.ExpoMethod class ScreenCaptureModule(context: Context) : ExportedModule(context) { private lateinit var mActivityProvider: ActivityProvider override fun getName(): String { return NAME } override fun onCreate(moduleRegistry: ModuleRegistry) { mActivityProvider = moduleRegistry.getModule(ActivityProvider::class.java) ScreenshotEventEmitter(context, moduleRegistry) } @ExpoMethod fun preventScreenCapture(promise: Promise) { val activity = getCurrentActivity() activity.runOnUiThread { try { activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_SECURE) } catch (exception: Exception) { promise.reject(ERROR_CODE_PREVENTION, "Failed to prevent screen capture: " + exception) } } promise.resolve(null) } @ExpoMethod fun allowScreenCapture(promise: Promise) { val activity = getCurrentActivity() activity.runOnUiThread { try { activity.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_SECURE) } catch (exception: Exception) { promise.reject(ERROR_CODE_PREVENTION, "Failed to reallow screen capture: " + exception) } } promise.resolve(null) } @Throws(CurrentActivityNotFoundException::class) fun getCurrentActivity(): Activity { val activity = mActivityProvider.currentActivity if (activity != null) { return activity } else { throw CurrentActivityNotFoundException() } } companion object { private val NAME = "ExpoScreenCapture" private const val ERROR_CODE_PREVENTION = "ERR_SCREEN_CAPTURE_PREVENTION" } }
bsd-3-clause
f31ab24de5a249d9d8954f00162623b2
28.072464
95
0.740778
4.697892
false
false
false
false
Undin/intellij-rust
debugger/src/main/kotlin/org/rust/debugger/lang/RsDebuggerTypesHelper.kt
3
1619
/* * Use of this source code is governed by the MIT license that can be * found in the LICENSE file. */ package org.rust.debugger.lang import com.intellij.psi.PsiElement import com.intellij.psi.PsiReference import com.intellij.xdebugger.XSourcePosition import com.jetbrains.cidr.execution.debugger.CidrDebugProcess import com.jetbrains.cidr.execution.debugger.backend.LLValue import com.jetbrains.cidr.execution.debugger.evaluation.CidrDebuggerTypesHelper import com.jetbrains.cidr.execution.debugger.evaluation.CidrMemberValue import org.rust.lang.core.psi.ext.RsElement import org.rust.lang.core.psi.ext.ancestorOrSelf import org.rust.lang.core.psi.ext.findInScope import org.rust.lang.core.resolve.VALUES class RsDebuggerTypesHelper(process: CidrDebugProcess) : CidrDebuggerTypesHelper(process) { override fun createReferenceFromText(`var`: LLValue, context: PsiElement): PsiReference? = null override fun computeSourcePosition(value: CidrMemberValue): XSourcePosition? = null override fun isImplicitContextVariable(position: XSourcePosition, `var`: LLValue): Boolean = false override fun resolveProperty(value: CidrMemberValue, dynamicTypeName: String?): XSourcePosition? = null override fun resolveToDeclaration(position: XSourcePosition?, `var`: LLValue): PsiElement? { val context = getContextElement(position) return resolveToDeclaration(context, `var`.name) } } private fun resolveToDeclaration(ctx: PsiElement?, name: String): PsiElement? { val composite = ctx?.ancestorOrSelf<RsElement>() ?: return null return composite.findInScope(name, VALUES) }
mit
64d83931cc6a69495d5d57fb120e1bff
41.605263
107
0.794317
4.305851
false
false
false
false
RSDT/Japp16
app/src/main/java/nl/rsdt/japp/jotial/maps/MapManager.kt
2
12992
package nl.rsdt.japp.jotial.maps import android.content.Intent import android.content.SharedPreferences import android.os.Bundle import com.google.android.gms.maps.GoogleMap import com.google.android.gms.maps.model.LatLng import com.google.android.gms.maps.model.MapStyleOptions import nl.rsdt.japp.application.Japp import nl.rsdt.japp.application.JappPreferences import nl.rsdt.japp.application.activities.SplashActivity import nl.rsdt.japp.jotial.maps.clustering.ScoutingGroepClusterManager import nl.rsdt.japp.jotial.maps.clustering.ScoutingGroepController import nl.rsdt.japp.jotial.maps.management.MapItemController import nl.rsdt.japp.jotial.maps.management.MapItemUpdatable import nl.rsdt.japp.jotial.maps.management.controllers.* import nl.rsdt.japp.jotial.maps.searching.Searchable import nl.rsdt.japp.jotial.maps.wrapper.IJotiMap import nl.rsdt.japp.jotial.maps.wrapper.IMarker import nl.rsdt.japp.service.cloud.data.NoticeInfo import nl.rsdt.japp.service.cloud.data.UpdateInfo import nl.rsdt.japp.service.cloud.messaging.MessageManager import java.io.Serializable import java.util.* /** * @author Dingenis Sieger Sinke * @version 1.0 * @since 24-7-2016 * Manages the map */ class MapManager : Searchable, MessageManager.UpdateMessageListener, SharedPreferences.OnSharedPreferenceChangeListener { private constructor(){ } /** * The value that determines if the MapManager is already recreated once. */ private var isRecreated = false /** * The GoogleMap */ var jotiMap: IJotiMap? = null private set /** * The HashMap with the MapItemControllers. */ var controllers: HashMap<String, MapItemController<*, *>> = HashMap() /** * The Controller for the ScoutingGroep map items. */ private var sgController: ScoutingGroepController = ScoutingGroepController() /** * Gets all the controllers. */ val all: Collection<MapItemController<*, *>> get() = controllers.values /** * Initializes a new instance of MapManager. */ init { JappPreferences.visiblePreferences.registerOnSharedPreferenceChangeListener(this) } /** * */ fun onIntentCreate(intent: Intent?) { // NOTE: no longer used if (intent != null && intent.hasExtra(SplashActivity.LOAD_ID)) { val bundle = intent.getBundleExtra(SplashActivity.LOAD_ID) if (bundle != null) { for ((_, controller) in controllers) { controller.onIntentCreate(bundle) } sgController.onIntentCreate(bundle) bundle.clear() intent.removeExtra(SplashActivity.LOAD_ID) } } } /** * Gets invoked when the Activity is created. * * @param savedInstanceState The Bundle where we have potential put things. */ fun onCreate(savedInstanceState: Bundle?) { if (savedInstanceState != null) { for ((_, controller) in controllers) { controller.onCreate(savedInstanceState) } sgController.onCreate(savedInstanceState) isRecreated = savedInstanceState.getBoolean(RECREATED_KEY) } else { val storage = MapStorage.instance val data = storage.data if (data != null) { for ((_, controller) in controllers) { controller.onIntentCreate(data) } sgController.onIntentCreate(data) storage.clear() } } } /** * Gets invoked when the Activity is being saved. * * @param saveInstanceState The Bundle where we can save things in. */ fun onSaveInstanceState(saveInstanceState: Bundle?) { if (saveInstanceState != null) { for ((_, controller) in controllers) { controller.onSaveInstanceState(saveInstanceState) } sgController.onSaveInstanceState(saveInstanceState) /** * Indicate the MapManager has already been created once. */ saveInstanceState.putBoolean(RECREATED_KEY, true) } } /** * Gets the MapItemController associated with the given id. * * @param id The id of the MapItemController, for example VosAlphaController.CONTROLLER_ID . * @return The MapItemController associated with the id, returns null if none. */ operator fun <T : MapItemController<*, *>> get(id: String): T? { return controllers[id] as T? } private /** * Gets the MapItemController associated with the given id. * * @param id The id of the MapItemController, for example VosAlphaController.CONTROLLER_ID . * @return The MapItemController associated with the id, returns null if none. */ fun <T : VosController> getVosControllerByDeelgebied(deelgebied: String): T? { when (deelgebied) { "alpha" -> return get(AlphaVosController.CONTROLLER_ID) "bravo" -> return get(BravoVosController.CONTROLLER_ID) "charlie" -> return get(CharlieVosController.CONTROLLER_ID) "delta" -> return get(DeltaVosController.CONTROLLER_ID) "echo" -> return get(EchoVosController.CONTROLLER_ID) "foxtrot" -> return get(FoxtrotVosController.CONTROLLER_ID) "xray" -> return get(XrayVosController.CONTROLLER_ID) } return null } /** * Gets invoked when a UpdateMessage is received. */ override fun onUpdateMessageReceived(info: UpdateInfo?) { if (info?.type == null || info.action == null) return var updatable: MapItemUpdatable<*>? = null when (info.type) { "hunter" -> updatable = get(HunterController.CONTROLLER_ID) "foto" -> updatable = get(FotoOpdrachtController.CONTROLLER_ID) "vos_a" -> updatable = get(AlphaVosController.CONTROLLER_ID) "vos_b" -> updatable = get(BravoVosController.CONTROLLER_ID) "vos_c" -> updatable = get(CharlieVosController.CONTROLLER_ID) "vos_d" -> updatable = get(DeltaVosController.CONTROLLER_ID) "vos_e" -> updatable = get(EchoVosController.CONTROLLER_ID) "vos_f" -> updatable = get(FoxtrotVosController.CONTROLLER_ID) "vos_x" -> updatable = get(XrayVosController.CONTROLLER_ID) "sc" -> updatable = sgController } updatable?.onUpdateMessage(info) } override fun onNoticeMessageReceived(info: NoticeInfo?) { } override fun onSharedPreferenceChanged(sharedPreferences: SharedPreferences, key: String) { when (key) { JappPreferences.AREAS -> { for (controller in controllers.values) { if (controller is VosController) { controller.visiblity = false } } val enabled = JappPreferences.areasEnabled for (area in enabled) { val controller = getVosControllerByDeelgebied<VosController>(area) controller?.visiblity = true } //TODO: make this nicer and less hacky if (sgController.clusterManager is ScoutingGroepClusterManager) { val clusterManager = sgController.clusterManager as ScoutingGroepClusterManager? clusterManager?.run { reRender() } } } JappPreferences.MAP_TYPE -> if (jotiMap != null) { val value = sharedPreferences.getString(key, GoogleMap.MAP_TYPE_NORMAL.toString())?:GoogleMap.MAP_TYPE_NORMAL.toString() jotiMap?.setGMapType(Integer.valueOf(value)) } JappPreferences.MAP_STYLE -> if (jotiMap != null) { val style = Integer.valueOf(sharedPreferences.getString(key, MapStyle.DAY.toString())?:MapStyle.DAY.toString()) if (style == MapStyle.AUTO) { } else { jotiMap?.setMapStyle(MapStyleOptions.loadRawResourceStyle(Japp.instance!!, MapStyle.getAssociatedRaw(style))) } } JappPreferences.MAP_CONTROLS -> { val set = sharedPreferences.getStringSet(key, null) if (set != null) { if (jotiMap != null) { jotiMap?.uiSettings?.setZoomControlsEnabled(set.contains(MapControls.ZOOM.toString())) jotiMap?.uiSettings?.setCompassEnabled(set.contains(MapControls.COMPASS.toString())) jotiMap?.uiSettings?.setIndoorLevelPickerEnabled(set.contains(MapControls.LEVEL.toString())) jotiMap?.uiSettings?.setMapToolbarEnabled(set.contains(MapControls.TOOLBAR.toString())) } } } } } /** * Updates all the controllers, without any smart fetching logic. */ fun update() { for ((_, controller) in controllers) { controller.onUpdateInvoked() } sgController.onUpdateInvoked() } /** * Gets invoked when the GoogleMap is ready for use. * * @param jotiMap */ fun onMapReady(jotiMap: IJotiMap) { this.jotiMap = jotiMap controllers[AlphaVosController.CONTROLLER_ID] = AlphaVosController(jotiMap) controllers[BravoVosController.CONTROLLER_ID] = BravoVosController(jotiMap) controllers[CharlieVosController.CONTROLLER_ID] = CharlieVosController(jotiMap) controllers[DeltaVosController.CONTROLLER_ID] = DeltaVosController(jotiMap) controllers[EchoVosController.CONTROLLER_ID] = EchoVosController(jotiMap) controllers[FoxtrotVosController.CONTROLLER_ID] = FoxtrotVosController(jotiMap) controllers[XrayVosController.CONTROLLER_ID] = XrayVosController(jotiMap) controllers[HunterController.CONTROLLER_ID] = HunterController(jotiMap) controllers[FotoOpdrachtController.CONTROLLER_ID] = FotoOpdrachtController(jotiMap) /** * Set the type and the style of the map. */ jotiMap.setGMapType(JappPreferences.mapType) jotiMap.setMapStyle(MapStyleOptions.loadRawResourceStyle(Japp.instance!!, MapStyle.getAssociatedRaw(JappPreferences.mapStyle))) val controls = JappPreferences.mapControls jotiMap.uiSettings.setZoomControlsEnabled(controls.contains(MapControls.ZOOM.toString())) jotiMap.uiSettings.setCompassEnabled(controls.contains(MapControls.COMPASS.toString())) jotiMap.uiSettings.setIndoorLevelPickerEnabled(controls.contains(MapControls.LEVEL.toString())) jotiMap.uiSettings.setMapToolbarEnabled(controls.contains(MapControls.TOOLBAR.toString())) /** * Checks if this is the first instance of MapManager. */ if (!isRecreated) { /** * Move the camera to the default position(Netherlands). */ jotiMap.animateCamera(LatLng(52.015379, 6.025979), 10) /** * Update the controllers. */ update() } sgController.onMapReady(jotiMap) for (controller in controllers.values) { if (controller is VosController) { controller.visiblity = false } } val enabled = JappPreferences.areasEnabled for (area in enabled) { val controller = getVosControllerByDeelgebied<VosController>(area) controller?.visiblity = true } } /** * Gets invoked when the Activity is beaning destroyed. */ fun onDestroy() { /** * Unregister this as listener to prevent memory leaks. */ JappPreferences.visiblePreferences.unregisterOnSharedPreferenceChangeListener(this) /** * Remove this as a listener for UpdateMessages. */ Japp.updateManager?.remove(this) jotiMap = null for (entry in controllers) { val controller = entry.value controller.onDestroy() } } override fun searchFor(query: String): IMarker? { return null } override fun provide(): MutableList<String> { val entries = ArrayList<String>() for ((_, controller) in controllers) { entries.addAll(controller.provide()) } return entries } companion object { /** * Defines the tag of this class. */ val TAG = "MapManager" /** * Defines a key for storing the isRecreated value. */ private val RECREATED_KEY = "RECREATED" public val instance = MapManager() } }
apache-2.0
bbb41ac59bd74b403dfe53afd8ad19a6
34.400545
136
0.616687
4.715789
false
false
false
false
foreverigor/TumCampusApp
app/src/main/java/de/tum/in/tumcampusapp/component/ui/cafeteria/details/CafeteriaViewModel.kt
1
3752
package de.tum.`in`.tumcampusapp.component.ui.cafeteria.details import android.arch.lifecycle.ViewModel import android.location.Location import de.tum.`in`.tumcampusapp.component.ui.cafeteria.model.Cafeteria import de.tum.`in`.tumcampusapp.component.ui.cafeteria.model.CafeteriaMenu import de.tum.`in`.tumcampusapp.component.ui.cafeteria.model.CafeteriaWithMenus import de.tum.`in`.tumcampusapp.component.ui.cafeteria.repository.CafeteriaLocalRepository import de.tum.`in`.tumcampusapp.component.ui.cafeteria.repository.CafeteriaRemoteRepository import de.tum.`in`.tumcampusapp.utils.Utils import io.reactivex.Flowable import io.reactivex.Observable import io.reactivex.android.schedulers.AndroidSchedulers import io.reactivex.disposables.CompositeDisposable import io.reactivex.schedulers.Schedulers import org.joda.time.DateTime /** * ViewModel for cafeterias. */ class CafeteriaViewModel(private val localRepository: CafeteriaLocalRepository, private val remoteRepository: CafeteriaRemoteRepository, private val compositeDisposable: CompositeDisposable) : ViewModel() { /** * Returns a flowable that emits a list of cafeterias from the local repository. */ fun getAllCafeterias(location: Location): Flowable<List<Cafeteria>> = localRepository.getAllCafeterias() .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .map { transformCafeteria(it, location) } .defaultIfEmpty(emptyList()) fun getCafeteriaWithMenus(cafeteriaId: Int): CafeteriaWithMenus { return localRepository.getCafeteriaWithMenus(cafeteriaId) } fun getCafeteriaMenus(id: Int, date: DateTime): Flowable<List<CafeteriaMenu>> { return Flowable .fromCallable { localRepository.getCafeteriaMenus(id, date) } .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .defaultIfEmpty(emptyList()) } fun getAllMenuDates(): Flowable<List<DateTime>> { return Flowable .fromCallable { localRepository.getAllMenuDates() } .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .defaultIfEmpty(emptyList()) } /** * Downloads cafeterias and stores them in the local repository. * * First checks whether a sync is necessary * Then clears current cache * Insert new cafeterias * Lastly updates last sync * */ fun getCafeteriasFromService(force: Boolean): Boolean = compositeDisposable.add(Observable.just(1) .filter { localRepository.getLastSync() == null || force } .subscribeOn(Schedulers.computation()) .observeOn(Schedulers.io()) .doOnNext { localRepository.clear() } .flatMap { remoteRepository.getAllCafeterias() } .doAfterNext { localRepository.updateLastSync() } .subscribe({ cafeteria -> cafeteria.forEach { localRepository.addCafeteria(it) } }, { throwable -> Utils.log(throwable) }) ) /** * Adds the distance between user and cafeteria to model. */ private fun transformCafeteria(cafeterias: List<Cafeteria>, location: Location): List<Cafeteria> = cafeterias.map { val results = FloatArray(1) Location.distanceBetween(it.latitude, it.longitude, location.latitude, location.longitude, results) it.distance = results[0] it } }
gpl-3.0
599d3f65d1ba9b30f1f55a0c8ecf1676
41.636364
115
0.654584
5.203883
false
false
false
false
CruGlobal/android-gto-support
gto-support-kotlin-coroutines/src/main/kotlin/org/ccci/gto/android/common/kotlin/coroutines/flow/StateFlowValue.kt
1
684
package org.ccci.gto.android.common.kotlin.coroutines.flow /** * Wrapper class for StateFlow values that supports indicating if the current value is the initial value or not. */ open class StateFlowValue<T>(val value: T) { class Initial<T>(value: T) : StateFlowValue<T>(value) { override val isInitial get() = true } open val isInitial get() = false override fun equals(other: Any?): Boolean { if (this === other) return true if (javaClass != other?.javaClass) return false other as StateFlowValue<*> if (value != other.value) return false return true } override fun hashCode() = value?.hashCode() ?: 0 }
mit
e6f83386fa871f8070b6bd3f7e6902a4
28.73913
112
0.650585
4.248447
false
false
false
false
CruGlobal/android-gto-support
gto-support-db/src/main/java/org/ccci/gto/android/common/db/AbstractDao.kt
2
14683
package org.ccci.gto.android.common.db import android.content.ContentValues import android.database.Cursor import android.database.sqlite.SQLiteDatabase import android.database.sqlite.SQLiteOpenHelper import android.database.sqlite.SQLiteTransactionListener import android.os.AsyncTask import androidx.annotation.WorkerThread import androidx.collection.SimpleArrayMap import java.util.Date import java.util.Locale import java.util.concurrent.Executor import org.ccci.gto.android.common.db.CommonTables.LastSyncTable import org.ccci.gto.android.common.util.ArrayUtils import org.ccci.gto.android.common.util.database.getLong import org.ccci.gto.android.common.util.database.map import org.ccci.gto.android.common.util.kotlin.threadLocal abstract class AbstractDao(private val helper: SQLiteOpenHelper) : Dao { companion object { private const val ARG_PREFIX = "org.ccci.gto.android.common.db.AbstractDao" const val ARG_DISTINCT = "$ARG_PREFIX.ARG_DISTINCT" const val ARG_JOINS = "$ARG_PREFIX.ARG_JOINS" const val ARG_PROJECTION = "$ARG_PREFIX.ARG_PROJECTION" const val ARG_WHERE = "$ARG_PREFIX.ARG_WHERE" const val ARG_ORDER_BY = "$ARG_PREFIX.ARG_ORDER_BY" @JvmStatic fun bindValues(vararg raw: Any) = raw.map { when (it) { is String -> it is Boolean -> if (it) "1" else "0" is Date -> it.time.toString() is Locale -> it.toLanguageTag() else -> it.toString() } }.toTypedArray() } @Deprecated("Since v3.11.0, the Dao no longer provides a backgroundExecutor, use coroutines instead.") override val backgroundExecutor: Executor get() = AsyncTask.THREAD_POOL_EXECUTOR final override val services = mutableMapOf<Class<*>, Any>() @get:WorkerThread protected val readableDatabase: SQLiteDatabase get() = helper.readableDatabase @get:WorkerThread protected val writableDatabase: SQLiteDatabase get() = helper.writableDatabase // region Registered Types private val tableTypes = SimpleArrayMap<Class<*>, TableType>() protected inline fun <reified T : Any> registerType( table: String, projection: Array<String>? = null, mapper: Mapper<T>? = null, pkWhere: Expression? = null ) = registerType(T::class.java, table, projection, mapper, pkWhere) protected fun <T : Any> registerType( clazz: Class<T>, table: String, projection: Array<String>? = null, mapper: Mapper<T>? = null, pkWhere: Expression? = null ) { tableTypes.put(clazz, TableType(table, projection, mapper, pkWhere)) } internal open fun tableName(clazz: Class<*>) = tableTypes.get(clazz)?.table ?: throw IllegalArgumentException("invalid class specified: ${clazz.name}") protected fun getTable(clazz: Class<*>) = tableName(clazz) fun getFullProjection(table: Table<*>) = getFullProjection(table.type) override fun getFullProjection(clazz: Class<*>) = tableTypes.get(clazz)?.projection ?: throw IllegalArgumentException("invalid class specified: ${clazz.name}") protected fun getPrimaryKeyWhere(clazz: Class<*>, vararg key: Any) = getPrimaryKeyWhere(clazz).args(*key) protected fun getPrimaryKeyWhere(clazz: Class<*>) = tableTypes.get(clazz)?.primaryWhere ?: throw IllegalArgumentException("invalid class specified: ${clazz.name}") protected open fun getPrimaryKeyWhere(obj: Any): Expression = throw IllegalArgumentException("unsupported object: ${obj.javaClass.name}") @Suppress("UNCHECKED_CAST") protected fun <T> getMapper(clazz: Class<T>) = tableTypes.get(clazz)?.mapper as? Mapper<T> ?: throw IllegalArgumentException("invalid class specified: ${clazz.name}") // endregion Registered Types // region Queries // region Read-Only @WorkerThread fun <T : Any> refresh(obj: T): T? = find(obj.javaClass, getPrimaryKeyWhere(obj)) @WorkerThread final override fun <T : Any> find(clazz: Class<T>, vararg key: Any): T? = find(clazz, getPrimaryKeyWhere(clazz, *key)) @WorkerThread private fun <T : Any> find(clazz: Class<T>, where: Expression): T? { Query.select(clazz).where(where).getCursor(this).use { c -> if (c.count > 0) { c.moveToFirst() return getMapper(clazz).toObject(c) } } // default to null return null } /** * retrieve all objects of the specified type * * @param clazz the type of object to retrieve * @return */ @WorkerThread fun <T : Any> get(clazz: Class<T>): List<T> = get(Query.select(clazz)) @WorkerThread final override fun <T : Any> get(query: Query<T>) = getCursor(query.projection()).use { c -> val mapper = getMapper(query.table.type) c.map { mapper.toObject(it) } } @WorkerThread final override fun getCursor(query: Query<*>): Cursor { var projection = query.projection?.toTypedArray() ?: getFullProjection(query.table.type) var orderBy = query.orderBy // prefix projection and orderBy when we have joins if (query.joins.isNotEmpty()) { val prefix = query.table.sqlPrefix(this) projection = projection.map { if (it.contains(".")) it else prefix + it }.toTypedArray() orderBy = orderBy?.prefixOrderByFieldsWith(prefix) } // generate "FROM {}" SQL val from = query.buildSqlFrom(this) var args = from.args // generate "WHERE {}" SQL val where = query.buildSqlWhere(this) args = ArrayUtils.merge(String::class.java, args, where?.args) // handle GROUP BY {} HAVING {} var groupBy: String? = null var having: String? = null if (query.groupBy.isNotEmpty()) { // generate "GROUP BY {}" SQL groupBy = query.groupBy.joinToString(",") { it.buildSql(this).sql } // generate "HAVING {}" SQL val havingRaw = query.buildSqlHaving(this) having = havingRaw?.sql args = ArrayUtils.merge(String::class.java, args, havingRaw?.args) } // execute actual query val c = transaction(exclusive = false, readOnly = true) { it.query(query.isDistinct, from.sql, projection, where?.sql, args, groupBy, having, orderBy, query.sqlLimit) } c.moveToPosition(-1) return c } // endregion Read-Only // region Read-Write @WorkerThread final override fun <T : Any> insert(obj: T, conflictAlgorithm: Int): Long { val clazz = obj.javaClass val table = tableName(clazz) val values = getMapper(clazz).toContentValues(obj, getFullProjection(clazz)) return transaction(exclusive = false) { db -> invalidateClass(clazz) db.insertWithOnConflict(table, null, values, conflictAlgorithm) } } @WorkerThread fun replace(obj: Any) { transaction { _ -> delete(obj) insert(obj) } } @WorkerThread fun update(obj: Any) = update(obj, projection = getFullProjection(obj.javaClass)) @WorkerThread final override fun <T : Any> update(obj: T, conflictAlgorithm: Int, vararg projection: String): Int { val type = obj.javaClass val values = getMapper(type).toContentValues(obj, projection) return update(type, values, getPrimaryKeyWhere(obj), conflictAlgorithm) } @WorkerThread final override fun <T : Any> update( obj: T, where: Expression?, conflictAlgorithm: Int, vararg projection: String ): Int { val type = obj.javaClass return update(type, getMapper(type).toContentValues(obj, projection), where, conflictAlgorithm) } /** * Update the specified `values` for objects of type `type` that match the specified `where` clause. * If `where` is null, all objects of type `type` will be updated * * @param type the type of Object to update * @param values the new values for the specified object * @param where an optional [Expression] to narrow the scope of which objects are updated * @param conflictAlgorithm the conflict algorithm to use when updating the database * @return the number of rows affected */ @JvmOverloads @WorkerThread protected fun update( type: Class<*>, values: ContentValues, where: Expression?, conflictAlgorithm: Int = SQLiteDatabase.CONFLICT_NONE ): Int { val table = tableName(type) val w = where?.buildSql(this) return transaction(exclusive = false) { db -> invalidateClass(type) db.updateWithOnConflict(table, values, w?.sql, w?.args, conflictAlgorithm) } } @WorkerThread fun updateOrInsert(obj: Any) = updateOrInsert(obj, projection = getFullProjection(obj.javaClass)) @WorkerThread @Suppress("IMPLICIT_CAST_TO_ANY") final override fun updateOrInsert(obj: Any, conflictAlgorithm: Int, vararg projection: String) { transaction { _ -> if (refresh(obj) != null) update(obj, conflictAlgorithm, *projection) else insert(obj, conflictAlgorithm) } } @WorkerThread final override fun delete(obj: Any) = delete(obj.javaClass, getPrimaryKeyWhere(obj)) @WorkerThread final override fun delete(clazz: Class<*>, where: Expression?) { val w = where?.buildSql(this) transaction(exclusive = false) { db -> db.delete(tableName(clazz), w?.sql, w?.args) invalidateClass(clazz) } } // endregion Read-Write // endregion Queries // region Transaction Management @WorkerThread private fun newTransaction(db: SQLiteDatabase) = Transaction.newTransaction(db).apply { transactionListener = InvalidationListener(this) } @WorkerThread fun <T, X : Throwable?> inTransaction(closure: Closure<T, X>): T = inTransaction(writableDatabase, true, closure) @WorkerThread fun <T, X : Throwable?> inNonExclusiveTransaction(closure: Closure<T, X>): T = inTransaction(writableDatabase, false, closure) @WorkerThread protected fun <T, X : Throwable?> inTransaction( db: SQLiteDatabase, exclusive: Boolean = true, closure: Closure<T, X> ): T = db.transaction(exclusive) { closure.run() } @WorkerThread override fun <T> transaction(exclusive: Boolean, body: () -> T): T = writableDatabase.transaction(exclusive) { body() } @WorkerThread protected fun <T> transaction( exclusive: Boolean = true, readOnly: Boolean = false, body: (SQLiteDatabase) -> T ): T = (if (readOnly) readableDatabase else writableDatabase).transaction(exclusive, body) @WorkerThread private inline fun <T> SQLiteDatabase.transaction( exclusive: Boolean = true, body: (SQLiteDatabase) -> T ): T = with(newTransaction(this)) { try { beginTransaction(exclusive) val result = body(this@transaction) setTransactionSuccessful() return result } finally { endTransaction().recycle() } } // endregion Transaction Management // region LastSync tracking init { registerType( LastSyncTable::class.java, LastSyncTable.TABLE_NAME, null, null, LastSyncTable.SQL_WHERE_PRIMARY_KEY ) } fun getLastSyncTime(vararg key: Any) = Query.select(LastSyncTable::class.java).projection(LastSyncTable.COLUMN_LAST_SYNCED) .where(LastSyncTable.SQL_WHERE_PRIMARY_KEY.args(key.joinToString(":"))) .getCursor(this) .use { if (it.moveToFirst()) it.getLong(LastSyncTable.COLUMN_LAST_SYNCED, 0) else 0 } fun updateLastSyncTime(vararg key: Any) { val values = ContentValues().apply { put(LastSyncTable.COLUMN_KEY, key.joinToString(":")) put(LastSyncTable.COLUMN_LAST_SYNCED, System.currentTimeMillis()) } // update the last sync time, we can use replace since this is just a keyed timestamp transaction(exclusive = false) { db -> db.replace(tableName(LastSyncTable::class.java), null, values) invalidateClass(LastSyncTable::class.java) } } // endregion LastSync tracking // region Data Invalidation private var currentTransaction by threadLocal<Transaction>() private inner class InvalidationListener( private val transaction: Transaction ) : SQLiteTransactionListener, Transaction.Listener { private var commited = false override fun onBegin() { transaction.parent = currentTransaction currentTransaction = transaction } override fun onCommit() { currentTransaction = transaction.parent commited = true } override fun onRollback() { currentTransaction = transaction.parent } override fun onFinished() { if (commited) transaction.invalidatedClasses.forEach { invalidateClass(it) } } } private val invalidationCallbacks = mutableListOf<Dao.InvalidationCallback>() final override fun registerInvalidationCallback(callback: Dao.InvalidationCallback) = synchronized(invalidationCallbacks) { invalidationCallbacks += callback } final override fun unregisterInvalidationCallback(callback: Dao.InvalidationCallback) = synchronized(invalidationCallbacks) { invalidationCallbacks -= callback } @WorkerThread protected fun invalidateClass(clazz: Class<*>) { currentTransaction?.let { it.invalidatedClasses.add(clazz) return } synchronized(invalidationCallbacks) { invalidationCallbacks.toTypedArray() }.forEach { it.onInvalidate(clazz) } } @Deprecated("Since v3.11.0, register an InvalidationCallback instead.") protected open fun onInvalidateClass(clazz: Class<*>) = Unit init { registerInvalidationCallback { onInvalidateClass(it) } } // endregion Data Invalidation protected fun compileExpression(expression: Expression) = expression.buildSql(this) } internal fun String.prefixOrderByFieldsWith(prefix: String): String = when { contains(",") -> split(",").joinToString(",") { it.prefixOrderByFieldsWith(prefix) } !contains(".") -> "$prefix${trimStart()}" else -> this }
mit
92ff9348fa9880a28ca81879a261545c
35.89196
120
0.646939
4.547228
false
false
false
false
esofthead/mycollab
mycollab-core/src/main/java/com/mycollab/core/NewUpdateAvailableNotification.kt
3
1892
/** * Copyright © MyCollab * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http:></http:>//www.gnu.org/licenses/>. */ package com.mycollab.core /** * @author MyCollab Ltd * @since 5.1.3 */ class NewUpdateAvailableNotification(val version: String, val autoDownloadLink: String?, val manualDownloadLink: String, val installerFile: String?) : AbstractNotification(AbstractNotification.SYSTEM) { override fun equals(other: Any?): Boolean { if (this === other) return true if (other !is NewUpdateAvailableNotification) return false val that = other as NewUpdateAvailableNotification? if (version != that!!.version) return false if (if (autoDownloadLink != null) autoDownloadLink != that.autoDownloadLink else that.autoDownloadLink != null) return false if (manualDownloadLink != that.manualDownloadLink) return false return if (installerFile != null) installerFile == that.installerFile else that.installerFile == null } override fun hashCode(): Int { var result = version.hashCode() result = 31 * result + (autoDownloadLink?.hashCode() ?: 0) result = 31 * result + manualDownloadLink.hashCode() result = 31 * result + (installerFile?.hashCode() ?: 0) return result } }
agpl-3.0
97df914d412aba2ae1b3ba765368c4b4
40.108696
202
0.701216
4.481043
false
false
false
false
inorichi/tachiyomi-extensions
src/ja/rawdevart/src/eu/kanade/tachiyomi/extension/ja/rawdevart/Rawdevart.kt
1
13053
package eu.kanade.tachiyomi.extension.ja.rawdevart import eu.kanade.tachiyomi.network.GET import eu.kanade.tachiyomi.source.model.Filter import eu.kanade.tachiyomi.source.model.FilterList import eu.kanade.tachiyomi.source.model.Page import eu.kanade.tachiyomi.source.model.SChapter import eu.kanade.tachiyomi.source.model.SManga import eu.kanade.tachiyomi.source.online.ParsedHttpSource import eu.kanade.tachiyomi.util.asJsoup import okhttp3.HttpUrl.Companion.toHttpUrlOrNull import okhttp3.OkHttpClient import okhttp3.Request import okhttp3.Response import org.jsoup.nodes.Document import org.jsoup.nodes.Element import java.text.SimpleDateFormat import java.util.Date import java.util.Locale class Rawdevart : ParsedHttpSource() { override val name = "Rawdevart" override val baseUrl = "https://rawdevart.com" override val lang = "ja" override val supportsLatest = true override val client: OkHttpClient = network.cloudflareClient override fun latestUpdatesRequest(page: Int) = GET("$baseUrl/comic/?page=$page&lister=0") override fun latestUpdatesSelector() = "div.row div.hovereffect" override fun latestUpdatesFromElement(element: Element): SManga { val manga = SManga.create() val item = element.select("a.head") manga.setUrlWithoutDomain(item.attr("href")) manga.title = item.text() manga.thumbnail_url = element.select("img").attr("abs:src") return manga } override fun latestUpdatesNextPageSelector() = "li.page-item:not(.disabled) a[aria-label=next]" override fun popularMangaRequest(page: Int) = GET("$baseUrl/comic/?page=$page&lister=5") override fun popularMangaFromElement(element: Element) = latestUpdatesFromElement(element) override fun popularMangaSelector() = latestUpdatesSelector() override fun popularMangaNextPageSelector() = latestUpdatesNextPageSelector() override fun searchMangaRequest(page: Int, query: String, filters: FilterList): Request { val url = "$baseUrl/search/".toHttpUrlOrNull()!!.newBuilder() url.addQueryParameter("page", page.toString()) url.addQueryParameter("title", query) filters.forEach { filter -> when (filter) { is AuthorFilter -> { url.addQueryParameter("author", filter.state) } is ArtistFilter -> { url.addQueryParameter("artist", filter.state) } is SortFilter -> { url.addQueryParameter("lister", filter.toUriPart()) } is TypeFilter -> { val typeToExclude = mutableListOf<String>() val typeToInclude = mutableListOf<String>() filter.state.forEach { content -> if (content.isExcluded()) typeToExclude.add(content.id) else if (content.isIncluded()) typeToInclude.add(content.id) } if (typeToExclude.isNotEmpty()) { url.addQueryParameter( "ctype_exc", typeToExclude .joinToString(",") ) } if (typeToInclude.isNotEmpty()) { url.addQueryParameter( "ctype_inc", typeToInclude .joinToString(",") ) } } is StatusFilter -> { val statusToExclude = mutableListOf<String>() val statusToInclude = mutableListOf<String>() filter.state.forEach { content -> if (content.isExcluded()) statusToExclude.add(content.id) else if (content.isIncluded()) statusToInclude.add(content.id) } if (statusToExclude.isNotEmpty()) { url.addQueryParameter( "status_exc", statusToExclude .joinToString(",") ) } if (statusToInclude.isNotEmpty()) { url.addQueryParameter( "status_inc", statusToInclude .joinToString(",") ) } } is GenreFilter -> { val genreToExclude = mutableListOf<String>() val genreToInclude = mutableListOf<String>() filter.state.forEach { content -> if (content.isExcluded()) genreToExclude.add(content.id) else if (content.isIncluded()) genreToInclude.add(content.id) } if (genreToExclude.isNotEmpty()) { url.addQueryParameter( "genre_exc", genreToExclude .joinToString(",") ) } if (genreToInclude.isNotEmpty()) { url.addQueryParameter( "genre_inc", genreToInclude .joinToString(",") ) } } } } return GET(url.build().toString(), headers) } override fun searchMangaSelector() = latestUpdatesSelector() override fun searchMangaFromElement(element: Element) = latestUpdatesFromElement(element) override fun searchMangaNextPageSelector() = latestUpdatesNextPageSelector() override fun mangaDetailsRequest(manga: SManga): Request { if (manga.url.startsWith("http")) { return GET(manga.url, headers) } return super.mangaDetailsRequest(manga) } override fun mangaDetailsParse(document: Document): SManga { val infoElement = document.select("div.manga-main") val manga = SManga.create() val status = infoElement.select("th:contains(Status) + td").text() val genres = mutableListOf<String>() infoElement.select("div.genres a").forEach { element -> val genre = element.text() genres.add(genre) } manga.title = infoElement.select("h1").text() manga.author = infoElement.select("th:contains(Author) + td").text() manga.artist = infoElement.select("th:contains(Artist) + td").text() manga.status = parseStatus(status) manga.genre = genres.joinToString(", ") manga.description = infoElement.select("div.description").text() .substringAfter("Description ") manga.thumbnail_url = infoElement.select("img.img-fluid.not-lazy").attr("abs:src") return manga } private fun parseStatus(status: String?) = when { status == null -> SManga.UNKNOWN status.contains("Ongoing") -> SManga.ONGOING status.contains("Finished") -> SManga.COMPLETED else -> SManga.UNKNOWN } override fun chapterListRequest(manga: SManga) = chapterListRequest(manga.url, 1) private fun chapterListRequest(mangaUrl: String, page: Int): Request { return GET("$baseUrl$mangaUrl?page=$page", headers) } override fun chapterListSelector() = "div.list-group-item" override fun chapterListParse(response: Response): List<SChapter> { var document = response.asJsoup() val chapters = mutableListOf<SChapter>() var nextPage = 2 document.select(chapterListSelector()).map { chapters.add(chapterFromElement(it)) } while (document.select(paginationNextPageSelector).isNotEmpty()) { val currentPage = document.select("form#filter_form").attr("action") document = client.newCall(chapterListRequest(currentPage, nextPage)).execute().asJsoup() document.select(chapterListSelector()).map { chapters.add(chapterFromElement(it)) } nextPage++ } return chapters } private val paginationNextPageSelector = latestUpdatesNextPageSelector() override fun chapterFromElement(element: Element): SChapter { val chapter = SChapter.create() chapter.setUrlWithoutDomain(element.select("a").attr("href")) chapter.name = element.select("div.rounded-0 span.text-truncate").text() chapter.date_upload = element.select("span.mr-2").text().let { try { when { it.contains("ago") -> Date(System.currentTimeMillis() - it.split("\\s".toRegex())[0].toLong() * 60 * 60 * 1000).time it.contains("Yesterday") -> Date(System.currentTimeMillis() - 24 * 60 * 60 * 1000).time it.contains(".") -> SimpleDateFormat("MMM. dd, yyyy", Locale.US).parse(it)?.time ?: 0L else -> SimpleDateFormat("yyyy-MM-dd", Locale.US).parse(it)?.time ?: 0L } } catch (e: Exception) { Date(System.currentTimeMillis()).time } } return chapter } override fun pageListParse(document: Document): List<Page> { val pages = mutableListOf<Page>() document.select("img.not-lazy[data-src]").forEachIndexed { i, img -> pages.add(Page(i, "", img.attr("data-src"))) } return pages } override fun imageUrlParse(document: Document): String = throw UnsupportedOperationException("Not used") private class AuthorFilter : Filter.Text("Author") private class ArtistFilter : Filter.Text("Artist") private class SortFilter : UriPartFilter( "Sort By", arrayOf( Pair("<select>", ""), Pair("Latest", "0"), Pair("A-Z", "1"), Pair("Z-A", "2"), Pair("Star", "3"), Pair("Bookmark", "4"), Pair("View", "5") ) ) private class TypeFilter(type: List<Tag>) : Filter.Group<Tag>("Types", type) private class StatusFilter(status: List<Tag>) : Filter.Group<Tag>("Status", status) private class GenreFilter(genres: List<Tag>) : Filter.Group<Tag>("Genres", genres) override fun getFilterList() = FilterList( Filter.Header("Combine Sort filter with other filters."), Filter.Separator(), AuthorFilter(), ArtistFilter(), SortFilter(), TypeFilter(getTypeList()), StatusFilter(getStatusList()), GenreFilter(getGenreList()) ) private fun getTypeList() = listOf( Tag("0", "Manga"), Tag("1", "Webtoon"), Tag("2", "Manhwa - Korean"), Tag("3", "Manhua - Chinese"), Tag("4", "Comic"), Tag("5", "Doujinshi") ) private fun getStatusList() = listOf( Tag("0", "Ongoing"), Tag("1", "Haitus"), Tag("2", "Axed"), Tag("3", "Unknown"), Tag("4", "Finished") ) private fun getGenreList() = listOf( Tag("29", "4-koma"), Tag("1", "Action"), Tag("37", "Adult"), Tag("2", "Adventure"), Tag("3", "Comedy"), Tag("33", "Cooking"), Tag("4", "Crime"), Tag("5", "Drama"), Tag("30", "Ecchi"), Tag("6", "Fantasy"), Tag("34", "Gender Bender"), Tag("31", "Gore"), Tag("39", "Harem"), Tag("7", "Historical"), Tag("8", "Horror"), Tag("9", "Isekai"), Tag("42", "Josei"), Tag("35", "Martial Arts"), Tag("36", "Mature"), Tag("10", "Mecha"), Tag("11", "Medical"), Tag("38", "Music"), Tag("12", "Mystery"), Tag("13", "Philosophical"), Tag("14", "Psychological"), Tag("15", "Romance"), Tag("40", "School Life"), Tag("16", "Sci-Fi"), Tag("41", "Seinen"), Tag("28", "Shoujo"), Tag("17", "Shoujo Ai"), Tag("27", "Shounen"), Tag("18", "Shounen Ai"), Tag("19", "Slice of Life"), Tag("32", "Smut"), Tag("20", "Sports"), Tag("21", "Super Powers"), Tag("43", "Supernatural"), Tag("22", "Thriller"), Tag("23", "Tragedy"), Tag("24", "Wuxia"), Tag("25", "Yaoi"), Tag("26", "Yuri") ) private open class UriPartFilter(displayName: String, val vals: Array<Pair<String, String>>) : Filter.Select<String>(displayName, vals.map { it.first }.toTypedArray()) { fun toUriPart() = vals[state].second } private class Tag(val id: String, name: String) : Filter.TriState(name) }
apache-2.0
f4cc160532dd31e1899a75b008cd0f7e
36.188034
136
0.538497
4.921946
false
false
false
false
java-opengl-labs/learn-OpenGL
src/main/kotlin/learnOpenGL/b_lighting/2.2 basic lighting specular.kt
1
4620
package learnOpenGL.b_lighting /** * Created by GBarbieri on 28.04.2017. */ import glm_.func.rad import glm_.glm import glm_.mat4x4.Mat4 import glm_.vec3.Vec3 import gln.buffer.glBindBuffer import gln.draw.glDrawArrays import gln.get import gln.glClearColor import gln.glf.glf import gln.uniform.glUniform import gln.uniform.glUniform3 import gln.vertexArray.glEnableVertexAttribArray import gln.vertexArray.glVertexAttribPointer import learnOpenGL.a_gettingStarted.end import learnOpenGL.a_gettingStarted.swapAndPoll import org.lwjgl.opengl.GL11.* import org.lwjgl.opengl.GL15.* import org.lwjgl.opengl.GL20.glGetUniformLocation import org.lwjgl.opengl.GL30.* import uno.buffer.destroyBuf import uno.buffer.intBufferBig import uno.glsl.Program import uno.glsl.glDeletePrograms import uno.glsl.glUseProgram fun main(args: Array<String>) { with(BasicLightingSpecular()) { run() end() } } private class BasicLightingSpecular { val window = initWindow0("Basic Lighting Specular") val lighting = Lighting() val lamp = Lamp() val vbo = intBufferBig(1) enum class VA { Cube, Light } val vao = intBufferBig<VA>() val lightPos = Vec3(1.2f, 1f, 2f) inner class Lighting : Lamp("shaders/b/_2_2", "basic-lighting") { val objCol = glGetUniformLocation(name, "objectColor") val lgtCol = glGetUniformLocation(name, "lightColor") val lgtPos = glGetUniformLocation(name, "lightPos") val viewPos = glGetUniformLocation(name, "viewPos") } inner open class Lamp(root: String = "shaders/b/_1", shader: String = "lamp") : Program(root, "$shader.vert", "$shader.frag") { val model = glGetUniformLocation(name, "model") val view = glGetUniformLocation(name, "view") val proj = glGetUniformLocation(name, "projection") } init { glEnable(GL_DEPTH_TEST) glGenVertexArrays(vao) // first, configure the cube's VAO (and VBO) glGenBuffers(vbo) glBindBuffer(GL_ARRAY_BUFFER, vbo) glBufferData(GL_ARRAY_BUFFER, verticesCube0, GL_STATIC_DRAW) glBindVertexArray(vao[VA.Cube]) glVertexAttribPointer(glf.pos3_nor3) glEnableVertexAttribArray(glf.pos3_nor3) // second, configure the light's VAO (VBO stays the same; the vertices are the same for the light object which is also a 3D cube) glBindVertexArray(vao[VA.Light]) glBindBuffer(GL_ARRAY_BUFFER, vbo) // note that we update the lamp's position attribute's stride to reflect the updated buffer data glVertexAttribPointer(glf.pos3_nor3[0]) glEnableVertexAttribArray(glf.pos3_nor3[0]) } fun run() { while (window.open) { window.processFrame() // render glClearColor(clearColor0) glClear(GL_COLOR_BUFFER_BIT or GL_DEPTH_BUFFER_BIT) // be sure to activate shader when setting uniforms/drawing objects glUseProgram(lighting) glUniform(lighting.objCol, 1f, 0.5f, 0.31f) /* we can avoid to write this glUniform(lighting.lgtCol, 1.0f, 1.0f, 1.0f) but we have to specify explicit the dimensionality with 3*/ glUniform3(lighting.lgtCol, 1f) glUniform(lighting.lgtPos, lightPos) glUniform(lighting.viewPos, camera.position) // view/projection transformations val projection = glm.perspective(camera.zoom.rad, window.aspect, 0.1f, 100f) val view = camera.viewMatrix glUniform(lighting.proj, projection) glUniform(lighting.view, view) // world transformation var model = Mat4() glUniform(lighting.model, model) // render the cube glBindVertexArray(vao[VA.Cube]) glDrawArrays(GL_TRIANGLES, 36) // also draw the lamp object glUseProgram(lamp) glUniform(lamp.proj, projection) glUniform(lamp.view, view) model = model .translate(lightPos) .scale(0.2f) // a smaller cube glUniform(lamp.model, model) glBindVertexArray(vao[VA.Light]) glDrawArrays(GL_TRIANGLES, 36) window.swapAndPoll() } } fun end() { // optional: de-allocate all resources once they've outlived their purpose: glDeletePrograms(lighting, lamp) glDeleteVertexArrays(vao) glDeleteBuffers(vbo) destroyBuf(vao, vbo) window.end() } }
mit
f3a8ec3f521d98c17d0afefa515166fd
27.006061
137
0.643074
4.07767
false
false
false
false
ligee/kotlin-jupyter
jupyter-lib/lib-ext/src/main/kotlin/org/jetbrains/kotlinx/jupyter/ext/graph/visualization/graphViz.kt
1
1687
package org.jetbrains.kotlinx.jupyter.ext.graph.visualization import guru.nidi.graphviz.engine.Engine import guru.nidi.graphviz.engine.Format import guru.nidi.graphviz.engine.Graphviz import guru.nidi.graphviz.parse.Parser import org.jetbrains.kotlinx.jupyter.api.graphs.GraphNode import org.jetbrains.kotlinx.jupyter.ext.Image import org.jetbrains.kotlinx.jupyter.ext.graph.structure.MultiGraph import java.io.ByteArrayOutputStream fun <T> MultiGraph<T>.dotText(): String { val nodesNumbers = nodes.mapIndexed { index, hierarchyElement -> hierarchyElement to index }.toMap() fun id(el: GraphNode<T>) = "n${nodesNumbers[el]}" return buildString { appendLine("""digraph "" { """) for (node in nodes) { val nodeId = id(node) appendLine("$nodeId ;") append("$nodeId [") with(node.label) { append("label=$text ") shape?.let { append("shape=$it ") } } appendLine("] ;") } for ((n1, n2) in directedEdges) { appendLine("${id(n1)} -> ${id(n2)} ;") } for ((n1, n2) in undirectedEdges) { appendLine("${id(n1)} -> ${id(n2)} [dir=none] ;") } appendLine("}") } } fun renderDotText(text: String): Image { val graph = Parser().read(text) val stream = ByteArrayOutputStream() Graphviz .fromGraph(graph) .engine(Engine.DOT) .render(Format.SVG) .toOutputStream(stream) return Image(stream.toByteArray(), "svg") } fun <T> MultiGraph<T>.render(): Image { return renderDotText(dotText()) } fun <T> MultiGraph<T>.toHTML() = render().toHTML()
apache-2.0
fde7f6adea63d1c7539980a72ebf4f1f
30.240741
104
0.611737
3.79955
false
false
false
false
googleads/googleads-mobile-android-examples
kotlin/admanager/RewardedInterstitialExample/app/src/main/java/com/google/android/gms/example/rewardedinterstitialexample/MainActivity.kt
1
6781
package com.google.android.gms.example.rewardedinterstitialexample import android.os.Bundle import android.os.CountDownTimer import android.util.Log import android.view.View import androidx.appcompat.app.AppCompatActivity import com.google.android.gms.ads.AdError import com.google.android.gms.ads.FullScreenContentCallback import com.google.android.gms.ads.LoadAdError import com.google.android.gms.ads.MobileAds import com.google.android.gms.ads.admanager.AdManagerAdRequest import com.google.android.gms.ads.rewardedinterstitial.RewardedInterstitialAd import com.google.android.gms.ads.rewardedinterstitial.RewardedInterstitialAdLoadCallback import kotlinx.android.synthetic.main.activity_main.coin_count_text import kotlinx.android.synthetic.main.activity_main.retry_button import kotlinx.android.synthetic.main.activity_main.timer private const val AD_UNIT_ID = "/21775744923/example/rewarded_interstitial" private const val GAME_COUNTER_TIME = 10L private const val GAME_OVER_REWARD = 1 private const val MAIN_ACTIVITY_TAG = "MainActivity" class MainActivity : AppCompatActivity() { private var coinCount: Int = 0 private var countDownTimer: CountDownTimer? = null private var gameOver = false private var gamePaused = false private var isLoadingAds = false private var rewardedInterstitialAd: RewardedInterstitialAd? = null private var timeRemaining: Long = 0L override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // Log the Mobile Ads SDK version. Log.d(MAIN_ACTIVITY_TAG, "Google Mobile Ads SDK Version: " + MobileAds.getVersion()) MobileAds.initialize(this) { initializationStatus -> loadRewardedInterstitialAd() } // Create the "retry" button, which tries to show a rewarded video ad between game plays. retry_button.visibility = View.INVISIBLE retry_button.setOnClickListener { startGame() } // Display current coin count to user. coin_count_text.text = "Coins: $coinCount" startGame() } public override fun onPause() { super.onPause() pauseGame() } public override fun onResume() { super.onResume() if (!gameOver && gamePaused) { resumeGame() } } private fun pauseGame() { countDownTimer?.cancel() gamePaused = true } private fun resumeGame() { createTimer(timeRemaining) gamePaused = false } private fun loadRewardedInterstitialAd() { if (rewardedInterstitialAd == null) { isLoadingAds = true val adRequest = AdManagerAdRequest.Builder().build() // Load an ad. RewardedInterstitialAd.load( this, AD_UNIT_ID, adRequest, object : RewardedInterstitialAdLoadCallback() { override fun onAdFailedToLoad(adError: LoadAdError) { super.onAdFailedToLoad(adError) Log.d(MAIN_ACTIVITY_TAG, "onAdFailedToLoad: ${adError.message}") isLoadingAds = false rewardedInterstitialAd = null } override fun onAdLoaded(rewardedAd: RewardedInterstitialAd) { super.onAdLoaded(rewardedAd) Log.d(MAIN_ACTIVITY_TAG, "Ad was loaded.") rewardedInterstitialAd = rewardedAd isLoadingAds = false } } ) } } private fun addCoins(coins: Int) { coinCount += coins coin_count_text.text = "Coins: $coinCount" } private fun startGame() { // Hide the retry button, load the ad, and start the timer. retry_button.visibility = View.INVISIBLE if (rewardedInterstitialAd == null && !isLoadingAds) { loadRewardedInterstitialAd() } createTimer(GAME_COUNTER_TIME) gamePaused = false gameOver = false } // Create the game timer, which counts down to the end of the level // and shows the "retry" button. private fun createTimer(time: Long) { countDownTimer?.cancel() countDownTimer = object : CountDownTimer(time * 1000, 50) { override fun onTick(millisUnitFinished: Long) { timeRemaining = millisUnitFinished / 1000 + 1 timer.text = "seconds remaining: $timeRemaining" } override fun onFinish() { timer.text = "The game has ended!" addCoins(GAME_OVER_REWARD) retry_button.visibility = View.VISIBLE gameOver = true if (rewardedInterstitialAd == null) { Log.d( MAIN_ACTIVITY_TAG, "The game is over but the rewarded interstitial ad wasn't ready yet." ) return } Log.d(MAIN_ACTIVITY_TAG, "The rewarded interstitial ad is ready.") val rewardAmount = rewardedInterstitialAd!!.rewardItem.amount val rewardType = rewardedInterstitialAd!!.rewardItem.type introduceVideoAd(rewardAmount, rewardType) } } countDownTimer?.start() } private fun introduceVideoAd(rewardAmount: Int, rewardType: String) { val dialog = AdDialogFragment.newInstance(rewardAmount, rewardType) dialog.setAdDialogInteractionListener( object : AdDialogFragment.AdDialogInteractionListener { override fun onShowAd() { Log.d(MAIN_ACTIVITY_TAG, "The rewarded interstitial ad is starting.") showRewardedVideo() } override fun onCancelAd() { Log.d(MAIN_ACTIVITY_TAG, "The rewarded interstitial ad was skipped before it starts.") } } ) dialog.show(supportFragmentManager, "AdDialogFragment") } private fun showRewardedVideo() { if (rewardedInterstitialAd == null) { Log.d(MAIN_ACTIVITY_TAG, "The rewarded interstitial ad wasn't ready yet.") return } rewardedInterstitialAd!!.fullScreenContentCallback = object : FullScreenContentCallback() { override fun onAdDismissedFullScreenContent() { Log.d(MAIN_ACTIVITY_TAG, "Ad was dismissed.") // Don't forget to set the ad reference to null so you // don't show the ad a second time. rewardedInterstitialAd = null // Preload the next rewarded interstitial ad. loadRewardedInterstitialAd() } override fun onAdFailedToShowFullScreenContent(adError: AdError) { Log.d(MAIN_ACTIVITY_TAG, "Ad failed to show.") // Don't forget to set the ad reference to null so you // don't show the ad a second time. rewardedInterstitialAd = null } override fun onAdShowedFullScreenContent() { Log.d(MAIN_ACTIVITY_TAG, "Ad showed fullscreen content.") } } rewardedInterstitialAd?.show(this) { rewardItem -> addCoins(rewardItem.amount) Log.d("TAG", "User earned the reward.") } } }
apache-2.0
339b40085b491ea49374294f5f6c3d1f
31.137441
96
0.676449
4.511643
false
false
false
false
felipebz/sonar-plsql
zpa-core/src/main/kotlin/org/sonar/plsqlopen/sslr/Statements.kt
1
2197
/** * Z PL/SQL Analyzer * Copyright (C) 2015-2022 Felipe Zorzo * mailto:felipe AT felipezorzo DOT com DOT br * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.plsqlopen.sslr import org.sonar.plsqlopen.asSemantic import org.sonar.plugins.plsqlopen.api.squid.SemanticAstNode class Statements(override val astNode: SemanticAstNode) : TreeImpl(astNode), List<SemanticAstNode> { private val children by lazy { astNode.children.asSemantic() } override val size: Int = children.size override fun contains(element: SemanticAstNode): Boolean = children.contains(element) override fun containsAll(elements: Collection<SemanticAstNode>): Boolean = children.containsAll(elements) override fun get(index: Int): SemanticAstNode = children[index] override fun indexOf(element: SemanticAstNode): Int = children.indexOf(element) override fun isEmpty(): Boolean = children.isEmpty() override fun iterator(): Iterator<SemanticAstNode> = children.iterator() override fun lastIndexOf(element: SemanticAstNode): Int = children.lastIndexOf(element) override fun listIterator(): ListIterator<SemanticAstNode> = children.listIterator() override fun listIterator(index: Int): ListIterator<SemanticAstNode> = children.listIterator(index) override fun subList(fromIndex: Int, toIndex: Int): List<SemanticAstNode> = children.subList(fromIndex, toIndex) }
lgpl-3.0
45ce976944a7f47a3217dc9bb62b9edb
34.435484
100
0.730086
4.548654
false
false
false
false
vmiklos/vmexam
osm/addr-osmify-kotlin/src/main/kotlin/TurboTags.kt
1
677
/* * Copyright 2020 Miklos Vajna. All rights reserved. * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ package hu.vmiklos.addr_osmify import com.google.gson.annotations.SerializedName /** * TurboTags contains various tags about one Overpass element. */ class TurboTags { @SerializedName("addr:city") var city: String = String() @SerializedName("addr:housenumber") var houseNumber: String = String() @SerializedName("addr:postcode") var postCode: String = String() @SerializedName("addr:street") var street: String = String() } /* vim:set shiftwidth=4 softtabstop=4 expandtab: */
mit
ae0902fcf7a2e6e32cc26f38626b61bc
27.208333
73
0.710487
3.71978
false
false
false
false
InsertKoinIO/koin
core/koin-core/src/jvmMain/kotlin/org/koin/core/registry/PropertyRegistryExt.kt
1
1639
package org.koin.core.registry import org.koin.core.Koin import org.koin.core.error.NoPropertyFileFoundException import org.koin.core.logger.Level import org.koin.ext.clearQuotes import java.util.* /** *Save properties values into PropertyRegister */ fun PropertyRegistry.saveProperties(properties: Properties) { _koin.logger.log(Level.DEBUG){"load ${properties.size} properties"} val propertiesMapValues = properties.toMap() as Map<String, String> propertiesMapValues.forEach { (k: String, v: String) -> saveProperty(k, v) } } /** * Load properties from Property file * @param fileName */ fun PropertyRegistry.loadPropertiesFromFile(fileName: String) { _koin.logger.log(Level.DEBUG){"load properties from $fileName"} val content = Koin::class.java.getResource(fileName)?.readText() if (content != null) { _koin.logger.log(Level.INFO){"loaded properties from file:'$fileName'" } val properties = readDataFromFile(content) saveProperties(properties) } else { throw NoPropertyFileFoundException("No properties found for file '$fileName'") } } private fun readDataFromFile(content: String): Properties { val properties = Properties() properties.load(content.byteInputStream()) return properties } /** * Load properties from environment */ fun PropertyRegistry.loadEnvironmentProperties() { _koin.logger.log(Level.DEBUG){"load properties from environment"} val sysProperties = System.getProperties() saveProperties(sysProperties) val sysEnvProperties = System.getenv().toProperties() saveProperties(sysEnvProperties) }
apache-2.0
68f85954513bfde7cee143f58e68b8e4
28.285714
86
0.729103
4.191816
false
false
false
false
dhleong/ideavim
src/com/maddyhome/idea/vim/group/visual/VimSelection.kt
1
7670
/* * IdeaVim - Vim emulator for IDEs based on the IntelliJ platform * Copyright (C) 2003-2019 The IdeaVim authors * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.maddyhome.idea.vim.group.visual import com.intellij.openapi.editor.Editor import com.intellij.openapi.editor.LogicalPosition import com.maddyhome.idea.vim.command.CommandState import com.maddyhome.idea.vim.command.SelectionType import com.maddyhome.idea.vim.command.SelectionType.* import com.maddyhome.idea.vim.common.TextRange import com.maddyhome.idea.vim.helper.EditorHelper import kotlin.math.max import kotlin.math.min /** * @author Alex Plate * * Interface for storing selection range. * * Type of selection is stored in [type] * [vimStart] and [vimEnd] - selection offsets in vim model. There values will be stored in '< and '> marks. * Actually [vimStart] - initial caret position when visual mode entered and [vimEnd] - current caret position. * * This selection has direction. That means that by moving in left-up direction (e.g. `vbbbb`) * [vimStart] will be greater then [vimEnd]. * * All starts are included and ends are excluded */ sealed class VimSelection { abstract val type: SelectionType abstract val vimStart: Int abstract val vimEnd: Int protected abstract val editor: Editor abstract fun toVimTextRange(skipNewLineForLineMode: Boolean = false): TextRange abstract fun getNativeStartAndEnd(): Pair<Int, Int> companion object { fun create(vimStart: Int, vimEnd: Int, type: SelectionType, editor: Editor) = when (type) { CHARACTER_WISE -> { val nativeSelection = toNativeSelection(editor, vimStart, vimEnd, CommandState.Mode.VISUAL, type.toSubMode()) VimCharacterSelection(vimStart, vimEnd, nativeSelection.first, nativeSelection.second, editor) } LINE_WISE -> { val nativeSelection = toNativeSelection(editor, vimStart, vimEnd, CommandState.Mode.VISUAL, type.toSubMode()) VimLineSelection(vimStart, vimEnd, nativeSelection.first, nativeSelection.second, editor) } BLOCK_WISE -> VimBlockSelection(vimStart, vimEnd, editor, false) } } override fun toString(): String { val startLogPosition = editor.offsetToLogicalPosition(vimStart) val endLogPosition = editor.offsetToLogicalPosition(vimEnd) return "Selection [$type]: vim start[offset: $vimStart : col ${startLogPosition.column} line ${startLogPosition.line}]" + " vim end[offset: $vimEnd : col ${endLogPosition.column} line ${endLogPosition.line}]" } } /** * Interface for storing simple selection range. * Simple means that this selection can be represented only by start and end values. * There selections in vim are character- and linewise selections. * * [nativeStart] and [nativeEnd] are the offsets of native selection * * [vimStart] and [vimEnd] - selection offsets in vim model. There values will be stored in '< and '> marks. * There values can differ from [nativeStart] and [nativeEnd] in case of linewise selection because [vimStart] - initial caret * position when visual mode entered and [vimEnd] - current caret position. * * This selection has direction. That means that by moving in left-up direction (e.g. `vbbbb`) * [nativeStart] will be greater than [nativeEnd]. * If you need normalized [nativeStart] and [nativeEnd] (start always less than end) you * can use [normNativeStart] and [normNativeEnd] * * All starts are included and ends are excluded */ sealed class VimSimpleSelection : VimSelection() { abstract val nativeStart: Int abstract val nativeEnd: Int abstract val normNativeStart: Int abstract val normNativeEnd: Int override fun getNativeStartAndEnd() = normNativeStart to normNativeEnd companion object { /** * Create character- and linewise selection if native selection is already known. Doesn't work for block selection */ fun createWithNative(vimStart: Int, vimEnd: Int, nativeStart: Int, nativeEnd: Int, type: SelectionType, editor: Editor) = when (type) { CHARACTER_WISE -> VimCharacterSelection(vimStart, vimEnd, nativeStart, nativeEnd, editor) LINE_WISE -> VimLineSelection(vimStart, vimEnd, nativeStart, nativeEnd, editor) BLOCK_WISE -> throw RuntimeException("This method works only for line and character selection") } } } class VimCharacterSelection( override val vimStart: Int, override val vimEnd: Int, override val nativeStart: Int, override val nativeEnd: Int, override val editor: Editor ) : VimSimpleSelection() { override val normNativeStart = min(nativeStart, nativeEnd) override val normNativeEnd = max(nativeStart, nativeEnd) override val type: SelectionType = CHARACTER_WISE override fun toVimTextRange(skipNewLineForLineMode: Boolean) = TextRange(normNativeStart, normNativeEnd) } class VimLineSelection( override val vimStart: Int, override val vimEnd: Int, override val nativeStart: Int, override val nativeEnd: Int, override val editor: Editor ) : VimSimpleSelection() { override val normNativeStart = min(nativeStart, nativeEnd) override val normNativeEnd = max(nativeStart, nativeEnd) override val type = LINE_WISE override fun toVimTextRange(skipNewLineForLineMode: Boolean) = if (skipNewLineForLineMode && editor.document.textLength >= normNativeEnd && normNativeEnd > 0 && editor.document.text[normNativeEnd - 1] == '\n') { TextRange(normNativeStart, (normNativeEnd - 1).coerceAtLeast(0)) } else { TextRange(normNativeStart, normNativeEnd) } } class VimBlockSelection( override val vimStart: Int, override val vimEnd: Int, override val editor: Editor, val toLineEnd: Boolean ) : VimSelection() { override fun getNativeStartAndEnd() = toNativeSelection(editor, vimStart, vimEnd, CommandState.Mode.VISUAL, type.toSubMode()) override val type = BLOCK_WISE override fun toVimTextRange(skipNewLineForLineMode: Boolean): TextRange { val starts = mutableListOf<Int>() val ends = mutableListOf<Int>() forEachLine { start, end -> starts += start ends += end } return TextRange(starts.toIntArray(), ends.toIntArray()).also { it.normalize(editor.document.textLength) } } private fun forEachLine(action: (start: Int, end: Int) -> Unit) { val offsets = toNativeSelection(editor, vimStart, vimEnd, CommandState.Mode.VISUAL, type.toSubMode()) val logicalStart = editor.offsetToLogicalPosition(min(offsets.first, offsets.second)) val logicalEnd = editor.offsetToLogicalPosition(max(offsets.first, offsets.second)) val lineRange = if (logicalStart.line > logicalEnd.line) logicalStart.line downTo logicalEnd.line else logicalStart.line..logicalEnd.line lineRange.map { line -> val start = editor.logicalPositionToOffset(LogicalPosition(line, logicalStart.column)) val end = if (toLineEnd) { EditorHelper.getLineEndOffset(editor, line, true) } else { editor.logicalPositionToOffset(LogicalPosition(line, logicalEnd.column)) } action(start, end) } } }
gpl-2.0
79d2abaaa26a6902d40589cf5519af39
40.684783
152
0.738201
4.110397
false
false
false
false
Cognifide/APM
app/aem/core/src/main/kotlin/com/cognifide/apm/core/grammar/parsedscript/InvalidSyntaxMessageFactory.kt
1
2276
/* * ========================LICENSE_START================================= * AEM Permission Management * %% * Copyright (C) 2013 Wunderman Thompson Technology * %% * 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. * =========================LICENSE_END================================== */ package com.cognifide.apm.core.grammar.parsedscript import org.antlr.v4.runtime.CommonTokenStream import org.antlr.v4.runtime.IntStream import org.antlr.v4.runtime.Recognizer import org.antlr.v4.runtime.Token import org.apache.commons.lang.StringUtils object InvalidSyntaxMessageFactory { fun detailedSyntaxError(e: InvalidSyntaxException): List<String> { return underlineError(e.recognizer, e.offendingToken, e.line, e.charPositionInLine) } private fun underlineError(recognizer: Recognizer<*, *>, offendingToken: Token?, line: Int, charPositionInLine: Int): List<String> { val errorLine = getErrorLine(recognizer, line) val invalidLine = "Invalid line [$line:$charPositionInLine]: $errorLine" return if (offendingToken != null && StringUtils.isNotBlank(offendingToken.text)) { listOf(invalidLine, "Invalid sequence: ${offendingToken.text}") } else { listOf(invalidLine) } } private fun getErrorLine(recognizer: Recognizer<*, *>, line: Int): String { val input = toString(recognizer.inputStream) val lines = input.split("\n".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray() return lines[line - 1] } private fun toString(inputStream: IntStream): String { return (inputStream as? CommonTokenStream)?.tokenSource?.inputStream?.toString() ?: inputStream.toString() } }
apache-2.0
1adf13adf07d7ebfc2a17fb778923dd0
40.148148
136
0.660369
4.524851
false
false
false
false
garmax1/material-flashlight
app/src/main/java/co/garmax/materialflashlight/features/modules/ModuleFactory.kt
1
724
package co.garmax.materialflashlight.features.modules import android.content.Context import android.os.Build class ModuleFactory(private val context: Context) { fun getModule(module: ModuleBase.Module): ModuleBase { // Create new module if (module == ModuleBase.Module.MODULE_SCREEN) { return ScreenModule(context) } else if (module === ModuleBase.Module.MODULE_CAMERA_FLASHLIGHT) { return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { CameraFlashModuleV23(context) } else { CameraFlashModuleV16(context) } } throw IllegalArgumentException(module.name + " module not implemented") } }
apache-2.0
ae2a4362c72d6db9d35f55708be3836d
31.954545
79
0.646409
4.441718
false
false
false
false
Heiner1/AndroidAPS
app/src/main/java/info/nightscout/androidaps/plugins/constraints/objectives/ObjectivesFragment.kt
1
18802
package info.nightscout.androidaps.plugins.constraints.objectives import android.annotation.SuppressLint import android.os.Bundle import android.os.Handler import android.os.HandlerThread import android.os.SystemClock import android.view.Gravity import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.LinearLayout import android.widget.TextView import androidx.appcompat.app.AppCompatActivity import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.LinearSmoothScroller import androidx.recyclerview.widget.RecyclerView import dagger.android.support.DaggerFragment import info.nightscout.androidaps.R import info.nightscout.androidaps.database.entities.UserEntry.Action import info.nightscout.androidaps.database.entities.UserEntry.Sources import info.nightscout.androidaps.database.entities.ValueWithUnit import info.nightscout.androidaps.databinding.ObjectivesFragmentBinding import info.nightscout.androidaps.databinding.ObjectivesItemBinding import info.nightscout.androidaps.dialogs.NtpProgressDialog import info.nightscout.androidaps.events.EventNtpStatus import info.nightscout.shared.logging.AAPSLogger import info.nightscout.androidaps.logging.UserEntryLogger import info.nightscout.androidaps.plugins.bus.RxBus import info.nightscout.androidaps.plugins.constraints.objectives.activities.ObjectivesExamDialog import info.nightscout.androidaps.plugins.constraints.objectives.events.EventObjectivesUpdateGui import info.nightscout.androidaps.plugins.constraints.objectives.objectives.Objective.ExamTask import info.nightscout.androidaps.receivers.ReceiverStatusStore import info.nightscout.androidaps.setupwizard.events.EventSWUpdate import info.nightscout.androidaps.utils.DateUtil import info.nightscout.androidaps.utils.FabricPrivacy import info.nightscout.androidaps.utils.HtmlHelper import info.nightscout.androidaps.utils.SntpClient import info.nightscout.androidaps.utils.alertDialogs.OKDialog import io.reactivex.rxjava3.kotlin.plusAssign import info.nightscout.androidaps.interfaces.ResourceHelper import info.nightscout.androidaps.utils.rx.AapsSchedulers import info.nightscout.shared.sharedPreferences.SP import io.reactivex.rxjava3.disposables.CompositeDisposable import javax.inject.Inject class ObjectivesFragment : DaggerFragment() { @Inject lateinit var rxBus: RxBus @Inject lateinit var aapsLogger: AAPSLogger @Inject lateinit var aapsSchedulers: AapsSchedulers @Inject lateinit var sp: SP @Inject lateinit var rh: ResourceHelper @Inject lateinit var fabricPrivacy: FabricPrivacy @Inject lateinit var objectivesPlugin: ObjectivesPlugin @Inject lateinit var receiverStatusStore: ReceiverStatusStore @Inject lateinit var dateUtil: DateUtil @Inject lateinit var sntpClient: SntpClient @Inject lateinit var uel: UserEntryLogger private val objectivesAdapter = ObjectivesAdapter() private val handler = Handler(HandlerThread(this::class.simpleName + "Handler").also { it.start() }.looper) private var disposable: CompositeDisposable = CompositeDisposable() private val objectiveUpdater = object : Runnable { override fun run() { handler.postDelayed(this, (60 * 1000).toLong()) updateGUI() } } private var _binding: ObjectivesFragmentBinding? = null // This property is only valid between onCreateView and // onDestroyView. private val binding get() = _binding!! override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View = ObjectivesFragmentBinding.inflate(inflater, container, false).also { _binding = it }.root override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) binding.recyclerview.layoutManager = LinearLayoutManager(view.context) binding.recyclerview.adapter = objectivesAdapter binding.fake.setOnClickListener { updateGUI() } binding.reset.setOnClickListener { objectivesPlugin.reset() binding.recyclerview.adapter?.notifyDataSetChanged() scrollToCurrentObjective() } scrollToCurrentObjective() startUpdateTimer() } @Synchronized override fun onResume() { super.onResume() disposable += rxBus .toObservable(EventObjectivesUpdateGui::class.java) .observeOn(aapsSchedulers.main) .subscribe({ binding.recyclerview.adapter?.notifyDataSetChanged() }, fabricPrivacy::logException) } @Synchronized override fun onPause() { super.onPause() disposable.clear() } @Synchronized override fun onDestroyView() { super.onDestroyView() handler.removeCallbacks(objectiveUpdater) _binding = null } private fun startUpdateTimer() { handler.removeCallbacks(objectiveUpdater) for (objective in objectivesPlugin.objectives) { if (objective.isStarted && !objective.isAccomplished) { val timeTillNextMinute = (System.currentTimeMillis() - objective.startedOn) % (60 * 1000) handler.postDelayed(objectiveUpdater, timeTillNextMinute) break } } } private fun scrollToCurrentObjective() { activity?.runOnUiThread { for (i in 0 until objectivesPlugin.objectives.size) { val objective = objectivesPlugin.objectives[i] if (!objective.isStarted || !objective.isAccomplished) { context?.let { val smoothScroller = object : LinearSmoothScroller(it) { override fun getVerticalSnapPreference(): Int = SNAP_TO_START override fun calculateTimeForScrolling(dx: Int): Int = super.calculateTimeForScrolling(dx) * 4 } smoothScroller.targetPosition = i binding.recyclerview.layoutManager?.startSmoothScroll(smoothScroller) } break } } } } private inner class ObjectivesAdapter : RecyclerView.Adapter<ObjectivesAdapter.ViewHolder>() { override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { return ViewHolder(LayoutInflater.from(parent.context).inflate(R.layout.objectives_item, parent, false)) } @SuppressLint("SetTextI18n") override fun onBindViewHolder(holder: ViewHolder, position: Int) { val objective = objectivesPlugin.objectives[position] holder.binding.title.text = rh.gs(R.string.nth_objective, position + 1) if (objective.objective != 0) { holder.binding.objective.visibility = View.VISIBLE holder.binding.objective.text = rh.gs(objective.objective) } else holder.binding.objective.visibility = View.GONE if (objective.gate != 0) { holder.binding.gate.visibility = View.VISIBLE holder.binding.gate.text = rh.gs(objective.gate) } else holder.binding.gate.visibility = View.GONE if (!objective.isStarted) { holder.binding.gate.setTextColor(rh.gac(context, R.attr.defaultTextColor)) holder.binding.verify.visibility = View.GONE holder.binding.progress.visibility = View.GONE holder.binding.accomplished.visibility = View.GONE holder.binding.unfinish.visibility = View.GONE holder.binding.unstart.visibility = View.GONE if (position == 0 || objectivesPlugin.allPriorAccomplished(position)) holder.binding.start.visibility = View.VISIBLE else holder.binding.start.visibility = View.GONE } else if (objective.isAccomplished) { holder.binding.gate.setTextColor(rh.gac(context, R.attr.isAccomplishedColor)) holder.binding.verify.visibility = View.GONE holder.binding.progress.visibility = View.GONE holder.binding.start.visibility = View.GONE holder.binding.accomplished.visibility = View.VISIBLE holder.binding.unfinish.visibility = View.VISIBLE holder.binding.unstart.visibility = View.GONE } else if (objective.isStarted) { holder.binding.gate.setTextColor(rh.gac(context,R.attr.defaultTextColor)) holder.binding.verify.visibility = View.VISIBLE holder.binding.verify.isEnabled = objective.isCompleted || binding.fake.isChecked holder.binding.start.visibility = View.GONE holder.binding.accomplished.visibility = View.GONE holder.binding.unfinish.visibility = View.GONE holder.binding.unstart.visibility = View.VISIBLE holder.binding.progress.visibility = View.VISIBLE holder.binding.progress.removeAllViews() for (task in objective.tasks) { if (task.shouldBeIgnored()) continue // name val name = TextView(holder.binding.progress.context) name.text = "${rh.gs(task.task)}:" name.setTextColor(rh.gac(context,R.attr.defaultTextColor) ) holder.binding.progress.addView(name, LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT) // hint task.hints.forEach { h -> if (!task.isCompleted()) context?.let { holder.binding.progress.addView(h.generate(it)) } } // state val state = TextView(holder.binding.progress.context) state.setTextColor(rh.gac(context,R.attr.defaultTextColor)) val basicHTML = "<font color=\"%1\$s\"><b>%2\$s</b></font>" val formattedHTML = String.format(basicHTML, if (task.isCompleted()) rh.gac(context, R.attr.isCompletedColor) else rh.gac(context, R.attr.isNotCompletedColor), task.progress) state.text = HtmlHelper.fromHtml(formattedHTML) state.gravity = Gravity.END holder.binding.progress.addView(state, LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT) if (task is ExamTask) { state.setOnClickListener { val dialog = ObjectivesExamDialog() val bundle = Bundle() val taskPosition = objective.tasks.indexOf(task) bundle.putInt("currentTask", taskPosition) dialog.arguments = bundle ObjectivesExamDialog.objective = objective dialog.show(childFragmentManager, "ObjectivesFragment") } } // horizontal line val separator = View(holder.binding.progress.context) separator.setBackgroundColor(rh.gac(context, R.attr.separatorColor)) holder.binding.progress.addView(separator, LinearLayout.LayoutParams.MATCH_PARENT, 2) } } holder.binding.accomplished.text = rh.gs(R.string.accomplished, dateUtil.dateAndTimeString(objective.accomplishedOn)) holder.binding.accomplished.setTextColor(rh.gac(context,R.attr.defaultTextColor)) holder.binding.verify.setOnClickListener { receiverStatusStore.updateNetworkStatus() if (binding.fake.isChecked) { objective.accomplishedOn = dateUtil.now() scrollToCurrentObjective() startUpdateTimer() rxBus.send(EventObjectivesUpdateGui()) rxBus.send(EventSWUpdate(false)) } else { // move out of UI thread Thread { NtpProgressDialog().show((context as AppCompatActivity).supportFragmentManager, "NtpCheck") rxBus.send(EventNtpStatus(rh.gs(R.string.timedetection), 0)) sntpClient.ntpTime(object : SntpClient.Callback() { override fun run() { aapsLogger.debug("NTP time: $time System time: ${dateUtil.now()}") SystemClock.sleep(300) if (!networkConnected) { rxBus.send(EventNtpStatus(rh.gs(R.string.notconnected), 99)) } else if (success) { if (objective.isCompleted(time)) { objective.accomplishedOn = time rxBus.send(EventNtpStatus(rh.gs(R.string.success), 100)) SystemClock.sleep(1000) rxBus.send(EventObjectivesUpdateGui()) rxBus.send(EventSWUpdate(false)) SystemClock.sleep(100) scrollToCurrentObjective() } else { rxBus.send(EventNtpStatus(rh.gs(R.string.requirementnotmet), 99)) } } else { rxBus.send(EventNtpStatus(rh.gs(R.string.failedretrievetime), 99)) } } }, receiverStatusStore.isConnected) }.start() } } holder.binding.start.setOnClickListener { receiverStatusStore.updateNetworkStatus() if (binding.fake.isChecked) { objective.startedOn = dateUtil.now() scrollToCurrentObjective() startUpdateTimer() rxBus.send(EventObjectivesUpdateGui()) rxBus.send(EventSWUpdate(false)) } else // move out of UI thread Thread { NtpProgressDialog().show((context as AppCompatActivity).supportFragmentManager, "NtpCheck") rxBus.send(EventNtpStatus(rh.gs(R.string.timedetection), 0)) sntpClient.ntpTime(object : SntpClient.Callback() { override fun run() { aapsLogger.debug("NTP time: $time System time: ${dateUtil.now()}") SystemClock.sleep(300) if (!networkConnected) { rxBus.send(EventNtpStatus(rh.gs(R.string.notconnected), 99)) } else if (success) { objective.startedOn = time rxBus.send(EventNtpStatus(rh.gs(R.string.success), 100)) SystemClock.sleep(1000) rxBus.send(EventObjectivesUpdateGui()) rxBus.send(EventSWUpdate(false)) SystemClock.sleep(100) scrollToCurrentObjective() } else { rxBus.send(EventNtpStatus(rh.gs(R.string.failedretrievetime), 99)) } } }, receiverStatusStore.isConnected) }.start() } holder.binding.unstart.setOnClickListener { activity?.let { activity -> OKDialog.showConfirmation(activity, rh.gs(R.string.objectives), rh.gs(R.string.doyouwantresetstart), Runnable { uel.log(Action.OBJECTIVE_UNSTARTED, Sources.Objectives, ValueWithUnit.SimpleInt(position + 1)) objective.startedOn = 0 scrollToCurrentObjective() rxBus.send(EventObjectivesUpdateGui()) rxBus.send(EventSWUpdate(false)) }) } } holder.binding.unfinish.setOnClickListener { objective.accomplishedOn = 0 scrollToCurrentObjective() rxBus.send(EventObjectivesUpdateGui()) rxBus.send(EventSWUpdate(false)) } if (objective.hasSpecialInput && !objective.isAccomplished && objective.isStarted && objective.specialActionEnabled()) { // generate random request code if none exists val request = sp.getString(R.string.key_objectives_request_code, String.format("%1$05d", (Math.random() * 99999).toInt())) sp.putString(R.string.key_objectives_request_code, request) holder.binding.requestcode.text = rh.gs(R.string.requestcode, request) holder.binding.requestcode.visibility = View.VISIBLE holder.binding.enterbutton.visibility = View.VISIBLE holder.binding.input.visibility = View.VISIBLE holder.binding.inputhint.visibility = View.VISIBLE holder.binding.enterbutton.setOnClickListener { val input = holder.binding.input.text.toString() activity?.let { activity -> objective.specialAction(activity, input) } rxBus.send(EventObjectivesUpdateGui()) } } else { holder.binding.enterbutton.visibility = View.GONE holder.binding.input.visibility = View.GONE holder.binding.inputhint.visibility = View.GONE holder.binding.requestcode.visibility = View.GONE } } override fun getItemCount(): Int { return objectivesPlugin.objectives.size } inner class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) { val binding = ObjectivesItemBinding.bind(itemView) } } fun updateGUI() { activity?.runOnUiThread { objectivesAdapter.notifyDataSetChanged() } } }
agpl-3.0
ef47cecd4065e46e095cd0a84f89cc4f
50.653846
194
0.59632
5.364337
false
false
false
false
Heiner1/AndroidAPS
core/src/main/java/info/nightscout/androidaps/services/AlarmSoundService.kt
1
5485
package info.nightscout.androidaps.services import android.content.Context import android.content.Intent import android.media.AudioManager import android.media.MediaPlayer import android.os.Binder import android.os.Handler import android.os.IBinder import android.os.Looper import dagger.android.DaggerService import info.nightscout.androidaps.activities.ErrorHelperActivity import info.nightscout.androidaps.core.R import info.nightscout.androidaps.interfaces.NotificationHolder import info.nightscout.shared.logging.AAPSLogger import info.nightscout.shared.logging.LTag import info.nightscout.androidaps.interfaces.ResourceHelper import info.nightscout.shared.sharedPreferences.SP import javax.inject.Inject import kotlin.math.ln import kotlin.math.pow class AlarmSoundService : DaggerService() { @Inject lateinit var aapsLogger: AAPSLogger @Inject lateinit var rh: ResourceHelper @Inject lateinit var notificationHolder: NotificationHolder @Inject lateinit var sp: SP private var player: MediaPlayer? = null private var resourceId = R.raw.error companion object { private const val VOLUME_INCREASE_STEPS = 40 // Total number of steps to increase volume with private const val VOLUME_INCREASE_INITIAL_SILENT_TIME_MILLIS = 3_000L // Number of milliseconds that the notification should initially be silent private const val VOLUME_INCREASE_BASE_DELAY_MILLIS = 15_000 // Base delay between volume increments private const val VOLUME_INCREASE_MIN_DELAY_MILLIS = 2_000L // Minimum delay between volume increments /* * Delay until the next volume increment will be the lowest value of VOLUME_INCREASE_MIN_DELAY_MILLIS and * VOLUME_INCREASE_BASE_DELAY_MILLIS - (currentVolumeLevel - 1) ^ VOLUME_INCREASE_DELAY_DECREMENT_EXPONENT * 1000 * */ private const val VOLUME_INCREASE_DELAY_DECREMENT_EXPONENT = 2.0 } inner class LocalBinder : Binder() { fun getService(): AlarmSoundService = this@AlarmSoundService } private val binder = LocalBinder() override fun onBind(intent: Intent): IBinder = binder private val increaseVolumeHandler = Handler(Looper.getMainLooper()) private var currentVolumeLevel = 0 override fun onCreate() { super.onCreate() aapsLogger.debug(LTag.CORE, "onCreate parent called") startForeground(notificationHolder.notificationID, notificationHolder.notification) aapsLogger.debug(LTag.CORE, "onCreate End") } override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int { aapsLogger.debug(LTag.CORE, "onStartCommand") startForeground(notificationHolder.notificationID, notificationHolder.notification) aapsLogger.debug(LTag.CORE, "onStartCommand Foreground called") player?.let { if (it.isPlaying) it.stop() } if (intent?.hasExtra(ErrorHelperActivity.SOUND_ID) == true) resourceId = intent.getIntExtra(ErrorHelperActivity.SOUND_ID, R.raw.error) player = MediaPlayer() try { val afd = rh.openRawResourceFd(resourceId) ?: return START_NOT_STICKY player?.setDataSource(afd.fileDescriptor, afd.startOffset, afd.length) afd.close() player?.isLooping = true val audioManager = getAudioManager() if (!audioManager.isMusicActive) { if (sp.getBoolean(R.string.key_gradually_increase_notification_volume, false)) { currentVolumeLevel = 0 player?.setVolume(0f, 0f) increaseVolumeHandler.postDelayed(volumeUpdater, VOLUME_INCREASE_INITIAL_SILENT_TIME_MILLIS) } else { player?.setVolume(1f, 1f) } } player?.prepare() player?.start() } catch (e: Exception) { aapsLogger.error("Unhandled exception", e) } aapsLogger.debug(LTag.CORE, "onStartCommand End") return START_NOT_STICKY } override fun onDestroy() { aapsLogger.debug(LTag.CORE, "onDestroy") increaseVolumeHandler.removeCallbacks(volumeUpdater) player?.stop() player?.release() aapsLogger.debug(LTag.CORE, "onDestroy End") } private fun getAudioManager() = getSystemService(Context.AUDIO_SERVICE) as AudioManager // TODO replace with VolumeShaper when min API level >= 26 private val volumeUpdater = object : Runnable { override fun run() { currentVolumeLevel++ val volumePercentage = 100.0.coerceAtMost(currentVolumeLevel / VOLUME_INCREASE_STEPS.toDouble() * 100) val volume = (1 - (ln(1.0.coerceAtLeast(100.0 - volumePercentage)) / ln(100.0))).toFloat() aapsLogger.debug(LTag.CORE, "Setting notification volume to {} ({} %)", volume, volumePercentage) player?.setVolume(volume, volume) if (currentVolumeLevel < VOLUME_INCREASE_STEPS) { // Increase volume faster as time goes by val delay = VOLUME_INCREASE_MIN_DELAY_MILLIS.coerceAtLeast(VOLUME_INCREASE_BASE_DELAY_MILLIS - ((currentVolumeLevel - 1).toDouble().pow(VOLUME_INCREASE_DELAY_DECREMENT_EXPONENT) * 1000).toLong()) aapsLogger.debug(LTag.CORE, "Next notification volume increment in {}ms", delay) increaseVolumeHandler.postDelayed(this, delay) } } } }
agpl-3.0
39a745bb0400aa7e3a9ec8a5129fd766
40.870229
152
0.684047
4.656197
false
false
false
false
kvakil/venus
src/main/kotlin/venus/riscv/insts/dsl/Instruction.kt
1
1307
package venus.riscv.insts.dsl import venus.assembler.AssemblerError import venus.riscv.MachineCode import venus.riscv.insts.dsl.disasms.InstructionDisassembler import venus.riscv.insts.dsl.formats.InstructionFormat import venus.riscv.insts.dsl.impls.InstructionImplementation import venus.riscv.insts.dsl.parsers.InstructionParser import venus.simulator.SimulatorError open class Instruction( val name: String, val format: InstructionFormat, val parser: InstructionParser, val impl32: InstructionImplementation, val impl64: InstructionImplementation, val disasm: InstructionDisassembler ) { companion object { private val allInstructions = arrayListOf<Instruction>() operator fun get(mcode: MachineCode): Instruction = allInstructions.filter { it.format.length == mcode.length } .firstOrNull { it.format.matches(mcode) } ?: throw SimulatorError("instruction not found for $mcode") operator fun get(name: String) = allInstructions.firstOrNull { it.name == name } ?: throw AssemblerError("instruction with name $name not found") } init { allInstructions.add(this) } override fun toString() = name }
mit
a470bac7572935577196b5596b15d8b4
34.324324
88
0.684009
4.770073
false
false
false
false
Heiner1/AndroidAPS
app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/NSClientPlugin.kt
1
10654
package info.nightscout.androidaps.plugins.general.nsclient import android.content.ComponentName import android.content.Context import android.content.Intent import android.content.ServiceConnection import android.os.Handler import android.os.HandlerThread import android.os.IBinder import androidx.preference.PreferenceFragmentCompat import androidx.preference.PreferenceScreen import androidx.preference.SwitchPreference import dagger.android.HasAndroidInjector import info.nightscout.androidaps.Constants import info.nightscout.androidaps.R import info.nightscout.androidaps.events.EventAppExit import info.nightscout.androidaps.events.EventChargingState import info.nightscout.androidaps.events.EventNetworkChange import info.nightscout.androidaps.events.EventPreferenceChange import info.nightscout.androidaps.interfaces.Config import info.nightscout.androidaps.interfaces.PluginBase import info.nightscout.androidaps.interfaces.PluginDescription import info.nightscout.androidaps.interfaces.PluginType import info.nightscout.androidaps.interfaces.ResourceHelper import info.nightscout.androidaps.plugins.bus.RxBus import info.nightscout.androidaps.plugins.general.nsclient.data.AlarmAck import info.nightscout.androidaps.plugins.general.nsclient.data.NSAlarm import info.nightscout.androidaps.plugins.general.nsclient.events.EventNSClientNewLog import info.nightscout.androidaps.plugins.general.nsclient.events.EventNSClientResend import info.nightscout.androidaps.plugins.general.nsclient.events.EventNSClientStatus import info.nightscout.androidaps.plugins.general.nsclient.events.EventNSClientUpdateGUI import info.nightscout.androidaps.plugins.general.nsclient.services.NSClientService import info.nightscout.androidaps.utils.FabricPrivacy import info.nightscout.androidaps.utils.HtmlHelper.fromHtml import info.nightscout.androidaps.utils.ToastUtils import info.nightscout.androidaps.interfaces.BuildHelper import info.nightscout.androidaps.utils.rx.AapsSchedulers import info.nightscout.shared.logging.AAPSLogger import info.nightscout.shared.logging.LTag import info.nightscout.shared.sharedPreferences.SP import io.reactivex.rxjava3.disposables.CompositeDisposable import io.reactivex.rxjava3.kotlin.plusAssign import javax.inject.Inject import javax.inject.Singleton @Singleton class NSClientPlugin @Inject constructor( injector: HasAndroidInjector, aapsLogger: AAPSLogger, private val aapsSchedulers: AapsSchedulers, private val rxBus: RxBus, rh: ResourceHelper, private val context: Context, private val fabricPrivacy: FabricPrivacy, private val sp: SP, private val nsClientReceiverDelegate: NsClientReceiverDelegate, private val config: Config, private val buildHelper: BuildHelper ) : PluginBase( PluginDescription() .mainType(PluginType.GENERAL) .fragmentClass(NSClientFragment::class.java.name) .pluginIcon(R.drawable.ic_nightscout_syncs) .pluginName(R.string.nsclientinternal) .shortName(R.string.nsclientinternal_shortname) .preferencesId(R.xml.pref_nsclientinternal) .alwaysEnabled(config.NSCLIENT) .visibleByDefault(config.NSCLIENT) .description(R.string.description_ns_client), aapsLogger, rh, injector ) { private val disposable = CompositeDisposable() private val handler = Handler(HandlerThread(this::class.simpleName + "Handler").also { it.start() }.looper) private val listLog: MutableList<EventNSClientNewLog> = ArrayList() var textLog = fromHtml("") var paused = false var autoscroll = false var status = "" var nsClientService: NSClientService? = null val isAllowed: Boolean get() = nsClientReceiverDelegate.allowed val blockingReason: String get() = nsClientReceiverDelegate.blockingReason override fun onStart() { paused = sp.getBoolean(R.string.key_nsclientinternal_paused, false) autoscroll = sp.getBoolean(R.string.key_nsclientinternal_autoscroll, true) context.bindService(Intent(context, NSClientService::class.java), mConnection, Context.BIND_AUTO_CREATE) super.onStart() nsClientReceiverDelegate.grabReceiversState() disposable += rxBus .toObservable(EventNSClientStatus::class.java) .observeOn(aapsSchedulers.io) .subscribe({ event: EventNSClientStatus -> status = event.getStatus(rh) rxBus.send(EventNSClientUpdateGUI()) }, fabricPrivacy::logException) disposable += rxBus .toObservable(EventNetworkChange::class.java) .observeOn(aapsSchedulers.io) .subscribe({ ev -> nsClientReceiverDelegate.onStatusEvent(ev) }, fabricPrivacy::logException) disposable += rxBus .toObservable(EventPreferenceChange::class.java) .observeOn(aapsSchedulers.io) .subscribe({ ev -> nsClientReceiverDelegate.onStatusEvent(ev) }, fabricPrivacy::logException) disposable += rxBus .toObservable(EventAppExit::class.java) .observeOn(aapsSchedulers.io) .subscribe({ if (nsClientService != null) context.unbindService(mConnection) }, fabricPrivacy::logException) disposable += rxBus .toObservable(EventNSClientNewLog::class.java) .observeOn(aapsSchedulers.io) .subscribe({ event: EventNSClientNewLog -> addToLog(event) aapsLogger.debug(LTag.NSCLIENT, event.action + " " + event.logText) }, fabricPrivacy::logException) disposable += rxBus .toObservable(EventChargingState::class.java) .observeOn(aapsSchedulers.io) .subscribe({ ev -> nsClientReceiverDelegate.onStatusEvent(ev) }, fabricPrivacy::logException) disposable += rxBus .toObservable(EventNSClientResend::class.java) .observeOn(aapsSchedulers.io) .subscribe({ event -> resend(event.reason) }, fabricPrivacy::logException) } override fun onStop() { context.applicationContext.unbindService(mConnection) disposable.clear() super.onStop() } override fun preprocessPreferences(preferenceFragment: PreferenceFragmentCompat) { super.preprocessPreferences(preferenceFragment) if (config.NSCLIENT) { preferenceFragment.findPreference<PreferenceScreen>(rh.gs(R.string.ns_sync_options))?.isVisible = false preferenceFragment.findPreference<SwitchPreference>(rh.gs(R.string.key_ns_create_announcements_from_errors))?.isVisible = false preferenceFragment.findPreference<SwitchPreference>(rh.gs(R.string.key_ns_create_announcements_from_carbs_req))?.isVisible = false // preferenceFragment.findPreference<SwitchPreference>(rh.gs(R.string.key_ns_sync_use_absolute))?.isVisible = false } else { // APS or pumpControl mode // preferenceFragment.findPreference<SwitchPreference>(rh.gs(R.string.key_ns_receive_profile_switch))?.isVisible = buildHelper.isEngineeringMode() // preferenceFragment.findPreference<SwitchPreference>(rh.gs(R.string.key_ns_receive_insulin))?.isVisible = buildHelper.isEngineeringMode() // preferenceFragment.findPreference<SwitchPreference>(rh.gs(R.string.key_ns_receive_carbs))?.isVisible = buildHelper.isEngineeringMode() // preferenceFragment.findPreference<SwitchPreference>(rh.gs(R.string.key_ns_receive_temp_target))?.isVisible = buildHelper.isEngineeringMode() } preferenceFragment.findPreference<SwitchPreference>(rh.gs(R.string.key_ns_receive_tbr_eb))?.isVisible = buildHelper.isEngineeringMode() } private val mConnection: ServiceConnection = object : ServiceConnection { override fun onServiceDisconnected(name: ComponentName) { aapsLogger.debug(LTag.NSCLIENT, "Service is disconnected") nsClientService = null } override fun onServiceConnected(name: ComponentName, service: IBinder) { aapsLogger.debug(LTag.NSCLIENT, "Service is connected") val mLocalBinder = service as NSClientService.LocalBinder? nsClientService = mLocalBinder?.serviceInstance // is null when running in roboelectric } } @Synchronized fun clearLog() { handler.post { synchronized(listLog) { listLog.clear() } rxBus.send(EventNSClientUpdateGUI()) } } @Synchronized private fun addToLog(ev: EventNSClientNewLog) { handler.post { synchronized(listLog) { listLog.add(ev) // remove the first line if log is too large if (listLog.size >= Constants.MAX_LOG_LINES) { listLog.removeAt(0) } } rxBus.send(EventNSClientUpdateGUI()) } } @Synchronized fun updateLog() { try { val newTextLog = StringBuilder() synchronized(listLog) { for (log in listLog) { newTextLog.append(log.toPreparedHtml()) } } textLog = fromHtml(newTextLog.toString()) } catch (e: OutOfMemoryError) { ToastUtils.showToastInUiThread(context, rxBus, "Out of memory!\nStop using this phone !!!", R.raw.error) } } fun resend(reason: String) { nsClientService?.resend(reason) } fun pause(newState: Boolean) { sp.putBoolean(R.string.key_nsclientinternal_paused, newState) paused = newState rxBus.send(EventPreferenceChange(rh, R.string.key_nsclientinternal_paused)) } fun url(): String = nsClientService?.nsURL ?: "" fun hasWritePermission(): Boolean = nsClientService?.hasWriteAuth ?: false fun handleClearAlarm(originalAlarm: NSAlarm, silenceTimeInMilliseconds: Long) { if (!isEnabled(PluginType.GENERAL)) return if (!sp.getBoolean(R.string.key_ns_upload, true)) { aapsLogger.debug(LTag.NSCLIENT, "Upload disabled. Message dropped") return } nsClientService?.sendAlarmAck( AlarmAck().also { ack -> ack.level = originalAlarm.level() ack.group = originalAlarm.group() ack.silenceTime = silenceTimeInMilliseconds }) } fun updateLatestDateReceivedIfNewer(latestReceived: Long) { nsClientService?.let { if (latestReceived > it.latestDateInReceivedData) it.latestDateInReceivedData = latestReceived } } }
agpl-3.0
e9e5219ab82fbad01e7aa38004536707
45.528384
157
0.705181
4.724612
false
false
false
false
bajdcc/jMiniLang
src/main/kotlin/com/bajdcc/util/lexer/algorithm/TokenAlgorithmCollection.kt
1
2245
package com.bajdcc.util.lexer.algorithm import com.bajdcc.util.lexer.error.IErrorHandler import com.bajdcc.util.lexer.regex.IRegexStringFilterHost import com.bajdcc.util.lexer.regex.IRegexStringIterator import com.bajdcc.util.lexer.token.Token import com.bajdcc.util.lexer.token.TokenType /** * 用于抽取单词的算法集合(包含数字、字符串等) * [iterator] 字符串迭代器 * [filterHost] 字符转换主体 * @author bajdcc */ class TokenAlgorithmCollection(var iterator: IRegexStringIterator, var filterHost: IRegexStringFilterHost?) : Cloneable { /** * 算法集合 */ private val arrAlgorithms = mutableListOf<ITokenAlgorithm>() /** * 错误处理 */ private var handler: IErrorHandler = TokenErrorAdvanceHandler(iterator) /** * 添加解析组件 * * @param alg 解析组件 */ fun attach(alg: ITokenAlgorithm) { arrAlgorithms.add(alg) } /** * 删除解析组件 * * @param alg 解析组件 */ fun detach(alg: ITokenAlgorithm) { arrAlgorithms.remove(alg) } /** * 清空解析组件 */ fun clear() { arrAlgorithms.clear() } fun scan(): Token { val token = Token() token.type = TokenType.ERROR if (!iterator.available()) { token.type = TokenType.EOF } else { for (alg in arrAlgorithms) { filterHost!!.setFilter(alg) iterator.translate() if (alg.accept(iterator, token)) return token } handler.handleError() } return token } /** * 拷贝构造 * * @param iter 迭代器 * @param filter 过滤器 * @return 拷贝 * @throws CloneNotSupportedException 不支持拷贝 */ @Throws(CloneNotSupportedException::class) fun copy(iter: IRegexStringIterator, filter: IRegexStringFilterHost): TokenAlgorithmCollection { val o = super.clone() as TokenAlgorithmCollection o.iterator = iter o.filterHost = filter o.handler = TokenErrorAdvanceHandler(iter) return o } }
mit
8c1856b0a6ea5774011ab2dda45d0550
23.127907
85
0.588434
3.990385
false
false
false
false