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
HabitRPG/habitrpg-android
Habitica/src/main/java/com/habitrpg/android/habitica/api/Server.kt
1
737
package com.habitrpg.android.habitica.api class Server { private var addr: String constructor(addr: String) : this(addr, true) {} private constructor(addr: String, attachSuffix: Boolean) { if (attachSuffix) { if (addr.endsWith("/api/v4") || addr.endsWith("/api/v4/")) { this.addr = addr } else if (addr.endsWith("/")) { this.addr = addr + "api/v4/" } else { this.addr = "$addr/api/v4/" } } else { this.addr = addr } } constructor(server: Server) { addr = server.toString() } override fun toString(): String { return addr } }
gpl-3.0
cbe9bb27f66bffabf4bee8feaca11580
24.321429
72
0.484396
4.211429
false
false
false
false
HabitRPG/habitrpg-android
Habitica/src/main/java/com/habitrpg/android/habitica/models/Achievement.kt
2
470
package com.habitrpg.android.habitica.models import io.realm.RealmObject import io.realm.annotations.PrimaryKey open class Achievement : RealmObject(), BaseObject { @PrimaryKey var key: String? = null var type: String? = null var title: String? = null var text: String? = null var icon: String? = null var category: String? = null var earned: Boolean = false var index: Int = 0 var optionalCount: Int? = null }
gpl-3.0
833c43abef82e41b04b2f9b8403b0a22
25.647059
52
0.659574
4.017094
false
false
false
false
SimpleMobileTools/Simple-Commons
commons/src/main/kotlin/com/simplemobiletools/commons/views/MyRecyclerView.kt
1
12517
package com.simplemobiletools.commons.views import android.content.Context import android.os.Handler import android.util.AttributeSet import android.view.MotionEvent import android.view.ScaleGestureDetector import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import com.simplemobiletools.commons.R import com.simplemobiletools.commons.interfaces.RecyclerScrollCallback // drag selection is based on https://github.com/afollestad/drag-select-recyclerview open class MyRecyclerView : RecyclerView { private val AUTO_SCROLL_DELAY = 25L private var isZoomEnabled = false private var isDragSelectionEnabled = false private var zoomListener: MyZoomListener? = null private var dragListener: MyDragListener? = null private var autoScrollHandler = Handler() private var scaleDetector: ScaleGestureDetector private var dragSelectActive = false private var lastDraggedIndex = -1 private var minReached = 0 private var maxReached = 0 private var initialSelection = 0 private var hotspotHeight = 0 private var hotspotOffsetTop = 0 private var hotspotOffsetBottom = 0 private var hotspotTopBoundStart = 0 private var hotspotTopBoundEnd = 0 private var hotspotBottomBoundStart = 0 private var hotspotBottomBoundEnd = 0 private var autoScrollVelocity = 0 private var inTopHotspot = false private var inBottomHotspot = false private var currScaleFactor = 1.0f private var lastUp = 0L // allow only pinch zoom, not double tap // things related to parallax scrolling (for now only in the music player) // cut from https://github.com/ksoichiro/Android-ObservableScrollView var recyclerScrollCallback: RecyclerScrollCallback? = null private var mPrevFirstVisiblePosition = 0 private var mPrevScrolledChildrenHeight = 0 private var mPrevFirstVisibleChildHeight = -1 private var mScrollY = 0 // variables used for fetching additional items at scrolling to the bottom/top var endlessScrollListener: EndlessScrollListener? = null private var totalItemCount = 0 private var lastMaxItemIndex = 0 private var linearLayoutManager: LinearLayoutManager? = null constructor(context: Context) : super(context) constructor(context: Context, attrs: AttributeSet) : super(context, attrs) init { hotspotHeight = context.resources.getDimensionPixelSize(R.dimen.dragselect_hotspot_height) if (layoutManager is LinearLayoutManager) { linearLayoutManager = layoutManager as LinearLayoutManager } val gestureListener = object : MyGestureListener { override fun getLastUp() = lastUp override fun getScaleFactor() = currScaleFactor override fun setScaleFactor(value: Float) { currScaleFactor = value } override fun getZoomListener() = zoomListener } scaleDetector = ScaleGestureDetector(context, GestureListener(gestureListener)) } override fun onMeasure(widthSpec: Int, heightSpec: Int) { super.onMeasure(widthSpec, heightSpec) if (hotspotHeight > -1) { hotspotTopBoundStart = hotspotOffsetTop hotspotTopBoundEnd = hotspotOffsetTop + hotspotHeight hotspotBottomBoundStart = measuredHeight - hotspotHeight - hotspotOffsetBottom hotspotBottomBoundEnd = measuredHeight - hotspotOffsetBottom } } private val autoScrollRunnable = object : Runnable { override fun run() { if (inTopHotspot) { scrollBy(0, -autoScrollVelocity) autoScrollHandler.postDelayed(this, AUTO_SCROLL_DELAY) } else if (inBottomHotspot) { scrollBy(0, autoScrollVelocity) autoScrollHandler.postDelayed(this, AUTO_SCROLL_DELAY) } } } fun resetItemCount() { totalItemCount = 0 } override fun dispatchTouchEvent(ev: MotionEvent): Boolean { if (!dragSelectActive) { try { super.dispatchTouchEvent(ev) } catch (ignored: Exception) { } } when (ev.action) { MotionEvent.ACTION_UP, MotionEvent.ACTION_CANCEL -> { dragSelectActive = false inTopHotspot = false inBottomHotspot = false autoScrollHandler.removeCallbacks(autoScrollRunnable) currScaleFactor = 1.0f lastUp = System.currentTimeMillis() return true } MotionEvent.ACTION_MOVE -> { if (dragSelectActive) { val itemPosition = getItemPosition(ev) if (hotspotHeight > -1) { if (ev.y in hotspotTopBoundStart.toFloat()..hotspotTopBoundEnd.toFloat()) { inBottomHotspot = false if (!inTopHotspot) { inTopHotspot = true autoScrollHandler.removeCallbacks(autoScrollRunnable) autoScrollHandler.postDelayed(autoScrollRunnable, AUTO_SCROLL_DELAY) } val simulatedFactor = (hotspotTopBoundEnd - hotspotTopBoundStart).toFloat() val simulatedY = ev.y - hotspotTopBoundStart autoScrollVelocity = (simulatedFactor - simulatedY).toInt() / 2 } else if (ev.y in hotspotBottomBoundStart.toFloat()..hotspotBottomBoundEnd.toFloat()) { inTopHotspot = false if (!inBottomHotspot) { inBottomHotspot = true autoScrollHandler.removeCallbacks(autoScrollRunnable) autoScrollHandler.postDelayed(autoScrollRunnable, AUTO_SCROLL_DELAY) } val simulatedY = ev.y + hotspotBottomBoundEnd val simulatedFactor = (hotspotBottomBoundStart + hotspotBottomBoundEnd).toFloat() autoScrollVelocity = (simulatedY - simulatedFactor).toInt() / 2 } else if (inTopHotspot || inBottomHotspot) { autoScrollHandler.removeCallbacks(autoScrollRunnable) inTopHotspot = false inBottomHotspot = false } } if (itemPosition != RecyclerView.NO_POSITION && lastDraggedIndex != itemPosition) { lastDraggedIndex = itemPosition if (minReached == -1) { minReached = lastDraggedIndex } if (maxReached == -1) { maxReached = lastDraggedIndex } if (lastDraggedIndex > maxReached) { maxReached = lastDraggedIndex } if (lastDraggedIndex < minReached) { minReached = lastDraggedIndex } dragListener?.selectRange(initialSelection, lastDraggedIndex, minReached, maxReached) if (initialSelection == lastDraggedIndex) { minReached = lastDraggedIndex maxReached = lastDraggedIndex } } return true } } } return if (isZoomEnabled) { scaleDetector.onTouchEvent(ev) } else { true } } fun setupDragListener(dragListener: MyDragListener?) { isDragSelectionEnabled = dragListener != null this.dragListener = dragListener } fun setupZoomListener(zoomListener: MyZoomListener?) { isZoomEnabled = zoomListener != null this.zoomListener = zoomListener } fun setDragSelectActive(initialSelection: Int) { if (dragSelectActive || !isDragSelectionEnabled) return lastDraggedIndex = -1 minReached = -1 maxReached = -1 this.initialSelection = initialSelection dragSelectActive = true dragListener?.selectItem(initialSelection) } private fun getItemPosition(e: MotionEvent): Int { val v = findChildViewUnder(e.x, e.y) ?: return RecyclerView.NO_POSITION if (v.tag == null || v.tag !is RecyclerView.ViewHolder) { throw IllegalStateException("Make sure your adapter makes a call to super.onBindViewHolder(), and doesn't override itemView tags.") } val holder = v.tag as RecyclerView.ViewHolder return holder.adapterPosition } override fun onScrollStateChanged(state: Int) { super.onScrollStateChanged(state) if (endlessScrollListener != null) { if (totalItemCount == 0) { totalItemCount = adapter!!.itemCount } if (state == SCROLL_STATE_IDLE) { val lastVisiblePosition = linearLayoutManager?.findLastVisibleItemPosition() ?: 0 if (lastVisiblePosition != lastMaxItemIndex && lastVisiblePosition == totalItemCount - 1) { lastMaxItemIndex = lastVisiblePosition endlessScrollListener!!.updateBottom() } val firstVisiblePosition = linearLayoutManager?.findFirstVisibleItemPosition() ?: -1 if (firstVisiblePosition == 0) { endlessScrollListener!!.updateTop() } } } } override fun onScrollChanged(l: Int, t: Int, oldl: Int, oldt: Int) { super.onScrollChanged(l, t, oldl, oldt) if (recyclerScrollCallback != null) { if (childCount > 0) { val firstVisiblePosition = getChildAdapterPosition(getChildAt(0)) val firstVisibleChild = getChildAt(0) if (firstVisibleChild != null) { if (mPrevFirstVisiblePosition < firstVisiblePosition) { mPrevScrolledChildrenHeight += mPrevFirstVisibleChildHeight } if (firstVisiblePosition == 0) { mPrevFirstVisibleChildHeight = firstVisibleChild.height mPrevScrolledChildrenHeight = 0 } if (mPrevFirstVisibleChildHeight < 0) { mPrevFirstVisibleChildHeight = 0 } mScrollY = mPrevScrolledChildrenHeight - firstVisibleChild.top recyclerScrollCallback?.onScrolled(mScrollY) } } } } class GestureListener(val gestureListener: MyGestureListener) : ScaleGestureDetector.SimpleOnScaleGestureListener() { private val ZOOM_IN_THRESHOLD = -0.4f private val ZOOM_OUT_THRESHOLD = 0.15f override fun onScale(detector: ScaleGestureDetector): Boolean { gestureListener.apply { if (System.currentTimeMillis() - getLastUp() < 1000) return false val diff = getScaleFactor() - detector.scaleFactor if (diff < ZOOM_IN_THRESHOLD && getScaleFactor() == 1.0f) { getZoomListener()?.zoomIn() setScaleFactor(detector.scaleFactor) } else if (diff > ZOOM_OUT_THRESHOLD && getScaleFactor() == 1.0f) { getZoomListener()?.zoomOut() setScaleFactor(detector.scaleFactor) } } return false } } interface MyZoomListener { fun zoomOut() fun zoomIn() } interface MyDragListener { fun selectItem(position: Int) fun selectRange(initialSelection: Int, lastDraggedIndex: Int, minReached: Int, maxReached: Int) } interface MyGestureListener { fun getLastUp(): Long fun getScaleFactor(): Float fun setScaleFactor(value: Float) fun getZoomListener(): MyZoomListener? } interface EndlessScrollListener { fun updateTop() fun updateBottom() } }
gpl-3.0
2b1dbc951c82ad39bf4edbaef8456dcc
36.588589
143
0.586962
5.56064
false
false
false
false
androidx/androidx
buildSrc/private/src/main/kotlin/androidx/build/ProjectExt.kt
3
2252
/** * Copyright 2018 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.build import org.gradle.api.Project import org.gradle.api.Task import org.gradle.api.tasks.TaskProvider import java.util.Collections import java.util.concurrent.locks.ReentrantLock import kotlin.concurrent.withLock /** * Holder class used for lazily registering tasks using the new Lazy task execution API. */ data class LazyTaskRegistry( private val names: MutableSet<String> = Collections.synchronizedSet(mutableSetOf()) ) { fun <T : Any?> once(name: String, f: () -> T): T? { if (names.add(name)) { return f() } return null } companion object { private const val KEY = "AndroidXAutoRegisteredTasks" private val lock = ReentrantLock() fun get(project: Project): LazyTaskRegistry { val existing = project.extensions.findByName(KEY) as? LazyTaskRegistry if (existing != null) { return existing } return lock.withLock { project.extensions.findByName(KEY) as? LazyTaskRegistry ?: LazyTaskRegistry().also { project.extensions.add(KEY, it) } } } } } inline fun <reified T : Task> Project.maybeRegister( name: String, crossinline onConfigure: (T) -> Unit, crossinline onRegister: (TaskProvider<T>) -> Unit ): TaskProvider<T> { @Suppress("UNCHECKED_CAST") return LazyTaskRegistry.get(project).once(name) { tasks.register(name, T::class.java) { onConfigure(it) }.also(onRegister) } ?: tasks.named(name) as TaskProvider<T> }
apache-2.0
1073d0d955a4bbc12d2ac552bfa7773e
32.626866
88
0.652309
4.322457
false
false
false
false
jean79/yested
src/main/docsite/demo/chartjs/chartjs_bar.kt
2
2204
package demo.chartjs import net.yested.Div import net.yested.div import net.yested.Chart import net.yested.BarChartData import net.yested.BarChartSeries import net.yested.randomColor import net.yested.toHTMLColor fun createChartJSBarSection(): Div { val chart = Chart(width = 300, height = 250) val temperatureCZE = arrayOf(-2.81, -1.06, 2.80, 7.49, 12.30, 15.41, 17.11, 16.90, 13.49, 8.59, 2.82, -1.06) val temperatureSVK = arrayOf(-2.03, 0.85, 5.44, 10.72, 15.49, 18.52, 20.11, 19.70, 16.13, 10.81, 4.89, 0.11) val colorCZE = randomColor(1.0) val colorSVK = randomColor(1.0) val chartData = BarChartData( labels = arrayOf("Jan", "Feb", "Mar", "Apr", "May", "Jun", "July", "Aug", "Sept", "Oct", "Nov", "Dec"), datasets = arrayOf( BarChartSeries( label = "Czech Re", strokeColor = colorCZE.copy(alpha = 0.8).toHTMLColor(), fillColor = colorCZE.copy(alpha = 0.5).toHTMLColor(), highlightStroke = colorCZE.copy(alpha = 1.0).toHTMLColor(), highlightFill = colorCZE.copy(alpha = 0.75).toHTMLColor(), data = temperatureCZE), BarChartSeries( label = "Slovakia", strokeColor = colorSVK.copy(alpha = 0.8).toHTMLColor(), fillColor = colorSVK.copy(alpha = 0.5).toHTMLColor(), highlightStroke = colorSVK.copy(alpha = 1.0).toHTMLColor(), highlightFill = colorSVK.copy(alpha = 0.75).toHTMLColor(), data = temperatureSVK))) val options = object { val responsive = true } chart.drawBarChart(chartData, options) return div { h4 { +"Bar Chart" } +chart a(href = "https://github.com/jean79/yested/blob/master/src/main/docsite/demo/chartjs/chartjs_bar.kt", target = "_blank") { +"Source code"} } }
mit
3d6078270918c0d69f9922135fa8d5d4
41.403846
146
0.511343
3.833043
false
false
false
false
EventFahrplan/EventFahrplan
app/src/main/java/nerd/tuxmobil/fahrplan/congress/models/DateInfos.kt
1
1470
package nerd.tuxmobil.fahrplan.congress.models import info.metadude.android.eventfahrplan.commons.temporal.Moment import java.util.ArrayList class DateInfos : ArrayList<DateInfo>() { fun sameDay(timestamp: Moment, sessionListDay: Int): Boolean { val currentDate = timestamp.startOfDay() return any { (dayIndex, date) -> dayIndex == sessionListDay && date == currentDate } } /** * Returns the index of today if found, [DateInfo.DAY_INDEX_NOT_FOUND] otherwise. */ val indexOfToday: Int get() { if (isEmpty()) { return DateInfo.DAY_INDEX_NOT_FOUND } val today = Moment.now() .minusHours(DAY_CHANGE_HOUR_DEFAULT.toLong()) .minusMinutes(DAY_CHANGE_MINUTE_DEFAULT.toLong()) .startOfDay() forEach { dateInfo -> val dayIndex = dateInfo.getDayIndex(today) if (dayIndex != DateInfo.DAY_INDEX_NOT_FOUND) { return dayIndex } } return DateInfo.DAY_INDEX_NOT_FOUND } private companion object { const val serialVersionUID = 1L /** * Hour of day change (all sessions which start before count to the previous day). */ const val DAY_CHANGE_HOUR_DEFAULT = 4 /** * Minute of day change. */ const val DAY_CHANGE_MINUTE_DEFAULT = 0 } }
apache-2.0
27530af1193edd19119d19b49f1d1bfe
27.843137
92
0.568027
4.666667
false
false
false
false
bjzhou/Coolapk
app/src/main/kotlin/bjzhou/coolapk/app/util/Utils.kt
1
2503
/* * Copyright (C) 2012 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 bjzhou.coolapk.app.util import android.content.Context import android.content.Intent import android.net.ConnectivityManager import android.net.Uri import android.os.Build import android.preference.PreferenceManager import android.text.Html import bjzhou.coolapk.app.App import java.util.* /** * Class containing some static utility methods. */ object Utils { val userAgent: String get() { val stringBuilder = StringBuilder() val str = System.getProperty("http.agent") stringBuilder.append(str).append(" (#Build; ").append(Build.BRAND).append("; ").append(Build.MODEL).append("; ").append(Build.DISPLAY).append("; ").append(Build.VERSION.RELEASE).append(")") stringBuilder.append(" +CoolMarket/7.3") return Html.escapeHtml(stringBuilder.toString()) } val localeString: String get() { val locale = Locale.getDefault() return locale.language + "-" + locale.country } val uuid: String get() { val sp = PreferenceManager.getDefaultSharedPreferences(App.context) if (sp.contains("uuid")) { return sp.getString("uuid", "") } val uuid = UUID.randomUUID().toString() sp.edit().putString("uuid", uuid).apply() return uuid } val networkConnected: Boolean get() { val cm = App.context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager return cm.activeNetworkInfo != null && cm.activeNetworkInfo.isConnectedOrConnecting } fun installApk(uri: Uri) { val intent = Intent(Intent.ACTION_VIEW) intent.setDataAndType(uri, "application/vnd.android.package-archive") intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK App.context.startActivity(intent) } }
gpl-2.0
23262afc3230fe240c880a9bb499b299
33.763889
201
0.662805
4.526221
false
false
false
false
handstandsam/ShoppingApp
multiplatform/src/jsMain/kotlin/com/handstandsam/shoppingapp/multiplatform/ui/Composables.kt
1
2434
package com.handstandsam.shoppingapp.multiplatform.ui import androidx.compose.runtime.Composable import org.jetbrains.compose.web.css.CSSColorValue import org.jetbrains.compose.web.css.Color import org.jetbrains.compose.web.css.backgroundColor import org.jetbrains.compose.web.css.whiteSpace import org.jetbrains.compose.web.dom.Button import org.jetbrains.compose.web.dom.Div import org.jetbrains.compose.web.dom.H3 import org.jetbrains.compose.web.dom.H6 import org.jetbrains.compose.web.dom.Img import org.jetbrains.compose.web.dom.Pre import org.jetbrains.compose.web.dom.Text @Composable fun WrappedPreformattedText(str: String) { Pre( { style { whiteSpace("pre-wrap") } } ) { Text(str) } } @Composable fun ImageAndTextRow(label: String, imageUrl: String, onClick: () -> Unit = {}) { Div({ onClick { onClick() } classes("list-group-item", "list-group-item-action") }) { Div(attrs = { classes("row") }) { Div(attrs = { classes("col") }) { Img( attrs = { classes("flex-shrink-0") }, src = imageUrl ) } Div(attrs = { classes("col") }) { H3 { Text(label) } } } } } @Composable fun PrimaryButton(label: String, onClick: () -> Unit = {}) { ShoppingAppButton(label, ButtonType.PRIMARY, onClick) } enum class ButtonType(val cssClass: String) { PRIMARY("btn-primary"), GREEN("btn-success"), RED("btn-danger") } @Composable fun ShoppingAppButton(label: String, buttonType: ButtonType, onClick: () -> Unit = {}) { Button( attrs = { classes("btn", buttonType.cssClass) style { when(buttonType){ ButtonType.PRIMARY ->{} ButtonType.GREEN -> backgroundColor(Color.green) ButtonType.RED -> backgroundColor(Color.red) } } onClick { onClick() } } ) { Text(label) } } @Composable fun ShoppingAppList(content: (@Composable () -> Unit)) { Div(attrs = { classes("list-group") }) { content() } }
apache-2.0
3052181351aa8f700100230001a63ed5
25.182796
88
0.530813
4.307965
false
false
false
false
tasomaniac/OpenLinkWith
app/src/main/java/com/tasomaniac/openwith/resolver/DefaultResolverPresenter.kt
1
4607
package com.tasomaniac.openwith.resolver import android.content.Intent import android.content.res.Resources import android.net.Uri import com.tasomaniac.openwith.R import com.tasomaniac.openwith.data.PreferredApp import timber.log.Timber import javax.inject.Inject internal class DefaultResolverPresenter @Inject constructor( private val resources: Resources, private val sourceIntent: Intent, private val callerPackage: CallerPackage, private val useCase: ResolverUseCase, private val viewState: ViewState ) : ResolverPresenter { override fun bind(view: ResolverView, navigation: ResolverView.Navigation) { view.setListener(ViewListener(view, navigation)) useCase.bind(UseCaseListener(view, navigation)) } override fun unbind(view: ResolverView) { view.setListener(null) useCase.unbind() } override fun release() { useCase.release() } private inner class UseCaseListener( private val view: ResolverView, private val navigation: ResolverView.Navigation ) : ResolverUseCase.Listener { @Suppress("TooGenericExceptionCaught") override fun onPreferredResolved( uri: Uri, preferredApp: PreferredApp, displayActivityInfo: DisplayActivityInfo ) { if (preferredApp.preferred.not()) return if (displayActivityInfo.packageName().isCaller()) return try { val preferredIntent = Intent(Intent.ACTION_VIEW, uri) .setComponent(preferredApp.componentName) navigation.startPreferred(preferredIntent, displayActivityInfo.displayLabel) view.dismiss() } catch (e: Exception) { Timber.e(e, "Security Exception for the url: %s", uri) useCase.deleteFailedHost(uri) } } private fun String.isCaller() = this == callerPackage.callerPackage override fun onIntentResolved(result: IntentResolverResult) { viewState.filteredItem = result.filteredItem val handled = handleQuick(result) if (handled) { navigation.dismiss() } else { view.displayData(result) view.setTitle(titleForAction(result.filteredItem)) view.setupActionButtons() } } @Suppress("TooGenericExceptionCaught") private fun handleQuick(result: IntentResolverResult) = when { result.isEmpty -> { Timber.e("No app is found to handle url: %s", sourceIntent.dataString) view.toast(R.string.empty_resolver_activity) true } result.totalCount() == 1 -> { val activityInfo = result.filteredItem ?: result.resolved[0] try { navigation.startPreferred(activityInfo.intentFrom(sourceIntent), activityInfo.displayLabel) true } catch (e: Exception) { Timber.e(e) false } } else -> false } private fun titleForAction(filteredItem: DisplayActivityInfo?): String { return if (filteredItem != null) { resources.getString(R.string.which_view_application_named, filteredItem.displayLabel) } else { resources.getString(R.string.which_view_application) } } } private inner class ViewListener( private val view: ResolverView, private val navigation: ResolverView.Navigation ) : ResolverView.Listener { override fun onActionButtonClick(always: Boolean) { startAndPersist(viewState.checkedItem(), always) navigation.dismiss() } override fun onItemClick(activityInfo: DisplayActivityInfo) { if (viewState.shouldUseAlwaysOption() && activityInfo != viewState.lastSelected) { view.enableActionButtons() viewState.lastSelected = activityInfo } else { startAndPersist(activityInfo, alwaysCheck = false) } } private fun startAndPersist(activityInfo: DisplayActivityInfo, alwaysCheck: Boolean) { val intent = activityInfo.intentFrom(sourceIntent) navigation.startSelected(intent) useCase.persistSelectedIntent(intent, alwaysCheck) } override fun onPackagesChanged() { useCase.resolve() } } }
apache-2.0
c5b9ed0ff8a4d1b1d4a6ac00b5749c16
34.167939
111
0.611895
5.211538
false
false
false
false
anlun/haskell-idea-plugin
plugin/src/org/jetbrains/grammar/bigTest/Main.kt
1
5084
package org.jetbrains.grammar.bigTest import java.io.File import java.io.FilenameFilter import org.jetbrains.grammar.parseFile import org.apache.commons.httpclient.methods.GetMethod import org.apache.commons.httpclient.HttpClient import org.apache.commons.httpclient.params.HttpMethodParams import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler import org.apache.commons.httpclient.HttpStatus import java.io.IOException import org.apache.commons.httpclient.HttpException import org.jetbrains.haskell.util.readLines import java.util.ArrayList import java.util.TreeMap import java.io.BufferedInputStream import java.io.FileInputStream import org.apache.commons.compress.compressors.gzip.GzipCompressorInputStream import org.apache.commons.compress.archivers.tar.TarArchiveInputStream import java.io.InputStream import java.io.ByteArrayOutputStream import com.sun.xml.internal.messaging.saaj.util.ByteInputStream import org.jetbrains.haskell.parser.lexer.HaskellLexer import org.jetbrains.haskell.parser.getCachedTokens import org.jetbrains.grammar.HaskellParser import org.jetbrains.grammar.dumb.LazyLLParser import java.io.FileWriter import java.io.FileOutputStream /** * Created by atsky on 12/12/14. */ fun main(args : Array<String>) { val map = TreeMap<String, MutableList<String>>() for (line in readLines(File("/home/atsky/.cabal/packages/hackage.haskell.org/00-index.cache"))) { val strings = line.split(' ') if (strings[0] == "pkg:") { val key = strings[1] val value = strings[2] map.getOrPut(key) { ArrayList<String>() }.add(value) } } for ((pkg, versions) in map) { versions.sort() val name = pkg + "-" + versions.lastOrNull() println(name) val tmp = File("hackage-cache") tmp.mkdirs() val file = File(tmp, name + ".tar.gz") if (!file.exists()) { val url = "http://hackage.haskell.org/package/${name}/${name}.tar.gz" println(url) val byteArray = fetchUrl(url) val stream = FileOutputStream(file) stream.write(byteArray) stream.close() } val byteArray = file.readBytes() val result = listHaskellFiles(name, ByteInputStream(byteArray, byteArray.size())) if (!result) { break } } } fun listHaskellFiles(packageName : String, stream : InputStream) : Boolean { val bin = BufferedInputStream(stream) val gzIn = GzipCompressorInputStream(bin); val tarArchiveInputStream = TarArchiveInputStream(gzIn) while (true) { val entry = tarArchiveInputStream.getNextTarEntry(); if (entry == null) { break } val name = entry.getName() if (name.endsWith(".hs")) { val content = readToArray(tarArchiveInputStream) if (!testFile(packageName, name, content)) { return false; } } } bin.close() return true } fun testFile(packageName: kotlin.String, name: kotlin.String?, content: kotlin.ByteArray) : Boolean { val lexer = HaskellLexer() lexer.start(String(content)) val cachedTokens = getCachedTokens(lexer, null) val grammar = HaskellParser(null).getGrammar() HaskellParser(null).findFirst(grammar) try { val parser = LazyLLParser(grammar, cachedTokens) val tree = parser.parse() if (tree == null) { println(packageName + " - " + name) println(String(content)) return false; } } catch (e : Exception) { println(packageName + " - " + name + " - exception") println(String(content)) return false; } return true; } fun readToArray(ins: InputStream): ByteArray { val buffer = ByteArrayOutputStream() var nRead: Int val data = ByteArray(16384) while (true) { nRead = ins.read(data, 0, data.size()) if (nRead == -1) { break; } buffer.write(data, 0, nRead); } buffer.flush(); return buffer.toByteArray(); } fun fetchUrl(url : String): ByteArray? { val client = HttpClient(); val method = GetMethod(url); // Provide custom retry handler is necessary method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, DefaultHttpMethodRetryHandler(3, false)); try { val statusCode = client.executeMethod(method); if (statusCode != HttpStatus.SC_OK) { System.err.println("Method failed: " + method.getStatusLine()); } // Read the response body. return method.getResponseBody() } catch (e : HttpException) { System.err.println("Fatal protocol violation: " + e.getMessage()); e.printStackTrace(); } catch (e : IOException) { System.err.println("Fatal transport error: " + e.getMessage()); e.printStackTrace(); } finally { // Release the connection. method.releaseConnection(); } return null }
apache-2.0
c0ab9d6f37526853a8376f7773acb62a
28.563953
101
0.642408
4.254393
false
false
false
false
bazelbuild/rules_kotlin
src/main/kotlin/io/bazel/kotlin/builder/toolchain/CompilationTaskContext.kt
1
5609
/* * Copyright 2018 The Bazel Authors. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package io.bazel.kotlin.builder.toolchain import com.google.protobuf.MessageOrBuilder import com.google.protobuf.TextFormat import io.bazel.kotlin.model.CompilationTaskInfo import java.io.ByteArrayInputStream import java.io.ByteArrayOutputStream import java.io.File import java.io.PrintStream import java.nio.file.FileSystems class CompilationTaskContext( val info: CompilationTaskInfo, private val out: PrintStream, private val executionRoot: String = FileSystems.getDefault().getPath("").toAbsolutePath() .toString() + File.separator, ) { private val start = System.currentTimeMillis() private var timings: MutableList<String>? private var level = -1 private val isTracing: Boolean init { val debugging = info.debugList.toSet() timings = if (debugging.contains("timings")) mutableListOf() else null isTracing = debugging.contains("trace") } fun reportUnhandledException(throwable: Throwable) { throwable.printStackTrace(out) } @Suppress("unused") fun print(msg: String) { out.println(msg) } /** * Print a list of debugging lines. * * @param header a header string * @param lines a list of lines to print out * @param prefix a prefix to add to each line * @param filterEmpty if empty lines should be discarded or not */ fun printLines( header: String, lines: List<String>, prefix: String = "| ", filterEmpty: Boolean = false, ) { check(header.isNotEmpty()) out.println(if (header.endsWith(":")) header else "$header:") lines.forEach { if (it.isNotEmpty() || !filterEmpty) { out.println("$prefix$it") } } out.println() } fun <T> whenTracing(block: CompilationTaskContext.() -> T): T? { return if (isTracing) { block() } else { null } } /** * Print a proto message if debugging is enabled for the task. */ fun printProto(header: String, msg: MessageOrBuilder) { printLines(header, TextFormat.printToString(msg).split("\n"), filterEmpty = true) } /** * This method normalizes and reports the output from the Kotlin compiler. */ fun printCompilerOutput(lines: List<String>) { lines.map(::trimExecutionRootPrefix).forEach(out::println) } private fun trimExecutionRootPrefix(toPrint: String): String { // trim off the workspace component return if (toPrint.startsWith(executionRoot)) { toPrint.replaceFirst(executionRoot, "") } else { toPrint } } /** * Execute a compilation task. * * @throws CompilationStatusException if the compiler returns a status of anything but zero. * @param args the compiler command line switches * @param printOnFail if this is true the output will be printed if the task fails else the caller is responsible * for logging it by catching the [CompilationStatusException] exception. * @param compile the compilation method. */ fun executeCompilerTask( args: List<String>, compile: (Array<String>, PrintStream) -> Int, printOnFail: Boolean = true, printOnSuccess: Boolean = true, ): List<String> { val outputStream = ByteArrayOutputStream() val ps = PrintStream(outputStream) val result = compile(args.toTypedArray(), ps) val output = ByteArrayInputStream(outputStream.toByteArray()) .bufferedReader() .readLines() if (result != 0) { if (printOnFail) { printCompilerOutput(output) throw CompilationStatusException("compile phase failed", result) } throw CompilationStatusException("compile phase failed", result, output) } else if (printOnSuccess) { printCompilerOutput(output) } return output } /** * Runs a task and records the timings. */ fun <T> execute(name: String, task: () -> T): T = execute({ name }, task) /** * Runs a task and records the timings. */ @Suppress("MemberVisibilityCanBePrivate") fun <T> execute(name: () -> String, task: () -> T): T { return if (timings == null) { task() } else { pushTimedTask(name(), task) } } private inline fun <T> pushTimedTask(name: String, task: () -> T): T { level += 1 val previousTimings = timings timings = mutableListOf() return try { System.currentTimeMillis().let { start -> task().also { val stop = System.currentTimeMillis() previousTimings!! += "${" ".repeat(level)} * $name: ${stop - start} ms" previousTimings.addAll(timings!!) } } } finally { level -= 1 timings = previousTimings } } /** * This method should be called at the end of builder invocation. * * @param successful true if the task finished successfully. */ fun finalize(successful: Boolean) { if (successful) { timings?.also { printLines( "Task timings for ${info.label} (total: ${System.currentTimeMillis() - start} ms)", it, ) } } } }
apache-2.0
2e14eda86ad337dfd5c5e045950da921
28.213542
115
0.661972
4.223645
false
false
false
false
Finnerale/ExaCalc
src/main/kotlin/de/leopoldluley/exacalc/view/MainView.kt
1
1186
package de.leopoldluley.exacalc.view import javafx.scene.input.MouseEvent import tornadofx.* class MainView : View("ExaCalc") { val navigation: NavigationView by inject() val calculator: CalculatorView by inject() val settings: SettingsView by inject() val variables: VariablesView by inject() val functions: FunctionsView by inject() var current: View = calculator override val root = stackpane { prefHeight = 400.0 prefWidth = 600.0 setOnMouseDragged { doDrag(it) } setOnMousePressed { startDrag(it) } this += current this += navigation } fun show(view: View) { if (current !== view) { current.replaceWith(view, ViewTransition.Reveal(0.3.seconds)) current = view } } var lastXPos = 0.0 var lastYPos = 0.0 fun startDrag(event: MouseEvent) { lastXPos = event.screenX - FX.primaryStage.x lastYPos = event.screenY - FX.primaryStage.y } fun doDrag(event: MouseEvent) { println(event.screenX) FX.primaryStage.x = event.screenX - lastXPos FX.primaryStage.y = event.screenY - lastYPos } }
gpl-3.0
80c3248a4a5370a9861e369c69da6c55
23.729167
73
0.631535
4.281588
false
false
false
false
TCA-Team/TumCampusApp
app/src/main/java/de/tum/in/tumcampusapp/component/tumui/roomfinder/RoomFinderListAdapter.kt
1
1530
package de.tum.`in`.tumcampusapp.component.tumui.roomfinder import android.content.Context import android.view.View import android.view.ViewGroup import android.widget.TextView import de.tum.`in`.tumcampusapp.R import de.tum.`in`.tumcampusapp.component.other.generic.adapter.SimpleStickyListHeadersAdapter import de.tum.`in`.tumcampusapp.component.tumui.roomfinder.model.RoomFinderRoom /** * Custom UI adapter for a list of employees. */ class RoomFinderListAdapter( context: Context, items: List<RoomFinderRoom> ) : SimpleStickyListHeadersAdapter<RoomFinderRoom>(context, items.toMutableList()) { internal class ViewHolder { var tvRoomTitle: TextView? = null var tvBuildingTitle: TextView? = null } override fun getView(position: Int, convertView: View?, parent: ViewGroup): View { val holder: ViewHolder val view: View if (convertView == null) { view = inflater.inflate(R.layout.list_roomfinder_item, parent, false) holder = ViewHolder() holder.tvRoomTitle = view.findViewById(R.id.startup_actionbar_title) holder.tvBuildingTitle = view.findViewById(R.id.building) view.tag = holder } else { view = convertView holder = view.tag as ViewHolder } val room = itemList[position] // Setting all values in listView holder.tvRoomTitle?.text = room.info holder.tvBuildingTitle?.text = room.formattedAddress return view } }
gpl-3.0
34fae278cfaa14899a7a6a4b330e4f22
32.26087
94
0.685621
4.285714
false
false
false
false
Polidea/RxAndroidBle
sample-kotlin/src/main/kotlin/com/polidea/rxandroidble2/samplekotlin/util/ScanExceptionHandler.kt
1
3179
package com.polidea.rxandroidble2.samplekotlin.util import android.app.Activity import android.util.Log import com.polidea.rxandroidble2.exceptions.BleScanException import com.polidea.rxandroidble2.samplekotlin.R import java.util.Date import java.util.Locale import java.util.concurrent.TimeUnit /** * Helper functions to show BleScanException error messages as toasts. */ /** * Mapping of exception reasons to error string resource ids. Add new mappings here. */ private val ERROR_MESSAGES = mapOf( BleScanException.BLUETOOTH_NOT_AVAILABLE to R.string.error_bluetooth_not_available, BleScanException.BLUETOOTH_DISABLED to R.string.error_bluetooth_disabled, BleScanException.LOCATION_PERMISSION_MISSING to R.string.error_location_permission_missing, BleScanException.LOCATION_SERVICES_DISABLED to R.string.error_location_services_disabled, BleScanException.SCAN_FAILED_ALREADY_STARTED to R.string.error_scan_failed_already_started, BleScanException.SCAN_FAILED_APPLICATION_REGISTRATION_FAILED to R.string.error_scan_failed_application_registration_failed, BleScanException.SCAN_FAILED_FEATURE_UNSUPPORTED to R.string.error_scan_failed_feature_unsupported, BleScanException.SCAN_FAILED_INTERNAL_ERROR to R.string.error_scan_failed_internal_error, BleScanException.SCAN_FAILED_OUT_OF_HARDWARE_RESOURCES to R.string.error_scan_failed_out_of_hardware_resources, BleScanException.BLUETOOTH_CANNOT_START to R.string.error_bluetooth_cannot_start, BleScanException.UNKNOWN_ERROR_CODE to R.string.error_unknown_error ) /** * Show toast in this Activity with error message appropriate to exception reason. * * @param exception BleScanException to show error message for */ internal fun Activity.showError(exception: BleScanException) = getErrorMessage(exception).let { errorMessage -> Log.e("Scanning", errorMessage, exception) showSnackbarShort(errorMessage) } private fun Activity.getErrorMessage(exception: BleScanException): String = // Special case, as there might or might not be a retry date suggestion if (exception.reason == BleScanException.UNDOCUMENTED_SCAN_THROTTLE) { getScanThrottleErrorMessage(exception.retryDateSuggestion) } else { // Handle all other possible errors ERROR_MESSAGES[exception.reason]?.let { errorResId -> getString(errorResId) } ?: run { // unknown error - return default message Log.w("Scanning", String.format(getString(R.string.error_no_message), exception.reason)) getString(R.string.error_unknown_error) } } private fun Activity.getScanThrottleErrorMessage(retryDate: Date?): String = with(StringBuilder(getString(R.string.error_undocumented_scan_throttle))) { retryDate?.let { date -> String.format( Locale.getDefault(), getString(R.string.error_undocumented_scan_throttle_retry), date.secondsUntil ).let { append(it) } } toString() } private val Date.secondsUntil: Long get() = TimeUnit.MILLISECONDS.toSeconds(time - System.currentTimeMillis())
apache-2.0
486aa4aff61825e595beb0ec8e458e82
43.152778
115
0.739226
4.188406
false
false
false
false
lydia-schiff/hella-renderscript
hella/src/main/java/com/lydiaschiff/hella/renderer/Lut3dRsRenderer.kt
1
2123
package com.lydiaschiff.hella.renderer import android.renderscript.Allocation import android.renderscript.Element import android.renderscript.RenderScript import android.renderscript.ScriptIntrinsic3DLUT import com.lydiaschiff.hella.RsRenderer import com.lydiaschiff.hella.RsUtil open class Lut3dRsRenderer(val cubeDim: Int) : RsRenderer { // explicit zero-arg constructor constructor() : this(CUBE_DIM) // all guarded by "this" private lateinit var lut3dScript: ScriptIntrinsic3DLUT protected lateinit var lutAlloc: Allocation protected var firstDraw = true private set protected var hasUpdate = false protected val rgbFloatLut: FloatArray = FloatArray(cubeDim * cubeDim * cubeDim * 3) @Synchronized override fun renderFrame(rs: RenderScript, inAlloc: Allocation, outAlloc: Allocation) { if (firstDraw) { lut3dScript = ScriptIntrinsic3DLUT.create(rs, Element.RGBA_8888(rs)) lutAlloc = RsUtil.lut3dAlloc(rs, SET_IDENTITY_BY_DEFAULT, cubeDim) lut3dScript.setLUT(lutAlloc) onFirstDraw(rs) firstDraw = false } if (hasUpdate) { onUpdate() } lut3dScript.forEach(inAlloc, outAlloc) } protected open fun onFirstDraw(rs : RenderScript) = Unit protected open fun onUpdate() { RsUtil.copyRgbFloatsToAlloc(rgbFloatLut, lutAlloc) lut3dScript.setLUT(lutAlloc) hasUpdate = false } @Synchronized fun setLutData(rgbFloatLut: FloatArray) { require(rgbFloatLut.size == N_VALUES_RGB) if (!rgbFloatLut.contentEquals(this.rgbFloatLut)) { rgbFloatLut.copyInto(this.rgbFloatLut) hasUpdate = true } } override val name = "Lut3dRenderer Cool Algebra!" override val canRenderInPlace = true companion object { const val CUBE_DIM = 17 const val N_COLORS = CUBE_DIM * CUBE_DIM * CUBE_DIM const val N_VALUES_RGB = N_COLORS * 3 const val SET_IDENTITY_BY_DEFAULT = true fun emptyRgbFloatLut() = FloatArray(N_VALUES_RGB) } }
mit
76437c0483fa96b68fde0480bd2d23d2
29.328571
91
0.675459
3.924214
false
false
false
false
TCA-Team/TumCampusApp
app/src/main/java/de/tum/in/tumcampusapp/component/ui/barrierfree/BarrierFreeFacilitiesActivity.kt
1
2898
package de.tum.`in`.tumcampusapp.component.ui.barrierfree import android.content.Intent import android.os.Bundle import android.view.View import android.widget.AdapterView import de.tum.`in`.tumcampusapp.R import de.tum.`in`.tumcampusapp.component.other.general.RecentsDao import de.tum.`in`.tumcampusapp.component.other.general.model.Recent import de.tum.`in`.tumcampusapp.component.other.generic.activity.ActivityForAccessingTumCabe import de.tum.`in`.tumcampusapp.component.other.locations.LocationManager import de.tum.`in`.tumcampusapp.component.tumui.roomfinder.RoomFinderDetailsActivity import de.tum.`in`.tumcampusapp.component.tumui.roomfinder.RoomFinderListAdapter import de.tum.`in`.tumcampusapp.component.tumui.roomfinder.model.RoomFinderRoom import de.tum.`in`.tumcampusapp.database.TcaDb import kotlinx.android.synthetic.main.activity_barrier_free_facilities.* import retrofit2.Call class BarrierFreeFacilitiesActivity : ActivityForAccessingTumCabe<List<RoomFinderRoom>>( R.layout.activity_barrier_free_facilities ), AdapterView.OnItemSelectedListener { private val recents: RecentsDao by lazy { TcaDb.getInstance(this).recentsDao() } private val locationManager: LocationManager by lazy { LocationManager(this) } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) spinnerToolbar.onItemSelectedListener = this } override fun onItemSelected(parent: AdapterView<*>, view: View, position: Int, id: Long) { when (position) { 0 -> fetchApiCallForCurrentLocation() 1 -> executeApiCall(apiClient.listOfElevators) else -> executeApiCall(apiClient.listOfElevators) } } private fun fetchApiCallForCurrentLocation() { locationManager.fetchBuildingIDFromCurrentLocation { val apiCall = apiClient.getListOfNearbyFacilities(it) executeApiCall(apiCall) } } private fun executeApiCall(apiCall: Call<List<RoomFinderRoom>>?) { apiCall?.let { fetch(it) } ?: showError(R.string.error_something_wrong) } override fun onDownloadSuccessful(response: List<RoomFinderRoom>) { barrierFreeFacilitiesListView.adapter = RoomFinderListAdapter(this, response) barrierFreeFacilitiesListView.setOnItemClickListener { _, _, index, _ -> val facility = response[index] recents.insert(Recent(facility.toString(), RecentsDao.ROOMS)) openRoomFinderDetails(facility) } } private fun openRoomFinderDetails(facility: RoomFinderRoom) { val intent = Intent(this, RoomFinderDetailsActivity::class.java) intent.putExtra(RoomFinderDetailsActivity.EXTRA_ROOM_INFO, facility) startActivity(intent) } override fun onNothingSelected(parent: AdapterView<*>) { // Nothing selected } }
gpl-3.0
08b83334df074a2d3c4660278b71d697
38.69863
94
0.73568
4.451613
false
false
false
false
laurentvdl/sqlbuilder
src/main/kotlin/sqlbuilder/meta/JavaGetterSetterPropertyReference.kt
1
2107
package sqlbuilder.meta import sqlbuilder.PersistenceException import java.lang.reflect.Method /** * Wrapper for bean property using getter/setter reflection. */ class JavaGetterSetterPropertyReference(override var name: String, private val method: Method, override var classType: Class<*>) : PropertyReference { override val columnName: String = findColumnName() override fun set(bean: Any, value: Any?) { try { if (!(value == null && classType.isPrimitive)) { method.invoke(bean, value) } } catch (e: Exception) { val signature = "${method.name}(${method.parameterTypes?.joinToString(",")})" throw PersistenceException("unable to set value $name to '$value' on bean $bean using setter <$signature>, expected argument of type <$classType>, but got <${value?.javaClass}>", e) } } override fun get(bean: Any): Any? { try { if (!method.isAccessible) { method.isAccessible = true } return method.invoke(bean) } catch (e: Exception) { val signature = "${method.name}(${method.parameterTypes?.joinToString(",")})" throw PersistenceException("unable to get value $name from bean $bean using getter $signature", e) } } private fun findColumnName(): String { return try { method.declaringClass.getDeclaredField(name).getAnnotation(Column::class.java)?.name ?: name } catch (ignore: NoSuchFieldException) { name } } override fun equals(other: Any?): Boolean { if (this === other) return true if (other == null || javaClass != other.javaClass) return false val setter = other as JavaGetterSetterPropertyReference return name == setter.name } override fun hashCode(): Int { var result = name.hashCode() result = 31 * result + classType.hashCode() return result } override fun toString(): String { return "property <${method.declaringClass}.$name>" } }
apache-2.0
41835b97574d90cf8b8a18f9ebeda9b0
32.444444
193
0.611296
4.934426
false
false
false
false
hitoshura25/Media-Player-Omega-Android
auth_framework/src/main/java/com/vmenon/mpo/auth/framework/openid/viewmodel/OpenIdHandlerViewModel.kt
1
4449
package com.vmenon.mpo.auth.framework.openid.viewmodel import android.app.Activity import android.content.Intent import androidx.activity.result.ActivityResultLauncher import androidx.activity.result.contract.ActivityResultContracts.StartActivityForResult import androidx.fragment.app.Fragment import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.vmenon.mpo.auth.framework.Authenticator import com.vmenon.mpo.auth.framework.openid.OpenIdAuthenticator import com.vmenon.mpo.auth.framework.openid.fragment.OpenIdHandlerFragment.Companion.EXTRA_OPERATION import com.vmenon.mpo.auth.framework.openid.fragment.OpenIdHandlerFragment.Companion.Operation import com.vmenon.mpo.system.domain.Logger import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import net.openid.appauth.AuthorizationException import net.openid.appauth.AuthorizationResponse import net.openid.appauth.EndSessionResponse import java.lang.IllegalStateException import javax.inject.Inject class OpenIdHandlerViewModel : ViewModel() { @Inject lateinit var authenticator: Authenticator @Inject lateinit var logger: Logger private val authenticated = MutableLiveData<Boolean>() private var startAuthContract: ActivityResultLauncher<Intent>? = null private var logoutContract: ActivityResultLauncher<Intent>? = null fun authenticated(): LiveData<Boolean> = authenticated fun onCreated(fragment: Fragment) { startAuthContract = fragment.registerForActivityResult( StartActivityForResult() ) { activityResult -> handlePerformAuthOperationResult(activityResult.resultCode, activityResult.data) } logoutContract = fragment.registerForActivityResult( StartActivityForResult() ) { activityResult -> handleEndSessionOperationResult(activityResult.resultCode, activityResult.data) } } fun onResume(fragment: Fragment) { val operation = fragment.arguments?.getSerializable(EXTRA_OPERATION) as Operation? if (operation != null) { fragment.arguments?.remove(EXTRA_OPERATION) when (operation) { Operation.PERFORM_AUTH -> startAuthContract?.let { contract -> handlePerformAuthOperationRequest(contract) } ?: throw IllegalStateException("startAuthContract should not be null!") Operation.LOGOUT -> logoutContract?.let { contract -> handleEndSessionRequest(contract) } ?: throw IllegalStateException("logoutContract should not be null!") } } } private fun handlePerformAuthOperationRequest(launcher: ActivityResultLauncher<Intent>) { viewModelScope.launch(Dispatchers.IO) { (authenticator as OpenIdAuthenticator).performAuthenticate(launcher) } } private fun handleEndSessionRequest(launcher: ActivityResultLauncher<Intent>) { viewModelScope.launch(Dispatchers.IO) { if (!(authenticator as OpenIdAuthenticator).performLogoutIfNecessary(launcher)) { authenticated.postValue(false) // Already logged out I Guess } } } private fun handlePerformAuthOperationResult(resultCode: Int, data: Intent?) { if (resultCode == Activity.RESULT_OK && data != null) { viewModelScope.launch(Dispatchers.IO) { (authenticator as OpenIdAuthenticator).handleAuthResponse( AuthorizationResponse.fromIntent(data), AuthorizationException.fromIntent(data) ) authenticated.postValue(true) } } else { logger.println("Issue with handling auth result $resultCode $data") authenticated.postValue(false) } } private fun handleEndSessionOperationResult(resultCode: Int, data: Intent?) { var exception: AuthorizationException? = null if (resultCode == Activity.RESULT_OK && data != null) { exception = AuthorizationException.fromIntent(data) } viewModelScope.launch(Dispatchers.IO) { (authenticator as OpenIdAuthenticator).handleEndSessionResponse( exception ) authenticated.postValue(false) } } }
apache-2.0
24cf2e54db437187a23112409c174bfc
39.454545
100
0.700382
5.458896
false
false
false
false
exponentjs/exponent
packages/expo-media-library/android/src/main/java/expo/modules/medialibrary/albums/AssetFileStrategy.kt
2
1277
package expo.modules.medialibrary.albums import android.content.ContentUris import android.content.Context import android.os.Build import android.provider.MediaStore import expo.modules.medialibrary.EXTERNAL_CONTENT_URI import expo.modules.medialibrary.MediaLibraryUtils import java.io.File import java.io.IOException internal fun interface AssetFileStrategy { @Throws(IOException::class) fun apply(src: File, dir: File, context: Context): File companion object { val copyStrategy = AssetFileStrategy { src, dir, _ -> MediaLibraryUtils.safeCopyFile(src, dir) } val moveStrategy = AssetFileStrategy strategy@{ src, dir, context -> if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R && src is MediaLibraryUtils.AssetFile) { val assetId = src.assetId val assetUri = ContentUris.withAppendedId(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, assetId.toLong()) val newFile = MediaLibraryUtils.safeCopyFile(src, dir) context.contentResolver.delete(assetUri, null) return@strategy newFile } val newFile = MediaLibraryUtils.safeMoveFile(src, dir) context.contentResolver.delete( EXTERNAL_CONTENT_URI, "${MediaStore.MediaColumns.DATA}=?", arrayOf(src.path) ) newFile } } }
bsd-3-clause
9aa39f0c94fec7c1327b73c50335d5be
36.558824
113
0.734534
4.106109
false
false
false
false
Heiner1/AndroidAPS
core/src/main/java/info/nightscout/androidaps/utils/MidnightTime.kt
1
1613
package info.nightscout.androidaps.utils import android.util.LongSparseArray import java.util.* object MidnightTime { val times = LongSparseArray<Long>() private var hits: Long = 0 private var misses: Long = 0 private const val THRESHOLD = 100000 fun calc(): Long { val c = Calendar.getInstance() c[Calendar.HOUR_OF_DAY] = 0 c[Calendar.MINUTE] = 0 c[Calendar.SECOND] = 0 c[Calendar.MILLISECOND] = 0 return c.timeInMillis } fun calcPlusMinutes(minutes: Int): Long { val h = minutes / 60 val m = minutes % 60 val c = Calendar.getInstance() c[Calendar.HOUR_OF_DAY] = h c[Calendar.MINUTE] = m c[Calendar.SECOND] = 0 c[Calendar.MILLISECOND] = 0 return c.timeInMillis } fun calc(time: Long): Long { var m: Long? synchronized(times) { m = times[time] if (m != null) { ++hits return m!! } val c = Calendar.getInstance() c.timeInMillis = time c[Calendar.HOUR_OF_DAY] = 0 c[Calendar.MINUTE] = 0 c[Calendar.SECOND] = 0 c[Calendar.MILLISECOND] = 0 m = c.timeInMillis times.append(time, m) ++misses if (times.size() > THRESHOLD) resetCache() } return m!! } fun resetCache() { hits = 0 misses = 0 times.clear() } fun log(): String = "Hits: " + hits + " misses: " + misses + " stored: " + times.size() }
agpl-3.0
4e9cd0a4eb60cccbf72c94d30b7684fa
24.21875
75
0.516429
4.104326
false
false
false
false
realm/realm-java
realm/kotlin-extensions/src/main/kotlin/io/realm/kotlin/RealmObjectExtensions.kt
1
5579
/* * Copyright 2020 Realm 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 io.realm.kotlin import io.realm.* import io.realm.annotations.Beta import io.realm.internal.RealmObjectProxy import io.realm.rx.ObjectChange import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.flowOf /** * Returns a [Flow] that monitors changes to this RealmObject. It will emit the current * RealmObject upon subscription. Object updates will continually be emitted as the RealmObject is * updated - `onCompletion` will never be called. * * Items emitted from Realm flows are frozen - see [RealmObject.freeze]. This means that they are * immutable and can be read from any thread. * * Realm flows always emit items from the thread holding the live RealmObject. This means that if * you need to do further processing, it is recommended to collect the values on a computation * dispatcher: * * ``` * object.toFlow() * .map { obj -> doExpensiveWork(obj) } * .flowOn(Dispatchers.IO) * .onEach { flowObject -> * // ... * }.launchIn(Dispatchers.Main) * ``` * * If your would like `toFlow()` to stop emitting items you can instruct the flow to only emit the * first item by calling [kotlinx.coroutines.flow.first]: * ``` * val foo = object.toFlow() * .flowOn(context) * .first() * ``` * * @return Kotlin [Flow] on which calls to `onEach` or `collect` can be made. */ @Beta fun <T : RealmModel> T?.toFlow(): Flow<T?> { // Return flow with object or null flow if this function is called on null return this?.let { obj -> if (obj is RealmObjectProxy) { val proxy = obj as RealmObjectProxy @Suppress("INACCESSIBLE_TYPE") when (val realm = proxy.`realmGet$proxyState`().`realm$realm`) { is Realm -> realm.configuration.flowFactory.from<T>(realm, obj) is DynamicRealm -> (obj as DynamicRealmObject).let { dynamicRealmObject -> realm.configuration.flowFactory.from(realm, dynamicRealmObject) as Flow<T?> } else -> throw UnsupportedOperationException("${realm.javaClass} is not supported as a candidate for 'toFlow'. Only subclasses of RealmModel/RealmObject can be used.") } } else { // Return a one-time emission in case the object is unmanaged return flowOf(this) } } ?: flowOf(null) } /** * Returns a [Flow] that monitors changes to this RealmObject. It will emit the current * RealmObject upon subscription. For each update to the RealmObject a [ObjectChange] consisting of * a pair with the RealmObject and its corresponding [ObjectChangeSet] will be sent. The changeset * will be `null` the first time the RealmObject is emitted. * * The RealmObject will continually be emitted as it is updated. This flow will never complete. * * Items emitted are frozen (see [RealmObject.freeze]). This means that they are immutable and can * be read on any thread. * * Realm flows always emit items from the thread holding the live Realm. This means that if * you need to do further processing, it is recommended to collect the values on a computation * dispatcher: * * ``` * object.toChangesetFlow() * .map { change -> doExpensiveWork(change) } * .flowOn(Dispatchers.IO) * .onEach { change -> * // ... * }.launchIn(Dispatchers.Main) * ``` * * If you would like `toChangesetFlow()` to stop emitting items you can instruct the flow to only * emit the first item by calling [kotlinx.coroutines.flow.first]: * ``` * val foo = object.toChangesetFlow() * .flowOn(context) * .first() * ``` * * @return Kotlin [Flow] that will never complete. * @throws UnsupportedOperationException if the required coroutines framework is not on the * classpath or the corresponding Realm instance doesn't support flows. * @throws IllegalStateException if the Realm wasn't opened on a Looper thread. */ @Beta fun <T : RealmModel> T?.toChangesetFlow(): Flow<ObjectChange<T>?> { // Return flow with objectchange containing this object or null flow if this function is called on null return this?.let { obj -> if (obj is RealmObjectProxy) { val proxy = obj as RealmObjectProxy @Suppress("INACCESSIBLE_TYPE") when (val realm = proxy.`realmGet$proxyState`().`realm$realm`) { is Realm -> realm.configuration.flowFactory.changesetFrom<T>(realm, obj) is DynamicRealm -> (obj as DynamicRealmObject).let { dynamicRealmObject -> realm.configuration.flowFactory.changesetFrom(realm, dynamicRealmObject) as Flow<ObjectChange<T>?> } else -> throw UnsupportedOperationException("${realm.javaClass} is not supported as a candidate for 'toFlow'. Only subclasses of RealmModel/RealmObject can be used.") } } else { // Return a one-time emission in case the object is unmanaged return flowOf(ObjectChange(this, null)) } } ?: flowOf(null) }
apache-2.0
86fef1eef888635e9ad737f406fdadf6
40.022059
182
0.681305
4.252287
false
false
false
false
AcornUI/Acorn
acornui-core/src/main/kotlin/com/acornui/audio/JsWebAudioSound.kt
1
2855
/* * Copyright 2020 Poly Forest, 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.acornui.audio import com.acornui.time.nowS import org.khronos.webgl.ArrayBuffer import kotlin.time.Duration import kotlin.time.seconds class JsWebAudioSound( private val audioManager: AudioManager, private val context: AudioContext, decodedData: ArrayBuffer, override val priority: Double) : Sound { override var onCompleted: (() -> Unit)? = null private var gain: GainNode private val panner: PannerNode private val audioBufferSourceNode: AudioBufferSourceNode private var _isPlaying: Boolean = false override val isPlaying: Boolean get() = _isPlaying private var _startTime: Double = 0.0 private var _stopTime: Double = 0.0 init { // create a sound source audioBufferSourceNode = context.createBufferSource() audioBufferSourceNode.addEventListener("ended", { complete() }) // Add the buffered data to our object audioBufferSourceNode.buffer = decodedData // Panning panner = context.createPanner() panner.panningModel = PanningModel.EQUAL_POWER.value // Volume gain = context.createGain() gain.gain.value = audioManager.soundVolume // Wire them together. audioBufferSourceNode.connect(panner) panner.connect(gain) panner.setPosition(0.0, 0.0, 1.0) gain.connect(context.destination) audioManager.registerSound(this) } private fun complete() { _stopTime = nowS() _isPlaying = false onCompleted?.invoke() onCompleted = null audioManager.unregisterSound(this) } override var loop: Boolean get() = audioBufferSourceNode.loop set(value) { audioBufferSourceNode.loop = value } private var _volume: Double = 1.0 override var volume: Double get() = _volume set(value) { _volume = value gain.gain.value = com.acornui.math.clamp(value * audioManager.soundVolume, 0.0, 1.0) } override fun setPosition(x: Double, y: Double, z: Double) { panner.setPosition(x, y, z) } override fun start() { audioBufferSourceNode.start(context.currentTime) _startTime = nowS() } override fun stop() { audioBufferSourceNode.stop(0.0) } override val currentTime: Duration get() { return if (!_isPlaying) (_stopTime - _startTime).seconds else (nowS() - _startTime).seconds } override fun dispose() { stop() } }
apache-2.0
7127bae7a9d9e0f94180421ea1e62595
22.991597
87
0.721541
3.511685
false
false
false
false
blindpirate/gradle
subprojects/kotlin-dsl/src/test/kotlin/org/gradle/kotlin/dsl/KotlinBuildScriptPatternTest.kt
3
2649
/* * Copyright 2021 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.gradle.kotlin.dsl import org.junit.Assert.assertEquals import org.junit.Test import org.junit.runner.RunWith import org.junit.runners.Parameterized import kotlin.reflect.KClass import kotlin.reflect.full.findAnnotation import kotlin.script.templates.ScriptTemplateDefinition @RunWith(Parameterized::class) class KotlinBuildScriptPatternTest(val script: Script) { enum class ScriptType { BUILD, INIT, SETTINGS } data class Script(val name: String, val type: ScriptType) companion object { @Parameterized.Parameters(name = "{0}") @JvmStatic fun scripts(): Iterable<Script> = listOf( Script("settings.gradle.kts", ScriptType.SETTINGS), Script("my.settings.gradle.kts", ScriptType.SETTINGS), Script("init.gradle.kts", ScriptType.INIT), Script("my.init.gradle.kts", ScriptType.INIT), Script("build.gradle.kts", ScriptType.BUILD), Script("no-settings.gradle.kts", ScriptType.BUILD), Script("no-init.gradle.kts", ScriptType.BUILD), Script("anything.gradle.kts", ScriptType.BUILD), ) } @Test fun `recognizes build scripts`() { checkScriptRecognizedBy(KotlinBuildScript::class, ScriptType.BUILD) } @Test fun `recognizes settings scripts`() { checkScriptRecognizedBy(KotlinSettingsScript::class, ScriptType.SETTINGS) } @Test fun `recognizes init scripts`() { checkScriptRecognizedBy(KotlinInitScript::class, ScriptType.INIT) } private fun checkScriptRecognizedBy(scriptParserClass: KClass<*>, supportedScriptType: ScriptType) { val buildScriptPattern = scriptParserClass.findAnnotation<ScriptTemplateDefinition>()!!.scriptFilePattern val shouldMatch = script.type == supportedScriptType assertEquals("${script.name} should${if (shouldMatch) "" else " not"} match $buildScriptPattern", shouldMatch, script.name.matches(buildScriptPattern.toRegex())) } }
apache-2.0
9dcb6ef2f8ce1f53f52bc6acef05bf0b
34.797297
169
0.701774
4.535959
false
true
false
false
JetBrains/ideavim
vim-engine/src/main/kotlin/com/maddyhome/idea/vim/vimscript/model/expressions/DictionaryExpression.kt
1
1508
/* * Copyright 2003-2022 The IdeaVim authors * * Use of this source code is governed by an MIT-style * license that can be found in the LICENSE.txt file or at * https://opensource.org/licenses/MIT. */ package com.maddyhome.idea.vim.vimscript.model.expressions import com.maddyhome.idea.vim.api.ExecutionContext import com.maddyhome.idea.vim.api.VimEditor import com.maddyhome.idea.vim.vimscript.model.VimLContext import com.maddyhome.idea.vim.vimscript.model.datatypes.VimDataType import com.maddyhome.idea.vim.vimscript.model.datatypes.VimDictionary import com.maddyhome.idea.vim.vimscript.model.datatypes.VimFuncref import com.maddyhome.idea.vim.vimscript.model.datatypes.VimString import com.maddyhome.idea.vim.vimscript.model.functions.DefinedFunctionHandler data class DictionaryExpression(val dictionary: LinkedHashMap<Expression, Expression>) : Expression() { override fun evaluate(editor: VimEditor, context: ExecutionContext, vimContext: VimLContext): VimDataType { val dict = VimDictionary(linkedMapOf()) for ((key, value) in dictionary) { val evaluatedVal = value.evaluate(editor, context, vimContext) var newFuncref = evaluatedVal if (evaluatedVal is VimFuncref && evaluatedVal.handler is DefinedFunctionHandler && !evaluatedVal.isSelfFixed) { newFuncref = evaluatedVal.copy() newFuncref.dictionary = dict } dict.dictionary[VimString(key.evaluate(editor, context, vimContext).asString())] = newFuncref } return dict } }
mit
cb840f9bcc8e6ffefd26b29aa16f67a5
42.085714
118
0.77321
4.108992
false
false
false
false
RadiationX/ForPDA
app/src/main/java/forpdateam/ru/forpda/ui/fragments/settings/BaseSettingFragment.kt
1
1635
package forpdateam.ru.forpda.ui.fragments.settings import android.os.Bundle import androidx.preference.PreferenceFragmentCompat import androidx.recyclerview.widget.RecyclerView import forpdateam.ru.forpda.App import forpdateam.ru.forpda.ui.activities.SettingsActivity /** * Created by radiationx on 24.09.17. */ open class BaseSettingFragment : PreferenceFragmentCompat() { private var listScrollY = 0 private var lastIsVisible = false override fun onCreatePreferences(savedInstanceState: Bundle?, rootKey: String?) { } override fun onActivityCreated(savedInstanceState: Bundle?) { super.onActivityCreated(savedInstanceState) view?.findViewById<androidx.recyclerview.widget.RecyclerView>(androidx.preference.R.id.recycler_view)?.also { list -> list.setPadding(0, 0, 0, 0) list.addOnScrollListener(object : androidx.recyclerview.widget.RecyclerView.OnScrollListener() { override fun onScrolled(recyclerView: androidx.recyclerview.widget.RecyclerView, dx: Int, dy: Int) { super.onScrolled(recyclerView, dx, dy) listScrollY = recyclerView.computeVerticalScrollOffset() updateToolbarShadow() } }) } updateToolbarShadow() setDividerHeight(0) } private fun updateToolbarShadow() { val isVisible = listScrollY > 0 if (lastIsVisible != isVisible) { (activity as? SettingsActivity)?.supportActionBar?.elevation = if (isVisible) App.px2.toFloat() else 0f lastIsVisible = isVisible } } }
gpl-3.0
e5f43bb7eb3920319c9f43e1af6c0eab
35.333333
125
0.68318
5.141509
false
false
false
false
kelsos/mbrc
app/src/main/kotlin/com/kelsos/mbrc/ui/navigation/library/albums/BrowseAlbumFragment.kt
1
3909
package com.kelsos.mbrc.ui.navigation.library.albums import android.os.Bundle import android.view.LayoutInflater import android.view.MenuItem import android.view.View import android.view.ViewGroup import android.widget.Button import android.widget.TextView import androidx.core.view.isGone import androidx.fragment.app.Fragment import androidx.recyclerview.widget.LinearLayoutManager import butterknife.BindView import butterknife.ButterKnife import com.google.android.material.snackbar.Snackbar import com.kelsos.mbrc.R import com.kelsos.mbrc.adapters.AlbumEntryAdapter import com.kelsos.mbrc.annotations.Queue import com.kelsos.mbrc.data.library.Album import com.kelsos.mbrc.helper.PopupActionHandler import com.kelsos.mbrc.ui.navigation.library.LibraryActivity.Companion.LIBRARY_SCOPE import com.kelsos.mbrc.ui.widgets.EmptyRecyclerView import com.raizlabs.android.dbflow.list.FlowCursorList import toothpick.Toothpick import toothpick.smoothie.module.SmoothieActivityModule import javax.inject.Inject class BrowseAlbumFragment : Fragment(), BrowseAlbumView, AlbumEntryAdapter.MenuItemSelectedListener { @BindView(R.id.library_data_list) lateinit var recycler: EmptyRecyclerView @BindView(R.id.empty_view) lateinit var emptyView: View @BindView(R.id.list_empty_title) lateinit var emptyTitle: TextView @Inject lateinit var adapter: AlbumEntryAdapter @Inject lateinit var actionHandler: PopupActionHandler @Inject lateinit var presenter: BrowseAlbumPresenter private lateinit var syncButton: Button; override fun search(term: String) { syncButton.isGone = term.isNotEmpty() } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { val view = inflater.inflate(R.layout.fragment_library_search, container, false) ButterKnife.bind(this, view) emptyTitle.setText(R.string.albums_list_empty) syncButton = view.findViewById<Button>(R.id.list_empty_sync); syncButton.setOnClickListener { presenter.sync() } return view } override fun onStart() { super.onStart() presenter.attach(this) adapter.refresh() } override fun onResume() { super.onResume() adapter.refresh() } override fun onCreate(savedInstanceState: Bundle?) { val scope = Toothpick.openScopes(requireActivity().application, LIBRARY_SCOPE, activity, this) scope.installModules( SmoothieActivityModule(requireActivity()), BrowseAlbumModule() ) super.onCreate(savedInstanceState) Toothpick.inject(this, scope) presenter.attach(this) presenter.load() } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) recycler.adapter = adapter recycler.emptyView = emptyView recycler.layoutManager = LinearLayoutManager(recycler.context) recycler.setHasFixedSize(true) adapter.setMenuItemSelectedListener(this) } override fun onMenuItemSelected(menuItem: MenuItem, album: Album) { val action = actionHandler.albumSelected(menuItem, album, requireActivity()) if (action != Queue.PROFILE) { presenter.queue(action, album) } } override fun onItemClicked(album: Album) { actionHandler.albumSelected(album, requireActivity()) } override fun onStop() { super.onStop() presenter.detach() } override fun update(cursor: FlowCursorList<Album>) { adapter.update(cursor) } override fun queue(success: Boolean, tracks: Int) { val message = if (success) { getString(R.string.queue_result__success, tracks) } else { getString(R.string.queue_result__failure) } Snackbar.make(recycler, R.string.queue_result__success, Snackbar.LENGTH_SHORT) .setText(message) .show() } override fun onDestroy() { Toothpick.closeScope(this) super.onDestroy() } }
gpl-3.0
b546c5a0cb036130d918174ce52341a3
27.326087
98
0.751855
4.25817
false
false
false
false
mdaniel/intellij-community
plugins/kotlin/jvm-debugger/test/test/org/jetbrains/kotlin/idea/debugger/test/sequence/exec/KotlinTraceTestCase.kt
1
6849
// 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.debugger.test.sequence.exec import com.intellij.debugger.engine.evaluation.EvaluationContextImpl import com.intellij.debugger.impl.OutputChecker import com.intellij.debugger.streams.lib.LibrarySupportProvider import com.intellij.debugger.streams.psi.DebuggerPositionResolver import com.intellij.debugger.streams.psi.impl.DebuggerPositionResolverImpl import com.intellij.debugger.streams.trace.* import com.intellij.debugger.streams.trace.impl.TraceResultInterpreterImpl import com.intellij.debugger.streams.wrapper.StreamChain import com.intellij.debugger.streams.wrapper.StreamChainBuilder import com.intellij.execution.process.ProcessOutputTypes import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.util.Computable import com.intellij.xdebugger.XDebugSessionListener import org.jetbrains.kotlin.idea.debugger.evaluate.KotlinEvaluator import org.jetbrains.kotlin.idea.debugger.test.KotlinDescriptorTestCaseWithStepping import org.jetbrains.kotlin.idea.debugger.test.TestFiles import org.jetbrains.kotlin.idea.debugger.test.preference.DebuggerPreferences import java.util.concurrent.atomic.AtomicBoolean abstract class KotlinTraceTestCase : KotlinDescriptorTestCaseWithStepping() { private companion object { val DEFAULT_CHAIN_SELECTOR = ChainSelector.byIndex(0) } private lateinit var traceChecker: StreamTraceChecker override fun initOutputChecker(): OutputChecker { traceChecker = StreamTraceChecker(this) return super.initOutputChecker() } abstract val librarySupportProvider: LibrarySupportProvider override fun doMultiFileTest(files: TestFiles, preferences: DebuggerPreferences) { // Sequence expressions are verbose. Disable expression logging for sequence debugger KotlinEvaluator.LOG_COMPILATIONS = false val session = debuggerSession.xDebugSession ?: kotlin.test.fail("XDebugSession is null") assertNotNull(session) val completed = AtomicBoolean(false) val positionResolver = getPositionResolver() val chainBuilder = getChainBuilder() val resultInterpreter = getResultInterpreter() val expressionBuilder = getExpressionBuilder() val chainSelector = DEFAULT_CHAIN_SELECTOR session.addSessionListener(object : XDebugSessionListener { override fun sessionPaused() { if (completed.getAndSet(true)) { resume() return } try { sessionPausedImpl() } catch (t: Throwable) { println("Exception caught: $t, ${t.message}", ProcessOutputTypes.SYSTEM) t.printStackTrace() resume() } } private fun sessionPausedImpl() { printContext(debugProcess.debuggerContext) val chain = ApplicationManager.getApplication().runReadAction( Computable<StreamChain> { val elementAtBreakpoint = positionResolver.getNearestElementToBreakpoint(session) val chains = if (elementAtBreakpoint == null) null else chainBuilder.build(elementAtBreakpoint) if (chains.isNullOrEmpty()) null else chainSelector.select(chains) }) if (chain == null) { complete(null, null, null, FailureReason.CHAIN_CONSTRUCTION) return } EvaluateExpressionTracer(session, expressionBuilder, resultInterpreter).trace(chain, object : TracingCallback { override fun evaluated(result: TracingResult, context: EvaluationContextImpl) { complete(chain, result, null, null) } override fun evaluationFailed(traceExpression: String, message: String) { complete(chain, null, message, FailureReason.EVALUATION) } override fun compilationFailed(traceExpression: String, message: String) { complete(chain, null, message, FailureReason.COMPILATION) } }) } private fun complete(chain: StreamChain?, result: TracingResult?, error: String?, errorReason: FailureReason?) { try { if (error != null) { assertNotNull(errorReason) assertNotNull(chain) throw AssertionError(error) } else { assertNull(errorReason) handleSuccess(chain, result) } } catch (t: Throwable) { println("Exception caught: " + t + ", " + t.message, ProcessOutputTypes.SYSTEM) } finally { resume() } } private fun resume() { ApplicationManager.getApplication().invokeLater { session.resume() } } }, testRootDisposable) } private fun getPositionResolver(): DebuggerPositionResolver { return DebuggerPositionResolverImpl() } protected fun handleSuccess(chain: StreamChain?, result: TracingResult?) { kotlin.test.assertNotNull(chain) kotlin.test.assertNotNull(result) println(chain.text, ProcessOutputTypes.SYSTEM) val trace = result.trace traceChecker.checkChain(trace) val resolvedTrace = result.resolve(librarySupportProvider.librarySupport.resolverFactory) traceChecker.checkResolvedChain(resolvedTrace) } private fun getResultInterpreter(): TraceResultInterpreter { return TraceResultInterpreterImpl(librarySupportProvider.librarySupport.interpreterFactory) } private fun getChainBuilder(): StreamChainBuilder { return librarySupportProvider.chainBuilder } private fun getExpressionBuilder(): TraceExpressionBuilder { return librarySupportProvider.getExpressionBuilder(project) } protected enum class FailureReason { COMPILATION, EVALUATION, CHAIN_CONSTRUCTION } @FunctionalInterface protected interface ChainSelector { fun select(chains: List<StreamChain>): StreamChain companion object { fun byIndex(index: Int): ChainSelector { return object : ChainSelector { override fun select(chains: List<StreamChain>): StreamChain = chains[index] } } } } }
apache-2.0
933274056cd8c9e696062374d8f692f5
40.017964
158
0.649438
5.637037
false
true
false
false
iPoli/iPoli-android
app/src/main/java/io/ipoli/android/common/TimePickerDialogViewController.kt
1
3299
package io.ipoli.android.common import android.annotation.SuppressLint import android.os.Bundle import android.support.v7.app.AlertDialog import android.view.LayoutInflater import android.view.View import android.widget.TimePicker import io.ipoli.android.R import io.ipoli.android.common.datetime.Time import io.ipoli.android.common.redux.Action import io.ipoli.android.common.redux.BaseViewState import io.ipoli.android.common.view.BaseDialogController /** * Created by Polina Zhelyazkova <[email protected]> * on 6/1/18. */ sealed class TimePickerDialogAction : Action object TimePickerDialogReducer : BaseViewStateReducer<TimePickerDialogViewState>() { override val stateKey = key<TimePickerDialogViewState>() override fun reduce( state: AppState, subState: TimePickerDialogViewState, action: Action ): TimePickerDialogViewState { return subState } override fun defaultState() = TimePickerDialogViewState( type = TimePickerDialogViewState.StateType.LOADING ) } data class TimePickerDialogViewState( val type: StateType ) : BaseViewState() { enum class StateType { LOADING } } @Suppress("DEPRECATION") class TimePickerDialogViewController(args: Bundle? = null) : BaseDialogController(args) { private var time: Time? = null private var shouldUse24HourFormat: Boolean = false private lateinit var listener: (Time?) -> Unit private var showNeutral: Boolean = true private var onDismissListener: (() -> Unit)? = null constructor( time: Time? = null, shouldUse24HourFormat: Boolean, showNeutral: Boolean = false, listener: (Time?) -> Unit ) : this() { this.time = time this.showNeutral = showNeutral this.shouldUse24HourFormat = shouldUse24HourFormat this.listener = listener } @SuppressLint("InflateParams") override fun onCreateContentView(inflater: LayoutInflater, savedViewState: Bundle?): View { val view = inflater.inflate(R.layout.dialog_time_picker, null) (view as TimePicker).setIs24HourView(shouldUse24HourFormat) time?.let { view.currentHour = it.hours view.currentMinute = it.getMinutes() } return view } override fun onCreateDialog( dialogBuilder: AlertDialog.Builder, contentView: View, savedViewState: Bundle? ): AlertDialog { val builder = dialogBuilder .setCustomTitle(null) .setPositiveButton(R.string.dialog_ok) { _, _ -> listener( Time.at( (contentView as TimePicker).currentHour, contentView.currentMinute ) ) } .setNegativeButton(R.string.cancel, null) if (showNeutral) { builder.setNeutralButton(R.string.do_not_know) { _, _ -> listener(null) } } return builder.create() } override fun createHeaderView(inflater: LayoutInflater): View? = null fun setOnDismissListener(onDismiss: () -> Unit) { this.onDismissListener = onDismiss } override fun onDismiss() { onDismissListener?.invoke() } }
gpl-3.0
cad7c7a36e1b101649c853b79474fdd2
28.20354
95
0.651106
4.837243
false
false
false
false
cfieber/orca
orca-queue/src/main/kotlin/com/netflix/spinnaker/orca/q/handler/StartStageHandler.kt
1
7567
/* * Copyright 2017 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License") * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.spinnaker.orca.q.handler import com.fasterxml.jackson.databind.ObjectMapper import com.netflix.spectator.api.Registry import com.netflix.spinnaker.orca.ExecutionStatus.NOT_STARTED import com.netflix.spinnaker.orca.ExecutionStatus.RUNNING import com.netflix.spinnaker.orca.events.StageStarted import com.netflix.spinnaker.orca.exceptions.ExceptionHandler import com.netflix.spinnaker.orca.ext.* import com.netflix.spinnaker.orca.pipeline.StageDefinitionBuilderFactory import com.netflix.spinnaker.orca.pipeline.expressions.PipelineExpressionEvaluator import com.netflix.spinnaker.orca.pipeline.model.Execution.ExecutionType.PIPELINE import com.netflix.spinnaker.orca.pipeline.model.OptionalStageSupport import com.netflix.spinnaker.orca.pipeline.model.Stage import com.netflix.spinnaker.orca.pipeline.persistence.ExecutionRepository import com.netflix.spinnaker.orca.pipeline.util.ContextParameterProcessor import com.netflix.spinnaker.orca.pipeline.util.StageNavigator import com.netflix.spinnaker.orca.q.* import com.netflix.spinnaker.q.AttemptsAttribute import com.netflix.spinnaker.q.MaxAttemptsAttribute import com.netflix.spinnaker.q.Queue import org.springframework.beans.factory.annotation.Qualifier import org.springframework.beans.factory.annotation.Value import org.springframework.context.ApplicationEventPublisher import org.springframework.stereotype.Component import java.time.Clock import java.time.Duration import java.time.Instant import kotlin.collections.set @Component class StartStageHandler( override val queue: Queue, override val repository: ExecutionRepository, override val stageNavigator: StageNavigator, override val stageDefinitionBuilderFactory: StageDefinitionBuilderFactory, override val contextParameterProcessor: ContextParameterProcessor, @Qualifier("queueEventPublisher") private val publisher: ApplicationEventPublisher, private val exceptionHandlers: List<ExceptionHandler>, @Qualifier("mapper") private val objectMapper: ObjectMapper, private val clock: Clock, private val registry: Registry, @Value("\${queue.retry.delay.ms:15000}") retryDelayMs: Long ) : OrcaMessageHandler<StartStage>, StageBuilderAware, ExpressionAware, AuthenticationAware { private val retryDelay = Duration.ofMillis(retryDelayMs) override fun handle(message: StartStage) { message.withStage { stage -> if (stage.anyUpstreamStagesFailed()) { // this only happens in restart scenarios log.warn("Tried to start stage ${stage.id} but something upstream had failed (executionId: ${message.executionId})") queue.push(CompleteExecution(message)) } else if (stage.allUpstreamStagesComplete()) { if (stage.status != NOT_STARTED) { log.warn("Ignoring $message as stage is already ${stage.status}") } else if (stage.shouldSkip()) { queue.push(SkipStage(message)) } else if (stage.isAfterStartTimeExpiry()) { log.warn("Stage is being skipped because its start time is after TTL (stageId: ${stage.id}, executionId: ${message.executionId})") queue.push(SkipStage(stage)) } else { try { stage.withAuth { stage.plan() } stage.status = RUNNING stage.startTime = clock.millis() repository.storeStage(stage) stage.start() publisher.publishEvent(StageStarted(this, stage)) trackResult(stage) } catch(e: Exception) { val exceptionDetails = exceptionHandlers.shouldRetry(e, stage.name) if (exceptionDetails?.shouldRetry == true) { val attempts = message.getAttribute<AttemptsAttribute>()?.attempts ?: 0 log.warn("Error planning ${stage.type} stage for ${message.executionType}[${message.executionId}] (attempts: $attempts)") message.setAttribute(MaxAttemptsAttribute(40)) queue.push(message, retryDelay) } else { log.error("Error running ${stage.type} stage for ${message.executionType}[${message.executionId}]", e) stage.apply { context["exception"] = exceptionDetails context["beforeStagePlanningFailed"] = true } repository.storeStage(stage) queue.push(CompleteStage(message)) } } } } else { log.warn("Re-queuing $message as upstream stages are not yet complete") queue.push(message, retryDelay) } } } private fun trackResult(stage: Stage) { // We only want to record invocations of parent-level stages; not synthetics if (stage.parentStageId != null) { return } val id = registry.createId("stage.invocations") .withTag("type", stage.type) .withTag("application", stage.execution.application) .let { id -> // TODO rz - Need to check synthetics for their cloudProvider. stage.context["cloudProvider"]?.let { id.withTag("cloudProvider", it.toString()) } ?: id } registry.counter(id).increment() } override val messageType = StartStage::class.java private fun Stage.plan() { builder().let { builder -> builder.buildTasks(this) builder.buildBeforeStages(this) { it: Stage -> repository.addStage(it.withMergedContext()) } } } private fun Stage.start() { val beforeStages = firstBeforeStages() if (beforeStages.isEmpty()) { val task = firstTask() if (task == null) { // TODO: after stages are no longer planned at this point. We could skip this val afterStages = firstAfterStages() if (afterStages.isEmpty()) { queue.push(CompleteStage(this)) } else { afterStages.forEach { queue.push(StartStage(it)) } } } else { queue.push(StartTask(this, task.id)) } } else { beforeStages.forEach { queue.push(StartStage(it)) } } } private fun Stage.shouldSkip(): Boolean { if (this.execution.type != PIPELINE) { return false } val clonedContext = objectMapper.convertValue(this.context, Map::class.java) as Map<String, Any> val clonedStage = Stage(this.execution, this.type, clonedContext).also { it.refId = refId it.requisiteStageRefIds = requisiteStageRefIds it.syntheticStageOwner = syntheticStageOwner it.parentStageId = parentStageId } if (clonedStage.context.containsKey(PipelineExpressionEvaluator.SUMMARY)) { this.context.put(PipelineExpressionEvaluator.SUMMARY, clonedStage.context[PipelineExpressionEvaluator.SUMMARY]) } return OptionalStageSupport.isOptional(clonedStage.withMergedContext(), contextParameterProcessor) } private fun Stage.isAfterStartTimeExpiry(): Boolean = startTimeExpiry?.let { Instant.ofEpochMilli(it) }?.isBefore(clock.instant()) ?: false }
apache-2.0
869f3cae2cf6bd023f0fd4bb7bb3fd4a
38.411458
140
0.700278
4.723471
false
false
false
false
mmo5/mmo5
mmo5-server/src/test/java/com/mmo5/server/manager/BoardManagerV2Test.kt
1
4151
package com.mmo5.server.manager import com.mmo5.server.model.Position import com.mmo5.server.model.messages.PlayerMove import com.mmo5.server.model.messages.Winner import org.junit.Assert.* import org.junit.Test class BoardManagerV2Test { @Test fun winToRight() { val tested = BoardManagerV2(boardSize = 3, winSeq = 2) tested.updatePlayerMove(PlayerMove(1, Position(0, 0))) tested.updatePlayerMove(PlayerMove(1, Position(1, 0))) val winner = tested.checkWinner() validateWinner(setOf(Position(0, 0), Position(1, 0)), winner) } private fun validateWinner(winSet: Set<Position>, winner: Winner?) { if (winner == null) { fail() } else { assertEquals(1, winner.playerId) assertEquals(winSet, winner.positions.toSet()) } } @Test fun winToBottom() { val tested = BoardManagerV2(boardSize = 3, winSeq = 2) tested.updatePlayerMove(PlayerMove(1, Position(0, 0))) tested.updatePlayerMove(PlayerMove(1, Position(0, 1))) val winner = tested.checkWinner() validateWinner(setOf(Position(0, 0), Position(0, 1)), winner) } @Test fun winToTopRight() { val tested = BoardManagerV2(boardSize = 3, winSeq = 2) tested.updatePlayerMove(PlayerMove(1, Position(1, 0))) tested.updatePlayerMove(PlayerMove(1, Position(0, 1))) val winner = tested.checkWinner() validateWinner(setOf(Position(0, 1), Position(1, 0)), winner) } @Test fun winToBottomRight() { val tested = BoardManagerV2(boardSize = 3, winSeq = 2) tested.updatePlayerMove(PlayerMove(1, Position(0, 0))) tested.updatePlayerMove(PlayerMove(1, Position(1, 1))) val winner = tested.checkWinner() validateWinner(setOf(Position(0, 0), Position(1, 1)), winner) } @Test fun `winToRight - More Than 2`() { val tested = BoardManagerV2(boardSize = 3, winSeq = 2) tested.updatePlayerMove(PlayerMove(1, Position(0, 0))) tested.updatePlayerMove(PlayerMove(1, Position(1, 0))) tested.updatePlayerMove(PlayerMove(1, Position(2, 0))) val winner = tested.checkWinner() validateWinner(setOf(Position(0, 0), Position(1, 0), Position(2, 0)), winner) } @Test fun `winToRight - real size board`() { val tested = BoardManagerV2() tested.updatePlayerMove(PlayerMove(1, Position(0, 0))) tested.updatePlayerMove(PlayerMove(1, Position(1, 0))) tested.updatePlayerMove(PlayerMove(1, Position(2, 0))) tested.updatePlayerMove(PlayerMove(1, Position(3, 0))) tested.updatePlayerMove(PlayerMove(1, Position(4, 0))) val winner = tested.checkWinner() validateWinner(setOf(Position(0, 0), Position(1, 0), Position(2, 0), Position(3, 0), Position(4, 0)), winner) } @Test fun `no winner - real size board`() { val tested = BoardManagerV2() tested.updatePlayerMove(PlayerMove(1, Position(0, 0))) tested.updatePlayerMove(PlayerMove(1, Position(1, 0))) tested.updatePlayerMove(PlayerMove(1, Position(3, 0))) tested.updatePlayerMove(PlayerMove(1, Position(4, 0))) val winner = tested.checkWinner() assertTrue(winner == null) } @Test fun `win in complex shape`() { val tested = BoardManagerV2(boardSize = 3, winSeq = 2) tested.updatePlayerMove(PlayerMove(1, Position(0, 0))) tested.updatePlayerMove(PlayerMove(1, Position(1, 0))) tested.updatePlayerMove(PlayerMove(1, Position(0, 1))) val winner = tested.checkWinner() validateWinner(setOf(Position(0, 0), Position(1, 0), Position(0, 1)), winner) } @Test fun `validate winner with another player - was a bug`() { val tested = BoardManagerV2(boardSize = 3, winSeq = 2) tested.updatePlayerMove(PlayerMove(1, Position(0, 0))) tested.updatePlayerMove(PlayerMove(1, Position(1, 0))) tested.updatePlayerMove(PlayerMove(2, Position(1, 1))) val winner = tested.checkWinner() validateWinner(setOf(Position(0, 0), Position(1, 0)), winner) } }
apache-2.0
cad1a83b797bf6e68ce21698caeb24cb
40.929293
117
0.644905
3.587727
false
true
false
false
dkandalov/katas
kotlin/src/katas/kotlin/eightQueen/EightQueen23.kt
1
2658
package katas.kotlin.eightQueen import datsok.shouldEqual import org.junit.Test class EightQueen23 { @Test fun `find positions of queens on board in which they don't attack each other`() { Board(size = 0).doFindQueenPositions() shouldEqual listOf() Board(size = 1).doFindQueenPositions() shouldEqual listOf(Board(size = 1, queens = listOf(Queen(0, 0)))) Board(size = 2).doFindQueenPositions() shouldEqual listOf() Board(size = 3).doFindQueenPositions() shouldEqual listOf() Board(size = 4).doFindQueenPositions() shouldEqual listOf( Board(size = 4, queens = listOf(Queen(x = 0, y = 1), Queen(x = 1, y = 3), Queen(x = 2, y = 0), Queen(x = 3, y = 2))), Board(size = 4, queens = listOf(Queen(x = 0, y = 2), Queen(x = 1, y = 0), Queen(x = 2, y = 3), Queen(x = 3, y = 1))) ) Board(size = 8).doFindQueenPositions().size shouldEqual 92 Board(size = 10).doFindQueenPositions().size shouldEqual 724 Board(size = 20).findQueenPositions().take(1).toList() shouldEqual listOf( Board(size = 20, queens = listOf( Queen(x = 0, y = 0), Queen(x = 1, y = 2), Queen(x = 2, y = 4), Queen(x = 3, y = 1), Queen(x = 4, y = 3), Queen(x = 5, y = 12), Queen(x = 6, y = 14), Queen(x = 7, y = 11), Queen(x = 8, y = 17), Queen(x = 9, y = 19), Queen(x = 10, y = 16), Queen(x = 11, y = 8), Queen(x = 12, y = 15), Queen(x = 13, y = 18), Queen(x = 14, y = 7), Queen(x = 15, y = 9), Queen(x = 16, y = 6), Queen(x = 17, y = 13), Queen(x = 18, y = 5), Queen(x = 19, y = 10) )) ) } private fun Board.doFindQueenPositions(): List<Board> = findQueenPositions().toList() private fun Board.findQueenPositions(): Sequence<Board> { val nextMoves = sequence { val x = (queens.map { it.x }.maxOrNull() ?: -1) + 1 0.until(size) .map { y -> Queen(x, y) } .filter { isValidMove(it) } .forEach { yield(it) } } return nextMoves.flatMap { move -> val newBoard = copy(queens = queens + move) if (newBoard.queens.size == size) sequenceOf(newBoard) else newBoard.findQueenPositions() } } private fun Board.isValidMove(queen: Queen) = queens.size < size && queens.none { it.x == queen.x || it.y == queen.y } && queens.none { Math.abs(it.x - queen.x) == Math.abs(it.y - queen.y) } private data class Board(val size: Int, val queens: List<Queen> = emptyList()) private data class Queen(val x: Int, val y: Int) }
unlicense
fd332acddaae5467289fd1e3525df70a
48.240741
129
0.55079
3.210145
false
false
false
false
phylame/jem
scj/src/main/kotlin/jem/sci/Commands.kt
1
3249
/* * Copyright 2015-2017 Peng Wan <[email protected]> * * This file is part of Jem. * * 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 jem.sci import jem.Book import jem.asBook import jem.epm.ParserParam import mala.App import mala.App.tr import mala.cli.CDelegate import mala.cli.Command import mala.cli.ListFetcher interface InputProcessor { fun process(input: String, format: String): Boolean } interface ProcessorCommand : Command, InputProcessor { override fun execute(delegate: CDelegate): Int = SCI.processInputs(this) } interface BookConsumer : ProcessorCommand { val attaching get() = true fun consume(book: Book): Boolean override fun process(input: String, format: String): Boolean { return openBook(ParserParam(input, format, SCI.inArguments), attaching)?.let { try { consume(it) } finally { it.cleanup() } } == true } } class ViewBook : ListFetcher("w"), BookConsumer { @Suppress("UNCHECKED_CAST") override fun consume(book: Book): Boolean { viewBook(book, (SCI["w"] as? List<String>) ?: listOf("all"), SCISettings.viewSettings()) return true } } class ConvertBook : BookConsumer { override fun consume(book: Book): Boolean { val path = saveBook(outParam(book)) ?: return false println(tr("save.result", path)) return true } } class JoinBook : Command, InputProcessor { private val book = Book() override fun execute(delegate: CDelegate): Int { var code = SCI.processInputs(this) if (!book.isSection) { // no input books App.error("no book specified") return -1 } attachBook(book, true) val path = saveBook(outParam(book)) if (path != null) { println(tr("save.result", path)) } else { code = -1 } book.cleanup() return code } override fun process(input: String, format: String): Boolean { book += openBook(ParserParam(input, format, SCI.inArguments), false) ?: return false return true } } class ExtractBook : ListFetcher("x"), BookConsumer { override val attaching get() = false @Suppress("UNCHECKED_CAST") override fun consume(book: Book): Boolean { return (SCI["x"] as? List<String> ?: return false).mapNotNull(::parseIndices).mapNotNull { locateChapter(book, it) }.map { val b = it.asBook() attachBook(b, true) saveBook(outParam(b)) }.all { if (it != null) { println(tr("save.result", it)) true } else false } } }
apache-2.0
55889330ce57f25dcca44c99c9d59be8
27.5
98
0.620191
4.076537
false
false
false
false
ThePreviousOne/tachiyomi
app/src/main/java/eu/kanade/tachiyomi/data/download/DownloadManager.kt
1
17103
package eu.kanade.tachiyomi.data.download import android.content.Context import android.net.Uri import com.google.gson.Gson import com.google.gson.reflect.TypeToken import com.google.gson.stream.JsonReader import eu.kanade.tachiyomi.R import eu.kanade.tachiyomi.data.database.models.Chapter import eu.kanade.tachiyomi.data.database.models.Manga import eu.kanade.tachiyomi.data.download.model.Download import eu.kanade.tachiyomi.data.download.model.DownloadQueue import eu.kanade.tachiyomi.data.preference.PreferencesHelper import eu.kanade.tachiyomi.data.preference.getOrDefault import eu.kanade.tachiyomi.data.source.Source import eu.kanade.tachiyomi.data.source.SourceManager import eu.kanade.tachiyomi.data.source.model.Page import eu.kanade.tachiyomi.data.source.online.OnlineSource import eu.kanade.tachiyomi.util.* import rx.Observable import rx.Subscription import rx.android.schedulers.AndroidSchedulers import rx.schedulers.Schedulers import rx.subjects.BehaviorSubject import rx.subjects.PublishSubject import timber.log.Timber import uy.kohesive.injekt.Injekt import uy.kohesive.injekt.api.get import java.io.File import java.io.FileReader import java.util.* class DownloadManager( private val context: Context, private val sourceManager: SourceManager = Injekt.get(), private val preferences: PreferencesHelper = Injekt.get() ) { private val gson = Gson() private val downloadsQueueSubject = PublishSubject.create<List<Download>>() val runningSubject = BehaviorSubject.create<Boolean>() private var downloadsSubscription: Subscription? = null val downloadNotifier by lazy { DownloadNotifier(context) } private val threadsSubject = BehaviorSubject.create<Int>() private var threadsSubscription: Subscription? = null val queue = DownloadQueue() val imageFilenameRegex = "[^\\sa-zA-Z0-9.-]".toRegex() val PAGE_LIST_FILE = "index.json" @Volatile var isRunning: Boolean = false private set private fun initializeSubscriptions() { downloadsSubscription?.unsubscribe() threadsSubscription = preferences.downloadThreads().asObservable() .subscribe { threadsSubject.onNext(it) downloadNotifier.multipleDownloadThreads = it > 1 } downloadsSubscription = downloadsQueueSubject.flatMap { Observable.from(it) } .lift(DynamicConcurrentMergeOperator<Download, Download>({ downloadChapter(it) }, threadsSubject)) .onBackpressureBuffer() .observeOn(AndroidSchedulers.mainThread()) .subscribe({ // Delete successful downloads from queue if (it.status == Download.DOWNLOADED) { // remove downloaded chapter from queue queue.del(it) downloadNotifier.onProgressChange(queue) } if (areAllDownloadsFinished()) { DownloadService.stop(context) } }, { error -> DownloadService.stop(context) Timber.e(error) downloadNotifier.onError(error.message) }) if (!isRunning) { isRunning = true runningSubject.onNext(true) } } fun destroySubscriptions() { if (isRunning) { isRunning = false runningSubject.onNext(false) } if (downloadsSubscription != null) { downloadsSubscription?.unsubscribe() downloadsSubscription = null } if (threadsSubscription != null) { threadsSubscription?.unsubscribe() } } // Create a download object for every chapter and add them to the downloads queue fun downloadChapters(manga: Manga, chapters: List<Chapter>) { val source = sourceManager.get(manga.source) as? OnlineSource ?: return // Add chapters to queue from the start val sortedChapters = chapters.sortedByDescending { it.source_order } // Used to avoid downloading chapters with the same name val addedChapters = ArrayList<String>() val pending = ArrayList<Download>() for (chapter in sortedChapters) { if (addedChapters.contains(chapter.name)) continue addedChapters.add(chapter.name) val download = Download(source, manga, chapter) if (!prepareDownload(download)) { queue.add(download) pending.add(download) } } // Initialize queue size downloadNotifier.initialQueueSize = queue.size // Show notification downloadNotifier.onProgressChange(queue) if (isRunning) downloadsQueueSubject.onNext(pending) } // Public method to check if a chapter is downloaded fun isChapterDownloaded(source: Source, manga: Manga, chapter: Chapter): Boolean { val directory = getAbsoluteChapterDirectory(source, manga, chapter) if (!directory.exists()) return false val pages = getSavedPageList(source, manga, chapter) return isChapterDownloaded(directory, pages) } // Prepare the download. Returns true if the chapter is already downloaded private fun prepareDownload(download: Download): Boolean { // If the chapter is already queued, don't add it again for (queuedDownload in queue) { if (download.chapter.id == queuedDownload.chapter.id) return true } // Add the directory to the download object for future access download.directory = getAbsoluteChapterDirectory(download) // If the directory doesn't exist, the chapter isn't downloaded. if (!download.directory.exists()) { return false } // If the page list doesn't exist, the chapter isn't downloaded val savedPages = getSavedPageList(download) ?: return false // Add the page list to the download object for future access download.pages = savedPages // If the number of files matches the number of pages, the chapter is downloaded. // We have the index file, so we check one file more return isChapterDownloaded(download.directory, download.pages) } // Check that all the images are downloaded private fun isChapterDownloaded(directory: File, pages: List<Page>?): Boolean { return pages != null && !pages.isEmpty() && pages.size + 1 == directory.listFiles().size } // Download the entire chapter private fun downloadChapter(download: Download): Observable<Download> { DiskUtils.createDirectory(download.directory) val pageListObservable: Observable<List<Page>> = if (download.pages == null) // Pull page list from network and add them to download object download.source.fetchPageListFromNetwork(download.chapter) .doOnNext { pages -> download.pages = pages savePageList(download) } else // Or if the page list already exists, start from the file Observable.just(download.pages) return Observable.defer { pageListObservable .doOnNext { pages -> download.downloadedImages = 0 download.status = Download.DOWNLOADING } // Get all the URLs to the source images, fetch pages if necessary .flatMap { download.source.fetchAllImageUrlsFromPageList(it) } // Start downloading images, consider we can have downloaded images already .concatMap { page -> getOrDownloadImage(page, download) } // Do when page is downloaded. .doOnNext { downloadNotifier.onProgressChange(download, queue) } // Do after download completes .doOnCompleted { onDownloadCompleted(download) } .toList() .map { pages -> download } // If the page list threw, it will resume here .onErrorResumeNext { error -> download.status = Download.ERROR downloadNotifier.onError(error.message, download.chapter.name) Observable.just(download) } }.subscribeOn(Schedulers.io()) } // Get the image from the filesystem if it exists or download from network private fun getOrDownloadImage(page: Page, download: Download): Observable<Page> { // If the image URL is empty, do nothing if (page.imageUrl == null) return Observable.just(page) val filename = getImageFilename(page) val imagePath = File(download.directory, filename) // If the image is already downloaded, do nothing. Otherwise download from network val pageObservable = if (isImageDownloaded(imagePath)) Observable.just(page) else downloadImage(page, download.source, download.directory, filename) return pageObservable // When the image is ready, set image path, progress (just in case) and status .doOnNext { page.imagePath = imagePath.absolutePath page.progress = 100 download.downloadedImages++ page.status = Page.READY } // Mark this page as error and allow to download the remaining .onErrorResumeNext { page.progress = 0 page.status = Page.ERROR Observable.just(page) } } // Save image on disk private fun downloadImage(page: Page, source: OnlineSource, directory: File, filename: String): Observable<Page> { page.status = Page.DOWNLOAD_IMAGE return source.imageResponse(page) .map { val file = File(directory, filename) try { file.parentFile.mkdirs() it.body().source().saveTo(file.outputStream()) } catch (e: Exception) { it.close() file.delete() throw e } page } // Retry 3 times, waiting 2, 4 and 8 seconds between attempts. .retryWhen(RetryWithDelay(3, { (2 shl it - 1) * 1000 }, Schedulers.trampoline())) } // Public method to get the image from the filesystem. It does NOT provide any way to download the image fun getDownloadedImage(page: Page, chapterDir: File): Observable<Page> { if (page.imageUrl == null) { page.status = Page.ERROR return Observable.just(page) } val imagePath = File(chapterDir, getImageFilename(page)) // When the image is ready, set image path, progress (just in case) and status if (isImageDownloaded(imagePath)) { page.imagePath = imagePath.absolutePath page.progress = 100 page.status = Page.READY } else { page.status = Page.ERROR } return Observable.just(page) } // Get the filename for an image given the page private fun getImageFilename(page: Page): String { val url = page.imageUrl val number = String.format("%03d", page.pageNumber + 1) // Try to preserve file extension return when { UrlUtil.isJpg(url) -> "$number.jpg" UrlUtil.isPng(url) -> "$number.png" UrlUtil.isGif(url) -> "$number.gif" else -> Uri.parse(url).lastPathSegment.replace(imageFilenameRegex, "_") } } private fun isImageDownloaded(imagePath: File): Boolean { return imagePath.exists() } // Called when a download finishes. This doesn't mean the download was successful, so we check it private fun onDownloadCompleted(download: Download) { checkDownloadIsSuccessful(download) savePageList(download) } private fun checkDownloadIsSuccessful(download: Download) { var actualProgress = 0 var status = Download.DOWNLOADED // If any page has an error, the download result will be error for (page in download.pages!!) { actualProgress += page.progress if (page.status != Page.READY) { status = Download.ERROR downloadNotifier.onError(context.getString(R.string.download_notifier_page_ready_error), download.chapter.name) } } // Ensure that the chapter folder has all the images if (!isChapterDownloaded(download.directory, download.pages)) { status = Download.ERROR downloadNotifier.onError(context.getString(R.string.download_notifier_page_error), download.chapter.name) } download.totalProgress = actualProgress download.status = status } // Return the page list from the chapter's directory if it exists, null otherwise fun getSavedPageList(source: Source, manga: Manga, chapter: Chapter): List<Page>? { val chapterDir = getAbsoluteChapterDirectory(source, manga, chapter) val pagesFile = File(chapterDir, PAGE_LIST_FILE) return try { JsonReader(FileReader(pagesFile)).use { val collectionType = object : TypeToken<List<Page>>() {}.type gson.fromJson(it, collectionType) } } catch (e: Exception) { null } } // Shortcut for the method above private fun getSavedPageList(download: Download): List<Page>? { return getSavedPageList(download.source, download.manga, download.chapter) } // Save the page list to the chapter's directory fun savePageList(source: Source, manga: Manga, chapter: Chapter, pages: List<Page>) { val chapterDir = getAbsoluteChapterDirectory(source, manga, chapter) val pagesFile = File(chapterDir, PAGE_LIST_FILE) pagesFile.outputStream().use { try { it.write(gson.toJson(pages).toByteArray()) it.flush() } catch (error: Exception) { Timber.e(error) } } } // Shortcut for the method above private fun savePageList(download: Download) { savePageList(download.source, download.manga, download.chapter, download.pages!!) } fun getAbsoluteMangaDirectory(source: Source, manga: Manga): File { val mangaRelativePath = source.toString() + File.separator + manga.title.replace("[^\\sa-zA-Z0-9.-]".toRegex(), "_") return File(preferences.downloadsDirectory().getOrDefault(), mangaRelativePath) } // Get the absolute path to the chapter directory fun getAbsoluteChapterDirectory(source: Source, manga: Manga, chapter: Chapter): File { val chapterRelativePath = chapter.name.replace("[^\\sa-zA-Z0-9.-]".toRegex(), "_") return File(getAbsoluteMangaDirectory(source, manga), chapterRelativePath) } // Shortcut for the method above private fun getAbsoluteChapterDirectory(download: Download): File { return getAbsoluteChapterDirectory(download.source, download.manga, download.chapter) } fun deleteChapter(source: Source, manga: Manga, chapter: Chapter) { val path = getAbsoluteChapterDirectory(source, manga, chapter) DiskUtils.deleteFiles(path) } fun areAllDownloadsFinished(): Boolean { for (download in queue) { if (download.status <= Download.DOWNLOADING) return false } return true } fun startDownloads(): Boolean { if (queue.isEmpty()) return false if (downloadsSubscription == null || downloadsSubscription!!.isUnsubscribed) initializeSubscriptions() val pending = ArrayList<Download>() for (download in queue) { if (download.status != Download.DOWNLOADED) { if (download.status != Download.QUEUE) download.status = Download.QUEUE pending.add(download) } } downloadsQueueSubject.onNext(pending) return !pending.isEmpty() } fun stopDownloads(errorMessage: String? = null) { destroySubscriptions() for (download in queue) { if (download.status == Download.DOWNLOADING) { download.status = Download.ERROR } } errorMessage?.let { downloadNotifier.onError(it) } } fun clearQueue() { queue.clear() downloadNotifier.onClear() } }
apache-2.0
6fb2ae866960c979458d6bfdf7ef68b3
37.006667
127
0.611647
5.091694
false
false
false
false
jmfayard/skripts
kotlin/man.kt
1
2160
#!/usr/bin/env kotlin-script.sh package man import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.channels.Channel import kotlinx.coroutines.channels.ReceiveChannel import kotlinx.coroutines.channels.produce import kotlinx.coroutines.runBlocking import okio.Buffer import org.zeroturnaround.exec.ProcessExecutor import kotlin.coroutines.CoroutineContext fun main(args: Array<String>) = runBlocking { if (args.size < 2) { println("Usage: $ main.kt ls -l") System.exit(1) return@runBlocking } val (command, option) = args println("Parsing $ man $command $option") val producer = executeBashCommand(coroutineContext, "man", command) searchForOption(option, producer) } suspend fun searchForOption(option: String, producer: ReceiveChannel<String>) { var foundBefore = false for (line in producer) { val words = line.splitToWords() val tries = listOf(words.getOrNull(0), words.getOrNull(1)) val foundNow = tries.any { it?.startsWith(option) == true } val hasArgument = tries.any { it?.startsWith("-") == true } if (foundBefore && hasArgument) break foundBefore = foundBefore or foundNow if (foundBefore && line.isNotBlank()) println(line) } } suspend fun CoroutineScope.executeBashCommand(context: CoroutineContext, command: String, vararg args: String) = produce<String>(context, Channel.UNLIMITED) { val allArgs = arrayOf(command, *args) Buffer().use { buffer -> ProcessExecutor().command(*allArgs) .redirectOutput(buffer.outputStream()) .setMessageLogger { _, _, _ -> } .execute() while (!buffer.exhausted()) { val line = buffer.readUtf8Line() ?: break channel.send(line) } } } private fun String.splitToWords(): List<String> { var line = this.trim() line = line.filterIndexed { i, c -> if (i == 0) return@filterIndexed true c != '\b' && line[i - 1] != '\b' } val words = line.split(' ', '\t', ',') return words.filter { it.isNotBlank() } }
apache-2.0
99c3c1f08bab3ee72d2595b1be784f4a
32.75
112
0.637037
4.16185
false
false
false
false
paplorinc/intellij-community
plugins/svn4idea/src/org/jetbrains/idea/svn/actions/MarkTreeConflictResolvedAction.kt
2
3938
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.idea.svn.actions import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.progress.ProgressIndicator import com.intellij.openapi.progress.Task import com.intellij.openapi.project.DumbAwareAction import com.intellij.openapi.ui.Messages import com.intellij.openapi.vcs.AbstractVcsHelper import com.intellij.openapi.vcs.FilePath import com.intellij.openapi.vcs.VcsDataKeys import com.intellij.openapi.vcs.VcsException import com.intellij.openapi.vcs.changes.ChangesUtil.getAfterPath import com.intellij.openapi.vcs.changes.ChangesUtil.getBeforePath import com.intellij.openapi.vcs.changes.VcsDirtyScopeManager import com.intellij.openapi.vcs.changes.ui.ChangesListView import org.jetbrains.idea.svn.* import org.jetbrains.idea.svn.api.Depth private fun getConflict(e: AnActionEvent): Conflict? { val changes = e.getData(VcsDataKeys.CHANGE_LEAD_SELECTION) val locallyDeletedChanges = e.getData(ChangesListView.LOCALLY_DELETED_CHANGES) if (locallyDeletedChanges.isNullOrEmpty()) { return (changes?.singleOrNull() as? ConflictedSvnChange)?.let { ChangeConflict(it) } } if (changes.isNullOrEmpty()) { return (locallyDeletedChanges.singleOrNull() as? SvnLocallyDeletedChange)?.let { LocallyDeletedChangeConflict(it) } } return null } class MarkTreeConflictResolvedAction : DumbAwareAction() { override fun update(e: AnActionEvent) { val project = e.project val conflict = getConflict(e) val enabled = project != null && conflict?.conflictState?.isTree == true e.presentation.isEnabledAndVisible = enabled } override fun actionPerformed(e: AnActionEvent) { val project = e.project!! val conflict = getConflict(e)!! val markText = SvnBundle.message("action.mark.tree.conflict.resolved.confirmation.title") val result = Messages.showYesNoDialog(project, SvnBundle.message("action.mark.tree.conflict.resolved.confirmation.text"), markText, Messages.getQuestionIcon()) if (result == Messages.YES) { object : Task.Backgroundable(project, markText, true) { private var exception: VcsException? = null override fun run(indicator: ProgressIndicator) { val path = conflict.path val vcs = SvnVcs.getInstance(project) try { vcs.getFactory(path.ioFile).createConflictClient().resolve(path.ioFile, Depth.EMPTY, false, false, true) } catch (e: VcsException) { exception = e } VcsDirtyScopeManager.getInstance(project).filePathsDirty(conflict.getPathsToRefresh(), null) } override fun onSuccess() { if (exception != null) { AbstractVcsHelper.getInstance(project).showError(exception, markText) } } }.queue() } } } private interface Conflict { val path: FilePath val conflictState: ConflictState fun getPathsToRefresh(): Collection<FilePath> } private class ChangeConflict(val change: ConflictedSvnChange) : Conflict { override val path: FilePath get() = change.treeConflictMarkHolder override val conflictState: ConflictState get() = change.conflictState override fun getPathsToRefresh(): Collection<FilePath> { val beforePath = getBeforePath(change) val afterPath = getAfterPath(change) val isAddMoveRename = beforePath == null || change.isMoved || change.isRenamed return listOfNotNull(beforePath, if (isAddMoveRename) afterPath else null) } } private class LocallyDeletedChangeConflict(val change: SvnLocallyDeletedChange) : Conflict { override val path: FilePath get() = change.path override val conflictState: ConflictState get() = change.conflictState override fun getPathsToRefresh(): Collection<FilePath> = listOf(path) }
apache-2.0
ad40f17d5ce8b9294fa59851aec82a32
37.617647
140
0.73743
4.395089
false
false
false
false
apoi/quickbeer-next
app/src/main/java/quickbeer/android/util/ktx/ZonedDateTimeExt.kt
2
2220
/* * This file is part of QuickBeer. * Copyright (C) 2017 Antti Poikela <[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 quickbeer.android.util.ktx import org.threeten.bp.Instant import org.threeten.bp.ZoneId import org.threeten.bp.ZoneOffset import org.threeten.bp.ZonedDateTime import org.threeten.bp.format.DateTimeFormatter import org.threeten.bp.format.FormatStyle import org.threeten.bp.temporal.ChronoUnit fun ZonedDateTime?.orEpoch(): ZonedDateTime { return if (isValidDate()) this!! else ZonedDateTime.ofInstant(Instant.ofEpochSecond(0), ZoneOffset.UTC) } fun ZonedDateTime?.isValidDate(): Boolean { return this != null && this.toEpochSecond() > 0 } fun ZonedDateTime?.within(millis: Long): Boolean { val compare = ZonedDateTime.now().minus(millis, ChronoUnit.MILLIS) return this != null && this > compare } fun ZonedDateTime?.formatDateTime(template: String): String { val localTime = orEpoch().withZoneSameInstant(ZoneId.systemDefault()) return String.format( template, localTime.format(DateTimeFormatter.ofLocalizedDate(FormatStyle.SHORT)), localTime.format(DateTimeFormatter.ofLocalizedTime(FormatStyle.SHORT)) ) } fun ZonedDateTime?.formatDate(): String { return orEpoch() .withZoneSameInstant(ZoneId.systemDefault()) .format(DateTimeFormatter.ofLocalizedDate(FormatStyle.MEDIUM)) } fun ZonedDateTime?.orLater(other: ZonedDateTime?): ZonedDateTime? { return when { this == null -> other other == null -> this this > other -> this else -> other } }
gpl-3.0
5d4eb67a7f4fe9c8582e7eaaa78450fd
33.6875
79
0.730631
4.294004
false
false
false
false
google/intellij-community
platform/build-scripts/src/org/jetbrains/intellij/build/impl/ToolboxLiteGen.kt
4
2842
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package org.jetbrains.intellij.build.impl import com.intellij.openapi.util.SystemInfo import com.intellij.util.SystemProperties import com.intellij.util.execution.ParametersListUtil import org.codehaus.groovy.runtime.ProcessGroovyMethods import org.jetbrains.intellij.build.BuildMessages import org.jetbrains.intellij.build.dependencies.BuildDependenciesCommunityRoot import org.jetbrains.intellij.build.dependencies.BuildDependenciesDownloader import org.jetbrains.intellij.build.dependencies.BuildDependenciesExtractOptions import org.jetbrains.intellij.build.dependencies.BuildDependenciesManualRunOnly import java.io.OutputStream import java.net.URI import java.nio.file.Files import java.nio.file.Path internal object ToolboxLiteGen { private fun downloadToolboxLiteGen(communityRoot: BuildDependenciesCommunityRoot?, liteGenVersion: String): Path { val liteGenUri = URI("https://repo.labs.intellij.net/toolbox/lite-gen/lite-gen-$liteGenVersion.zip") val zip = BuildDependenciesDownloader.downloadFileToCacheLocation(communityRoot, liteGenUri) return BuildDependenciesDownloader.extractFileToCacheLocation(communityRoot, zip, BuildDependenciesExtractOptions.STRIP_ROOT) } fun runToolboxLiteGen(communityRoot: BuildDependenciesCommunityRoot?, messages: BuildMessages, liteGenVersion: String, vararg args: String) { check(SystemInfo.isUnix) { "Currently, lite gen runs only on Unix" } val liteGenPath = downloadToolboxLiteGen(communityRoot, liteGenVersion) messages.info("Toolbox LiteGen is at $liteGenPath") val binPath = liteGenPath.resolve("bin/lite") check(Files.isExecutable(binPath)) { "File at \'$binPath\' is missing or not executable" } val command: MutableList<String?> = ArrayList() command.add(binPath.toString()) command.addAll(args) messages.info("Running " + ParametersListUtil.join(command)) val processBuilder = ProcessBuilder(command) processBuilder.directory(liteGenPath.toFile()) processBuilder.environment()["JAVA_HOME"] = SystemProperties.getJavaHome() val process = processBuilder.start() // todo get rid of ProcessGroovyMethods ProcessGroovyMethods.consumeProcessOutputStream(process, System.out as OutputStream) ProcessGroovyMethods.consumeProcessErrorStream(process, System.err as OutputStream) val rc = process.waitFor() check(rc == 0) { "\'${command.joinToString(separator = " ")}\' exited with exit code $rc" } } @JvmStatic fun main(args: Array<String>) { val path = downloadToolboxLiteGen(BuildDependenciesManualRunOnly.getCommunityRootFromWorkingDirectory(), "1.2.1553") println("litegen is at $path") } }
apache-2.0
c6d506976ec0c209a700c252e2d811fa
51.648148
129
0.775158
4.808799
false
false
false
false
JetBrains/intellij-community
platform/webSymbols/src/com/intellij/webSymbols/documentation/impl/WebSymbolDocumentationTargetImpl.kt
1
6747
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.webSymbols.documentation.impl import com.intellij.lang.documentation.DocumentationMarkup import com.intellij.lang.documentation.DocumentationResult import com.intellij.lang.documentation.DocumentationTarget import com.intellij.model.Pointer import com.intellij.openapi.util.text.StringUtil import com.intellij.ui.scale.ScaleContext import com.intellij.ui.scale.ScaleType import com.intellij.util.IconUtil import com.intellij.util.ui.UIUtil import com.intellij.webSymbols.WebSymbol import com.intellij.webSymbols.WebSymbolOrigin import com.intellij.webSymbols.WebSymbolsBundle import com.intellij.webSymbols.documentation.WebSymbolDocumentation import com.intellij.webSymbols.documentation.WebSymbolDocumentationTarget import com.intellij.webSymbols.impl.scaleToHeight import java.awt.Image import java.awt.image.BufferedImage import javax.swing.Icon internal class WebSymbolDocumentationTargetImpl(override val symbol: WebSymbol) : WebSymbolDocumentationTarget { override fun createPointer(): Pointer<out DocumentationTarget> { val pointer = symbol.createPointer() return Pointer<DocumentationTarget> { pointer.dereference()?.let { WebSymbolDocumentationTargetImpl(it) } } } companion object { fun buildDocumentation(origin: WebSymbolOrigin, doc: WebSymbolDocumentation): DocumentationResult? { val url2ImageMap = mutableMapOf<String, Image>() @Suppress("HardCodedStringLiteral") val contents = StringBuilder() .appendDefinition(doc, url2ImageMap) .appendDescription(doc) .appendSections(doc) .appendFootnote(doc) .toString() .loadLocalImages(origin, url2ImageMap) return DocumentationResult.documentation(contents).images(url2ImageMap).externalUrl(doc.docUrl) } private fun StringBuilder.appendDefinition(doc: WebSymbolDocumentation, url2ImageMap: MutableMap<String, Image>): StringBuilder = append(DocumentationMarkup.DEFINITION_START) .also { doc.icon?.let { appendIcon(it, url2ImageMap).append("&nbsp;&nbsp;") } } .append(doc.definition) .append(DocumentationMarkup.DEFINITION_END) .append('\n') private fun StringBuilder.appendDescription(doc: WebSymbolDocumentation): StringBuilder = doc.description?.let { append(DocumentationMarkup.CONTENT_START).append('\n') .append(it).append('\n') .append(DocumentationMarkup.CONTENT_END) } ?: this private fun StringBuilder.appendSections(doc: WebSymbolDocumentation): StringBuilder = buildSections(doc).let { sections -> if (sections.isNotEmpty()) { append(DocumentationMarkup.SECTIONS_START) .append('\n') sections.entries.forEach { (name, value) -> append(DocumentationMarkup.SECTION_HEADER_START) .append(StringUtil.capitalize(name)) if (value.isNotBlank()) { if (!name.endsWith(":")) append(':') // Workaround misalignment of monospace font if (value.contains("<code")) { append("<code> </code>") } append(DocumentationMarkup.SECTION_SEPARATOR) .append(value) } append(DocumentationMarkup.SECTION_END) .append('\n') } append(DocumentationMarkup.SECTIONS_END) .append('\n') } this } private fun StringBuilder.appendFootnote(doc: WebSymbolDocumentation): StringBuilder = doc.footnote?.let { append(DocumentationMarkup.CONTENT_START) .append(it) .append(DocumentationMarkup.CONTENT_END) .append('\n') } ?: this private fun buildSections(doc: WebSymbolDocumentation): Map<String, String> = LinkedHashMap(doc.descriptionSections).also { sections -> if (doc.required) sections[WebSymbolsBundle.message("mdn.documentation.section.isRequired")] = "" if (doc.deprecated) sections[WebSymbolsBundle.message("mdn.documentation.section.status.Deprecated")] = "" if (doc.experimental) sections[WebSymbolsBundle.message("mdn.documentation.section.status.Experimental")] = "" doc.defaultValue?.let { sections[WebSymbolsBundle.message("mdn.documentation.section.defaultValue")] = "<p><code>$it</code>" } doc.library?.let { sections[WebSymbolsBundle.message("mdn.documentation.section.library")] = "<p>$it" } } private fun StringBuilder.appendIcon(icon: Icon, url2ImageMap: MutableMap<String, Image>): StringBuilder { // TODO adjust it to the actual component being used @Suppress("UndesirableClassUsage") val bufferedImage = BufferedImage(1, 1, BufferedImage.TYPE_INT_ARGB) val g = bufferedImage.createGraphics() g.font = UIUtil.getToolTipFont() val height = (g.fontMetrics.getStringBounds("a", g).height / ScaleContext.create().getScale(ScaleType.USR_SCALE)).toInt() g.dispose() val image = try { IconUtil.toBufferedImage(icon.scaleToHeight(height)) } catch (e: Exception) { // ignore return this } val url = "https://img${url2ImageMap.size}" url2ImageMap[url] = image val screenHeight = height * ScaleContext.create().getScale(ScaleType.SYS_SCALE) append("<img src='$url' height=\"$screenHeight\" width=\"${(screenHeight * icon.iconWidth) / icon.iconHeight}\" border=0 />") return this } private val imgSrcRegex = Regex("<img [^>]*src\\s*=\\s*['\"]([^'\"]+)['\"]") private fun String.loadLocalImages(origin: WebSymbolOrigin, url2ImageMap: MutableMap<String, Image>): String { val replaces = imgSrcRegex.findAll(this) .mapNotNull { it.groups[1] } .filter { !it.value.contains(':') } .mapNotNull { group -> origin.loadIcon(group.value) ?.let { IconUtil.toBufferedImage(it, true) } ?.let { val url = "https://img${url2ImageMap.size}" url2ImageMap[url] = it Pair(group.range, url) } } .sortedBy { it.first.first } .toList() if (replaces.isEmpty()) return this val result = StringBuilder() var lastIndex = 0 for (replace in replaces) { result.appendRange(this, lastIndex, replace.first.first) result.append(replace.second) lastIndex = replace.first.last + 1 } if (lastIndex < this.length) { result.appendRange(this, lastIndex, this.length) } return result.toString() } } }
apache-2.0
0e0aa70bb9cf982c86dc67e96c96a949
40.146341
134
0.668149
4.534274
false
false
false
false
Atsky/haskell-idea-plugin
plugin/src/org/jetbrains/haskell/debugger/protocol/FlowCommand.kt
1
4649
package org.jetbrains.haskell.debugger.protocol import org.jetbrains.haskell.debugger.parser.GHCiParser import java.util.Deque import org.jetbrains.haskell.debugger.parser.HsStackFrameInfo import org.jetbrains.haskell.debugger.utils.HaskellUtils import org.jetbrains.haskell.debugger.frames.HsDebuggerEvaluator import com.intellij.xdebugger.evaluation.XDebuggerEvaluator import com.intellij.xdebugger.frame.XValue import org.jetbrains.haskell.debugger.frames.HsDebugValue import com.intellij.notification.Notifications import com.intellij.notification.Notification import com.intellij.notification.NotificationType import org.jetbrains.haskell.debugger.frames.HsSuspendContext import org.jetbrains.haskell.debugger.frames.ProgramThreadInfo import org.json.simple.JSONObject import org.jetbrains.haskell.debugger.frames.HsHistoryFrame import org.jetbrains.haskell.debugger.parser.JSONConverter import org.jetbrains.haskell.debugger.procdebuggers.utils.DebugRespondent import org.jetbrains.haskell.debugger.procdebuggers.ProcessDebugger import org.jetbrains.haskell.debugger.breakpoints.HaskellLineBreakpointDescription /** * Base class for commands that continue program execution until reaching breakpoint or finish * (trace and continue commands) * * Created by vlad on 7/17/14. */ abstract class FlowCommand(callback: CommandCallback<HsStackFrameInfo?>?) : AbstractCommand<HsStackFrameInfo?>(callback) { override fun parseGHCiOutput(output: Deque<String?>): HsStackFrameInfo? = GHCiParser.tryParseStoppedAt(output) override fun parseJSONOutput(output: JSONObject): HsStackFrameInfo? = JSONConverter.stoppedAtFromJSON(output) class StandardFlowCallback(val debugger: ProcessDebugger, val debugRespondent: DebugRespondent) : CommandCallback<HsStackFrameInfo?>() { override fun execBeforeSending() = debugRespondent.resetHistoryStack() override fun execAfterParsing(result: HsStackFrameInfo?) { if (result != null) { if (result.filePosition == null) { setExceptionContext(result) return } val module = debugRespondent.getModuleByFile(result.filePosition.filePath) val breakpoint = debugRespondent.getBreakpointAt(module, result.filePosition.rawStartLine) val condition = breakpoint?.condition if (breakpoint != null && condition != null) { handleCondition(breakpoint, condition, result) } else { setContext(result, breakpoint) } } else { debugRespondent.traceFinished() } } private fun handleCondition(breakpoint: HaskellLineBreakpointDescription, condition: String, result: HsStackFrameInfo) { val evaluator = HsDebuggerEvaluator(debugger) evaluator.evaluate(condition, object : XDebuggerEvaluator.XEvaluationCallback { override fun errorOccurred(errorMessage: String) { val msg = "Condition \"$condition\" of breakpoint at line ${breakpoint.line}" + "cannot be evaluated, reason: $errorMessage" Notifications.Bus.notify(Notification("", "Wrong breakpoint condition", msg, NotificationType.WARNING)) setContext(result, breakpoint) } override fun evaluated(evalResult: XValue) { if (evalResult is HsDebugValue && evalResult.binding.typeName == HaskellUtils.HS_BOOLEAN_TYPENAME && evalResult.binding.value == HaskellUtils.HS_BOOLEAN_TRUE) { setContext(result, breakpoint) } else { debugger.resume() } } }, null) } private fun setExceptionContext(result: HsStackFrameInfo) { val frame = HsHistoryFrame(debugger, result) frame.obsolete = false debugRespondent.historyChange(frame, null) val context = HsSuspendContext(debugger, ProgramThreadInfo(null, "Main", result)) debugRespondent.exceptionReached(context) } private fun setContext(result: HsStackFrameInfo, breakpoint: HaskellLineBreakpointDescription?) { val frame = HsHistoryFrame(debugger, result) frame.obsolete = false debugger.history(HistoryCommand.DefaultHistoryCallback(debugger, debugRespondent, frame, breakpoint)) } } }
apache-2.0
1b24871d048098feb5f80ba4015ef5dc
45.029703
128
0.674769
5.307078
false
false
false
false
Atsky/haskell-idea-plugin
plugin/src/org/jetbrains/haskell/psi/reference/TypeReference.kt
1
1643
package org.jetbrains.haskell.psi.reference import org.jetbrains.haskell.psi.SomeId import com.intellij.psi.PsiReferenceBase import com.intellij.openapi.util.TextRange import com.intellij.psi.PsiElement import org.jetbrains.haskell.psi.Module import org.jetbrains.haskell.psi.TypeVariable import org.jetbrains.haskell.scope.ModuleScope import com.intellij.psi.ElementManipulator import org.jetbrains.haskell.psi.util.HaskellElementFactory /** * Created by atsky on 4/25/14. */ class TypeReference(val typeRef: TypeVariable) : PsiReferenceBase<TypeVariable>( typeRef, TextRange(0, typeRef.textRange!!.length)) { override fun resolve(): PsiElement? { val module = Module.findModule(element!!) if (module != null) { for (aType in ModuleScope(module).getVisibleDataDeclarations()) { if (aType.getDeclarationName() == typeRef.text) { return aType.getNameElement() } } for (aType in ModuleScope(module).getVisibleTypeSynonyms()) { if (aType.getDeclarationName() == typeRef.text) { return aType.getNameElement() } } } return null } override fun getVariants(): Array<Any> = arrayOf() override fun handleElementRename(newElementName: String?): PsiElement? { if (newElementName != null) { val qcon = HaskellElementFactory.createExpressionFromText(element.project, newElementName) element.firstChild.replace(qcon) return qcon } else { return null } } }
apache-2.0
cd1858a5256071f2ffcdae01533a3fe1
31.235294
102
0.647596
4.762319
false
false
false
false
Skatteetaten/boober
src/main/kotlin/no/skatteetaten/aurora/boober/utils/ConditionalOnPropertyMissingOrEmpty.kt
1
1360
package no.skatteetaten.aurora.boober.utils import org.springframework.context.annotation.Condition import org.springframework.context.annotation.ConditionContext import org.springframework.context.annotation.Conditional import org.springframework.core.type.AnnotatedTypeMetadata import java.lang.annotation.Retention import java.lang.annotation.RetentionPolicy @Target( AnnotationTarget.CLASS, AnnotationTarget.FILE, AnnotationTarget.FUNCTION, AnnotationTarget.PROPERTY_GETTER, AnnotationTarget.PROPERTY_SETTER ) @Retention(RetentionPolicy.RUNTIME) @Conditional(ConditionalOnPropertyMissingOrEmpty.OnPropertyNotEmptyCondition::class) annotation class ConditionalOnPropertyMissingOrEmpty(vararg val value: String) { class OnPropertyNotEmptyCondition : Condition { override fun matches(context: ConditionContext, metadata: AnnotatedTypeMetadata): Boolean { val properties: List<String?>? = metadata.getAnnotationAttributes(ConditionalOnPropertyMissingOrEmpty::class.java.name) ?.let { it["value"] as Array<*> }?.map { context.environment.getProperty(it as String) } return properties?.any { it == null || it == "false" } ?: true } } }
apache-2.0
72fba013ba90aeb9bc19b157571a255f
34.789474
102
0.696324
5.271318
false
false
false
false
allotria/intellij-community
plugins/changeReminder/src/com/jetbrains/changeReminder/plugin/UserSettings.kt
2
1312
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.jetbrains.changeReminder.plugin import com.intellij.openapi.Disposable import com.intellij.openapi.components.BaseState import com.intellij.openapi.components.SimplePersistentStateComponent import com.intellij.openapi.components.State import com.intellij.openapi.components.Storage import com.intellij.util.EventDispatcher import java.util.* @State(name = "ChangeReminder", storages = [Storage(file = "changeReminder.xml")]) internal class UserSettings : SimplePersistentStateComponent<UserSettingsState>(UserSettingsState()) { private val eventDispatcher = EventDispatcher.create(PluginStatusListener::class.java) var isPluginEnabled: Boolean get() = state.isPluginEnabled set(value) { state.isPluginEnabled = value eventDispatcher.multicaster.statusChanged(value) } fun addPluginStatusListener(listener: PluginStatusListener, parentDisposable: Disposable) { eventDispatcher.addListener(listener, parentDisposable) } interface PluginStatusListener : EventListener { fun statusChanged(isEnabled: Boolean) } } internal class UserSettingsState : BaseState() { var isPluginEnabled: Boolean by property(false) }
apache-2.0
90fc33a7bebde1e5ef099c1036fba468
37.617647
140
0.799543
4.805861
false
false
false
false
fboldog/anko
anko/library/robolectricTests/src/test/java/IntentForTest.kt
2
1195
package test import android.app.Activity import android.os.Bundle import org.jetbrains.anko.intentFor import org.junit.Test import org.junit.runner.RunWith import org.robolectric.Robolectric import org.robolectric.RobolectricGradleTestRunner import org.robolectric.annotation.Config open class IntentForTestActivity : Activity() { public override fun onCreate(savedInstanceState: Bundle?): Unit { super.onCreate(savedInstanceState) } } @RunWith(RobolectricGradleTestRunner::class) @Config(constants = BuildConfig::class) class IntentForTest { @Test fun test() { val activity = Robolectric.buildActivity(IntentForTestActivity::class.java).create().get() val intent1 = activity.intentFor<IntentForTestActivity>() assert(intent1.extras == null) val intent2 = activity.intentFor<IntentForTestActivity>( "one" to 1, "abc" to "ABC", "null" to null) val extras2 = intent2.extras!! assert(extras2.size() == 3) assert(extras2.get("one") == 1) assert(extras2.get("abc") == "ABC") assert(extras2.get("null") == null) println("[COMPLETE]") } }
apache-2.0
91d081beeffc6847df36083d5a6958ae
27.47619
98
0.674477
4.222615
false
true
false
false
VREMSoftwareDevelopment/WiFiAnalyzer
app/src/main/kotlin/com/vrem/wifianalyzer/navigation/NavigationGroup.kt
1
2152
/* * WiFiAnalyzer * Copyright (C) 2015 - 2022 VREM Software Development <[email protected]> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> */ package com.vrem.wifianalyzer.navigation import android.view.Menu enum class NavigationGroup(val navigationMenus: List<NavigationMenu>) { GROUP_FEATURE(listOf(NavigationMenu.ACCESS_POINTS, NavigationMenu.CHANNEL_RATING, NavigationMenu.CHANNEL_GRAPH, NavigationMenu.TIME_GRAPH)), GROUP_OTHER(listOf(NavigationMenu.EXPORT, NavigationMenu.CHANNEL_AVAILABLE, NavigationMenu.VENDORS, NavigationMenu.PORT_AUTHORITY)), GROUP_SETTINGS(listOf(NavigationMenu.SETTINGS, NavigationMenu.ABOUT)); fun next(navigationMenu: NavigationMenu): NavigationMenu { var index = navigationMenus.indexOf(navigationMenu) if (index < 0) { return navigationMenu } index++ if (index >= navigationMenus.size) { index = 0 } return navigationMenus[index] } fun previous(navigationMenu: NavigationMenu): NavigationMenu { var index = navigationMenus.indexOf(navigationMenu) if (index < 0) { return navigationMenu } index-- if (index < 0) { index = navigationMenus.size - 1 } return navigationMenus[index] } fun populateMenuItems(menu: Menu): Unit = navigationMenus.forEach { val menuItem = menu.add(ordinal, it.ordinal, it.ordinal, it.title) menuItem.setIcon(it.icon) } }
gpl-3.0
24460648af2beb841f8d13665226a080
36.77193
144
0.687268
4.569002
false
false
false
false
agoda-com/Kakao
kakao/src/main/kotlin/com/agoda/kakao/dialog/KAlertDialog.kt
1
1051
package com.agoda.kakao.dialog import android.app.AlertDialog import com.agoda.kakao.common.views.KBaseView import com.agoda.kakao.image.KImageView import com.agoda.kakao.text.KButton import com.agoda.kakao.text.KTextView /** * View for interact with default alert dialog * * @see AlertDialog */ class KAlertDialog : KBaseView<KAlertDialog>({ isRoot() }) { init { inRoot { isDialog() } } val positiveButton = KButton { withId(android.R.id.button1) } .also { it.inRoot { isDialog() } } val negativeButton = KButton { withId(android.R.id.button2) } .also { it.inRoot { isDialog() } } val neutralButton = KButton { withId(android.R.id.button3) } .also { it.inRoot { isDialog() } } val title = KTextView { withResourceName("alertTitle")} .also { it.inRoot { isDialog() } } val message = KTextView { withId(android.R.id.message) } .also { it.inRoot { isDialog() } } val icon = KImageView { withId(android.R.id.icon) } .also { it.inRoot { isDialog() } } }
apache-2.0
da4e486bb23cc1bc5f8097ab7dab2332
27.405405
65
0.649857
3.624138
false
false
false
false
code-helix/slatekit
src/lib/kotlin/slatekit-meta/src/main/kotlin/slatekit/meta/models/Model.kt
1
5488
/** * <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.meta.models import slatekit.utils.naming.Namer import slatekit.common.ext.orElse import slatekit.meta.Reflector import slatekit.meta.Schema import kotlin.reflect.KClass /** * Stores the schema of a data-model with properties. */ class Model( val name: String, val fullName: String, val dataType: KClass<*>? = null, val desc: String = "", tableName: String = "", modelFields: List<ModelField>? = null, val namer: Namer? = null ) { constructor(dataType: KClass<*>, tableName: String = "") : this(dataType.simpleName!!, dataType.qualifiedName!!, dataType, tableName = tableName) constructor(dataType: KClass<*>, fields: List<ModelField>, tableName: String = "") : this(dataType.simpleName!!, dataType.qualifiedName!!, dataType, tableName = tableName, modelFields = fields) /** * The name of the table */ val table = tableName.orElse(name) /** * gets the list of fields in this model or returns an emptylist if none * @return */ val fields: List<ModelField> = modelFields ?: listOf() /** * Lookup of field names to column names */ val lookup: Map<String, ModelField> = loadFields(fields) /** * The field that represents the id */ val idField: ModelField? = fields.find { p -> p.category == FieldCategory.Id } /** * whether there are any fields in the model * @return */ val any: Boolean get() = size > 0 /** * whether this model has an id field * @return */ val hasId: Boolean get() = idField != null /** * the number of fields in this model. * @return */ val size: Int get() = fields.size fun add(field: ModelField): Model { val newPropList = fields.plus(field) return Model(this.name, fullName, this.dataType, desc, table, newPropList) } companion object { inline fun <reified TId, reified T> of(builder: Schema<TId, T>.() -> Unit ): Model where TId : Comparable<TId>, T:Any { val schema = Schema<TId, T>(TId::class, T::class) builder(schema) return schema.model } fun <TId, T> of(idType:KClass<*>, tType:KClass<*>, builder: Schema<TId, T>.() -> Unit ): Model where TId : Comparable<TId>, T:Any { val schema = Schema<TId, T>(idType, tType) builder(schema) return schema.model } /** * Builds a schema ( Model ) from the Class/Type supplied. * NOTE: The mapper then works off the Model class for to/from mapping of data to model. * @param dataType * @return */ @JvmStatic fun load (dataType: KClass<*>, idFieldName: String? = null, namer: Namer? = null, table: String? = null): Model { val modelName = dataType.simpleName ?: "" val modelNameFull = dataType.qualifiedName ?: "" // Get Id val idFields = Reflector.getAnnotatedProps<Id>(dataType, Id::class) val idField = idFields.firstOrNull() // Now add all the fields. val matchedFields = Reflector.getAnnotatedProps<Field>(dataType, Field::class) // Loop through each field val withAnnos = matchedFields.filter { it.second != null } val fields = withAnnos.map { matchedField -> val modelField = ModelField.ofData(matchedField.first, matchedField.second!!, namer, idField == null, idFieldName) val finalModelField = if (!modelField.isBasicType()) { val model = load(modelField.dataCls, namer = namer) modelField.copy(model = model) } else modelField finalModelField } val allFields = when(idField) { null -> fields else -> mutableListOf(ModelField.ofId(idField.first, "", namer)).plus(fields) } return Model(modelName, modelNameFull, dataType, modelFields = allFields, namer = namer, tableName = table ?: modelName) } fun loadFields(modelFields: List<ModelField>):Map<String, ModelField> { val fields = modelFields.fold(mutableListOf<Pair<String, ModelField>>()) { acc, field -> when(field.model) { null -> acc.add(field.name to field) else -> { acc.add(field.name to field) field.model.fields.forEach { subField -> // Need to modify the field name and stored name here as "a_b" val subFieldName = field.name + "_" + subField.name val subFieldColumn = field.name + "_" + subField.storedName val subFieldFinal = subField.copy(storedName = subFieldColumn) acc.add(subFieldName to subFieldFinal) } } } acc }.toMap() return fields } } }
apache-2.0
7d02dbc6badcf3af6e8ae50e8658a5e0
34.406452
197
0.571793
4.393915
false
false
false
false
smmribeiro/intellij-community
plugins/gradle/tooling-proxy/src/org/jetbrains/plugins/gradle/tooling/proxy/ProgressEventConverter.kt
10
4372
// 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.gradle.tooling.proxy import org.gradle.tooling.Failure import org.gradle.tooling.events.* import org.gradle.tooling.events.task.* import org.gradle.tooling.model.UnsupportedMethodException import org.jetbrains.plugins.gradle.tooling.serialization.internal.adapter.events.* import org.jetbrains.plugins.gradle.tooling.serialization.internal.adapter.events.task.* import java.util.* class ProgressEventConverter { private val descriptorsMap = IdentityHashMap<OperationDescriptor, InternalOperationDescriptor>() fun convert(progressEvent: ProgressEvent): ProgressEvent = when (progressEvent) { is TaskStartEvent -> progressEvent.run { InternalTaskStartEvent(eventTime, displayName, convert(descriptor) as InternalTaskOperationDescriptor) } is TaskFinishEvent -> progressEvent.run { InternalTaskFinishEvent(eventTime, displayName, convert(descriptor) as InternalTaskOperationDescriptor, convert(result)) } is StatusEvent -> progressEvent.run { InternalStatusEvent(eventTime, displayName, convert(descriptor), total, progress, unit) } is StartEvent -> progressEvent.run { InternalStartEvent(eventTime, displayName, convert(descriptor)) } is FinishEvent -> progressEvent.run { InternalFinishEvent(eventTime, displayName, convert(descriptor), convert(result)) } else -> progressEvent } private fun convert(result: TaskOperationResult?): TaskOperationResult? { when (result) { null -> return null is TaskSuccessResult -> return result.run { InternalTaskSuccessResult(startTime, endTime, isUpToDate, isFromCache, taskExecutionDetails()) } is TaskFailureResult -> return result.run { InternalTaskFailureResult(startTime, endTime, failures?.map<Failure?, Failure?>(::convert), taskExecutionDetails()) } is TaskSkippedResult -> return result.run { InternalTaskSkippedResult(startTime, endTime, skipMessage) } else -> throw IllegalArgumentException("Unsupported task operation result ${result.javaClass}") } } private fun convert(result: OperationResult?): OperationResult? { when (result) { null -> return null is SuccessResult -> return result.run { InternalOperationSuccessResult(startTime, endTime) } is FailureResult -> return result.run { InternalOperationFailureResult(startTime, endTime, failures?.map<Failure?, Failure?>(::convert)) } else -> throw IllegalArgumentException("Unsupported operation result ${result.javaClass}") } } private fun TaskExecutionResult.taskExecutionDetails(): InternalTaskExecutionDetails? = try { InternalTaskExecutionDetails.of(isIncremental, executionReasons) } catch (e: UnsupportedMethodException) { InternalTaskExecutionDetails.unsupported() } private fun convert(failure: Failure?): InternalFailure? { return failure?.run { InternalFailure(message, description, causes?.map<Failure?, InternalFailure?>(::convert)) } } fun convert(operationDescriptor: OperationDescriptor?): InternalOperationDescriptor? { if (operationDescriptor == null) return null val id = if (operationDescriptor is org.gradle.tooling.internal.protocol.events.InternalOperationDescriptor) operationDescriptor.id.toString() else operationDescriptor.displayName return descriptorsMap.getOrPut(operationDescriptor, { when (operationDescriptor) { is TaskOperationDescriptor -> operationDescriptor.run { InternalTaskOperationDescriptor( id, name, displayName, convert(parent), taskPath, { mutableSetOf<OperationDescriptor>().apply { dependencies.mapNotNullTo(this) { convert(it) } } }, { convert(originPlugin) }) } else -> operationDescriptor.run { InternalOperationDescriptor(id, name, displayName, convert(parent)) } } }) } private fun convert(pluginIdentifier: PluginIdentifier?): PluginIdentifier? = when (pluginIdentifier) { null -> null is BinaryPluginIdentifier -> pluginIdentifier.run { InternalBinaryPluginIdentifier(displayName, className, pluginId) } is ScriptPluginIdentifier -> pluginIdentifier.run { InternalScriptPluginIdentifier(displayName, uri) } else -> null } }
apache-2.0
620b6ba5e09d6f84a080df3493621bcd
49.837209
183
0.750915
4.923423
false
false
false
false
jotomo/AndroidAPS
core/src/main/java/info/nightscout/androidaps/activities/ErrorHelperActivity.kt
1
1073
package info.nightscout.androidaps.activities import android.os.Bundle import info.nightscout.androidaps.core.R import info.nightscout.androidaps.dialogs.ErrorDialog import info.nightscout.androidaps.plugins.general.nsclient.NSUpload import info.nightscout.androidaps.utils.sharedPreferences.SP import javax.inject.Inject class ErrorHelperActivity : DialogAppCompatActivity() { @Inject lateinit var sp : SP @Inject lateinit var nsUpload: NSUpload @Override override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) val errorDialog = ErrorDialog() errorDialog.helperActivity = this errorDialog.status = intent.getStringExtra("status") errorDialog.sound = intent.getIntExtra("soundid", R.raw.error) errorDialog.title = intent.getStringExtra("title") errorDialog.show(supportFragmentManager, "Error") if (sp.getBoolean(R.string.key_ns_create_announcements_from_errors, true)) { nsUpload.uploadError(intent.getStringExtra("status")) } } }
agpl-3.0
561ad29d9a7fa7dc67a5ab8192535b0e
37.321429
84
0.743709
4.70614
false
false
false
false
jotomo/AndroidAPS
core/src/main/java/info/nightscout/androidaps/db/StaticInjector.kt
1
783
package info.nightscout.androidaps.db import dagger.android.AndroidInjector import dagger.android.HasAndroidInjector import java.lang.IllegalStateException import javax.inject.Inject import javax.inject.Singleton @Singleton class StaticInjector @Inject constructor( private val injector: HasAndroidInjector ) : HasAndroidInjector { companion object { private var instance : StaticInjector? = null @Deprecated("Only until DB is refactored") fun getInstance() : StaticInjector { if (instance == null) throw IllegalStateException("StaticInjector not initialized") return instance!! } } init { instance = this } override fun androidInjector(): AndroidInjector<Any> = injector.androidInjector() }
agpl-3.0
37e9b7705fd88d6fae4c79884be0e0f8
28.037037
95
0.720307
5.290541
false
false
false
false
mdaniel/intellij-community
platform/core-impl/src/com/intellij/ide/plugins/PluginLoadingResult.kt
1
6661
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. @file:Suppress("ReplaceGetOrSet", "ReplacePutWithAssignment") package com.intellij.ide.plugins import com.intellij.core.CoreBundle import com.intellij.openapi.extensions.PluginId import com.intellij.openapi.util.BuildNumber import com.intellij.util.PlatformUtils import com.intellij.util.lang.Java11Shim import com.intellij.util.text.VersionComparatorUtil import org.jetbrains.annotations.ApiStatus import org.jetbrains.annotations.TestOnly import org.jetbrains.annotations.VisibleForTesting import java.util.* // https://www.jetbrains.org/intellij/sdk/docs/basics/getting_started/plugin_compatibility.html // If a plugin does not include any module dependency tags in its plugin.xml, // it's assumed to be a legacy plugin and is loaded only in IntelliJ IDEA. @ApiStatus.Internal class PluginLoadingResult(private val checkModuleDependencies: Boolean = !PlatformUtils.isIntelliJ()) { private val incompletePlugins = HashMap<PluginId, IdeaPluginDescriptorImpl>() @JvmField val enabledPluginsById = HashMap<PluginId, IdeaPluginDescriptorImpl>() private val idMap = HashMap<PluginId, IdeaPluginDescriptorImpl>() @JvmField var duplicateModuleMap: MutableMap<PluginId, MutableList<IdeaPluginDescriptorImpl>>? = null private val pluginErrors = HashMap<PluginId, PluginLoadingError>() @VisibleForTesting @JvmField val shadowedBundledIds: MutableSet<PluginId> = Collections.newSetFromMap(HashMap()) @get:TestOnly val hasPluginErrors: Boolean get() = !pluginErrors.isEmpty() @get:TestOnly val enabledPlugins: List<IdeaPluginDescriptorImpl> get() = enabledPluginsById.entries.sortedBy { it.key }.map { it.value } internal fun copyPluginErrors(): MutableMap<PluginId, PluginLoadingError> = HashMap(pluginErrors) fun getIncompleteIdMap(): Map<PluginId, IdeaPluginDescriptorImpl> = incompletePlugins fun getIdMap(): Map<PluginId, IdeaPluginDescriptorImpl> = idMap private fun addIncompletePlugin(plugin: IdeaPluginDescriptorImpl, error: PluginLoadingError?) { // do not report if some compatible plugin were already added // no race condition here: plugins from classpath are loaded before and not in parallel to loading from plugin dir if (idMap.containsKey(plugin.pluginId)) { return } val existingIncompletePlugin = incompletePlugins.putIfAbsent(plugin.pluginId, plugin) if (existingIncompletePlugin != null && VersionComparatorUtil.compare(plugin.version, existingIncompletePlugin.version) > 0) { incompletePlugins.put(plugin.pluginId, plugin) if (error != null) { // force put pluginErrors.put(plugin.pluginId, error) } } else if (error != null) { pluginErrors.putIfAbsent(plugin.pluginId, error) } } fun addAll(descriptors: Iterable<IdeaPluginDescriptorImpl?>, overrideUseIfCompatible: Boolean, productBuildNumber: BuildNumber) { for (descriptor in descriptors) { if (descriptor != null) { add(descriptor, overrideUseIfCompatible, productBuildNumber) } } } private fun add(descriptor: IdeaPluginDescriptorImpl, overrideUseIfCompatible: Boolean, productBuildNumber: BuildNumber) { val pluginId = descriptor.pluginId descriptor.isIncomplete?.let { error -> addIncompletePlugin(descriptor, error.takeIf { !it.isDisabledError }) return } if (checkModuleDependencies && !descriptor.isBundled && descriptor.packagePrefix == null && !hasModuleDependencies(descriptor)) { addIncompletePlugin(descriptor, PluginLoadingError( plugin = descriptor, detailedMessageSupplier = { CoreBundle.message("plugin.loading.error.long.compatible.with.intellij.idea.only", descriptor.name) }, shortMessageSupplier = { CoreBundle.message("plugin.loading.error.short.compatible.with.intellij.idea.only") }, isNotifyUser = true )) return } // remove any error that occurred for plugin with the same `id` pluginErrors.remove(pluginId) incompletePlugins.remove(pluginId) val prevDescriptor = if (descriptor.onDemand) null else enabledPluginsById.put(pluginId, descriptor) if (prevDescriptor == null) { idMap.put(pluginId, descriptor) for (module in descriptor.modules) { checkAndAdd(descriptor, module) } return } if (prevDescriptor.isBundled || descriptor.isBundled) { shadowedBundledIds.add(pluginId) } if (PluginManagerCore.checkBuildNumberCompatibility(descriptor, productBuildNumber) == null && (overrideUseIfCompatible || VersionComparatorUtil.compare(descriptor.version, prevDescriptor.version) > 0)) { PluginManagerCore.getLogger().info("$descriptor overrides $prevDescriptor") idMap.put(pluginId, descriptor) return } else { enabledPluginsById.put(pluginId, prevDescriptor) return } } private fun checkAndAdd(descriptor: IdeaPluginDescriptorImpl, id: PluginId) { duplicateModuleMap?.get(id)?.let { duplicates -> duplicates.add(descriptor) return } val existingDescriptor = idMap.put(id, descriptor) ?: return // if duplicated, both are removed idMap.remove(id) if (duplicateModuleMap == null) { duplicateModuleMap = LinkedHashMap() } val list = ArrayList<IdeaPluginDescriptorImpl>(2) list.add(existingDescriptor) list.add(descriptor) duplicateModuleMap!!.put(id, list) } } // todo merge into PluginSetState? @ApiStatus.Internal class PluginManagerState internal constructor(@JvmField val pluginSet: PluginSet, disabledRequiredIds: Set<IdeaPluginDescriptorImpl>, effectiveDisabledIds: Set<IdeaPluginDescriptorImpl>) { @JvmField val effectiveDisabledIds: Set<PluginId> = Java11Shim.INSTANCE.copyOf(effectiveDisabledIds.mapTo(HashSet(effectiveDisabledIds.size), IdeaPluginDescriptorImpl::getPluginId)) @JvmField val disabledRequiredIds: Set<PluginId> = Java11Shim.INSTANCE.copyOf(disabledRequiredIds.mapTo(HashSet(disabledRequiredIds.size), IdeaPluginDescriptorImpl::getPluginId)) } internal fun hasModuleDependencies(descriptor: IdeaPluginDescriptorImpl): Boolean { for (dependency in descriptor.pluginDependencies) { val dependencyPluginId = dependency.pluginId if (PluginManagerCore.JAVA_PLUGIN_ID == dependencyPluginId || PluginManagerCore.JAVA_MODULE_ID == dependencyPluginId || PluginManagerCore.isModuleDependency(dependencyPluginId)) { return true } } return false }
apache-2.0
0ab65d1ac81aa98018e2bcdff41ed8e1
40.6375
138
0.742531
4.844364
false
false
false
false
kivensolo/UiUsingListView
module-Common/src/main/java/com/kingz/module/common/utils/RvUtils.kt
1
1044
package com.kingz.module.common.utils import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView /** * author:ZekeWang * date:2021/2/23 * description:RecyclerView 工具类 */ object RvUtils { /** * 平滑滚动到第1个元素 */ fun smoothScrollTop(rv: RecyclerView?) { if (rv != null) { val layoutManager: RecyclerView.LayoutManager? = rv.layoutManager if (layoutManager is LinearLayoutManager) { val linearLayoutManager: LinearLayoutManager = layoutManager val first: Int = linearLayoutManager.findFirstVisibleItemPosition() val last: Int = linearLayoutManager.findLastVisibleItemPosition() val visibleCount = last - first + 1 val scrollIndex = visibleCount * 2 - 1 if (first > scrollIndex) { rv.scrollToPosition(scrollIndex) } } rv.smoothScrollToPosition(0) } } }
gpl-2.0
fe547ce4852fc2f48bb710711dde770a
31.741935
83
0.617357
5.147208
false
false
false
false
JetBrains/xodus
crypto/src/main/kotlin/jetbrains/exodus/crypto/convert/ScytaleEngine.kt
1
6514
/** * Copyright 2010 - 2022 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package jetbrains.exodus.crypto.convert import jetbrains.exodus.crypto.StreamCipherProvider import jetbrains.exodus.crypto.asHashedIV import jetbrains.exodus.log.LogUtil import jetbrains.exodus.util.ByteArraySpinAllocator import mu.KLogging import java.io.Closeable import java.util.concurrent.ArrayBlockingQueue import java.util.concurrent.TimeUnit class ScytaleEngine( private val listener: EncryptListener, private val cipherProvider: StreamCipherProvider, private val key: ByteArray, private val basicIV: Long, private val blockAlignment: Int = LogUtil.LOG_BLOCK_ALIGNMENT, bufferSize: Int = 1024 * 1024, // 1MB inputQueueSize: Int = 40, outputQueueSize: Int = 40 ) : Closeable { companion object : KLogging() { val timeout = 200L } private val inputQueue = ArrayBlockingQueue<EncryptMessage>(inputQueueSize) private val outputQueue = ArrayBlockingQueue<EncryptMessage>(outputQueueSize) private val bufferAllocator = ByteArraySpinAllocator(bufferSize, inputQueueSize + outputQueueSize + 4) @Volatile private var producerFinished = false @Volatile private var consumerFinished = false @Volatile private var cancelled = false @Volatile var error: Throwable? = null private val statefulProducer = object : Runnable { private val cipher = cipherProvider.newCipher() private var offset = 0 private var iv = 0L override fun run() { try { while (!cancelled && error == null) { inputQueue.poll(timeout, TimeUnit.MILLISECONDS)?.let { when (it) { is FileHeader -> { offset = 0 iv = basicIV + if (it.chunkedIV) { it.handle / blockAlignment } else { it.handle } cipher.init(key, iv.asHashedIV()) } is FileChunk -> encryptChunk(it) is EndChunk -> Unit else -> throw IllegalArgumentException() } while (!outputQueue.offer(it, timeout, TimeUnit.MILLISECONDS)) { if (cancelled || error != null) { return } } } ?: if (producerFinished) { return } } } catch (t: Throwable) { producerFinished = true error = t } } private fun encryptChunk(it: FileChunk) { if (it.header.canBeEncrypted) { val data = it.data if (it.header.chunkedIV) { blockEncrypt(it.size, data) } else { encrypt(it.size, data) } } } private fun encrypt(size: Int, data: ByteArray) { for (i in 0 until size) { data[i] = cipher.crypt(data[i]) } } private fun blockEncrypt(size: Int, data: ByteArray) { for (i in 0 until size) { data[i] = cipher.crypt(data[i]) if (++offset == blockAlignment) { offset = 0 cipher.init(key, (++iv).asHashedIV()) } } } } private val producer = Thread(statefulProducer, "xodus encrypt " + hashCode()) private val consumer = Thread({ try { var currentFile: FileHeader? = null while (!cancelled && error == null) { outputQueue.poll(timeout, TimeUnit.MILLISECONDS)?.let { when (it) { is FileHeader -> { currentFile?.let { listener.onFileEnd(it) } currentFile = it listener.onFile(it) } is FileChunk -> { val current = currentFile if (current != null && current != it.header) { throw Throwable("Invalid chunk with header " + it.header.path) } else { listener.onData(it.header, it.size, it.data) bufferAllocator.dispose(it.data) } } is EndChunk -> { currentFile?.let { listener.onFileEnd(it) } } else -> throw IllegalArgumentException() } } ?: if (consumerFinished) { return@Thread } } } catch (t: Throwable) { consumerFinished = true error = t } }, "xodus write " + hashCode()) fun start() { producer.start() consumer.start() } fun alloc(): ByteArray = bufferAllocator.alloc() fun put(e: EncryptMessage) { while (!inputQueue.offer(e, timeout, TimeUnit.MILLISECONDS)) { if (error != null) { throw RuntimeException(error) } } } fun cancel() { cancelled = true } override fun close() { producerFinished = true producer.join() consumerFinished = true consumer.join() error?.let { throw RuntimeException(it) } } }
apache-2.0
e12bae2d5d4f452f2329e6a7296ecad7
33.834225
106
0.487565
5.387924
false
false
false
false
jwren/intellij-community
plugins/kotlin/idea/tests/test/org/jetbrains/kotlin/idea/imports/AbstractFilteringAutoImportTest.kt
4
1896
// 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.imports import com.intellij.codeInsight.daemon.ReferenceImporter import org.jetbrains.kotlin.idea.codeInsight.AbstractKotlinReferenceImporter import org.jetbrains.kotlin.idea.codeInsight.KotlinCodeInsightSettings import org.jetbrains.kotlin.idea.codeInsight.KotlinAutoImportsFilter import org.jetbrains.kotlin.name.FqName import org.jetbrains.kotlin.psi.KtFile private class KotlinAutoImportsFilterImpl(val isEnabled: Boolean) : KotlinAutoImportsFilter { override fun forceAutoImportForElement(file: KtFile, suggestions: Collection<FqName>): Boolean = isEnabled override fun filterSuggestions(suggestions: Collection<FqName>): Collection<FqName> = suggestions.filter { it.asString() == "a.b.AmbiguousClazzForFilter" }.ifEmpty { suggestions } } private class TestReferenceImporterImpl(val isEnabled: Boolean) : AbstractKotlinReferenceImporter() { override fun isEnabledFor(file: KtFile): Boolean = isEnabled override val enableAutoImportFilter: Boolean = true } abstract class AbstractFilteringAutoImportTest : AbstractAutoImportTest() { override fun setupAutoImportEnvironment(settings: KotlinCodeInsightSettings, withAutoImport: Boolean) { // KotlinAutoImportsFilter.forceAutoImportForFile() should work even if addUnambiguousImportsOnTheFly is disabled: settings.addUnambiguousImportsOnTheFly = false KotlinAutoImportsFilter.EP_NAME.point.registerExtension( KotlinAutoImportsFilterImpl(isEnabled = withAutoImport), testRootDisposable ) ReferenceImporter.EP_NAME.point.registerExtension( TestReferenceImporterImpl(isEnabled = withAutoImport), testRootDisposable ) } }
apache-2.0
dc6a35f9a9d2e6249f218fc3e45e620c
48.921053
158
0.787447
4.989474
false
true
false
false
jwren/intellij-community
plugins/grazie/src/main/kotlin/com/intellij/grazie/ide/fus/GrazieFUSState.kt
1
4545
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.grazie.ide.fus import com.intellij.grazie.GrazieConfig import com.intellij.grazie.config.CheckingContext import com.intellij.grazie.detector.model.LanguageISO import com.intellij.grazie.ide.ui.grammar.tabs.rules.component.allRules import com.intellij.internal.statistic.beans.MetricEvent import com.intellij.internal.statistic.beans.newMetric import com.intellij.internal.statistic.collectors.fus.LangCustomRuleValidator import com.intellij.internal.statistic.collectors.fus.PluginInfoValidationRule import com.intellij.internal.statistic.eventLog.EventLogGroup import com.intellij.internal.statistic.eventLog.FeatureUsageData import com.intellij.internal.statistic.eventLog.events.EventFields import com.intellij.internal.statistic.eventLog.events.StringEventField import com.intellij.internal.statistic.service.fus.collectors.ApplicationUsagesCollector import com.intellij.internal.statistic.utils.getPluginInfo internal class GrazieFUSState : ApplicationUsagesCollector() { override fun getGroup(): EventLogGroup { return GROUP } override fun getMetrics(): Set<MetricEvent> { val metrics = HashSet<MetricEvent>() val state = GrazieConfig.get() for (lang in state.enabledLanguages) { metrics.add(ENABLE_LANGUAGE.metric(lang.iso)) } val allRules by lazy { allRules().values.flatten().groupBy { it.globalId } } fun logRule(id: String, enabled: Boolean) { val rule = allRules[id]?.firstOrNull() ?: return metrics.add(RULE.metric(getPluginInfo(rule.javaClass), id, enabled)) } state.userEnabledRules.forEach { logRule(it, enabled = true) } state.userDisabledRules.forEach { logRule(it, enabled = false) } val checkingContext = state.checkingContext for (id in checkingContext.disabledLanguages) { metrics.add(CHECKING_CONTEXT.metric(LANGUAGE_FIELD.with(id), USER_CHANGE_FIELD.with("disabled"))) } for (id in checkingContext.enabledLanguages) { metrics.add(CHECKING_CONTEXT.metric(LANGUAGE_FIELD.with(id), USER_CHANGE_FIELD.with("enabled"))) } val defaults = CheckingContext() fun checkDomain(name: StringEventField, isEnabled: (CheckingContext) -> Boolean) { if (isEnabled(defaults) != isEnabled(checkingContext)) { metrics.add(CHECKING_CONTEXT.metric(name.with(if (isEnabled(checkingContext)) "enabled" else "disabled"))) } } checkDomain(DOCUMENTATION_FIELD) { it.isCheckInDocumentationEnabled } checkDomain(COMMENTS_FIELD) { it.isCheckInCommentsEnabled } checkDomain(LITERALS_FIELD) { it.isCheckInStringLiteralsEnabled } checkDomain(COMMIT_FIELD) { it.isCheckInCommitMessagesEnabled } return metrics } companion object { private val GROUP = EventLogGroup("grazie.state", 6) private val ENABLE_LANGUAGE = GROUP.registerEvent("enabled.language", EventFields.Enum("value", LanguageISO::class.java) { it.name.lowercase() }) private val RULE = GROUP.registerEvent("rule", EventFields.PluginInfo, EventFields.StringValidatedByCustomRule("id", PluginInfoValidationRule::class.java), EventFields.Enabled) private val DOCUMENTATION_FIELD = EventFields.StringValidatedByEnum("documentation", "state") private val COMMENTS_FIELD = EventFields.StringValidatedByEnum("comments", "state") private val LITERALS_FIELD = EventFields.StringValidatedByEnum("literals", "state") private val COMMIT_FIELD = EventFields.StringValidatedByEnum("commit", "state") private val USER_CHANGE_FIELD = EventFields.StringValidatedByEnum("userChange", "state") private val LANGUAGE_FIELD = EventFields.StringValidatedByCustomRule("language", LangCustomRuleValidator::class.java) private val CHECKING_CONTEXT = GROUP.registerVarargEvent("checkingContext", LANGUAGE_FIELD, USER_CHANGE_FIELD, DOCUMENTATION_FIELD, COMMENTS_FIELD, LITERALS_FIELD, COMMIT_FIELD) } }
apache-2.0
5dc956ba0dedcb67080dee51b42f8e16
51.241379
140
0.679208
5.005507
false
false
false
false
androidx/androidx
health/health-services-client/src/main/java/androidx/health/services/client/impl/event/PassiveListenerEvent.kt
3
2954
/* * 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 * * 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.health.services.client.impl.event import android.os.Parcelable import androidx.annotation.RestrictTo import androidx.health.services.client.PassiveListenerCallback import androidx.health.services.client.PassiveListenerService import androidx.health.services.client.data.ProtoParcelable import androidx.health.services.client.impl.response.HealthEventResponse import androidx.health.services.client.impl.response.PassiveMonitoringGoalResponse import androidx.health.services.client.impl.response.PassiveMonitoringUpdateResponse import androidx.health.services.client.proto.EventsProto.PassiveListenerEvent as EventProto import androidx.health.services.client.proto.ResponsesProto.PermissionLostResponse /** * An event representing a [PassiveListenerCallback] or [PassiveListenerService] invocation. * * @hide */ @RestrictTo(RestrictTo.Scope.LIBRARY) internal class PassiveListenerEvent(public override val proto: EventProto) : ProtoParcelable<EventProto>() { public companion object { @JvmField public val CREATOR: Parcelable.Creator<PassiveListenerEvent> = newCreator { PassiveListenerEvent(EventProto.parseFrom(it)) } @JvmStatic public fun createPermissionLostResponse(): PassiveListenerEvent = PassiveListenerEvent( EventProto.newBuilder() .setPermissionLostResponse(PermissionLostResponse.newBuilder().build()) .build() ) @JvmStatic public fun createPassiveUpdateResponse( response: PassiveMonitoringUpdateResponse ): PassiveListenerEvent = PassiveListenerEvent( EventProto.newBuilder().setPassiveUpdateResponse(response.proto).build() ) @JvmStatic public fun createPassiveGoalResponse( response: PassiveMonitoringGoalResponse ): PassiveListenerEvent = PassiveListenerEvent( EventProto.newBuilder().setPassiveGoalResponse(response.proto).build() ) @JvmStatic public fun createHealthEventResponse(response: HealthEventResponse): PassiveListenerEvent = PassiveListenerEvent( EventProto.newBuilder().setHealthEventResponse(response.proto).build() ) } }
apache-2.0
fa24d563dff4c5475ed83c635c054084
38.386667
99
0.726134
5.256228
false
false
false
false
GunoH/intellij-community
plugins/git4idea/src/git4idea/remote/GitDefineRemoteDialog.kt
1
5282
// 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 git4idea.remote import com.intellij.openapi.application.AppUIExecutor import com.intellij.openapi.application.impl.coroutineDispatchingContext import com.intellij.openapi.diagnostic.logger import com.intellij.openapi.progress.runUnderIndicator import com.intellij.openapi.ui.DialogWrapper import com.intellij.openapi.ui.ValidationInfo import com.intellij.openapi.util.Disposer import com.intellij.openapi.util.NlsSafe import com.intellij.openapi.vfs.VfsUtilCore.virtualToIoFile import com.intellij.openapi.wm.IdeFocusManager import com.intellij.ui.AnimatedIcon import com.intellij.ui.DocumentAdapter import com.intellij.ui.components.JBTextField import com.intellij.ui.components.fields.ExtendableTextComponent import com.intellij.ui.components.fields.ExtendableTextField import com.intellij.ui.dsl.builder.AlignX import com.intellij.ui.dsl.builder.panel import git4idea.GitUtil.mention import git4idea.commands.Git import git4idea.commands.GitCommandResult import git4idea.i18n.GitBundle.message import git4idea.repo.GitRepository import git4idea.validators.GitRefNameValidator import kotlinx.coroutines.* import javax.swing.JComponent import javax.swing.event.DocumentEvent private val LOG = logger<GitDefineRemoteDialog>() class GitDefineRemoteDialog( private val repository: GitRepository, private val git: Git, @NlsSafe private val initialName: String, @NlsSafe initialUrl: String ) : DialogWrapper(repository.project) { private val uiDispatcher get() = AppUIExecutor.onUiThread().coroutineDispatchingContext() private val scope = CoroutineScope(SupervisorJob()).also { Disposer.register(disposable) { it.cancel() } } private val nameField = JBTextField(initialName, 30) private val urlField = ExtendableTextField(initialUrl, 30) private val loadingExtension = ExtendableTextComponent.Extension { AnimatedIcon.Default.INSTANCE } private var urlAccessError: ValidationInfo? = null init { title = message("remotes.define.remote") + mention(repository) init() } val remoteName: String get() = nameField.text.orEmpty().trim() val remoteUrl: String get() = urlField.text.orEmpty().trim() override fun getPreferredFocusedComponent(): JComponent = if (nameField.text.isNullOrEmpty()) nameField else urlField override fun createCenterPanel(): JComponent = panel { row(message("remotes.define.remote.name")) { cell(nameField) .align(AlignX.FILL) .validationOnApply { nameNotBlank() ?: nameWellFormed() ?: nameUnique() } } row(message("remotes.define.remote.url")) { cell(urlField) .align(AlignX.FILL) .validationOnApply { urlNotBlank() ?: urlAccessError } .applyToComponent { clearUrlAccessErrorOnTextChanged() } } } override fun doOKAction() { scope.launch(uiDispatcher + CoroutineName("Define Remote - checking url")) { setLoading(true) try { urlAccessError = checkUrlAccess() } finally { setLoading(false) } if (urlAccessError == null) { super.doOKAction() } else { IdeFocusManager.getGlobalInstance().requestFocus(urlField, true) startTrackingValidation() } } } private fun setLoading(isLoading: Boolean) { nameField.isEnabled = !isLoading urlField.apply { if (isLoading) addExtension(loadingExtension) else removeExtension(loadingExtension) } urlField.isEnabled = !isLoading isOKActionEnabled = !isLoading } private fun nameNotBlank(): ValidationInfo? = if (remoteName.isNotEmpty()) null else ValidationInfo(message("remotes.define.empty.remote.name.validation.message"), nameField) private fun nameWellFormed(): ValidationInfo? = if (GitRefNameValidator.getInstance().checkInput(remoteName)) null else ValidationInfo(message("remotes.define.invalid.remote.name.validation.message"), nameField) private fun nameUnique(): ValidationInfo? { val name = remoteName return if (name == initialName || repository.remotes.none { it.name == name }) null else ValidationInfo(message("remotes.define.duplicate.remote.name.validation.message", name), nameField) } private fun urlNotBlank(): ValidationInfo? = if (remoteUrl.isNotEmpty()) null else ValidationInfo(message("remotes.define.empty.remote.url.validation.message"), urlField) private fun JBTextField.clearUrlAccessErrorOnTextChanged() = document.addDocumentListener(object : DocumentAdapter() { override fun textChanged(e: DocumentEvent) { urlAccessError = null } }) private suspend fun checkUrlAccess(): ValidationInfo? { val url = remoteUrl val result = lsRemote(url) if (result.success()) return null LOG.warn("Invalid remote. Name: $remoteName, URL: $url, error: ${result.errorOutputAsJoinedString}") return ValidationInfo(result.errorOutputAsHtmlString, urlField).withOKEnabled() } private suspend fun lsRemote(url: String): GitCommandResult = withContext(Dispatchers.IO) { runUnderIndicator { git.lsRemote(repository.project, virtualToIoFile(repository.root), url) } } }
apache-2.0
a4c7f1d38aa76828d600e2d628fc5a37
35.6875
140
0.746498
4.625219
false
false
false
false
GunoH/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/hierarchy/calls/callHierarchyUtils.kt
4
2733
// 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.hierarchy.calls import com.intellij.ide.hierarchy.HierarchyNodeDescriptor import com.intellij.ide.hierarchy.call.CallHierarchyNodeDescriptor import com.intellij.ide.util.treeView.NodeDescriptor import com.intellij.psi.PsiElement import com.intellij.psi.PsiMember import com.intellij.psi.PsiReference import org.jetbrains.kotlin.asJava.toLightElements import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.parentsWithSelf fun isCallHierarchyElement(e: PsiElement): Boolean { return (e is KtNamedFunction && e.name != null) || e is KtSecondaryConstructor || (e is KtProperty && !e.isLocal) || e is KtObjectDeclaration || (e is KtClass && !e.isInterface()) || e is KtFile } fun getCallHierarchyElement(element: PsiElement) = element.parentsWithSelf.firstOrNull(::isCallHierarchyElement) as? KtElement private fun NodeDescriptor<*>.incrementUsageCount() { when (this) { is KotlinCallHierarchyNodeDescriptor -> incrementUsageCount() is CallHierarchyNodeDescriptor -> incrementUsageCount() } } private fun NodeDescriptor<*>.addReference(reference: PsiReference) { when (this) { is KotlinCallHierarchyNodeDescriptor -> addReference(reference) is CallHierarchyNodeDescriptor -> addReference(reference) } } internal fun getOrCreateNodeDescriptor( parent: HierarchyNodeDescriptor, originalElement: PsiElement, reference: PsiReference?, navigateToReference: Boolean, elementToDescriptorMap: MutableMap<PsiElement, NodeDescriptor<*>>, isJavaMap: Boolean ): HierarchyNodeDescriptor? { val element = (if (isJavaMap && originalElement is KtElement) originalElement.toLightElements().firstOrNull() else originalElement) ?: return null val existingDescriptor = elementToDescriptorMap[element] as? HierarchyNodeDescriptor val result = if (existingDescriptor != null) { existingDescriptor.incrementUsageCount() existingDescriptor } else { val newDescriptor: HierarchyNodeDescriptor = when (element) { is KtElement -> KotlinCallHierarchyNodeDescriptor(parent, element, false, navigateToReference) is PsiMember -> CallHierarchyNodeDescriptor(element.project, parent, element, false, navigateToReference) else -> return null } elementToDescriptorMap[element] = newDescriptor newDescriptor } if (reference != null) { result.addReference(reference) } return result }
apache-2.0
fc5f28dc3f6094e3902c12af14b0e0cd
38.057143
158
0.732894
5.12758
false
false
false
false
GunoH/intellij-community
plugins/git4idea/src/git4idea/remote/hosting/gitAsyncExtensions.kt
2
3124
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package git4idea.remote.hosting import com.intellij.collaboration.api.ServerPath import com.intellij.dvcs.repo.VcsRepositoryManager import com.intellij.dvcs.repo.VcsRepositoryMappingListener import com.intellij.openapi.project.Project import com.intellij.openapi.util.Disposer import git4idea.remote.GitRemoteUrlCoordinates import git4idea.repo.GitRepository import git4idea.repo.GitRepositoryChangeListener import git4idea.repo.GitRepositoryManager import kotlinx.coroutines.async import kotlinx.coroutines.awaitAll import kotlinx.coroutines.channels.awaitClose import kotlinx.coroutines.flow.* fun gitRemotesFlow(project: Project): Flow<Set<GitRemoteUrlCoordinates>> = callbackFlow { val disposable = Disposer.newDisposable() project.messageBus.connect(disposable).subscribe(VcsRepositoryManager.VCS_REPOSITORY_MAPPING_UPDATED, VcsRepositoryMappingListener { trySend(GitRepositoryManager.getInstance(project).collectRemotes()) }) project.messageBus.connect(disposable).subscribe(GitRepository.GIT_REPO_CHANGE, GitRepositoryChangeListener { trySend(GitRepositoryManager.getInstance(project).collectRemotes()) }) send(GitRepositoryManager.getInstance(project).collectRemotes()) awaitClose { Disposer.dispose(disposable) } } private fun GitRepositoryManager.collectRemotes(): Set<GitRemoteUrlCoordinates> { if (repositories.isEmpty()) { return emptySet() } return repositories.flatMap { repo -> repo.remotes.flatMap { remote -> remote.urls.mapNotNull { url -> GitRemoteUrlCoordinates(url, remote, repo) } } }.toSet() } private typealias GitRemotesFlow = Flow<Collection<GitRemoteUrlCoordinates>> fun <S : ServerPath, M : HostedGitRepositoryMapping> GitRemotesFlow.mapToServers(serversState: Flow<Set<S>>, mapper: (S, GitRemoteUrlCoordinates) -> M?) : Flow<Set<M>> = combine(serversState) { remotes, servers -> remotes.asSequence().mapNotNull { remote -> servers.find { GitHostingUrlUtil.match(it.toURI(), remote.url) }?.let { mapper(it, remote) } }.toSet() } fun <S : ServerPath> GitRemotesFlow.discoverServers(knownServersFlow: Flow<Set<S>>, parallelism: Int = 10, checkForDedicatedServer: suspend (GitRemoteUrlCoordinates) -> S?) : Flow<S> { val remotesFlow = this return channelFlow { remotesFlow.combine(knownServersFlow) { remotes, servers -> remotes.filter { remote -> servers.none { GitHostingUrlUtil.match(it.toURI(), remote.url) } } } .conflate() .collect { remotes -> remotes.chunked(parallelism).forEach { remotesChunk -> remotesChunk.map { remote -> async { val server = checkForDedicatedServer(remote) if (server != null) send(server) } }.awaitAll() } } } }
apache-2.0
88dd1d47e9065ac4dadb85d3345c7f4a
38.556962
136
0.689821
4.690691
false
false
false
false
GunoH/intellij-community
plugins/groovy/src/org/jetbrains/plugins/groovy/codeInsight/hint/types/GroovyParameterTypeHintsCollector.kt
2
4391
// 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.plugins.groovy.codeInsight.hint.types import com.intellij.codeInsight.hints.FactoryInlayHintsCollector import com.intellij.codeInsight.hints.InlayHintsSink import com.intellij.codeInsight.hints.presentation.InlayPresentation import com.intellij.codeInsight.hints.settings.CASE_KEY import com.intellij.openapi.editor.Editor import com.intellij.openapi.project.DumbService import com.intellij.psi.CommonClassNames import com.intellij.psi.PsiElement import com.intellij.psi.PsiType import com.intellij.psi.util.PsiUtilCore import com.intellij.psi.util.parentOfType import com.intellij.refactoring.suggested.endOffset import com.intellij.util.asSafely import org.jetbrains.plugins.groovy.intentions.style.inference.MethodParameterAugmenter import org.jetbrains.plugins.groovy.lang.psi.GrControlFlowOwner import org.jetbrains.plugins.groovy.lang.psi.api.auxiliary.modifiers.GrModifier.DEF import org.jetbrains.plugins.groovy.lang.psi.api.statements.blocks.GrClosableBlock import org.jetbrains.plugins.groovy.lang.psi.api.statements.params.GrParameter import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.members.GrMethod import org.jetbrains.plugins.groovy.lang.psi.dataFlow.types.TypeAugmenter import org.jetbrains.plugins.groovy.lang.psi.dataFlow.types.TypeInferenceHelper import org.jetbrains.plugins.groovy.lang.psi.impl.synthetic.ClosureSyntheticParameter import org.jetbrains.plugins.groovy.lang.psi.typeEnhancers.GrVariableEnhancer class GroovyParameterTypeHintsCollector(editor: Editor, private val settings: GroovyParameterTypeHintsInlayProvider.Settings) : FactoryInlayHintsCollector(editor) { override fun collect(element: PsiElement, editor: Editor, sink: InlayHintsSink): Boolean { if (DumbService.isDumb(element.project) || element.project.isDefault) { return false } if (!settings.showInferredParameterTypes && CASE_KEY.get(editor) == null) { return false } PsiUtilCore.ensureValid(element) if (element is GrParameter && element.typeElement == null && !element.isVarArgs) { val type: PsiType = getRepresentableType(element) ?: return true val typeRepresentation = with(factory) { roundWithBackground(seq(buildRepresentation(type), smallText(" "))) } sink.addInlineElement(element.textOffset, false, typeRepresentation, false) } if (element is GrClosableBlock && element.parameterList.isEmpty) { val itParameter = element.allParameters.singleOrNull()?.asSafely<ClosureSyntheticParameter>() ?: return true if (!itParameter.isStillValid) return true val type: PsiType = getRepresentableType(itParameter) ?: return true val textRepresentation: InlayPresentation = with(factory) { roundWithBackground(seq(buildRepresentation(type), smallText(" it -> "))) } sink.addInlineElement(element.lBrace.endOffset, true, textRepresentation, false) } if (settings.showTypeParameterList && element is GrMethod && !element.hasTypeParameters() && element.parameters.any { it.typeElement == null }) { val (virtualMethod, _) = MethodParameterAugmenter.createInferenceResult(element) ?: return true val typeParameterList = virtualMethod?.typeParameterList?.takeIf { it.typeParameters.isNotEmpty() } ?: return true val representation = factory.buildRepresentation(typeParameterList) if (element.modifierList.hasModifierProperty(DEF)) { sink.addInlineElement(element.modifierList.getModifier(DEF)!!.textRange.endOffset, true, representation, false) } else { sink.addInlineElement(element.textRange.startOffset, true, representation, false) } } return true } private fun getRepresentableType(variable: GrParameter): PsiType? { var inferredType: PsiType? = GrVariableEnhancer.getEnhancedType(variable) if (inferredType == null) { val ownerFlow = variable.parentOfType<GrControlFlowOwner>()?.controlFlow ?: return null if (TypeInferenceHelper.isSimpleEnoughForAugmenting(ownerFlow)) { inferredType = TypeAugmenter.inferAugmentedType(variable) } } return inferredType?.takeIf { !it.equalsToText(CommonClassNames.JAVA_LANG_OBJECT) } } }
apache-2.0
2c5506dd85fbfffef968f282de4c708c
51.27381
120
0.767251
4.494371
false
false
false
false
GunoH/intellij-community
plugins/kotlin/base/fe10/analysis/src/org/jetbrains/kotlin/util/DescriptorUtils.kt
4
4941
// 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.util import org.jetbrains.kotlin.descriptors.* import org.jetbrains.kotlin.load.java.descriptors.JavaCallableMemberDescriptor import org.jetbrains.kotlin.load.java.descriptors.JavaClassDescriptor import org.jetbrains.kotlin.name.FqNameUnsafe import org.jetbrains.kotlin.resolve.OverridingUtil import org.jetbrains.kotlin.resolve.OverridingUtil.OverrideCompatibilityInfo.Result.CONFLICT import org.jetbrains.kotlin.resolve.OverridingUtil.OverrideCompatibilityInfo.Result.OVERRIDABLE import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameUnsafe import org.jetbrains.kotlin.resolve.descriptorUtil.overriddenTreeUniqueAsSequence import org.jetbrains.kotlin.resolve.scopes.DescriptorKindFilter import org.jetbrains.kotlin.synthetic.SyntheticJavaPropertyDescriptor import org.jetbrains.kotlin.types.KotlinType import org.jetbrains.kotlin.types.TypeConstructor import org.jetbrains.kotlin.types.checker.KotlinTypeChecker import org.jetbrains.kotlin.types.checker.KotlinTypeCheckerImpl import org.jetbrains.kotlin.types.typeUtil.equalTypesOrNulls fun descriptorsEqualWithSubstitution( descriptor1: DeclarationDescriptor?, descriptor2: DeclarationDescriptor?, checkOriginals: Boolean = true ): Boolean { if (descriptor1 == descriptor2) return true if (descriptor1 == null || descriptor2 == null) return false if (checkOriginals && descriptor1.original != descriptor2.original) return false if (descriptor1 !is CallableDescriptor) return true descriptor2 as CallableDescriptor val typeChecker = KotlinTypeCheckerImpl.withAxioms(object : KotlinTypeChecker.TypeConstructorEquality { override fun equals(a: TypeConstructor, b: TypeConstructor): Boolean { val typeParam1 = a.declarationDescriptor as? TypeParameterDescriptor val typeParam2 = b.declarationDescriptor as? TypeParameterDescriptor if (typeParam1 != null && typeParam2 != null && typeParam1.containingDeclaration == descriptor1 && typeParam2.containingDeclaration == descriptor2 ) { return typeParam1.index == typeParam2.index } return a == b } }) if (!typeChecker.equalTypesOrNulls(descriptor1.returnType, descriptor2.returnType)) return false val parameters1 = descriptor1.valueParameters val parameters2 = descriptor2.valueParameters if (parameters1.size != parameters2.size) return false for ((param1, param2) in parameters1.zip(parameters2)) { if (!typeChecker.equalTypes(param1.type, param2.type)) return false } return true } fun ClassDescriptor.findCallableMemberBySignature( signature: CallableMemberDescriptor, allowOverridabilityConflicts: Boolean = false ): CallableMemberDescriptor? { val descriptorKind = if (signature is FunctionDescriptor) DescriptorKindFilter.FUNCTIONS else DescriptorKindFilter.VARIABLES return defaultType.memberScope .getContributedDescriptors(descriptorKind) .filterIsInstance<CallableMemberDescriptor>() .firstOrNull { if (it.containingDeclaration != this) return@firstOrNull false val overridability = OverridingUtil.DEFAULT.isOverridableBy(it as CallableDescriptor, signature, null).result overridability == OVERRIDABLE || (allowOverridabilityConflicts && overridability == CONFLICT) } } fun TypeConstructor.supertypesWithAny(): Collection<KotlinType> { val supertypes = supertypes val noSuperClass = supertypes.map { it.constructor.declarationDescriptor as? ClassDescriptor }.all { it == null || it.kind == ClassKind.INTERFACE } return if (noSuperClass) supertypes + builtIns.anyType else supertypes } val ClassifierDescriptorWithTypeParameters.constructors: Collection<ConstructorDescriptor> get() = when (this) { is TypeAliasDescriptor -> this.constructors is ClassDescriptor -> this.constructors else -> emptyList() } val ClassifierDescriptorWithTypeParameters.kind: ClassKind? get() = when (this) { is TypeAliasDescriptor -> classDescriptor?.kind is ClassDescriptor -> kind else -> null } val DeclarationDescriptor.isJavaDescriptor get() = this is JavaClassDescriptor || this is JavaCallableMemberDescriptor fun FunctionDescriptor.shouldNotConvertToProperty(notProperties: Set<FqNameUnsafe>): Boolean { if (fqNameUnsafe in notProperties) return true return this.overriddenTreeUniqueAsSequence(false).any { fqNameUnsafe in notProperties } } fun SyntheticJavaPropertyDescriptor.suppressedByNotPropertyList(set: Set<FqNameUnsafe>) = getMethod.shouldNotConvertToProperty(set) || setMethod?.shouldNotConvertToProperty(set) ?: false
apache-2.0
68468a875906d2953fe13d7eff261e0e
45.622642
158
0.763206
5.109617
false
false
false
false
siosio/intellij-community
plugins/completion-ml-ranking/src/com/intellij/completion/ml/util/RelevanceUtil.kt
1
4600
package com.intellij.completion.ml.util import com.intellij.codeInsight.completion.ml.MLWeigherUtil import com.intellij.completion.ml.features.MLCompletionWeigher import com.intellij.completion.ml.sorting.FeatureUtils import com.intellij.internal.statistic.utils.PluginType import com.intellij.internal.statistic.utils.getPluginInfo import com.intellij.openapi.diagnostic.logger import com.intellij.openapi.util.Pair import com.intellij.openapi.util.text.StringUtil object RelevanceUtil { private val LOG = logger<RelevanceUtil>() private const val NULL_TEXT = "null" private val IGNORED_FACTORS = setOf("kotlin.byNameAlphabetical", "scalaMethodCompletionWeigher", "unresolvedOnTop", "alphabetic", "TabNineLookupElementWeigher", "AixLookupElementWeigher", "CodotaCompletionWeigher", "CodotaCompletionWeigher_Kotlin", "EmcSuggestionsWeigher", "codotaPriorityWeigher", "com.zlabs.code.completion.ScaCompletionWeigher", "com.aliyun.odps.studio.intellij.compiler.codecompletion.OdpsqlCompletionWeigher") private val weighersClassesCache = mutableMapOf<String, PluginType>() /* * First map contains only features affecting default elements ordering * */ fun asRelevanceMaps(relevanceObjects: List<Pair<String, Any?>>): kotlin.Pair<MutableMap<String, Any>, MutableMap<String, Any>> { val relevanceMap = mutableMapOf<String, Any>() val additionalMap = mutableMapOf<String, Any>() for (pair in relevanceObjects) { val name = pair.first.normalized() val value = pair.second if (name in IGNORED_FACTORS || value == null) continue when (name) { "proximity" -> relevanceMap.addProximityValues("prox", value) "kotlin.proximity" -> relevanceMap.addProximityValues("kt_prox", value) "swiftSymbolProximity" -> { relevanceMap[name] = value // while this feature is used in actual models relevanceMap.addProximityValues("swift_prox", value) } "kotlin.callableWeight" -> relevanceMap.addDataClassValues("kotlin.callableWeight", value.toString()) "ml_weigh" -> additionalMap.addMlFeatures("ml", value) else -> if (acceptValue(value) || name == FeatureUtils.ML_RANK) relevanceMap[name] = value } } return kotlin.Pair(relevanceMap, additionalMap) } private fun acceptValue(value: Any): Boolean { return value is Number || value is Boolean || value.javaClass.isEnum || isJetBrainsClass(value.javaClass) } private fun isJetBrainsClass(cl: Class<*>): Boolean { val pluginType = weighersClassesCache.getOrPut(cl.name) { getPluginInfo(cl).type } return pluginType.isDevelopedByJetBrains() } private fun String.normalized(): String { return substringBefore('@') } private fun MutableMap<String, Any>.addMlFeatures(prefix: String, comparable: Any) { if (comparable !is MLCompletionWeigher.DummyComparable) { LOG.error("Unexpected value type of `$prefix`: ${comparable.javaClass.simpleName}") return } for ((name, value) in comparable.mlFeatures) { this["${prefix}_$name"] = value } } private fun MutableMap<String, Any>.addProximityValues(prefix: String, proximity: Any) { val weights = MLWeigherUtil.extractWeightsOrNull(proximity) if (weights == null) { LOG.error("Unexpected comparable type for `$prefix` weigher: ${proximity.javaClass.simpleName}") return } for ((name, weight) in weights) { this["${prefix}_$name"] = weight } } private fun MutableMap<String, Any>.addDataClassValues(featureName: String, dataClassString: String) { if (StringUtil.countChars(dataClassString, '(') != 1) { this[featureName] = dataClassString } else { this.addProperties(featureName, dataClassString.substringAfter('(').substringBeforeLast(')').split(',')) } } private fun MutableMap<String, Any>.addProperties(prefix: String, properties: List<String>) { properties.forEach { if (it.isNotBlank()) { val key = "${prefix}_${it.substringBefore('=').trim()}" val value = it.substringAfter('=').trim() if (value == NULL_TEXT) return@forEach this[key] = value } } } }
apache-2.0
4c4e14179c96bcf6fc40c22b12c495a6
39.716814
130
0.644783
4.698672
false
false
false
false
siosio/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/NamingConventionInspections.kt
1
17836
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.inspections import com.intellij.analysis.AnalysisScope import com.intellij.codeInspection.* import com.intellij.codeInspection.reference.RefEntity import com.intellij.codeInspection.reference.RefFile import com.intellij.codeInspection.reference.RefPackage import com.intellij.openapi.editor.event.DocumentEvent import com.intellij.openapi.editor.event.DocumentListener import com.intellij.openapi.ui.LabeledComponent import com.intellij.openapi.util.text.StringUtil import com.intellij.psi.JavaPsiFacade import com.intellij.psi.PsiElement import com.intellij.psi.PsiElementVisitor import com.intellij.psi.PsiNameIdentifierOwner import com.intellij.ui.EditorTextField import com.siyeh.ig.BaseGlobalInspection import com.siyeh.ig.psiutils.TestUtils import org.intellij.lang.annotations.Language import org.intellij.lang.regexp.RegExpFileType import org.jdom.Element import org.jetbrains.annotations.NonNls import org.jetbrains.kotlin.idea.KotlinBundle import org.jetbrains.kotlin.idea.caches.resolve.resolveToDescriptorIfAny import org.jetbrains.kotlin.idea.core.packageMatchesDirectoryOrImplicit import org.jetbrains.kotlin.idea.quickfix.RenameIdentifierFix import org.jetbrains.kotlin.idea.refactoring.fqName.fqName import org.jetbrains.kotlin.idea.refactoring.isInjectedFragment import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.name.FqName import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.containingClassOrObject import org.jetbrains.kotlin.psi.psiUtil.visibilityModifierType import java.awt.BorderLayout import java.util.regex.PatternSyntaxException import javax.swing.JPanel data class NamingRule(val message: String, val matcher: (String) -> Boolean) private fun findRuleMessage(checkString: String, rules: Array<out NamingRule>): String? { for (rule in rules) { if (rule.matcher(checkString)) { return rule.message } } return null } private val START_UPPER = NamingRule(KotlinBundle.message("should.start.with.an.uppercase.letter")) { it.getOrNull(0)?.isUpperCase() == false } private val START_LOWER = NamingRule(KotlinBundle.message("should.start.with.a.lowercase.letter")) { it.getOrNull(0)?.isLowerCase() == false } private val NO_UNDERSCORES = NamingRule(KotlinBundle.message("should.not.contain.underscores")) { '_' in it } private val NO_START_UPPER = NamingRule(KotlinBundle.message("should.not.start.with.an.uppercase.letter")) { it.getOrNull(0)?.isUpperCase() == true } private val NO_START_UNDERSCORE = NamingRule(KotlinBundle.message("should.not.start.with.an.underscore")) { it.startsWith('_') } private val NO_MIDDLE_UNDERSCORES = NamingRule(KotlinBundle.message("should.not.contain.underscores.in.the.middle.or.the.end")) { '_' in it.substring(1) } private val NO_BAD_CHARACTERS = NamingRule(KotlinBundle.message("may.contain.only.letters.and.digits")) { it.any { c -> c !in 'a'..'z' && c !in 'A'..'Z' && c !in '0'..'9' } } private val NO_BAD_CHARACTERS_OR_UNDERSCORE = NamingRule(KotlinBundle.message("may.contain.only.letters.digits.or.underscores")) { it.any { c -> c !in 'a'..'z' && c !in 'A'..'Z' && c !in '0'..'9' && c != '_' } } class NamingConventionInspectionSettings( private val entityName: String, @Language("RegExp") val defaultNamePattern: String, private val setNamePatternCallback: ((value: String) -> Unit), private vararg val rules: NamingRule ) { var nameRegex: Regex? = defaultNamePattern.toRegex() var namePattern: String = defaultNamePattern set(value) { field = value setNamePatternCallback.invoke(value) nameRegex = try { value.toRegex() } catch (e: PatternSyntaxException) { null } } fun verifyName(element: PsiNameIdentifierOwner, holder: ProblemsHolder, additionalCheck: () -> Boolean) { val name = element.name val nameIdentifier = element.nameIdentifier if (name != null && nameIdentifier != null && nameRegex?.matches(name) == false && additionalCheck()) { val message = getNameMismatchMessage(name) holder.registerProblem( element.nameIdentifier!!, "$entityName ${KotlinBundle.message("text.name")} <code>#ref</code> $message #loc", RenameIdentifierFix() ) } } fun getNameMismatchMessage(name: String): String { if (namePattern != defaultNamePattern) { return getDefaultErrorMessage() } return findRuleMessage(name, rules) ?: getDefaultErrorMessage() } fun getDefaultErrorMessage() = KotlinBundle.message("doesn.t.match.regex.0", namePattern) fun createOptionsPanel(): JPanel = NamingConventionOptionsPanel(this) private class NamingConventionOptionsPanel(settings: NamingConventionInspectionSettings) : JPanel() { init { layout = BorderLayout() val regexField = EditorTextField(settings.namePattern, null, RegExpFileType.INSTANCE).apply { setOneLineMode(true) } regexField.document.addDocumentListener(object : DocumentListener { override fun documentChanged(e: DocumentEvent) { settings.namePattern = regexField.text } }) val labeledComponent = LabeledComponent.create(regexField, KotlinBundle.message("text.pattern"), BorderLayout.WEST) add(labeledComponent, BorderLayout.NORTH) } } } sealed class NamingConventionInspection( entityName: String, @Language("RegExp") defaultNamePattern: String, vararg rules: NamingRule ) : AbstractKotlinInspection() { // Serialized inspection state @Suppress("MemberVisibilityCanBePrivate") var namePattern: String = defaultNamePattern private val namingSettings = NamingConventionInspectionSettings( entityName, defaultNamePattern, setNamePatternCallback = { value -> namePattern = value }, rules = *rules ) protected fun verifyName(element: PsiNameIdentifierOwner, holder: ProblemsHolder, additionalCheck: () -> Boolean = { true }) { namingSettings.verifyName(element, holder, additionalCheck) } protected fun getNameMismatchMessage(name: String): String { return namingSettings.getNameMismatchMessage(name) } override fun createOptionsPanel(): JPanel = namingSettings.createOptionsPanel() override fun readSettings(node: Element) { super.readSettings(node) namingSettings.namePattern = namePattern } } class ClassNameInspection : NamingConventionInspection( KotlinBundle.message("class"), "[A-Z][A-Za-z\\d]*", START_UPPER, NO_UNDERSCORES, NO_BAD_CHARACTERS ) { override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean): PsiElementVisitor { return object : KtVisitorVoid() { override fun visitClassOrObject(classOrObject: KtClassOrObject) { verifyName(classOrObject, holder) } override fun visitEnumEntry(enumEntry: KtEnumEntry) { // do nothing } } } } class EnumEntryNameInspection : NamingConventionInspection( KotlinBundle.message("enum.entry"), "[A-Z]([A-Za-z\\d]*|[A-Z_\\d]*)", START_UPPER, NO_BAD_CHARACTERS_OR_UNDERSCORE ) { override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean): PsiElementVisitor { return enumEntryVisitor { enumEntry -> verifyName(enumEntry, holder) } } } class FunctionNameInspection : NamingConventionInspection( KotlinBundle.message("function"), "[a-z][A-Za-z\\d]*", START_LOWER, NO_UNDERSCORES, NO_BAD_CHARACTERS ) { override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean): PsiElementVisitor { return namedFunctionVisitor { function -> if (function.hasModifier(KtTokens.OVERRIDE_KEYWORD)) { return@namedFunctionVisitor } if (!TestUtils.isInTestSourceContent(function)) { verifyName(function, holder) { val functionName = function.name val typeReference = function.typeReference if (typeReference != null) { typeReference.text != functionName } else { function.resolveToDescriptorIfAny() ?.returnType ?.fqName ?.takeUnless(FqName::isRoot) ?.shortName() ?.asString() != functionName } } } } } } class TestFunctionNameInspection : NamingConventionInspection( KotlinBundle.message("test.function"), "[a-z][A-Za-z_\\d]*", START_LOWER ) { override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean): PsiElementVisitor { return namedFunctionVisitor { function -> if (!TestUtils.isInTestSourceContent(function)) { return@namedFunctionVisitor } if (function.nameIdentifier?.text?.startsWith("`") == true) { return@namedFunctionVisitor } verifyName(function, holder) } } } abstract class PropertyNameInspectionBase protected constructor( private val kind: PropertyKind, entityName: String, defaultNamePattern: String, vararg rules: NamingRule ) : NamingConventionInspection(entityName, defaultNamePattern, *rules) { protected enum class PropertyKind { NORMAL, PRIVATE, OBJECT_OR_TOP_LEVEL, CONST, LOCAL } override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean): PsiElementVisitor { return propertyVisitor { property -> if (property.hasModifier(KtTokens.OVERRIDE_KEYWORD)) { return@propertyVisitor } if (property.getKind() == kind) { verifyName(property, holder) } } } private fun KtProperty.getKind(): PropertyKind = when { isLocal -> PropertyKind.LOCAL containingClassOrObject is KtObjectDeclaration -> PropertyKind.OBJECT_OR_TOP_LEVEL isTopLevel -> PropertyKind.OBJECT_OR_TOP_LEVEL hasModifier(KtTokens.CONST_KEYWORD) -> PropertyKind.CONST visibilityModifierType() == KtTokens.PRIVATE_KEYWORD -> PropertyKind.PRIVATE else -> PropertyKind.NORMAL } } class PropertyNameInspection : PropertyNameInspectionBase( PropertyKind.NORMAL, KotlinBundle.message("property"), "[a-z][A-Za-z\\d]*", START_LOWER, NO_UNDERSCORES, NO_BAD_CHARACTERS ) class ObjectPropertyNameInspection : PropertyNameInspectionBase( PropertyKind.OBJECT_OR_TOP_LEVEL, KotlinBundle.message("object.or.top.level.property"), "[A-Za-z][_A-Za-z\\d]*", NO_START_UNDERSCORE, NO_BAD_CHARACTERS_OR_UNDERSCORE ) class PrivatePropertyNameInspection : PropertyNameInspectionBase( PropertyKind.PRIVATE, KotlinBundle.message("private.property"), "_?[a-z][A-Za-z\\d]*", NO_MIDDLE_UNDERSCORES, NO_BAD_CHARACTERS_OR_UNDERSCORE ) class ConstPropertyNameInspection : PropertyNameInspectionBase(PropertyKind.CONST, KotlinBundle.message("const.property"), "[A-Z][_A-Z\\d]*") class LocalVariableNameInspection : PropertyNameInspectionBase( PropertyKind.LOCAL, KotlinBundle.message("local.variable"), "[a-z][A-Za-z\\d]*", START_LOWER, NO_UNDERSCORES, NO_BAD_CHARACTERS ) private class PackageNameInspectionLocal( val parentInspection: InspectionProfileEntry, val namingSettings: NamingConventionInspectionSettings ) : AbstractKotlinInspection() { override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean, session: LocalInspectionToolSession): PsiElementVisitor { return packageDirectiveVisitor { directive -> val packageNameExpression = directive.packageNameExpression ?: return@packageDirectiveVisitor val checkResult = checkPackageDirective(directive, namingSettings) ?: return@packageDirectiveVisitor val descriptionTemplate = checkResult.toProblemTemplateString() holder.registerProblem( packageNameExpression, descriptionTemplate, RenamePackageFix() ) } } companion object { data class CheckResult(val errorMessage: String, val isForPart: Boolean) fun CheckResult.toProblemTemplateString(): String { return KotlinBundle.message("package.name") + if (isForPart) { " <code>#ref</code> ${KotlinBundle.message("text.part")} $errorMessage #loc" } else { " <code>#ref</code> $errorMessage #loc" } } fun checkPackageDirective(directive: KtPackageDirective, namingSettings: NamingConventionInspectionSettings): CheckResult? { return checkQualifiedName(directive.qualifiedName, namingSettings) } fun checkQualifiedName(qualifiedName: String, namingSettings: NamingConventionInspectionSettings): CheckResult? { if (qualifiedName.isEmpty() || namingSettings.nameRegex?.matches(qualifiedName) != false) { return null } val partErrorMessage = if (namingSettings.namePattern == namingSettings.defaultNamePattern) { qualifiedName.split('.').asSequence() .mapNotNull { part -> findRuleMessage(part, PackageNameInspection.PART_RULES) } .firstOrNull() } else { null } return if (partErrorMessage != null) { CheckResult(partErrorMessage, true) } else { CheckResult(namingSettings.getDefaultErrorMessage(), false) } } } private class RenamePackageFix : RenameIdentifierFix() { override fun getElementToRename(element: PsiElement): PsiElement? { val packageDirective = element as? KtPackageDirective ?: return null return JavaPsiFacade.getInstance(element.project).findPackage(packageDirective.qualifiedName) } } override fun getShortName(): String = parentInspection.shortName override fun getDisplayName(): String = parentInspection.displayName } class PackageNameInspection : BaseGlobalInspection() { companion object { const val DEFAULT_PACKAGE_NAME_PATTERN = "[a-z_][a-zA-Z\\d_]*(\\.[a-z_][a-zA-Z\\d_]*)*" val PART_RULES = arrayOf(NO_BAD_CHARACTERS_OR_UNDERSCORE, NO_START_UPPER) private fun PackageNameInspectionLocal.Companion.CheckResult.toErrorMessage(qualifiedName: String): String { return KotlinBundle.message("package.name") + if (isForPart) { " <code>$qualifiedName</code> ${KotlinBundle.message("text.part")} $errorMessage" } else { " <code>$qualifiedName</code> $errorMessage" } } } // Serialized setting @Suppress("MemberVisibilityCanBePrivate") var namePattern: String = DEFAULT_PACKAGE_NAME_PATTERN private val namingSettings = NamingConventionInspectionSettings( KotlinBundle.message("text.Package"), DEFAULT_PACKAGE_NAME_PATTERN, setNamePatternCallback = { value -> namePattern = value } ) override fun checkElement( refEntity: RefEntity, analysisScope: AnalysisScope, inspectionManager: InspectionManager, globalInspectionContext: GlobalInspectionContext ): Array<CommonProblemDescriptor>? { when (refEntity) { is RefFile -> { val psiFile = refEntity.psiElement if (psiFile is KtFile && !psiFile.isInjectedFragment && !psiFile.packageMatchesDirectoryOrImplicit()) { val packageDirective = psiFile.packageDirective if (packageDirective != null) { val qualifiedName = packageDirective.qualifiedName val checkResult = PackageNameInspectionLocal.checkPackageDirective(packageDirective, namingSettings) if (checkResult != null) { return arrayOf(inspectionManager.createProblemDescriptor(checkResult.toErrorMessage(qualifiedName))) } } } } is RefPackage -> { @NonNls val name = StringUtil.getShortName(refEntity.getQualifiedName()) if (name.isEmpty() || InspectionsBundle.message("inspection.reference.default.package") == name) { return null } val checkResult = PackageNameInspectionLocal.checkQualifiedName(name, namingSettings) if (checkResult != null) { return arrayOf(inspectionManager.createProblemDescriptor(checkResult.toErrorMessage(name))) } } else -> { return null } } return null } override fun readSettings(element: Element) { super.readSettings(element) namingSettings.namePattern = namePattern } override fun createOptionsPanel() = namingSettings.createOptionsPanel() override fun getSharedLocalInspectionTool(): LocalInspectionTool { return PackageNameInspectionLocal(this, namingSettings) } }
apache-2.0
1f535e6a54e85194f8bccccb85a49661
37.276824
158
0.660967
4.966862
false
false
false
false
siosio/intellij-community
platform/dvcs-impl/src/com/intellij/dvcs/ignore/IgnoredToExcludedSynchronizer.kt
1
11918
// Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.dvcs.ignore import com.intellij.CommonBundle import com.intellij.ProjectTopics import com.intellij.icons.AllIcons import com.intellij.ide.BrowserUtil import com.intellij.ide.projectView.actions.MarkExcludeRootAction import com.intellij.ide.util.PropertiesComponent import com.intellij.idea.ActionsBundle import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.application.runInEdt import com.intellij.openapi.application.runReadAction import com.intellij.openapi.components.Service import com.intellij.openapi.components.service import com.intellij.openapi.diagnostic.logger import com.intellij.openapi.fileEditor.FileEditor import com.intellij.openapi.fileEditor.FileEditorManager import com.intellij.openapi.module.Module import com.intellij.openapi.module.ModuleUtil import com.intellij.openapi.progress.ProgressManager import com.intellij.openapi.progress.runModalTask import com.intellij.openapi.project.DumbAwareAction import com.intellij.openapi.project.Project import com.intellij.openapi.roots.* import com.intellij.openapi.util.Key import com.intellij.openapi.util.io.FileUtil import com.intellij.openapi.util.registry.Registry import com.intellij.openapi.vcs.FilePath import com.intellij.openapi.vcs.FilesProcessorImpl import com.intellij.openapi.vcs.VcsBundle.message import com.intellij.openapi.vcs.VcsConfiguration import com.intellij.openapi.vcs.VcsNotificationIdsHolder.Companion.IGNORED_TO_EXCLUDE_NOT_FOUND import com.intellij.openapi.vcs.VcsNotifier import com.intellij.openapi.vcs.changes.ChangeListManager import com.intellij.openapi.vcs.changes.VcsIgnoreManagerImpl import com.intellij.openapi.vcs.changes.ignore.lang.IgnoreFileType import com.intellij.openapi.vcs.changes.shelf.ShelveChangesManager import com.intellij.openapi.vcs.changes.ui.SelectFilesDialog import com.intellij.openapi.vcs.ignore.IgnoredToExcludedSynchronizerConstants.ASKED_MARK_IGNORED_FILES_AS_EXCLUDED_PROPERTY import com.intellij.openapi.vfs.VirtualFile import com.intellij.ui.EditorNotificationPanel import com.intellij.ui.EditorNotifications import java.util.* private val LOG = logger<IgnoredToExcludedSynchronizer>() private val excludeAction = object : MarkExcludeRootAction() { fun exclude(module: Module, dirs: Collection<VirtualFile>) = runInEdt { modifyRoots(module, dirs.toTypedArray()) } } /** * Shows [EditorNotifications] in .ignore files with suggestion to exclude ignored directories. * Silently excludes them if [VcsConfiguration.MARK_IGNORED_AS_EXCLUDED] is enabled. * * Not internal service. Can be used directly in related modules. */ @Service class IgnoredToExcludedSynchronizer(project: Project) : FilesProcessorImpl(project, project) { init { project.messageBus.connect(this).subscribe(ProjectTopics.PROJECT_ROOTS, object : ModuleRootListener { override fun rootsChanged(event: ModuleRootEvent) = updateNotificationState() }) project.messageBus.connect(this).subscribe(AdditionalLibraryRootsListener.TOPIC, (AdditionalLibraryRootsListener { _, _, _, _ -> updateNotificationState() })) } private fun updateNotificationState() { if (synchronizationTurnOff()) return // in case if the project roots changed (e.g. by build tools) then the directories shown in notification can be outdated. // filter directories which excluded or containing source roots and expire notification if needed. ChangeListManager.getInstance(project).invokeAfterUpdate(false) { val fileIndex = ProjectFileIndex.getInstance(project) val sourceRoots = getProjectSourceRoots(project) val acquiredFiles = selectValidFiles() LOG.debug("updateNotificationState, acquiredFiles", acquiredFiles) val filesToRemove = acquiredFiles .asSequence() .filter { file -> runReadAction { fileIndex.isExcluded(file) } || sourceRoots.contains(file) } .toList() LOG.debug("updateNotificationState, filesToRemove", filesToRemove) if (removeFiles(filesToRemove)) { EditorNotifications.getInstance(project).updateAllNotifications() } } } fun isNotEmpty() = !isFilesEmpty() fun clearFiles(files: Collection<VirtualFile>) = removeFiles(files) fun getValidFiles() = with(ChangeListManager.getInstance(project)) { selectValidFiles().filter(this::isIgnoredFile) } private fun wasAskedBefore() = PropertiesComponent.getInstance(project).getBoolean(ASKED_MARK_IGNORED_FILES_AS_EXCLUDED_PROPERTY, false) fun muteForCurrentProject() { PropertiesComponent.getInstance(project).setValue(ASKED_MARK_IGNORED_FILES_AS_EXCLUDED_PROPERTY, true) clearFiles() } fun mutedForCurrentProject() = wasAskedBefore() && !needDoForCurrentProject() override fun doActionOnChosenFiles(files: Collection<VirtualFile>) { if (files.isEmpty()) return markIgnoredAsExcluded(project, files) } override fun doFilterFiles(files: Collection<VirtualFile>) = files.filter(VirtualFile::isValid) override fun needDoForCurrentProject() = VcsConfiguration.getInstance(project).MARK_IGNORED_AS_EXCLUDED fun ignoredUpdateFinished(ignoredPaths: Collection<FilePath>) { ProgressManager.checkCanceled() if (synchronizationTurnOff()) return if (mutedForCurrentProject()) return processIgnored(ignoredPaths) } private fun processIgnored(ignoredPaths: Collection<FilePath>) { val ignoredDirs = determineIgnoredDirsToExclude(project, ignoredPaths) if (allowShowNotification()) { processFiles(ignoredDirs) val editorNotifications = EditorNotifications.getInstance(project) FileEditorManager.getInstance(project).openFiles .forEach { openFile -> if (openFile.fileType is IgnoreFileType) { editorNotifications.updateNotifications(openFile) } } } else if (needDoForCurrentProject()) { doActionOnChosenFiles(doFilterFiles(ignoredDirs)) } } } private fun markIgnoredAsExcluded(project: Project, files: Collection<VirtualFile>) { val ignoredDirsByModule = files .groupBy { ModuleUtil.findModuleForFile(it, project) } //if the directory already excluded then ModuleUtil.findModuleForFile return null and this will filter out such directories from processing. .filterKeys(Objects::nonNull) for ((module, ignoredDirs) in ignoredDirsByModule) { excludeAction.exclude(module!!, ignoredDirs) } } private fun getProjectSourceRoots(project: Project): Set<VirtualFile> = runReadAction { OrderEnumerator.orderEntries(project).withoutSdk().withoutLibraries().sources().usingCache().roots.toHashSet() } private fun containsShelfDirectoryOrUnderIt(filePath: FilePath, shelfPath: String) = FileUtil.isAncestor(shelfPath, filePath.path, false) || FileUtil.isAncestor(filePath.path, shelfPath, false) private fun determineIgnoredDirsToExclude(project: Project, ignoredPaths: Collection<FilePath>): List<VirtualFile> { val sourceRoots = getProjectSourceRoots(project) val fileIndex = ProjectFileIndex.getInstance(project) val shelfPath = ShelveChangesManager.getShelfPath(project) return ignoredPaths .asSequence() .filter(FilePath::isDirectory) //shelf directory usually contains in project and excluding it prevents local history to work on it .filterNot { containsShelfDirectoryOrUnderIt(it, shelfPath) } .mapNotNull(FilePath::getVirtualFile) .filterNot { runReadAction { fileIndex.isExcluded(it) } } //do not propose to exclude if there is a source root inside .filterNot { ignored -> sourceRoots.contains(ignored) } .toList() } private fun selectFilesToExclude(project: Project, ignoredDirs: List<VirtualFile>): Collection<VirtualFile> { val dialog = IgnoredToExcludeSelectDirectoriesDialog(project, ignoredDirs) if (!dialog.showAndGet()) return emptyList() return dialog.selectedFiles } private fun allowShowNotification() = Registry.`is`("vcs.propose.add.ignored.directories.to.exclude", true) private fun synchronizationTurnOff() = !Registry.`is`("vcs.enable.add.ignored.directories.to.exclude", true) class IgnoredToExcludeNotificationProvider : EditorNotifications.Provider<EditorNotificationPanel>() { companion object { private val KEY: Key<EditorNotificationPanel> = Key.create("IgnoredToExcludeNotificationProvider") } override fun getKey(): Key<EditorNotificationPanel> = KEY private fun canCreateNotification(project: Project, file: VirtualFile) = file.fileType is IgnoreFileType && with(project.service<IgnoredToExcludedSynchronizer>()) { !synchronizationTurnOff() && allowShowNotification() && !mutedForCurrentProject() && isNotEmpty() } private fun showIgnoredAction(project: Project) { val allFiles = project.service<IgnoredToExcludedSynchronizer>().getValidFiles() if (allFiles.isEmpty()) return val userSelectedFiles = selectFilesToExclude(project, allFiles) if (userSelectedFiles.isEmpty()) return with(project.service<IgnoredToExcludedSynchronizer>()) { markIgnoredAsExcluded(project, userSelectedFiles) clearFiles(userSelectedFiles) } } private fun muteAction(project: Project) = Runnable { project.service<IgnoredToExcludedSynchronizer>().muteForCurrentProject() EditorNotifications.getInstance(project).updateNotifications(this@IgnoredToExcludeNotificationProvider) } override fun createNotificationPanel(file: VirtualFile, fileEditor: FileEditor, project: Project): EditorNotificationPanel? { if (!canCreateNotification(project, file)) return null return EditorNotificationPanel(fileEditor).apply { icon(AllIcons.General.Information) text = message("ignore.to.exclude.notification.message") createActionLabel(message("ignore.to.exclude.notification.action.view")) { showIgnoredAction(project) } createActionLabel(message("ignore.to.exclude.notification.action.mute"), muteAction(project)) createActionLabel(message("ignore.to.exclude.notification.action.details")) { BrowserUtil.browse("https://www.jetbrains.com/help/idea/content-roots.html#folder-categories") } } } } internal class CheckIgnoredToExcludeAction : DumbAwareAction() { override fun update(e: AnActionEvent) { e.presentation.isEnabled = e.project != null } override fun actionPerformed(e: AnActionEvent) { val project = e.project!! runModalTask(ActionsBundle.message("action.CheckIgnoredAndNotExcludedDirectories.progress"), project, true) { VcsIgnoreManagerImpl.getInstanceImpl(project).awaitRefreshQueue() val ignoredFilePaths = ChangeListManager.getInstance(project).ignoredFilePaths val dirsToExclude = determineIgnoredDirsToExclude(project, ignoredFilePaths) if (dirsToExclude.isEmpty()) { VcsNotifier.getInstance(project) .notifyMinorInfo(IGNORED_TO_EXCLUDE_NOT_FOUND, "", message("ignore.to.exclude.no.directories.found")) } else { val userSelectedFiles = selectFilesToExclude(project, dirsToExclude) if (userSelectedFiles.isNotEmpty()) { markIgnoredAsExcluded(project, userSelectedFiles) } } } } } // do not use SelectFilesDialog.init because it doesn't provide clear statistic: what exactly dialog shown/closed, action clicked private class IgnoredToExcludeSelectDirectoriesDialog( project: Project?, files: List<VirtualFile> ) : SelectFilesDialog(project, files, message("ignore.to.exclude.notification.notice"), null, true, true) { init { title = message("ignore.to.exclude.view.dialog.title") selectedFiles = files setOKButtonText(message("ignore.to.exclude.view.dialog.exclude.action")) setCancelButtonText(CommonBundle.getCancelButtonText()) init() } }
apache-2.0
b19f1eff9d6a5d99ef076d6bd109676a
41.412811
146
0.771019
4.695823
false
false
false
false
jwren/intellij-community
plugins/kotlin/uast/uast-kotlin-idea/src/org/jetbrains/uast/kotlin/generate/KotlinUastCodeGenerationPlugin.kt
1
22422
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package org.jetbrains.uast.kotlin.generate import com.intellij.lang.Language import com.intellij.openapi.diagnostic.logger import com.intellij.openapi.project.Project import com.intellij.openapi.util.text.StringUtil import com.intellij.psi.* import com.intellij.psi.util.PsiTreeUtil import org.jetbrains.kotlin.idea.KotlinLanguage import org.jetbrains.kotlin.idea.caches.resolve.getResolutionFacade import org.jetbrains.kotlin.idea.core.* import org.jetbrains.kotlin.idea.refactoring.fqName.fqName import org.jetbrains.kotlin.idea.references.KtSimpleNameReference import org.jetbrains.kotlin.idea.references.KtSimpleNameReferenceDescriptorsImpl import org.jetbrains.kotlin.idea.util.getResolutionScope import org.jetbrains.kotlin.idea.util.resolveToKotlinType import org.jetbrains.kotlin.incremental.components.NoLookupLocation import org.jetbrains.kotlin.name.Name import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.* import org.jetbrains.kotlin.resolve.scopes.utils.findClassifier import org.jetbrains.kotlin.utils.addToStdlib.safeAs import org.jetbrains.uast.* import org.jetbrains.uast.generate.UParameterInfo import org.jetbrains.uast.generate.UastCodeGenerationPlugin import org.jetbrains.uast.generate.UastElementFactory import org.jetbrains.uast.kotlin.* import org.jetbrains.uast.kotlin.internal.KotlinFakeUElement class KotlinUastCodeGenerationPlugin : UastCodeGenerationPlugin { override val language: Language get() = KotlinLanguage.INSTANCE override fun getElementFactory(project: Project): UastElementFactory = KotlinUastElementFactory(project) override fun <T : UElement> replace(oldElement: UElement, newElement: T, elementType: Class<T>): T? { val oldPsi = oldElement.toSourcePsiFakeAware().singleOrNull() ?: return null val newPsi = newElement.sourcePsi?.let { when { it is KtCallExpression && it.parent is KtQualifiedExpression -> it.parent else -> it } } ?: return null val psiFactory = KtPsiFactory(oldPsi.project) val oldParentPsi = oldPsi.parent val (updOldPsi, updNewPsi) = when { oldParentPsi is KtStringTemplateExpression && oldParentPsi.entries.size == 1 -> oldParentPsi to newPsi oldPsi is KtStringTemplateEntry && newPsi !is KtStringTemplateEntry && newPsi is KtExpression -> oldPsi to psiFactory.createBlockStringTemplateEntry(newPsi) oldPsi is KtBlockExpression && newPsi is KtBlockExpression -> { if (!hasBraces(oldPsi) && hasBraces(newPsi)) { oldPsi to psiFactory.createLambdaExpression("none", newPsi.statements.joinToString("\n") { "println()" }).bodyExpression!!.also { it.statements.zip(newPsi.statements).forEach { it.first.replace(it.second) } } } else oldPsi to newPsi } else -> oldPsi to newPsi } val replaced = updOldPsi.replace(updNewPsi)?.safeAs<KtElement>()?.let { ShortenReferences.DEFAULT.process(it) } return when { newElement.sourcePsi is KtCallExpression && replaced is KtQualifiedExpression -> replaced.selectorExpression else -> replaced }?.toUElementOfExpectedTypes(elementType) } override fun bindToElement(reference: UReferenceExpression, element: PsiElement): PsiElement? { val sourcePsi = reference.sourcePsi ?: return null if (sourcePsi !is KtSimpleNameExpression) return null return KtSimpleNameReferenceDescriptorsImpl(sourcePsi) .bindToElement(element, KtSimpleNameReference.ShorteningMode.FORCED_SHORTENING) } override fun shortenReference(reference: UReferenceExpression): UReferenceExpression? { val sourcePsi = reference.sourcePsi ?: return null if (sourcePsi !is KtElement) return null return ShortenReferences.DEFAULT.process(sourcePsi).toUElementOfType() } } private fun hasBraces(oldPsi: KtBlockExpression): Boolean = oldPsi.lBrace != null && oldPsi.rBrace != null class KotlinUastElementFactory(project: Project) : UastElementFactory { private val psiFactory = KtPsiFactory(project) @Suppress("UNUSED_PARAMETER") override fun createQualifiedReference(qualifiedName: String, context: PsiElement?): UQualifiedReferenceExpression? { return psiFactory.createExpression(qualifiedName).let { when (it) { is KtDotQualifiedExpression -> KotlinUQualifiedReferenceExpression(it, null) is KtSafeQualifiedExpression -> KotlinUSafeQualifiedExpression(it, null) else -> null } } } override fun createCallExpression( receiver: UExpression?, methodName: String, parameters: List<UExpression>, expectedReturnType: PsiType?, kind: UastCallKind, context: PsiElement? ): UCallExpression? { if (kind != UastCallKind.METHOD_CALL) return null val name = methodName.quoteIfNeeded() val methodCall = psiFactory.createExpression( buildString { if (receiver != null) { append("a") receiver.sourcePsi?.nextSibling.safeAs<PsiWhiteSpace>()?.let { whitespaces -> append(whitespaces.text) } append(".") } append(name) append("()") } ).getPossiblyQualifiedCallExpression() ?: return null if (receiver != null) { methodCall.parent.safeAs<KtDotQualifiedExpression>()?.receiverExpression?.replace(wrapULiteral(receiver).sourcePsi!!) } val valueArgumentList = methodCall.valueArgumentList for (parameter in parameters) { valueArgumentList?.addArgument(psiFactory.createArgument(wrapULiteral(parameter).sourcePsi as KtExpression)) } if (context !is KtElement) return KotlinUFunctionCallExpression(methodCall, null) val analyzableMethodCall = psiFactory.getAnalyzableMethodCall(methodCall, context) if (analyzableMethodCall.canMoveLambdaOutsideParentheses()) { analyzableMethodCall.moveFunctionLiteralOutsideParentheses() } if (expectedReturnType == null) return KotlinUFunctionCallExpression(analyzableMethodCall, null) val methodCallPsiType = KotlinUFunctionCallExpression(analyzableMethodCall, null).getExpressionType() if (methodCallPsiType == null || !expectedReturnType.isAssignableFrom(GenericsUtil.eliminateWildcards(methodCallPsiType))) { val typeParams = (context as? KtElement)?.let { kontext -> val resolutionFacade = kontext.getResolutionFacade() (expectedReturnType as? PsiClassType)?.parameters?.map { it.resolveToKotlinType(resolutionFacade) } } if (typeParams == null) return KotlinUFunctionCallExpression(analyzableMethodCall, null) for (typeParam in typeParams) { val typeParameter = psiFactory.createTypeArgument(typeParam.fqName?.asString().orEmpty()) analyzableMethodCall.addTypeArgument(typeParameter) } return KotlinUFunctionCallExpression(analyzableMethodCall, null) } return KotlinUFunctionCallExpression(analyzableMethodCall, null) } private fun KtPsiFactory.getAnalyzableMethodCall(methodCall: KtCallExpression, context: KtElement): KtCallExpression { val analyzableElement = ((createExpressionCodeFragment("(null)", context).copy() as KtExpressionCodeFragment) .getContentElement()!! as KtParenthesizedExpression).expression!! val isQualified = methodCall.parent is KtQualifiedExpression return if (isQualified) { (analyzableElement.replaced(methodCall.parent) as KtQualifiedExpression).lastChild as KtCallExpression } else { analyzableElement.replaced(methodCall) } } override fun createCallableReferenceExpression( receiver: UExpression?, methodName: String, context: PsiElement? ): UCallableReferenceExpression? { val text = receiver?.sourcePsi?.text ?: "" val callableExpression = psiFactory.createCallableReferenceExpression("$text::$methodName") ?: return null return KotlinUCallableReferenceExpression(callableExpression, null) } override fun createStringLiteralExpression(text: String, context: PsiElement?): ULiteralExpression { return KotlinStringULiteralExpression(psiFactory.createExpression(StringUtil.wrapWithDoubleQuote(text)), null) } override fun createLongConstantExpression(long: Long, context: PsiElement?): UExpression? { return when (val literalExpr = psiFactory.createExpression(long.toString() + "L")) { is KtConstantExpression -> KotlinULiteralExpression(literalExpr, null) is KtPrefixExpression -> KotlinUPrefixExpression(literalExpr, null) else -> null } } override fun createNullLiteral(context: PsiElement?): ULiteralExpression { return psiFactory.createExpression("null").toUElementOfType()!! } @Suppress("UNUSED_PARAMETER") /*override*/ fun createIntLiteral(value: Int, context: PsiElement?): ULiteralExpression { return psiFactory.createExpression(value.toString()).toUElementOfType()!! } private fun KtExpression.ensureBlockExpressionBraces(): KtExpression { if (this !is KtBlockExpression || hasBraces(this)) return this val blockExpression = psiFactory.createBlock(this.statements.joinToString("\n") { "println()" }) for ((placeholder, statement) in blockExpression.statements.zip(this.statements)) { placeholder.replace(statement) } return blockExpression } @Deprecated("use version with context parameter") fun createIfExpression(condition: UExpression, thenBranch: UExpression, elseBranch: UExpression?): UIfExpression? { logger<KotlinUastElementFactory>().error("Please switch caller to the version with a context parameter") return createIfExpression(condition, thenBranch, elseBranch, null) } override fun createIfExpression( condition: UExpression, thenBranch: UExpression, elseBranch: UExpression?, context: PsiElement? ): UIfExpression? { val conditionPsi = condition.sourcePsi as? KtExpression ?: return null val thenBranchPsi = thenBranch.sourcePsi as? KtExpression ?: return null val elseBranchPsi = elseBranch?.sourcePsi as? KtExpression return KotlinUIfExpression( psiFactory.createIf(conditionPsi, thenBranchPsi.ensureBlockExpressionBraces(), elseBranchPsi?.ensureBlockExpressionBraces()), givenParent = null ) } @Deprecated("use version with context parameter") fun createParenthesizedExpression(expression: UExpression): UParenthesizedExpression? { logger<KotlinUastElementFactory>().error("Please switch caller to the version with a context parameter") return createParenthesizedExpression(expression, null) } override fun createParenthesizedExpression(expression: UExpression, context: PsiElement?): UParenthesizedExpression? { val source = expression.sourcePsi ?: return null val parenthesized = psiFactory.createExpression("(${source.text})") as? KtParenthesizedExpression ?: return null return KotlinUParenthesizedExpression(parenthesized, null) } @Deprecated("use version with context parameter") fun createSimpleReference(name: String): USimpleNameReferenceExpression? { logger<KotlinUastElementFactory>().error("Please switch caller to the version with a context parameter") return createSimpleReference(name, null) } override fun createSimpleReference(name: String, context: PsiElement?): USimpleNameReferenceExpression { return KotlinUSimpleReferenceExpression(psiFactory.createSimpleName(name), null) } @Deprecated("use version with context parameter") fun createSimpleReference(variable: UVariable): USimpleNameReferenceExpression? { logger<KotlinUastElementFactory>().error("Please switch caller to the version with a context parameter") return createSimpleReference(variable, null) } override fun createSimpleReference(variable: UVariable, context: PsiElement?): USimpleNameReferenceExpression? { return createSimpleReference(variable.name ?: return null, context) } @Deprecated("use version with context parameter") fun createReturnExpresion(expression: UExpression?, inLambda: Boolean): UReturnExpression? { logger<KotlinUastElementFactory>().error("Please switch caller to the version with a context parameter") return createReturnExpresion(expression, inLambda, null) } override fun createReturnExpresion(expression: UExpression?, inLambda: Boolean, context: PsiElement?): UReturnExpression { val label = if (inLambda && context != null) getParentLambdaLabelName(context)?.let { "@$it" } ?: "" else "" val returnExpression = psiFactory.createExpression("return$label 1") as KtReturnExpression val sourcePsi = expression?.sourcePsi if (sourcePsi != null) { returnExpression.returnedExpression!!.replace(sourcePsi) } else { returnExpression.returnedExpression?.delete() } return KotlinUReturnExpression(returnExpression, null) } private fun getParentLambdaLabelName(context: PsiElement): String? { val lambdaExpression = context.getParentOfType<KtLambdaExpression>(false) ?: return null lambdaExpression.parent.safeAs<KtLabeledExpression>()?.let { return it.getLabelName() } val callExpression = lambdaExpression.getStrictParentOfType<KtCallExpression>() ?: return null callExpression.valueArguments.find { it.getArgumentExpression()?.unpackFunctionLiteral(allowParentheses = false) === lambdaExpression } ?: return null return callExpression.getCallNameExpression()?.text } @Deprecated("use version with context parameter") fun createBinaryExpression( leftOperand: UExpression, rightOperand: UExpression, operator: UastBinaryOperator ): UBinaryExpression? { logger<KotlinUastElementFactory>().error("Please switch caller to the version with a context parameter") return createBinaryExpression(leftOperand, rightOperand, operator, null) } override fun createBinaryExpression( leftOperand: UExpression, rightOperand: UExpression, operator: UastBinaryOperator, context: PsiElement? ): UBinaryExpression? { val binaryExpression = joinBinaryExpression(leftOperand, rightOperand, operator) ?: return null return KotlinUBinaryExpression(binaryExpression, null) } private fun joinBinaryExpression( leftOperand: UExpression, rightOperand: UExpression, operator: UastBinaryOperator ): KtBinaryExpression? { val leftPsi = leftOperand.sourcePsi ?: return null val rightPsi = rightOperand.sourcePsi ?: return null val binaryExpression = psiFactory.createExpression("a ${operator.text} b") as? KtBinaryExpression ?: return null binaryExpression.left?.replace(leftPsi) binaryExpression.right?.replace(rightPsi) return binaryExpression } @Deprecated("use version with context parameter") fun createFlatBinaryExpression( leftOperand: UExpression, rightOperand: UExpression, operator: UastBinaryOperator ): UPolyadicExpression? { logger<KotlinUastElementFactory>().error("Please switch caller to the version with a context parameter") return createFlatBinaryExpression(leftOperand, rightOperand, operator, null) } override fun createFlatBinaryExpression( leftOperand: UExpression, rightOperand: UExpression, operator: UastBinaryOperator, context: PsiElement? ): UPolyadicExpression? { fun unwrapParentheses(exp: KtExpression?) { if (exp !is KtParenthesizedExpression) return if (!KtPsiUtil.areParenthesesUseless(exp)) return exp.expression?.let { exp.replace(it) } } val binaryExpression = joinBinaryExpression(leftOperand, rightOperand, operator) ?: return null unwrapParentheses(binaryExpression.left) unwrapParentheses(binaryExpression.right) return psiFactory.createExpression(binaryExpression.text).toUElementOfType()!! } @Deprecated("use version with context parameter") fun createBlockExpression(expressions: List<UExpression>): UBlockExpression? { logger<KotlinUastElementFactory>().error("Please switch caller to the version with a context parameter") return createBlockExpression(expressions, null) } override fun createBlockExpression(expressions: List<UExpression>, context: PsiElement?): UBlockExpression { val sourceExpressions = expressions.flatMap { it.toSourcePsiFakeAware() } val block = psiFactory.createBlock( sourceExpressions.joinToString(separator = "\n") { "println()" } ) for ((placeholder, psiElement) in block.statements.zip(sourceExpressions)) { placeholder.replace(psiElement) } return KotlinUBlockExpression(block, null) } @Deprecated("use version with context parameter") fun createDeclarationExpression(declarations: List<UDeclaration>): UDeclarationsExpression? { logger<KotlinUastElementFactory>().error("Please switch caller to the version with a context parameter") return createDeclarationExpression(declarations, null) } override fun createDeclarationExpression(declarations: List<UDeclaration>, context: PsiElement?): UDeclarationsExpression { return object : KotlinUDeclarationsExpression(null), KotlinFakeUElement { override var declarations: List<UDeclaration> = declarations override fun unwrapToSourcePsi(): List<PsiElement> = declarations.flatMap { it.toSourcePsiFakeAware() } } } override fun createLambdaExpression( parameters: List<UParameterInfo>, body: UExpression, context: PsiElement? ): ULambdaExpression? { val resolutionFacade = (context as? KtElement)?.getResolutionFacade() val validator = (context as? KtElement)?.let { usedNamesFilter(it) } ?: { true } val newLambdaStatements = if (body is UBlockExpression) { body.expressions.flatMap { member -> when { member is UReturnExpression -> member.returnExpression?.toSourcePsiFakeAware().orEmpty() else -> member.toSourcePsiFakeAware() } } } else listOf(body.sourcePsi!!) val ktLambdaExpression = psiFactory.createLambdaExpression( parameters.joinToString(", ") { p -> val ktype = resolutionFacade?.let { p.type?.resolveToKotlinType(it) } StringBuilder().apply { append(p.suggestedName ?: ktype?.let { KotlinNameSuggester.suggestNamesByType(it, validator).firstOrNull() }) ?: KotlinNameSuggester.suggestNameByName("v", validator) ktype?.fqName?.toString()?.let { append(": ").append(it) } } }, newLambdaStatements.joinToString("\n") { "placeholder" } ) for ((old, new) in ktLambdaExpression.bodyExpression!!.statements.zip(newLambdaStatements)) { old.replace(new) } return ktLambdaExpression.toUElementOfType()!! } @Deprecated("use version with context parameter") fun createLambdaExpression(parameters: List<UParameterInfo>, body: UExpression): ULambdaExpression? { logger<KotlinUastElementFactory>().error("Please switch caller to the version with a context parameter") return createLambdaExpression(parameters, body, null) } override fun createLocalVariable( suggestedName: String?, type: PsiType?, initializer: UExpression, immutable: Boolean, context: PsiElement? ): ULocalVariable { val resolutionFacade = (context as? KtElement)?.getResolutionFacade() val validator = (context as? KtElement)?.let { usedNamesFilter(it) } ?: { true } val ktype = resolutionFacade?.let { type?.resolveToKotlinType(it) } val function = psiFactory.createFunction( buildString { append("fun foo() { ") append(if (immutable) "val" else "var") append(" ") append(suggestedName ?: ktype?.let { KotlinNameSuggester.suggestNamesByType(it, validator).firstOrNull() }) ?: KotlinNameSuggester.suggestNameByName("v", validator) ktype?.fqName?.toString()?.let { append(": ").append(it) } append(" = null") append("}") } ) val ktVariable = PsiTreeUtil.findChildOfType(function, KtVariableDeclaration::class.java)!! val newVariable = ktVariable.initializer!!.replace(initializer.sourcePsi!!).parent return newVariable.toUElementOfType<UVariable>() as ULocalVariable } @Deprecated("use version with context parameter") fun createLocalVariable( suggestedName: String?, type: PsiType?, initializer: UExpression, immutable: Boolean ): ULocalVariable? { logger<KotlinUastElementFactory>().error("Please switch caller to the version with a context parameter") return createLocalVariable(suggestedName, type, initializer, immutable, null) } } private fun usedNamesFilter(context: KtElement): (String) -> Boolean { val scope = context.getResolutionScope() return { name: String -> scope.findClassifier(Name.identifier(name), NoLookupLocation.FROM_IDE) == null } }
apache-2.0
325c62fda88daa37a9fce573940ab60c
45.518672
149
0.692713
5.85278
false
false
false
false
jwren/intellij-community
plugins/kotlin/frontend-independent/src/org/jetbrains/kotlin/idea/search/usagesSearch/utilsIndependent.kt
4
5279
// 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.search.usagesSearch import com.intellij.openapi.application.ApplicationManager import com.intellij.psi.* import com.intellij.psi.search.SearchScope import com.intellij.psi.search.searches.MethodReferencesSearch import com.intellij.psi.search.searches.ReferencesSearch import org.jetbrains.kotlin.asJava.elements.KtLightElement import org.jetbrains.kotlin.asJava.elements.KtLightMethod import org.jetbrains.kotlin.asJava.toLightMethods import org.jetbrains.kotlin.asJava.unwrapped import org.jetbrains.kotlin.idea.search.KotlinSearchUsagesSupport import org.jetbrains.kotlin.idea.search.KotlinSearchUsagesSupport.Companion.createConstructorHandle import org.jetbrains.kotlin.idea.search.declarationsSearch.HierarchySearchRequest import org.jetbrains.kotlin.idea.search.declarationsSearch.searchInheritors import org.jetbrains.kotlin.idea.util.application.runReadAction import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.contains fun PsiElement.processDelegationCallConstructorUsages(scope: SearchScope, process: (KtCallElement) -> Boolean): Boolean { val task = buildProcessDelegationCallConstructorUsagesTask(scope, process) return task() } // should be executed under read-action, returns long-running part to be executed outside read-action fun PsiElement.buildProcessDelegationCallConstructorUsagesTask(scope: SearchScope, process: (KtCallElement) -> Boolean): () -> Boolean { ApplicationManager.getApplication().assertReadAccessAllowed() val task1 = buildProcessDelegationCallKotlinConstructorUsagesTask(scope, process) val task2 = buildProcessDelegationCallJavaConstructorUsagesTask(scope, process) return { task1() && task2() } } private fun PsiElement.buildProcessDelegationCallKotlinConstructorUsagesTask( scope: SearchScope, process: (KtCallElement) -> Boolean ): () -> Boolean { val element = unwrapped if (element != null && element !in scope) return { true } val klass = when (element) { is KtConstructor<*> -> element.getContainingClassOrObject() is KtClass -> element else -> return { true } } if (klass !is KtClass || element !is KtDeclaration) return { true } val constructorHandler = createConstructorHandle(element) if (!processClassDelegationCallsToSpecifiedConstructor(klass, constructorHandler, process)) return { false } // long-running task, return it to execute outside read-action return { processInheritorsDelegatingCallToSpecifiedConstructor(klass, scope, constructorHandler, process) } } private fun PsiElement.buildProcessDelegationCallJavaConstructorUsagesTask( scope: SearchScope, process: (KtCallElement) -> Boolean ): () -> Boolean { if (this is KtLightElement<*, *>) return { true } // TODO: Temporary hack to avoid NPE while KotlinNoOriginLightMethod is around if (this is KtLightMethod && this.kotlinOrigin == null) return { true } if (!(this is PsiMethod && isConstructor)) return { true } val klass = containingClass ?: return { true } val ctorHandle = createConstructorHandle(this) return { processInheritorsDelegatingCallToSpecifiedConstructor(klass, scope, ctorHandle, process) } } private fun processInheritorsDelegatingCallToSpecifiedConstructor( klass: PsiElement, scope: SearchScope, constructorCallComparator: KotlinSearchUsagesSupport.ConstructorCallHandle, process: (KtCallElement) -> Boolean ): Boolean { return HierarchySearchRequest(klass, scope, false).searchInheritors().all { runReadAction { val unwrapped = it.takeIf { it.isValid }?.unwrapped if (unwrapped is KtClass) processClassDelegationCallsToSpecifiedConstructor(unwrapped, constructorCallComparator, process) else true } } } private fun processClassDelegationCallsToSpecifiedConstructor( klass: KtClass, constructorCallHandle: KotlinSearchUsagesSupport.ConstructorCallHandle, process: (KtCallElement) -> Boolean ): Boolean { for (secondaryConstructor in klass.secondaryConstructors) { val delegationCall = secondaryConstructor.getDelegationCall() if (constructorCallHandle.referencedTo(delegationCall)) { if (!process(delegationCall)) return false } } if (!klass.isEnum()) return true for (declaration in klass.declarations) { if (declaration is KtEnumEntry) { val delegationCall = declaration.superTypeListEntries.firstOrNull() as? KtSuperTypeCallEntry ?: continue if (constructorCallHandle.referencedTo(delegationCall.calleeExpression)) { if (!process(delegationCall)) return false } } } return true } fun PsiElement.searchReferencesOrMethodReferences(): Collection<PsiReference> { val lightMethods = toLightMethods() return if (lightMethods.isNotEmpty()) { lightMethods.flatMapTo(LinkedHashSet()) { MethodReferencesSearch.search(it) } } else { ReferencesSearch.search(this).findAll() } }
apache-2.0
286206299ed657e0d0460ee33883876f
41.926829
158
0.748248
5.110358
false
false
false
false
vovagrechka/fucking-everything
phizdets/phizdetsc/src/org/jetbrains/kotlin/js/descriptorUtils/descriptorUtils.kt
3
2315
/* * Copyright 2010-2016 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.kotlin.js.descriptorUtils import com.intellij.openapi.util.text.StringUtil import org.jetbrains.kotlin.builtins.KotlinBuiltIns import org.jetbrains.kotlin.descriptors.ClassDescriptor import org.jetbrains.kotlin.descriptors.DeclarationDescriptor import org.jetbrains.kotlin.descriptors.TypeParameterDescriptor import org.jetbrains.kotlin.descriptors.impl.AnonymousFunctionDescriptor import org.jetbrains.kotlin.name.Name import org.jetbrains.kotlin.resolve.DescriptorUtils import org.jetbrains.kotlin.types.KotlinType import org.jetbrains.kotlin.utils.addToStdlib.check val KotlinType.nameIfStandardType: Name? get() = constructor.declarationDescriptor?.check(KotlinBuiltIns::isBuiltIn)?.name fun KotlinType.getJetTypeFqName(printTypeArguments: Boolean): String { val declaration = requireNotNull(constructor.declarationDescriptor) if (declaration is TypeParameterDescriptor) { return StringUtil.join(declaration.upperBounds, { type -> type.getJetTypeFqName(printTypeArguments) }, "&") } val typeArguments = arguments val typeArgumentsAsString: String if (printTypeArguments && !typeArguments.isEmpty()) { val joinedTypeArguments = StringUtil.join(typeArguments, { projection -> projection.type.getJetTypeFqName(false) }, ", ") typeArgumentsAsString = "<$joinedTypeArguments>" } else { typeArgumentsAsString = "" } return DescriptorUtils.getFqName(declaration).asString() + typeArgumentsAsString } fun ClassDescriptor.hasPrimaryConstructor(): Boolean = unsubstitutedPrimaryConstructor != null val DeclarationDescriptor.isCoroutineLambda: Boolean get() = this is AnonymousFunctionDescriptor && isSuspend
apache-2.0
867da536cacb6dadd19b0e9ef3956617
39.614035
129
0.781425
4.743852
false
false
false
false
jwren/intellij-community
plugins/git4idea/src/git4idea/pull/GitPullDialog.kt
1
14707
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package git4idea.pull import com.intellij.codeInsight.hint.HintUtil import com.intellij.dvcs.DvcsUtil.sortRepositories import com.intellij.ide.actions.RefreshAction import com.intellij.ide.ui.laf.darcula.DarculaUIUtil.BW import com.intellij.openapi.actionSystem.* import com.intellij.openapi.components.service import com.intellij.openapi.keymap.KeymapUtil import com.intellij.openapi.progress.ProgressIndicator import com.intellij.openapi.progress.Task.Backgroundable import com.intellij.openapi.project.Project import com.intellij.openapi.ui.ComboBox import com.intellij.openapi.ui.DialogWrapper import com.intellij.openapi.ui.ValidationInfo import com.intellij.openapi.util.SystemInfo import com.intellij.openapi.util.text.HtmlChunk import com.intellij.openapi.util.text.HtmlChunk.Element.html import com.intellij.openapi.vcs.VcsNotifier import com.intellij.openapi.vfs.VirtualFile import com.intellij.ui.MutableCollectionComboBoxModel import com.intellij.ui.SimpleListCellRenderer import com.intellij.ui.components.DropDownLink import com.intellij.util.ui.JBDimension import com.intellij.util.ui.JBUI import git4idea.GitNotificationIdsHolder.Companion.FETCH_ERROR import git4idea.GitRemoteBranch import git4idea.GitUtil import git4idea.GitVcs import git4idea.branch.GitBranchUtil import git4idea.config.GitExecutableManager import git4idea.config.GitPullSettings import git4idea.config.GitVersionSpecialty.NO_VERIFY_SUPPORTED import git4idea.fetch.GitFetchSupport import git4idea.i18n.GitBundle import git4idea.merge.GIT_REF_PROTOTYPE_VALUE import git4idea.merge.createRepositoryField import git4idea.merge.createSouthPanelWithOptionsDropDown import git4idea.merge.dialog.* import git4idea.merge.validateBranchExists import git4idea.repo.GitRemote import git4idea.repo.GitRepository import git4idea.repo.GitRepositoryManager import git4idea.ui.ComboBoxWithAutoCompletion import net.miginfocom.layout.AC import net.miginfocom.layout.CC import net.miginfocom.layout.LC import net.miginfocom.swing.MigLayout import java.awt.Insets import java.awt.event.ItemEvent import java.awt.event.KeyEvent import javax.swing.JComponent import javax.swing.JPanel import javax.swing.KeyStroke import javax.swing.SwingConstants class GitPullDialog(private val project: Project, private val roots: List<VirtualFile>, private val defaultRoot: VirtualFile) : DialogWrapper(project) { val selectedOptions = mutableSetOf<GitPullOption>() private val fetchSupport = project.service<GitFetchSupport>() private val pullSettings = project.service<GitPullSettings>() private val repositories = sortRepositories(GitRepositoryManager.getInstance(project).repositories) private val branches = collectBranches().toMutableMap() private val optionInfos = mutableMapOf<GitPullOption, OptionInfo<GitPullOption>>() private val popupBuilder = createPopupBuilder() private val repositoryField = createRepoField() private val remoteField = createRemoteField() private val branchField = createBranchField() private val commandPanel = createCommandPanel() private val optionsPanel = GitOptionsPanel(::optionChosen, ::getOptionInfo) private val panel = createPanel() private val isNoVerifySupported = NO_VERIFY_SUPPORTED.existsIn(GitExecutableManager.getInstance().getVersion(project)) init { updateTitle() setOKButtonText(GitBundle.message("pull.button")) loadSettings() updateRemotesField() init() updateUi() } override fun createCenterPanel() = panel override fun getPreferredFocusedComponent() = branchField override fun createSouthPanel() = createSouthPanelWithOptionsDropDown(super.createSouthPanel(), createOptionsDropDown()) override fun getHelpId() = "reference.VersionControl.Git.Pull" override fun doValidateAll() = listOf(::validateRepositoryField, ::validateRemoteField, ::validateBranchField).mapNotNull { it() } override fun doOKAction() { try { saveSettings() } finally { super.doOKAction() } } fun gitRoot() = getSelectedRepository()?.root ?: error("No selected repository found") fun getSelectedRemote(): GitRemote = remoteField.item ?: error("No selected remote found") fun getSelectedBranch(): GitRemoteBranch { val repository = getSelectedRepository() ?: error("No selected repository found") val remote = getSelectedRemote() val branchName = "${remote.name}/${branchField.item}" return repository.branches.findRemoteBranch(branchName) ?: error("Unable to find remote branch: $branchName") } fun isCommitAfterMerge() = GitPullOption.NO_COMMIT !in selectedOptions private fun getRemote(): GitRemote? = remoteField.item private fun loadSettings() { selectedOptions += pullSettings.options } private fun saveSettings() { pullSettings.options = selectedOptions } private fun collectBranches() = repositories.associateWith { repository -> getBranchesInRepo(repository) } private fun getBranchesInRepo(repository: GitRepository) = repository.branches.remoteBranches .sortedBy { branch -> branch.nameForRemoteOperations } .groupBy { branch -> branch.remote } private fun validateRepositoryField(): ValidationInfo? { return if (getSelectedRepository() != null) null else ValidationInfo(GitBundle.message("pull.repository.not.selected.error"), repositoryField) } private fun validateRemoteField(): ValidationInfo? { return if (getRemote() != null) null else ValidationInfo(GitBundle.message("pull.remote.not.selected"), remoteField) } private fun validateBranchField() = validateBranchExists(branchField, "pull.branch.not.selected.error") private fun getSelectedRepository(): GitRepository? = repositoryField.item private fun updateRemotesField() { val repository = getSelectedRepository() val model = remoteField.model as MutableCollectionComboBoxModel model.update(repository?.remotes?.toList() ?: emptyList()) model.selectedItem = getCurrentOrDefaultRemote(repository) } private fun updateBranchesField() { var branchToSelect = branchField.item val repository = getSelectedRepository() ?: return val remote = getRemote() ?: return val branches = GitBranchUtil.sortBranchNames(getRemoteBranches(repository, remote)) val model = branchField.model as MutableCollectionComboBoxModel model.update(branches) if (branchToSelect == null || branchToSelect !in branches) { branchToSelect = repository.currentBranch?.findTrackedBranch(repository)?.nameForRemoteOperations ?: branches.find { branch -> branch == repository.currentBranchName } ?: "" } if (branchToSelect.isEmpty()) { startTrackingValidation() } branchField.selectedItem = branchToSelect } private fun getRemoteBranches(repository: GitRepository, remote: GitRemote): List<String> { return branches[repository]?.get(remote)?.map { it.nameForRemoteOperations } ?: emptyList() } private fun getCurrentOrDefaultRemote(repository: GitRepository?): GitRemote? { val remotes = repository?.remotes ?: return null if (remotes.isEmpty()) { return null } return GitUtil.getTrackInfoForCurrentBranch(repository)?.remote ?: GitUtil.getDefaultOrFirstRemote(remotes) } private fun optionChosen(option: GitPullOption) { if (option !in selectedOptions) { selectedOptions += option } else { selectedOptions -= option } updateUi() } private fun performFetch() { if (fetchSupport.isFetchRunning) { return } val repository = getSelectedRepository() val remote = getRemote() if (repository == null || remote == null) { VcsNotifier.getInstance(project).notifyError(FETCH_ERROR, GitBundle.message("pull.fetch.failed.notification.title"), GitBundle.message("pull.fetch.failed.notification.text")) return } GitVcs.runInBackground(getFetchTask(repository, remote)) } private fun getFetchTask(repository: GitRepository, remote: GitRemote) = object : Backgroundable(project, GitBundle.message("fetching"), true) { override fun run(indicator: ProgressIndicator) { fetchSupport.fetch(repository, remote) } override fun onSuccess() { branches[repository] = getBranchesInRepo(repository) if (getSelectedRepository() == repository && getRemote() == remote) { updateBranchesField() } } } private fun createPopupBuilder() = GitOptionsPopupBuilder( project, GitBundle.message("pull.options.modify.popup.title"), ::getOptions, ::getOptionInfo, ::isOptionSelected, ::isOptionEnabled, ::optionChosen ) private fun isOptionSelected(option: GitPullOption) = option in selectedOptions private fun createOptionsDropDown() = DropDownLink(GitBundle.message("merge.options.modify")) { popupBuilder.createPopup() }.apply { mnemonic = KeyEvent.VK_M } private fun getOptionInfo(option: GitPullOption) = optionInfos.computeIfAbsent(option) { OptionInfo(option, option.option, option.description) } private fun getOptions(): List<GitPullOption> = GitPullOption.values().toMutableList().apply { if (!isNoVerifySupported) { remove(GitPullOption.NO_VERIFY) } } private fun updateUi() { optionsPanel.rerender(selectedOptions) rerender() } private fun rerender() { window.pack() window.revalidate() pack() repaint() } private fun isOptionEnabled(option: GitPullOption) = selectedOptions.all { it.isOptionSuitable(option) } private fun updateTitle() { val currentBranchName = getSelectedRepository()?.currentBranchName title = (if (currentBranchName.isNullOrEmpty()) GitBundle.message("pull.dialog.title") else GitBundle.message("pull.dialog.with.branch.title", currentBranchName)) } private fun createPanel() = JPanel().apply { layout = MigLayout(LC().insets("0").hideMode(3), AC().grow()) add(commandPanel, CC().growX()) add(optionsPanel, CC().newline().width("100%").alignY("top")) } private fun showRootField() = roots.size > 1 private fun createCommandPanel() = JPanel().apply { val colConstraints = if (showRootField()) AC().grow(100f, 0, 3) else AC().grow(100f, 2) layout = MigLayout( LC() .fillX() .insets("0") .gridGap("0", "0") .noVisualPadding(), colConstraints) if (showRootField()) { add(repositoryField, CC() .gapAfter("0") .minWidth("${JBUI.scale(115)}px") .growX()) } add(createCmdLabel(), CC() .gapAfter("0") .alignY("top") .minWidth("${JBUI.scale(85)}px")) add(remoteField, CC() .alignY("top") .minWidth("${JBUI.scale(90)}px")) add(branchField, CC() .alignY("top") .minWidth("${JBUI.scale(250)}px") .growX()) } private fun createCmdLabel() = CmdLabel("git pull", Insets(1, if (showRootField()) 0 else 1, 1, 0), JBDimension(JBUI.scale(85), branchField.preferredSize.height, true)) private fun createRepoField() = createRepositoryField(repositories, defaultRoot).apply { addActionListener { updateTitle() updateRemotesField() } } private fun createRemoteField() = ComboBox<GitRemote>(MutableCollectionComboBoxModel()).apply { isSwingPopup = false renderer = SimpleListCellRenderer.create( HtmlChunk.text(GitBundle.message("util.remote.renderer.none")).italic().wrapWith(html()).toString() ) { it.name } @Suppress("UsePropertyAccessSyntax") setUI(FlatComboBoxUI( outerInsets = Insets(BW.get(), 0, BW.get(), 0), popupEmptyText = GitBundle.message("pull.branch.no.matching.remotes"))) item = getCurrentOrDefaultRemote(getSelectedRepository()) addItemListener { e -> if (e.stateChange == ItemEvent.SELECTED) { updateBranchesField() } } } private fun createBranchField() = ComboBoxWithAutoCompletion(MutableCollectionComboBoxModel(mutableListOf<String>()), project).apply { prototypeDisplayValue = GIT_REF_PROTOTYPE_VALUE setPlaceholder(GitBundle.message("pull.branch.field.placeholder")) object : RefreshAction() { override fun actionPerformed(e: AnActionEvent) { popup?.hide() performFetch() } override fun update(e: AnActionEvent) { e.presentation.isEnabled = true } }.registerCustomShortcutSet(getFetchActionShortcut(), this) @Suppress("UsePropertyAccessSyntax") setUI(FlatComboBoxUI( Insets(1, 0, 1, 1), Insets(BW.get(), 0, BW.get(), BW.get()), GitBundle.message("pull.branch.nothing.to.pull"), this@GitPullDialog::createBranchFieldPopupComponent)) } private fun createBranchFieldPopupComponent(content: JComponent) = JPanel().apply { layout = MigLayout(LC().insets("0")) add(content, CC().width("100%")) val hintLabel = HintUtil.createAdComponent( GitBundle.message("pull.dialog.fetch.shortcuts.hint", getFetchActionShortcutText()), JBUI.CurrentTheme.BigPopup.advertiserBorder(), SwingConstants.LEFT) hintLabel.preferredSize = JBDimension.create(hintLabel.preferredSize, true) .withHeight(17) add(hintLabel, CC().newline().width("100%")) } private fun getFetchActionShortcut(): ShortcutSet { val refreshActionShortcut = ActionManager.getInstance().getAction(IdeActions.ACTION_REFRESH).shortcutSet if (refreshActionShortcut.shortcuts.isNotEmpty()) { return refreshActionShortcut } else { return FETCH_ACTION_SHORTCUT } } private fun getFetchActionShortcutText() = KeymapUtil.getPreferredShortcutText(getFetchActionShortcut().shortcuts) companion object { private val FETCH_ACTION_SHORTCUT = if (SystemInfo.isMac) CustomShortcutSet(KeyStroke.getKeyStroke(KeyEvent.VK_R, KeyEvent.META_DOWN_MASK)) else CustomShortcutSet(KeyStroke.getKeyStroke(KeyEvent.VK_F5, KeyEvent.CTRL_DOWN_MASK)) } }
apache-2.0
b09bc82431ec9157bf8cdaae3b4064e1
33.046296
140
0.703135
4.852194
false
false
false
false
vovagrechka/fucking-everything
phizdets/phizdetsc/src/org/jetbrains/kotlin/js/parser/parserUtils.kt
3
2955
/* * Copyright 2010-2015 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.kotlin.js.parser import com.google.gwt.dev.js.* import com.google.gwt.dev.js.rhino.* import org.jetbrains.kotlin.js.backend.ast.JsFunction import org.jetbrains.kotlin.js.backend.ast.JsFunctionScope import org.jetbrains.kotlin.js.backend.ast.JsScope import org.jetbrains.kotlin.js.backend.ast.JsStatement import org.jetbrains.kotlin.js.common.SourceInfoImpl import java.io.* import java.util.* private val FAKE_SOURCE_INFO = SourceInfoImpl(null, 0, 0, 0, 0) fun parse(code: String, reporter: ErrorReporter, scope: JsScope): List<JsStatement> { val insideFunction = scope is JsFunctionScope val node = parse(code, 0, reporter, insideFunction, Parser::parse) return node.toJsAst(scope, JsAstMapper::mapStatements) } fun parseFunction(code: String, offset: Int, reporter: ErrorReporter, scope: JsScope): JsFunction = parse(code, offset, reporter, insideFunction = false) { addObserver(FunctionParsingObserver()) primaryExpr(it) }.toJsAst(scope, JsAstMapper::mapFunction) private class FunctionParsingObserver : Observer { var functionsStarted = 0 override fun update(o: Observable?, arg: Any?) { when (arg) { is ParserEvents.OnFunctionParsingStart -> { functionsStarted++ } is ParserEvents.OnFunctionParsingEnd -> { functionsStarted-- if (functionsStarted == 0) { arg.tokenStream.ungetToken(TokenStream.EOF) } } } } } inline private fun parse( code: String, offset: Int, reporter: ErrorReporter, insideFunction: Boolean, parseAction: Parser.(TokenStream)->Any ): Node { Context.enter().setErrorReporter(reporter) try { val ts = TokenStream(StringReader(code, offset), "<parser>", FAKE_SOURCE_INFO.line) val parser = Parser(IRFactory(ts), insideFunction) return parser.parseAction(ts) as Node } finally { Context.exit() } } inline private fun <T> Node.toJsAst(scope: JsScope, mapAction: JsAstMapper.(Node)->T): T = JsAstMapper(scope).mapAction(this) private fun StringReader(string: String, offset: Int): Reader { val reader = StringReader(string) reader.skip(offset.toLong()) return reader }
apache-2.0
40baeacd49d9098d39f681609bd501e5
31.844444
99
0.680541
4.031378
false
false
false
false
testIT-LivingDoc/livingdoc2
livingdoc-converters/src/main/kotlin/org/livingdoc/converters/time/LocalDateTimeConverter.kt
2
596
package org.livingdoc.converters.time import java.time.LocalDateTime import java.time.format.DateTimeFormatter /** * This converter parses a String to the local date and time format */ open class LocalDateTimeConverter : AbstractTemporalConverter<LocalDateTime>() { override fun defaultFormatter(): DateTimeFormatter = DateTimeFormatter.ISO_LOCAL_DATE_TIME override fun doParse(value: String, formatter: DateTimeFormatter): LocalDateTime = LocalDateTime.parse(value, formatter) override fun canConvertTo(targetType: Class<*>) = LocalDateTime::class.java == targetType }
apache-2.0
80650fee34036e82424f9fc14045f462
36.25
94
0.781879
5.008403
false
false
false
false
joaomneto/TitanCompanion
src/main/java/pt/joaomneto/titancompanion/adapter/SavegameListAdapter.kt
1
2452
package pt.joaomneto.titancompanion.adapter import android.content.Context import android.view.ContextMenu import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.ArrayAdapter import android.widget.ImageView import android.widget.TextView import java.text.SimpleDateFormat import pt.joaomneto.titancompanion.LoadAdventureActivity import pt.joaomneto.titancompanion.R import pt.joaomneto.titancompanion.consts.FightingFantasyGamebook class SavegameListAdapter(private val ctx: Context, private val values: List<Savegame>) : ArrayAdapter<Savegame>( ctx, -1, values ), View.OnCreateContextMenuListener { private val adv: LoadAdventureActivity = ctx as LoadAdventureActivity override fun getView(position: Int, convertView: View?, parent: ViewGroup): View { val inflater = ctx.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater val robotView = inflater.inflate(R.layout.component_load_dventure, parent, false) val nameValue = robotView.rootView.findViewById<TextView>(R.id.nameValue) val gamebookValue = robotView.rootView.findViewById<TextView>(R.id.gamebookValue) val dateValue = robotView.rootView.findViewById<TextView>(R.id.dateValue) val gamebookIcon = robotView.rootView.findViewById<ImageView>(R.id.gamebookIcon) val value = values[position].getFilename() val tokens = value.split("_".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray() nameValue.text = tokens[2] val gamebookNameId = adv.resources.getIdentifier( tokens[1].toLowerCase(), "string", adv.applicationContext.packageName ) val gamebookCoverId = adv.resources.getIdentifier( "ff" + FightingFantasyGamebook.gamebookFromInitials(tokens[1].toLowerCase()), "drawable", adv.applicationContext.packageName ) gamebookValue.setText(gamebookNameId) dateValue.text = df.format(values[position].getLastUpdated()) gamebookIcon.setImageResource(gamebookCoverId) return robotView } override fun onCreateContextMenu( contextMenu: ContextMenu, view: View, contextMenuInfo: ContextMenu.ContextMenuInfo ) { println() } companion object { private val df = SimpleDateFormat("yyyy-MM-dd HH:mm") } }
lgpl-3.0
7deee2d75bdb31d87c88343c85f451c9
33.535211
94
0.712887
4.770428
false
false
false
false
TachiWeb/TachiWeb-Server
Tachiyomi-App/src/main/java/eu/kanade/tachiyomi/network/PersistentCookieStore.kt
1
2455
package eu.kanade.tachiyomi.network import android.content.Context import okhttp3.Cookie import okhttp3.HttpUrl import java.net.URI import java.util.concurrent.ConcurrentHashMap class PersistentCookieStore(context: Context) { private val cookieMap = ConcurrentHashMap<String, List<Cookie>>() private val prefs = context.getSharedPreferences("cookie_store", Context.MODE_PRIVATE) init { for ((key, value) in prefs.all) { @Suppress("UNCHECKED_CAST") val cookies = value as? Set<String> if (cookies != null) { try { val url = HttpUrl.parse("http://$key") ?: continue val nonExpiredCookies = cookies.mapNotNull { Cookie.parse(url, it) } .filter { !it.hasExpired() } cookieMap.put(key, nonExpiredCookies) } catch (e: Exception) { // Ignore } } } } @Synchronized fun addAll(url: HttpUrl, cookies: List<Cookie>) { val key = url.uri().host // Append or replace the cookies for this domain. val cookiesForDomain = cookieMap[key].orEmpty().toMutableList() for (cookie in cookies) { // Find a cookie with the same name. Replace it if found, otherwise add a new one. val pos = cookiesForDomain.indexOfFirst { it.name() == cookie.name() } if (pos == -1) { cookiesForDomain.add(cookie) } else { cookiesForDomain[pos] = cookie } } cookieMap.put(key, cookiesForDomain) // Get cookies to be stored in disk val newValues = cookiesForDomain.asSequence() .filter { it.persistent() && !it.hasExpired() } .map(Cookie::toString) .toSet() prefs.edit().putStringSet(key, newValues).apply() } @Synchronized fun removeAll() { prefs.edit().clear().apply() cookieMap.clear() } fun remove(uri: URI) { prefs.edit().remove(uri.host).apply() cookieMap.remove(uri.host) } fun get(url: HttpUrl) = get(url.uri().host) fun get(uri: URI) = get(uri.host) private fun get(url: String): List<Cookie> { return cookieMap[url].orEmpty().filter { !it.hasExpired() } } private fun Cookie.hasExpired() = System.currentTimeMillis() >= expiresAt() }
apache-2.0
3d4552805d5ba9ad3ad037dcd409ae53
30.487179
94
0.567821
4.415468
false
false
false
false
holgerbrandl/kscript-support-api
src/main/kotlin/kscript/text/StreamUtil.kt
1
2895
package kscript.text /** A `Sequence<String>` iterator for standard input */ public val stdin by lazy { generateSequence() { readLine() } } fun linesFrom(file: java.io.File) = java.io.BufferedReader(java.io.FileReader(file)).lineSequence() /** * File argument processor that works similar to awk: If data is available on stdin, use it. If not expect a file argument and read from that one instead. * */ fun resolveArgFile(args: Array<String>, position: Int = 0): Sequence<String> { // if (stdin.iterator().hasNext()) return stdin if (System.`in`.available() > 0) return kscript.text.stdin kscript.stopIfNot(args.isNotEmpty()) { "Missing file or input input stream" } kscript.stopIfNot(args.size >= position) { "arg position ${position} exceeds number of arguments ${args.size} " } val fileArg = args[position] // stdinNames: List<String> = listOf("-", "stdin") // if (stdinNames.contains(fileArg)) return stdin val inputFile = java.io.File(fileArg) kscript.stopIfNot(inputFile.canRead()) { "Can not read from '${fileArg}'" } // test for compression and uncompress files automatically val isCompressedInput = inputFile.name.run { endsWith(".zip") || endsWith(".gz") } val lineReader = if (isCompressedInput) { java.io.InputStreamReader(java.util.zip.GZIPInputStream(java.io.FileInputStream(inputFile))) } else { java.io.FileReader(inputFile) } // todo we don't close the buffer with this approach // BufferedReader(FileReader(inputFile )).use { return it } return java.io.BufferedReader(lineReader).lineSequence() } /** Endpoint for a kscript pipe. */ fun Sequence<String>.print() = forEach { println(it) } /** Endpoint for a kscript pipe. */ fun Iterable<String>.print() = forEach { println(it) } fun Iterable<String>.trim() = map { it.trim() } fun Sequence<String>.trim() = map { it.trim() } //https://dzone.com/articles/readingwriting-compressed-and /** Save a list of items into a file. Output can be option ally zipped and a the stringifying operation can be changed from toString to custom operation if needed. */ fun <T> Iterable<T>.saveAs(f: java.io.File, transform: (T) -> String = { it.toString() }, separator: Char = '\n', overwrite: Boolean = true, compress: Boolean = f.name.let { it.endsWith(".zip") || it.endsWith(".gz") }) { // ensure that file is not yet there or overwrite flag is set require(!f.isFile || overwrite) { "$f is present already. Use overwrite=true to enforce file replacement." } val p = if (!compress) java.io.PrintWriter(f) else java.io.BufferedWriter(java.io.OutputStreamWriter(java.util.zip.GZIPOutputStream(java.io.FileOutputStream(f)))) toList().forEach { p.write(transform(it) + separator) } p.close() }
mit
abd44ec7caa706361441a64f89f89a4c
38.121622
166
0.664594
3.965753
false
false
false
false
shabtaisharon/ds3_java_browser
dsb-gui/src/test/java/com/spectralogic/dsbrowser/gui/util/FunctionalExtensionsTest.kt
1
2162
/* * *************************************************************************** * Copyright 2014-2017 Spectra Logic Corporation. 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. A copy of the License is located at * * http://www.apache.org/licenses/LICENSE-2.0 * * or in the "license" file accompanying this file. * This file 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.spectralogic.dsbrowser.gui.util import com.spectralogic.dsbrowser.util.andThen import com.spectralogic.dsbrowser.util.exists import org.assertj.core.api.Assertions.* import org.junit.Test class FunctionalExtensionsTest { @Test fun existDoesNotFalseExecute() { val h: String? = null var b = false h.exists { b = true it } assertThat(b).isFalse() } @Test fun existDoesOnExist() { val h: String? = "Hello World" var b = false h.exists { b = true null } assertThat(b).isTrue() } @Test fun existsAssignment() { val h: String? = "Hello World" val b = h.exists { it } assertThat(b).isEqualTo("Hello World") } @Test fun existsInlineAssignment() { val b = "H".exists { it } assertThat(b).isEqualTo("H") } @Test fun existsNull() { val b = null.exists { "Hello World" } assertThat(b).isNull() } @Test fun notExistingAssignment() { val h: String? = null val b = h.exists { it } assertThat(b).isNull() } @Test fun andThenTest() { val a = { b: Int -> b + 2 } var f = false val c = a.andThen { f = true }.invoke(1) assertThat(f).isTrue() assertThat(c).isEqualTo(3) } }
apache-2.0
a6cbda0bece1fcc7a323f9a552a40630
25.378049
89
0.546716
4.222656
false
true
false
false
MichelPro/CoolWeather
app/src/main/java/com/michel/coolweather/activity/WeatherActivity.kt
1
6618
package com.michel.coolweather.activity import android.graphics.Color import android.os.Build import android.os.Bundle import android.preference.PreferenceManager import android.util.Log import android.view.LayoutInflater import android.view.View import android.widget.ImageView import android.widget.LinearLayout import android.widget.ScrollView import android.widget.TextView import com.bumptech.glide.Glide import com.michel.coolweather.R import com.michel.coolweather.base.BaseActivity import com.michel.coolweather.entity.Weather import com.michel.coolweather.other.Constant import com.michel.coolweather.other.setVisible import com.michel.coolweather.utils.SpUtils import com.michel.coolweather.utils.Utility import com.zhy.http.okhttp.OkHttpUtils import com.zhy.http.okhttp.callback.StringCallback import okhttp3.Call import org.jetbrains.anko.AnkoLogger import org.jetbrains.anko.debug import org.jetbrains.anko.find import org.jetbrains.anko.toast import java.lang.Exception class WeatherActivity : BaseActivity(), AnkoLogger { lateinit var bingPicImg: ImageView lateinit var weatherLayout: ScrollView lateinit var titleCity: TextView lateinit var titleUpdateTime: TextView lateinit var degreeText: TextView lateinit var weatherInfoText: TextView lateinit var forecastLayout: LinearLayout lateinit var aqiText: TextView lateinit var pm25Text: TextView lateinit var comfortText: TextView lateinit var carWashText: TextView lateinit var sportText: TextView override fun onCreate(savedInstanceState: Bundle?) { // 透明状态栏 if (Build.VERSION.SDK_INT >= 21) { val decorView = window.decorView decorView.systemUiVisibility = View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN or View.SYSTEM_UI_FLAG_LAYOUT_STABLE window.statusBarColor = Color.TRANSPARENT } super.onCreate(savedInstanceState) } override fun initVariables() { } override fun getLayoutResId(): Int = R.layout.activity_weather override fun initViews(savedInstanceState: Bundle?) { bingPicImg = find(R.id.bing_pic_img) weatherLayout = find(R.id.weather_layout) titleCity = find(R.id.title_city) titleUpdateTime = find(R.id.title_update_time) degreeText = find(R.id.degree_text) weatherInfoText = find(R.id.weather_info_text) forecastLayout = find(R.id.forecast_layout) aqiText = find(R.id.api_text) pm25Text = find(R.id.pm25_text) comfortText = find(R.id.comfort_text) carWashText = find(R.id.car_wash_text) sportText = find(R.id.sport_text) } override fun initData() { val bingPic = SpUtils.instance.get("bing_pic", "") as String if (bingPic.isNotEmpty()) { Glide.with(this).load(bingPic).into(bingPicImg) } else { loadBingPic() } val weatherString = SpUtils.instance.get("weather", "") as String if (weatherString.isNotEmpty()) { // 有缓存时直接解析天气数据 val weather = Utility.handleWeatherResponse(weatherString) showWeatherInfo(weather) } else { // 无缓存时去服务器查询天气 val weatherId = intent.getStringExtra("weather_id") Log.d("CoolWeather", "weather_id是$weatherId") weatherLayout.setVisible(false) requestWeather(weatherId) } } /** * 加载必应每日一图 */ private fun loadBingPic() { OkHttpUtils.get().url(Constant.URL_BING_PIC).build().execute(object : StringCallback(){ override fun onResponse(response: String, id: Int) { SpUtils.instance.put("bing_pic", response) Glide.with(this@WeatherActivity).load(response).into(bingPicImg) } override fun onError(call: Call?, e: Exception, id: Int) { e.printStackTrace() } }) } /** * 根据天气id请求天气信息 */ private fun requestWeather(weatherId: String?) { OkHttpUtils.get().url(Constant.URL_WEATHER).addParams("cityid", weatherId) .addParams("key", Constant.KEY_WEATHER) .build().execute(object : StringCallback(){ override fun onResponse(response: String, id: Int) { Log.d("CoolWeather", "返回结果是$response") val weather = Utility.handleWeatherResponse(response) if (weather != null && "ok" == weather.status) { SpUtils.instance.put("weather", response) showWeatherInfo(weather) } else { toast("获取天气信息失败") } } override fun onError(call: Call?, e: Exception, id: Int) { e.printStackTrace() toast("获取天气信息失败") } }) } /** * 处理并展示Weather实体类中的数据 */ private fun showWeatherInfo(weather: Weather) { val cityName = weather.basic.cityName val updateTime = weather.basic.update.updateTime.split(" ")[1] val degree = weather.now.temperature + "℃" val weatherInfo = weather.now.more.info titleCity.text = cityName titleUpdateTime.text = updateTime degreeText.text = degree weatherInfoText.text = weatherInfo forecastLayout.removeAllViews() weather.forecastList.forEach { val view = LayoutInflater.from(this).inflate(R.layout.forecast_item, forecastLayout, false) val dateText = view.find<TextView>(R.id.date_text) val infoText = view.find<TextView>(R.id.info_text) val maxText = view.find<TextView>(R.id.max_text) val minText = view.find<TextView>(R.id.min_text) dateText.text = it.date infoText.text = it.more.info maxText.text = it.temperature.max minText.text = it.temperature.min forecastLayout.addView(view) } weather.aqi?.let { aqiText.text = it.city.aqi pm25Text.text = it.city.pm25 } val comfort = "舒适度:${weather.suggestion.comfort.info}" val carWash = "洗车指数:${weather.suggestion.carWash.info}" val sport = "运动建议:${weather.suggestion.sport.info}" comfortText.text = comfort carWashText.text = carWash sportText.text = sport weatherLayout.setVisible(true) } }
apache-2.0
8ec9cd29e3e7006a0edac0ec08d5002c
32.821053
117
0.638967
4.064516
false
false
false
false
NicholasFeldman/NudeKt
src/main/kotlin/tech/feldman/nudekt/colorUtils.kt
1
1039
package tech.feldman.nudekt internal fun maxRgb(r: Float, g: Float, b: Float): Float { return Math.max(Math.max(r, g), b) } internal fun minRgb(r: Float, g: Float, b: Float): Float { return Math.min(Math.min(r, g), b) } internal data class NormalizedRGB(val r: Float, val g: Float, val b: Float) internal fun toNormalizedRgb(r: Float, g: Float, b: Float): NormalizedRGB { val sum = r + g + b val nr = r / sum val ng = g / sum val nb = b / sum return NormalizedRGB(nr, ng, nb) } internal data class Hsv(val h: Float, val s: Float, val v: Float) internal fun toHsv(r: Float, g: Float, b: Float): Hsv { val sum = r + g + b val max = maxRgb(r, g, b) val min = minRgb(r, g, b) val diff = max - min var h = when (max) { r -> (g - b) / diff g -> 2 + (g - r) / diff else -> 4 + (r - g) / diff }.toFloat() h *= 60 if (h < 0) { h += 360 } val s = 1 - 3.toFloat() * (min / sum) val v = (1 / 3.toFloat()) * max return Hsv(h, s, v) }
mit
1fa883a210ddb7333406d2ee26733321
22.613636
75
0.541867
2.815718
false
false
false
false
kvnxiao/meirei
meirei-jda/src/main/kotlin/com/github/kvnxiao/discord/meirei/jda/command/CommandBuilder.kt
1
10719
/* * Copyright (C) 2017-2018 Ze Hao Xiao * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.kvnxiao.discord.meirei.jda.command import com.github.kvnxiao.discord.meirei.command.CommandContext import com.github.kvnxiao.discord.meirei.command.CommandDefaults import com.github.kvnxiao.discord.meirei.command.CommandPackage import com.github.kvnxiao.discord.meirei.command.CommandProperties import com.github.kvnxiao.discord.meirei.jda.permission.LevelDefaults import com.github.kvnxiao.discord.meirei.jda.permission.PermissionPropertiesJDA import com.github.kvnxiao.discord.meirei.permission.PermissionData import com.github.kvnxiao.discord.meirei.permission.PermissionDefaults import net.dv8tion.jda.core.Permission import net.dv8tion.jda.core.events.message.MessageReceivedEvent import java.util.Arrays import java.util.HashSet /** * Builder class to help create a (JDA) command package for adding to the command registry */ class CommandBuilder /** * Creates a command builder instance with the specified unique command id. * @param id the unique identifier (name) for the command */ (private val id: String) { // Command properties private val aliases = HashSet<String>() private var prefix = CommandDefaults.PREFIX private var parentId = CommandDefaults.PARENT_ID // Settings private var execWithSubCommands = CommandDefaults.EXEC_ALONGSIDE_SUBCOMMANDS private var isDisabled = CommandDefaults.IS_DISABLED // Metadata private var description = CommandDefaults.NO_DESCRIPTION private var usage = CommandDefaults.NO_USAGE // Permission properties private var allowDm = PermissionDefaults.ALLOW_DIRECT_MSGING private var forceDm = PermissionDefaults.FORCE_DIRECT_MSGING private var forceDmReply = PermissionDefaults.FORCE_DIRECT_REPLY private var removeCallMsg = PermissionDefaults.REMOVE_CALL_MSG private var rateLimitPeriodMs = PermissionDefaults.RATE_LIMIT_PERIOD_MS private var tokensPerPeriod = PermissionDefaults.TOKENS_PER_PERIOD private var rateLimitOnGuild = PermissionDefaults.RATE_LIMIT_ON_GUILD private var reqBotOwner = PermissionDefaults.REQUIRE_BOT_OWNER private var reqGuildOwner = PermissionDefaults.REQUIRE_GUILD_OWNER private var reqMention = PermissionDefaults.REQUIRE_MENTION // Command registry settings private var isRegistryAware = CommandDefaults.IS_REGISTRY_AWARE // Discord permissions private var permissionLevel = LevelDefaults.DEFAULT_PERMS_RW /** * Sets the alias(es) for the command. * @param aliases the command alias(es) * @return the current command builder */ fun aliases(vararg aliases: String): CommandBuilder { this.aliases.addAll(Arrays.asList(*aliases)) return this } /** * Sets the prefix for the command. * @param prefix the command prefix * @return the current command builder */ fun prefix(prefix: String): CommandBuilder { this.prefix = prefix return this } /** * Sets the parentId for this command. * @param parentId the parent command's id * @return the current command builder */ fun parentId(parentId: String): CommandBuilder { this.parentId = parentId return this } /** * Sets whether the command should execute along with its sub-commands. * @param execWithSubCommands a boolean * @return the current command builder */ fun execWithSubCommands(execWithSubCommands: Boolean): CommandBuilder { this.execWithSubCommands = execWithSubCommands return this } /** * Sets whether the command is disabled or not. * @param isDisabled a boolean * @return the current command builder */ fun isDisabled(isDisabled: Boolean): CommandBuilder { this.isDisabled = isDisabled return this } /** * Sets the description for the command. * @param description the description string * @return the current command builder */ fun description(description: String): CommandBuilder { this.description = description return this } /** * Sets the usage details for the command. * @param usage the usage string * @return the current command builder */ fun usage(usage: String): CommandBuilder { this.usage = usage return this } /** * Sets whether the command is allowed to be executed through direct messages to the bot (otherwise it is guild only). * @param allowDm a boolean * @return the current command builder */ fun allowDirectMessages(allowDm: Boolean): CommandBuilder { this.allowDm = allowDm return this } /** * Sets whether the command can only be executed through direct messages to the bot from the user. * @param forceDm a boolean * @return the current command builder */ fun forceDirectMessages(forceDm: Boolean): CommandBuilder { this.forceDm = forceDm return this } /** * Sets whether the bot is forced to reply with a direct message to the user during command execution. * @param forceDmReply a boolean * @return the current command builder */ fun forceDirectMessageReply(forceDmReply: Boolean): CommandBuilder { this.forceDmReply = forceDmReply return this } /** * Sets whether or not the user's message that executed the command should be deleted upon execution. * @param removeCallMsg a boolean * @return the current command builder */ fun removeCallMessage(removeCallMsg: Boolean): CommandBuilder { this.removeCallMsg = removeCallMsg return this } /** * Sets the rate limit period in milliseconds for the command call, before the rate limits are reset on a per-period basis. * @param rateLimitPeriodMs the period in milliseconds * @return the current command builder */ fun rateLimitPeriodMs(rateLimitPeriodMs: Long): CommandBuilder { this.rateLimitPeriodMs = rateLimitPeriodMs return this } /** * Sets the number of tokens (number of calls to the command) allowed per rate limit period. * @param tokensPerPeriod the number of tokens per period * @return the current command builder */ fun tokensPerPeriod(tokensPerPeriod: Long): CommandBuilder { this.tokensPerPeriod = tokensPerPeriod return this } /** * Sets whether the rate limiting for the command should be done on a per-guild basis, or a per-user basis. * @param rateLimitOnGuild a boolean * @return the current command builder */ fun rateLimitOnGuild(rateLimitOnGuild: Boolean): CommandBuilder { this.rateLimitOnGuild = rateLimitOnGuild return this } /** * Sets whether the command requires bot owner privileges in order to be successfully executed. * @param reqBotOwner a boolean * @return the current command builder */ fun requireBotOwner(reqBotOwner: Boolean): CommandBuilder { this.reqBotOwner = reqBotOwner return this } /** * Sets whether the command requires guild owner privileges in order to be successfully executed. * @param reqGuildOwner a boolean * @return the current command builder */ fun requireGuildOwner(reqGuildOwner: Boolean): CommandBuilder { this.reqGuildOwner = reqGuildOwner return this } /** * Sets whether the command requires an '@' mention before the command prefix and alias in order to be executed. * @param reqMention a boolean * @return the current command builder */ fun requireMention(reqMention: Boolean): CommandBuilder { this.reqMention = reqMention return this } /** * Sets the command's discord permissions that are required for a user to execute the command * @param permissions the required discord permissions * @return the current command builder */ fun permissionLevel(vararg permissions: Permission): CommandBuilder { this.permissionLevel.clear() this.permissionLevel.addAll(permissions) return this } /** * Sets whether the command is capable of reading the command registry to retrieve information regarding other commands. * @param isRegistryAware whether the command is registry aware * @return the current command builder */ fun isRegistryAware(isRegistryAware: Boolean): CommandBuilder { this.isRegistryAware = isRegistryAware return this } /** * Builds the JDA command package using the values set in the builder. * @param executable the command method * @return the (JDA) command package containing the executable, command properties, and permission properties */ fun build(executable: CommandExecutable): CommandPackage { if (this.aliases.isEmpty()) { this.aliases.add(this.id) } return CommandPackage( object : CommandJDA(this.id, this.isRegistryAware) { override fun execute(context: CommandContext, event: MessageReceivedEvent) { executable.execute(context, event) } }, CommandProperties(this.id, this.aliases, this.prefix, this.description, this.usage, this.execWithSubCommands, this.isDisabled, this.parentId), PermissionPropertiesJDA(PermissionData(this.allowDm, this.forceDm, this.forceDmReply, this.removeCallMsg, this.rateLimitPeriodMs, this.tokensPerPeriod, this.rateLimitOnGuild, this.reqGuildOwner, this.reqBotOwner, this.reqMention), this.permissionLevel) ) } } /** * Kotlin-based lambda helper for building CommandPackages */ fun CommandBuilder.build(execute: (context: CommandContext, event: MessageReceivedEvent) -> Unit): CommandPackage { return this.build(object : CommandExecutable { override fun execute(context: CommandContext, event: MessageReceivedEvent) { execute.invoke(context, event) } }) }
apache-2.0
a7cd9815779c65cca2566ad5f3390b6b
35.835052
141
0.697826
4.77036
false
false
false
false
hazuki0x0/YuzuBrowser
module/adblock/src/main/java/jp/hazuki/yuzubrowser/adblock/filter/unified/io/ElementReader.kt
1
3369
/* * Copyright (C) 2017-2019 Hazuki * * 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 jp.hazuki.yuzubrowser.adblock.filter.unified.io import jp.hazuki.yuzubrowser.adblock.filter.toInt import jp.hazuki.yuzubrowser.adblock.filter.unified.ELEMENT_FILTER_CACHE_HEADER import jp.hazuki.yuzubrowser.adblock.filter.unified.element.ElementFilter import jp.hazuki.yuzubrowser.adblock.filter.unified.element.PlaneElementFilter import jp.hazuki.yuzubrowser.adblock.filter.unified.element.TldRemovedElementFilter import jp.hazuki.yuzubrowser.adblock.filter.unified.readVariableInt import java.io.InputStream class ElementReader(private val input: InputStream) { fun checkHeader(): Boolean { val header = ELEMENT_FILTER_CACHE_HEADER.toByteArray() val data = ByteArray(header.size) input.read(data) return header contentEquals data } fun readAll() = sequence { val intBuf = ByteArray(4) val shortBuf = ByteArray(2) input.read(intBuf) val size = intBuf.toInt() val list = ArrayList<ElementFilter>(size) var patternBuffer = ByteArray(32) loop@ for (loop in 0 until size) { val filterType = input.read() if (filterType < 0) break val isHide = when (input.read()) { 0 -> false 1 -> true else -> break@loop } val isNot = when (input.read()) { 0 -> false 1 -> true else -> break@loop } val patternSize = input.readVariableInt(shortBuf, intBuf) if (patternSize == -1) break if (patternBuffer.size < patternSize) { patternBuffer = ByteArray(patternSize) } if (input.read(patternBuffer, 0, patternSize) != patternSize) break val pattern = String(patternBuffer, 0, patternSize) val selectorSize = input.readVariableInt(shortBuf, intBuf) if (selectorSize == -1) break if (patternBuffer.size < selectorSize) { patternBuffer = ByteArray(selectorSize) } if (input.read(patternBuffer, 0, selectorSize) != selectorSize) break val selector = String(patternBuffer, 0, selectorSize) val filter = when (filterType) { ElementFilter.TYPE_PLANE -> PlaneElementFilter( pattern, isHide, isNot, selector, ) ElementFilter.TYPE_TLD_REMOVED -> TldRemovedElementFilter( pattern, isHide, isNot, selector, ) else -> break@loop } yield(filter) } } }
apache-2.0
046777d45d438bb6b889ceedd88a828d
34.09375
83
0.598991
4.646897
false
false
false
false
kpspemu/kpspemu
src/commonMain/kotlin/com/soywiz/kpspemu/hle/manager/FileManager.kt
1
4805
package com.soywiz.kpspemu.hle.manager import com.soywiz.korio.async.* import com.soywiz.korio.file.* import com.soywiz.korio.file.VfsUtil import com.soywiz.korio.lang.* import com.soywiz.korio.stream.* import com.soywiz.kpspemu.* import com.soywiz.kpspemu.util.* import kotlinx.coroutines.* class FileManager(val emulator: Emulator) { companion object { val INIT_CURRENT_DIRECTORY = "umd0:" val INIT_EXECUTABLE_FILE = "umd0:/PSP_GAME/USRDIR/EBOOT.BIN" } val deviceManager get() = emulator.deviceManager var currentDirectory = INIT_CURRENT_DIRECTORY var executableFile = INIT_EXECUTABLE_FILE val fileDescriptors = ResourceList<FileDescriptor>("FileDescriptor") { FileDescriptor(it) } val directoryDescriptors = ResourceList<DirectoryDescriptor>("DirectoryDescriptor") { DirectoryDescriptor(it) } fun reset() { currentDirectory = INIT_CURRENT_DIRECTORY executableFile = INIT_EXECUTABLE_FILE fileDescriptors.reset() directoryDescriptors.reset() } fun resolvePath(path: String): String { if (path.contains(':')) { return path } else { if (path.startsWith('/')) { return currentDirectory.split(':').first() + ":" + path } else { return VfsUtil.combine(currentDirectory, path) } } } fun resolve(path: String): VfsFile { val resolvedPath = resolvePath(path) //println("resolvedPath --> $resolvedPath") return deviceManager.root[resolvedPath] } } class FileDescriptor(override val id: Int) : ResourceItem { lateinit var fileName: String lateinit var file: VfsFile lateinit var stream: AsyncStream var doLater: (suspend () -> Unit)? = null var asyncPromise: Deferred<Unit>? = null var asyncResult: Long = 0L var asyncDone: Boolean = false } class DirectoryDescriptor(override val id: Int) : ResourceItem { lateinit var directory: VfsFile var pos: Int = 0 var files: List<VfsFile> = listOf() val remaining: Int get() = files.size - pos } data class SceIoStat( var mode: Int = 0, // SceMode var attributes: Int = 0, // IOFileModes.File var size: Long = 0L, var timeCreation: ScePspDateTime = ScePspDateTime(0L), var timeLastAccess: ScePspDateTime = ScePspDateTime(0L), var timeLastModification: ScePspDateTime = ScePspDateTime(0L), var device: IntArray = IntArray(6) ) { companion object : Struct<SceIoStat>( { SceIoStat() }, SceIoStat::mode AS INT32, SceIoStat::attributes AS INT32, SceIoStat::size AS INT64, SceIoStat::timeCreation AS ScePspDateTime, SceIoStat::timeLastAccess AS ScePspDateTime, SceIoStat::timeLastModification AS ScePspDateTime, SceIoStat::device AS INTLIKEARRAY(INT32, 6) ) } //class SceIoStat( // val mode: Int, // val attributes: Int, // val size: Long, // val timeCreation: ScePspDateTime, // val timeLastAccess: ScePspDateTime, // val timeLastModifications: ScePspDateTime, // val device: IntArray = IntArray(6) //) { // fun write(s: SyncStream) = s.run { // write32_le(mode) // write32_le(attributes) // write64_le(size) // timeCreation.write(s) // timeLastAccess.write(s) // timeLastModifications.write(s) // for (n in 0 until 6) write32_le(device[n]) // } //} data class HleIoDirent( var stat: SceIoStat = SceIoStat(), var name: String = "", var privateData: Int = 0, var dummy: Int = 0 ) { companion object : Struct<HleIoDirent>( { HleIoDirent() }, HleIoDirent::stat AS SceIoStat, HleIoDirent::name AS STRINGZ(UTF8, 256), HleIoDirent::privateData AS INT32, HleIoDirent::dummy AS INT32 ) } object IOFileModes { val DIR = 0x1000 val FILE = 0x2000 val FormatMask = 0x0038 val SymbolicLink = 0x0008 val Directory = 0x0010 val File = 0x0020 val CanRead = 0x0004 val CanWrite = 0x0002 val CanExecute = 0x0001 } object SeekType { val Set = 0 val Cur = 1 val End = 2 val Tell = 65536 } object FileOpenFlags { val Read = 0x0001 val Write = 0x0002 val ReadWrite = Read or Write val NoBlock = 0x0004 val _InternalDirOpen = 0x0008 // Internal use for dopen val Append = 0x0100 val Create = 0x0200 val Truncate = 0x0400 val Excl = 0x0800 val Unknown1 = 0x4000 // something async? val NoWait = 0x8000 val Unknown2 = 0xf0000 // seen on Wipeout Pure and Infected val Unknown3 = 0x2000000 // seen on Puzzle Guzzle, Hammerin' Hero } //object IOFileModes { // val FormatMask = 0x0038 // val SymbolicLink = 0x0008 // val Directory = 0x0010 // val File = 0x0020 // val CanRead = 0x0004 // val CanWrite = 0x0002 // val CanExecute = 0x0001 //}
mit
74ffd3139929396be387b2b83f11e302
27.270588
115
0.66077
3.494545
false
false
false
false
osfans/trime
app/src/main/java/com/osfans/trime/data/db/CollectionHelper.kt
1
1106
package com.osfans.trime.data.db import android.content.Context import androidx.room.Room import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.SupervisorJob object CollectionHelper : CoroutineScope by CoroutineScope(SupervisorJob() + Dispatchers.Default) { private lateinit var cltDb: Database private lateinit var cltDao: DatabaseDao fun init(context: Context) { cltDb = Room .databaseBuilder(context, Database::class.java, "collection.db") .addMigrations(Database.MIGRATION_3_4) .build() cltDao = cltDb.databaseDao() } suspend fun insert(bean: DatabaseBean) = cltDao.insert(bean) suspend fun getAll() = cltDao.getAll() suspend fun pin(id: Int) = cltDao.updatePinned(id, true) suspend fun unpin(id: Int) = cltDao.updatePinned(id, false) suspend fun delete(id: Int) = cltDao.delete(id) suspend fun deleteAll(skipPinned: Boolean = true) { if (skipPinned) cltDao.deleteAllUnpinned() else cltDao.deleteAll() } }
gpl-3.0
aab8f3085667cbfe743a15363cc1403b
28.891892
99
0.690778
3.99278
false
false
false
false
RocketChat/Rocket.Chat.Android
app/src/main/java/chat/rocket/android/profile/ui/ProfileFragment.kt
2
14005
package chat.rocket.android.profile.ui import DrawableHelper import android.app.Activity import android.content.Intent import android.content.pm.PackageManager import android.graphics.Bitmap import android.os.Build import android.os.Bundle import android.view.LayoutInflater import android.view.Menu import android.view.MenuItem import android.view.View import android.view.ViewGroup import android.widget.RadioGroup import androidx.appcompat.app.AlertDialog import androidx.appcompat.app.AppCompatActivity import androidx.appcompat.view.ActionMode import androidx.core.net.toUri import androidx.core.view.isVisible import androidx.fragment.app.Fragment import chat.rocket.android.R import chat.rocket.android.analytics.AnalyticsManager import chat.rocket.android.analytics.event.ScreenViewEvent import chat.rocket.android.helper.AndroidPermissionsHelper import chat.rocket.android.helper.AndroidPermissionsHelper.getCameraPermission import chat.rocket.android.helper.AndroidPermissionsHelper.hasCameraPermission import chat.rocket.android.main.ui.MainActivity import chat.rocket.android.profile.presentation.ProfilePresenter import chat.rocket.android.profile.presentation.ProfileView import chat.rocket.android.util.extension.asObservable import chat.rocket.android.util.extension.dispatchImageSelection import chat.rocket.android.util.extension.dispatchTakePicture import chat.rocket.android.util.extensions.inflate import chat.rocket.android.util.extensions.showToast import chat.rocket.android.util.extensions.textContent import chat.rocket.android.util.extensions.ui import chat.rocket.common.model.UserStatus import chat.rocket.common.model.userStatusOf import com.facebook.drawee.backends.pipeline.Fresco import com.google.android.material.snackbar.Snackbar import dagger.android.support.AndroidSupportInjection import io.reactivex.disposables.CompositeDisposable import io.reactivex.rxkotlin.Observables import kotlinx.android.synthetic.main.app_bar.* import kotlinx.android.synthetic.main.avatar_profile.* import kotlinx.android.synthetic.main.fragment_profile.* import kotlinx.android.synthetic.main.update_avatar_options.* import javax.inject.Inject internal const val TAG_PROFILE_FRAGMENT = "ProfileFragment" private const val REQUEST_CODE_FOR_PERFORM_SAF = 1 private const val REQUEST_CODE_FOR_PERFORM_CAMERA = 2 fun newInstance() = ProfileFragment() class ProfileFragment : Fragment(), ProfileView, ActionMode.Callback { @Inject lateinit var presenter: ProfilePresenter @Inject lateinit var analyticsManager: AnalyticsManager private var currentStatus = "" private var currentName = "" private var currentUsername = "" private var currentEmail = "" private var actionMode: ActionMode? = null private val editTextsDisposable = CompositeDisposable() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) AndroidSupportInjection.inject(this) setHasOptionsMenu(true) } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? = container?.inflate(R.layout.fragment_profile) override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) setupToolbar() if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.M) { tintEditTextDrawableStart() } presenter.loadUserProfile() setupListeners() subscribeEditTexts() analyticsManager.logScreenView(ScreenViewEvent.Profile) } override fun onDestroyView() { super.onDestroyView() unsubscribeEditTexts() } override fun onActivityResult(requestCode: Int, resultCode: Int, resultData: Intent?) { resultData?.run { if (resultCode == Activity.RESULT_OK) { if (requestCode == REQUEST_CODE_FOR_PERFORM_SAF) { data?.let { presenter.updateAvatar(it) } } else if (requestCode == REQUEST_CODE_FOR_PERFORM_CAMERA) { extras?.get("data")?.let { presenter.preparePhotoAndUpdateAvatar(it as Bitmap) } } } } } override fun onPrepareOptionsMenu(menu: Menu) { if (actionMode != null) { menu.clear() } super.onPrepareOptionsMenu(menu) } override fun showProfile( status: String, avatarUrl: String, name: String, username: String, email: String? ) { ui { text_status.text = getString(R.string.status, status.capitalize()) image_avatar.setImageURI(avatarUrl) text_name.textContent = name text_username.textContent = username text_email.textContent = email ?: "" currentStatus = status currentName = name currentUsername = username currentEmail = email ?: "" profile_container.isVisible = true } } override fun reloadUserAvatar(avatarUrl: String) { Fresco.getImagePipeline().evictFromCache(avatarUrl.toUri()) image_avatar?.setImageURI(avatarUrl) } override fun onProfileUpdatedSuccessfully( updatedEmail: String, updatedName: String, updatedUserName: String ) { currentEmail = updatedEmail currentName = updatedName currentUsername = updatedUserName showMessage(getString(R.string.msg_profile_updated_successfully)) } override fun showLoading() { enableUserInput(false) ui { view_loading.isVisible = true } } override fun hideLoading() { ui { if (view_loading != null) { view_loading.isVisible = false } } enableUserInput(true) } override fun showMessage(resId: Int) { ui { showToast(resId) } } override fun showMessage(message: String) { ui { showToast(message) } } override fun showGenericErrorMessage() = showMessage(getString(R.string.msg_generic_error)) override fun onCreateActionMode(mode: ActionMode, menu: Menu): Boolean { mode.menuInflater.inflate(R.menu.action_mode_profile, menu) mode.title = getString(R.string.title_update_profile) return true } override fun onPrepareActionMode(mode: ActionMode, menu: Menu): Boolean = false override fun onActionItemClicked(mode: ActionMode, menuItem: MenuItem): Boolean { return when (menuItem.itemId) { R.id.action_update_profile -> { updateProfile() mode.finish() true } else -> false } } override fun onDestroyActionMode(mode: ActionMode) { actionMode = null if (text_email.textContent != currentEmail || text_username.textContent != currentUsername || text_name.textContent != currentName ) { showChangesNotSavedDialog() } } private fun setupToolbar() { with((activity as AppCompatActivity)) { with(toolbar) { setSupportActionBar(this) title = getString(R.string.title_profile) setNavigationIcon(R.drawable.ic_arrow_back_white_24dp) setNavigationOnClickListener { activity?.onBackPressed() } } } } private fun setupListeners() { text_status.setOnClickListener { showStatusDialog(currentStatus) } image_avatar.setOnClickListener { showUpdateAvatarOptions() } view_dim.setOnClickListener { hideUpdateAvatarOptions() } button_open_gallery.setOnClickListener { dispatchImageSelection(REQUEST_CODE_FOR_PERFORM_SAF) hideUpdateAvatarOptions() } button_take_a_photo.setOnClickListener { context?.let { if (hasCameraPermission(it)) { dispatchTakePicture(REQUEST_CODE_FOR_PERFORM_CAMERA) } else { getCameraPermission(this) } } hideUpdateAvatarOptions() } button_reset_avatar.setOnClickListener { hideUpdateAvatarOptions() presenter.resetAvatar() } button_view_profile_photo.setOnClickListener { hideUpdateAvatarOptions() presenter.toProfileImage() } } private fun showUpdateAvatarOptions() { view_dim.isVisible = true layout_update_avatar_options.isVisible = true } private fun hideUpdateAvatarOptions() { layout_update_avatar_options.isVisible = false view_dim.isVisible = false } private fun tintEditTextDrawableStart() { (activity as MainActivity).apply { val personDrawable = DrawableHelper.getDrawableFromId(R.drawable.ic_person_black_20dp, this) val atDrawable = DrawableHelper.getDrawableFromId(R.drawable.ic_at_black_20dp, this) val emailDrawable = DrawableHelper.getDrawableFromId(R.drawable.ic_email_black_20dp, this) val drawables = arrayOf(personDrawable, atDrawable, emailDrawable) DrawableHelper.wrapDrawables(drawables) DrawableHelper.tintDrawables(drawables, this, R.color.colorDrawableTintGrey) DrawableHelper.compoundDrawables( arrayOf(text_name, text_username, text_email), drawables ) } } private fun subscribeEditTexts() { editTextsDisposable.add(Observables.combineLatest( text_name.asObservable(), text_username.asObservable(), text_email.asObservable() ) { text_name, text_username, text_email -> return@combineLatest (text_name.toString() != currentName || text_username.toString() != currentUsername || text_email.toString() != currentEmail) }.subscribe { isValid -> activity?.invalidateOptionsMenu() if (isValid) { startActionMode() } else { finishActionMode() } }) } private fun unsubscribeEditTexts() = editTextsDisposable.clear() private fun startActionMode() { if (actionMode == null) { actionMode = (activity as MainActivity).startSupportActionMode(this) } } private fun finishActionMode() = actionMode?.finish() private fun enableUserInput(value: Boolean) { ui { text_username.isEnabled = value text_username.isEnabled = value text_email.isEnabled = value } } private fun showStatusDialog(currentStatus: String) { val dialogLayout = layoutInflater.inflate(R.layout.dialog_status, null) val radioGroup = dialogLayout.findViewById<RadioGroup>(R.id.radio_group_status) radioGroup.check( when (userStatusOf(currentStatus)) { is UserStatus.Online -> R.id.radio_button_online is UserStatus.Away -> R.id.radio_button_away is UserStatus.Busy -> R.id.radio_button_busy else -> R.id.radio_button_invisible } ) var newStatus: UserStatus = userStatusOf(currentStatus) radioGroup.setOnCheckedChangeListener { _, checkId -> when (checkId) { R.id.radio_button_online -> newStatus = UserStatus.Online() R.id.radio_button_away -> newStatus = UserStatus.Away() R.id.radio_button_busy -> newStatus = UserStatus.Busy() else -> newStatus = UserStatus.Offline() } } context?.let { AlertDialog.Builder(it) .setView(dialogLayout) .setPositiveButton(R.string.msg_change_status) { dialog, _ -> presenter.updateStatus(newStatus) text_status.text = getString(R.string.status, newStatus.toString().capitalize()) this.currentStatus = newStatus.toString() dialog.dismiss() }.show() } } override fun onRequestPermissionsResult( requestCode: Int, permissions: Array<out String>, grantResults: IntArray ) { super.onRequestPermissionsResult(requestCode, permissions, grantResults) when (requestCode) { AndroidPermissionsHelper.CAMERA_CODE -> { if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) { // permission was granted dispatchTakePicture(REQUEST_CODE_FOR_PERFORM_CAMERA) } else { // permission denied Snackbar.make( relative_layout, R.string.msg_camera_permission_denied, Snackbar.LENGTH_SHORT ).show() } return } } } private fun showChangesNotSavedDialog() { context?.let { val builder = AlertDialog.Builder(it) builder.setMessage(R.string.msg_changes_not_saved) .setPositiveButton(R.string.msg_save) { _, _ -> updateProfile() } .setNegativeButton(android.R.string.cancel) { _, _ -> text_email.setText(currentEmail) text_username.setText(currentUsername) text_name.setText(currentName) } .create() .show() } } private fun updateProfile() { presenter.updateUserProfile( text_email.textContent, text_name.textContent, text_username.textContent ) } }
mit
258c9d2aa42d36de18ceb5a45ffe3001
33.495074
104
0.630989
4.989312
false
false
false
false
zitmen/thunderstorm-algorithms
src/main/kotlin/cz/cuni/lf1/thunderstorm/parser/FormulaParser.kt
1
7531
package cz.cuni.lf1.thunderstorm.parser import cz.cuni.lf1.thunderstorm.parser.syntaxtree.* internal class FormulaParser(formula: String) { private val lexer = FormulaLexer(formula) private var token: FormulaToken? = null private fun peek(): FormulaToken { if(token == null) token = lexer.nextToken() return token!! } @Throws(FormulaParserException::class) private fun match(type: FormulaToken): String { if(peek() == type) { val tok = token!!.token token = null return tok!! } error("Syntax error near `${token!!.token}`. Expected `$type` instead!") } @Throws(FormulaParserException::class) public fun parse(): Node { return expr() } /* ---------------------------------------------- * --- Implementation of LL1 recursive parser --- * ---------------------------------------------- */ @Throws(FormulaParserException::class) private fun error(message: String?): Nothing { if((message == null) || message.trim().isEmpty()) { throw FormulaParserException("Syntax error!") } throw FormulaParserException(message) } @Throws(FormulaParserException::class) private fun expr(): Node { return logOrExpr() } @Throws(FormulaParserException::class) private fun logOrExpr(): Node { // l|r return logOrExprTail(logAndExpr()) } @Throws(FormulaParserException::class) private fun logOrExprTail(l: Node): Node { // l|r when (peek()) { FormulaToken.OP_OR -> { match(FormulaToken.OP_OR) return logOrExprTail(BinaryOperator(Operator.OR, l, logAndExpr())) } else -> { return l } } } @Throws(FormulaParserException::class) private fun logAndExpr(): Node { // l&r return logAndExprTail(relExpr()) } @Throws(FormulaParserException::class) private fun logAndExprTail(l: Node): Node { // l&r when (peek()) { FormulaToken.OP_AND -> { match(FormulaToken.OP_AND) return logAndExprTail(BinaryOperator(Operator.AND, l, relExpr())) } else -> { return l } } } @Throws(FormulaParserException::class) private fun relExpr(): Node { // l=r, l!=r, l<r, l>r return relExprTail(addSubExpr()) } @Throws(FormulaParserException::class) private fun relExprTail(l: Node): Node { // l=r, l<r, l>r when (peek()) { FormulaToken.OP_NOT -> { match(FormulaToken.OP_NOT) match(FormulaToken.OP_EQ) return relExprTail(BinaryOperator(Operator.NEQ, l, addSubExpr())) } FormulaToken.OP_EQ -> { match(FormulaToken.OP_EQ) return relExprTail(BinaryOperator(Operator.EQ, l, addSubExpr())) } FormulaToken.OP_GT -> { match(FormulaToken.OP_GT) return relExprTail(BinaryOperator(Operator.GT, l, addSubExpr())) } FormulaToken.OP_LT -> { match(FormulaToken.OP_LT) return relExprTail(BinaryOperator(Operator.LT, l, addSubExpr())) } else -> { return l } } } @Throws(FormulaParserException::class) private fun addSubExpr(): Node { // l+r, l-r return addSubExprTail(mulDivExpr()) } @Throws(FormulaParserException::class) private fun addSubExprTail(l: Node): Node { // l+r, l-r when (peek()) { FormulaToken.OP_ADD -> { match(FormulaToken.OP_ADD) return addSubExprTail(BinaryOperator(Operator.ADD, l, mulDivExpr())) } FormulaToken.OP_SUB -> { match(FormulaToken.OP_SUB) return addSubExprTail(BinaryOperator(Operator.SUB, l, mulDivExpr())) } else -> { return l } } } @Throws(FormulaParserException::class) private fun mulDivExpr(): Node { // l*r, l/r, l%r return mulDivExprTail(powExpr()) } @Throws(FormulaParserException::class) private fun mulDivExprTail(l: Node): Node { // l*r, l/r, l%r when (peek()) { FormulaToken.OP_MUL -> { match(FormulaToken.OP_MUL) return mulDivExprTail(BinaryOperator(Operator.MUL, l, powExpr())) } FormulaToken.OP_DIV -> { match(FormulaToken.OP_DIV) return mulDivExprTail(BinaryOperator(Operator.DIV, l, powExpr())) } FormulaToken.OP_MOD -> { match(FormulaToken.OP_MOD) return mulDivExprTail(BinaryOperator(Operator.MOD, l, powExpr())) } else -> { return l } } } @Throws(FormulaParserException::class) private fun powExpr(): Node { // x^n return powExprTail(unaryExpr()) } @Throws(FormulaParserException::class) private fun powExprTail(l: Node): Node { // x^n when (peek()) { FormulaToken.OP_POW -> { match(FormulaToken.OP_POW) return powExprTail(BinaryOperator(Operator.POW, l, unaryExpr())) } else -> { return l } } } @Throws(FormulaParserException::class) private fun unaryExpr(): Node { // -x or +x when (peek()) { FormulaToken.OP_ADD -> { match(FormulaToken.OP_ADD) return BinaryOperator(Operator.ADD, Constant(0.0), atom()) } FormulaToken.OP_SUB -> { match(FormulaToken.OP_SUB) return BinaryOperator(Operator.SUB, Constant(0.0), atom()) } else -> { return atom() } } } @Throws(FormulaParserException::class) private fun atom(): Node { when (peek()) { FormulaToken.LPAR -> { match(FormulaToken.LPAR) val e = expr() match(FormulaToken.RPAR) return e } FormulaToken.FLOAT -> { return floatVal() } FormulaToken.NAME -> { return name() } else -> { error("Syntax error near `${token!!.token}`. Expected `(expression)` or a number or a variable instead!") } } } @Throws(FormulaParserException::class) private fun name(): Node { val tok = match(FormulaToken.NAME) when (peek()) { FormulaToken.DOT -> { match(FormulaToken.DOT) return Variable(namespace = tok, varName = match(FormulaToken.NAME)) } FormulaToken.LPAR -> { match(FormulaToken.LPAR) val arg = expr() match(FormulaToken.RPAR) return Function(tok, arg) // function call } else -> { return Variable(varName = tok) // just a variable (no object) } } } @Throws(FormulaParserException::class) private fun floatVal(): Node { return Constant(match(FormulaToken.FLOAT).toDouble()) } }
gpl-3.0
bbfd13005ee3f512a44c2840d40036e1
30.253112
121
0.511751
4.490757
false
false
false
false
grote/Liberario
app/src/main/java/de/grobox/transportr/trips/detail/LegAdapter.kt
1
2018
/* * Transportr * * Copyright (c) 2013 - 2018 Torsten Grote * * 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.grobox.transportr.trips.detail import androidx.recyclerview.widget.RecyclerView.Adapter import android.view.LayoutInflater import android.view.ViewGroup import de.grobox.transportr.R import de.grobox.transportr.trips.detail.LegViewHolder.LegType import de.grobox.transportr.trips.detail.LegViewHolder.LegType.* import de.schildbach.pte.dto.Trip.Leg internal class LegAdapter internal constructor( private val legs: List<Leg>, private val listener: LegClickListener, private val showLineName: Boolean) : Adapter<LegViewHolder>() { override fun onCreateViewHolder(viewGroup: ViewGroup, i: Int): LegViewHolder { val v = LayoutInflater.from(viewGroup.context).inflate(R.layout.list_item_leg, viewGroup, false) return LegViewHolder(v, listener, showLineName) } override fun onBindViewHolder(ui: LegViewHolder, i: Int) { val leg = legs[i] ui.bind(leg, getLegType(i)) } override fun getItemCount(): Int { return legs.size } private fun getLegType(position: Int): LegType { return when { legs.size == 1 -> FIRST_LAST position == 0 -> FIRST position == legs.size - 1 -> LAST else -> MIDDLE } } }
gpl-3.0
62bd4c34f1d19955f6903334df2b634a
33.793103
104
0.689296
4.152263
false
false
false
false
Jire/Acelta
src/main/kotlin/com/acelta/packet/SplitPacketeer.kt
1
1752
package com.acelta.packet import com.acelta.packet.Packeteer.AccessMode open class SplitPacketeer<T : Packeteer> : Packeteer { open lateinit var read: T open lateinit var write: T override var readIndex: Int get() = read.readIndex set(value) { read.readIndex = value } override fun get(index: Int) = read[index] override fun skip(bytes: Int) = read.skip(bytes) override val readable: Int get() = read.readable override val byte: Byte get() = read.byte override val short: Short get() = read.short override val int: Int get() = read.int override val long: Long get() = read.long override val string: String get() = read.string override var writeIndex: Int get() = write.writeIndex set(value) { write.writeIndex = value } override fun clear() = write.clear() override fun ensureWritable(bytes: Int) = write.ensureWritable(bytes) override fun set(index: Int, value: Int) { write[index] = value } override fun plus(values: ByteArray) = write + values override fun plus(value: Packeteer) = write + value override fun plus(value: Byte) = write + value override fun plus(value: Short) = write + value override fun plus(value: Int) = write + value override fun plus(value: Long) = write + value override fun plus(value: String) = write + value override var bitIndex: Int = 0 get() = write.bitIndex override var accessMode: AccessMode get() = write.accessMode set(value) { write.accessMode = value } override fun bitAccess() = write.bitAccess() override fun finishBitAccess() = write.finishBitAccess() override fun ensureAccessMode(accessMode: AccessMode) = write.ensureAccessMode(accessMode) override fun bits(numBits: Int, value: Int) = write.bits(numBits, value) }
gpl-3.0
10ac17a4c02e729dc2632daa06853af1
22.373333
91
0.712329
3.349904
false
false
false
false
google/private-compute-libraries
java/com/google/android/libraries/pcc/chronicle/codegen/Type.kt
1
4324
/* * 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.codegen /** * A [TypeSet] contains the result of the run of a converter frontend. It contains a single * top-level type, along with any supporting types needed to fully represent the fields of the type, * including any recursive dependencies required by nested types. */ data class TypeSet(val primary: Type, val additional: Set<Type> = emptySet()) : Set<Type> { constructor(vararg allTypes: Type) : this(allTypes.first(), allTypes.drop(1).toSet()) override val size = additional.size + 1 override fun contains(element: Type) = primary == element || additional.contains(element) override fun containsAll(elements: Collection<Type>) = elements.all { contains(it) } override fun isEmpty() = false override fun iterator(): Iterator<Type> { return iterator { yield(primary) additional.forEach { yield(it) } } } } /** * Intermediary representation of a POJO/Proto for use converting to a Chronicle schema. * * @param location The [TypeLocation] of the underlying Java/Kotlin type * @param fields The fields the type contains * @param oneOfs Information about mutually-exclusive field groups (from protos) conversion. The * `Set<Type>` returned from a frontend should contain exactly one item with this flag set. */ data class Type( val location: TypeLocation, val fields: List<FieldEntry>, val oneOfs: OneOfs = OneOfs(), val jvmLocation: TypeLocation = location, val tooling: Tooling = Tooling.UNKNOWN ) { val name = location.name val enclosingNames = location.enclosingNames val pkg = location.pkg /** * The library or framework within which the type was defined. * * This can be useful when generating code when it comes to knowing how to approach doing things * like creating a new instance of a type or returning a copy with a changed field. */ enum class Tooling { /** The [Type] was defined by a protocol buffer descriptor. */ PROTO, /** The [Type] was defined as an AutoValue abstract class. */ AUTOVALUE, /** The [Type] was defined as a kotlin data class. */ DATA_CLASS, /** It is either unknown or unsupported which system the [Type] was defined within. */ UNKNOWN, } } /** * Information needed to locate a Java/Kotlin type. * * @param name The simple name of the type * @param enclosingNames a list of names of enclosing types for the type, ordered innermost-first. * @param pkg The package containing the type */ data class TypeLocation( val name: String, val enclosingNames: List<String> = emptyList(), val pkg: String ) { override fun toString(): String { val fullName = (enclosingNames.reversed().filter { it.isNotEmpty() } + name).joinToString(".") return "$pkg.$fullName" } } /** * Describes one field in a structure that will become a Chronicle schema. * * @property name the name to use in the generated schema * @property category the FieldCategory of the field * @property sourceName the name in the source structure, can be an arbitrary code snippet * @property presenceCondition the code to emit to detect the presence of this field in the object */ data class FieldEntry( val name: String, val category: FieldCategory, val sourceName: String = name, val presenceCondition: String = "" ) /** * A structure to hold information of "oneof" protobuf fields. * * @property oneOfForField a map from a field name to the field name of its containing oneof field. * @property fieldsForOneOf a map from a oneof field name to a list of the field names it contains. */ data class OneOfs( val oneOfForField: Map<String, String> = emptyMap(), val fieldsForOneOf: Map<String, List<String>> = emptyMap() )
apache-2.0
fbcd7bc265d699b17ccad1b8b276cf44
35.336134
100
0.721554
4.149712
false
false
false
false
kamgurgul/cpu-info
app/src/main/java/com/kgurgul/cpuinfo/features/information/sensors/SensorsInfoViewModel.kt
1
5907
/* * Copyright 2017 KG Soft * * 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.kgurgul.cpuinfo.features.information.sensors import android.hardware.Sensor import android.hardware.SensorEvent import android.hardware.SensorEventListener import android.hardware.SensorManager import androidx.lifecycle.ViewModel import com.kgurgul.cpuinfo.utils.lifecycleawarelist.ListLiveData import com.kgurgul.cpuinfo.utils.round1 import com.kgurgul.cpuinfo.utils.runOnApiAbove import dagger.hilt.android.lifecycle.HiltViewModel import javax.inject.Inject /** * ViewModel for sensors data * * @author kgurgul */ @HiltViewModel class SensorsInfoViewModel @Inject constructor( private val sensorManager: SensorManager ) : ViewModel(), SensorEventListener { val listLiveData = ListLiveData<Pair<String, String>>() private val sensorList = sensorManager.getSensorList(Sensor.TYPE_ALL) @Synchronized fun startProvidingData() { if (listLiveData.isEmpty()) { listLiveData.addAll(sensorList.map { Pair(it.name, " ") }) } // Start register process on new Thread to avoid UI block Thread { for (sensor in sensorList) { sensorManager.registerListener(this, sensor, SensorManager.SENSOR_DELAY_NORMAL) } }.start() } fun stopProvidingData() { Thread { sensorManager.unregisterListener(this) }.start() } override fun onAccuracyChanged(sensor: Sensor, accuracy: Int) { // Do nothing } override fun onSensorChanged(event: SensorEvent) { updateSensorInfo(event) } /** * Replace sensor value with the new one */ @Synchronized private fun updateSensorInfo(event: SensorEvent) { val updatedRowId = sensorList.indexOf(event.sensor) listLiveData[updatedRowId] = Pair(event.sensor.name, getSensorData(event)) } /** * Detect sensor type for passed [SensorEvent] and format it to the correct unit */ @Suppress("DEPRECATION") private fun getSensorData(event: SensorEvent): String { var data = " " val sensorType = event.sensor.type when (sensorType) { Sensor.TYPE_ACCELEROMETER, Sensor.TYPE_GRAVITY, Sensor.TYPE_LINEAR_ACCELERATION -> data = "X=${event.values[0].round1()}m/s² Y=${ event.values[1].round1()}m/s² Z=${event.values[2].round1()}m/s²" Sensor.TYPE_GYROSCOPE -> data = "X=${event.values[0].round1()}rad/s Y=${ event.values[1].round1()}rad/s Z=${event.values[2].round1()}rad/s" Sensor.TYPE_ROTATION_VECTOR -> data = "X=${event.values[0].round1()} Y=${ event.values[1].round1()} Z=${event.values[2].round1()}" Sensor.TYPE_MAGNETIC_FIELD -> data = "X=${event.values[0].round1()}μT Y=${ event.values[1].round1()}μT Z=${event.values[2].round1()}μT" Sensor.TYPE_ORIENTATION -> data = "Azimuth=${event.values[0].round1()}° Pitch=${ event.values[1].round1()}° Roll=${event.values[2].round1()}°" Sensor.TYPE_PROXIMITY -> data = "Distance=${event.values[0].round1()}cm" Sensor.TYPE_AMBIENT_TEMPERATURE -> data = "Air temperature=${event.values[0].round1()}°C" Sensor.TYPE_LIGHT -> data = "Illuminance=${event.values[0].round1()}lx" Sensor.TYPE_PRESSURE -> data = "Air pressure=${event.values[0].round1()}hPa" Sensor.TYPE_RELATIVE_HUMIDITY -> data = "Relative humidity=${event.values[0].round1()}%" Sensor.TYPE_TEMPERATURE -> data = "Device temperature=${event.values[0].round1()}°C" } // TODO: Multiline support for this kind of data is necessary runOnApiAbove(17) { when (sensorType) { Sensor.TYPE_GYROSCOPE_UNCALIBRATED -> data = "X=${event.values[0].round1()}rad/s Y=${ event.values[1].round1()}rad/s Z=${ event.values[2].round1()}rad/s" /*\nEstimated drift: X=${ event.values[3].round1() }rad/s Y=${ event.values[4].round1() }rad/s Z=${ event.values[5].round1() }rad/s"*/ Sensor.TYPE_GAME_ROTATION_VECTOR -> data = "X=${event.values[0].round1()} Y=${ event.values[1].round1()} Z=${event.values[2].round1()}" Sensor.TYPE_MAGNETIC_FIELD_UNCALIBRATED -> data = "X=${event.values[0].round1()}μT Y=${ event.values[1].round1()}μT Z=${ event.values[2].round1()}μT" /*\nIron bias: X=${ event.values[3].round1() }μT Y=${ event.values[4].round1() }μT Z=${ event.values[5].round1() }μT"*/ } } runOnApiAbove(18) { when (sensorType) { Sensor.TYPE_GEOMAGNETIC_ROTATION_VECTOR -> data = "X=${event.values[0].round1()} Y=${ event.values[1].round1()} Z=${event.values[2].round1()}" } } return data } }
apache-2.0
45e6b2063ce0d6f879587f9a8938b1a1
37.503268
94
0.579117
4.028728
false
false
false
false
funfunStudy/algorithm
kotlin/src/main/kotlin/LilyHomework.kt
1
2437
import java.util.* fun main(args: Array<String>) { require(lilysHomework(arrayOf(3, 5, 2, 6, 1)) == 2) require(lilysHomework(arrayOf(3, 2, 1)) == 0) } fun lilysHomework(arr: Array<Int>): Int { val startSize = arr.size val asc = asc(Arrays.copyOf(arr, startSize), startSize) val desc = desc(Arrays.copyOf(arr, startSize), startSize) return if (asc < desc) asc else desc } tailrec fun asc(arrays: Array<Int>, startSize: Int, acc: Int = 0): Int { return when (arrays.size) { 0 -> acc else -> { val firstValue = arrays[0] val position = getMinValuePosition(arrays.toList(), 0, firstValue, 0) arrays[0] = arrays[position] arrays[position] = firstValue val arrayCopy = arrays.sliceArray(1 until startSize) asc(arrayCopy, startSize - 1, acc + if (position == 0) 0 else 1) } } } tailrec fun desc(arrays: Array<Int>, startSize: Int, acc: Int = 0): Int { return when (arrays.size) { 0 -> acc else -> { val firstValue = arrays[0] val position = getMaxValuePosition(arrays.toList(), 0, firstValue, 0) arrays[0] = arrays[position] arrays[position] = firstValue val arrayCopy = arrays.sliceArray(1 until startSize) desc(arrayCopy, startSize - 1, acc + if (position == 0) 0 else 1) } } } tailrec fun getMinValuePosition( list: List<Int>, position: Int, min: Int, currentPosition: Int ): Int = when (list.isEmpty()) { true -> position false -> { val firstValue = list[0] getMinValuePosition( list.drop(1), if (min < firstValue) position else currentPosition, if (min < firstValue) min else firstValue, currentPosition + 1) } } tailrec fun getMaxValuePosition(list: List<Int>, position: Int, max: Int, currentPosition: Int): Int = when (list.isEmpty()) { true -> position false -> { val firstValueInList = list[0] getMaxValuePosition( list.drop(1), if (max > firstValueInList) position else currentPosition, if (max > firstValueInList) max else firstValueInList, currentPosition + 1 ) } }
mit
7297d2c927439412fd4d229ca4caad34
29.848101
102
0.550267
4.151618
false
false
false
false
joseph-roque/BowlingCompanion
app/src/main/java/ca/josephroque/bowlingcompanion/statistics/impl/general/BowlerNameStatistic.kt
1
1857
package ca.josephroque.bowlingcompanion.statistics.impl.general import android.os.Parcel import android.os.Parcelable import ca.josephroque.bowlingcompanion.R import ca.josephroque.bowlingcompanion.common.interfaces.parcelableCreator import ca.josephroque.bowlingcompanion.statistics.StatisticsCategory import ca.josephroque.bowlingcompanion.statistics.StringStatistic import ca.josephroque.bowlingcompanion.statistics.unit.BowlerUnit import ca.josephroque.bowlingcompanion.statistics.unit.GameUnit import ca.josephroque.bowlingcompanion.statistics.unit.LeagueUnit import ca.josephroque.bowlingcompanion.statistics.unit.SeriesUnit import ca.josephroque.bowlingcompanion.statistics.unit.StatisticsUnit /** * Copyright (C) 2018 Joseph Roque * * Name of the bowler whose statistics are on display. */ class BowlerNameStatistic(override var value: String = "") : StringStatistic { // MARK: Modifiers /** @Override */ override fun modify(unit: StatisticsUnit) { when (unit) { is GameUnit -> value = unit.bowlerName is SeriesUnit -> value = unit.bowlerName is LeagueUnit -> value = unit.bowlerName is BowlerUnit -> value = unit.name } } // MARK: Overrides override val titleId = Id override val id = Id.toLong() override val category = StatisticsCategory.General override fun isModifiedBy(unit: StatisticsUnit) = true // MARK: Parcelable companion object { /** Creator, required by [Parcelable]. */ @Suppress("unused") @JvmField val CREATOR = parcelableCreator(::BowlerNameStatistic) /** Unique ID for the statistic. */ const val Id = R.string.statistic_bowler } /** * Construct this statistic from a [Parcel]. */ private constructor(p: Parcel): this(value = p.readString()!!) }
mit
6ce4261955f800b09c366288a271345f
32.160714
78
0.718901
4.6425
false
false
false
false
rori-dev/lunchbox
backend-spring-kotlin/src/test/kotlin/lunchbox/util/pdf/PdfTextGroupStripperTest.kt
1
3505
package lunchbox.util.pdf import io.mockk.every import io.mockk.mockk import org.amshove.kluent.shouldBe import org.amshove.kluent.shouldBeEqualTo import org.amshove.kluent.shouldHaveSize import org.apache.pdfbox.text.TextPosition import org.junit.jupiter.api.Test class PdfTextGroupStripperTest { @Test fun `should equip TextGroup with one letter`() { val text_a = text(Pos(1.0f, 2.0f), 1.0f, 2.0f, "a") val group = TextGroup(listOf(text_a)) group.toString() shouldBeEqualTo "a" group.xMin() shouldBeEqualTo 1.0f group.xMid() shouldBeEqualTo 1.5f group.xMax() shouldBeEqualTo 2.0f group.yMin() shouldBeEqualTo 2.0f group.yMid() shouldBeEqualTo 3.0f group.yMax() shouldBeEqualTo 4.0f group.width() shouldBeEqualTo 1.0f group.height() shouldBeEqualTo 2.0f group.xIn(0.8f) shouldBe false group.xIn(1.0f) shouldBe true group.xIn(1.5f) shouldBe true group.xIn(2.0f) shouldBe true group.xIn(2.2f) shouldBe false group.yIn(1.8f) shouldBe false group.yIn(2.0f) shouldBe true group.yIn(3.0f) shouldBe true group.yIn(4.0f) shouldBe true group.yIn(4.2f) shouldBe false } @Test fun `should equip TextGroup with three letters`() { val text_a = text(Pos(1.0f, 2.0f), 1.0f, 2.0f, "a") val text_b = text(Pos(2.0f, 2.0f), 1.0f, 2.0f, "b") val text_c = text(Pos(3.0f, 2.0f), 1.0f, 2.0f, "c") val group = TextGroup(listOf(text_a, text_b, text_c)) group.toString() shouldBeEqualTo "abc" group.xMin() shouldBeEqualTo 1.0f group.xMax() shouldBeEqualTo 4.0f group.xMid() shouldBeEqualTo 2.5f group.yMin() shouldBeEqualTo 2.0f group.yMax() shouldBeEqualTo 4.0f group.yMid() shouldBeEqualTo 3.0f group.width() shouldBeEqualTo 3.0f group.height() shouldBeEqualTo 2.0f group.xIn(0.8f) shouldBe false group.xIn(1.0f) shouldBe true group.xIn(2.5f) shouldBe true group.xIn(4.0f) shouldBe true group.xIn(4.2f) shouldBe false group.yIn(1.8f) shouldBe false group.yIn(2.0f) shouldBe true group.yIn(3.0f) shouldBe true group.yIn(4.0f) shouldBe true group.yIn(4.2f) shouldBe false } @Test fun `extract text groups from simple table`() { val url = javaClass.getResource("/simple_table.pdf") val textGroups = PdfExtractor.extractGroups(url) textGroups shouldHaveSize 4 val text_11 = textGroups.filter { it.toString() == "row 1 column 1" } text_11 shouldHaveSize 1 val text_12 = textGroups.filter { it.toString() == "row 1 column 2" } text_12 shouldHaveSize 1 val text_21 = textGroups.filter { it.toString() == "row 2 column 1" } text_21 shouldHaveSize 1 val text_22 = textGroups.filter { it.toString() == "row 2 column 2" } text_22 shouldHaveSize 1 text_11[0].xIn(text_12[0].xMid()) shouldBe false text_11[0].yIn(text_12[0].yMid()) shouldBe true text_11[0].xIn(text_21[0].xMid()) shouldBe true text_11[0].yIn(text_21[0].yMid()) shouldBe false text_11[0].xIn(text_22[0].xMid()) shouldBe false text_11[0].yIn(text_22[0].yMid()) shouldBe false } private fun text(pos: Pos, width: Float, height: Float, char: String): TextPosition { val mockPos = mockk<TextPosition>() every { mockPos.x } returns pos.x every { mockPos.y } returns pos.y every { mockPos.width } returns width every { mockPos.height } returns height every { mockPos.toString() } returns char return mockPos } data class Pos(val x: Float, val y: Float) }
mit
f3dbb9986da88cddfc996485d86a1657
28.208333
87
0.675892
3.157658
false
false
false
false
ajalt/clikt
clikt/src/jsMain/kotlin/com/github/ajalt/clikt/mpp/JsCompat.kt
1
2100
package com.github.ajalt.clikt.mpp // https://github.com/iliakan/detect-node private val isNode: Boolean = js( "Object.prototype.toString.call(typeof process !== 'undefined' ? process : 0) === '[object process]'" ) as Boolean /** Load module [mod], or throw an exception if not running on NodeJS */ internal fun nodeRequire(mod: String): dynamic { require(isNode) { "Module not available: $mod" } // This hack exists to silence webpack warnings when running on the browser. `require` is a // built-in function on Node, and doesn't exist on browsers. Webpack will statically look for // calls to `require` and rewrite them into its own module loading system. This means that when // we have `require("fs")` in our code, webpack will complain during compilation with two types // of warnings: // // 1. It will warn about the module not existing (since it's node-only), even if we never // execute that statement at runtime on the browser. // 2. It will complain with a different warning if the argument to `require` isn't static // (e.g. `fun myRequire(m:String) { require(m) }`). // // If we do run `require("fs")` on the browser, webpack will normally cause it to throw a // `METHOD_NOT_FOUND` error. If the user marks `fs` as "external" in their webpack // configuration, it will silence the first type of warning above, and the `require` call // will now return `undefined` instead of throwing an exception. // // So since we never call `require` at runtime on browsers anyway, we hide our `require` // calls from webpack by loading the method dynamically. This prevents any warnings, and // doesn't require users to add anything to their webpack config. val imported = try { js("module['' + 'require']")(mod) } catch (e: dynamic) { throw IllegalArgumentException("Module not available: $mod", e as? Throwable) } require( imported != null && js("typeof imported !== 'undefined'").unsafeCast<Boolean>() ) { "Module not available: $mod" } return imported }
apache-2.0
9a78d6c42ad9e65b625c6352d98852c7
49
105
0.677619
4.046243
false
false
false
false
BracketCove/PosTrainer
androiddata/src/main/java/com/wiseassblog/androiddata/data/reminderapi/NotificationManager.kt
1
2816
package com.wiseassblog.androiddata.data.reminderapi import android.app.NotificationChannel import android.app.NotificationManager import android.app.PendingIntent import android.content.Context import android.content.Intent import android.graphics.Color import android.os.Build import androidx.core.app.NotificationCompat import androidx.core.app.NotificationManagerCompat import com.wiseassblog.androiddata.R import com.wiseassblog.androiddata.data.* object NotificationManager { internal fun showNotification(reminderId: String, context: Context) { createNotificationChannel(context) val notification = NotificationCompat.Builder(context, CHANNEL_REMINDER) .setContentTitle(NOTIFICATION_DISMISS_TITLE) .setContentText(NOTIFICATION_CONTENT) .setColor(Color.BLUE) .setSmallIcon(R.drawable.ic_alarm_black_48dp) .setOngoing(true) //cancel on click .setAutoCancel(true) .setDefaults(NotificationCompat.DEFAULT_LIGHTS) .setWhen(0) .setCategory(NotificationCompat.CATEGORY_REMINDER) .setVisibility(NotificationCompat.VISIBILITY_PUBLIC) .setLocalOnly(true) notification.setContentIntent( getDismissIntent(context, reminderId) ) notification.setPriority(NotificationCompat.PRIORITY_MAX) NotificationManagerCompat.from(context).notify( NOTIFICATION_DISMISS_ID, notification.build() ) } private fun getDismissIntent(context: Context, reminderId: String): PendingIntent { return Intent(context, ReminderService::class.java).let { it.action = ACTION_REMINDER_DISMISSED it.putExtra(REMINDER_ID, reminderId) PendingIntent.getService( context, NOTIFICATION_DISMISS_ID, it, PendingIntent.FLAG_UPDATE_CURRENT ) } } private fun createNotificationChannel(context: Context) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { // Create the NotificationChannel val name = CHANNEL_REMINDER val descriptionText = CHANNEL_DISMISS_DESCRIPTION val importance = NotificationManager.IMPORTANCE_HIGH val channel = NotificationChannel(CHANNEL_REMINDER, CHANNEL_DISMISS_NAME, importance) channel.description = descriptionText // Register the channel with the system; you can't change the importance // or other notification behaviors after this val notificationManager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager notificationManager.createNotificationChannel(channel) } } }
apache-2.0
f69f84a029da89ebdd96c29df500d598
38.125
115
0.682173
5.436293
false
false
false
false
JustinMullin/drifter-kotlin
src/main/kotlin/xyz/jmullin/drifter/rendering/shader/ShaderUniforms.kt
1
3581
package xyz.jmullin.drifter.rendering.shader import com.badlogic.gdx.graphics.Color import com.badlogic.gdx.graphics.glutils.ShaderProgram import com.badlogic.gdx.math.Matrix3 import com.badlogic.gdx.math.Matrix4 import com.badlogic.gdx.math.Vector2 import com.badlogic.gdx.math.Vector3 abstract class ShaderUniform<T>(internal val program: ShaderProgram, internal val name: String, open val tick: (() -> T)?) { abstract fun set(value: T) fun setFromTick() { tick?.let { set(it()) } } } typealias Uniform<T> = (program: ShaderProgram, name: String) -> (T) -> Unit object Uniforms { val boolean: Uniform<Boolean> = { p, name -> { value -> p.setUniformi(name, if(value) 1 else 0) } } val int: Uniform<Int> = { p, name -> { value -> p.setUniformi(name, value) } } val float: Uniform<Float> = { p, name -> { value -> p.setUniformf(name, value) } } val vector2: Uniform<Vector2> = { p, name -> { value -> p.setUniformf(name, value) } } val vector3: Uniform<Vector3> = { p, name -> { value -> p.setUniformf(name, value) } } val matrix3: Uniform<Matrix3> = { p, name -> { value -> p.setUniformMatrix(name, value) } } val matrix4: Uniform<Matrix4> = { p, name -> { value -> p.setUniformMatrix(name, value) } } val color: Uniform<Color> = { p, name -> { value -> p.setUniformf(name, value) } } } class BooleanUniform(program: ShaderProgram, name: String, override val tick: (() -> Boolean)?) : ShaderUniform<Boolean>(program, name, tick) { override fun set(value: Boolean) = Uniforms.boolean(program, name)(value) } class IntUniform(program: ShaderProgram, name: String, override val tick: (() -> Int)?) : ShaderUniform<Int>(program, name, tick) { override fun set(value: Int) = Uniforms.int(program, name)(value) } class FloatUniform(program: ShaderProgram, name: String, override val tick: (() -> Float)?) : ShaderUniform<Float>(program, name, tick) { override fun set(value: Float) = Uniforms.float(program, name)(value) } class Vector2Uniform(program: ShaderProgram, name: String, override val tick: (() -> Vector2)?) : ShaderUniform<Vector2>(program, name, tick) { override fun set(value: Vector2) = Uniforms.vector2(program, name)(value) } class Vector3Uniform(program: ShaderProgram, name: String, override val tick: (() -> Vector3)?) : ShaderUniform<Vector3>(program, name, tick) { override fun set(value: Vector3) = Uniforms.vector3(program, name)(value) } class Matrix3Uniform(program: ShaderProgram, name: String, override val tick: (() -> Matrix3)?) : ShaderUniform<Matrix3>(program, name, tick) { override fun set(value: Matrix3) = Uniforms.matrix3(program, name)(value) } class Matrix4Uniform(program: ShaderProgram, name: String, override val tick: (() -> Matrix4)?) : ShaderUniform<Matrix4>(program, name, tick) { override fun set(value: Matrix4) = Uniforms.matrix4(program, name)(value) } class ColorUniform(program: ShaderProgram, name: String, override val tick: (() -> Color)?) : ShaderUniform<Color>(program, name, tick) { override fun set(value: Color) = Uniforms.color(program, name)(value) } class ArrayUniform<T>(program: ShaderProgram, name: String, private val subUniform: Uniform<T>, override val tick: (() -> List<T>)?) : ShaderUniform<List<T>>(program, name, tick) { override fun set(value: List<T>) { value.forEachIndexed { i, v -> subUniform(program, "$name[$i]")(v) } } }
mit
1fbb80753a49fdc8bcc9d9a4bece8af5
48.068493
124
0.656241
3.650357
false
false
false
false
signed/intellij-community
platform/platform-impl/src/com/intellij/openapi/keymap/impl/DefaultKeymap.kt
1
4745
/* * Copyright 2000-2017 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.openapi.keymap.impl import com.intellij.configurationStore.SchemeDataHolder import com.intellij.openapi.components.ServiceManager import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.diagnostic.catchAndLog import com.intellij.openapi.extensions.Extensions import com.intellij.openapi.keymap.Keymap import com.intellij.openapi.keymap.KeymapManager import com.intellij.openapi.util.JDOMUtil import com.intellij.openapi.util.SystemInfo import com.intellij.openapi.util.io.FileUtilRt import gnu.trove.THashMap import org.jdom.Element import java.util.* private val LOG = Logger.getInstance("#com.intellij.openapi.keymap.impl.DefaultKeymap") open class DefaultKeymap { private val myKeymaps = ArrayList<Keymap>() private val nameToScheme = THashMap<String, Keymap>() protected open val providers: Array<BundledKeymapProvider> get() = Extensions.getExtensions(BundledKeymapProvider.EP_NAME) init { for (provider in providers) { for (fileName in provider.keymapFileNames) { // backward compatibility (no external usages of BundledKeymapProvider, but maybe it is not published to plugin manager) val key = when (fileName) { "Keymap_Default.xml" -> "\$default.xml" "Keymap_Mac.xml" -> "Mac OS X 10.5+.xml" "Keymap_MacClassic.xml" -> "Mac OS X.xml" "Keymap_GNOME.xml" -> "Default for GNOME.xml" "Keymap_KDE.xml" -> "Default for KDE.xml" "Keymap_XWin.xml" -> "Default for XWin.xml" "Keymap_EclipseMac.xml" -> "Eclipse (Mac OS X).xml" "Keymap_Eclipse.xml" -> "Eclipse.xml" "Keymap_Emacs.xml" -> "Emacs.xml" "JBuilderKeymap.xml" -> "JBuilder.xml" "Keymap_Netbeans.xml" -> "NetBeans 6.5.xml" "Keymap_ReSharper_OSX.xml" -> "ReSharper OSX.xml" "Keymap_ReSharper.xml" -> "ReSharper.xml" "RM_TextMateKeymap.xml" -> "TextMate.xml" "Keymap_Xcode.xml" -> "Xcode.xml" else -> fileName } LOG.catchAndLog { loadKeymapsFromElement(object: SchemeDataHolder<KeymapImpl> { override fun read() = provider.load(key) { JDOMUtil.load(it) } override fun updateDigest(scheme: KeymapImpl) { } override fun updateDigest(data: Element) { } }, FileUtilRt.getNameWithoutExtension(key)) } } } } companion object { @JvmStatic val instance: DefaultKeymap get() = ServiceManager.getService(DefaultKeymap::class.java) @JvmStatic fun matchesPlatform(keymap: Keymap): Boolean { val name = keymap.name return when (name) { KeymapManager.DEFAULT_IDEA_KEYMAP -> SystemInfo.isWindows KeymapManager.MAC_OS_X_KEYMAP, KeymapManager.MAC_OS_X_10_5_PLUS_KEYMAP -> SystemInfo.isMac KeymapManager.X_WINDOW_KEYMAP, KeymapManager.GNOME_KEYMAP, KeymapManager.KDE_KEYMAP -> SystemInfo.isXWindow else -> true } } } private fun loadKeymapsFromElement(dataHolder: SchemeDataHolder<KeymapImpl>, keymapName: String) { val keymap = if (keymapName.startsWith(KeymapManager.MAC_OS_X_KEYMAP)) MacOSDefaultKeymap(dataHolder, this) else DefaultKeymapImpl(dataHolder, this) keymap.name = keymapName myKeymaps.add(keymap) nameToScheme.put(keymapName, keymap) } val keymaps: Array<Keymap> get() = myKeymaps.toTypedArray() internal fun findScheme(name: String) = nameToScheme.get(name) open val defaultKeymapName: String get() = when { SystemInfo.isMac -> KeymapManager.MAC_OS_X_KEYMAP SystemInfo.isGNOME -> KeymapManager.GNOME_KEYMAP SystemInfo.isKDE -> KeymapManager.KDE_KEYMAP SystemInfo.isXWindow -> KeymapManager.X_WINDOW_KEYMAP else -> KeymapManager.DEFAULT_IDEA_KEYMAP } open fun getKeymapPresentableName(keymap: KeymapImpl): String { val name = keymap.name // Netbeans keymap is no longer for version 6.5, but we need to keep the id if (name == "NetBeans 6.5") { return "NetBeans" } return if (KeymapManager.DEFAULT_IDEA_KEYMAP == name) "Default" else name } }
apache-2.0
86354294d6cfd7ef1a729faf1f72b9b2
36.070313
152
0.691465
4.086994
false
false
false
false
saru95/DSA
Kotlin/InsertionSort.kt
1
1187
// cruxiu :) import java.util.ArrayList import java.util.Scanner class InsertionSort { fun insertionSort(list: Array<Integer>): Array<Integer> { var temp: Int for (i in 1 until list.size) { for (j in i downTo 1) { if (list[j] < list[j - 1]) { temp = list[j].toInt() list[j] = list[j - 1] list[j - 1] = temp } } } return list } fun main(a: Array<String>) { val scanner = Scanner(System.`in`) val arrayList = ArrayList<Integer>() System.out.println("Please, enter the elements of the list.") while (scanner.hasNextInt()) { arrayList.add(scanner.nextInt()) } var array = arrayList.toArray(arrayOfNulls<Integer>(0)) System.out.println("Now, we will sort the list. Your list now is:") for (i in array.indices) { System.out.println(array[i]) } array = insertionSort(array) System.out.println("After sort, your list now is:") for (i in array.indices) { System.out.println(array[i]) } } }
mit
a9aeb27e3c4f92a3263f7f887b3cd31c
30.236842
75
0.518113
3.996633
false
false
false
false
christophpickl/gadsu
src/main/kotlin/at/cpickl/gadsu/version/service.kt
1
3928
package at.cpickl.gadsu.version import at.cpickl.gadsu.global.APP_SUFFIX import at.cpickl.gadsu.global.AppStartupEvent import at.cpickl.gadsu.global.GadsuSystemProperty import at.cpickl.gadsu.preferences.Prefs import at.cpickl.gadsu.service.InternetConnectionLostEvent import at.cpickl.gadsu.service.LOG import at.cpickl.gadsu.service.NoInternetConnectionException import at.cpickl.gadsu.service.OpenWebpageEvent import at.cpickl.gadsu.view.AsyncDialogSettings import at.cpickl.gadsu.view.AsyncWorker import at.cpickl.gadsu.view.components.DialogType import at.cpickl.gadsu.view.components.Dialogs import at.cpickl.gadsu.view.currentActiveJFrame import com.google.common.eventbus.EventBus import com.google.common.eventbus.Subscribe import java.net.URL import javax.inject.Inject interface VersionUpdater { // nothing, just via events :) } open class VersionUpdaterImpl @Inject constructor( private val checker: VersionChecker, private val dialogs: Dialogs, private val asyncWorker: AsyncWorker, private val bus: EventBus, private val prefs: Prefs ) : VersionUpdater { private val log = LOG(javaClass) private val dialogTitle = "Auto Update" private fun checkForUpdates(settings: AsyncDialogSettings?) { log.debug("validateVersion(settings)") asyncWorker.doInBackground(settings, { checker.check() }, { onResult(result = it!!, suppressUpToDateDialog = settings == null) }, { e -> if (e is NoInternetConnectionException) { bus.post(InternetConnectionLostEvent()) } else { throw e } }) } @Subscribe open fun onAppStartupEvent(event: AppStartupEvent) { if (prefs.preferencesData.checkUpdates) { if (GadsuSystemProperty.disableAutoUpdate.isEnabledOrFalse()) { log.warn("Auto update disabled (most likely because of UI test).") } else { log.debug("Preferences stated we should check updates on startup") checkForUpdates(null) // dont display progress dialog when checking at startup } } } @Subscribe open fun onCheckForUpdatesEvent(event: CheckForUpdatesEvent) { checkForUpdates(AsyncDialogSettings(dialogTitle, "Prüfe die aktuellste Version ...")) } private fun onResult(result: VersionCheckResult, suppressUpToDateDialog: Boolean = false) { log.trace("onResult(result={}, suppressUpToDateDialog={})", result, suppressUpToDateDialog) when (result) { is VersionCheckResult.UpToDate -> { if (!suppressUpToDateDialog) { dialogs.show(dialogTitle, "Juchu, du hast die aktuellste Version installiert!", arrayOf("Ok"), null, DialogType.INFO, currentActiveJFrame()) } } is VersionCheckResult.OutDated -> { val selected = dialogs.show(dialogTitle, "Es gibt eine neuere Version von Gadsu.\n" + "Du benutzt zur Zeit ${result.current.toLabel()} aber es ist bereits Version ${result.latest.toLabel()} verfügbar.\n" + "Bitte lade die neueste Version herunter.", arrayOf("Download starten"), null, DialogType.WARN, currentActiveJFrame()) if (selected == null) { log.debug("User closed window by hitting the close button, seems as he doesnt care about using the latest version :-/") return } val version = result.latest.toLabel() val downloadUrl = "https://github.com/christophpickl/gadsu/releases/download/v$version/Gadsu-$version.${APP_SUFFIX}" log.info("Going to download latest gadsu version from: {}", downloadUrl) bus.post(OpenWebpageEvent(URL(downloadUrl))) } } } }
apache-2.0
432efc6a7ebf68203e19824fe115c4a4
41.673913
144
0.657667
4.59719
false
true
false
false
jiangkang/KTools
hybrid/src/main/java/com/jiangkang/hybrid/web/WebArgs.kt
1
432
package com.jiangkang.hybrid.web /** * Created by jiangkang on 2018/2/27. * description: */ class WebArgs { var isLoadImgLazy: Boolean = false var isInterceptResources: Boolean = false companion object { val IS_LOAD_IMG_LAZY = "is_load_img_lazy" val IS_INTERCEPT_RESOURCES = "IS_INTERCEPT_RESOURCES" val STR_INJECTED_JS = "str_injected_js" } var jsInjected: String = "" }
mit
1fc5f8a10353125bb7cac011022e9976
14.962963
61
0.64186
3.553719
false
false
false
false
andrei-heidelbacher/algostorm
algostorm-core/src/main/kotlin/com/andreihh/algostorm/core/engine/Engine.kt
1
5309
/* * Copyright (c) 2017 Andrei Heidelbacher <[email protected]> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.andreihh.algostorm.core.engine import com.andreihh.algostorm.core.engine.Engine.Status.RELEASED import com.andreihh.algostorm.core.engine.Engine.Status.RUNNING import com.andreihh.algostorm.core.engine.Engine.Status.STOPPED import com.andreihh.algostorm.core.engine.Engine.Status.STOPPING import com.andreihh.algostorm.core.engine.Engine.Status.UNINITIALIZED import java.util.ServiceLoader import kotlin.concurrent.thread import kotlin.system.measureNanoTime /** * An asynchronous engine that runs the game loop on its own private thread. * * All changes to the game state outside of this engine's thread may lead to * inconsistent state and concurrency issues. Thus, the engine state should * remain private to the engine and modified only in the [Handler.onUpdate] and * [Handler.onRelease] methods. * * All the engine methods are thread safe as long as the complete construction * of the engine and initialization of the state happen-before any other method * call. * * @property platform the platform of this engine */ class Engine(private val platform: Platform) { companion object { /** Name of the engine thread. */ const val NAME: String = "ALGOSTORM" } /** The status of an engine. */ enum class Status { UNINITIALIZED, RUNNING, STOPPING, STOPPED, RELEASED } /** The current status of this engine. */ @Volatile var status: Status = UNINITIALIZED private set private val handler = ServiceLoader.load(Handler::class.java).first() private var process: Thread? = null @Throws(Exception::class) private fun run() { handler.onStart() while (status == RUNNING) { val elapsedMillis = measureNanoTime(handler::onUpdate) / 1000000 check(elapsedMillis >= 0) { "Elapsed time can't be negative!" } val updateMillis = handler.millisPerUpdate check(updateMillis > 0) { "Update time must be positive!" } val sleepMillis = updateMillis - elapsedMillis if (sleepMillis > 0) { Thread.sleep(sleepMillis) } } handler.onStop() } fun init(args: Map<String, Any?>) { check(status == UNINITIALIZED) { "Engine already initialized!" } handler.onInit(platform, args) status = STOPPED } /** * Sets the [status] to [Status.RUNNING] and starts the engine thread. * * While this engine is running, at most once every * [Handler.millisPerUpdate] milliseconds, it will invoke the * [Handler.onUpdate] method on the engine thread. * * Time is measured using [measureNanoTime]. If, at any point, the measured * time or [Handler.millisPerUpdate] is negative, the engine thread throws * an [IllegalStateException] and terminates. * * @throws IllegalStateException if the `status` is not `Status.STOPPED` */ fun start() { check(status == STOPPED) { "Engine can't start if not stopped!" } status = RUNNING process = thread(name = NAME) { try { run() } catch (e: Exception) { handler.onError(e) } } } /** * Sets the engine [status] to [Status.STOPPING] and then joins the engine * thread to the current thread, waiting at most [timeoutMillis] * milliseconds. * * If the join succeeds, the `status` will be set to `Status.STOPPED`. * * The timeout must be positive. * * @throws InterruptedException if the current thread is interrupted while * waiting for this engine to stop * @throws IllegalStateException if this engine attempts to stop itself, * because the engine thread can't join itself */ @Throws(InterruptedException::class) fun stop(timeoutMillis: Int) { require(timeoutMillis > 0) { "Timeout must be positive!" } check(status == RUNNING || status == STOPPING) { "Engine can't stop if not running or stopping!" } status = STOPPING check(process != Thread.currentThread()) { "Engine can't stop itself!" } process?.join(timeoutMillis.toLong()) process = null status = STOPPED } /** * Performs clean-up logic and releases this engine's drivers. * * The engine `status` must be `Status.STOPPED`. * * @throws IllegalStateException if this engine is not stopped */ fun release() { check(status == STOPPED) { "Engine can't be released if not stopped!" } handler.onRelease() platform.release() status = RELEASED } }
apache-2.0
689ee1c3ee14516e6d24096b691c6629
35.115646
80
0.658128
4.47262
false
false
false
false
nlefler/Glucloser
Glucloser/app/src/main/kotlin/com/nlefler/glucloser/a/dataSource/jsonAdapter/PlaceJsonAdapter.kt
1
1116
package com.nlefler.glucloser.a.dataSource.jsonAdapter import com.nlefler.glucloser.a.models.Place import com.nlefler.glucloser.a.models.PlaceEntity import com.nlefler.glucloser.a.models.json.PlaceJson import com.squareup.moshi.FromJson import com.squareup.moshi.ToJson /** * Created by nathan on 1/31/16. */ public class PlaceJsonAdapter() { companion object { private val LOG_TAG = "PlaceJsonAdapter" } @FromJson fun fromJson(json: PlaceJson): Place { val place = PlaceEntity() place.primaryId = json.primaryId place.name = json.name place.foursquareId = json.foursquareId place.latitude = json.latitude place.longitude = json.longitude place.visitCount = json.visitCount return place } @ToJson fun toJson(place: Place): PlaceJson { return PlaceJson(primaryId = place.primaryId, foursquareId = place.foursquareId, name = place.name, latitude = place.latitude, longitude = place.longitude, visitCount = place.visitCount) } }
gpl-2.0
52dbeea1a218ec3ee3bb1e1ee945b9b0
30
54
0.658602
4.148699
false
false
false
false
Magneticraft-Team/Magneticraft
src/main/kotlin/com/cout970/magneticraft/features/decoration/Blocks.kt
2
3840
package com.cout970.magneticraft.features.decoration import com.cout970.magneticraft.misc.CreativeTabMg import com.cout970.magneticraft.misc.RegisterBlocks import com.cout970.magneticraft.misc.resource import com.cout970.magneticraft.misc.vector.createAABBUsing import com.cout970.magneticraft.systems.blocks.* import com.cout970.magneticraft.systems.itemblocks.itemBlockListOf import com.cout970.magneticraft.systems.tilerenderers.PIXEL import net.minecraft.block.Block import net.minecraft.block.material.Material import net.minecraft.block.properties.IProperty import net.minecraft.block.properties.PropertyEnum import net.minecraft.block.state.IBlockState import net.minecraft.item.ItemBlock import net.minecraft.util.IStringSerializable import net.minecraft.util.math.Vec3d /** * Created by cout970 on 2017/06/08. */ @RegisterBlocks object Blocks : IBlockMaker { val PROPERTY_LIMESTONE_KIND = PropertyEnum.create("limestone_kind", LimestoneKind::class.java) val PROPERTY_INVERTED = PropertyEnum.create("inverted", TileInverted::class.java) lateinit var limestone: BlockBase private set lateinit var burnLimestone: BlockBase private set lateinit var tileLimestone: BlockBase private set lateinit var tubeLight: BlockBase private set override fun initBlocks(): List<Pair<Block, ItemBlock>> { val builder = BlockBuilder().apply { material = Material.ROCK creativeTab = CreativeTabMg states = LimestoneKind.values().toList() } limestone = builder.withName("limestone").build() burnLimestone = builder.withName("burnt_limestone").build() tileLimestone = builder.withName("tile_limestone").copy { states = TileInverted.values().toList() }.build() tubeLight = builder.withName("tube_light").copy { states = CommonMethods.Orientation.values().toList() factory = factoryOf(::TileTubeLight) lightEmission = 1f hasCustomModel = true generateDefaultItemBlockModel = false alwaysDropDefault = true customModels = listOf( "model" to resource("models/block/mcx/tube_light.mcx"), "inventory" to resource("models/block/mcx/tube_light.mcx") ) //methods boundingBox = CommonMethods.updateBoundingBoxWithOrientation { listOf(Vec3d(PIXEL * 3, 1.0, 0.0) createAABBUsing Vec3d(1.0 - PIXEL * 3, 1.0 - PIXEL * 4, 1.0)) } onBlockPlaced = CommonMethods::placeWithOrientation pickBlock = CommonMethods::pickDefaultBlock }.build() return itemBlockListOf(limestone, burnLimestone, tileLimestone, tubeLight) } enum class LimestoneKind(override val stateName: String, override val isVisible: Boolean) : IStatesEnum, IStringSerializable { NORMAL("normal", true), BRICK("brick", true), COBBLE("cobble", true); override fun getName() = name.toLowerCase() override val properties: List<IProperty<*>> get() = listOf(PROPERTY_LIMESTONE_KIND) override fun getBlockState(block: Block): IBlockState { return block.defaultState.withProperty(PROPERTY_LIMESTONE_KIND, this) } } enum class TileInverted(override val stateName: String, override val isVisible: Boolean) : IStatesEnum, IStringSerializable { NORMAL("normal", true), INVERTED("inverted", true); override fun getName() = name.toLowerCase() override val properties: List<IProperty<*>> get() = listOf(PROPERTY_INVERTED) override fun getBlockState(block: Block): IBlockState { return block.defaultState.withProperty(PROPERTY_INVERTED, this) } } }
gpl-2.0
77421dfba6d832e657ac777e5d74a87b
38.597938
111
0.682813
4.491228
false
false
false
false
cFerg/CloudStorming
ObjectAvoidance/kotlin/src/elite/math/angle/MicroArcSecond.kt
1
1220
package elite.math.angle /** * * @author CFerg (Elite) */ class MicroArcSecond { internal var microSecond: Double = 0.toDouble() /** * */ constructor() { this.microSecond = (1 / 60 / 60 / 1000 / 1000).toDouble() } /** * * @param a */ constructor(a: Degree) { this.microSecond = a.degree / 3600 / 1000 / 1000 } /** * * @param a */ constructor(a: ArcMinute) { this.microSecond = a.minute / 60 / 1000 / 1000 } /** * * @param a */ constructor(a: ArcSecond) { this.microSecond = a.second * 1000 * 1000 } /** * * @param a */ constructor(a: MilliArcSecond) { this.microSecond = a.milliSecond * 1000 } /** * * @return */ fun toDegree(): Degree { return Degree(this) } /** * * @return */ fun toMinute(): ArcMinute { return ArcMinute(this) } /** * * @return */ fun toSecond(): ArcSecond { return ArcSecond(this) } /** * * @return */ fun toMilliSecond(): MilliArcSecond { return MilliArcSecond(this) } }
bsd-3-clause
f49b6f4c56d0a2132ca5239ca7dae521
14.074074
65
0.463934
3.730887
false
false
false
false
EyeBody/EyeBody
EyeBody2/app/src/main/java/com/example/android/eyebody/dialog/EnterGalleryDialog.kt
1
2964
package com.example.android.eyebody.dialog import android.app.AlertDialog import android.app.Dialog import android.app.DialogFragment import android.content.Context import android.content.Intent import android.content.SharedPreferences import android.os.Bundle import android.util.Log import android.widget.Button import android.widget.EditText import android.widget.Toast import com.example.android.eyebody.gallery.GalleryActivity import com.example.android.eyebody.R import java.security.MessageDigest /** * Created by YOON on 2017-09-24. */ class EnterGalleryDialog : DialogFragment() { override fun onCreateDialog(savedInstanceState: Bundle?): Dialog { val layoutInflater = activity.layoutInflater val dialogbuilder = AlertDialog.Builder(activity) val view = layoutInflater.inflate(R.layout.dialog_main_enter_gallery_input_pw, null) Log.d("mydbg_enterGallery", "[ enterGallery 다이얼로그 진입 ]") val bt_pwSubmit = view.findViewById<Button>(R.id.Button_enter_gallery_pw_submit) val tv_pwInput = view.findViewById<EditText>(R.id.EditText_enter_gallery_pw_input) val sharedPref: SharedPreferences = activity.getSharedPreferences( getString(R.string.getSharedPreference_initSetting), Context.MODE_PRIVATE) val sharedPref_hashedPW = sharedPref.getString( getString(R.string.sharedPreference_hashedPW), getString(R.string.sharedPreference_default_hashedPW)) // 키보드-확인 눌렀을 때 반응 tv_pwInput.setOnEditorActionListener { textView, i, keyEvent -> true Log.d("mydbg_enterGallery", "is ok ????") bt_pwSubmit.callOnClick() } dialogbuilder.setView(view) .setTitle("Input Password") .setMessage("Please type your private password") // button Listener bt_pwSubmit.setOnClickListener { // EditText 친 부분 MD5 암호화 val md5 = MessageDigest.getInstance("MD5") val str_inputPW: String = tv_pwInput.text.toString() val pwByte: ByteArray = str_inputPW.toByteArray(charset("unicode")) md5.update(pwByte) val hashedPW = md5.digest().toString(charset("unicode")) // 공유변수와 일치여부 검증 Log.d("mydbg_enterGallery", "prePW : $sharedPref_hashedPW / PW : $hashedPW") if (hashedPW == sharedPref_hashedPW.toString()) { val galleryPage = Intent(activity, GalleryActivity::class.java) startActivity(galleryPage) dismiss() } else { Toast.makeText(activity, "관계자 외 출입금지~", Toast.LENGTH_LONG).show() } } return dialogbuilder.create() } override fun onStop() { super.onStop() Log.d("mydbg_enterGallery", "다이얼로그가 가려짐 또는 종료됨") } }
mit
7e32c3323a3e5b8df885dedec94b7695
35.088608
117
0.660351
3.947368
false
false
false
false