repo_name
stringlengths 7
81
| path
stringlengths 6
242
| copies
stringclasses 55
values | size
stringlengths 2
6
| content
stringlengths 55
737k
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 5.44
99.8
| line_max
int64 15
979
| alpha_frac
float64 0.3
0.91
| ratio
float64 2
9.93
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
carlphilipp/chicago-commutes | android-app/src/main/kotlin/fr/cph/chicago/core/model/BusStop.kt | 1 | 2365 | /**
* Copyright 2021 Carl-Philipp Harmant
*
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*
* http://www.apache.org/licenses/LICENSE-2.0
*
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package fr.cph.chicago.core.model
import android.os.Parcel
import android.os.Parcelable
import org.apache.commons.lang3.StringUtils
/**
* Bus stop entity
*
* @author Carl-Philipp Harmant
* @version 1
*/
class BusStop(
id: String,
name: String,
val description: String,
val position: Position) : Comparable<BusStop>, Parcelable, Station(id, name) {
companion object {
@JvmField
val CREATOR: Parcelable.Creator<BusStop> = object : Parcelable.Creator<BusStop> {
override fun createFromParcel(source: Parcel): BusStop {
return BusStop(source)
}
override fun newArray(size: Int): Array<BusStop?> {
return arrayOfNulls(size)
}
}
}
private constructor(source: Parcel) : this(
id = source.readString() ?: StringUtils.EMPTY,
name = source.readString() ?: StringUtils.EMPTY,
description = source.readString() ?: StringUtils.EMPTY,
position = source.readParcelable<Position>(Position::class.java.classLoader) ?: Position())
override fun toString(): String {
return "[id:$id;name:$name;description:$description;position:$position]"
}
override fun compareTo(other: BusStop): Int {
val position = other.position
val latitude = position.latitude.compareTo(position.latitude)
return if (latitude == 0) position.longitude.compareTo(position.longitude) else latitude
}
override fun describeContents(): Int {
return 0
}
override fun writeToParcel(dest: Parcel, flags: Int) {
dest.writeString(id)
dest.writeString(name)
dest.writeString(description)
dest.writeParcelable(position, flags)
}
}
| apache-2.0 | de625433f6b90b3143e86a81dc21415b | 29.714286 | 99 | 0.668499 | 4.437148 | false | false | false | false |
BennyKok/PxerStudio | app/src/main/java/com/benny/pxerstudio/shape/draw/LineShape.kt | 1 | 2422 | package com.benny.pxerstudio.shape.draw
import android.graphics.Color
import android.graphics.Paint
import com.benny.pxerstudio.widget.PxerView
import com.benny.pxerstudio.widget.PxerView.Pxer
/**
* Created by BennyKok on 10/12/2016.
*/
class LineShape : DrawShape() {
private val p = Paint()
private val previousPxer = ArrayList<Pxer>()
private var hasInit = false
var width: Float
get() { return p.strokeWidth }
set(value) { p.strokeWidth = value }
override fun onDraw(
pxerView: PxerView,
startX: Int,
startY: Int,
endX: Int,
endY: Int
): Boolean {
if (!super.onDraw(pxerView, startX, startY, endX, endY)) {
return true
}
if (!hasInit) {
p.color = Color.YELLOW
pxerView.preview!!.eraseColor(Color.TRANSPARENT)
pxerView.previewCanvas.setBitmap(pxerView.preview)
hasInit = true
}
val layerToDraw = pxerView.pxerLayers[pxerView.currentLayer]!!.bitmap
draw(layerToDraw!!, previousPxer)
pxerView.preview!!.eraseColor(Color.TRANSPARENT)
/*
if (startX < endX) endX++ else endX--
if (startX > endX) startX++ else startX--
if (startY < endY) endY++ else endY--
if (startY > endY) startY++ else startY--
*/
pxerView.previewCanvas.drawLine(
startX.toFloat(),
startY.toFloat(),
endX.toFloat(),
endY.toFloat(),
p
)
// pxerView.preview!!.setPixel(startX, startY, pxerView.selectedColor)
// pxerView.preview!!.setPixel(endX, endY, pxerView.selectedColor)
for (i in 0 until pxerView.picWidth) {
for (y in 0 until pxerView.picHeight) {
var c = pxerView.preview!!.getPixel(i, y)
if (i == startX && y == startY || i == endX && y == endY) c = Color.YELLOW
if (c == Color.YELLOW) {
addPxerView(layerToDraw, previousPxer, i, y)
drawOnLayer(layerToDraw, pxerView, i, y)
}
}
}
pxerView.invalidate()
return true
}
override fun onDrawEnd(pxerView: PxerView) {
super.onDrawEnd(pxerView)
hasInit = false
pxerView.endDraw(previousPxer)
}
init {
p.style = Paint.Style.STROKE
p.strokeWidth = 1f
}
}
| apache-2.0 | 36408952a497e95786b78a54d27963f6 | 28.901235 | 90 | 0.57019 | 4.348294 | false | false | false | false |
google/horologist | sample/src/main/java/com/google/android/horologist/sectionedlist/stateful/SectionedListStatefulScreenViewModel.kt | 1 | 4255 | /*
* Copyright 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.horologist.sectionedlist.stateful
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.DirectionsRun
import androidx.compose.material.icons.filled.SelfImprovement
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.launch
import kotlin.random.Random
class SectionedListStatefulScreenViewModel : ViewModel() {
private val _uiState = MutableStateFlow(
UiState(
recommendationSectionState = RecommendationSectionState.Loading,
trendingSectionState = TrendingSectionState.Loading
)
)
val uiState: StateFlow<UiState> = _uiState
init {
loadRecommendations()
loadTrending()
}
data class UiState(
val recommendationSectionState: RecommendationSectionState,
val trendingSectionState: TrendingSectionState
)
sealed class RecommendationSectionState {
object Loading : RecommendationSectionState()
data class Loaded(val list: List<Recommendation>) : RecommendationSectionState()
object Failed : RecommendationSectionState()
}
data class Recommendation(
val playlistName: String,
val icon: ImageVector
)
sealed class TrendingSectionState {
object Loading : TrendingSectionState()
data class Loaded(val list: List<Trending>) : TrendingSectionState()
object Failed : TrendingSectionState()
}
data class Trending(
val name: String,
val artist: String
)
fun loadRecommendations() {
viewModelScope.launch {
_uiState.value = _uiState.value.copy(
recommendationSectionState = RecommendationSectionState.Loading
)
// pretend it is fetching date over remote
delay(getRandomTimeInMillis())
_uiState.value = _uiState.value.copy(
recommendationSectionState = if (shouldFailToLoad()) {
RecommendationSectionState.Failed
} else {
RecommendationSectionState.Loaded(
list = listOf(
Recommendation("Running playlist", Icons.Default.DirectionsRun),
Recommendation("Focus", Icons.Default.SelfImprovement)
)
)
}
)
}
}
fun loadTrending() {
viewModelScope.launch {
_uiState.value = _uiState.value.copy(
trendingSectionState = TrendingSectionState.Loading
)
// pretend it is fetching date over remote
delay(getRandomTimeInMillis())
_uiState.value = _uiState.value.copy(
trendingSectionState = if (shouldFailToLoad()) {
TrendingSectionState.Failed
} else {
TrendingSectionState.Loaded(
list = listOf(
Trending("There'd Better Be A Mirrorball", "Arctic Monkeys"),
Trending("180 Hours", "Dudu Kanegae")
)
)
}
)
}
}
private fun shouldFailToLoad(): Boolean {
return Random.nextInt(1, 3) == 1
}
private fun getRandomTimeInMillis(): Long {
return Random.nextLong(3000, 7000)
}
}
| apache-2.0 | a36ca4c8d43710480083b0f9c74216e0 | 32.242188 | 92 | 0.629847 | 5.606061 | false | false | false | false |
googlecodelabs/tv-watchnext | step_final/src/main/java/com/example/android/watchnextcodelab/channels/WatchNextAction.kt | 4 | 2606 | /*
* Copyright (C) 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 com.example.android.watchnextcodelab.channels
import android.content.Context
import android.support.annotation.WorkerThread
import com.example.android.watchnextcodelab.database.MockDatabase
import com.example.android.watchnextcodelab.database.SharedPreferencesDatabase
import com.example.android.watchnextcodelab.watchlist.WatchlistManager
/**
* Functions for managing the watch next row.
*/
object WatchNextAction {
private val database = MockDatabase.get()
@WorkerThread
fun watchNext(context: Context, movieId: Long) {
val movie = database.findMovieById(movieId) ?: return
val watchNextId = WatchNextTvProvider.addToWatchNextNext(context, movie)
database.updateMovieProgramId(context, movieId, watchNextProgramId = watchNextId)
}
@WorkerThread
fun addToContinueWatching(context: Context, movieId: Long, playbackPosition: Int) {
val movie = database.findMovieById(movieId) ?: return
val watchNextId = WatchNextTvProvider.addToWatchNextContinue(context, movie, playbackPosition)
database.updateMovieProgramId(context, movieId, watchNextProgramId = watchNextId)
SharedPreferencesDatabase().savePlaybackPosition(context, movie, playbackPosition)
}
@WorkerThread
fun removeFromContinueWatching(context: Context, movieId: Long) {
WatchNextTvProvider.deleteFromWatchNext(context, movieId.toString())
SharedPreferencesDatabase().deletePlaybackPosition(context, movieId.toString())
// If the user finishes watching a movie in the watch list, then remove it from the list.
WatchlistManager.get().removeMovieFromWatchlist(context, movieId)
}
@WorkerThread
fun addToWatchlist(context: Context, movieId: Long) {
WatchlistManager.get().addToWatchlist(context, movieId)
}
@WorkerThread
fun removeFromWatchlist(context: Context, movieId: Long) {
WatchlistManager.get().removeMovieFromWatchlist(context, movieId)
}
}
| apache-2.0 | b982e1238cbc7e7e78cd44fe10bf9ac7 | 36.768116 | 102 | 0.755564 | 4.790441 | false | false | false | false |
fnberta/PopularMovies | app/src/main/java/ch/berta/fabio/popularmovies/features/grid/vdos/GridViewData.kt | 1 | 1728 | /*
* Copyright (c) 2017 Fabio Berta
*
* 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 ch.berta.fabio.popularmovies.features.grid.vdos
import android.databinding.BaseObservable
import android.databinding.Bindable
import ch.berta.fabio.popularmovies.BR
import ch.berta.fabio.popularmovies.features.common.vdos.LoadingEmptyViewData
class GridViewData : BaseObservable(), LoadingEmptyViewData {
@get:Bindable
override var loading: Boolean = false
set(value) {
field = value
notifyPropertyChanged(BR.loading)
}
@get:Bindable
override var empty: Boolean = false
set(value) {
field = value
notifyPropertyChanged(BR.empty)
}
@get:Bindable
var refreshEnabled: Boolean = false
set(value) {
field = value
notifyPropertyChanged(BR.refreshEnabled)
}
@get:Bindable
var refreshing: Boolean = false
set(value) {
field = value
notifyPropertyChanged(BR.refreshing)
}
@get:Bindable
var loadingMore: Boolean = false
set(value) {
field = value
notifyPropertyChanged(BR.loadingMore)
}
} | apache-2.0 | c285c3de548858e3d9e6ffda1593c6ff | 28.305085 | 77 | 0.668981 | 4.571429 | false | false | false | false |
chrisbanes/tivi | ui/discover/src/main/java/app/tivi/home/discover/DiscoverViewState.kt | 1 | 1793 | /*
* Copyright 2017 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 app.tivi.home.discover
import androidx.compose.runtime.Immutable
import app.tivi.api.UiMessage
import app.tivi.data.entities.TraktUser
import app.tivi.data.resultentities.EpisodeWithSeasonWithShow
import app.tivi.data.resultentities.PopularEntryWithShow
import app.tivi.data.resultentities.RecommendedEntryWithShow
import app.tivi.data.resultentities.TrendingEntryWithShow
import app.tivi.trakt.TraktAuthState
@Immutable
internal data class DiscoverViewState(
val user: TraktUser? = null,
val authState: TraktAuthState = TraktAuthState.LOGGED_OUT,
val trendingItems: List<TrendingEntryWithShow> = emptyList(),
val trendingRefreshing: Boolean = false,
val popularItems: List<PopularEntryWithShow> = emptyList(),
val popularRefreshing: Boolean = false,
val recommendedItems: List<RecommendedEntryWithShow> = emptyList(),
val recommendedRefreshing: Boolean = false,
val nextEpisodeWithShowToWatched: EpisodeWithSeasonWithShow? = null,
val message: UiMessage? = null
) {
val refreshing: Boolean
get() = trendingRefreshing || popularRefreshing || recommendedRefreshing
companion object {
val Empty = DiscoverViewState()
}
}
| apache-2.0 | 78603ce7b06c4455c3e315b80fe1f54f | 37.148936 | 80 | 0.766871 | 4.505025 | false | false | false | false |
Kennyc1012/TextDrawable | library/src/main/java/com/kennyc/textdrawable/TextDrawable.kt | 1 | 6313 | package com.kennyc.textdrawable
import android.graphics.*
import android.graphics.drawable.ShapeDrawable
import android.graphics.drawable.shapes.OvalShape
import android.graphics.drawable.shapes.RectShape
import android.graphics.drawable.shapes.RoundRectShape
import android.graphics.drawable.shapes.Shape
import androidx.annotation.ColorInt
import androidx.annotation.IntDef
class TextDrawable(
// The Shape the drawable should take
@DrawableShape val shape: Int = TextDrawable.DRAWABLE_SHAPE_RECT,
// The solid fill color of the drawable
@ColorInt var color: Int = Color.GRAY,
// The color of the text for the drawable. Will be ignored if an icon is set
@ColorInt var textColor: Int = Color.WHITE,
// The corner radius for the drawable. Will be ignored if the shape is not a DRAWABLE_SHAPE_ROUND_RECT
var cornerRadius: Float = 0F,
// The text size for the text of the drawable. Will be ignored if an icon is set
var textSize: Float = 0f,
// The desired height of the drawable
var desiredHeight: Int = -1,
// The desired width of the drawable
var desiredWidth: Int = -1,
// The border thickness of the drawable
var borderThickness: Float = 0F,
// The color of the border. Will be ignored if borderThickness is <= 0
@ColorInt var borderColor: Int = color,
// The typeface to use for the text of the drawable. Will be ignored if an icon is set
var typeFace: Typeface = Typeface.DEFAULT,
// The text to use for the drawable. Will be ignored if an icon is set
var text: String? = null,
// The icon to use for the drawable. Will override any text that may have been set
var icon: Bitmap? = null) : ShapeDrawable(getShapeDrawable(shape, cornerRadius)) {
companion object {
private const val SHADE_FACTOR = 0.9f
const val DRAWABLE_SHAPE_RECT = 0
const val DRAWABLE_SHAPE_ROUND_RECT = 1
const val DRAWABLE_SHAPE_OVAL = 2
private fun getShapeDrawable(@DrawableShape shape: Int, cornerRadius: Float): Shape {
return when (shape) {
DRAWABLE_SHAPE_ROUND_RECT -> {
val radii = floatArrayOf(cornerRadius, cornerRadius, cornerRadius, cornerRadius, cornerRadius, cornerRadius, cornerRadius, cornerRadius)
RoundRectShape(radii, null, null)
}
DRAWABLE_SHAPE_OVAL -> OvalShape()
else -> RectShape()
}
}
}
@Retention(AnnotationRetention.SOURCE)
@IntDef(DRAWABLE_SHAPE_RECT, DRAWABLE_SHAPE_ROUND_RECT, DRAWABLE_SHAPE_OVAL)
annotation class DrawableShape
private val textPaint = Paint(Paint.ANTI_ALIAS_FLAG)
private val innerPaint = Paint()
init {
// text paint settings
text?.takeIf { !it.isBlank() }?.apply {
textPaint.color = textColor
textPaint.style = Paint.Style.FILL
textPaint.typeface = typeFace
textPaint.textAlign = Paint.Align.CENTER
textPaint.strokeWidth = borderThickness
}
if (borderThickness > 0F) {
// draw shape as color of border
// then fill shape inset by border with the normal color
paint.color = getColorForBorder()
innerPaint.style = Paint.Style.FILL
innerPaint.strokeWidth = borderThickness
innerPaint.color = color
} else {
paint.color = color
}
}
override fun onDraw(shape: Shape, canvas: Canvas, paint: Paint) {
super.onDraw(shape, canvas, paint)
val r = bounds
// draw border
if (borderThickness > 0F) {
drawInnerShape(canvas)
}
val count = canvas.save()
if (icon == null) {
canvas.translate(r.left.toFloat(), r.top.toFloat())
}
// draw text
val width = if (desiredWidth <= 0) r.width() else desiredWidth
val height = if (desiredHeight <= 0) r.height() else desiredHeight
val fontSize = if (textSize <= 0) (Math.min(width, height) / 2).toFloat() else textSize
icon?.let {
canvas.drawBitmap(it, ((width - it.width) / 2).toFloat(), ((height - it.height) / 2).toFloat(), null)
}
text?.takeIf { !it.isBlank() }?.apply {
textPaint.textSize = fontSize
canvas.drawText(this, (width / 2).toFloat(), height / 2 - (textPaint.descent() + textPaint.ascent()) / 2, textPaint)
}
canvas.restoreToCount(count)
}
override fun setAlpha(alpha: Int) {
textPaint.alpha = alpha
}
override fun setColorFilter(cf: ColorFilter?) {
textPaint.colorFilter = cf
}
override fun getOpacity(): Int {
return PixelFormat.TRANSLUCENT
}
override fun getIntrinsicWidth(): Int {
return desiredWidth
}
override fun getIntrinsicHeight(): Int {
return desiredHeight
}
/**
* Converts the [TextDrawable] to a [Bitmap]
*
* @return
*/
fun toBitmap(): Bitmap {
val bitmap = Bitmap.createBitmap(intrinsicWidth, intrinsicHeight, Bitmap.Config.ARGB_8888)
val canvas = Canvas(bitmap)
setBounds(0, 0, canvas.width, canvas.height)
draw(canvas)
return bitmap
}
private fun drawInnerShape(canvas: Canvas) {
val rect = RectF(bounds)
val inset = borderThickness
rect.inset(inset, inset)
when (shape) {
DRAWABLE_SHAPE_ROUND_RECT -> {
val roundRectCornerRadius = cornerRadius - inset
canvas.drawRoundRect(rect, roundRectCornerRadius, roundRectCornerRadius, innerPaint)
}
DRAWABLE_SHAPE_OVAL -> canvas.drawOval(rect, innerPaint)
else -> canvas.drawRect(rect, innerPaint)
}
}
private fun getColorForBorder(): Int {
return when (borderColor) {
color -> {
Color.rgb((SHADE_FACTOR * Color.red(color)).toInt(),
(SHADE_FACTOR * Color.green(color)).toInt(),
(SHADE_FACTOR * Color.blue(color)).toInt())
}
else -> borderColor
}
}
} | mit | 1638f183be4ed0fc5c40b677ab148bf6 | 32.585106 | 156 | 0.608427 | 4.707681 | false | false | false | false |
HerbLuo/shop-api | src/main/java/cn/cloudself/model/DeliverEntity.kt | 1 | 746 | package cn.cloudself.model
import org.hibernate.annotations.DynamicInsert
import javax.persistence.*
/**
* @author HerbLuo
* @version 1.0.0.d
*/
@Entity
@DynamicInsert
@Table(name = "deliver", schema = "shop")
data class DeliverEntity(
@get:Id
@get:Column(name = "id", nullable = false)
@get:GeneratedValue(strategy = GenerationType.IDENTITY)
var id: Int = 0,
@get:Basic
@get:Column(name = "number", nullable = true, length = 64)
var number: String? = null,
@get:Basic
@get:Column(name = "name", nullable = true, length = 10)
var name: String? = null,
@get:Basic
@get:Column(name = "order_a_shop_id")
var orderAShopId: Int? = null
)
| mit | 5f491413da46daaae8c63bc013c3076f | 23.064516 | 66 | 0.603217 | 3.469767 | false | false | false | false |
danfma/kodando | kodando-react-router-dom/src/main/kotlin/kodando/react/router/dom/Prompt.kt | 1 | 715 | package kodando.react.router.dom
import kodando.react.Configurer
import kodando.react.ReactProps
import kodando.react.addComponent
import kodando.react.createProps
/**
* Created by danfma on 04/04/17.
*/
private inline fun ReactProps.prompt(configurer: Configurer<PromptProps>) {
addComponent(Module.PromptClass, createProps(configurer))
}
@JsName("promptWithText")
fun ReactProps.prompt(message: String, matched: Boolean = false) {
prompt {
this.messageText = message
this.matched = matched
}
}
@JsName("promptWithFunc")
fun ReactProps.prompt(messageFactory: (Location) -> String, matched: Boolean = false) {
prompt {
this.messageFunc = messageFactory
this.matched = matched
}
}
| mit | a82542558bf9d7bdba7018fa2af547a4 | 21.34375 | 87 | 0.748252 | 3.783069 | false | true | false | false |
rock3r/detekt | detekt-rules/src/test/resources/cases/ComplexMethods.kt | 1 | 1126 | @file:Suppress("unused")
package cases
// reports 1 - only if ignoreSingleWhenExpression = false
fun complexMethodWithSingleWhen1(i: Int) =
when (i) {
1 -> print("one")
2 -> print("two")
3 -> print("three")
else -> print(i)
}
// reports 1 - only if ignoreSingleWhenExpression = false
fun complexMethodWithSingleWhen2(i: Int) {
when (i) {
1 -> print("one")
2 -> print("two")
3 -> print("three")
else -> print(i)
}
}
// reports 1 - only if ignoreSingleWhenExpression = false
fun complexMethodWithSingleWhen3(i: Int): String {
return when (i) {
1 -> "one"
2 -> "two"
3 -> "three"
else -> ""
}
}
// reports 1 - only if ignoreSingleWhenExpression = false
fun complexMethodWithSingleWhen4(i: Int) = when (i) {
1 -> "one"
2 -> "two"
3 -> "three"
else -> ""
}
// reports 1
fun complexMethodWith2Statements(i: Int) {
when (i) {
1 -> print("one")
2 -> print("two")
3 -> print("three")
else -> print(i)
}
if (i == 1) {
}
}
| apache-2.0 | e2c120d2f10284f56d811635233255f0 | 20.653846 | 57 | 0.521314 | 3.597444 | false | false | false | false |
matkoniecz/StreetComplete | app/src/main/java/de/westnordost/streetcomplete/location/FineLocationManager.kt | 1 | 4308 | package de.westnordost.streetcomplete.location
import android.Manifest.permission.ACCESS_FINE_LOCATION
import android.location.Location
import android.location.LocationManager
import android.location.LocationManager.GPS_PROVIDER
import android.location.LocationManager.NETWORK_PROVIDER
import android.os.Looper
import androidx.annotation.RequiresPermission
/** Convenience wrapper around the location manager with easier API, making use of both the GPS
* and Network provider */
class FineLocationManager(private val mgr: LocationManager, private var locationUpdateCallback: ((Location) -> Unit)) {
private var lastLocation: Location? = null
private val deviceHasGPS: Boolean get() = mgr.allProviders.contains(GPS_PROVIDER)
private val deviceHasNetworkLocationProvider: Boolean get() = mgr.allProviders.contains(NETWORK_PROVIDER)
private val locationListener = object : LocationUpdateListener {
override fun onLocationChanged(location: Location) {
if (isBetterLocation(location, lastLocation)) {
lastLocation = location
locationUpdateCallback(location)
}
}
}
private val singleLocationListener = object : LocationUpdateListener {
override fun onLocationChanged(location: Location) {
mgr.removeUpdates(this)
locationUpdateCallback(location)
}
}
@RequiresPermission(ACCESS_FINE_LOCATION)
fun requestUpdates(minTime: Long, minDistance: Float) {
if (deviceHasGPS)
mgr.requestLocationUpdates(GPS_PROVIDER, minTime, minDistance, locationListener, Looper.getMainLooper())
if (deviceHasNetworkLocationProvider)
mgr.requestLocationUpdates(NETWORK_PROVIDER, minTime, minDistance, locationListener, Looper.getMainLooper())
}
@RequiresPermission(ACCESS_FINE_LOCATION)
fun requestSingleUpdate() {
if (deviceHasGPS)
mgr.requestSingleUpdate(GPS_PROVIDER, singleLocationListener, Looper.getMainLooper())
if (deviceHasNetworkLocationProvider)
mgr.requestSingleUpdate(NETWORK_PROVIDER, singleLocationListener, Looper.getMainLooper())
}
fun removeUpdates() {
mgr.removeUpdates(locationListener)
mgr.removeUpdates(singleLocationListener)
}
}
// taken from https://developer.android.com/guide/topics/location/strategies.html#kotlin
private const val TWO_MINUTES = 1000L * 60 * 2
/** Determines whether one Location reading is better than the current Location fix
* @param location The new Location that you want to evaluate
* @param currentBestLocation The current Location fix, to which you want to compare the new one
*/
private fun isBetterLocation(location: Location, currentBestLocation: Location?): Boolean {
// check whether this is a valid location at all. Happened once that lat/lon is NaN, maybe issue
// of that particular device
if (location.longitude.isNaN() || location.latitude.isNaN()) return false
if (currentBestLocation == null) {
// A new location is always better than no location
return true
}
// Check whether the new location fix is newer or older
val timeDelta = location.time - currentBestLocation.time
val isSignificantlyNewer = timeDelta > TWO_MINUTES
val isSignificantlyOlder = timeDelta < -TWO_MINUTES
val isNewer = timeDelta > 0L
// Check whether the new location fix is more or less accurate
val accuracyDelta = location.accuracy - currentBestLocation.accuracy
val isLessAccurate = accuracyDelta > 0f
val isMoreAccurate = accuracyDelta < 0f
val isSignificantlyLessAccurate = accuracyDelta > 200f
// Check if the old and new location are from the same provider
val isFromSameProvider = location.provider == currentBestLocation.provider
// Determine location quality using a combination of timeliness and accuracy
return when {
// the user has likely moved
isSignificantlyNewer -> return true
// If the new location is more than two minutes older, it must be worse
isSignificantlyOlder -> return false
isMoreAccurate -> true
isNewer && !isLessAccurate -> true
isNewer && !isSignificantlyLessAccurate && isFromSameProvider -> true
else -> false
}
}
| gpl-3.0 | fc1946817ee58a14bad23942826d9b1f | 41.235294 | 120 | 0.72818 | 5.190361 | false | false | false | false |
aleksey-zhidkov/jeb-k | src/main/kotlin/jeb/Storage.kt | 1 | 4946 | package jeb
import java.io.File
import java.nio.file.Path
import java.nio.file.Paths
import java.util.*
open class Storage {
private val log = jeb.log
open fun lastModified(dir: File, predicate: (File) -> Boolean) = dir.
listFiles().
filter { predicate(it) }.
maxBy { it.lastModified() }
open fun fileExists(dir: File, predicate: (File) -> Boolean) = dir.
listFiles().
filter(predicate).
any()
open fun fileExists(file: File) = file.exists()
open fun remove(f: File) = f.deleteRecursively()
open fun fullBackup(from: List<Source>, excludeFile: Path?, to: File) =
rsync(from, excludeFile, null, to)
open fun incBackup(from: List<Source>, excludeFile: Path?, base: File, to: File) =
rsync(from, excludeFile, base, to)
private fun rsync(sources: List<Source>, excludeFile: Path?, base: File?, dest: File) =
try {
// when single file is passed as source to rsync, then it's interprets
// destination as full file name and do not create parent directory
// but when sources is more than one or it's a directory, then it's
// interprets destination as parent directory and creates it
val (from, to) =
if (sources.size > 1 || sources.first().path.toFile().isDirectory) {
Pair(sources.map { toRsync(it) }.joinToString(" "),
dest.absolutePath)
} else {
dest.absoluteFile.mkdirs()
Pair(sources.first().absolutePath,
Paths.get(dest.absolutePath, sources.first().path.fileName.toString()))
}
!"rsync -avh ${excludeFile?.let { "--exclude-from=" + it} ?: ""} --delete ${base?.let { "--link-dest=" + it.absolutePath } ?: ""} $from $to"
} catch (e: JebExecException) {
if (e.stderr.contains("vanished") && e.stderr.contains("/.sync/status")) {
// it's workaround for case, when service's status file has been changed, while syncing
// it's harmless and in this case follow output printed:
// file has vanished: "/data/yandex-disk/.sync/status"
// rsync warning: some files vanished before they could be transferred (code 24) at main.c(1183) [sender=3.1.0]
// Do nothing in this case
log.warn("Rsync error ignored")
log.warn(e.toString())
} else {
throw e
}
}
open fun move(from: File, to: File) {
!"mv ${from.absolutePath} ${to.absolutePath}"
Thread.sleep(1000) // Dirty hack for functional test...
to.setLastModified(System.currentTimeMillis())
}
open fun findOne(dir: File, predicate: (File) -> Boolean): File? {
val res = dir.
listFiles().
filter(predicate)
assert(res.size <= 1, { "To many files matches predicate: $res"})
return res.firstOrNull()
}
private fun toRsync(src: Source) = src.path.toString() + (if (src.type == BackupType.DIRECTORY) "/" else "")
private operator fun String.not() {
log.debug("Executing command: $this")
val proc = Runtime.getRuntime().exec(this)
val stdoutLines = LinkedList<String>()
val stderrLines = LinkedList<String>()
proc.inputStream.bufferedReader().lines().forEach(handleStdOutputLine(stdoutLines, OutputType.STDOUT))
proc.errorStream.bufferedReader().lines().forEach(handleStdOutputLine(stderrLines, OutputType.STDERR))
val returnCode = proc.waitFor()
log.debug("""
returnCode=$returnCode
stdout:
======
${stdoutLines.joinToString("\n")}
======
stderr:
======
${stderrLines.joinToString("\n")}
======
""".trimIndent())
if (returnCode != 0 || stderrLines.isNotEmpty()) {
throw JebExecException(
cmd = this,
stdout = stdoutLines.joinToString("\n"),
stderr = stderrLines.joinToString("\n"),
returnCode = returnCode)
}
}
private fun handleStdOutputLine(buffer: LinkedList<String>, type: OutputType): (String) -> Unit = {
val msg = "[$type]: $it"
when (type) {
OutputType.STDOUT -> log.debug(msg)
OutputType.STDERR -> log.error(msg)
else -> throw AssertionError("Unknown type: $type")
}
buffer.add(it)
if (buffer.size > 1000) {
buffer.removeFirst()
}
}
private enum class OutputType{ STDOUT, STDERR }
}
| apache-2.0 | 000a77d50aec28f8fa0477ffaedbc3d6 | 38.887097 | 156 | 0.539224 | 4.65725 | false | false | false | false |
cooltee/vehicles | vehicles_service/src/main/java/com/cooltee/service/impl/SessionServiceImpl.kt | 1 | 1338 | package com.cooltee.service.impl
import com.cooltee.redis.RedisClient
import com.cooltee.service.interfaces.SessionService
import com.cooltee.session.SessionInfo
import com.cooltee.util.Utils
import org.springframework.stereotype.Service
/**
* The Implements of Session Service
* Created by Daniel on 2017/5/16.
*/
@Service
class SessionServiceImpl : SessionService {
private val cache: ThreadLocal<SessionInfo> = ThreadLocal()
override fun getSessionInfo(): SessionInfo? {
return cache.get()
}
override fun checkSigned(sessionId: String): Boolean {
var sessionInfo = RedisClient.get(sessionId) as SessionInfo?
if (sessionInfo == null) {
sessionInfo = SessionInfo(Utils.generateUUID(), null, null)
}
val flag = sessionId == sessionInfo.sid
if (flag) {
cache.set(sessionInfo)
}
return flag
}
override fun destroyCache() {
cache.remove()
}
override fun refreshEffective(sessionId: String) {
RedisClient.expire(sessionId, 1800)
}
override fun save(sessionInfo: SessionInfo) {
cache.set(sessionInfo)
RedisClient.setex(sessionInfo.sid, 1800, sessionInfo)
}
override fun delete(sessionId: String) {
RedisClient.del(sessionId)
destroyCache()
}
} | mit | a1672d335bdfd97ed16ab937728a6ecd | 25.254902 | 71 | 0.671898 | 4.582192 | false | false | false | false |
BrianLusina/MovieReel | app/src/main/kotlin/com/moviereel/data/db/entities/movie/MovieLatestEntity.kt | 1 | 2112 | package com.moviereel.data.db.entities.movie
import android.arch.persistence.room.ColumnInfo
import android.arch.persistence.room.Entity
import android.arch.persistence.room.Ignore
import com.google.gson.annotations.Expose
import com.google.gson.annotations.SerializedName
import com.moviereel.data.db.entities.*
/**
* @author lusinabrian on 15/05/17.
* *
* @Notes Data entry for the latest movie
*/
// @Entity(tableName = "movie_latest")
data class MovieLatestEntity(
@Expose
//@ColumnInfo(name = "belongs_to_collection")
var belongsToCollection: String? = null,
@Expose
//@ColumnInfo(name = "budget")
var budget: Int = 0,
@Expose
//@ColumnInfo(name = "genres")
//@Ignore
var genres: ArrayList<GenreEntity>,
@Expose
@SerializedName("homepage")
//@ColumnInfo(name = "homepage")
var homepage: String,
@Expose
@SerializedName("imdb_id")
//@ColumnInfo(name = "imdb_id")
var imdbId: String,
@Expose
@SerializedName("production_companies")
//@ColumnInfo(name = "production_companies")
//@Ignore
var productionCompanies: ArrayList<ProductionCompany>,
@Expose
@SerializedName("production_countries")
//@ColumnInfo(name = "production_countries")
//@Ignore
var productionCountry: ArrayList<ProductionCountry>,
@Expose
@SerializedName("revenue")
//@ColumnInfo(name = "revenue")
var revenue: Int,
@Expose
@SerializedName("runtime")
//@ColumnInfo(name = "runtime")
var runtime: Int,
@Expose
@SerializedName("spoken_languages")
//@ColumnInfo(name = "spoken_languages")
//@Ignore
var spokenLanguage: ArrayList<SpokenLanguage>,
@Expose
@SerializedName("status")
//@ColumnInfo(name = "status")
var status: String,
@Expose
@SerializedName("tagline")
//@ColumnInfo(name = "tagline")
var tagline: String
) : BaseEntity()
| mit | 4efac8adcc4306b044503d5e532639f5 | 26.076923 | 62 | 0.611742 | 4.541935 | false | false | false | false |
wordpress-mobile/WordPress-Stores-Android | plugins/woocommerce/src/main/kotlin/org/wordpress/android/fluxc/model/user/WCUserMapper.kt | 2 | 677 | package org.wordpress.android.fluxc.model.user
import org.wordpress.android.fluxc.model.SiteModel
import org.wordpress.android.fluxc.network.rest.wpcom.wc.user.WCUserRestClient.UserApiResponse
import javax.inject.Inject
class WCUserMapper
@Inject constructor() {
fun map(user: UserApiResponse, siteModel: SiteModel): WCUserModel {
return WCUserModel().apply {
remoteUserId = user.id
username = user.username ?: ""
firstName = user.firstName ?: ""
lastName = user.lastName ?: ""
email = user.email ?: ""
roles = user.roles.toString()
localSiteId = siteModel.id
}
}
}
| gpl-2.0 | 672fd06c8434095f0a35602be3f6dfa9 | 31.238095 | 94 | 0.646972 | 4.367742 | false | false | false | false |
ccomeaux/boardgamegeek4android | app/src/main/java/com/boardgamegeek/ui/dialog/EditUsernameDialogFragment.kt | 1 | 1973 | package com.boardgamegeek.ui.dialog
import android.app.Dialog
import android.os.Bundle
import android.text.InputType
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.appcompat.app.AlertDialog
import androidx.fragment.app.DialogFragment
import androidx.fragment.app.activityViewModels
import com.boardgamegeek.R
import com.boardgamegeek.databinding.DialogEditTextBinding
import com.boardgamegeek.extensions.requestFocus
import com.boardgamegeek.ui.viewmodel.BuddyViewModel
class EditUsernameDialogFragment : DialogFragment() {
private var _binding: DialogEditTextBinding? = null
private val binding get() = _binding!!
private val viewModel by activityViewModels<BuddyViewModel>()
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
_binding = DialogEditTextBinding.inflate(layoutInflater)
val builder = AlertDialog.Builder(requireContext(), R.style.Theme_bgglight_Dialog_Alert)
.setTitle(R.string.title_add_username)
.setView(binding.root)
.setNegativeButton(R.string.cancel, null)
.setPositiveButton(R.string.ok) { _, _ ->
val text = binding.editText.text?.toString()
viewModel.addUsernameToPlayer(text?.trim() ?: "")
}
return builder.create().apply {
requestFocus(binding.editText)
}
}
@Suppress("RedundantNullableReturnType")
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
binding.editText.inputType = binding.editText.inputType or InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS
binding.editTextContainer.hint = getString(R.string.username)
}
override fun onDestroyView() {
super.onDestroyView()
_binding = null
}
}
| gpl-3.0 | 23c68a2ae544b5963226efe1280e278b | 36.226415 | 116 | 0.722757 | 4.788835 | false | false | false | false |
wordpress-mobile/WordPress-Stores-Android | example/src/test/java/org/wordpress/android/fluxc/store/GetDeviceRegistrationStatusTest.kt | 1 | 1870 | package org.wordpress.android.fluxc.store
import android.content.SharedPreferences
import com.nhaarman.mockitokotlin2.doReturn
import com.nhaarman.mockitokotlin2.mock
import com.nhaarman.mockitokotlin2.whenever
import org.junit.Assert.assertEquals
import org.junit.Test
import org.junit.runner.RunWith
import org.mockito.junit.MockitoJUnitRunner
import org.wordpress.android.fluxc.store.NotificationStore.Companion.WPCOM_PUSH_DEVICE_SERVER_ID
import org.wordpress.android.fluxc.utils.PreferenceUtils
@RunWith(MockitoJUnitRunner::class)
class GetDeviceRegistrationStatusTest {
private val preferences: SharedPreferences = mock()
private val preferencesWrapper: PreferenceUtils.PreferenceUtilsWrapper = mock {
on { getFluxCPreferences() } doReturn preferences
}
private val sut = GetDeviceRegistrationStatus(preferencesWrapper)
@Test
fun `when device id is not empty, return registered status`() {
// given
whenever(preferences.getString(WPCOM_PUSH_DEVICE_SERVER_ID, null)).doReturn("not-empty-id")
// when
val result = sut.invoke()
// then
assertEquals(GetDeviceRegistrationStatus.Status.REGISTERED, result)
}
@Test
fun `when device id is empty, return unregistered status`() {
// given
whenever(preferences.getString(WPCOM_PUSH_DEVICE_SERVER_ID, null)).doReturn("")
// when
val result = sut.invoke()
// then
assertEquals(GetDeviceRegistrationStatus.Status.UNREGISTERED, result)
}
@Test
fun `when device id is null, return unregistered status`() {
// given
whenever(preferences.getString(WPCOM_PUSH_DEVICE_SERVER_ID, null)).doReturn(null)
// when
val result = sut.invoke()
// then
assertEquals(GetDeviceRegistrationStatus.Status.UNREGISTERED, result)
}
}
| gpl-2.0 | 4154f22b4fbc6859ecf01f41d0dba7d7 | 31.241379 | 99 | 0.718717 | 4.675 | false | true | false | false |
jcam3ron/cassandra-migration | src/main/java/com/builtamont/cassandra/migration/internal/dbsupport/Delimiter.kt | 1 | 2157 | /**
* File : Delimiter.kt
* License :
* Original - Copyright (c) 2010 - 2016 Boxfuse GmbH
* Derivative - Copyright (c) 2016 Citadel Technology Solutions Pte Ltd
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.builtamont.cassandra.migration.internal.dbsupport
/**
* Represents a CQL statement delimiter.
*
* @param delimiter The actual delimiter string.
* @param isAloneOnLine Whether the delimiter sits alone on a new line or not.
*/
class Delimiter(val delimiter: String, val isAloneOnLine: Boolean) {
/**
* @return The computed delimiter instance hash value.
*/
override fun hashCode(): Int {
var result = delimiter.hashCode()
result = 31 * result + if (isAloneOnLine) 1 else 0
return result
}
/**
* @return {@code true} if this delimiter instance is the same as the given object.
*/
override fun equals(other: Any?): Boolean {
/**
* @return {@code true} if this version instance is not the same as the given object.
*/
fun isNotSame(): Boolean {
return other == null || javaClass != other.javaClass
}
/**
* @return {@code true} if delimiter is alone on line.
*/
fun isDelimiterAloneOnLine(): Boolean {
val delimiter1 = other as Delimiter?
return isAloneOnLine == delimiter1!!.isAloneOnLine && delimiter == delimiter1.delimiter
}
return when {
this === other -> true
isNotSame() -> false
else -> isDelimiterAloneOnLine()
}
}
}
| apache-2.0 | 24eec43c22122c03b945aef94ea9e799 | 32.184615 | 99 | 0.628651 | 4.503132 | false | false | false | false |
world-federation-of-advertisers/cross-media-measurement | src/main/kotlin/org/wfanet/measurement/kingdom/deploy/gcloud/spanner/writers/CreateAccount.kt | 1 | 3941 | // Copyright 2021 The Cross-Media Measurement 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.wfanet.measurement.kingdom.deploy.gcloud.spanner.writers
import com.google.cloud.spanner.Value
import org.wfanet.measurement.common.identity.ExternalId
import org.wfanet.measurement.gcloud.spanner.bufferInsertMutation
import org.wfanet.measurement.gcloud.spanner.set
import org.wfanet.measurement.internal.kingdom.Account
import org.wfanet.measurement.internal.kingdom.account
import org.wfanet.measurement.kingdom.deploy.gcloud.spanner.common.AccountNotFoundException
import org.wfanet.measurement.kingdom.deploy.gcloud.spanner.common.KingdomInternalException
import org.wfanet.measurement.kingdom.deploy.gcloud.spanner.common.PermissionDeniedException
import org.wfanet.measurement.kingdom.deploy.gcloud.spanner.readers.AccountReader
import org.wfanet.measurement.kingdom.deploy.gcloud.spanner.readers.MeasurementConsumerOwnerReader
/**
* Creates an account in the database.
*
* Throws a subclass of [KingdomInternalException] on [execute].
* @throws [PermissionDeniedException] Permission denied due to ownership of MeasurementConsumer
* @throws [AccountNotFoundException] Creator's Account not found
*/
class CreateAccount(
private val externalCreatorAccountId: ExternalId?,
private val externalOwnedMeasurementConsumerId: ExternalId?
) : SimpleSpannerWriter<Account>() {
override suspend fun TransactionScope.runTransaction(): Account {
val internalAccountId = idGenerator.generateInternalId()
val externalAccountId = idGenerator.generateExternalId()
val activationToken = idGenerator.generateExternalId()
val source = this@CreateAccount
return account {
transactionContext.bufferInsertMutation("Accounts") {
if (source.externalCreatorAccountId != null) {
val readCreatorAccountResult = readAccount(source.externalCreatorAccountId)
set("CreatorAccountId" to readCreatorAccountResult.accountId)
externalCreatorAccountId = source.externalCreatorAccountId.value
if (source.externalOwnedMeasurementConsumerId != null) {
MeasurementConsumerOwnerReader()
.checkOwnershipExist(
transactionContext,
readCreatorAccountResult.accountId,
source.externalOwnedMeasurementConsumerId
)
?.let {
externalOwnedMeasurementConsumerId = source.externalOwnedMeasurementConsumerId.value
set("OwnedMeasurementConsumerId" to it.measurementConsumerId)
}
?: throw PermissionDeniedException()
}
}
set("AccountId" to internalAccountId)
set("ExternalAccountId" to externalAccountId)
set("ActivationState" to Account.ActivationState.UNACTIVATED)
set("ActivationToken" to activationToken)
set("CreateTime" to Value.COMMIT_TIMESTAMP)
set("UpdateTime" to Value.COMMIT_TIMESTAMP)
}
this.externalAccountId = externalAccountId.value
activationState = Account.ActivationState.UNACTIVATED
this.activationToken = activationToken.value
}
}
private suspend fun TransactionScope.readAccount(
externalAccountId: ExternalId
): AccountReader.Result =
AccountReader().readByExternalAccountId(transactionContext, externalAccountId)
?: throw AccountNotFoundException(externalAccountId)
}
| apache-2.0 | 85b3715b7c26e00b61de70f3d38c09d5 | 43.280899 | 100 | 0.756661 | 5.199208 | false | false | false | false |
debop/debop4k | debop4k-timeperiod/src/main/kotlin/debop4k/timeperiod/models/Quarter.kt | 1 | 1853 | /*
* Copyright (c) 2016. Sunghyouk Bae <[email protected]>
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package debop4k.timeperiod.models
import debop4k.timeperiod.*
/**
* 분기를 표현
* @author debop [email protected]
*/
enum class Quarter(val value: Int) {
/** 1/4 분기 */
FIRST(1),
/** 2/4 분기 */
SECOND(2),
/** 3/4 분기 */
THIRD(3),
/** 4/4 분기 */
FOURTH(4);
operator fun plus(delta: Int): Quarter {
val amount = delta % QuartersPerYear
return quarterArray[(ordinal + (amount + 4)) % 4]
}
operator fun minus(delta: Int): Quarter = plus(-(delta % 12))
val months: IntArray get() = when (this) {
FIRST -> FirstQuarterMonths
SECOND -> SecondQuarterMonths
THIRD -> ThirdQuarterMonths
FOURTH -> FourthQuarterMonths
}
val startMonth: Int get() = this.ordinal * MonthsPerQuarter + 1
val endMonth: Int get() = this.value * MonthsPerQuarter
companion object {
val quarterArray: Array<Quarter> = Quarter.values()
@JvmStatic
fun of(q: Int): Quarter {
if (q < 1 || q > 4)
throw IllegalArgumentException("Invalid q for Quarter. 1..4")
return quarterArray[q - 1]
}
@JvmStatic
fun ofMonth(monthOfYear: Int): Quarter {
return quarterArray[(monthOfYear - 1) / MonthsPerQuarter]
}
}
} | apache-2.0 | 1ca6cad14d964f43cf201167e29fc94e | 23.373333 | 75 | 0.661193 | 3.736196 | false | false | false | false |
ziggy42/Blum | app/src/main/java/com/andreapivetta/blu/data/model/PrivateMessage.kt | 1 | 2801 | package com.andreapivetta.blu.data.model
import io.realm.RealmObject
import io.realm.annotations.Index
import io.realm.annotations.PrimaryKey
import twitter4j.DirectMessage
import java.io.Serializable
open class PrivateMessage(
@PrimaryKey open var id: Long = 0,
open var senderId: Long = 0,
open var recipientId: Long = 0,
@Index open var otherId: Long = 0,
open var timeStamp: Long = System.currentTimeMillis(),
open var text: String = "",
open var otherUserName: String = "",
open var otherUserProfilePicUrl: String = "",
open var isRead: Boolean = false) :
RealmObject(), Comparable<PrivateMessage>, Serializable {
companion object {
val NEW_PRIVATE_MESSAGE_INTENT =
"com.andreapivetta.blu.data.model.NEW_PRIVATE_MESSAGE_INTENT"
fun valueOf(directMessage: DirectMessage, userId: Long, inverted: Boolean = false):
PrivateMessage {
if (inverted)
return getInverted(directMessage, userId)
val otherUserId = if (directMessage.recipientId == userId)
directMessage.senderId else directMessage.recipientId
val otherUsername = if (userId == directMessage.senderId)
directMessage.recipientScreenName else directMessage.senderScreenName
val otherUserProfilePicUrl: String = if (userId == directMessage.senderId)
directMessage.recipient.biggerProfileImageURL else
directMessage.sender.biggerProfileImageURL
return PrivateMessage(directMessage.id, directMessage.senderId,
directMessage.recipientId, otherUserId, directMessage.createdAt.time,
directMessage.text, otherUsername, otherUserProfilePicUrl, false)
}
private fun getInverted(directMessage: DirectMessage, userId: Long): PrivateMessage {
val otherUserId = if (directMessage.recipientId != userId)
directMessage.senderId else directMessage.recipientId
val otherUsername = if (userId != directMessage.senderId)
directMessage.recipientScreenName else directMessage.senderScreenName
val otherUserProfilePicUrl: String = if (userId != directMessage.senderId)
directMessage.recipient.biggerProfileImageURL else
directMessage.sender.biggerProfileImageURL
return PrivateMessage(directMessage.id, directMessage.senderId,
directMessage.recipientId, otherUserId, directMessage.createdAt.time,
directMessage.text, otherUsername, otherUserProfilePicUrl, false)
}
}
override fun compareTo(other: PrivateMessage) = (other.timeStamp - this.timeStamp).toInt()
} | apache-2.0 | f8664692799481d16d694c4d7f314cde | 44.934426 | 94 | 0.67583 | 5.647177 | false | false | false | false |
FHannes/intellij-community | platform/diff-impl/tests/com/intellij/diff/util/DiffUtilTest.kt | 9 | 5362 | /*
* Copyright 2000-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* Copyright 2000-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.diff.util
import com.intellij.diff.DiffRequestFactoryImpl
import com.intellij.diff.DiffTestCase
import com.intellij.openapi.diff.DiffBundle
import com.intellij.util.containers.ContainerUtil
import java.io.File
class DiffUtilTest : DiffTestCase() {
fun `test getSortedIndexes`() {
fun <T> doTest(vararg values: T, comparator: (T, T) -> Int) {
val list = values.toList()
val sortedIndexes = DiffUtil.getSortedIndexes(list, comparator)
val expected = ContainerUtil.sorted(list, comparator)
val actual = (0..values.size - 1).map { values[sortedIndexes[it]] }
assertOrderedEquals(expected, actual)
assertEquals(sortedIndexes.toSet().size, list.size)
}
doTest(1, 2, 3, 4, 5, 6, 7, 8) { v1, v2 -> v1 - v2 }
doTest(8, 7, 6, 5, 4, 3, 2, 1) { v1, v2 -> v1 - v2 }
doTest(1, 3, 5, 7, 8, 6, 4, 2) { v1, v2 -> v1 - v2 }
doTest(1, 2, 3, 4, 5, 6, 7, 8) { v1, v2 -> v2 - v1 }
doTest(8, 7, 6, 5, 4, 3, 2, 1) { v1, v2 -> v2 - v1 }
doTest(1, 3, 5, 7, 8, 6, 4, 2) { v1, v2 -> v2 - v1 }
}
fun `test merge conflict partially resolved confirmation message`() {
fun doTest(changes: Int, conflicts: Int, expected: String) {
val actual = DiffBundle.message("merge.dialog.apply.partially.resolved.changes.confirmation.message", changes, conflicts)
assertTrue(actual.startsWith(expected), actual)
}
doTest(1, 0, "There is one change left")
doTest(0, 1, "There is one conflict left")
doTest(1, 1, "There is one change and one conflict left")
doTest(2, 0, "There are 2 changes left")
doTest(0, 2, "There are 2 conflicts left")
doTest(2, 2, "There are 2 changes and 2 conflicts left")
doTest(1, 2, "There is one change and 2 conflicts left")
doTest(2, 1, "There are 2 changes and one conflict left")
doTest(2, 3, "There are 2 changes and 3 conflicts left")
}
fun `test diff content titles`() {
fun doTest(path: String, expected: String) {
val filePath = createFilePath(path)
val actual1 = DiffRequestFactoryImpl.getContentTitle(filePath)
val actual2 = DiffRequestFactoryImpl.getTitle(filePath, null, " <-> ")
val actual3 = DiffRequestFactoryImpl.getTitle(null, filePath, " <-> ")
val expectedNative = expected.replace('/', File.separatorChar)
assertEquals(expectedNative, actual1)
assertEquals(expectedNative, actual2)
assertEquals(expectedNative, actual3)
}
doTest("file.txt", "file.txt")
doTest("/path/to/file.txt", "file.txt (/path/to)")
doTest("/path/to/dir/", "/path/to/dir")
}
fun `test diff request titles`() {
fun doTest(path1: String, path2: String, expected: String) {
val filePath1 = createFilePath(path1)
val filePath2 = createFilePath(path2)
val actual = DiffRequestFactoryImpl.getTitle(filePath1, filePath2, " <-> ")
assertEquals(expected.replace('/', File.separatorChar), actual)
}
doTest("file1.txt", "file1.txt", "file1.txt")
doTest("/path/to/file1.txt", "/path/to/file1.txt", "file1.txt (/path/to)")
doTest("/path/to/dir1/", "/path/to/dir1/", "/path/to/dir1")
doTest("file1.txt", "file2.txt", "file1.txt <-> file2.txt")
doTest("/path/to/file1.txt", "/path/to/file2.txt", "file1.txt <-> file2.txt (/path/to)")
doTest("/path/to/dir1/", "/path/to/dir2/", "dir1 <-> dir2 (/path/to)")
doTest("/path/to/file1.txt", "/path/to_another/file1.txt", "file1.txt (/path/to <-> /path/to_another)")
doTest("/path/to/file1.txt", "/path/to_another/file2.txt", "file1.txt <-> file2.txt (/path/to <-> /path/to_another)")
doTest("/path/to/dir1/", "/path/to_another/dir2/", "dir1 <-> dir2 (/path/to <-> /path/to_another)")
doTest("file1.txt", "/path/to/file1.txt", "file1.txt <-> /path/to/file1.txt")
doTest("file1.txt", "/path/to/file2.txt", "file1.txt <-> /path/to/file2.txt")
doTest("/path/to/dir1/", "/path/to/file2.txt", "dir1/ <-> file2.txt (/path/to)")
doTest("/path/to/file1.txt", "/path/to/dir2/", "file1.txt <-> dir2/ (/path/to)")
doTest("/path/to/dir1/", "/path/to_another/file2.txt", "dir1/ <-> file2.txt (/path/to <-> /path/to_another)")
}
}
| apache-2.0 | cbe6978d41d48e6cd4208d4012ac91a9 | 40.565891 | 127 | 0.659642 | 3.33873 | false | true | false | false |
QuickBlox/quickblox-android-sdk | sample-pushnotifications-kotlin/app/src/main/java/com/quickblox/sample/pushnotifications/kotlin/App.kt | 1 | 3836 | package com.quickblox.sample.pushnotifications.kotlin
import android.app.Application
import android.util.Log
import com.google.android.gms.common.GoogleApiAvailability
import com.quickblox.auth.session.QBSession
import com.quickblox.auth.session.QBSessionManager
import com.quickblox.auth.session.QBSessionParameters
import com.quickblox.auth.session.QBSettings
import com.quickblox.messages.services.QBPushManager
import com.quickblox.sample.pushnotifications.kotlin.utils.ActivityLifecycle
import com.quickblox.sample.pushnotifications.kotlin.utils.shortToast
// app credentials
private const val APPLICATION_ID = ""
private const val AUTH_KEY = ""
private const val AUTH_SECRET = ""
private const val ACCOUNT_KEY = ""
// default user config
const val DEFAULT_USER_PASSWORD = "quickblox"
class App : Application() {
private val TAG = App::class.java.simpleName
companion object {
private lateinit var instance: App
fun getInstance(): App = instance
}
override fun onCreate() {
super.onCreate()
instance = this
registerActivityLifecycleCallbacks(ActivityLifecycle)
checkConfig()
initCredentials()
initQBSessionManager()
initPushManager()
}
private fun checkConfig() {
if (APPLICATION_ID.isEmpty() || AUTH_KEY.isEmpty() || AUTH_SECRET.isEmpty() || ACCOUNT_KEY.isEmpty()
|| DEFAULT_USER_PASSWORD.isEmpty()) {
throw AssertionError(getString(R.string.error_qb_credentials_empty))
}
}
private fun initCredentials() {
QBSettings.getInstance().init(applicationContext, APPLICATION_ID, AUTH_KEY, AUTH_SECRET)
QBSettings.getInstance().accountKey = ACCOUNT_KEY
// uncomment and put your Api and Chat servers endpoints if you want to point the sample
// against your own server.
//
// QBSettings.getInstance().setEndpoints("https://your_api_endpoint.com", "your_chat_endpoint", ServiceZone.PRODUCTION);
// QBSettings.getInstance().zone = ServiceZone.PRODUCTION
}
private fun initQBSessionManager() {
QBSessionManager.getInstance().addListener(object : QBSessionManager.QBSessionListener {
override fun onSessionCreated(qbSession: QBSession) {
Log.d(TAG, "Session Created")
}
override fun onSessionUpdated(qbSessionParameters: QBSessionParameters) {
Log.d(TAG, "Session Updated")
}
override fun onSessionDeleted() {
Log.d(TAG, "Session Deleted")
}
override fun onSessionRestored(qbSession: QBSession) {
Log.d(TAG, "Session Restored")
}
override fun onSessionExpired() {
Log.d(TAG, "Session Expired")
}
override fun onProviderSessionExpired(provider: String) {
Log.d(TAG, "Session Expired for provider: $provider")
}
})
}
private fun initPushManager() {
QBPushManager.getInstance().addListener(object : QBPushManager.QBSubscribeListener {
override fun onSubscriptionCreated() {
shortToast("Subscription Created")
Log.d(TAG, "SubscriptionCreated")
}
override fun onSubscriptionError(e: Exception, resultCode: Int) {
Log.d(TAG, "SubscriptionError" + e.localizedMessage)
if (resultCode >= 0) {
val error = GoogleApiAvailability.getInstance().getErrorString(resultCode)
Log.d(TAG, "SubscriptionError playServicesAbility: $error")
}
shortToast(e.localizedMessage)
}
override fun onSubscriptionDeleted(success: Boolean) {
}
})
}
} | bsd-3-clause | 866152a75a0204aabfc77c3230d6f005 | 34.201835 | 128 | 0.644682 | 4.936937 | false | false | false | false |
danwime/eazyajax | core/src/me/danwi/ezajax/container/Scanner.kt | 1 | 1404 | package me.danwi.ezajax.container
import org.apache.commons.io.FileUtils
import java.io.File
import java.util.jar.JarFile
/**
* 扫描
* Created by demon on 2017/2/13.
*/
/**
* 获取到所有的类
*/
fun scanAllClasses(): List<String> {
//获取到classpath
val url = Thread.currentThread().contextClassLoader.getResource("")
val classesPath = File(url.path)
var classes = (getClassesFromPath(classesPath))
//获取到lib目录
val jarsPath = File(url.path.replace("classes", "lib"))
var jars = jarsPath.listFiles { dir, filename -> filename.endsWith(".jar") }
jars.forEach { classes += getClassesFromJar(it) }
return classes
}
/**
* 获取到指定文件目录下所有的class包名
*/
private fun getClassesFromPath(path: File): List<String> {
return FileUtils.listFiles(path, arrayOf("class"), true)
.map {
it.absolutePath
.drop(path.absolutePath.length + 1)
.replace(File.separatorChar, '.')
.dropLast(6)
}
}
/**
* 获取指定jar文件里面所有的class包名
*/
private fun getClassesFromJar(jarFile: File): List<String> {
val jar = JarFile(jarFile)
return jar.entries()
.toList()
.filter { it.name.endsWith(".class") }
.map { it.name.replace(File.separatorChar, '.').dropLast(6) }
} | apache-2.0 | dad2cf0cc0eeaefb2fe48351c207d4c5 | 25.836735 | 80 | 0.614155 | 3.74359 | false | false | false | false |
dafi/photoshelf | core/src/main/java/com/ternaryop/photoshelf/adapter/AbsBaseAdapter.kt | 1 | 747 | package com.ternaryop.photoshelf.adapter
import android.view.View
import androidx.recyclerview.widget.RecyclerView
/**
* Created by dave on 10/03/18.
* Base Adapter
*/
abstract class AbsBaseAdapter<VH : RecyclerView.ViewHolder> : RecyclerView.Adapter<VH>() {
fun setEmptyView(view: View, onAdapterChanged: ((RecyclerView.Adapter<VH>) -> Boolean)? = null) {
registerAdapterDataObserver(object : RecyclerView.AdapterDataObserver() {
override fun onChanged() {
super.onChanged()
if (onAdapterChanged == null || onAdapterChanged(this@AbsBaseAdapter)) {
view.visibility = if (itemCount == 0) View.VISIBLE else View.GONE
}
}
})
}
}
| mit | c98edb14280e1210b7faf051953b6afc | 34.571429 | 101 | 0.641232 | 4.611111 | false | false | false | false |
tasks/tasks | app/src/main/java/org/tasks/jobs/AfterSaveWork.kt | 1 | 1492 | package org.tasks.jobs
import android.content.Context
import androidx.hilt.work.HiltWorker
import androidx.work.WorkerParameters
import com.todoroo.astrid.gcal.GCalHelper
import com.todoroo.astrid.repeats.RepeatTaskHelper
import dagger.assisted.Assisted
import dagger.assisted.AssistedInject
import org.tasks.analytics.Firebase
import org.tasks.data.CaldavDao
import org.tasks.data.TaskDao
import org.tasks.injection.BaseWorker
@HiltWorker
class AfterSaveWork @AssistedInject constructor(
@Assisted context: Context,
@Assisted workerParams: WorkerParameters,
firebase: Firebase,
private val repeatTaskHelper: RepeatTaskHelper,
private val taskDao: TaskDao,
private val caldavDao: CaldavDao,
private val gCalHelper: GCalHelper
) : BaseWorker(context, workerParams, firebase) {
override suspend fun run(): Result {
val taskId = inputData.getLong(EXTRA_ID, -1)
val task = taskDao.fetch(taskId) ?: return Result.failure()
if (inputData.getBoolean(EXTRA_SUPPRESS_COMPLETION_SNACKBAR, false)) {
task.suppressRefresh()
}
gCalHelper.updateEvent(task)
if (caldavDao.getAccountForTask(taskId)?.isSuppressRepeatingTasks != true) {
repeatTaskHelper.handleRepeat(task)
}
return Result.success()
}
companion object {
const val EXTRA_ID = "extra_id"
const val EXTRA_SUPPRESS_COMPLETION_SNACKBAR = "extra_suppress_snackbar"
}
} | gpl-3.0 | 887fb1b8e74081bf7a061543114ce0ea | 32.931818 | 84 | 0.719839 | 4.388235 | false | false | false | false |
trinhlbk1991/vivid | library/src/main/java/com/icetea09/vivid/model/Image.kt | 1 | 1350 | package com.icetea09.vivid.model
import android.os.Parcel
import android.os.Parcelable
class Image : Parcelable {
var id: Long = 0
var name: String? = null
var path: String? = null
var isSelected: Boolean = false
constructor(id: Long, name: String, path: String, isSelected: Boolean) {
this.id = id
this.name = name
this.path = path
this.isSelected = isSelected
}
override fun describeContents(): Int {
return 0
}
override fun writeToParcel(dest: Parcel, flags: Int) {
dest.writeLong(this.id)
dest.writeString(this.name)
dest.writeString(this.path)
dest.writeByte(if (this.isSelected) 1.toByte() else 0.toByte())
}
protected constructor(parcel: Parcel) {
this.id = parcel.readLong()
this.name = parcel.readString()
this.path = parcel.readString()
this.isSelected = parcel.readByte().toInt() != 0
}
companion object {
@JvmField @Suppress("unused")
val CREATOR: Parcelable.Creator<Image> = object : Parcelable.Creator<Image> {
override fun createFromParcel(source: Parcel): Image {
return Image(source)
}
override fun newArray(size: Int): Array<Image> {
return arrayOf()
}
}
}
}
| mit | f723622531bc93029384fbdc85a6b7e9 | 26 | 85 | 0.596296 | 4.326923 | false | false | false | false |
nickthecoder/paratask | paratask-app/src/main/kotlin/uk/co/nickthecoder/paratask/table/TimestampColumn.kt | 1 | 1884 | /*
ParaTask Copyright (C) 2017 Nick Robinson
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 uk.co.nickthecoder.paratask.table
import javafx.scene.control.cell.TextFieldTableCell
import uk.co.nickthecoder.paratask.util.uncamel
import java.time.Instant
import java.time.LocalDateTime
import java.time.ZoneId
open class TimestampColumn<R>(
name: String,
label: String = name.uncamel(),
getter: (R) -> Long) :
Column<R, Long>(
name = name,
label = label,
getter = getter,
width = 150,
filterGetter = { row: R ->
LocalDateTime.ofInstant(Instant.ofEpochMilli(getter(row)), ZoneId.systemDefault())
}) {
init {
setCellFactory { DateTableCell() }
styleClass.add("timestamp")
}
class DateTableCell<R> : TextFieldTableCell<R, Long>() {
override fun updateItem(item: Long?, empty: Boolean) {
super.updateItem(item, empty)
if (empty || item == null) {
setText(null)
} else {
val dateTime = LocalDateTime.ofInstant(Instant.ofEpochMilli(item), ZoneId.systemDefault())
setText(LocalDateTimeColumn.format(dateTime))
}
}
}
} | gpl-3.0 | 872eb41cb5449ad0435d1346bc88f158 | 31.5 | 106 | 0.646497 | 4.561743 | false | false | false | false |
nemerosa/ontrack | ontrack-extension-chart/src/main/java/net/nemerosa/ontrack/extension/chart/support/Interval.kt | 1 | 2524 | package net.nemerosa.ontrack.extension.chart.support
import net.nemerosa.ontrack.common.Time
import net.nemerosa.ontrack.model.exceptions.InputException
import java.time.LocalDateTime
data class Interval(
val start: LocalDateTime,
val end: LocalDateTime,
) {
fun split(intervalPeriod: IntervalPeriod): List<Interval> {
check(start < end) { "Start must be < end" }
val result = mutableListOf<Interval>()
var start = this.start
while (start < this.end) {
val end = intervalPeriod.addTo(start)
result += Interval(start, end)
start = end
}
return result
}
operator fun contains(timestamp: LocalDateTime): Boolean =
timestamp >= start && timestamp < end
companion object {
private val fixed = "(\\d+)([dwmy])".toRegex()
private val explicit =
"(\\d\\d\\d\\d-\\d\\d-\\d\\dT\\d\\d:\\d\\d:\\d\\d)-(\\d\\d\\d\\d-\\d\\d-\\d\\dT\\d\\d:\\d\\d:\\d\\d)".toRegex()
fun parse(value: String, ref: LocalDateTime = Time.now()): Interval {
val f = fixed.matchEntire(value)
return if (f != null) {
val count = f.groupValues[1].toLong()
val type = f.groupValues[2]
fixed(value, count, type, ref)
} else {
val x = explicit.matchEntire(value)
if (x != null) {
val start = Time.fromStorage(x.groupValues[1])
?: throw IntervalFormatException("Cannot parse interval start date: ${x.groupValues[1]}")
val end = Time.fromStorage(x.groupValues[2])
?: throw IntervalFormatException("Cannot parse interval start date: ${x.groupValues[2]}")
Interval(start, end)
} else {
throw IntervalFormatException("Cannot parse interval: $value")
}
}
}
private fun fixed(value: String, count: Long, type: String, ref: LocalDateTime): Interval {
val start = when (type) {
"d" -> ref.minusDays(count)
"w" -> ref.minusWeeks(count)
"m" -> ref.minusMonths(count)
"y" -> ref.minusYears(count)
else -> throw IntervalFormatException("Unknown time interval [$type] in $value")
}
return Interval(start, ref)
}
}
}
class IntervalFormatException(message: String) : InputException(message)
| mit | c2838479f9595ed1e2bab1369782c82f | 37.242424 | 123 | 0.547544 | 4.459364 | false | false | false | false |
wiltonlazary/kotlin-native | backend.native/compiler/ir/backend.native/src/org/jetbrains/kotlin/backend/konan/lower/DelegationLowering.kt | 1 | 14399 | /*
* Copyright 2010-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license
* that can be found in the LICENSE file.
*/
package org.jetbrains.kotlin.backend.konan.lower
import org.jetbrains.kotlin.backend.common.FileLoweringPass
import org.jetbrains.kotlin.backend.common.IrElementTransformerVoidWithContext
import org.jetbrains.kotlin.backend.common.lower.createIrBuilder
import org.jetbrains.kotlin.backend.common.lower.irBlock
import org.jetbrains.kotlin.backend.konan.Context
import org.jetbrains.kotlin.backend.konan.descriptors.synthesizedName
import org.jetbrains.kotlin.backend.konan.ir.buildSimpleAnnotation
import org.jetbrains.kotlin.descriptors.*
import org.jetbrains.kotlin.ir.builders.*
import org.jetbrains.kotlin.ir.declarations.*
import org.jetbrains.kotlin.ir.declarations.impl.IrFieldImpl
import org.jetbrains.kotlin.ir.descriptors.WrappedFieldDescriptor
import org.jetbrains.kotlin.ir.expressions.IrExpression
import org.jetbrains.kotlin.ir.expressions.IrLocalDelegatedPropertyReference
import org.jetbrains.kotlin.ir.expressions.IrPropertyReference
import org.jetbrains.kotlin.ir.expressions.impl.*
import org.jetbrains.kotlin.ir.symbols.IrConstructorSymbol
import org.jetbrains.kotlin.ir.symbols.impl.IrFieldSymbolImpl
import org.jetbrains.kotlin.ir.types.*
import org.jetbrains.kotlin.ir.types.IrType
import org.jetbrains.kotlin.ir.types.typeWith
import org.jetbrains.kotlin.ir.util.*
import org.jetbrains.kotlin.ir.visitors.transformChildrenVoid
import org.jetbrains.kotlin.name.Name
internal class PropertyDelegationLowering(val context: Context) : FileLoweringPass {
private var tempIndex = 0
private val kTypeGenerator = KTypeGenerator(context)
private fun getKPropertyImplConstructor(receiverTypes: List<IrType>,
returnType: IrType,
isLocal: Boolean,
isMutable: Boolean) : Pair<IrConstructorSymbol, List<IrType>> {
val symbols = context.ir.symbols
val classSymbol =
if (isLocal) {
assert(receiverTypes.isEmpty()) { "Local delegated property cannot have explicit receiver" }
when {
isMutable -> symbols.kLocalDelegatedMutablePropertyImpl
else -> symbols.kLocalDelegatedPropertyImpl
}
} else {
when (receiverTypes.size) {
0 -> when {
isMutable -> symbols.kMutableProperty0Impl
else -> symbols.kProperty0Impl
}
1 -> when {
isMutable -> symbols.kMutableProperty1Impl
else -> symbols.kProperty1Impl
}
2 -> when {
isMutable -> symbols.kMutableProperty2Impl
else -> symbols.kProperty2Impl
}
else -> throw AssertionError("More than 2 receivers is not allowed")
}
}
val arguments = (receiverTypes + listOf(returnType))
return classSymbol.constructors.single() to arguments
}
override fun lower(irFile: IrFile) {
// Somehow there is no reasonable common ancestor for IrProperty and IrLocalDelegatedProperty,
// so index by IrDeclaration.
val kProperties = mutableMapOf<IrDeclaration, Pair<IrExpression, Int>>()
val arrayClass = context.ir.symbols.array.owner
val arrayItemGetter = arrayClass.functions.single { it.name == Name.identifier("get") }
val anyType = context.irBuiltIns.anyType
val kPropertyImplType = context.ir.symbols.kProperty1Impl.typeWith(anyType, anyType)
val kPropertiesFieldType: IrType = context.ir.symbols.array.typeWith(kPropertyImplType)
val kPropertiesField = WrappedFieldDescriptor().let {
IrFieldImpl(
SYNTHETIC_OFFSET, SYNTHETIC_OFFSET,
DECLARATION_ORIGIN_KPROPERTIES_FOR_DELEGATION,
IrFieldSymbolImpl(it),
"KPROPERTIES".synthesizedName,
kPropertiesFieldType,
DescriptorVisibilities.PRIVATE,
isFinal = true,
isExternal = false,
isStatic = true,
).apply {
it.bind(this)
parent = irFile
annotations += buildSimpleAnnotation(context.irBuiltIns, startOffset, endOffset, context.ir.symbols.sharedImmutable.owner)
}
}
irFile.transformChildrenVoid(object : IrElementTransformerVoidWithContext() {
override fun visitPropertyReference(expression: IrPropertyReference): IrExpression {
expression.transformChildrenVoid(this)
val startOffset = expression.startOffset
val endOffset = expression.endOffset
val irBuilder = context.createIrBuilder(currentScope!!.scope.scopeOwnerSymbol, startOffset, endOffset)
irBuilder.run {
val receiversCount = listOf(expression.dispatchReceiver, expression.extensionReceiver).count { it != null }
return when (receiversCount) {
1 -> createKProperty(expression, this) // Has receiver.
2 -> error("Callable reference to properties with two receivers is not allowed: ${expression.symbol.owner.name}")
else -> { // Cache KProperties with no arguments.
val field = kProperties.getOrPut(expression.symbol.owner) {
createKProperty(expression, this) to kProperties.size
}
irCall(arrayItemGetter).apply {
dispatchReceiver = irGetField(null, kPropertiesField)
putValueArgument(0, irInt(field.second))
}
}
}
}
}
override fun visitLocalDelegatedPropertyReference(expression: IrLocalDelegatedPropertyReference): IrExpression {
expression.transformChildrenVoid(this)
val startOffset = expression.startOffset
val endOffset = expression.endOffset
val irBuilder = context.createIrBuilder(currentScope!!.scope.scopeOwnerSymbol, startOffset, endOffset)
irBuilder.run {
val receiversCount = listOf(expression.dispatchReceiver, expression.extensionReceiver).count { it != null }
if (receiversCount == 2)
throw AssertionError("Callable reference to properties with two receivers is not allowed: ${expression}")
else { // Cache KProperties with no arguments.
// TODO: what about `receiversCount == 1` case?
val field = kProperties.getOrPut(expression.symbol.owner) {
createLocalKProperty(
expression.symbol.owner.name.asString(),
expression.getter.owner.returnType,
this
) to kProperties.size
}
return irCall(arrayItemGetter).apply {
dispatchReceiver = irGetField(null, kPropertiesField)
putValueArgument(0, irInt(field.second))
}
}
}
}
})
if (kProperties.isNotEmpty()) {
val initializers = kProperties.values.sortedBy { it.second }.map { it.first }
// TODO: move to object for lazy initialization.
irFile.declarations.add(0, kPropertiesField.apply {
initializer = IrExpressionBodyImpl(startOffset, endOffset,
context.createArrayOfExpression(startOffset, endOffset, kPropertyImplType, initializers))
})
}
}
private fun createKProperty(expression: IrPropertyReference, irBuilder: IrBuilderWithScope): IrExpression {
val startOffset = expression.startOffset
val endOffset = expression.endOffset
return irBuilder.irBlock(expression) {
val receiverTypes = mutableListOf<IrType>()
val dispatchReceiver = expression.dispatchReceiver.let {
if (it == null)
null
else
irTemporary(value = it, nameHint = "\$dispatchReceiver${tempIndex++}")
}
val extensionReceiver = expression.extensionReceiver.let {
if (it == null)
null
else
irTemporary(value = it, nameHint = "\$extensionReceiver${tempIndex++}")
}
val returnType = expression.getter?.owner?.returnType ?: expression.field!!.owner.type
val getterCallableReference = expression.getter?.owner?.let { getter ->
getter.extensionReceiverParameter.let {
if (it != null && expression.extensionReceiver == null)
receiverTypes.add(it.type)
}
getter.dispatchReceiverParameter.let {
if (it != null && expression.dispatchReceiver == null)
receiverTypes.add(it.type)
}
val getterKFunctionType = this@PropertyDelegationLowering.context.ir.symbols.getKFunctionType(
returnType,
receiverTypes
)
IrFunctionReferenceImpl(
startOffset = startOffset,
endOffset = endOffset,
type = getterKFunctionType,
symbol = expression.getter!!,
typeArgumentsCount = getter.typeParameters.size,
valueArgumentsCount = getter.valueParameters.size,
reflectionTarget = expression.getter!!
).apply {
this.dispatchReceiver = dispatchReceiver?.let { irGet(it) }
this.extensionReceiver = extensionReceiver?.let { irGet(it) }
for (index in 0 until expression.typeArgumentsCount)
putTypeArgument(index, expression.getTypeArgument(index))
}
}
val setterCallableReference = expression.setter?.owner?.let { setter ->
if (!isKMutablePropertyType(expression.type)) null
else {
val setterKFunctionType = this@PropertyDelegationLowering.context.ir.symbols.getKFunctionType(
context.irBuiltIns.unitType,
receiverTypes + returnType
)
IrFunctionReferenceImpl(
startOffset = startOffset,
endOffset = endOffset,
type = setterKFunctionType,
symbol = expression.setter!!,
typeArgumentsCount = setter.typeParameters.size,
valueArgumentsCount = setter.valueParameters.size,
reflectionTarget = expression.setter!!
).apply {
this.dispatchReceiver = dispatchReceiver?.let { irGet(it) }
this.extensionReceiver = extensionReceiver?.let { irGet(it) }
for (index in 0 until expression.typeArgumentsCount)
putTypeArgument(index, expression.getTypeArgument(index))
}
}
}
val (symbol, constructorTypeArguments) = getKPropertyImplConstructor(
receiverTypes = receiverTypes,
returnType = returnType,
isLocal = false,
isMutable = setterCallableReference != null)
val initializer = irCall(symbol.owner, constructorTypeArguments).apply {
putValueArgument(0, irString(expression.symbol.owner.name.asString()))
putValueArgument(1, with(kTypeGenerator) { irKType(returnType) })
if (getterCallableReference != null)
putValueArgument(2, getterCallableReference)
if (setterCallableReference != null)
putValueArgument(3, setterCallableReference)
}
+initializer
}
}
private fun createLocalKProperty(propertyName: String,
propertyType: IrType,
irBuilder: IrBuilderWithScope): IrExpression {
irBuilder.run {
val (symbol, constructorTypeArguments) = getKPropertyImplConstructor(
receiverTypes = emptyList(),
returnType = propertyType,
isLocal = true,
isMutable = false)
val initializer = irCall(symbol.owner, constructorTypeArguments).apply {
putValueArgument(0, irString(propertyName))
putValueArgument(1, with(kTypeGenerator) { irKType(propertyType) })
}
return initializer
}
}
private fun isKMutablePropertyType(type: IrType): Boolean {
if (type !is IrSimpleType) return false
val expectedClass = when (type.arguments.size) {
0 -> return false
1 -> context.ir.symbols.kMutableProperty0
2 -> context.ir.symbols.kMutableProperty1
3 -> context.ir.symbols.kMutableProperty2
else -> throw AssertionError("More than 2 receivers is not allowed")
}
return type.classifier == expectedClass
}
private object DECLARATION_ORIGIN_KPROPERTIES_FOR_DELEGATION :
IrDeclarationOriginImpl("KPROPERTIES_FOR_DELEGATION")
}
| apache-2.0 | 52be43a518114c171ea9471dac88b401 | 47.810169 | 138 | 0.570734 | 6.106446 | false | false | false | false |
jraska/github-client | feature/repo/src/main/java/com/jraska/github/client/repo/ui/RepoDetailActivity.kt | 1 | 3110 | package com.jraska.github.client.repo.ui
import android.app.Activity
import android.content.Intent
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.airbnb.epoxy.SimpleEpoxyAdapter
import com.airbnb.epoxy.SimpleEpoxyModel
import com.google.android.material.floatingactionbutton.FloatingActionButton
import com.jraska.github.client.core.android.viewModel
import com.jraska.github.client.repo.R
import com.jraska.github.client.repo.RepoDetailViewModel
import com.jraska.github.client.repo.model.RepoDetail
import com.jraska.github.client.users.ui.ErrorHandler
import com.jraska.github.client.users.ui.SimpleTextModel
internal class RepoDetailActivity : AppCompatActivity() {
private val viewModel: RepoDetailViewModel by lazy { viewModel(RepoDetailViewModel::class.java) }
private val repoDetailRecycler: RecyclerView get() = findViewById(R.id.repo_detail_recycler)
private fun fullRepoName(): String {
return intent.getStringExtra(EXTRA_FULL_REPO_NAME)!!
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_repo_detail)
setSupportActionBar(findViewById(R.id.toolbar))
repoDetailRecycler.layoutManager = LinearLayoutManager(this)
title = fullRepoName()
val liveData = viewModel.repoDetail(fullRepoName())
liveData.observe(this, { this.setState(it) })
findViewById<FloatingActionButton>(R.id.repo_detail_github_fab)
.setOnClickListener { viewModel.onGitHubIconClicked(fullRepoName()) }
}
private fun setState(state: RepoDetailViewModel.ViewState) {
when (state) {
is RepoDetailViewModel.ViewState.Loading -> showLoading()
is RepoDetailViewModel.ViewState.Error -> setError(state.error)
is RepoDetailViewModel.ViewState.ShowRepo -> setRepoDetail(state.repo)
}
}
private fun showLoading() {
findViewById<RecyclerView>(R.id.repo_detail_recycler).adapter = SimpleEpoxyAdapter().apply { addModels(SimpleEpoxyModel(R.layout.item_loading)) }
}
private fun setError(error: Throwable) {
ErrorHandler.displayError(error, repoDetailRecycler)
}
private fun setRepoDetail(repoDetail: RepoDetail) {
val adapter = SimpleEpoxyAdapter()
adapter.addModels(RepoDetailHeaderModel(repoDetail))
val languageText = getString(
R.string.repo_detail_language_used_template,
repoDetail.data.language
)
adapter.addModels(SimpleTextModel(languageText))
val issuesText = getString(
R.string.repo_detail_issues_template,
repoDetail.data.issuesCount.toString()
)
adapter.addModels(SimpleTextModel(issuesText))
repoDetailRecycler.adapter = adapter
}
companion object {
private const val EXTRA_FULL_REPO_NAME = "fullRepoName"
fun start(from: Activity, fullRepoName: String) {
val intent = Intent(from, RepoDetailActivity::class.java)
intent.putExtra(EXTRA_FULL_REPO_NAME, fullRepoName)
from.startActivity(intent)
}
}
}
| apache-2.0 | b18430fa1b0e6ea2fbe84956dbe53191 | 33.555556 | 149 | 0.770418 | 4.374121 | false | false | false | false |
MimiReader/mimi-reader | mimi-app/src/main/java/com/emogoth/android/phone/mimi/db/HiddenThreadTableConnection.kt | 1 | 1854 | package com.emogoth.android.phone.mimi.db
import android.util.Log
import com.emogoth.android.phone.mimi.db.MimiDatabase.Companion.getInstance
import com.emogoth.android.phone.mimi.db.models.HiddenThread
import io.reactivex.Single
import java.util.concurrent.TimeUnit
object HiddenThreadTableConnection {
val LOG_TAG: String = HiddenThreadTableConnection::class.java.simpleName
@JvmStatic
fun fetchHiddenThreads(boardName: String): Single<List<HiddenThread>> {
return getInstance()?.hiddenThreads()?.getHiddenThreadsForBoard(boardName)
?.onErrorReturn { throwable: Throwable? ->
Log.e(LOG_TAG, "Error loading hidden threads from the database", throwable)
emptyList()
} ?: Single.just(emptyList())
}
@JvmStatic
fun hideThread(boardName: String, threadId: Long, sticky: Boolean): Single<Boolean> {
return Single.defer {
val hiddenThread = HiddenThread()
hiddenThread.boardName = boardName
hiddenThread.threadId = threadId
hiddenThread.time = System.currentTimeMillis()
hiddenThread.sticky = (if (sticky) 1 else 0)
getInstance()?.hiddenThreads()?.upsert(hiddenThread) ?: return@defer Single.just(false)
Single.just(true)
}
}
@JvmStatic
fun clearAll(): Single<Boolean> {
return Single.defer {
getInstance()?.hiddenThreads()?.clear() ?: Single.just(false)
Single.just(true)
}
}
@JvmStatic
fun prune(days: Int): Single<Boolean> {
return Single.defer {
val oldestTime = System.currentTimeMillis() - TimeUnit.DAYS.toMillis(days.toLong())
getInstance()?.hiddenThreads()?.prune(oldestTime) ?: Single.just(false)
Single.just(true)
}
}
} | apache-2.0 | 19d978279abc670babe4a4cfe684adf6 | 36.1 | 99 | 0.645092 | 4.658291 | false | false | false | false |
is00hcw/anko | dsl/src/org/jetbrains/android/anko/utils/stringUtils.kt | 2 | 1346 | /*
* Copyright 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.android.anko.utils
fun String.toCamelCase(separator: Char = '_', firstCapital: Boolean = true): String {
val builder = StringBuilder()
var capitalFlag = firstCapital
for (c in this) {
when (c) {
separator -> capitalFlag = true
else -> {
builder.append(if (capitalFlag) Character.toUpperCase(c) else Character.toLowerCase(c))
capitalFlag = false
}
}
}
return builder.toString()
}
fun String.toUPPER_CASE(): String {
val builder = StringBuilder()
for (c in this) {
if (c.isUpperCase() && builder.length() > 0) builder.append('_')
builder.append(c.toUpperCase())
}
return builder.toString()
} | apache-2.0 | 1fded8ebaa1442a83aa4d6b77ed16738 | 31.853659 | 103 | 0.657504 | 4.193146 | false | false | false | false |
donald-w/Anki-Android | AnkiDroid/src/main/java/com/ichi2/ui/KeyPicker.kt | 1 | 3051 | /*
* Copyright (c) 2021 David Allison <[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.ichi2.ui
import android.content.Context
import android.view.KeyEvent
import android.view.LayoutInflater
import android.view.View
import android.widget.TextView
import com.ichi2.anki.R
import com.ichi2.anki.reviewer.Binding
import timber.log.Timber
typealias KeyCode = Int
/**
* Square dialog which allows a user to select a [Binding] for a key press
* This does not yet support bluetooth headsets.
*/
class KeyPicker(val rootLayout: View) {
private val textView: TextView = rootLayout.findViewById(R.id.key_picker_selected_key)
private val context: Context get() = rootLayout.context
private var text: String
set(value) {
textView.text = value
}
get() = textView.text.toString()
private var onBindingChangedListener: ((Binding) -> Unit)? = null
private var isValidKeyCode: ((KeyCode) -> Boolean)? = null
/** Currently bound key */
private var binding: Binding? = null
fun getBinding(): Binding? = binding
fun dispatchKeyEvent(event: KeyEvent): Boolean {
if (event.action != KeyEvent.ACTION_DOWN) return true
// When accepting a keypress, we only want to find the keycode, not the unicode character.
val isValidKeyCode = isValidKeyCode
val maybeBinding = Binding.key(event).stream().filter { x -> x.isKeyCode && (isValidKeyCode == null || isValidKeyCode(x.getKeycode()!!)) }.findFirst()
if (!maybeBinding.isPresent) {
return true
}
val newBinding = maybeBinding.get()
Timber.d("Changed key to '%s'", newBinding)
binding = newBinding
text = newBinding.toDisplayString(context)
onBindingChangedListener?.invoke(newBinding)
return true
}
fun setBindingChangedListener(listener: (Binding) -> Unit) {
onBindingChangedListener = listener
}
fun setKeycodeValidation(validation: (KeyCode) -> Boolean) {
isValidKeyCode = validation
}
init {
textView.requestFocus()
textView.setOnKeyListener { _, _, event -> dispatchKeyEvent(event) }
}
companion object {
fun inflate(context: Context): KeyPicker {
val layout = LayoutInflater.from(context).inflate(R.layout.dialog_key_picker, null)
return KeyPicker(layout)
}
}
}
| gpl-3.0 | e6ef72ccbc13c48273ba811e4a4632c2 | 32.9 | 158 | 0.684694 | 4.396254 | false | false | false | false |
Ztiany/Repository | Android/AAC-Sample/Paging-Sample/src/main/java/com/ztiany/acc/MainActivity.kt | 2 | 969 | package com.ztiany.acc
import android.content.Intent
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import kotlinx.android.synthetic.main.activity_main.*
class MainActivity : AppCompatActivity() {
companion object {
const val LIVE_DATA = "LiveData"
const val RXJAVA = "RxJava"
const val TYPE = "TYPE"
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
setupView()
}
private fun setupView() {
btnLiveData.setOnClickListener {
val intent = Intent(this, ContentActivity::class.java)
intent.putExtra(TYPE, LIVE_DATA)
startActivity(intent)
}
btnRxJava.setOnClickListener {
val intent = Intent(this, ContentActivity::class.java)
intent.putExtra(TYPE, RXJAVA)
startActivity(intent)
}
}
}
| apache-2.0 | ee4df5ba0608b305b7ac0ce8d973b15d | 25.189189 | 66 | 0.647059 | 4.614286 | false | false | false | false |
uchuhimo/kotlin-playground | lang/src/main/kotlin/com/uchuhimo/privateAccess/Play.kt | 1 | 506 | package com.uchuhimo.privateAccess
class A(private val a: Int) {
fun accessOtherA(otherA: A) {
println(otherA.a)
}
}
class B<out T : Number>(private var b: T) {
fun accessOtherB(otherB: B<Int>) {
// `b` is private to `this` since variance
// otherB.b
println(otherB.getB())
}
fun getB(): T = b
}
fun main(args: Array<String>) {
val a1 = A(1)
val a2 = A(2)
a1.accessOtherA(a2)
val b1 = B(1)
val b2 = B(2)
b1.accessOtherB(b2)
}
| apache-2.0 | 50dad40057761e735d65e06cb9f26560 | 18.461538 | 50 | 0.561265 | 2.72043 | false | false | false | false |
matejdro/WearMusicCenter | mobile/src/main/java/com/matejdro/wearmusiccenter/view/buttonconfig/GesturePickerFragment.kt | 1 | 12465 | package com.matejdro.wearmusiccenter.view.buttonconfig
import android.Manifest
import android.app.Activity
import android.content.ActivityNotFoundException
import android.content.Intent
import android.content.pm.PackageManager
import android.graphics.Color
import android.graphics.PorterDuff
import android.graphics.drawable.VectorDrawable
import android.os.Bundle
import android.os.PersistableBundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import androidx.appcompat.app.AlertDialog
import androidx.core.content.ContextCompat
import androidx.core.view.isVisible
import androidx.fragment.app.DialogFragment
import androidx.fragment.app.FragmentContainerView
import com.matejdro.wearmusiccenter.R
import com.matejdro.wearmusiccenter.actions.NullAction
import com.matejdro.wearmusiccenter.actions.PhoneAction
import com.matejdro.wearmusiccenter.common.buttonconfig.ButtonGesture
import com.matejdro.wearmusiccenter.common.buttonconfig.ButtonInfo
import com.matejdro.wearmusiccenter.common.buttonconfig.GESTURE_DOUBLE_TAP
import com.matejdro.wearmusiccenter.common.buttonconfig.GESTURE_LONG_TAP
import com.matejdro.wearmusiccenter.common.buttonconfig.GESTURE_SINGLE_TAP
import com.matejdro.wearmusiccenter.common.buttonconfig.NUM_BUTTON_GESTURES
import com.matejdro.wearmusiccenter.config.ActionConfig
import com.matejdro.wearmusiccenter.config.CustomIconStorage
import com.matejdro.wearmusiccenter.config.buttons.ButtonConfig
import com.matejdro.wearmusiccenter.databinding.PopupGesturePickerBinding
import com.matejdro.wearmusiccenter.di.LocalActivityConfig
import com.matejdro.wearmusiccenter.view.ActivityResultReceiver
import com.matejdro.wearmusiccenter.view.actionconfigs.ActionConfigFragment
import com.matejdro.wearutils.miscutils.BitmapUtils
import dagger.android.support.AndroidSupportInjection
import javax.inject.Inject
class GesturePickerFragment : DialogFragment() {
companion object {
const val REQUEST_CODE_SAVE_NOTIFICATION = 1578
private const val PARAM_SETS_PLAYBACK_ACTIONS = "SetsPlaybackActions"
private const val PARAM_BUTTON_INFO = "ButtonInfo"
private const val PARAM_BUTTON_NAME = "ButtonName"
private const val PARAM_SUPPORTS_LONG_PRESS = "SupportsLongPress"
private const val REQUEST_CODE_PICK_ACTION = 5891
private const val REQUEST_CODE_PICK_ACTION_TO = REQUEST_CODE_PICK_ACTION + NUM_BUTTON_GESTURES
private const val REQUEST_CODE_PICK_ICON = 5991
fun newInstance(setsPlaybackButtons: Boolean, baseButtonInfo: ButtonInfo, buttonName: String, supportsLongPress: Boolean): GesturePickerFragment {
val fragment = GesturePickerFragment()
val args = Bundle()
args.putBoolean(PARAM_SETS_PLAYBACK_ACTIONS, setsPlaybackButtons)
args.putParcelable(PARAM_BUTTON_INFO, baseButtonInfo.serialize())
args.putString(PARAM_BUTTON_NAME, buttonName)
args.putBoolean(PARAM_SUPPORTS_LONG_PRESS, supportsLongPress)
fragment.arguments = args
return fragment
}
}
private var setsPlaybackButtons: Boolean = false
private lateinit var binding: PopupGesturePickerBinding
private lateinit var baseButtonInfo: ButtonInfo
private lateinit var buttonName: String
private var supportsLongPress: Boolean = false
private lateinit var actions: Array<PhoneAction?>
@Inject
@LocalActivityConfig
lateinit var config: ActionConfig
@Inject
lateinit var customIconStorage: CustomIconStorage
private lateinit var buttonConfig: ButtonConfig
private lateinit var buttons: Array<ButtonSet>
private var anyActionChanged = false
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
baseButtonInfo = ButtonInfo(requireArguments().getParcelable(PARAM_BUTTON_INFO)!!)
buttonName = requireArguments().getString(PARAM_BUTTON_NAME)!!
setsPlaybackButtons = requireArguments().getBoolean(PARAM_SETS_PLAYBACK_ACTIONS)
supportsLongPress = requireArguments().getBoolean(PARAM_SUPPORTS_LONG_PRESS)
AndroidSupportInjection.inject(this)
setStyle(STYLE_NORMAL, R.style.AppTheme_Dialog_Short)
buttonConfig = if (setsPlaybackButtons)
config.getPlayingConfig()
else
config.getStoppedConfig()
actions = Array(NUM_BUTTON_GESTURES) {
buttonConfig.getScreenAction(baseButtonInfo.copy(gesture = it))
}
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View {
binding = PopupGesturePickerBinding.inflate(inflater, container, false)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
dialog!!.setCanceledOnTouchOutside(true)
dialog!!.setTitle(buttonName)
buttons = arrayOf(
ButtonSet(binding.singlePressButton, binding.singlePressConfigFragment),
ButtonSet(binding.doublePressButton, binding.doublePressConfigFragment),
ButtonSet(binding.longPressButton, binding.longPressConfigFragment)
)
updateButton(buttons.elementAt(0), GESTURE_SINGLE_TAP)
updateButton(buttons.elementAt(1), GESTURE_DOUBLE_TAP)
updateButton(buttons.elementAt(2), GESTURE_LONG_TAP)
binding.customizeIcon.isVisible = !baseButtonInfo.physicalButton
binding.longPressDescription.isVisible = supportsLongPress
binding.longPressButton.isVisible = supportsLongPress
binding.customizeIcon.setOnClickListener { startIconSelection() }
binding.singlePressButton.setOnClickListener { changeAction(GESTURE_SINGLE_TAP) }
binding.doublePressButton.setOnClickListener { changeAction(GESTURE_DOUBLE_TAP) }
binding.longPressButton.setOnClickListener { changeAction(GESTURE_LONG_TAP) }
binding.okButton.setOnClickListener { save() }
binding.cancelButton.setOnClickListener { dismiss() }
}
private fun changeAction(gesture: Int) {
val requestCode = REQUEST_CODE_PICK_ACTION + gesture
startActivityForResult(Intent(activity, ActionPickerActivity::class.java), requestCode)
}
private fun updateButton(buttonSet: ButtonSet, @ButtonGesture gesture: Int) {
val phoneAction = actions[gesture]
updateButton(buttonSet, phoneAction)
}
private fun updateButton(buttonSet: ButtonSet, phoneAction: PhoneAction?) {
var mutableAction = phoneAction
if (mutableAction == null) {
mutableAction = NullAction(requireActivity())
}
var icon = customIconStorage[mutableAction]
if (icon is VectorDrawable) {
icon = icon.mutate()
icon.setColorFilter(Color.BLACK, PorterDuff.Mode.MULTIPLY)
}
val iconSize = resources.getDimensionPixelSize(R.dimen.action_icon_size)
icon.setBounds(0, 0, iconSize, iconSize)
buttonSet.button.text = mutableAction.title
buttonSet.button.setCompoundDrawables(icon, null, null, null)
val configFragmentClass = mutableAction.configFragment
if (configFragmentClass != null) {
@Suppress("UNCHECKED_CAST")
val configFragment: ActionConfigFragment<PhoneAction> = configFragmentClass.newInstance() as ActionConfigFragment<PhoneAction>
childFragmentManager.beginTransaction()
.replace(buttonSet.configFragmentContainer.id, configFragment)
.commit()
configFragment.load(mutableAction)
} else {
val existingFragment = childFragmentManager.findFragmentById(buttonSet.configFragmentContainer.id)
existingFragment?.let {
childFragmentManager.beginTransaction()
.remove(it)
.commit()
}
}
}
fun save() {
val anyActionHasConfigFragment = buttons
.mapNotNull { childFragmentManager.findFragmentById(it.configFragmentContainer.id) }
.isNotEmpty()
if (anyActionChanged || anyActionHasConfigFragment) {
for ((gesture, action) in actions.withIndex()) {
val button = buttons[gesture]
if (action != null) {
@Suppress("UNCHECKED_CAST")
(childFragmentManager.findFragmentById(button.configFragmentContainer.id) as? ActionConfigFragment<PhoneAction>)
?.save(action)
}
val buttonInfo = baseButtonInfo.copy(gesture = gesture)
buttonConfig.saveButtonAction(buttonInfo, action)
}
(activity as ActivityResultReceiver)
.onActivityResult(REQUEST_CODE_SAVE_NOTIFICATION, Activity.RESULT_OK, null)
}
dismiss()
}
private fun startIconSelection() {
if (ContextCompat.checkSelfPermission(requireActivity(), Manifest.permission.READ_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED) {
requestStoragePermission()
return
}
try {
var intent = Intent(Intent.ACTION_PICK)
intent.type = "image/*"
intent = Intent.createChooser(intent, getString(R.string.icon_selection_title))
startActivityForResult(intent, REQUEST_CODE_PICK_ICON)
} catch (ignored: ActivityNotFoundException) {
AlertDialog.Builder(requireContext())
.setTitle(R.string.icon_selection_title)
.setMessage(R.string.icon_selection_no_icon_pack)
.setPositiveButton(android.R.string.ok, null)
.show()
}
}
private fun requestStoragePermission() {
AlertDialog.Builder(requireContext())
.setTitle(R.string.icon_selection_title)
.setMessage(R.string.icon_selection_no_storage_permission)
.setPositiveButton(android.R.string.ok, null)
.setOnDismissListener {
requestPermissions(arrayOf(Manifest.permission.READ_EXTERNAL_STORAGE),
REQUEST_CODE_PICK_ACTION)
}
.show()
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
if (resultCode != Activity.RESULT_OK || data == null) {
return
}
if (requestCode in REQUEST_CODE_PICK_ACTION until REQUEST_CODE_PICK_ACTION_TO) {
val gesture = requestCode - REQUEST_CODE_PICK_ACTION
val actionBundle = data.getParcelableExtra<PersistableBundle>(ActionPickerActivity.EXTRA_ACTION_BUNDLE)
val action = PhoneAction.deserialize<PhoneAction>(requireActivity(), actionBundle)
anyActionChanged = anyActionChanged || action != actions[gesture]
actions[gesture] = action
updateButton(buttons[gesture], action)
} else if (requestCode == REQUEST_CODE_PICK_ICON) {
val iconUri = data.data!!
val action = actions[GESTURE_SINGLE_TAP].let {
if (it == null) {
val newAction = NullAction(requireContext())
actions[GESTURE_SINGLE_TAP] = newAction
newAction
} else {
it
}
}
val bitmap = BitmapUtils.getBitmap(BitmapUtils.getDrawableFromUri(activity, iconUri)) ?: return
action.customIconUri = iconUri
customIconStorage.setIcon(iconUri, bitmap)
anyActionChanged = true
updateButton(buttons[GESTURE_SINGLE_TAP], action)
}
}
override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
if (permissions.isNotEmpty() &&
permissions[0] == Manifest.permission.READ_EXTERNAL_STORAGE &&
grantResults[0] == PackageManager.PERMISSION_GRANTED) {
startIconSelection()
}
}
private class ButtonSet(val button: Button, val configFragmentContainer: FragmentContainerView)
}
| gpl-3.0 | 92cb14563cd0bd4409b12546ffbb3839 | 39.339806 | 154 | 0.686963 | 5.268385 | false | true | false | false |
LivotovLabs/AndroidApplicationSkeleton | template-kotlin/mobile/src/main/java/helpers/location.kt | 1 | 2824 | package eu.livotov.labs.androidappskeleton
import android.Manifest
import android.content.Context
import android.location.Location
import android.location.LocationManager
import com.google.android.gms.common.ConnectionResult
import com.google.android.gms.common.GoogleApiAvailability
class LocationHelper()
{
companion object
{
private val PK = 180 / 3.1415926
private val EARTH_RADIUS = 6371.0
fun findDistanceInKm(lat1: Double, lon1: Double, lat2: Double, lon2: Double): Double = Math.acos(Math.sin(Math.toRadians(lat1)) * Math.sin(Math.toRadians(lat2)) + Math.cos(Math.toRadians(lat1)) * Math.cos(Math.toRadians(lat2)) * (Math.cos(Math.toRadians(lon1)) * Math.cos(Math.toRadians(lon2)) + Math.sin(Math.toRadians(lon1)) * Math.sin(Math.toRadians(lon2)))) * EARTH_RADIUS
fun findDistanceInKm(fromLocation: Location, toLocation: Location): Double = Math.abs(fromLocation.distanceTo(toLocation)).toDouble() / 1000
fun isLocationServiceEnabled(ctx: Context = App.self): Boolean
{
var lm: LocationManager? = null
var gps_enabled = false
var network_enabled = false
if (lm == null)
{
lm = ctx.getSystemService(Context.LOCATION_SERVICE) as LocationManager
}
try
{
gps_enabled = lm.isProviderEnabled(LocationManager.GPS_PROVIDER)
}
catch (ignored: Exception)
{
}
try
{
network_enabled = lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER)
}
catch (ignored: Exception)
{
}
return gps_enabled || network_enabled
}
fun isGoogleServicesPresent(ctx: Context = App.self): Boolean
{
return try
{
GoogleApiAvailability.getInstance().isGooglePlayServicesAvailable(ctx) == ConnectionResult.SUCCESS
}
catch (err: Throwable)
{
false
}
}
fun getLocationServicesGlobalStatus(): LocationServicesStatus
{
return if (!App.hasPermissions(Manifest.permission.ACCESS_COARSE_LOCATION))
{
LocationServicesStatus.NoPermissions
} else if (!isLocationServiceEnabled())
{
LocationServicesStatus.NotEnabled
} else if (!isGoogleServicesPresent())
{
LocationServicesStatus.HasGeopositionButNoGoogleServices
} else
{
LocationServicesStatus.FullyPresent
}
}
}
}
enum class LocationServicesStatus
{
FullyPresent, NoPermissions, HasGeopositionButNoGoogleServices, NotEnabled
}
| apache-2.0 | a9537ac1cfcf2e1797030f515b962bc7 | 32.619048 | 384 | 0.604462 | 4.911304 | false | false | false | false |
Studium-SG/neurals | src/main/java/sg/studium/neurals/model/Dl4jModel.kt | 1 | 6373 | package sg.studium.neurals.model
import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.module.kotlin.KotlinModule
import org.apache.commons.io.IOUtils
import org.deeplearning4j.nn.multilayer.MultiLayerNetwork
import org.deeplearning4j.util.ModelSerializer
import org.nd4j.linalg.dataset.api.preprocessor.NormalizerStandardize
import org.nd4j.linalg.dataset.api.preprocessor.serializer.NormalizerSerializer
import org.nd4j.linalg.factory.Nd4j
import java.io.ByteArrayInputStream
import java.io.ByteArrayOutputStream
import java.io.InputStream
import java.io.OutputStream
import java.util.zip.ZipEntry
import java.util.zip.ZipInputStream
import java.util.zip.ZipOutputStream
/**
* Practically usable Dl4j [MultiLayerNetwork] with [NormalizerStandardize] and column labels.
*/
class Dl4jModel(
private val colsX: List<String>,
private val colsY: List<String>,
private val normalizer: NormalizerStandardize?,
private val net: MultiLayerNetwork
) : Model {
private val colsXMap: Map<String, Int> by lazy {
colsX.withIndex().associate { (idx, v) -> Pair(v, idx) }
}
override fun predict(explanatory: Map<String, Any>): Map<String, Double> {
val features = DoubleArray(colsX.size, { 0.0 })
explanatory.forEach { (s, v) ->
if (v is String) {
// categorical, "feature[value]" case, set to 1.0
features[colsXMap["$s[$v]"]!!] = 1.0
} else if (v is Number) {
// numeric case
features[colsXMap[s]!!] = v.toDouble()
} else {
throw RuntimeException("Should be String or Number, got ${v.javaClass}")
}
}
val output = predict(features)
return output.withIndex().associate { (idx, value) -> Pair(colsY[idx], value) }
}
override fun predict(X: DoubleArray): DoubleArray {
val features = Nd4j.create(X)
normalizer?.transform(features)
val output = net.output(features)
assert(output.rows() == 1)
assert(output.columns() == colsY.size)
return DoubleArray(output.columns(), { output.getDouble(it) })
}
/**
* Saves the model into a zip file.
*
* Recommended suffix: ".dl4jmodel.zip"
*/
fun save(outputStream: OutputStream) {
val mapper = ObjectMapper().registerModule(KotlinModule())
val zout = ZipOutputStream(outputStream)
zout.putNextEntry(ZipEntry("colsX.json"))
zout.write(mapper.writeValueAsBytes(colsX))
zout.closeEntry()
zout.putNextEntry(ZipEntry("colsY.json"))
zout.write(mapper.writeValueAsBytes(colsY))
zout.closeEntry()
if (normalizer != null) {
val baosNormalizer = ByteArrayOutputStream()
NormalizerSerializer.getDefault().write(normalizer, baosNormalizer)
zout.putNextEntry(ZipEntry("normalizer.data"))
zout.write(baosNormalizer.toByteArray())
zout.closeEntry()
}
val modelBaos = ByteArrayOutputStream()
ModelSerializer.writeModel(net, modelBaos, true)
zout.putNextEntry(ZipEntry("model.dl4j.zip"))
zout.write(modelBaos.toByteArray())
zout.closeEntry()
zout.close()
}
companion object {
/**
* @param allColumnNames list of all column names, X and Y
* @param colsY list of Y column names
* @param normalizer optional normalizer that was used to train the model
* @param net the trained network
* @return created model
*/
fun build(allColumnNames: List<String>,
colsY: List<String>,
normalizer: NormalizerStandardize?,
net: MultiLayerNetwork): Dl4jModel {
val colsX = allColumnNames.filter { scIt -> !colsY.any { scIt.startsWith("$it[") || scIt == it } }
return Dl4jModel(colsX, colsY, normalizer, net)
}
/**
* @param allColumnNames array of all column names, X and Y
* @param colsY array of Y column names
* @param normalizer optional normalizer that was used to train the model
* @param net the trained network
* @return created model
*/
fun build(allColumnNames: Array<String>,
colsY: Array<String>,
normalizer: NormalizerStandardize?,
net: MultiLayerNetwork): Dl4jModel {
return build(allColumnNames.toList(), colsY.toList(), normalizer, net)
}
/**
* Loads the model from a zip file.
*
* Recommended suffix: ".dl4jmodel.zip"
*/
fun load(inputStream: InputStream): Dl4jModel {
val mapper = ObjectMapper().registerModule(KotlinModule())
var colsX: List<String>? = null
var colsY: List<String>? = null
var normalizer: NormalizerStandardize? = null
var net: MultiLayerNetwork? = null
val zin = ZipInputStream(inputStream)
var entry = zin.nextEntry
while (entry != null) {
val bar = IOUtils.toByteArray(zin)
@Suppress("UNCHECKED_CAST")
when {
entry.name == "colsX.json" -> colsX = mapper.readValue(bar, List::class.java) as List<String>
entry.name == "colsY.json" -> colsY = mapper.readValue(bar, List::class.java) as List<String>
entry.name == "normalizer.data" -> normalizer = NormalizerSerializer.getDefault().restore(ByteArrayInputStream(bar))
entry.name == "model.dl4j.zip" -> net = ModelSerializer.restoreMultiLayerNetwork(ByteArrayInputStream(bar), true)
else -> throw RuntimeException("Unknown entry: ${entry.name}")
}
entry = zin.nextEntry
}
if (colsX == null) throw RuntimeException("Zip file does not have 'colsX.json'")
if (colsY == null) throw RuntimeException("Zip file does not have 'colsY.json'")
if (net == null) throw RuntimeException("Zip file does not have 'model.dl4j.zip'")
return Dl4jModel(
colsX,
colsY,
normalizer,
net)
}
}
} | gpl-3.0 | 8f8488d55de34b89173da8793883fb3d | 37.630303 | 136 | 0.605994 | 4.662034 | false | false | false | false |
deeplearning4j/deeplearning4j | nd4j/samediff-import/samediff-import-onnx/src/main/kotlin/org/nd4j/samediff/frameworkimport/onnx/definitions/implementations/Dropout.kt | 1 | 1865 | package org.nd4j.samediff.frameworkimport.onnx.definitions.implementations
import org.nd4j.autodiff.samediff.SDVariable
import org.nd4j.autodiff.samediff.SameDiff
import org.nd4j.autodiff.samediff.internal.SameDiffOp
import org.nd4j.samediff.frameworkimport.ImportGraph
import org.nd4j.samediff.frameworkimport.hooks.PreImportHook
import org.nd4j.samediff.frameworkimport.hooks.annotations.PreHookRule
import org.nd4j.samediff.frameworkimport.registry.OpMappingRegistry
import org.nd4j.shade.protobuf.GeneratedMessageV3
import org.nd4j.shade.protobuf.ProtocolMessageEnum
/**
* Maps dropout
* @author Adam Gibson
*/
@PreHookRule(nodeNames = [],opNames = ["Dropout"],frameworkName = "onnx")
class Dropout : PreImportHook {
override fun doImport(
sd: SameDiff,
attributes: Map<String, Any>,
outputNames: List<String>,
op: SameDiffOp,
mappingRegistry: OpMappingRegistry<GeneratedMessageV3, GeneratedMessageV3, GeneratedMessageV3, GeneratedMessageV3, ProtocolMessageEnum, GeneratedMessageV3, GeneratedMessageV3>,
importGraph: ImportGraph<GeneratedMessageV3, GeneratedMessageV3, GeneratedMessageV3, GeneratedMessageV3, GeneratedMessageV3, GeneratedMessageV3, ProtocolMessageEnum>,
dynamicVariables: Map<String, GeneratedMessageV3>
): Map<String, List<SDVariable>> {
var inputVariable = sd.getVariable(op.inputsToOp[0])
val p = if(attributes.containsKey("ratio")) {
val fVal = attributes["ratio"] as Float
fVal.toDouble()
} else if(op.inputsToOp.size > 1) {
val dropoutVar = sd.getVariable(op.inputsToOp[1]).arr.getDouble(0)
dropoutVar
} else {
0.5
}
val outputVar = sd.nn().dropout(outputNames[0],inputVariable,true,p)
return mapOf(outputVar.name() to listOf(outputVar))
}
} | apache-2.0 | c490f47f3bde0bc9ceff7ba89ad28a4a | 37.875 | 184 | 0.731903 | 4.17226 | false | false | false | false |
Undin/intellij-rust | src/main/kotlin/org/rust/lang/core/psi/RsPsiTreeChangeListener.kt | 3 | 9444 | /*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.lang.core.psi
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiFile
import com.intellij.psi.PsiTreeChangeEvent
import com.intellij.psi.PsiTreeChangeListener
import com.intellij.psi.impl.PsiTreeChangeEventImpl
import java.util.*
sealed class RsPsiTreeChangeEvent {
/**
* Event can relate to changes in a file system, e.g. file creation/deletion/movement.
* In this case the property is set to null.
*/
open val file: PsiFile? get() = null
sealed class ChildAddition(
override val file: PsiFile?,
val parent: PsiElement
) : RsPsiTreeChangeEvent() {
abstract val child: PsiElement?
class Before(
file: PsiFile?,
parent: PsiElement,
override val child: PsiElement?
) : ChildAddition(file, parent)
class After(
file: PsiFile?,
parent: PsiElement,
override val child: PsiElement
) : ChildAddition(file, parent)
override fun toString(): String =
"ChildAddition.${javaClass.simpleName}(file=$file, parent=`${parent.text}`, child=`${child?.text}`)"
}
sealed class ChildRemoval(
override val file: PsiFile?,
val parent: PsiElement,
/** Invalid in [ChildRemoval.After] */
val child: PsiElement
) : RsPsiTreeChangeEvent() {
class Before(file: PsiFile?, parent: PsiElement, child: PsiElement) : ChildRemoval(file, parent, child)
class After(file: PsiFile?, parent: PsiElement, child: PsiElement) : ChildRemoval(file, parent, child)
override fun toString(): String =
"ChildRemoval.${javaClass.simpleName}(file=$file, parent=`${parent.text}`, child=`${child.safeText}`)"
}
sealed class ChildReplacement(
override val file: PsiFile?,
val parent: PsiElement,
/** Invalid in [ChildReplacement.After] */
val oldChild: PsiElement
) : RsPsiTreeChangeEvent() {
abstract val newChild: PsiElement?
class Before(
file: PsiFile?,
parent: PsiElement,
oldChild: PsiElement,
override val newChild: PsiElement?
) : ChildReplacement(file, parent, oldChild)
class After(
file: PsiFile?,
parent: PsiElement,
oldChild: PsiElement,
override val newChild: PsiElement
) : ChildReplacement(file, parent, oldChild)
override fun toString(): String =
"ChildReplacement.${javaClass.simpleName}(file=$file, parent=`${parent.text}`, " +
"oldChild=`${oldChild.safeText}`, newChild=`${newChild?.text}`)"
}
@Suppress("MemberVisibilityCanBePrivate")
sealed class ChildMovement(
override val file: PsiFile?,
val oldParent: PsiElement,
val newParent: PsiElement,
val child: PsiElement
) : RsPsiTreeChangeEvent() {
class Before(file: PsiFile?, oldParent: PsiElement, newParent: PsiElement, child: PsiElement) : ChildMovement(file, oldParent, newParent, child)
class After(file: PsiFile?, oldParent: PsiElement, newParent: PsiElement, child: PsiElement) : ChildMovement(file, oldParent, newParent, child)
override fun toString(): String =
"ChildMovement.${javaClass.simpleName}(file=$file, oldParent=`${oldParent.text}`, " +
"newParent=`${newParent.text}`, child=`${child.text}`)"
}
sealed class ChildrenChange(
override val file: PsiFile?,
val parent: PsiElement,
/**
* "generic change" event means that "something changed inside an element" and
* sends before/after all events for concrete PSI changes in the element.
*/
val isGenericChange: Boolean
) : RsPsiTreeChangeEvent() {
class Before(file: PsiFile?, parent: PsiElement, isGenericChange: Boolean) : ChildrenChange(file, parent, isGenericChange)
class After(file: PsiFile?, parent: PsiElement, isGenericChange: Boolean) : ChildrenChange(file, parent, isGenericChange)
override fun toString(): String =
"ChildrenChange.${javaClass.simpleName}(file=$file, parent=`${parent.text}`, " +
"isGenericChange=$isGenericChange)"
}
@Suppress("MemberVisibilityCanBePrivate")
sealed class PropertyChange(
val propertyName: String,
val oldValue: Any?,
val newValue: Any?,
val element: PsiElement?,
val child: PsiElement?,
) : RsPsiTreeChangeEvent() {
class Before(
propertyName: String,
oldValue: Any?,
newValue: Any?,
element: PsiElement?,
child: PsiElement?
) : PropertyChange(propertyName, oldValue, newValue, element, child)
class After(
propertyName: String,
oldValue: Any?,
newValue: Any?,
element: PsiElement?,
child: PsiElement?
) : PropertyChange(propertyName, oldValue, newValue, element, child)
override fun toString(): String {
val oldValue = if (oldValue is Array<*>) Arrays.toString(oldValue) else oldValue
val newValue = if (newValue is Array<*>) Arrays.toString(newValue) else newValue
return "PropertyChange.${javaClass.simpleName}(propertyName='$propertyName', " +
"oldValue=$oldValue, newValue=$newValue, element=$element, child=$child)"
}
}
}
abstract class RsPsiTreeChangeAdapter : PsiTreeChangeListener {
abstract fun handleEvent(event: RsPsiTreeChangeEvent)
override fun beforePropertyChange(event: PsiTreeChangeEvent) {
handleEvent(
RsPsiTreeChangeEvent.PropertyChange.Before(
event.propertyName,
event.oldValue,
event.newValue,
event.element,
event.child
)
)
}
override fun propertyChanged(event: PsiTreeChangeEvent) {
handleEvent(
RsPsiTreeChangeEvent.PropertyChange.After(
event.propertyName,
event.oldValue,
event.newValue,
event.element,
event.child
)
)
}
override fun beforeChildReplacement(event: PsiTreeChangeEvent) {
handleEvent(
RsPsiTreeChangeEvent.ChildReplacement.Before(
event.file,
event.parent,
event.oldChild,
event.newChild
)
)
}
override fun childReplaced(event: PsiTreeChangeEvent) {
handleEvent(
RsPsiTreeChangeEvent.ChildReplacement.After(
event.file,
event.parent,
event.oldChild,
event.newChild
)
)
}
override fun beforeChildAddition(event: PsiTreeChangeEvent) {
handleEvent(
RsPsiTreeChangeEvent.ChildAddition.Before(
event.file,
event.parent,
event.child
)
)
}
override fun childAdded(event: PsiTreeChangeEvent) {
handleEvent(
RsPsiTreeChangeEvent.ChildAddition.After(
event.file,
event.parent,
event.child
)
)
}
override fun beforeChildMovement(event: PsiTreeChangeEvent) {
handleEvent(
RsPsiTreeChangeEvent.ChildMovement.Before(
event.file,
event.oldParent,
event.newParent,
event.child
)
)
}
override fun childMoved(event: PsiTreeChangeEvent) {
handleEvent(
RsPsiTreeChangeEvent.ChildMovement.After(
event.file,
event.oldParent,
event.newParent,
event.child
)
)
}
override fun beforeChildRemoval(event: PsiTreeChangeEvent) {
handleEvent(
RsPsiTreeChangeEvent.ChildRemoval.Before(
event.file,
event.parent,
event.child
)
)
}
override fun childRemoved(event: PsiTreeChangeEvent) {
handleEvent(
RsPsiTreeChangeEvent.ChildRemoval.After(
event.file,
event.parent,
event.child
)
)
}
override fun beforeChildrenChange(event: PsiTreeChangeEvent) {
handleEvent(
RsPsiTreeChangeEvent.ChildrenChange.Before(
event.file,
event.parent,
(event as? PsiTreeChangeEventImpl)?.isGenericChange == true
)
)
}
override fun childrenChanged(event: PsiTreeChangeEvent) {
handleEvent(
RsPsiTreeChangeEvent.ChildrenChange.After(
event.file,
event.parent,
(event as? PsiTreeChangeEventImpl)?.isGenericChange == true
)
)
}
}
/**
* It is not safe to call getText() on invalid PSI elements, but sometimes it works,
* so we can try to use it for debug purposes
*/
private val PsiElement.safeText
get() = try {
text
} catch (ignored: Exception) {
"<exception>"
}
| mit | 5e21112395976830cb2e2b1f0342c7aa | 31.122449 | 152 | 0.587886 | 5.481138 | false | false | false | false |
Undin/intellij-rust | src/main/kotlin/org/rust/lang/core/resolve2/DefMapService.kt | 2 | 12436 | /*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.lang.core.resolve2
import com.intellij.injected.editor.VirtualFileWindow
import com.intellij.openapi.Disposable
import com.intellij.openapi.components.Service
import com.intellij.openapi.components.service
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.ModificationTracker
import com.intellij.openapi.vfs.VirtualFileWithId
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiFile
import com.intellij.psi.PsiManager
import com.intellij.psi.PsiTreeChangeEvent
import com.intellij.util.containers.MultiMap
import org.rust.RsTask.TaskType.*
import org.rust.cargo.project.model.CargoProjectsService
import org.rust.cargo.project.model.CargoProjectsService.CargoProjectsListener
import org.rust.lang.core.crate.Crate
import org.rust.lang.core.crate.CratePersistentId
import org.rust.lang.core.macros.MacroExpansionMode
import org.rust.lang.core.macros.macroExpansionManager
import org.rust.lang.core.psi.*
import org.rust.lang.core.psi.RsPsiTreeChangeEvent.*
import org.rust.openapiext.checkWriteAccessAllowed
import org.rust.openapiext.pathAsPath
import org.rust.stdext.mapToSet
import java.lang.ref.WeakReference
import java.nio.file.Path
import java.util.concurrent.ConcurrentHashMap
import java.util.concurrent.ConcurrentMap
import java.util.concurrent.atomic.AtomicInteger
import java.util.concurrent.atomic.AtomicLong
import java.util.concurrent.atomic.AtomicReference
import java.util.concurrent.locks.ReentrantLock
/** Stores [CrateDefMap] and data needed to determine whether [defMap] is up-to-date. */
class DefMapHolder(
val crateId: CratePersistentId,
private val structureModificationTracker: ModificationTracker,
) {
/**
* Write access requires read action with [DefMapService.defMapsBuildLock] or write action.
* Read access requires only read action (needed for fast path in [DefMapService.getOrUpdateIfNeeded]).
*/
@Volatile
var defMap: CrateDefMap? = null
private set
/**
* Value of [rustStructureModificationTracker] at the time when [defMap] started to built.
* Write access requires read action with [DefMapService.defMapsBuildLock] or write action.
* Read access requires only read action (needed for fast path in [DefMapService.getOrUpdateIfNeeded]).
*/
private val defMapStamp: AtomicLong = AtomicLong(-1)
fun hasLatestStamp(): Boolean = defMapStamp.get() == structureModificationTracker.modificationCount
private fun setLatestStamp() {
defMapStamp.set(structureModificationTracker.modificationCount)
}
fun checkHasLatestStamp() {
if (defMap != null && !hasLatestStamp()) {
RESOLVE_LOG.error(
"DefMapHolder must have latest stamp right after DefMap($defMap) was updated. " +
"$defMapStamp vs ${structureModificationTracker.modificationCount}"
)
}
}
val modificationCount: Long get() = defMapStamp.get()
/**
* If true then we should rebuild [defMap], regardless of [shouldRecheck] or [changedFiles] values.
* Any access requires read action with [DefMapService.defMapsBuildLock] or write action.
*/
@Volatile
var shouldRebuild: Boolean = true
set(value) {
field = value
if (value) {
defMapStamp.decrementAndGet()
shouldRecheck = false
changedFiles.clear()
}
}
/**
* If true then we should check for possible modification every file of the crate
* (using [FileInfo.modificationStamp] or [HashCalculator]).
* Any access requires read action with [DefMapService.defMapsBuildLock] or write action.
*/
@Volatile
var shouldRecheck: Boolean = false
set(value) {
field = value
if (value) {
defMapStamp.decrementAndGet()
}
}
/** Any access requires read action with [DefMapService.defMapsBuildLock] or write action. */
val changedFiles: MutableSet<RsFile> = hashSetOf()
fun addChangedFile(file: RsFile) {
changedFiles += file
defMapStamp.decrementAndGet()
}
fun setDefMap(defMap: CrateDefMap?) {
this.defMap = defMap
shouldRebuild = false
setLatestStamp()
}
fun updateShouldRebuild(crate: Crate): Boolean {
val shouldRebuild = getShouldRebuild(crate)
if (shouldRebuild) {
this.shouldRebuild = true
} else {
setLatestStamp()
}
return shouldRebuild
}
override fun toString(): String = "DefMapHolder($defMap, stamp=$defMapStamp)"
}
@Service
class DefMapService(val project: Project) : Disposable {
/** Concurrent because [DefMapsBuilder] uses multiple threads. */
private val defMaps: ConcurrentMap<CratePersistentId, DefMapHolder> = ConcurrentHashMap()
val defMapsBuildLock: ReentrantLock = ReentrantLock()
private val fileIdToCrateId: MultiMap<FileId, CratePersistentId> = MultiMap.createConcurrent()
/** Merged map of [CrateDefMap.missedFiles] for all crates */
private val missedFiles: ConcurrentHashMap<Path, CratePersistentId> = ConcurrentHashMap()
/** Used as an optimization in [removeStaleDefMaps] */
private val lastCheckedTopSortedCrates: AtomicReference<WeakReference<List<Crate>>?> = AtomicReference(null)
private val structureModificationTracker: ModificationTracker =
project.rustPsiManager.rustStructureModificationTracker
/** The last value of [structureModificationTracker] when *all* def maps has been updated */
@Volatile
private var allDefMapsUpdatedStamp: Long = -1
init {
setupListeners()
}
/**
* Possible modifications:
* - After IDE restart: full recheck (for each crate compare [CrateMetaData] and `modificationStamp` of each file).
* Tasks [CARGO_SYNC] and [MACROS_UNPROCESSED] are executed.
* - File changed: calculate hash and compare with hash stored in [CrateDefMap.fileInfos].
* Task [MACROS_FULL] is executed.
* - File added: check whether [missedFiles] contains file path
* - File deleted: check whether [fileIdToCrateId] contains this file
* - Crate workspace changed: full recheck
* Tasks [CARGO_SYNC] and [MACROS_UNPROCESSED] are executed.
*/
private fun setupListeners() {
PsiManager.getInstance(project).addPsiTreeChangeListener(DefMapPsiTreeChangeListener(), this)
val connection = project.messageBus.connect()
project.rustPsiManager.subscribeRustPsiChange(connection, object : RustPsiChangeListener {
override fun rustPsiChanged(file: PsiFile, element: PsiElement, isStructureModification: Boolean) {
/** When macro expansion is enabled, file modification is handled in `ChangedMacroUpdater.rustPsiChanged` */
if (file is RsFile && project.macroExpansionManager.macroExpansionMode !is MacroExpansionMode.New) {
onFileChanged(file)
}
}
})
connection.subscribe(CargoProjectsService.CARGO_PROJECTS_TOPIC, CargoProjectsListener { _, _ ->
scheduleRecheckAllDefMaps()
})
}
fun getDefMapHolder(crate: CratePersistentId): DefMapHolder {
return defMaps.computeIfAbsent(crate) { DefMapHolder(crate, structureModificationTracker) }
}
fun hasDefMapFor(crate: CratePersistentId): Boolean = defMaps[crate] != null
fun setDefMap(crate: CratePersistentId, defMap: CrateDefMap?) {
updateFilesMaps(crate, defMap)
val holder = getDefMapHolder(crate)
holder.setDefMap(defMap)
}
private fun updateFilesMaps(crate: CratePersistentId, defMap: CrateDefMap?) {
fileIdToCrateId.values().removeIf { it == crate }
missedFiles.values.removeIf { it == crate }
if (defMap != null) {
for (fileId in defMap.fileInfos.keys) {
fileIdToCrateId.putValue(fileId, crate)
}
for (missedFile in defMap.missedFiles) {
missedFiles[missedFile] = crate
}
}
}
private fun onFileAdded(file: RsFile) {
checkWriteAccessAllowed()
val path = file.virtualFile.pathAsPath
val crate = missedFiles[path] ?: return
getDefMapHolder(crate).shouldRebuild = true
}
private fun onFileRemoved(file: RsFile) {
checkWriteAccessAllowed()
for (crate in findCrates(file)) {
getDefMapHolder(crate).shouldRebuild = true
}
}
fun onFileChanged(file: RsFile) {
checkWriteAccessAllowed()
for (crate in findCrates(file)) {
getDefMapHolder(crate).addChangedFile(file)
}
}
/** Note: we can't use [RsFile.crate], because it can trigger resolve */
fun findCrates(file: RsFile): Collection<CratePersistentId> {
/** Virtual file can be [VirtualFileWindow] if it is doctest injection */
val virtualFile = file.virtualFile as? VirtualFileWithId ?: return emptyList()
return fileIdToCrateId[virtualFile.id]
}
fun scheduleRebuildAllDefMaps() {
for (defMapHolder in defMaps.values) {
defMapHolder.shouldRebuild = true
}
}
fun scheduleRebuildDefMap(crateId: CratePersistentId) {
val holder = getDefMapHolder(crateId)
holder.shouldRebuild = true
}
private fun scheduleRecheckAllDefMaps() {
checkWriteAccessAllowed()
for (defMapHolder in defMaps.values) {
defMapHolder.shouldRecheck = true
}
}
/** Removes DefMaps for crates not in crate graph */
fun removeStaleDefMaps(allCrates: List<Crate>) {
// Optimization: proceed only if the list of crates has been changed since a previous check. We can compare
// the list by reference because the list is immutable (it refers to `CrateGraphService.topSortedCrates`)
if (lastCheckedTopSortedCrates.getAndSet(WeakReference(allCrates))?.get() === allCrates) return
val allCrateIds = allCrates.mapToSet { it.id }
val staleCrates = hashSetOf<CratePersistentId>()
defMaps.keys.removeIf { crate ->
val isStale = crate !in allCrateIds
if (isStale) staleCrates += crate
isStale
}
fileIdToCrateId.values().removeIf { it in staleCrates }
missedFiles.values.removeIf { it in staleCrates }
}
fun setAllDefMapsUpToDate() {
allDefMapsUpdatedStamp = structureModificationTracker.modificationCount
}
fun areAllDefMapsUpToDate(): Boolean = allDefMapsUpdatedStamp == structureModificationTracker.modificationCount
override fun dispose() {}
private inner class DefMapPsiTreeChangeListener : RsPsiTreeChangeAdapter() {
override fun handleEvent(event: RsPsiTreeChangeEvent) {
// events for file addition/deletion have null `event.file` and not-null `event.child`
if (event.file != null) return
when (event) {
is ChildAddition.After -> {
val file = event.child as? RsFile ?: return
onFileAdded(file)
}
is ChildRemoval.Before -> {
val file = event.child as? RsFile ?: return
onFileRemoved(file)
}
is PropertyChange.Before -> { // before rename
if (event.propertyName == PsiTreeChangeEvent.PROP_FILE_NAME) {
val file = event.child as? RsFile ?: return
onFileRemoved(file)
}
}
is PropertyChange.After -> { // after rename
if (event.propertyName == PsiTreeChangeEvent.PROP_FILE_NAME) {
val file = event.element as? RsFile ?: return
onFileAdded(file)
return
}
}
else -> Unit
}
}
}
companion object {
private val nextNonCargoCrateId: AtomicInteger = AtomicInteger(-1)
fun getNextNonCargoCrateId(): Int = nextNonCargoCrateId.decrementAndGet()
}
}
val Project.defMapService: DefMapService
get() = service()
| mit | 228c390e98f4aa090178af27a6f9a130 | 37.264615 | 124 | 0.667337 | 5.071778 | false | false | false | false |
androidx/androidx | lifecycle/lifecycle-runtime-compose/src/main/java/androidx/lifecycle/compose/FlowExt.kt | 3 | 7968 | /*
* Copyright 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.lifecycle.compose
import androidx.compose.runtime.Composable
import androidx.compose.runtime.State
import androidx.compose.runtime.produceState
import androidx.compose.ui.platform.LocalLifecycleOwner
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.repeatOnLifecycle
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.withContext
import kotlin.coroutines.CoroutineContext
import kotlin.coroutines.EmptyCoroutineContext
/**
* Collects values from this [StateFlow] and represents its latest value via [State] in a
* lifecycle-aware manner.
*
* The [StateFlow.value] is used as an initial value. Every time there would be new value posted
* into the [StateFlow] the returned [State] will be updated causing recomposition of every
* [State.value] usage whenever the [lifecycleOwner]'s lifecycle is at least [minActiveState].
*
* This [StateFlow] is collected every time the [lifecycleOwner]'s lifecycle reaches the
* [minActiveState] Lifecycle state. The collection stops when the [lifecycleOwner]'s lifecycle
* falls below [minActiveState].
*
* @sample androidx.lifecycle.compose.samples.StateFlowCollectAsStateWithLifecycle
*
* Warning: [Lifecycle.State.INITIALIZED] is not allowed in this API. Passing it as a
* parameter will throw an [IllegalArgumentException].
*
* @param lifecycleOwner [LifecycleOwner] whose `lifecycle` is used to restart collecting `this`
* flow.
* @param minActiveState [Lifecycle.State] in which the upstream flow gets collected. The
* collection will stop if the lifecycle falls below that state, and will restart if it's in that
* state again.
* @param context [CoroutineContext] to use for collecting.
*/
@ExperimentalLifecycleComposeApi
@Composable
fun <T> StateFlow<T>.collectAsStateWithLifecycle(
lifecycleOwner: LifecycleOwner = LocalLifecycleOwner.current,
minActiveState: Lifecycle.State = Lifecycle.State.STARTED,
context: CoroutineContext = EmptyCoroutineContext
): State<T> = collectAsStateWithLifecycle(
initialValue = this.value,
lifecycle = lifecycleOwner.lifecycle,
minActiveState = minActiveState,
context = context
)
/**
* Collects values from this [StateFlow] and represents its latest value via [State] in a
* lifecycle-aware manner.
*
* The [StateFlow.value] is used as an initial value. Every time there would be new value posted
* into the [StateFlow] the returned [State] will be updated causing recomposition of every
* [State.value] usage whenever the [lifecycle] is at least [minActiveState].
*
* This [StateFlow] is collected every time [lifecycle] reaches the [minActiveState] Lifecycle
* state. The collection stops when [lifecycle] falls below [minActiveState].
*
* @sample androidx.lifecycle.compose.samples.StateFlowCollectAsStateWithLifecycle
*
* Warning: [Lifecycle.State.INITIALIZED] is not allowed in this API. Passing it as a
* parameter will throw an [IllegalArgumentException].
*
* @param lifecycle [Lifecycle] used to restart collecting `this` flow.
* @param minActiveState [Lifecycle.State] in which the upstream flow gets collected. The
* collection will stop if the lifecycle falls below that state, and will restart if it's in that
* state again.
* @param context [CoroutineContext] to use for collecting.
*/
@ExperimentalLifecycleComposeApi
@Composable
fun <T> StateFlow<T>.collectAsStateWithLifecycle(
lifecycle: Lifecycle,
minActiveState: Lifecycle.State = Lifecycle.State.STARTED,
context: CoroutineContext = EmptyCoroutineContext
): State<T> = collectAsStateWithLifecycle(
initialValue = this.value,
lifecycle = lifecycle,
minActiveState = minActiveState,
context = context
)
/**
* Collects values from this [Flow] and represents its latest value via [State] in a
* lifecycle-aware manner.
*
* Every time there would be new value posted into the [Flow] the returned [State] will be updated
* causing recomposition of every [State.value] usage whenever the [lifecycleOwner]'s lifecycle is
* at least [minActiveState].
*
* This [Flow] is collected every time the [lifecycleOwner]'s lifecycle reaches the [minActiveState]
* Lifecycle state. The collection stops when the [lifecycleOwner]'s lifecycle falls below
* [minActiveState].
*
* @sample androidx.lifecycle.compose.samples.FlowCollectAsStateWithLifecycle
*
* Warning: [Lifecycle.State.INITIALIZED] is not allowed in this API. Passing it as a
* parameter will throw an [IllegalArgumentException].
*
* @param initialValue The initial value given to the returned [State.value].
* @param lifecycleOwner [LifecycleOwner] whose `lifecycle` is used to restart collecting `this`
* flow.
* @param minActiveState [Lifecycle.State] in which the upstream flow gets collected. The
* collection will stop if the lifecycle falls below that state, and will restart if it's in that
* state again.
* @param context [CoroutineContext] to use for collecting.
*/
@ExperimentalLifecycleComposeApi
@Composable
fun <T> Flow<T>.collectAsStateWithLifecycle(
initialValue: T,
lifecycleOwner: LifecycleOwner = LocalLifecycleOwner.current,
minActiveState: Lifecycle.State = Lifecycle.State.STARTED,
context: CoroutineContext = EmptyCoroutineContext
): State<T> = collectAsStateWithLifecycle(
initialValue = initialValue,
lifecycle = lifecycleOwner.lifecycle,
minActiveState = minActiveState,
context = context
)
/**
* Collects values from this [Flow] and represents its latest value via [State] in a
* lifecycle-aware manner.
*
* Every time there would be new value posted into the [Flow] the returned [State] will be updated
* causing recomposition of every [State.value] usage whenever the [lifecycle] is at
* least [minActiveState].
*
* This [Flow] is collected every time [lifecycle] reaches the [minActiveState] Lifecycle
* state. The collection stops when [lifecycle] falls below [minActiveState].
*
* @sample androidx.lifecycle.compose.samples.FlowCollectAsStateWithLifecycle
*
* Warning: [Lifecycle.State.INITIALIZED] is not allowed in this API. Passing it as a
* parameter will throw an [IllegalArgumentException].
*
* @param initialValue The initial value given to the returned [State.value].
* @param lifecycle [Lifecycle] used to restart collecting `this` flow.
* @param minActiveState [Lifecycle.State] in which the upstream flow gets collected. The
* collection will stop if the lifecycle falls below that state, and will restart if it's in that
* state again.
* @param context [CoroutineContext] to use for collecting.
*/
@ExperimentalLifecycleComposeApi
@Composable
fun <T> Flow<T>.collectAsStateWithLifecycle(
initialValue: T,
lifecycle: Lifecycle,
minActiveState: Lifecycle.State = Lifecycle.State.STARTED,
context: CoroutineContext = EmptyCoroutineContext
): State<T> {
return produceState(initialValue, this, lifecycle, minActiveState, context) {
lifecycle.repeatOnLifecycle(minActiveState) {
if (context == EmptyCoroutineContext) {
[email protected] { [email protected] = it }
} else withContext(context) {
[email protected] { [email protected] = it }
}
}
}
}
| apache-2.0 | ca91a4d81df86a167a8ca249d5f1bdeb | 42.540984 | 100 | 0.763052 | 4.695345 | false | false | false | false |
brianwernick/ExoMedia | library/src/main/kotlin/com/devbrackets/android/exomedia/nmp/manager/track/TrackManager.kt | 1 | 8061 | package com.devbrackets.android.exomedia.nmp.manager.track
import android.content.Context
import android.util.ArrayMap
import androidx.media3.common.C
import androidx.media3.common.TrackGroup
import com.devbrackets.android.exomedia.core.renderer.RendererType
import androidx.media3.exoplayer.source.TrackGroupArray
import androidx.media3.exoplayer.trackselection.AdaptiveTrackSelection
import androidx.media3.exoplayer.trackselection.DefaultTrackSelector
import androidx.media3.exoplayer.trackselection.MappingTrackSelector
import java.util.ArrayList
/**
* Handles managing the tracks for the [CorePlayer]
*/
class TrackManager(context: Context) {
private val selectionFactory: AdaptiveTrackSelection.Factory = AdaptiveTrackSelection.Factory()
val selector: DefaultTrackSelector = DefaultTrackSelector(context, selectionFactory)
/**
* Retrieves a list of available tracks
*
* @return A list of available tracks associated with each type
*/
@Suppress("FoldInitializerAndIfToElvis")
fun getAvailableTracks(): Map<RendererType, TrackGroupArray>? {
val mappedTrackInfo = selector.currentMappedTrackInfo
if (mappedTrackInfo == null) {
return null
}
val trackMap = ArrayMap<RendererType, TrackGroupArray>()
RendererType.values().forEach { type ->
val trackGroups = ArrayList<TrackGroup>()
for (exoPlayerTrackIndex in getExoPlayerTracksInfo(type, 0, mappedTrackInfo).indexes) {
val trackGroupArray = mappedTrackInfo.getTrackGroups(exoPlayerTrackIndex)
for (i in 0 until trackGroupArray.length) {
trackGroups.add(trackGroupArray.get(i))
}
}
if (trackGroups.isNotEmpty()) {
trackMap[type] = TrackGroupArray(*trackGroups.toTypedArray())
}
}
return trackMap
}
fun getExoPlayerTracksInfo(type: RendererType, groupIndex: Int, mappedTrackInfo: MappingTrackSelector.MappedTrackInfo?): RendererTrackInfo {
if (mappedTrackInfo == null) {
return RendererTrackInfo(emptyList(), C.INDEX_UNSET, C.INDEX_UNSET)
}
// holder for the all exo player renderer track indexes of the specified renderer type
val rendererTrackIndexes = ArrayList<Int>()
var rendererTrackIndex = C.INDEX_UNSET
// the corrected exoplayer group index
var rendererTrackGroupIndex = C.INDEX_UNSET
var skippedRenderersGroupsCount = 0
for (rendererIndex in 0 until mappedTrackInfo.rendererCount) {
if (type.exoPlayerTrackType != mappedTrackInfo.getRendererType(rendererIndex)) {
continue
}
rendererTrackIndexes.add(rendererIndex)
val trackGroups = mappedTrackInfo.getTrackGroups(rendererIndex)
if (skippedRenderersGroupsCount + trackGroups.length <= groupIndex) {
skippedRenderersGroupsCount += trackGroups.length
continue
}
// if the groupIndex belongs to the current exo player renderer
if (rendererTrackIndex == C.INDEX_UNSET) {
rendererTrackIndex = rendererIndex
rendererTrackGroupIndex = groupIndex - skippedRenderersGroupsCount
}
}
return RendererTrackInfo(rendererTrackIndexes, rendererTrackIndex, rendererTrackGroupIndex)
}
@JvmOverloads
fun getSelectedTrackIndex(type: RendererType, groupIndex: Int = 0): Int {
// Retrieves the available tracks
val mappedTrackInfo = selector.currentMappedTrackInfo
val tracksInfo = getExoPlayerTracksInfo(type, groupIndex, mappedTrackInfo)
if (tracksInfo.index == C.INDEX_UNSET) {
return -1
}
val trackGroupArray = mappedTrackInfo!!.getTrackGroups(tracksInfo.index)
if (trackGroupArray.length == 0) {
return -1
}
// Verifies the track selection has been overridden
val selectionOverride = selector.parameters.getSelectionOverride(tracksInfo.index, trackGroupArray)
if (selectionOverride == null || selectionOverride.groupIndex != tracksInfo.groupIndex || selectionOverride.length <= 0) {
return -1
}
// In the current implementation only one track can be selected at a time so get the first one.
return selectionOverride.tracks[0]
}
fun setSelectedTrack(type: RendererType, groupIndex: Int, trackIndex: Int) {
// Retrieves the available tracks
val mappedTrackInfo = selector.currentMappedTrackInfo
val tracksInfo = getExoPlayerTracksInfo(type, groupIndex, mappedTrackInfo)
if (tracksInfo.index == C.INDEX_UNSET || mappedTrackInfo == null) {
return
}
val trackGroupArray = mappedTrackInfo.getTrackGroups(tracksInfo.index)
if (trackGroupArray.length == 0 || trackGroupArray.length <= tracksInfo.groupIndex) {
return
}
// Finds the requested group
val group = trackGroupArray.get(tracksInfo.groupIndex)
if (group.length <= trackIndex) {
return
}
val parametersBuilder = selector.buildUponParameters()
for (rendererTrackIndex in tracksInfo.indexes) {
parametersBuilder.clearSelectionOverrides(rendererTrackIndex)
// Disable renderers of the same type to prevent playback errors
if (tracksInfo.index != rendererTrackIndex) {
parametersBuilder.setRendererDisabled(rendererTrackIndex, true)
continue
}
// Specifies the correct track to use
parametersBuilder.setSelectionOverride(rendererTrackIndex, trackGroupArray,
DefaultTrackSelector.SelectionOverride(tracksInfo.groupIndex, trackIndex))
// make sure renderer is enabled
parametersBuilder.setRendererDisabled(rendererTrackIndex, false)
}
selector.setParameters(parametersBuilder)
}
/**
* Clear all selected tracks for the specified renderer and re-enable all renderers so the player can select the default track.
*
* @param type The renderer type
*/
fun clearSelectedTracks(type: RendererType) {
// Retrieves the available tracks
val mappedTrackInfo = selector.currentMappedTrackInfo
val tracksInfo = getExoPlayerTracksInfo(type, 0, mappedTrackInfo)
val parametersBuilder = selector.buildUponParameters()
for (rendererTrackIndex in tracksInfo.indexes) {
// Reset all renderers re-enabling so the player can select the streams default track.
parametersBuilder.setRendererDisabled(rendererTrackIndex, false)
.clearSelectionOverrides(rendererTrackIndex)
}
selector.setParameters(parametersBuilder)
}
fun setRendererEnabled(type: RendererType, enabled: Boolean) {
val mappedTrackInfo = selector.currentMappedTrackInfo
val tracksInfo = getExoPlayerTracksInfo(type, 0, mappedTrackInfo)
if (tracksInfo.indexes.isEmpty()) {
return
}
var enabledSomething = false
val parametersBuilder = selector.buildUponParameters()
for (rendererTrackIndex in tracksInfo.indexes) {
if (!enabled) {
parametersBuilder.setRendererDisabled(rendererTrackIndex, true)
continue
}
val selectionOverride = selector.parameters.getSelectionOverride(rendererTrackIndex, mappedTrackInfo!!.getTrackGroups(rendererTrackIndex))
// check whether the renderer has been selected before
// other renderers should be kept disabled to avoid playback errors
if (selectionOverride != null) {
parametersBuilder.setRendererDisabled(rendererTrackIndex, false)
enabledSomething = true
}
}
if (enabled && !enabledSomething) {
// if nothing has been enabled enable the first sequential renderer
parametersBuilder.setRendererDisabled(tracksInfo.indexes[0], false)
}
selector.setParameters(parametersBuilder)
}
/**
* Return true if at least one renderer for the given type is enabled
* @param type The renderer type
* @return true if at least one renderer for the given type is enabled
*/
fun isRendererEnabled(type: RendererType): Boolean {
val mappedTrackInfo = selector.currentMappedTrackInfo
val tracksInfo = getExoPlayerTracksInfo(type, 0, mappedTrackInfo)
val parameters = selector.parameters
return tracksInfo.indexes.any {
!parameters.getRendererDisabled(it)
}
}
} | apache-2.0 | deb654c40af6fc7327d03b1d17cd9442 | 35.645455 | 144 | 0.737874 | 5.366844 | false | false | false | false |
noemus/kotlin-eclipse | kotlin-eclipse-ui/src/org/jetbrains/kotlin/ui/editors/navigation/navigationUtils.kt | 1 | 17608 | /*******************************************************************************
* Copyright 2000-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*******************************************************************************/
package org.jetbrains.kotlin.ui.editors.navigation
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.psi.PsiClass
import com.intellij.psi.PsiElement
import com.intellij.psi.util.PsiTreeUtil
import org.eclipse.core.resources.IFile
import org.eclipse.core.resources.IProject
import org.eclipse.core.resources.ResourcesPlugin
import org.eclipse.core.runtime.IPath
import org.eclipse.core.runtime.Path
import org.eclipse.jdt.core.IClassFile
import org.eclipse.jdt.core.IJavaProject
import org.eclipse.jdt.core.IPackageFragment
import org.eclipse.jdt.core.dom.IBinding
import org.eclipse.jdt.core.dom.IMethodBinding
import org.eclipse.jdt.internal.compiler.classfmt.ClassFileReader
import org.eclipse.jdt.internal.core.SourceMapper
import org.eclipse.jdt.internal.ui.javaeditor.EditorUtility
import org.eclipse.jdt.ui.JavaUI
import org.eclipse.jface.util.OpenStrategy
import org.eclipse.ui.IEditorPart
import org.eclipse.ui.IReusableEditor
import org.eclipse.ui.IStorageEditorInput
import org.eclipse.ui.PlatformUI
import org.eclipse.ui.ide.IDE
import org.eclipse.ui.texteditor.AbstractTextEditor
import org.jetbrains.kotlin.core.KotlinClasspathContainer
import org.jetbrains.kotlin.core.log.KotlinLogger
import org.jetbrains.kotlin.core.model.KotlinNature
import org.jetbrains.kotlin.core.resolve.EclipseDescriptorUtils
import org.jetbrains.kotlin.core.resolve.KotlinSourceIndex
import org.jetbrains.kotlin.core.resolve.lang.java.resolver.EclipseJavaSourceElement
import org.jetbrains.kotlin.core.resolve.lang.java.structure.EclipseJavaElement
import org.jetbrains.kotlin.core.utils.ProjectUtils
import org.jetbrains.kotlin.descriptors.DeclarationDescriptor
import org.jetbrains.kotlin.descriptors.SourceElement
import org.jetbrains.kotlin.eclipse.ui.utils.EditorUtil
import org.jetbrains.kotlin.eclipse.ui.utils.LineEndUtil
import org.jetbrains.kotlin.eclipse.ui.utils.getTextDocumentOffset
import org.jetbrains.kotlin.load.java.sources.JavaSourceElement
import org.jetbrains.kotlin.load.java.structure.JavaElement
import org.jetbrains.kotlin.load.java.structure.impl.JavaElementImpl
import org.jetbrains.kotlin.load.kotlin.KotlinJvmBinaryClass
import org.jetbrains.kotlin.load.kotlin.KotlinJvmBinaryPackageSourceElement
import org.jetbrains.kotlin.load.kotlin.KotlinJvmBinarySourceElement
import org.jetbrains.kotlin.load.kotlin.VirtualFileKotlinClass
import org.jetbrains.kotlin.load.kotlin.header.KotlinClassHeader
import org.jetbrains.kotlin.name.Name
import org.jetbrains.kotlin.psi.KtElement
import org.jetbrains.kotlin.psi.KtFile
import org.jetbrains.kotlin.psi.KtPsiFactory
import org.jetbrains.kotlin.resolve.source.KotlinSourceElement
import org.jetbrains.kotlin.resolve.source.PsiSourceElement
import org.jetbrains.kotlin.serialization.deserialization.descriptors.DeserializedCallableMemberDescriptor
import org.jetbrains.kotlin.ui.editors.KotlinEditor
import org.jetbrains.kotlin.ui.editors.KotlinExternalReadOnlyEditor
import org.jetbrains.kotlin.ui.editors.KotlinScriptEditor
import org.jetbrains.kotlin.ui.editors.getScriptDependencies
import org.jetbrains.kotlin.ui.formatter.createKtFile
import org.jetbrains.kotlin.ui.navigation.KotlinOpenEditor
private val KOTLIN_SOURCE_PATH = Path(ProjectUtils.buildLibPath(KotlinClasspathContainer.LIB_RUNTIME_SRC_NAME))
private val RUNTIME_SOURCE_MAPPER = KOTLIN_SOURCE_PATH.createSourceMapperWithRoot()
fun gotoElement(descriptor: DeclarationDescriptor, fromElement: KtElement,
fromEditor: KotlinEditor, javaProject: IJavaProject) {
val elementWithSource = getElementWithSource(descriptor, javaProject.project)
if (elementWithSource != null) gotoElement(elementWithSource, descriptor, fromElement, fromEditor, javaProject)
}
fun getElementWithSource(descriptor: DeclarationDescriptor, project: IProject): SourceElement? {
val sourceElements = EclipseDescriptorUtils.descriptorToDeclarations(descriptor, project)
return sourceElements.find { element -> element != SourceElement.NO_SOURCE }
}
fun gotoElement(
element: SourceElement,
descriptor: DeclarationDescriptor,
fromElement: KtElement,
fromEditor: KotlinEditor,
project: IJavaProject) {
when (element) {
is EclipseJavaSourceElement -> {
val binding = (element.javaElement as EclipseJavaElement<*>).binding
gotoJavaDeclaration(binding)
}
is KotlinSourceElement -> gotoKotlinDeclaration(element.psi, fromElement, fromEditor, project)
is KotlinJvmBinarySourceElement -> gotoElementInBinaryClass(element.binaryClass, descriptor, fromElement, project)
is KotlinJvmBinaryPackageSourceElement -> gotoClassByPackageSourceElement(element, fromElement, descriptor, project)
is PsiSourceElement -> {
if (element is JavaSourceElement) {
gotoJavaDeclarationFromNonClassPath(element.javaElement, element.psi, fromEditor, project)
}
}
}
}
private fun gotoJavaDeclarationFromNonClassPath(
javaElement: JavaElement,
psi: PsiElement?,
fromEditor: KotlinEditor,
javaProject: IJavaProject) {
if (!fromEditor.isScript) return
val javaPsi = (javaElement as JavaElementImpl<*>).psi
val editorPart = tryToFindSourceInJavaProject(javaPsi, javaProject)
if (editorPart != null) {
revealJavaElementInEditor(editorPart, javaElement, EditorUtil.getSourceCode(editorPart))
return
}
val virtualFile = psi?.containingFile?.virtualFile ?: return
val (sourceName, packagePath) = findSourceFilePath(virtualFile)
val dependencies = getScriptDependencies(fromEditor as KotlinScriptEditor) ?: return
val pathToSource = packagePath.append(sourceName)
val source = dependencies.sources.asSequence()
.map { Path(it.absolutePath).createSourceMapperWithRoot() }
.mapNotNull { it.findSource(pathToSource.toOSString()) }
.firstOrNull() ?: return
val sourceString = String(source)
val targetEditor = openJavaEditorForExternalFile(sourceString, sourceName, packagePath.toOSString()) ?: return
revealJavaElementInEditor(targetEditor, javaElement, sourceString)
return
}
private fun revealJavaElementInEditor(editor: IEditorPart, javaElement: JavaElement, source: String) {
val offset = findDeclarationInJavaFile(javaElement, source)
if (offset != null && editor is AbstractTextEditor) {
editor.selectAndReveal(offset, 0)
}
}
private fun getClassFile(binaryClass: VirtualFileKotlinClass, javaProject: IJavaProject): IClassFile? {
val file = binaryClass.file
val fragment = javaProject.findPackageFragment(pathFromUrlInArchive(file.parent.path))
return fragment?.getClassFile(file.name)
}
private fun findImplementingClassInClasspath(
binaryClass: VirtualFileKotlinClass,
descriptor: DeclarationDescriptor,
javaProject: IJavaProject): IClassFile? {
return if (KotlinClassHeader.Kind.MULTIFILE_CLASS == binaryClass.classHeader.kind)
getImplementingFacadePart(binaryClass, descriptor, javaProject)
else
getClassFile(binaryClass, javaProject)
}
private fun getImplementingFacadePart(
binaryClass: VirtualFileKotlinClass,
descriptor: DeclarationDescriptor,
javaProject: IJavaProject): IClassFile? {
if (descriptor !is DeserializedCallableMemberDescriptor) return null
val className = getImplClassName(descriptor)
if (className == null) {
KotlinLogger.logWarning("Class file with implementation of $descriptor is null")
return null
}
val classFile = getClassFile(binaryClass, javaProject)
if (classFile == null) {
KotlinLogger.logWarning("Class file for $binaryClass is null")
return null
}
val fragment = classFile.getParent() as IPackageFragment
val file = fragment.getClassFile(className.asString() + ".class")
return if (file.exists()) file else null
}
//implemented via Reflection because Eclipse has issues with ProGuard-shrunken compiler
//in com.google.protobuf.GeneratedMessageLite.ExtendableMessage
private fun getImplClassName(memberDescriptor: DeserializedCallableMemberDescriptor): Name? {
val nameIndex: Int
try
{
val getProtoMethod = DeserializedCallableMemberDescriptor::class.java.getMethod("getProto")
val proto = getProtoMethod!!.invoke(memberDescriptor)
val implClassNameField = Class.forName("org.jetbrains.kotlin.serialization.jvm.JvmProtoBuf").getField("implClassName")
val implClassName = implClassNameField!!.get(null)
val protobufCallable = Class.forName("org.jetbrains.kotlin.serialization.ProtoBuf\$Callable")
val getExtensionMethod = protobufCallable!!.getMethod("getExtension", implClassName!!.javaClass)
val indexObj = getExtensionMethod!!.invoke(proto, implClassName)
if (indexObj !is Int) return null
nameIndex = indexObj.toInt()
} catch (e: ReflectiveOperationException) {
KotlinLogger.logAndThrow(e)
return null
} catch (e: IllegalArgumentException) {
KotlinLogger.logAndThrow(e)
return null
} catch (e: SecurityException) {
KotlinLogger.logAndThrow(e)
return null
}
return memberDescriptor.nameResolver.getName(nameIndex)
}
private fun gotoClassByPackageSourceElement(
sourceElement: KotlinJvmBinaryPackageSourceElement,
fromElement: KtElement,
descriptor: DeclarationDescriptor,
javaProject: IJavaProject) {
if (descriptor !is DeserializedCallableMemberDescriptor) return
val binaryClass = sourceElement.getContainingBinaryClass(descriptor)
if (binaryClass == null) {
KotlinLogger.logWarning("Containing binary class for $sourceElement is null")
return
}
gotoElementInBinaryClass(binaryClass, descriptor, fromElement, javaProject)
}
private fun gotoElementInBinaryClass(
binaryClass: KotlinJvmBinaryClass,
descriptor: DeclarationDescriptor,
fromElement: KtElement,
javaProject: IJavaProject) {
if (binaryClass !is VirtualFileKotlinClass) return
val classFile = findImplementingClassInClasspath(binaryClass, descriptor, javaProject)
val targetEditor = if (classFile != null) {
KotlinOpenEditor.openKotlinClassFileEditor(classFile, OpenStrategy.activateOnOpen())
} else {
tryToFindExternalClassInStdlib(binaryClass, fromElement, javaProject)
}
if (targetEditor !is KotlinEditor) return
val targetKtFile = targetEditor.parsedFile ?: return
val offset = findDeclarationInParsedFile(descriptor, targetKtFile)
val start = LineEndUtil.convertLfToDocumentOffset(targetKtFile.getText(), offset, targetEditor.document)
targetEditor.javaEditor.selectAndReveal(start, 0)
}
private fun gotoKotlinDeclaration(element: PsiElement, fromElement: KtElement, fromEditor: KotlinEditor, javaProject: IJavaProject) {
val targetEditor = findEditorForReferencedElement(element, fromElement, fromEditor, javaProject)
if (targetEditor !is KotlinEditor) return
val start = element.getTextDocumentOffset(targetEditor.document)
targetEditor.selectAndReveal(start, 0)
}
private fun tryToFindExternalClassInStdlib(
binaryClass: VirtualFileKotlinClass,
fromElement: KtElement,
javaProject: IJavaProject): IEditorPart? {
if (KotlinNature.hasKotlinNature(javaProject.project)) {
// If project has Kotlin nature, then search in stdlib should be done earlier by searching class in the classpath
return null
}
val (name, pckg, source) = findSourceForElementInStdlib(binaryClass) ?: return null
val content = String(source)
val ktFile = createKtFile(content, KtPsiFactory(fromElement), "dummy.kt")
return openKotlinEditorForExternalFile(content, name, pckg, ktFile)
}
private fun findSourceForElementInStdlib(binaryClass: VirtualFileKotlinClass): ExternalSourceFile? {
val (sourceName, packagePath) = findSourceFilePath(binaryClass.file)
val source = KotlinSourceIndex.getSource(RUNTIME_SOURCE_MAPPER, sourceName, packagePath, KOTLIN_SOURCE_PATH)
return if (source != null) ExternalSourceFile(sourceName, packagePath.toPortableString(), source) else null
}
private data class ExternalSourceFile(val name: String, val packageFqName: String, val source: CharArray)
private fun findEditorForReferencedElement(
element: PsiElement,
fromElement: KtElement,
fromEditor: KotlinEditor,
javaProject: IJavaProject): AbstractTextEditor? {
// if element is in the same file
if (fromElement.getContainingFile() == element.getContainingFile()) {
return fromEditor.javaEditor
}
val virtualFile = element.getContainingFile().getVirtualFile()
if (virtualFile == null) return null
val filePath = virtualFile.path
val targetFile = ResourcesPlugin.getWorkspace().root.getFileForLocation(Path(filePath)) ?: getAcrhivedFileFromPath(filePath)
return findEditorPart(targetFile, element, javaProject) as? AbstractTextEditor
}
private fun gotoJavaDeclaration(binding: IBinding) {
val javaElement = if (binding is IMethodBinding && binding.isConstructor())
binding.getDeclaringClass().getJavaElement() // because <init>() may correspond to null java element
else
binding.javaElement
if (javaElement != null) {
val editorPart = EditorUtility.openInEditor(javaElement, OpenStrategy.activateOnOpen())
JavaUI.revealInEditor(editorPart, javaElement)
}
}
private fun findSourceFilePath(virtualFile: VirtualFile): Pair<String, IPath> {
val reader = ClassFileReader(virtualFile.contentsToByteArray(), virtualFile.name.toCharArray())
val sourceName = String(reader.sourceFileName())
val fileNameWithPackage = Path(String(reader.getName()))
val packagePath = fileNameWithPackage.removeLastSegments(1)
return Pair(sourceName, packagePath)
}
private fun findEditorPart(
targetFile: IFile,
element: PsiElement,
javaProject: IJavaProject): IEditorPart? {
if (targetFile.exists()) return openInEditor(targetFile)
val editor = tryToFindSourceInJavaProject(element, javaProject)
if (editor != null) {
return editor
}
//external jar
if (targetFile.getFullPath().toOSString().contains("jar")) {
val elementFile = element.getContainingFile()
if (elementFile == null) return null
val directory = elementFile.getContainingDirectory()
return openKotlinEditorForExternalFile(
elementFile.text,
elementFile.name,
getFqNameInsideArchive(directory.toString()),
elementFile as KtFile)
}
return null
}
private fun tryToFindSourceInJavaProject(element: PsiElement, javaProject: IJavaProject): AbstractTextEditor? {
val psiClass = PsiTreeUtil.getParentOfType(element, PsiClass::class.java, false) ?: return null
val targetType = javaProject.findType(psiClass.getQualifiedName()) ?: return null
return EditorUtility.openInEditor(targetType, true) as? AbstractTextEditor?
}
private fun openKotlinEditorForExternalFile(
sourceText: String,
sourceName: String,
packageFqName: String,
ktFile: KtFile): IEditorPart? {
val storage = StringStorage(sourceText, sourceName, packageFqName)
val input = KotlinExternalEditorInput(ktFile, storage)
return openEditorForExternalFile(input, KotlinExternalReadOnlyEditor.EDITOR_ID)
}
private fun openJavaEditorForExternalFile(
sourceText: String,
sourceName: String,
packageFqName: String): IEditorPart? {
val storage = StringStorage(sourceText, sourceName, packageFqName)
val input = StringInput(storage)
return openEditorForExternalFile(input, JavaUI.ID_CU_EDITOR)
}
private fun openEditorForExternalFile(storageInput: IStorageEditorInput, editorId: String): IEditorPart? {
val page = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage()
if (page == null) return null
val reusedEditor = page.findEditor(storageInput)
if (reusedEditor != null) {
page.reuseEditor(reusedEditor as IReusableEditor?, storageInput)
}
return page.openEditor(storageInput, editorId)
}
private fun openInEditor(file: IFile): IEditorPart {
val page = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage()
return IDE.openEditor(page, file, false)
}
private fun IPath.createSourceMapperWithRoot(): SourceMapper = SourceMapper(this, "", emptyMap<Any, Any>()) | apache-2.0 | 655efafcd27b1cba9eb4466296c0fdcc | 41.126794 | 133 | 0.745286 | 4.955812 | false | false | false | false |
pedpess/aurinkoapp | app/src/main/java/com/ppes/aurinkoapp/data/db/Tables.kt | 1 | 440 | package com.ppes.aurinkoapp.data.db
/**
* Created by ppes on 03/09/2017.
*/
object CityForecastTable {
val NAME = "CityForecast"
val ID = "_id"
val CITY = "city"
val COUNTRY = "country"
}
object DayForecastTable {
val NAME = "DayForecast"
val ID = "_id"
val DATE = "date"
val DESCRIPTION = "description"
val HIGH = "high"
val LOW = "low"
val ICON_URL = "iconUrl"
val CITY_ID = "cityId"
} | apache-2.0 | bdda9216df4bfd9d4187caf5e3300a6b | 18.173913 | 35 | 0.602273 | 3.259259 | false | false | false | false |
minjaesong/TerranVirtualDisk | src/net/torvald/terrarum/modulecomputers/virtualcomputer/tvd/finder/Popups.kt | 1 | 2983 | package net.torvald.terrarum.modulecomputers.virtualcomputer.tvd.finder
import java.awt.BorderLayout
import java.awt.GridLayout
import javax.swing.*
/**
* Created by SKYHi14 on 2017-04-01.
*/
object Popups {
val okCancel = arrayOf("OK", "Cancel")
}
class OptionDiskNameAndCap {
val name = JTextField(11)
val capacity = JSpinner(SpinnerNumberModel(
368640L.toJavaLong(),
0L.toJavaLong(),
(1L shl 38).toJavaLong(),
1L.toJavaLong()
)) // default 360 KiB, MAX 256 GiB
val mainPanel = JPanel()
val settingPanel = JPanel()
init {
mainPanel.layout = BorderLayout()
settingPanel.layout = GridLayout(2, 2, 2, 0)
//name.text = "Unnamed"
settingPanel.add(JLabel("Name (max 32 bytes)"))
settingPanel.add(name)
settingPanel.add(JLabel("Capacity (bytes)"))
settingPanel.add(capacity)
mainPanel.add(settingPanel, BorderLayout.CENTER)
mainPanel.add(JLabel("Set capacity to 0 to make the disk read-only"), BorderLayout.SOUTH)
}
/**
* returns either JOptionPane.OK_OPTION or JOptionPane.CANCEL_OPTION
*/
fun showDialog(title: String): Int {
return JOptionPane.showConfirmDialog(null, mainPanel,
title, JOptionPane.OK_CANCEL_OPTION)
}
}
fun kotlin.Long.toJavaLong() = java.lang.Long(this)
class OptionFileNameAndCap {
val name = JTextField(11)
val capacity = JSpinner(SpinnerNumberModel(
4096L.toJavaLong(),
0L.toJavaLong(),
((1L shl 48) - 1L).toJavaLong(),
1L.toJavaLong()
)) // default 360 KiB, MAX 256 TiB
val mainPanel = JPanel()
val settingPanel = JPanel()
init {
mainPanel.layout = BorderLayout()
settingPanel.layout = GridLayout(2, 2, 2, 0)
//name.text = "Unnamed"
settingPanel.add(JLabel("Name (max 32 bytes)"))
settingPanel.add(name)
settingPanel.add(JLabel("Capacity (bytes)"))
settingPanel.add(capacity)
mainPanel.add(settingPanel, BorderLayout.CENTER)
}
/**
* returns either JOptionPane.OK_OPTION or JOptionPane.CANCEL_OPTION
*/
fun showDialog(title: String): Int {
return JOptionPane.showConfirmDialog(null, mainPanel,
title, JOptionPane.OK_CANCEL_OPTION)
}
}
class OptionSize {
val capacity = JSpinner(SpinnerNumberModel(
368640L.toJavaLong(),
0L.toJavaLong(),
(1L shl 38).toJavaLong(),
1L.toJavaLong()
)) // default 360 KiB, MAX 256 GiB
val settingPanel = JPanel()
init {
settingPanel.add(JLabel("Size (bytes)"))
settingPanel.add(capacity)
}
/**
* returns either JOptionPane.OK_OPTION or JOptionPane.CANCEL_OPTION
*/
fun showDialog(title: String): Int {
return JOptionPane.showConfirmDialog(null, settingPanel,
title, JOptionPane.OK_CANCEL_OPTION)
}
}
| mit | fa421ba0284b10fdac56569fac372c6e | 26.878505 | 97 | 0.623198 | 4.28592 | false | false | false | false |
CruGlobal/android-gto-support | buildSrc/src/main/kotlin/AndroidConfiguration.kt | 1 | 3041 | import com.android.build.api.dsl.CommonExtension
import com.android.build.gradle.BaseExtension
import com.android.build.gradle.LibraryExtension
import org.gradle.api.JavaVersion
import org.gradle.api.Project
import org.gradle.api.plugins.ExtensionAware
import org.gradle.kotlin.dsl.configure
import org.gradle.kotlin.dsl.findByType
import org.jetbrains.kotlin.gradle.dsl.KotlinJvmOptions
fun Project.configureAndroidLibrary() {
extensions.configure<LibraryExtension> {
baseConfiguration(project)
}
}
fun Project.configureAndroidTestingLibrary() {
extensions.configure<LibraryExtension> {
baseConfiguration(project)
}
overridePublishingGroupForTestFixtureProject()
}
// TODO: provide Project using the new multiple context receivers functionality.
// this is prototyped in 1.6.20 and will probably reach beta in Kotlin 1.8 or 1.9
//context(Project)
fun LibraryExtension.baseConfiguration(project: Project) {
configureSdk()
configureProguardRules(project)
configureCompilerOptions()
configureTestOptions()
project.configureKotlinKover()
project.configurePublishing()
}
private fun BaseExtension.configureSdk() {
compileSdkVersion(33)
defaultConfig {
minSdk = 21
targetSdk = 33
}
}
private fun BaseExtension.configureProguardRules(project: Project) {
defaultConfig.consumerProguardFiles(project.rootProject.file("proguard-consumer-jetbrains.pro"))
}
private fun BaseExtension.configureCompilerOptions() {
compileOptions {
sourceCompatibility = JavaVersion.VERSION_1_8
targetCompatibility = JavaVersion.VERSION_1_8
}
(this as ExtensionAware).extensions.findByType<KotlinJvmOptions>()?.apply {
jvmTarget = JavaVersion.VERSION_1_8.toString()
freeCompilerArgs += "-Xjvm-default=all"
}
}
// TODO: provide Project using the new multiple context receivers functionality.
// this is prototyped in 1.6.20 and will probably reach beta in Kotlin 1.8 or 1.9
//context(Project)
fun CommonExtension<*, *, *, *>.configureCompose(project: Project) {
buildFeatures.compose = true
composeOptions.kotlinCompilerExtensionVersion =
project.libs.findVersion("androidx-compose-compiler").get().requiredVersion
project.dependencies.apply {
// the runtime dependency is required to build a library when compose is enabled
addProvider("implementation", project.libs.findLibrary("androidx-compose-runtime").get())
// these dependencies are required for tests of Composables
addProvider("debugImplementation", project.libs.findBundle("androidx-compose-debug").get())
addProvider("testDebugImplementation", project.libs.findBundle("androidx-compose-testing").get())
}
}
private fun BaseExtension.configureTestOptions() {
testOptions {
unitTests {
isIncludeAndroidResources = true
all {
// increase unit tests max heap size
it.jvmArgs("-Xmx2g")
}
}
}
}
| mit | 917be28bf6b1f46af2f5ac1684533299 | 32.788889 | 105 | 0.727721 | 4.671275 | false | true | false | false |
kilel/jotter | snt-ui-javafx/src/main/kotlin/org/github/snt/ui/javafx/lib/UIUtils.kt | 1 | 4415 | /*
* Copyright 2018 Kislitsyn Ilya
*
* 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.github.snt.ui.javafx.lib
import com.sun.javafx.scene.control.skin.TextAreaSkin
import javafx.scene.Node
import javafx.scene.Scene
import javafx.scene.control.*
import javafx.scene.input.KeyCode
import javafx.scene.input.KeyEvent
import javafx.scene.layout.Background
import javafx.scene.layout.GridPane
import javafx.scene.layout.Priority
import javafx.stage.Stage
import org.github.snt.lib.err.SntException
import org.github.snt.lib.err.SntResult.GENERAL_ERROR
import org.github.snt.lib.util.extractStackTrace
fun initWindow(stage: Stage, call: Stage.() -> Unit) {
stage.call()
}
fun changeScene(scene: Scene, targetScene: StatefulScene) {
val stage = scene.window as Stage
stage.scene = targetScene.scene
stage.sizeToScene()
}
fun closeScene(scene: Scene) {
val stage = scene.window as Stage
stage.close()
}
fun showError(error: Throwable) {
val cause = error as? SntException ?: SntException(GENERAL_ERROR, error)
val alert = Alert(Alert.AlertType.ERROR)
alert.title = "Application error"
alert.headerText = "Error - ${cause.result}"
alert.contentText = cause.message
alert.dialogPane.expandableContent = buildDialogInfoArea("Stacktrace:", cause.extractStackTrace())
alert.showAndWait()
}
fun requestConfirm(text: String): Boolean {
val alert = Alert(Alert.AlertType.CONFIRMATION)
alert.title = "Confirmation required"
alert.headerText = text
return alert.showAndWait().orElse(ButtonType.CANCEL) == ButtonType.OK
}
fun buildDialogInfoArea(header: String, data: String): GridPane {
val label = Label(header)
val textArea = TextArea(data)
textArea.isEditable = false
textArea.isWrapText = true
textArea.maxWidth = java.lang.Double.MAX_VALUE
textArea.maxHeight = java.lang.Double.MAX_VALUE
GridPane.setVgrow(textArea, Priority.ALWAYS)
GridPane.setHgrow(textArea, Priority.ALWAYS)
val content = GridPane()
content.maxWidth = java.lang.Double.MAX_VALUE
content.add(label, 0, 0)
content.add(textArea, 0, 1)
return content
}
fun newLabel(text: String = "", isUnderlined: Boolean = false): Label {
val result = Label(text)
result.isWrapText = true
result.isUnderline = isUnderlined
return result
}
fun newTextField(text: String = "", id: String? = null, isEditable: Boolean = true): Node {
if (!isEditable) {
return Label(text)
}
val result = TextField()
result.text = text
result.id = id
return result
}
fun newPasswordField(text: String = "", id: String? = null, isEditable: Boolean = true): Node {
if (!isEditable) {
// TODO add context menu to copy value to the buffer
return Label("******")
}
val result = PasswordField()
result.text = text
result.id = id
return result
}
/**
* Creates text area with correct behavior.
* @param text Text to fill area with
* @param id Area ID
* @return Correct text area
*/
fun newTextArea(text: String = "", id: String? = null, isEditable: Boolean = true, background: Background? = null): Node {
// if (!isEditable) {
// return newLabel(text)
// }
val result = TextArea(text)
result.id = id
result.isWrapText = true
if (background != null) {
result.background = background
}
if (!isEditable) {
result.isEditable = false
}
result.addEventHandler(KeyEvent.KEY_PRESSED) { event ->
val source = event.source as TextArea
val skin = source.skin as TextAreaSkin
if (event.code == KeyCode.TAB && !event.isControlDown) {
if (event.isShiftDown) {
skin.behavior.traversePrevious()
} else {
skin.behavior.traverseNext()
}
event.consume()
}
}
return result
}
| apache-2.0 | 68286f19cc5e1b962f427c7369a8b8cd | 26.59375 | 122 | 0.682673 | 3.959641 | false | false | false | false |
EmmyLua/IntelliJ-EmmyLua | src/main/java/com/tang/intellij/lua/codeInsight/LuaParameterHintsProvider.kt | 2 | 5208 | /*
* Copyright (c) 2017. tangzx([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.tang.intellij.lua.codeInsight
import com.intellij.codeInsight.hints.HintInfo
import com.intellij.codeInsight.hints.InlayInfo
import com.intellij.codeInsight.hints.InlayParameterHintsProvider
import com.intellij.codeInsight.hints.Option
import com.intellij.psi.PsiElement
import com.intellij.psi.util.PsiTreeUtil
import com.tang.intellij.lua.psi.*
import com.tang.intellij.lua.search.SearchContext
import com.tang.intellij.lua.ty.*
import java.util.*
/**
* Created by TangZX on 2016/12/14.
*/
class LuaParameterHintsProvider : InlayParameterHintsProvider {
companion object {
private val ARGS_HINT = Option("lua.hints.show_args_type",
"Show argument name hints",
true)
private val LOCAL_VARIABLE_HINT = Option("lua.hints.show_local_var_type",
"Show local variable type hints",
false)
private val PARAMETER_TYPE_HINT = Option("lua.hints.show_parameter_type",
"Show parameter type hints",
false)
private val FUNCTION_HINT = Option("lua.hints.show_function_type",
"Show function return type hints",
false)
private const val TYPE_INFO_PREFIX = "@TYPE@"
private var EXPR_HINT = arrayOf(LuaLiteralExpr::class.java,
LuaBinaryExpr::class.java,
LuaUnaryExpr::class.java,
LuaClosureExpr::class.java,
LuaTableExpr::class.java)
}
override fun getParameterHints(psi: PsiElement): List<InlayInfo> {
val list = ArrayList<InlayInfo>()
if (psi is LuaCallExpr) {
if (!ARGS_HINT.get())
return list
@Suppress("UnnecessaryVariable")
val callExpr = psi
val args = callExpr.args as? LuaListArgs ?: return list
val exprList = args.exprList
val context = SearchContext.get(callExpr.getProject())
val type = callExpr.guessParentType(context)
val ty = TyUnion.find(type, ITyFunction::class.java) ?: return list
// 是否是 inst:method() 被用为 inst.method(self) 形式
val isInstanceMethodUsedAsStaticMethod = ty.isColonCall && callExpr.isMethodDotCall
val sig = ty.findPerfectSignature(callExpr)
sig.processArgs(null, callExpr.isMethodColonCall) { index, paramInfo ->
val expr = exprList.getOrNull(index) ?: return@processArgs false
val show =
if (index == 0 && isInstanceMethodUsedAsStaticMethod) {
true
} else PsiTreeUtil.instanceOf(expr, *EXPR_HINT)
if (show)
list.add(InlayInfo(paramInfo.name, expr.node.startOffset))
true
}
}
else if (psi is LuaParamNameDef) {
if (PARAMETER_TYPE_HINT.get()) {
val type = psi.guessType(SearchContext.get(psi.project))
if (!Ty.isInvalid(type)) {
return listOf(InlayInfo("$TYPE_INFO_PREFIX${type.displayName}", psi.textOffset + psi.textLength))
}
}
}
else if (psi is LuaNameDef) {
if (LOCAL_VARIABLE_HINT.get()) {
val type = psi.guessType(SearchContext.get(psi.project))
if (!Ty.isInvalid(type)) {
return listOf(InlayInfo("$TYPE_INFO_PREFIX${type.displayName}", psi.textOffset + psi.textLength))
}
}
}
else if (psi is LuaFuncBodyOwner) {
val paren = psi.funcBody?.rparen
if (FUNCTION_HINT.get() && paren != null) {
val type = psi.guessReturnType(SearchContext.get(psi.project))
if (!Ty.isInvalid(type)) {
return listOf(InlayInfo("$TYPE_INFO_PREFIX${type.displayName}", paren.textOffset + paren.textLength))
}
}
}
return list
}
override fun getHintInfo(psiElement: PsiElement): HintInfo? = null
override fun getDefaultBlackList(): Set<String> {
return HashSet()
}
override fun isBlackListSupported() = false
override fun getSupportedOptions(): List<Option> {
return listOf(ARGS_HINT, LOCAL_VARIABLE_HINT, PARAMETER_TYPE_HINT, FUNCTION_HINT)
}
override fun getInlayPresentation(inlayText: String): String {
if (inlayText.startsWith(TYPE_INFO_PREFIX)) {
return " : ${inlayText.substring(TYPE_INFO_PREFIX.length)}"
}
return "$inlayText : "
}
}
| apache-2.0 | b00934de375c432ff3da81e6ddaf9455 | 38.333333 | 121 | 0.613636 | 4.522648 | false | false | false | false |
ohmae/DmsExplorer | mobile/src/main/java/net/mm2d/dmsexplorer/domain/tabs/CustomTabsHelper.kt | 1 | 4494 | /*
* Copyright (c) 2018 大前良介 (OHMAE Ryosuke)
*
* This software is released under the MIT License.
* http://opensource.org/licenses/MIT
*/
package net.mm2d.dmsexplorer.domain.tabs
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.net.Uri
import androidx.browser.customtabs.*
import androidx.core.os.bundleOf
import java.util.*
/**
* @author [大前良介 (OHMAE Ryosuke)](mailto:[email protected])
*/
class CustomTabsHelper(
private val context: Context
) : CustomTabsServiceConnection() {
private var bound: Boolean = false
var session: CustomTabsSession? = null
private set
internal fun bind() {
if (!bound) {
val packageName = findPackageNameToUse(context) ?: return
bound = CustomTabsClient.bindCustomTabsService(context, packageName, this)
}
}
internal fun unbind() {
if (bound) {
context.unbindService(this)
bound = false
session = null
}
}
fun mayLaunchUrl(url: String) {
session?.mayLaunchUrl(Uri.parse(url), null, null)
}
fun mayLaunchUrl(urls: List<String>) {
val session = session ?: return
if (urls.isEmpty()) {
return
}
try {
if (urls.size == 1) {
session.mayLaunchUrl(Uri.parse(urls[0]), null, null)
return
}
val otherLikelyBundles = urls.subList(1, urls.size).map {
bundleOf(CustomTabsService.KEY_URL to Uri.parse(it))
}
session.mayLaunchUrl(Uri.parse(urls[0]), null, otherLikelyBundles)
} catch (ignored: Exception) {
unbind()
}
}
override fun onCustomTabsServiceConnected(
name: ComponentName,
client: CustomTabsClient
) {
try {
client.warmup(0)
session = client.newSession(CustomTabsCallback())
} catch (ignored: Exception) {
unbind()
}
}
override fun onServiceDisconnected(name: ComponentName) {
session = null
}
companion object {
private val PREFERRED_PACKAGES = listOf(
"com.android.chrome", // Chrome
"com.chrome.beta", // Chrome Beta
"com.chrome.dev", // Chrome Dev
"com.chrome.canary" // Chrome Canary
)
private const val ACTION_CUSTOM_TABS_CONNECTION =
"android.support.customtabs.action.CustomTabsService"
private const val EXTRA_CUSTOM_TABS_KEEP_ALIVE =
"android.support.customtabs.extra.KEEP_ALIVE"
var packageNameToBind: String? = null
private set
fun addKeepAliveExtra(
context: Context,
intent: Intent
) {
val keepAliveIntent = Intent().setClassName(
context.packageName, KeepAliveService::class.java.canonicalName!!
)
intent.putExtra(EXTRA_CUSTOM_TABS_KEEP_ALIVE, keepAliveIntent)
}
private fun findPackageNameToUse(context: Context): String? {
packageNameToBind = findPackageNameToUseInner(context)
return packageNameToBind
}
private fun findPackageNameToUseInner(context: Context): String? {
val pm = context.packageManager
val browsers = OpenUriUtils.getBrowserPackages(context)
val services = pm.queryIntentServices(Intent(ACTION_CUSTOM_TABS_CONNECTION), 0)
val candidate = ArrayList<String>()
for (service in services) {
if (service.serviceInfo == null) {
continue
}
val packageName = service.serviceInfo.packageName
if (browsers.contains(packageName)) {
candidate.add(packageName)
}
}
if (candidate.isEmpty()) {
return null
}
if (candidate.size == 1) {
return candidate[0]
}
val defaultBrowser = OpenUriUtils.getDefaultBrowserPackage(context)
if (candidate.contains(defaultBrowser)) {
return defaultBrowser
}
for (packageName in PREFERRED_PACKAGES) {
if (candidate.contains(packageName)) {
return packageName
}
}
return null
}
}
}
| mit | 87b8de062cdea5f9c3fd285465a7f498 | 30.097222 | 91 | 0.572577 | 4.959025 | false | false | false | false |
naosim/RPGSample | app/src/main/kotlin/com/naosim/rpgmodel/android/sirokuro/DataSaveRepositoryAndroidImpl.kt | 1 | 2366 | package com.naosim.rpgmodel.android.sirokuro
import android.content.SharedPreferences
import com.naosim.rpglib.model.value.ItemId
import com.naosim.rpglib.model.value.ItemSet
import com.naosim.rpglib.model.value.field.FieldNameImpl
import com.naosim.rpglib.model.value.field.Position
import com.naosim.rpglib.model.value.field.X
import com.naosim.rpglib.model.value.field.Y
import com.naosim.rpgmodel.sirokuro.charactor.GameItem
import com.naosim.rpgmodel.sirokuro.charactor.getGameItem
import com.naosim.rpgmodel.sirokuro.global.DataSaveContainer
import com.naosim.rpgmodel.sirokuro.global.DataSaveRepository
import com.naosim.rpgmodel.sirokuro.global.Status
import com.naosim.rpgmodel.sirokuro.global.Turn
import com.naosim.rpgmodel.sirokuro.map.YagiFieldName
class DataSaveRepositoryAndroidImpl(val sharedPreferences: SharedPreferences): DataSaveRepository {
override fun load(): DataSaveContainer {
val itemSet = ItemSet<GameItem>()
val itemCsv = sharedPreferences.getString("itemCsv", "${GameItem.やくそう.itemId.value}")
itemCsv
.split(",")
.filter { it.trim().length > 0 }
.map { getGameItem(ItemId(it)) }
.forEach { itemSet.add(it) }
val status = Status()
val turnString = sharedPreferences.getString("turn", "kuro_eat")
status.turnValue.setValue(Turn.valueOf(turnString))
val position = Position(
FieldNameImpl(sharedPreferences.getString("fieldName", YagiFieldName.main.value)),
X(sharedPreferences.getInt("x", 0)),
Y(sharedPreferences.getInt("y", 0))
)
return DataSaveContainer(status, itemSet, position)
}
override fun save(dataSaveContainer: DataSaveContainer) {
val editor = sharedPreferences.edit()
editor.putString("turn", dataSaveContainer.status.turnValue.getValueString())
val itemCsv = dataSaveContainer
.itemSet
.list
.map({ it.itemId.value })
.joinToString(",")
editor.putString("itemCsv", itemCsv)
editor.putString("fieldName", dataSaveContainer.position.fieldName.value)
editor.putInt("x", dataSaveContainer.position.x.value)
editor.putInt("y", dataSaveContainer.position.y.value)
editor.commit()
}
}
| mit | d12c851732ba2c7b7d4c5f933b715e76 | 39.655172 | 99 | 0.694232 | 4.3829 | false | false | false | false |
ShadwLink/Shadow-Mapper | src/main/java/nl/shadowlink/tools/shadowlib/paths/Node.kt | 1 | 1271 | package nl.shadowlink.tools.shadowlib.paths
import nl.shadowlink.tools.io.ReadFunctions
/**
* @author Shadow-Link
*/
class Node(rf: ReadFunctions) {
val memAdress = rf.readInt()
val zero = rf.readInt()
val areaID = rf.readShort()
val nodeID = rf.readShort()
val unknown = rf.readInt()
val always7FFE = rf.readShort()
val linkID = rf.readShort()
val posX = rf.readShort()
val posY = rf.readShort()
val posZ = rf.readShort()
val pathWidth = rf.readByte()
val pathType = rf.readByte()
val flags = rf.readInt()
override fun toString(): String {
return StringBuilder("--------------Node---------------")
.append("Mem Adress: $memAdress")
.append("Zero: $zero")
.append("AreaID: $areaID")
.append("NodeID: $nodeID")
.append("unknown: $unknown")
.append("Always7FFE: $always7FFE")
.append("LinkID: $linkID")
.append("PosX: " + (posX / 8).toFloat())
.append("PosY: " + (posY / 8).toFloat())
.append("PosZ: " + (posZ / 128).toFloat())
.append("PathWidth: $pathWidth")
.append("PathType: $pathType")
.append("Flags: $flags")
.toString()
}
} | gpl-2.0 | 900ae81a8c5664643f6cfc30b0743fff | 30.8 | 65 | 0.546027 | 3.816817 | false | false | false | false |
kesmarag/megaptera | src/main/org/kesmarag/megaptera/kmeans/Kmeans.kt | 1 | 2685 | package org.kesmarag.megaptera.kmeans
import org.kesmarag.megaptera.data.DataSet
import org.kesmarag.megaptera.data.Observation
import org.kesmarag.megaptera.utils.Owner
import java.io.Serializable
class Kmeans(val dataSet: DataSet, val clusters: Int = 3, id: Int = 0) : Owner(id), Serializable {
public var centroids: Array<DoubleArray> = Array(clusters, { DoubleArray(dataSet.observationLength) })
private set
private var observationList: List<Observation> = dataSet.members
.filter { isOwned(it) }
.flatMap { it.data.toList() }
private var changes = 0
init {
adapt()
//display()
}
public fun adapt() {
observationList.forEach { it.redistribute(clusters, 0) }
var step: Int = 0
do {
step++
var sum = Array(clusters, { DoubleArray(dataSet.observationLength) })
var L = IntArray(clusters)
changes = 0
observationList.forEach {
L[it.ownerID]++
for (n in 0..dataSet.observationLength - 1) {
centroids[it.ownerID][n] += it.data[n]
}
}
centroids.forEachIndexed { i, it ->
for (n in 0..dataSet.observationLength - 1) {
centroids[i][n] /= (L[i].toDouble() + 1)
}
}
for (i in 0..observationList.size - 1) {
var pos: Int = 0
var min: Double = dist(observationList[i].data, centroids[0])
for (k in 1..clusters - 1) {
if (dist(observationList[i].data, centroids[k]) < min) {
min = dist(observationList[i].data, centroids[k])
pos = k
}
}
if (observationList[i].ownerID != pos ) {
changes++
observationList[i].forceSetOwner(pos)
}
for (n in 0..dataSet.observationLength - 1) {
sum[pos][n] += observationList[i].data[n]
}
L[pos]++
}
} while (changes > 0 && step <= 100)
}
public fun dist(a1: DoubleArray, a2: DoubleArray): Double {
var s: Double = 0.0
for (n in 0..a1.size - 1) {
s += (a1[n] - a2[n]) * (a1[n] - a2[n])
}
return s
}
public fun display(): Unit {
println("==> centroids <==")
centroids.forEach {
for (n in 0..dataSet.observationLength - 1) {
print(it[n])
print(" ")
}
println()
}
}
} | apache-2.0 | c78e84533f31023981122706020fd9cf | 31.756098 | 106 | 0.486406 | 4.215071 | false | false | false | false |
MaTriXy/material-dialogs | core/src/main/java/com/afollestad/materialdialogs/utils/Colors.kt | 2 | 1588 | /**
* Designed and developed by Aidan Follestad (@afollestad)
*
* 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.afollestad.materialdialogs.utils
import android.graphics.Color
import androidx.annotation.AttrRes
import androidx.annotation.CheckResult
import androidx.annotation.ColorInt
import androidx.annotation.ColorRes
import com.afollestad.materialdialogs.MaterialDialog
import com.afollestad.materialdialogs.utils.MDUtil.resolveColor
import com.afollestad.materialdialogs.utils.MDUtil.resolveColors
@ColorInt @CheckResult
internal fun MaterialDialog.resolveColor(
@ColorRes res: Int? = null,
@AttrRes attr: Int? = null,
fallback: (() -> Int)? = null
): Int = resolveColor(windowContext, res, attr, fallback)
@CheckResult
internal fun MaterialDialog.resolveColors(
attrs: IntArray,
fallback: ((forAttr: Int) -> Int)? = null
) = resolveColors(windowContext, attrs, fallback)
@ColorInt @CheckResult
internal fun Int.adjustAlpha(alpha: Float): Int {
return Color.argb((255 * alpha).toInt(), Color.red(this), Color.green(this), Color.blue(this))
}
| apache-2.0 | 078fdaa8159c128a9355cbf73c79cf25 | 35.930233 | 96 | 0.768892 | 4.212202 | false | false | false | false |
Maccimo/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/refactoring/move/changePackage/KotlinChangePackageRefactoring.kt | 2 | 2561 | // 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.refactoring.move.changePackage
import com.intellij.refactoring.RefactoringBundle
import org.jetbrains.kotlin.idea.base.util.quoteIfNeeded
import org.jetbrains.kotlin.idea.KotlinBundle
import org.jetbrains.kotlin.idea.codeInsight.shorten.performDelayedRefactoringRequests
import org.jetbrains.kotlin.idea.core.util.runSynchronouslyWithProgress
import org.jetbrains.kotlin.idea.refactoring.move.ContainerChangeInfo
import org.jetbrains.kotlin.idea.refactoring.move.ContainerInfo
import org.jetbrains.kotlin.idea.refactoring.move.getInternalReferencesToUpdateOnPackageNameChange
import org.jetbrains.kotlin.idea.refactoring.move.moveDeclarations.*
import org.jetbrains.kotlin.idea.refactoring.move.postProcessMoveUsages
import org.jetbrains.kotlin.idea.util.application.executeWriteCommand
import org.jetbrains.kotlin.idea.util.application.runReadAction
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.psi.KtFile
class KotlinChangePackageRefactoring(val file: KtFile) {
private val project = file.project
fun run(newFqName: FqName) {
val packageDirective = file.packageDirective ?: return
val currentFqName = packageDirective.fqName
val declarationProcessor = MoveKotlinDeclarationsProcessor(
MoveDeclarationsDescriptor(
project = project,
moveSource = MoveSource(file),
moveTarget = KotlinDirectoryMoveTarget(newFqName, file.containingDirectory!!.virtualFile),
delegate = MoveDeclarationsDelegate.TopLevel
)
)
val declarationUsages = project.runSynchronouslyWithProgress(RefactoringBundle.message("progress.text"), true) {
runReadAction {
declarationProcessor.findUsages().toList()
}
} ?: return
val changeInfo = ContainerChangeInfo(ContainerInfo.Package(currentFqName), ContainerInfo.Package(newFqName))
val internalUsages = file.getInternalReferencesToUpdateOnPackageNameChange(changeInfo)
project.executeWriteCommand(KotlinBundle.message("text.change.file.package.to.0", newFqName)) {
packageDirective.fqName = newFqName.quoteIfNeeded()
postProcessMoveUsages(internalUsages)
performDelayedRefactoringRequests(project)
declarationProcessor.execute(declarationUsages)
}
}
}
| apache-2.0 | cdfa0440e064039a3846ca2401e773f1 | 49.215686 | 158 | 0.762983 | 5.368973 | false | false | false | false |
bajdcc/jMiniLang | src/main/kotlin/com/bajdcc/LALR1/interpret/module/web/ModuleNetWebContext.kt | 1 | 4592 | package com.bajdcc.LALR1.interpret.module.web
import com.bajdcc.LALR1.grammar.runtime.RuntimeObject
import com.bajdcc.LALR1.grammar.runtime.data.RuntimeMap
import java.net.MalformedURLException
import java.net.URL
import java.nio.channels.SelectionKey
import java.util.concurrent.Semaphore
import java.util.regex.Pattern
/**
* 【模块】请求上下文
*
* @author bajdcc
*/
class ModuleNetWebContext(val key: SelectionKey) {
private var sem: Semaphore? = null // 多线程同步只能用信号量
private var header: String? = null
var response = ""
var mime = "html-utf8"
var code = 200
var contentType = 0
private var method: String? = null
private var uri: String? = null
private var protocol: String? = null
private var version: String? = null
var url: String? = null
private set
private val mapReqHeaders = mutableMapOf<String, String>()
private val mapRespHeaders = mutableMapOf<String, String>()
/**
* 请求的结构:
* headers(map), method, uri, protocol, version
* @return HTTP请求
*/
val reqHeader: RuntimeMap
get() {
val req = RuntimeMap()
val headers = RuntimeMap()
mapReqHeaders.forEach { key, value -> headers.put(key, RuntimeObject(value)) }
req.put("headers", RuntimeObject(headers))
req.put("method", RuntimeObject(method))
req.put("uri", RuntimeObject(uri))
req.put("version", RuntimeObject(version))
req.put("protocol", RuntimeObject(protocol!!.toLowerCase()))
req.put("url", RuntimeObject(url))
try {
val u = URL(url!!)
req.put("port", RuntimeObject(u.port.toLong()))
req.put("host", RuntimeObject(u.host))
req.put("path", RuntimeObject(u.path))
req.put("query", RuntimeObject(u.query))
req.put("authority", RuntimeObject(u.authority))
val idx = u.path.lastIndexOf(".")
if (idx >= 0) {
val postfix = u.path.substring(idx + 1)
req.put("ext", RuntimeObject(postfix))
}
} catch (e: MalformedURLException) {
e.printStackTrace()
}
return req
}
var respHeader: RuntimeMap
get() {
val resp = RuntimeMap()
mapRespHeaders.forEach { key, value -> resp.put(key, RuntimeObject(value)) }
return resp
}
set(map) = map.getMap().forEach { key, value -> mapRespHeaders[key] = value.obj.toString() }
val respHeaderMap: Map<String, String>
get() = mapRespHeaders
val respText: String
get() = String.format("%s/%s %d %s", protocol, version, code, ModuleNetWebHelper.getStatusCodeText(code))
val mimeString: String
get() = ModuleNetWebHelper.getMimeByExtension(mime)
fun setReqHeader(header: String) {
this.header = header
initHeader()
}
fun getReqHeaderValue(key: String): String {
return mapReqHeaders.getOrDefault(key, "")
}
fun getRespHeaderValue(key: String): String {
return mapRespHeaders.getOrDefault(key, "")
}
private fun initHeader() {
val re1 = Pattern.compile("([A-Z]+) ([^ ]+) ([A-Z]+)/(\\d\\.\\d)")
val headers = header!!.split("\r\n".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()
for (i in 1 until headers.size) {
val colon = headers[i].indexOf(':')
if (colon != -1) {
val key = headers[i].substring(0, colon)
val value = headers[i].substring(colon + 1)
mapReqHeaders[key.trim { it <= ' ' }] = value.trim { it <= ' ' }
}
}
val m = re1.matcher(headers[0])
if (m.find()) {
method = m.group(1).trim { it <= ' ' }
uri = m.group(2).trim { it <= ' ' }
protocol = m.group(3).trim { it <= ' ' }
version = m.group(4).trim { it <= ' ' }
url = String.format("%s://%s%s", protocol!!.toLowerCase(), mapReqHeaders.getOrDefault("Host", "unknown"), uri)
}
mapRespHeaders["Server"] = "jMiniLang Server"
}
fun block(): Semaphore {
sem = Semaphore(0)
return sem!!
}
fun unblock() {
try {
while (sem == null) {
Thread.sleep(100)
}
} catch (e: InterruptedException) {
e.printStackTrace()
}
sem!!.release()
}
}
| mit | fab2dd92d2d314d094188cdd48e2ba9c | 32.109489 | 122 | 0.555776 | 4.192237 | false | false | false | false |
PolymerLabs/arcs | javatests/arcs/showcase/nullable/Attending.kt | 1 | 728 | @file:Suppress("EXPERIMENTAL_FEATURE_WARNING", "EXPERIMENTAL_API_USAGE")
package arcs.showcase.nullable
import arcs.jvm.host.TargetHost
@TargetHost(arcs.android.integration.IntegrationHost::class)
class Attending : AbstractAttending() {
override fun onReady() {
handles.attending.storeAll(
handles.invited.fetchAll().filter { it.rsvp == true }.map {
// Nulls can be propagated
Guest(name = it.name, employee_id = it.employee_id, rsvp = it.rsvp)
}
)
handles.no_response.storeAll(
// Nulls can be read & filtered on
handles.invited.fetchAll().filter { it.rsvp == null }.map {
Guest(name = it.name, employee_id = it.employee_id, rsvp = it.rsvp)
}
)
}
}
| bsd-3-clause | 0425cbf1f148b44d955d08d30a9861b2 | 29.333333 | 75 | 0.662088 | 3.586207 | false | false | false | false |
Maccimo/intellij-community | plugins/package-search/src/com/jetbrains/packagesearch/intellij/plugin/ui/toolwindow/panels/management/packages/columns/renderers/PopupMenuListItemCellRenderer.kt | 4 | 3395 | /*******************************************************************************
* Copyright 2000-2022 JetBrains s.r.o. and contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
package com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.panels.management.packages.columns.renderers
import com.intellij.ide.ui.AntialiasingType
import com.intellij.util.ui.EmptyIcon
import com.intellij.util.ui.GraphicsUtil
import com.jetbrains.packagesearch.PackageSearchIcons
import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.panels.management.packages.columns.TableColors
import java.awt.Component
import javax.accessibility.AccessibleContext
import javax.accessibility.AccessibleRole
import javax.accessibility.AccessibleState
import javax.accessibility.AccessibleStateSet
import javax.swing.DefaultListCellRenderer
import javax.swing.JLabel
import javax.swing.JList
internal class PopupMenuListItemCellRenderer<T>(
private val selectedValue: T?,
private val colors: TableColors,
private val itemLabelRenderer: (T) -> String = { it.toString() }
) : DefaultListCellRenderer() {
private val selectedIcon = PackageSearchIcons.Checkmark
private val emptyIcon = EmptyIcon.create(selectedIcon.iconWidth)
private var currentItemIsSelected = false
override fun getListCellRendererComponent(list: JList<*>, value: Any, index: Int, isSelected: Boolean, cellHasFocus: Boolean): Component {
@Suppress("UNCHECKED_CAST") // It's ok to crash if this isn't true
val item = value as T
val itemLabel = itemLabelRenderer(item) + " " // The spaces are to compensate for the lack of padding in the label (yes, I know, it's a hack)
val label = super.getListCellRendererComponent(list, itemLabel, index, isSelected, cellHasFocus) as JLabel
label.font = list.font
colors.applyTo(label, isSelected)
currentItemIsSelected = item === selectedValue
label.icon = if (currentItemIsSelected) selectedIcon else emptyIcon
GraphicsUtil.setAntialiasingType(label, AntialiasingType.getAAHintForSwingComponent())
return label
}
override fun getAccessibleContext(): AccessibleContext {
if (accessibleContext == null) {
accessibleContext = AccessibleRenderer(currentItemIsSelected)
}
return accessibleContext
}
private inner class AccessibleRenderer(
private val isSelected: Boolean
) : AccessibleJLabel() {
override fun getAccessibleRole(): AccessibleRole = AccessibleRole.CHECK_BOX
override fun getAccessibleStateSet(): AccessibleStateSet {
val set = super.getAccessibleStateSet()
if (isSelected) {
set.add(AccessibleState.CHECKED)
}
return set
}
}
}
| apache-2.0 | 06e877e1ab238c5e4a8b1dcdb274edec | 40.91358 | 149 | 0.704271 | 5.167428 | false | false | false | false |
JetBrains/ideavim | src/main/java/com/maddyhome/idea/vim/action/VimShortcutKeyAction.kt | 1 | 14267 | /*
* 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.action
import com.google.common.collect.ImmutableSet
import com.intellij.codeInsight.lookup.LookupManager
import com.intellij.openapi.actionSystem.ActionManager
import com.intellij.openapi.actionSystem.ActionUpdateThread
import com.intellij.openapi.actionSystem.AnAction
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.actionSystem.EmptyAction
import com.intellij.openapi.actionSystem.PlatformDataKeys
import com.intellij.openapi.application.invokeLater
import com.intellij.openapi.diagnostic.debug
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.progress.ProcessCanceledException
import com.intellij.openapi.project.DumbAware
import com.intellij.openapi.util.Key
import com.intellij.ui.KeyStrokeAdapter
import com.maddyhome.idea.vim.KeyHandler
import com.maddyhome.idea.vim.VimPlugin
import com.maddyhome.idea.vim.api.injector
import com.maddyhome.idea.vim.helper.EditorDataContext
import com.maddyhome.idea.vim.helper.EditorHelper
import com.maddyhome.idea.vim.helper.HandlerInjector
import com.maddyhome.idea.vim.helper.inInsertMode
import com.maddyhome.idea.vim.helper.inNormalMode
import com.maddyhome.idea.vim.helper.isIdeaVimDisabledHere
import com.maddyhome.idea.vim.helper.isPrimaryEditor
import com.maddyhome.idea.vim.helper.isTemplateActive
import com.maddyhome.idea.vim.helper.updateCaretsVisualAttributes
import com.maddyhome.idea.vim.key.ShortcutOwner
import com.maddyhome.idea.vim.key.ShortcutOwnerInfo
import com.maddyhome.idea.vim.listener.AceJumpService
import com.maddyhome.idea.vim.listener.AppCodeTemplates.appCodeTemplateCaptured
import com.maddyhome.idea.vim.newapi.IjVimEditor
import com.maddyhome.idea.vim.newapi.vim
import com.maddyhome.idea.vim.options.OptionChangeListener
import com.maddyhome.idea.vim.options.OptionConstants
import com.maddyhome.idea.vim.options.OptionScope
import com.maddyhome.idea.vim.vimscript.model.datatypes.VimDataType
import com.maddyhome.idea.vim.vimscript.model.datatypes.VimString
import com.maddyhome.idea.vim.vimscript.services.IjVimOptionService
import java.awt.event.InputEvent
import java.awt.event.KeyEvent
import javax.swing.KeyStroke
/**
* Handles Vim keys that are treated as action shortcuts by the IDE.
*
*
* These keys are not passed to [com.maddyhome.idea.vim.VimTypedActionHandler] and should be handled by actions.
*/
class VimShortcutKeyAction : AnAction(), DumbAware/*, LightEditCompatible*/ {
private val traceTime = VimPlugin.getOptionService().isSet(OptionScope.GLOBAL, OptionConstants.ideatracetimeName)
override fun actionPerformed(e: AnActionEvent) {
LOG.trace("Executing shortcut key action")
val editor = getEditor(e)
val keyStroke = getKeyStroke(e)
if (editor != null && keyStroke != null) {
val owner = VimPlugin.getKey().savedShortcutConflicts[keyStroke]
if ((owner as? ShortcutOwnerInfo.AllModes)?.owner == ShortcutOwner.UNDEFINED) {
VimPlugin.getNotifications(editor.project).notifyAboutShortcutConflict(keyStroke)
}
// Should we use HelperKt.getTopLevelEditor(editor) here, as we did in former EditorKeyHandler?
try {
val start = if (traceTime) System.currentTimeMillis() else null
KeyHandler.getInstance().handleKey(editor.vim, keyStroke, EditorDataContext.init(editor, e.dataContext).vim)
if (start != null) {
val duration = System.currentTimeMillis() - start
LOG.info("VimShortcut update '$keyStroke': $duration ms")
}
} catch (ignored: ProcessCanceledException) {
// Control-flow exceptions (like ProcessCanceledException) should never be logged
// See {@link com.intellij.openapi.diagnostic.Logger.checkException}
} catch (throwable: Throwable) {
LOG.error(throwable)
}
}
}
// There is a chance that we can use BGT, but we call for isCell inside the update.
// Not sure if can can use BGT with this call. Let's use EDT for now.
override fun getActionUpdateThread() = ActionUpdateThread.EDT
override fun update(e: AnActionEvent) {
val start = if (traceTime) System.currentTimeMillis() else null
e.presentation.isEnabled = isEnabled(e)
LOG.debug { "Shortcut key. Enabled: ${e.presentation.isEnabled}" }
if (start != null) {
val keyStroke = getKeyStroke(e)
val duration = System.currentTimeMillis() - start
LOG.info("VimShortcut update '$keyStroke': $duration ms")
}
}
private fun isEnabled(e: AnActionEvent): Boolean {
if (!VimPlugin.isEnabled()) return false
val editor = getEditor(e)
val keyStroke = getKeyStroke(e)
if (editor != null && keyStroke != null) {
if (editor.isIdeaVimDisabledHere) {
LOG.trace("Do not execute shortcut because it's disabled here")
return false
}
// Workaround for smart step into
@Suppress("DEPRECATION", "LocalVariableName", "VariableNaming")
val SMART_STEP_INPLACE_DATA = Key.findKeyByName("SMART_STEP_INPLACE_DATA")
if (SMART_STEP_INPLACE_DATA != null && editor.getUserData(SMART_STEP_INPLACE_DATA) != null) {
LOG.trace("Do not execute shortcut because of smart step")
return false
}
val keyCode = keyStroke.keyCode
if (HandlerInjector.notebookCommandMode(editor)) {
LOG.debug("Python Notebook command mode")
if (keyCode == KeyEvent.VK_RIGHT || keyCode == KeyEvent.VK_KP_RIGHT || keyCode == KeyEvent.VK_ENTER) {
invokeLater { editor.updateCaretsVisualAttributes() }
}
return false
}
if (AceJumpService.getInstance()?.isActive(editor) == true) {
LOG.trace("Do not execute shortcut because AceJump is active")
return false
}
if (LookupManager.getActiveLookup(editor) != null && !LookupKeys.isEnabledForLookup(keyStroke)) {
LOG.trace("Do not execute shortcut because of lookup keys")
return false
}
if (keyCode == KeyEvent.VK_ESCAPE) return isEnabledForEscape(editor)
if (keyCode == KeyEvent.VK_TAB && editor.isTemplateActive()) return false
if ((keyCode == KeyEvent.VK_TAB || keyCode == KeyEvent.VK_ENTER) && editor.appCodeTemplateCaptured()) return false
if (editor.inInsertMode) {
if (keyCode == KeyEvent.VK_TAB) {
// TODO: This stops VimEditorTab seeing <Tab> in insert mode and correctly scrolling the view
// There are multiple actions registered for VK_TAB. The important items, in order, are this, the Live
// Templates action and TabAction. Returning false in insert mode means that the Live Template action gets to
// execute, and this allows Emmet to work (VIM-674). But it also means that the VimEditorTab handle is never
// called, so we can't scroll the caret into view correctly.
// If we do return true, VimEditorTab handles the Vim side of things and then invokes
// IdeActions.ACTION_EDITOR_TAB, which inserts the tab. It also bypasses the Live Template action, and Emmet
// no longer works.
// This flag is used when recording text entry/keystrokes for repeated insertion. Because we return false and
// don't execute the VimEditorTab handler, we don't record tab as an action. Instead, we see an incoming text
// change of multiple whitespace characters, which is normally ignored because it's auto-indent content from
// hitting <Enter>. When this flag is set, we record the whitespace as the output of the <Tab>
VimPlugin.getChange().tabAction = true
return false
}
// Debug watch, Python console, etc.
if (keyStroke in NON_FILE_EDITOR_KEYS && !EditorHelper.isFileEditor(editor)) return false
}
if (keyStroke in VIM_ONLY_EDITOR_KEYS) return true
val savedShortcutConflicts = VimPlugin.getKey().savedShortcutConflicts
val info = savedShortcutConflicts[keyStroke]
return when (info?.forEditor(editor.vim)) {
ShortcutOwner.VIM -> true
ShortcutOwner.IDE -> !isShortcutConflict(keyStroke)
else -> {
if (isShortcutConflict(keyStroke)) {
savedShortcutConflicts[keyStroke] = ShortcutOwnerInfo.allUndefined
}
true
}
}
}
return false
}
private fun isEnabledForEscape(editor: Editor): Boolean {
val ideaVimSupportValue = (VimPlugin.getOptionService().getOptionValue(OptionScope.LOCAL(IjVimEditor(editor)), IjVimOptionService.ideavimsupportName) as VimString).value
return editor.isPrimaryEditor() ||
EditorHelper.isFileEditor(editor) && !editor.inNormalMode ||
ideaVimSupportValue.contains(IjVimOptionService.ideavimsupport_dialog) && !editor.inNormalMode
}
private fun isShortcutConflict(keyStroke: KeyStroke): Boolean {
return VimPlugin.getKey().getKeymapConflicts(keyStroke).isNotEmpty()
}
/**
* getDefaultKeyStroke is needed for NEO layout keyboard VIM-987
* but we should cache the value because on the second call (isEnabled -> actionPerformed)
* the event is already consumed
*/
private var keyStrokeCache: Pair<KeyEvent?, KeyStroke?> = null to null
private fun getKeyStroke(e: AnActionEvent): KeyStroke? {
val inputEvent = e.inputEvent
if (inputEvent is KeyEvent) {
val defaultKeyStroke = KeyStrokeAdapter.getDefaultKeyStroke(inputEvent)
val strokeCache = keyStrokeCache
if (defaultKeyStroke != null) {
keyStrokeCache = inputEvent to defaultKeyStroke
return defaultKeyStroke
} else if (strokeCache.first === inputEvent) {
keyStrokeCache = null to null
return strokeCache.second
}
return KeyStroke.getKeyStrokeForEvent(inputEvent)
}
return null
}
private fun getEditor(e: AnActionEvent): Editor? = e.getData(PlatformDataKeys.EDITOR)
/**
* Every time the key pressed with an active lookup, there is a decision:
* should this key be processed by IdeaVim, or by IDE. For example, dot and enter should be processed by IDE, but
* <C-W> by IdeaVim.
*
* The list of keys that should be processed by IDE is stored in the "lookupKeys" option. So, we should search
* if the pressed key is presented in this list. The caches are used to speedup the process.
*/
private object LookupKeys {
private var parsedLookupKeys: Set<KeyStroke> = parseLookupKeys()
init {
VimPlugin.getOptionService().addListener(
OptionConstants.lookupkeysName,
object : OptionChangeListener<VimDataType> {
override fun processGlobalValueChange(oldValue: VimDataType?) {
parsedLookupKeys = parseLookupKeys()
}
}
)
}
fun isEnabledForLookup(keyStroke: KeyStroke): Boolean = keyStroke !in parsedLookupKeys
private fun parseLookupKeys() = (VimPlugin.getOptionService().getOptionValue(OptionScope.GLOBAL, OptionConstants.lookupkeysName) as VimString).value
.split(",")
.map { injector.parser.parseKeys(it) }
.filter { it.isNotEmpty() }
.map { it.first() }
.toSet()
}
companion object {
@JvmField
val VIM_ONLY_EDITOR_KEYS: Set<KeyStroke> =
ImmutableSet.builder<KeyStroke>().addAll(getKeyStrokes(KeyEvent.VK_ENTER, 0))
.addAll(getKeyStrokes(KeyEvent.VK_ESCAPE, 0))
.addAll(getKeyStrokes(KeyEvent.VK_TAB, 0))
.addAll(getKeyStrokes(KeyEvent.VK_BACK_SPACE, 0, InputEvent.CTRL_DOWN_MASK))
.addAll(getKeyStrokes(KeyEvent.VK_INSERT, 0))
.addAll(getKeyStrokes(KeyEvent.VK_DELETE, 0, InputEvent.CTRL_DOWN_MASK))
.addAll(getKeyStrokes(KeyEvent.VK_UP, 0, InputEvent.CTRL_DOWN_MASK, InputEvent.SHIFT_DOWN_MASK))
.addAll(getKeyStrokes(KeyEvent.VK_DOWN, 0, InputEvent.CTRL_DOWN_MASK, InputEvent.SHIFT_DOWN_MASK))
.addAll(
getKeyStrokes(
KeyEvent.VK_LEFT,
0,
InputEvent.CTRL_DOWN_MASK,
InputEvent.SHIFT_DOWN_MASK,
InputEvent.CTRL_DOWN_MASK or InputEvent.SHIFT_DOWN_MASK
)
)
.addAll(
getKeyStrokes(
KeyEvent.VK_RIGHT,
0,
InputEvent.CTRL_DOWN_MASK,
InputEvent.SHIFT_DOWN_MASK,
InputEvent.CTRL_DOWN_MASK or InputEvent.SHIFT_DOWN_MASK
)
)
.addAll(
getKeyStrokes(
KeyEvent.VK_HOME,
0,
InputEvent.CTRL_DOWN_MASK,
InputEvent.SHIFT_DOWN_MASK,
InputEvent.CTRL_DOWN_MASK or InputEvent.SHIFT_DOWN_MASK
)
)
.addAll(
getKeyStrokes(
KeyEvent.VK_END,
0,
InputEvent.CTRL_DOWN_MASK,
InputEvent.SHIFT_DOWN_MASK,
InputEvent.CTRL_DOWN_MASK or InputEvent.SHIFT_DOWN_MASK
)
)
.addAll(
getKeyStrokes(
KeyEvent.VK_PAGE_UP,
0,
InputEvent.SHIFT_DOWN_MASK,
InputEvent.CTRL_DOWN_MASK or InputEvent.SHIFT_DOWN_MASK
)
)
.addAll(
getKeyStrokes(
KeyEvent.VK_PAGE_DOWN,
0,
InputEvent.SHIFT_DOWN_MASK,
InputEvent.CTRL_DOWN_MASK or InputEvent.SHIFT_DOWN_MASK
)
).build()
private const val ACTION_ID = "VimShortcutKeyAction"
private val NON_FILE_EDITOR_KEYS: Set<KeyStroke> = ImmutableSet.builder<KeyStroke>()
.addAll(getKeyStrokes(KeyEvent.VK_ENTER, 0))
.addAll(getKeyStrokes(KeyEvent.VK_ESCAPE, 0))
.addAll(getKeyStrokes(KeyEvent.VK_TAB, 0))
.addAll(getKeyStrokes(KeyEvent.VK_UP, 0))
.addAll(getKeyStrokes(KeyEvent.VK_DOWN, 0))
.build()
private val LOG = logger<VimShortcutKeyAction>()
@JvmStatic
val instance: AnAction by lazy {
EmptyAction.wrap(ActionManager.getInstance().getAction(ACTION_ID))
}
private fun getKeyStrokes(keyCode: Int, vararg modifiers: Int) =
modifiers.map { KeyStroke.getKeyStroke(keyCode, it) }
}
}
| mit | cc33ef045c289a91d31d9fdae4713a66 | 41.085546 | 173 | 0.696082 | 4.497793 | false | false | false | false |
hpost/kommon | app/src/main/java/cc/femto/kommon/ui/recyclerview/AdvancedRecyclerViewAdapter.kt | 1 | 5775 | package cc.femto.kommon.ui.recyclerview
import android.support.v7.widget.RecyclerView
import android.view.View
import android.view.ViewGroup
import rx.Observable
import rx.subjects.PublishSubject
import java.util.concurrent.TimeUnit
/**
* Inspired by https://gist.github.com/sebnapi/fde648c17616d9d3bcde
*
* If you extend this Adapter you are able to add a Header, a Footer or both by a similar ViewHolder pattern as in
* RecyclerView.
* Don't override (Be careful while overriding) - onCreateViewHolder - onBindViewHolder -
* getItemCount - getItemViewType
* You need to override the abstract methods introduced by this class. This class is
* not using generics as RecyclerView.Adapter. Make yourself sure to cast right.
*/
abstract class AdvancedRecyclerViewAdapter(val paginationListener: OnPaginationListener? = null)
: RecyclerView.Adapter<RecyclerView.ViewHolder>() {
companion object {
val PAGINATION_OFFSET = 10
val TYPE_HEADER = Integer.MIN_VALUE
val TYPE_FOOTER = Integer.MIN_VALUE + 1
val TYPE_ADAPTEE_OFFSET = 2
}
interface OnPaginationListener {
fun onPagination()
}
private var headerViewHolder: RecyclerView.ViewHolder? = null
private var footerViewHolder: RecyclerView.ViewHolder? = null
private var paginationSubject: PublishSubject<Void>? = null
/**
* Returns an Observable that emits items once the pagination threshold was reached. It is throttled to avoid
* excessive pagination.
*/
val paginationObservable: Observable<Void>
get() {
if (paginationSubject == null) {
paginationSubject = PublishSubject.create<Void>()
}
return paginationSubject!!.asObservable().throttleFirst(500, TimeUnit.MILLISECONDS)
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
if (viewType == TYPE_HEADER && headerViewHolder != null) {
return headerViewHolder!!
} else if (viewType == TYPE_FOOTER && footerViewHolder != null) {
return footerViewHolder!!
}
return onCreateBasicItemViewHolder(parent, viewType - TYPE_ADAPTEE_OFFSET)
}
override fun onBindViewHolder(holder: RecyclerView.ViewHolder?, position: Int) {
if (paginationListener != null
&& getBasicItemCount() != 0 //don't callback when list is empty
&& position >= itemCount - 1 - PAGINATION_OFFSET) {
paginationListener.onPagination()
}
if (paginationSubject != null && paginationSubject!!.hasObservers()
&& getBasicItemCount() != 0 //don't callback when list is empty
&& position >= itemCount - 1 - PAGINATION_OFFSET) {
paginationSubject!!.onNext(null)
}
if (position == 0 && holder!!.itemViewType == TYPE_HEADER) {
//no need to bind, header is not being recycled
return
}
val last = itemCount - 1
if (position == last && holder!!.itemViewType == TYPE_FOOTER) {
//no need to bind, footer is not being recycled
return
}
if (holder != null) {
val headerOffset = if (headerViewHolder != null) 1 else 0
onBindBasicItemView(holder, position - headerOffset)
}
}
fun offsetPosition(position: Int): Int = if (headerViewHolder != null) position - 1 else position
override fun getItemCount(): Int {
var itemCount = getBasicItemCount()
if (headerViewHolder != null) {
itemCount += 1
}
if (footerViewHolder != null) {
itemCount += 1
}
return itemCount
}
val isEmpty: Boolean
get() = getBasicItemCount() == 0
override fun getItemViewType(position: Int): Int {
var position = position
if (position == 0 && headerViewHolder != null) {
return TYPE_HEADER
}
val last = itemCount - 1
if (position == last && footerViewHolder != null) {
return TYPE_FOOTER
}
//if header exists, readjust position to pass back the true BasicItemViewType position
if (headerViewHolder != null) {
position--
}
if (getBasicItemViewType(position) >= Integer.MAX_VALUE - TYPE_ADAPTEE_OFFSET) {
throw IllegalStateException(
"AdvancedRecyclerViewAdapter offsets your BasicItemType by $TYPE_ADAPTEE_OFFSET.")
}
return getBasicItemViewType(position) + TYPE_ADAPTEE_OFFSET
}
fun setHeaderView(view: View?) {
if (view == null) {
headerViewHolder = null
return
}
//create concrete instance of abstract ViewHolder class
val viewHolder = object : RecyclerView.ViewHolder(view) {
}
headerViewHolder = viewHolder
}
fun setFooterView(view: View?) {
if (view == null) {
footerViewHolder = null
return
}
//create concrete instance of abstract ViewHolder class
val viewHolder = object : RecyclerView.ViewHolder(view) {
}
footerViewHolder = viewHolder
}
protected abstract fun onCreateBasicItemViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder
protected abstract fun onBindBasicItemView(holder: RecyclerView.ViewHolder, position: Int)
abstract fun getBasicItemCount(): Int
/**
* Override when multiple row types are supported.
* Make sure you don't use [Integer.MIN_VALUE, Integer.MIN_VALUE + 1]
* or Integer.MAX_VALUE as BasicItemViewType
*/
protected open fun getBasicItemViewType(position: Int): Int {
return 0
}
} | apache-2.0 | 7a915c6ae1fe49f79990f1fe83bcf2d1 | 34.219512 | 114 | 0.637922 | 5.110619 | false | false | false | false |
DuncanCasteleyn/DiscordModBot | src/main/kotlin/be/duncanc/discordmodbot/bot/sequences/PlanUnmuteSequence.kt | 1 | 4506 | package be.duncanc.discordmodbot.bot.sequences
import be.duncanc.discordmodbot.bot.commands.CommandModule
import be.duncanc.discordmodbot.bot.services.GuildLogger
import be.duncanc.discordmodbot.bot.utils.messageTimeFormat
import be.duncanc.discordmodbot.bot.utils.nicknameAndUsername
import be.duncanc.discordmodbot.data.repositories.jpa.MuteRolesRepository
import be.duncanc.discordmodbot.data.services.ScheduledUnmuteService
import net.dv8tion.jda.api.EmbedBuilder
import net.dv8tion.jda.api.Permission
import net.dv8tion.jda.api.entities.Guild
import net.dv8tion.jda.api.entities.MessageChannel
import net.dv8tion.jda.api.entities.TextChannel
import net.dv8tion.jda.api.entities.User
import net.dv8tion.jda.api.events.message.MessageReceivedEvent
import org.springframework.stereotype.Component
import java.time.OffsetDateTime
import java.util.concurrent.TimeUnit
open class PlanUnmuteSequence(
user: User,
channel: MessageChannel,
private val scheduledUnmuteService: ScheduledUnmuteService,
private val targetUser: User,
private val guildLogger: GuildLogger
) : Sequence(
user,
channel
), MessageSequence {
init {
super.channel.sendMessage("In how much days should the user be unmuted?").queue {
addMessageToCleaner(it)
}
}
override fun onMessageReceivedDuringSequence(event: MessageReceivedEvent) {
val days = event.message.contentRaw.toLong()
if (days <= 0) {
throw IllegalArgumentException("The numbers of days should not be negative or 0")
}
val unmuteDateTime = OffsetDateTime.now().plusDays(days)
scheduledUnmuteService.planUnmute((channel as TextChannel).guild.idLong, targetUser.idLong, unmuteDateTime)
confirmationMessage()
val guild = channel.guild
logScheduledMute(guild, unmuteDateTime)
super.destroy()
}
private fun confirmationMessage() {
super.channel.sendMessage("Unmute has been planned.").queue {
it.delete().queueAfter(1, TimeUnit.MINUTES)
}
}
private fun logScheduledMute(guild: Guild, unmuteDateTime: OffsetDateTime) {
val logEmbed = EmbedBuilder()
.setColor(GuildLogger.LIGHT_BLUE)
.setTitle("User unmute planned")
.addField("User", guild.getMember(targetUser)?.nicknameAndUsername ?: targetUser.name, true)
.addField("Moderator", guild.getMember(user)?.nicknameAndUsername ?: user.name, true)
.addField("Unmute planned after", unmuteDateTime.format(messageTimeFormat), false)
guildLogger.log(logEmbed, targetUser, guild, null, GuildLogger.LogTypeAction.MODERATOR)
}
}
@Component
class PlanUnmuteCommand(
private val scheduledUnmuteService: ScheduledUnmuteService,
private val guildLogger: GuildLogger,
private val muteRolesRepository: MuteRolesRepository
) : CommandModule(
arrayOf("PlanUnmute"),
null,
null,
ignoreWhitelist = true,
requiredPermissions = arrayOf(Permission.MANAGE_ROLES)
) {
override fun commandExec(event: MessageReceivedEvent, command: String, arguments: String?) {
val userId = try {
event.message.contentRaw.substring(command.length + 2).trimStart('<', '@', '!').trimEnd('>').toLong()
} catch (ignored: IndexOutOfBoundsException) {
throw IllegalArgumentException("This command requires a user id or mention")
} catch (ignored: NumberFormatException) {
throw IllegalArgumentException("This command requires a user id or mention")
}
val guild = event.guild
muteRolesRepository.findById(guild.idLong).ifPresent {
val memberById = guild.getMemberById(userId)
if (memberById != null && memberById.roles.contains(memberById.guild.getRoleById(it.roleId))
) {
event.jda.addEventListener(
PlanUnmuteSequence(
event.author,
event.channel,
scheduledUnmuteService,
memberById.user,
guildLogger
)
)
} else {
sendUserNotMutedMessage(event)
}
}
}
private fun sendUserNotMutedMessage(event: MessageReceivedEvent) {
event.channel.sendMessage("${event.author.asMention} This user is not muted.").queue {
it.delete().queueAfter(1, TimeUnit.MINUTES)
}
}
}
| apache-2.0 | 7cc5d620f15a4aec12470ece4521b209 | 38.876106 | 115 | 0.682645 | 4.908497 | false | false | false | false |
nicopico-dev/HappyBirthday | dashclock/src/main/java/fr/nicopico/dashclock/birthday/BirthdayService.kt | 1 | 8821 | /*
* Copyright 2016 Nicolas Picon <[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 fr.nicopico.dashclock.birthday
import android.Manifest.permission.READ_CONTACTS
import android.content.Intent
import android.content.SharedPreferences
import android.content.res.Configuration
import android.content.res.Resources
import android.net.Uri
import android.preference.PreferenceManager
import android.provider.ContactsContract
import android.provider.ContactsContract.Contacts
import com.google.android.apps.dashclock.api.DashClockExtension
import com.google.android.apps.dashclock.api.ExtensionData
import com.jakewharton.threetenabp.AndroidThreeTen
import fr.nicopico.happybirthday.domain.model.Contact
import fr.nicopico.happybirthday.domain.model.nextBirthdaySorter
import fr.nicopico.happybirthday.extensions.hasPermissions
import fr.nicopico.happybirthday.extensions.today
import fr.nicopico.happybirthday.inject.DataModule
import org.threeten.bp.LocalDate
import rx.Observable
import rx.Subscriber
import rx.schedulers.Schedulers
import timber.log.Timber
import java.util.*
import java.util.concurrent.TimeUnit
class BirthdayService : DashClockExtension() {
private val DEFAULT_LANG = BuildConfig.DEFAULT_LANG
private val contactRepository by lazy {
DaggerAppComponent.builder()
.appModule(AppModule(application))
.dataModule(DataModule(BuildConfig.DEBUG))
.build()
.contactRepository()
}
private val prefs: SharedPreferences by lazy {
PreferenceManager.getDefaultSharedPreferences(applicationContext)
}
private var daysLimit: Int = 0
private var showQuickContact: Boolean = false
private var disableLocalization: Boolean = false
private var contactGroupId: Long? = null
private var needToRefreshLocalization: Boolean = false
override fun onCreate() {
super.onCreate()
AndroidThreeTen.init(application)
if (BuildConfig.DEBUG) {
Timber.plant(Timber.DebugTree())
}
}
override fun onInitialize(isReconnect: Boolean) {
super.onInitialize(isReconnect)
addWatchContentUris(arrayOf(ContactsContract.Contacts.CONTENT_URI.toString()))
updatePreferences()
}
override fun onUpdateData(reason: Int) {
if (reason == DashClockExtension.UPDATE_REASON_SETTINGS_CHANGED) {
updatePreferences()
}
handleLocalization()
if (hasPermissions(READ_CONTACTS)) {
Timber.d("READ_CONTACTS permission granted")
val today = today()
val contactObs = contactRepository
.list(
filter = { it.inDays(today) <= daysLimit },
sorter = nextBirthdaySorter(),
groupId = contactGroupId
)
.first()
.observeOn(Schedulers.immediate())
contactObs.subscribe(ContactSubscriber(today))
}
else {
Timber.d("READ_CONTACTS permission denied !")
displayMissingPermissionInfo()
Observable.timer(5, TimeUnit.SECONDS)
.takeUntil { hasPermissions(READ_CONTACTS) }
.toCompletable()
.subscribe { onUpdateData(UPDATE_REASON_CONTENT_CHANGED) }
}
}
@Suppress("DEPRECATION")
private fun handleLocalization() {
val config = Configuration()
config.setToDefaults()
if (needToRefreshLocalization || disableLocalization && DEFAULT_LANG != Locale.getDefault().language) {
val locale = when {
disableLocalization -> Locale(DEFAULT_LANG)
else -> Resources.getSystem().configuration.locale
}
config.locale = locale
Locale.setDefault(locale)
baseContext.resources.updateConfiguration(config, baseContext.resources.displayMetrics)
}
}
private fun updatePreferences() {
// Note daysLimit preference is stored as a String because of the EditTextPreference
daysLimit = prefs.getString(SettingsActivity.PREF_DAYS_LIMIT_KEY, "7").toInt()
showQuickContact = prefs.getBoolean(SettingsActivity.PREF_SHOW_QUICK_CONTACT, true)
val noGroupId = SettingsActivity.NO_CONTACT_GROUP_SELECTED
contactGroupId = prefs.getString(SettingsActivity.PREF_CONTACT_GROUP, noGroupId)
.let {
if (it != noGroupId) it
else null
}
?.toLong()
val previousDisableLocalizationValue = disableLocalization
disableLocalization = prefs.getBoolean(SettingsActivity.PREF_DISABLE_LOCALIZATION, false)
needToRefreshLocalization = previousDisableLocalizationValue != disableLocalization
}
private fun buildClickIntent(contacts: List<Contact>): Intent {
val clickIntent: Intent
val firstContact = contacts.first()
if (showQuickContact) {
// Open QuickContact dialog on click
clickIntent = QuickContactProxy.buildIntent(applicationContext, firstContact.lookupKey)
}
else {
clickIntent = Intent(Intent.ACTION_VIEW)
clickIntent.data = Uri.withAppendedPath(Contacts.CONTENT_URI, firstContact.id.toString())
}
return clickIntent
}
private fun displayMissingPermissionInfo() {
publishUpdate(ExtensionData()
.visible(true)
.icon(R.drawable.ic_extension_white)
.status(getString(R.string.permission_error_title))
.expandedBody(getString(R.string.permission_error_body))
.clickIntent(PermissionActivity.createIntent(this))
)
}
private inner class ContactSubscriber(val today: LocalDate) : Subscriber<List<Contact>>() {
override fun onNext(contacts: List<Contact>) {
if (contacts.isEmpty()) {
publishUpdate(ExtensionData().visible(false))
}
else {
val res = resources
val firstContactName = contacts.first().displayName
val collapsedTitle = when (contacts.size) {
1 -> firstContactName
else -> "$firstContactName + ${contacts.size - 1}"
}
val expandedTitle = res.getString(R.string.single_birthday_title_format, firstContactName)
val body = StringBuilder()
contacts.forEachIndexed { i, contact ->
if (i > 0) {
body.append(contact.displayName).append(", ")
}
val birthday = contact.birthday
if (contact.canComputeAge()) {
// Compute age on next birthday
val nextBirthdayCal = birthday.nextBirthdayDate(today)
val age = contact.getAge(nextBirthdayCal)!!
body.append(res.getQuantityString(R.plurals.age_format, age, age)).append(' ')
}
val inDays = birthday.inDays(today)
val inDaysFormat = when (inDays) {
0L -> R.string.when_today_format
1L -> R.string.when_tomorrow_format
else -> R.string.when_days_format
}
body.append(res.getString(inDaysFormat, inDays)).append('\n')
}
publishUpdate(ExtensionData()
.visible(true)
.icon(R.drawable.ic_extension_white)
.status(collapsedTitle)
.expandedTitle(expandedTitle)
.expandedBody(body.toString())
.clickIntent(buildClickIntent(contacts))
)
}
}
override fun onError(e: Throwable) {
Timber.e(e, "Unable to retrieve birthdays")
if (e is SecurityException) {
displayMissingPermissionInfo()
}
}
override fun onCompleted() {
// no-op
}
}
}
| apache-2.0 | d6cd2d78c7e8c2198775a6cd408b6b6e | 37.688596 | 111 | 0.615576 | 5.219527 | false | false | false | false |
mdaniel/intellij-community | plugins/kotlin/base/scripting/src/org/jetbrains/kotlin/idea/core/script/ucache/ScriptClassRootsCache.kt | 1 | 9863 | // 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.core.script.ucache
import com.intellij.ide.caches.CachesInvalidator
import com.intellij.openapi.project.Project
import com.intellij.openapi.project.ProjectManager
import com.intellij.openapi.projectRoots.Sdk
import com.intellij.openapi.roots.OrderRootType
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.psi.search.GlobalSearchScope
import com.intellij.psi.search.NonClasspathDirectoriesScope.compose
import org.jetbrains.kotlin.idea.core.script.ScriptConfigurationManager.Companion.classpathEntryToVfs
import org.jetbrains.kotlin.idea.core.script.ScriptConfigurationManager.Companion.toVfsRoots
import org.jetbrains.kotlin.idea.core.script.configuration.utils.ScriptClassRootsStorage
import org.jetbrains.kotlin.scripting.definitions.ScriptDefinition
import org.jetbrains.kotlin.scripting.resolve.ScriptCompilationConfigurationWrapper
import java.lang.ref.Reference
import java.lang.ref.SoftReference
import kotlin.io.path.Path
class ScriptClassRootsCache(
private val scripts: Map<String, LightScriptInfo>,
private val classes: Set<String>,
private val sources: Set<String>,
val customDefinitionsUsed: Boolean,
val sdks: ScriptSdks
) {
companion object {
val EMPTY = ScriptClassRootsCache(
mapOf(), setOf(), setOf(), true,
ScriptSdks(mapOf(), setOf(), setOf())
)
}
fun withUpdatedSdks(newSdks: ScriptSdks) =
ScriptClassRootsCache(scripts, classes, sources, customDefinitionsUsed, newSdks)
fun builder(project: Project): ScriptClassRootsBuilder {
return ScriptClassRootsBuilder(
project,
classes.toMutableSet(),
sources.toMutableSet(),
scripts.toMutableMap()
).also { builder ->
if (customDefinitionsUsed) {
builder.useCustomScriptDefinition()
}
builder.sdks.addAll(sdks)
}
}
abstract class LightScriptInfo(val definition: ScriptDefinition?) {
@Volatile
var heavyCache: Reference<HeavyScriptInfo>? = null
abstract fun buildConfiguration(): ScriptCompilationConfigurationWrapper?
}
class DirectScriptInfo(val result: ScriptCompilationConfigurationWrapper) : LightScriptInfo(null) {
override fun buildConfiguration(): ScriptCompilationConfigurationWrapper = result
}
class HeavyScriptInfo(
val scriptConfiguration: ScriptCompilationConfigurationWrapper,
val classFilesScope: GlobalSearchScope,
val sdk: Sdk?
)
fun getLightScriptInfo(file: String) = scripts[file]
fun contains(file: VirtualFile): Boolean = file.path in scripts
private fun getHeavyScriptInfo(file: String): HeavyScriptInfo? {
val lightScriptInfo = getLightScriptInfo(file) ?: return null
val heavy0 = lightScriptInfo.heavyCache?.get()
if (heavy0 != null) return heavy0
synchronized(lightScriptInfo) {
val heavy1 = lightScriptInfo.heavyCache?.get()
if (heavy1 != null) return heavy1
val heavy2 = computeHeavy(lightScriptInfo)
lightScriptInfo.heavyCache = SoftReference(heavy2)
return heavy2
}
}
private fun computeHeavy(lightScriptInfo: LightScriptInfo): HeavyScriptInfo? {
val configuration = lightScriptInfo.buildConfiguration() ?: return null
val roots = configuration.dependenciesClassPath
val sdk = sdks[SdkId(configuration.javaHome?.toPath())]
return if (sdk == null) {
HeavyScriptInfo(configuration, compose(toVfsRoots(roots)), null)
} else {
val sdkClasses = sdk.rootProvider.getFiles(OrderRootType.CLASSES).toList()
HeavyScriptInfo(configuration, compose(sdkClasses + toVfsRoots(roots)), sdk)
}
}
val firstScriptSdk: Sdk?
get() = sdks.first
val allDependenciesClassFiles: Set<VirtualFile>
val allDependenciesSources: Set<VirtualFile>
init {
allDependenciesClassFiles = mutableSetOf<VirtualFile>().also { result ->
classes.mapNotNullTo(result) { classpathEntryToVfs(Path(it)) }
}
allDependenciesSources = mutableSetOf<VirtualFile>().also { result ->
sources.mapNotNullTo(result) { classpathEntryToVfs(Path(it)) }
}
}
val allDependenciesClassFilesScope = compose(allDependenciesClassFiles.toList() + sdks.nonIndexedClassRoots)
val allDependenciesSourcesScope = compose(allDependenciesSources.toList() + sdks.nonIndexedSourceRoots)
fun getScriptConfiguration(file: VirtualFile): ScriptCompilationConfigurationWrapper? =
getHeavyScriptInfo(file.path)?.scriptConfiguration
fun getScriptSdk(file: VirtualFile): Sdk? =
getHeavyScriptInfo(file.path)?.sdk
fun getScriptDependenciesClassFilesScope(file: VirtualFile): GlobalSearchScope =
getHeavyScriptInfo(file.path)?.classFilesScope ?: GlobalSearchScope.EMPTY_SCOPE
fun diff(project: Project, old: ScriptClassRootsCache?): Updates =
when (old) {
null -> FullUpdate(project, this)
this -> NotChanged(this)
else -> IncrementalUpdates(
cache = this,
hasNewRoots = this.hasNewRoots(old),
hasOldRoots = old.hasNewRoots(this),
updatedScripts = getChangedScripts(old),
oldRoots = old.allDependenciesClassFiles + old.allDependenciesSources,
newRoots = allDependenciesClassFiles + allDependenciesSources,
oldSdkRoots = old.sdks.nonIndexedClassRoots + old.sdks.nonIndexedSourceRoots,
newSdkRoots = sdks.nonIndexedClassRoots + sdks.nonIndexedSourceRoots
)
}
private fun hasNewRoots(old: ScriptClassRootsCache): Boolean {
val oldClassRoots = old.allDependenciesClassFiles.toSet()
val oldSourceRoots = old.allDependenciesSources.toSet()
return allDependenciesClassFiles.any { it !in oldClassRoots } ||
allDependenciesSources.any { it !in oldSourceRoots } ||
old.sdks != sdks
}
private fun getChangedScripts(old: ScriptClassRootsCache): Set<String> {
val changed = mutableSetOf<String>()
scripts.forEach {
if (old.scripts[it.key] != it.value) {
changed.add(it.key)
}
}
old.scripts.forEach {
if (it.key !in scripts) {
changed.add(it.key)
}
}
return changed
}
interface Updates {
val cache: ScriptClassRootsCache
val changed: Boolean
val hasNewRoots: Boolean
val oldRoots: Collection<VirtualFile>
val newRoots: Collection<VirtualFile>
val oldSdkRoots: Collection<VirtualFile>
val newSdkRoots: Collection<VirtualFile>
val hasUpdatedScripts: Boolean
fun isScriptChanged(scriptPath: String): Boolean
}
class IncrementalUpdates(
override val cache: ScriptClassRootsCache,
override val hasNewRoots: Boolean,
override val oldRoots: Collection<VirtualFile>,
override val newRoots: Collection<VirtualFile>,
override val oldSdkRoots: Collection<VirtualFile>,
override val newSdkRoots: Collection<VirtualFile>,
private val hasOldRoots: Boolean,
private val updatedScripts: Set<String>
) : Updates {
override val hasUpdatedScripts: Boolean get() = updatedScripts.isNotEmpty()
override fun isScriptChanged(scriptPath: String) = scriptPath in updatedScripts
override val changed: Boolean
get() = hasNewRoots || updatedScripts.isNotEmpty() || hasOldRoots
}
class FullUpdate(private val project: Project, override val cache: ScriptClassRootsCache) : Updates {
override val changed: Boolean get() = true
override val hasUpdatedScripts: Boolean get() = true
override fun isScriptChanged(scriptPath: String): Boolean = true
override val oldRoots: Collection<VirtualFile> = emptyList()
override val oldSdkRoots: Collection<VirtualFile> = emptyList()
override val newRoots: Collection<VirtualFile>
get() = cache.allDependenciesClassFiles +
cache.allDependenciesSources
override val newSdkRoots: Collection<VirtualFile>
get() = cache.sdks.nonIndexedClassRoots +
cache.sdks.nonIndexedSourceRoots
override val hasNewRoots: Boolean
get() =
cache.allDependenciesClassFiles.isNotEmpty() ||
cache.allDependenciesSources.isNotEmpty() ||
cache.sdks.nonIndexedClassRoots.isNotEmpty() ||
cache.sdks.nonIndexedSourceRoots.isNotEmpty()
}
class NotChanged(override val cache: ScriptClassRootsCache) : Updates {
override val changed: Boolean get() = false
override val hasNewRoots: Boolean get() = false
override val hasUpdatedScripts: Boolean get() = false
override val oldRoots: Collection<VirtualFile> = emptyList()
override val newRoots: Collection<VirtualFile> = emptyList()
override val oldSdkRoots: Collection<VirtualFile> = emptyList()
override val newSdkRoots: Collection<VirtualFile> = emptyList()
override fun isScriptChanged(scriptPath: String): Boolean = false
}
}
class ScriptCacheDependenciesFileInvalidator : CachesInvalidator() {
override fun invalidateCaches() {
ProjectManager.getInstance().openProjects.forEach {
ScriptClassRootsStorage.getInstance(it).clear()
}
}
}
| apache-2.0 | 5b406fc51623c30e7145bb2e8d89a7ba | 39.093496 | 158 | 0.68397 | 5.473363 | false | true | false | false |
android/nowinandroid | core/designsystem/src/main/java/com/google/samples/apps/nowinandroid/core/designsystem/theme/Theme.kt | 1 | 7775 | /*
* Copyright 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.samples.apps.nowinandroid.core.designsystem.theme
import android.os.Build
import androidx.annotation.ChecksSdkIntAtLeast
import androidx.annotation.VisibleForTesting
import androidx.compose.foundation.isSystemInDarkTheme
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.darkColorScheme
import androidx.compose.material3.dynamicDarkColorScheme
import androidx.compose.material3.dynamicLightColorScheme
import androidx.compose.material3.lightColorScheme
import androidx.compose.runtime.Composable
import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.unit.dp
/**
* Light default theme color scheme
*/
@VisibleForTesting
val LightDefaultColorScheme = lightColorScheme(
primary = Purple40,
onPrimary = Color.White,
primaryContainer = Purple90,
onPrimaryContainer = Purple10,
secondary = Orange40,
onSecondary = Color.White,
secondaryContainer = Orange90,
onSecondaryContainer = Orange10,
tertiary = Blue40,
onTertiary = Color.White,
tertiaryContainer = Blue90,
onTertiaryContainer = Blue10,
error = Red40,
onError = Color.White,
errorContainer = Red90,
onErrorContainer = Red10,
background = DarkPurpleGray99,
onBackground = DarkPurpleGray10,
surface = DarkPurpleGray99,
onSurface = DarkPurpleGray10,
surfaceVariant = PurpleGray90,
onSurfaceVariant = PurpleGray30,
outline = PurpleGray50
)
/**
* Dark default theme color scheme
*/
@VisibleForTesting
val DarkDefaultColorScheme = darkColorScheme(
primary = Purple80,
onPrimary = Purple20,
primaryContainer = Purple30,
onPrimaryContainer = Purple90,
secondary = Orange80,
onSecondary = Orange20,
secondaryContainer = Orange30,
onSecondaryContainer = Orange90,
tertiary = Blue80,
onTertiary = Blue20,
tertiaryContainer = Blue30,
onTertiaryContainer = Blue90,
error = Red80,
onError = Red20,
errorContainer = Red30,
onErrorContainer = Red90,
background = DarkPurpleGray10,
onBackground = DarkPurpleGray90,
surface = DarkPurpleGray10,
onSurface = DarkPurpleGray90,
surfaceVariant = PurpleGray30,
onSurfaceVariant = PurpleGray80,
outline = PurpleGray60
)
/**
* Light Android theme color scheme
*/
@VisibleForTesting
val LightAndroidColorScheme = lightColorScheme(
primary = Green40,
onPrimary = Color.White,
primaryContainer = Green90,
onPrimaryContainer = Green10,
secondary = DarkGreen40,
onSecondary = Color.White,
secondaryContainer = DarkGreen90,
onSecondaryContainer = DarkGreen10,
tertiary = Teal40,
onTertiary = Color.White,
tertiaryContainer = Teal90,
onTertiaryContainer = Teal10,
error = Red40,
onError = Color.White,
errorContainer = Red90,
onErrorContainer = Red10,
background = DarkGreenGray99,
onBackground = DarkGreenGray10,
surface = DarkGreenGray99,
onSurface = DarkGreenGray10,
surfaceVariant = GreenGray90,
onSurfaceVariant = GreenGray30,
outline = GreenGray50
)
/**
* Dark Android theme color scheme
*/
@VisibleForTesting
val DarkAndroidColorScheme = darkColorScheme(
primary = Green80,
onPrimary = Green20,
primaryContainer = Green30,
onPrimaryContainer = Green90,
secondary = DarkGreen80,
onSecondary = DarkGreen20,
secondaryContainer = DarkGreen30,
onSecondaryContainer = DarkGreen90,
tertiary = Teal80,
onTertiary = Teal20,
tertiaryContainer = Teal30,
onTertiaryContainer = Teal90,
error = Red80,
onError = Red20,
errorContainer = Red30,
onErrorContainer = Red90,
background = DarkGreenGray10,
onBackground = DarkGreenGray90,
surface = DarkGreenGray10,
onSurface = DarkGreenGray90,
surfaceVariant = GreenGray30,
onSurfaceVariant = GreenGray80,
outline = GreenGray60
)
/**
* Light default gradient colors
*/
val LightDefaultGradientColors = GradientColors(
primary = Purple95,
secondary = Orange95,
tertiary = Blue95,
neutral = DarkPurpleGray95
)
/**
* Light Android background theme
*/
val LightAndroidBackgroundTheme = BackgroundTheme(color = DarkGreenGray95)
/**
* Dark Android background theme
*/
val DarkAndroidBackgroundTheme = BackgroundTheme(color = Color.Black)
/**
* Now in Android theme.
*
* @param darkTheme Whether the theme should use a dark color scheme (follows system by default).
* @param androidTheme Whether the theme should use the Android theme color scheme instead of the
* default theme. If this is `false`, then dynamic theming will be used when supported.
*/
@Composable
fun NiaTheme(
darkTheme: Boolean = isSystemInDarkTheme(),
androidTheme: Boolean = false,
content: @Composable () -> Unit
) = NiaTheme(
darkTheme = darkTheme,
androidTheme = androidTheme,
disableDynamicTheming = false,
content = content
)
/**
* Now in Android theme. This is an internal only version, to allow disabling dynamic theming
* in tests.
*
* @param darkTheme Whether the theme should use a dark color scheme (follows system by default).
* @param androidTheme Whether the theme should use the Android theme color scheme instead of the
* default theme.
* @param disableDynamicTheming If `true`, disables the use of dynamic theming, even when it is
* supported. This parameter has no effect if [androidTheme] is `true`.
*/
@Composable
internal fun NiaTheme(
darkTheme: Boolean = isSystemInDarkTheme(),
androidTheme: Boolean = false,
disableDynamicTheming: Boolean,
content: @Composable () -> Unit
) {
val colorScheme = if (androidTheme) {
if (darkTheme) DarkAndroidColorScheme else LightAndroidColorScheme
} else if (!disableDynamicTheming && supportsDynamicTheming()) {
val context = LocalContext.current
if (darkTheme) dynamicDarkColorScheme(context) else dynamicLightColorScheme(context)
} else {
if (darkTheme) DarkDefaultColorScheme else LightDefaultColorScheme
}
val defaultGradientColors = GradientColors()
val gradientColors = if (androidTheme || (!disableDynamicTheming && supportsDynamicTheming())) {
defaultGradientColors
} else {
if (darkTheme) defaultGradientColors else LightDefaultGradientColors
}
val defaultBackgroundTheme = BackgroundTheme(
color = colorScheme.surface,
tonalElevation = 2.dp
)
val backgroundTheme = if (androidTheme) {
if (darkTheme) DarkAndroidBackgroundTheme else LightAndroidBackgroundTheme
} else {
defaultBackgroundTheme
}
CompositionLocalProvider(
LocalGradientColors provides gradientColors,
LocalBackgroundTheme provides backgroundTheme
) {
MaterialTheme(
colorScheme = colorScheme,
typography = NiaTypography,
content = content
)
}
}
@ChecksSdkIntAtLeast(api = Build.VERSION_CODES.S)
private fun supportsDynamicTheming() = Build.VERSION.SDK_INT >= Build.VERSION_CODES.S
| apache-2.0 | 674b434cd69ce5d7c5663c6aa4d76eac | 30.2249 | 100 | 0.730161 | 4.778734 | false | false | false | false |
dmeybohm/chocolate-cakephp | src/main/kotlin/com/daveme/chocolateCakePHP/view/ViewHelperInViewHelperTypeProvider.kt | 1 | 1794 | package com.daveme.chocolateCakePHP.view
import com.daveme.chocolateCakePHP.viewHelperTypeFromFieldName
import com.daveme.chocolateCakePHP.startsWithUppercaseCharacter
import com.daveme.chocolateCakePHP.Settings
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiElement
import com.jetbrains.php.lang.psi.elements.FieldReference
import com.jetbrains.php.lang.psi.elements.PhpNamedElement
import com.jetbrains.php.lang.psi.resolve.types.PhpType
import com.jetbrains.php.lang.psi.resolve.types.PhpTypeProvider4
class ViewHelperInViewHelperTypeProvider : PhpTypeProvider4 {
override fun getKey(): Char {
return '\u8314'
}
override fun complete(p0: String?, p1: Project?): PhpType? = null
override fun getType(psiElement: PsiElement): PhpType? {
if (psiElement !is FieldReference) {
return null
}
val settings = Settings.getInstance(psiElement.project)
if (!settings.enabled) {
return null
}
val classReference = psiElement.classReference ?: return null
val referenceType = classReference.type
if (!referenceType.isComplete) {
return null
}
val fieldReferenceName = psiElement.name ?: return null
if (!fieldReferenceName.startsWithUppercaseCharacter()) {
return null
}
for (type in referenceType.types) {
if (type.contains("Helper")) {
return viewHelperTypeFromFieldName(settings, fieldReferenceName)
}
}
return null
}
override fun getBySignature(s: String, set: Set<String>, i: Int, project: Project): Collection<PhpNamedElement> {
// We use the default signature processor exclusively:
return emptyList()
}
}
| mit | 65b10cd4d700b4f45aef9a016fc2de1f | 34.176471 | 117 | 0.691193 | 4.822581 | false | false | false | false |
JavaEden/Orchid-Core | OrchidCore/src/main/kotlin/com/eden/orchid/impl/generators/ExternalIndexGenerator.kt | 2 | 3688 | package com.eden.orchid.impl.generators
import com.eden.common.util.EdenUtils
import com.eden.orchid.api.OrchidContext
import com.eden.orchid.api.generators.OrchidCollection
import com.eden.orchid.api.generators.OrchidGenerator
import com.eden.orchid.api.generators.PageCollection
import com.eden.orchid.api.indexing.OrchidIndex
import com.eden.orchid.api.options.OptionsHolder
import com.eden.orchid.api.options.annotations.Archetype
import com.eden.orchid.api.options.annotations.Description
import com.eden.orchid.api.options.annotations.ImpliedKey
import com.eden.orchid.api.options.annotations.Option
import com.eden.orchid.api.options.archetypes.ConfigArchetype
import com.eden.orchid.api.resources.resource.ExternalResource
import com.eden.orchid.api.theme.pages.OrchidPage
import org.apache.commons.io.FilenameUtils
import org.json.JSONObject
@Description(value = "Index external Orchid sites to create strong links between sites.", name = "External Indices")
@Archetype(value = ConfigArchetype::class, key = "services.generators")
class ExternalIndexGenerator :
OrchidGenerator<ExternalIndexGenerator.ExternalIndexModel>(GENERATOR_KEY, Stage.WARM_UP) {
@Option
@Description(
"The indices generated by an Orchid site can be included in the build of another Orchid site, to " +
"make strong links between the two sites. The index at `meta/indices.json` will crawl all the sub-indices " +
"of that site, or just a single one of that site's sub-indices can be included."
)
@ImpliedKey(typeKey = "url")
lateinit var externalIndices: List<ExternalIndex>
override fun startIndexing(context: OrchidContext): ExternalIndexModel {
val allPages = mutableMapOf<String, OrchidIndex>()
if (!EdenUtils.isEmpty(externalIndices)) {
for (externalIndex in externalIndices) {
val indexResource = context.getDefaultResourceSource(null, null).getResourceEntry(context, externalIndex.url)
if (indexResource != null) {
if(indexResource is ExternalResource) {
indexResource.download = true
indexResource.downloadInProdOnly = false
}
val resourceContent = indexResource.parseContent(context, null)
val index = OrchidIndex.fromJSON(context, JSONObject(resourceContent))
allPages[externalIndex.indexKey] = index
}
}
}
return ExternalIndexModel(allPages)
}
override fun startGeneration(context: OrchidContext, model: ExternalIndexModel) {
}
fun getCollections(
model: ExternalIndexModel
): List<OrchidCollection<*>> {
return model.indexMap.map { (key, value) ->
PageCollection(this, key, value.allPages)
}
}
inner class ExternalIndexModel(
val indexMap: Map<String, OrchidIndex>
) : Model {
override val allPages: List<OrchidPage> = indexMap.values.flatMap { it.allPages }
override val collections: List<OrchidCollection<*>> = indexMap.map { (key, value) ->
PageCollection(this@ExternalIndexGenerator, key, value.allPages)
}
}
class ExternalIndex : OptionsHolder {
@Option
lateinit var collectionId: String
@Option
lateinit var url: String
val indexKey: String
get() {
return if (collectionId.isNotBlank()) collectionId
else FilenameUtils.getBaseName(url).replace(".index", "")
}
}
companion object {
val GENERATOR_KEY = "external"
}
}
| mit | 0c6950e315306375b002a7dc976796ad | 37.821053 | 125 | 0.680315 | 4.692112 | false | false | false | false |
GunoH/intellij-community | platform/vcs-log/impl/src/com/intellij/vcs/log/history/VcsLogFileHistoryProviderImpl.kt | 2 | 8544 | // 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.vcs.log.history
import com.google.common.util.concurrent.SettableFuture
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.registry.Registry
import com.intellij.openapi.vcs.FilePath
import com.intellij.openapi.vcs.VcsBundle
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.ui.content.TabGroupId
import com.intellij.vcs.log.*
import com.intellij.vcs.log.data.VcsLogData
import com.intellij.vcs.log.data.VcsLogStorage
import com.intellij.vcs.log.impl.*
import com.intellij.vcs.log.impl.VcsLogNavigationUtil.jumpToRow
import com.intellij.vcs.log.impl.VcsLogTabLocation.Companion.findLogUi
import com.intellij.vcs.log.statistics.VcsLogUsageTriggerCollector
import com.intellij.vcs.log.ui.MainVcsLogUi
import com.intellij.vcs.log.ui.VcsLogUiEx
import com.intellij.vcs.log.util.VcsLogUtil
import com.intellij.vcs.log.visible.VisiblePack
import com.intellij.vcs.log.visible.filters.VcsLogFilterObject
import com.intellij.vcs.log.visible.filters.matches
import com.intellij.vcsUtil.VcsUtil
import java.util.function.Function
class VcsLogFileHistoryProviderImpl(project: Project) : VcsLogFileHistoryProvider {
private val providers = listOf(VcsLogSingleFileHistoryProvider(project), VcsLogDirectoryHistoryProvider(project))
override fun canShowFileHistory(paths: Collection<FilePath>, revisionNumber: String?): Boolean {
return providers.any { it.canShowFileHistory(paths, revisionNumber) }
}
override fun showFileHistory(paths: Collection<FilePath>, revisionNumber: String?) {
providers.firstOrNull { it.canShowFileHistory(paths, revisionNumber) }?.showFileHistory(paths, revisionNumber)
}
}
private class VcsLogDirectoryHistoryProvider(private val project: Project) : VcsLogFileHistoryProvider {
override fun canShowFileHistory(paths: Collection<FilePath>, revisionNumber: String?): Boolean {
if (!Registry.`is`("vcs.history.show.directory.history.in.log")) return false
val dataManager = VcsProjectLog.getInstance(project).dataManager ?: return false
return createPathsFilter(project, dataManager, paths) != null
}
override fun showFileHistory(paths: Collection<FilePath>, revisionNumber: String?) {
val hash = revisionNumber?.let { HashImpl.build(it) }
val root = VcsLogUtil.getActualRoot(project, paths.first())!!
triggerFileHistoryUsage(project, paths, hash)
val logManager = VcsProjectLog.getInstance(project).logManager!!
val pathsFilter = createPathsFilter(project, logManager.dataManager, paths)!!
val hashFilter = createHashFilter(hash, root)
var ui = logManager.findLogUi(VcsLogTabLocation.TOOL_WINDOW, MainVcsLogUi::class.java, true) { logUi ->
matches(logUi.filterUi.filters, pathsFilter, hashFilter)
}
val firstTime = ui == null
if (firstTime) {
val filters = VcsLogFilterObject.collection(pathsFilter, hashFilter)
ui = VcsProjectLog.getInstance(project).openLogTab(filters) ?: return
ui.properties.set(MainVcsLogUiProperties.SHOW_ONLY_AFFECTED_CHANGES, true)
}
selectRowWhenOpen(logManager, hash, root, ui!!, firstTime)
}
companion object {
private fun createPathsFilter(project: Project, dataManager: VcsLogData, paths: Collection<FilePath>): VcsLogFilter? {
val forRootFilter = mutableSetOf<VirtualFile>()
val forPathsFilter = mutableListOf<FilePath>()
for (path in paths) {
val root = VcsLogUtil.getActualRoot(project, path)
if (root == null) return null
if (!dataManager.roots.contains(root) ||
!VcsLogProperties.SUPPORTS_LOG_DIRECTORY_HISTORY.getOrDefault(dataManager.getLogProvider(root))) return null
val correctedPath = getCorrectedPath(project, path, root, false)
if (!correctedPath.isDirectory) return null
if (path.virtualFile == root) {
forRootFilter.add(root)
}
else {
forPathsFilter.add(correctedPath)
}
if (forPathsFilter.isNotEmpty() && forRootFilter.isNotEmpty()) return null
}
if (forPathsFilter.isNotEmpty()) return VcsLogFilterObject.fromPaths(forPathsFilter)
return VcsLogFilterObject.fromRoots(forRootFilter)
}
private fun createHashFilter(hash: Hash?, root: VirtualFile): VcsLogFilter {
if (hash == null) {
return VcsLogFilterObject.fromBranch(VcsLogUtil.HEAD)
}
return VcsLogFilterObject.fromCommit(CommitId(hash, root))
}
private fun matches(filters: VcsLogFilterCollection, pathsFilter: VcsLogFilter, hashFilter: VcsLogFilter): Boolean {
if (!filters.matches(hashFilter.key, pathsFilter.key)) {
return false
}
return filters.get(pathsFilter.key) == pathsFilter && filters.get(hashFilter.key) == hashFilter
}
}
}
private class VcsLogSingleFileHistoryProvider(private val project: Project) : VcsLogFileHistoryProvider {
private val tabGroupId: TabGroupId = TabGroupId("History", VcsBundle.messagePointer("file.history.tab.name"), false)
override fun canShowFileHistory(paths: Collection<FilePath>, revisionNumber: String?): Boolean {
if (!isNewHistoryEnabled() || paths.size != 1) return false
val root = VcsLogUtil.getActualRoot(project, paths.single()) ?: return false
val correctedPath = getCorrectedPath(project, paths.single(), root, revisionNumber != null)
if (correctedPath.isDirectory) return false
val dataManager = VcsProjectLog.getInstance(project).dataManager ?: return false
if (dataManager.logProviders[root]?.diffHandler == null) return false
return dataManager.index.isIndexingEnabled(root) || Registry.`is`("vcs.force.new.history")
}
override fun showFileHistory(paths: Collection<FilePath>, revisionNumber: String?) {
if (paths.size != 1) return
val root = VcsLogUtil.getActualRoot(project, paths.first())!!
val path = getCorrectedPath(project, paths.single(), root, revisionNumber != null)
if (path.isDirectory) return
val hash = revisionNumber?.let { HashImpl.build(it) }
triggerFileHistoryUsage(project, paths, hash)
val logManager = VcsProjectLog.getInstance(project).logManager!!
var fileHistoryUi = logManager.findLogUi(VcsLogTabLocation.TOOL_WINDOW, FileHistoryUi::class.java, true) { ui ->
ui.matches(path, hash)
}
val firstTime = fileHistoryUi == null
if (firstTime) {
val suffix = if (hash != null) " (" + hash.toShortString() + ")" else ""
fileHistoryUi = VcsLogContentUtil.openLogTab(project, logManager, tabGroupId, Function { path.name + suffix },
FileHistoryUiFactory(path, root, hash), true)
}
selectRowWhenOpen(logManager, hash, root, fileHistoryUi!!, firstTime)
}
}
fun isNewHistoryEnabled() = Registry.`is`("vcs.new.history")
private fun selectRowWhenOpen(logManager: VcsLogManager, hash: Hash?, root: VirtualFile, ui: VcsLogUiEx, firstTime: Boolean) {
if (hash != null) {
ui.jumpToNearestCommit(logManager.dataManager.storage, hash, root, true)
}
else if (firstTime) {
ui.jumpToRow(0, true, true)
}
}
private fun VcsLogUiEx.jumpToNearestCommit(storage: VcsLogStorage, hash: Hash, root: VirtualFile, silently: Boolean) {
jumpTo(hash, { visiblePack: VisiblePack, h: Hash? ->
if (!storage.containsCommit(CommitId(h!!, root))) return@jumpTo VcsLogUiEx.COMMIT_NOT_FOUND
val commitIndex: Int = storage.getCommitIndex(h, root)
var rowIndex = visiblePack.visibleGraph.getVisibleRowIndex(commitIndex)
if (rowIndex == null) {
rowIndex = findVisibleAncestorRow(commitIndex, visiblePack)
}
rowIndex ?: VcsLogUiEx.COMMIT_DOES_NOT_MATCH
}, SettableFuture.create(), silently, true)
}
private fun getCorrectedPath(project: Project, path: FilePath, root: VirtualFile,
isRevisionHistory: Boolean): FilePath {
var correctedPath = path
if (root != VcsUtil.getVcsRootFor(project, correctedPath) && correctedPath.isDirectory) {
correctedPath = VcsUtil.getFilePath(correctedPath.path, false)
}
if (!isRevisionHistory) {
return VcsUtil.getLastCommitPath(project, correctedPath)
}
return correctedPath
}
private fun triggerFileHistoryUsage(project: Project, paths: Collection<FilePath>, hash: Hash?) {
val kind = if (paths.size > 1) "multiple" else if (paths.first().isDirectory) "folder" else "file"
VcsLogUsageTriggerCollector.triggerFileHistoryUsage(project, kind, hash != null)
} | apache-2.0 | 346e247cf4bf6b83142221eda9c862ed | 43.274611 | 126 | 0.739466 | 4.673961 | false | false | false | false |
ktorio/ktor | ktor-http/jvm/src/io/ktor/http/content/URIFileContent.kt | 1 | 932 | /*
* Copyright 2014-2021 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license.
*/
package io.ktor.http.content
import io.ktor.http.*
import io.ktor.util.cio.*
import io.ktor.utils.io.*
import io.ktor.utils.io.jvm.javaio.*
import java.net.*
/**
* Represents a content that is served from the specified [uri]
* @property uri that is used as a source
*/
public class URIFileContent(
public val uri: URI,
override val contentType: ContentType = ContentType.defaultForFilePath(uri.path),
override val contentLength: Long? = null,
) : OutgoingContent.ReadChannelContent() {
public constructor(url: URL, contentType: ContentType = ContentType.defaultForFilePath(url.path)) : this(
url.toURI(),
contentType
)
// TODO: use http client
override fun readFrom(): ByteReadChannel = uri.toURL().openStream().toByteReadChannel(pool = KtorDefaultPool)
}
| apache-2.0 | bd9e3d049e16d81c708ba1cd98256a4e | 31.137931 | 118 | 0.723176 | 3.932489 | false | false | false | false |
google/ground-android | ground/src/main/java/com/google/android/ground/model/job/Job.kt | 1 | 1398 | /*
* 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
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.ground.model.job
import com.google.android.ground.model.task.Task
import com.google.android.ground.util.toImmutableList
import com.google.common.collect.ImmutableList
import com.google.common.collect.ImmutableMap
import java8.util.Optional
data class Job
@JvmOverloads
constructor(
val id: String,
val name: String? = null,
val tasks: ImmutableMap<String, Task> = ImmutableMap.of(),
val type: Type = Type.AUTOMATIC,
val status: Status = Status.NOT_STARTED
) {
val tasksSorted: ImmutableList<Task>
get() = tasks.values.sortedBy { it.id }.toImmutableList()
fun getTask(id: String): Optional<Task> = Optional.ofNullable(tasks[id])
enum class Type {
AUTOMATIC,
MANUAL
}
enum class Status {
NOT_STARTED,
IN_PROGRESS,
COMPLETE
}
}
| apache-2.0 | 3464ed8888c5f916da93da238067bce7 | 28.125 | 75 | 0.735336 | 3.905028 | false | false | false | false |
delight-im/ShortURL | Kotlin/ShortURL.kt | 1 | 1199 | /*
* ShortURL (https://github.com/delight-im/ShortURL)
* Copyright (c) delight.im (https://www.delight.im/)
* Licensed under the MIT License (https://opensource.org/licenses/MIT)
*/
/**
* ShortURL: Bijective conversion between natural numbers (IDs) and short strings
*
* ShortURL.encode() takes an ID and turns it into a short string
* ShortURL.decode() takes a short string and turns it into an ID
*
* Features:
* + large alphabet (51 chars) and thus very short resulting strings
* + proof against offensive words (removed 'a', 'e', 'i', 'o' and 'u')
* + unambiguous (removed 'I', 'l', '1', 'O' and '0')
*
* Example output:
* 123456789 <=> pgK8p
*/
object ShortURL {
private val ALPHABET = "23456789bcdfghjkmnpqrstvwxyzBCDFGHJKLMNPQRSTVWXYZ-_"
private val BASE = ALPHABET.length
fun encode(num: Int): String {
var number = num
val stringBuilder = StringBuilder()
while (number > 0) {
stringBuilder.insert(0, ALPHABET[number % BASE])
number /= BASE
}
return stringBuilder.toString()
}
fun decode(string: String): Int {
var number = 0
for (i in 0 until string.length) {
number = number * BASE + ALPHABET.indexOf(string[i])
}
return number
}
}
| mit | a667ad29e55a1068844c462128895e06 | 25.065217 | 81 | 0.678899 | 3.293956 | false | false | false | false |
VenomVendor/Tigerspike | demo/src/main/java/com/venomvendor/tigerspike/ui/adapter/GalleryListAdapter.kt | 1 | 2768 | /*
* Copyright (c) 2019 VenomVendor. All rights reserved.
* Created by VenomVendor on 18-Feb-2019.
*/
package com.venomvendor.tigerspike.ui.adapter
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.ListAdapter
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.RequestManager
import com.venomvendor.sdk.core.model.gallery.Feed
import com.venomvendor.tigerspike.R
import com.venomvendor.tigerspike.ui.factory.OnItemClickListener
import com.venomvendor.tigerspike.util.DiffUtilHelper
/**
* Recycler Adapter for displaying list of results.
*/
internal class GalleryListAdapter(glideManager: RequestManager) :
ListAdapter<Feed, GalleryListAdapter.GalleryViewHolder>(DiffUtilHelper.FEED_DIFF) {
// Image renderer
private val glide = glideManager
// Event listener
private var itemClickListener: OnItemClickListener<Feed>? = null
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): GalleryViewHolder {
val view = LayoutInflater.from(parent.context)
// Update item view
.inflate(R.layout.gallery_item, parent, false)
return GalleryViewHolder(view)
}
override fun onBindViewHolder(holder: GalleryViewHolder, position: Int) {
// Get item
val feed = getItem(position)
// Update views
holder.author.text = feed.author
holder.published.text = feed.published.toString()
// Load image
glide.load(feed.media.medium)
.centerCrop()
// place holder until image loads
.placeholder(R.drawable.ic_launcher_background)
.into(holder.media)
}
fun setOnItemClickLister(listener: OnItemClickListener<Feed>?) {
itemClickListener = listener
}
/**
* View Holder pattern, used by recycler view.
*/
internal inner class GalleryViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView),
View.OnClickListener {
internal val author: TextView = itemView.findViewById(R.id.author)
internal val published: TextView = itemView.findViewById(R.id.desc)
internal val media: ImageView = itemView.findViewById(R.id.media)
init {
// Add event listener
itemView.setOnClickListener(this)
}
override fun onClick(view: View) {
val selectedPos = adapterPosition
if (selectedPos == RecyclerView.NO_POSITION) {
return
}
// Pass on to root level event listener
itemClickListener?.onClick(getItem(selectedPos), view, selectedPos)
}
}
}
| apache-2.0 | b3d00cc36e67ac0aab0742e6eba387ff | 31.564706 | 95 | 0.689668 | 4.813913 | false | false | false | false |
dahlstrom-g/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/refactoring/introduce/introduceUtil.kt | 3 | 10467 | // 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.refactoring.introduce
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.editor.ScrollType
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.Key
import com.intellij.openapi.util.NlsContexts
import com.intellij.openapi.util.TextRange
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiWhiteSpace
import com.intellij.psi.util.PsiTreeUtil
import org.jetbrains.kotlin.idea.KotlinBundle
import org.jetbrains.kotlin.idea.base.psi.unifier.KotlinPsiRange
import org.jetbrains.kotlin.idea.core.util.CodeInsightUtils
import org.jetbrains.kotlin.idea.refactoring.chooseContainerElementIfNecessary
import org.jetbrains.kotlin.idea.refactoring.selectElement
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.*
import org.jetbrains.kotlin.utils.SmartList
fun showErrorHint(project: Project, editor: Editor, @NlsContexts.DialogMessage message: String, @NlsContexts.DialogTitle title: String) {
CodeInsightUtils.showErrorHint(project, editor, message, title, null)
}
fun showErrorHintByKey(project: Project, editor: Editor, messageKey: String, @NlsContexts.DialogTitle title: String) {
showErrorHint(project, editor, KotlinBundle.message(messageKey), title)
}
fun selectElementsWithTargetSibling(
@NlsContexts.DialogTitle operationName: String,
editor: Editor,
file: KtFile,
@NlsContexts.DialogTitle title: String,
elementKinds: Collection<CodeInsightUtils.ElementKind>,
elementValidator: (List<PsiElement>) -> String?,
getContainers: (elements: List<PsiElement>, commonParent: PsiElement) -> List<PsiElement>,
continuation: (elements: List<PsiElement>, targetSibling: PsiElement) -> Unit
) {
fun onSelectionComplete(elements: List<PsiElement>, targetContainer: PsiElement) {
val physicalElements = elements.map { it.substringContextOrThis }
val parent = PsiTreeUtil.findCommonParent(physicalElements)
?: throw AssertionError("Should have at least one parent: ${physicalElements.joinToString("\n")}")
if (parent == targetContainer) {
continuation(elements, physicalElements.first())
return
}
val outermostParent = parent.getOutermostParentContainedIn(targetContainer)
if (outermostParent == null) {
showErrorHintByKey(file.project, editor, "cannot.refactor.no.container", operationName)
return
}
continuation(elements, outermostParent)
}
selectElementsWithTargetParent(operationName, editor, file, title, elementKinds, elementValidator, getContainers, ::onSelectionComplete)
}
fun selectElementsWithTargetParent(
@NlsContexts.DialogTitle operationName: String,
editor: Editor,
file: KtFile,
@NlsContexts.DialogTitle title: String,
elementKinds: Collection<CodeInsightUtils.ElementKind>,
elementValidator: (List<PsiElement>) -> String?,
getContainers: (elements: List<PsiElement>, commonParent: PsiElement) -> List<PsiElement>,
continuation: (elements: List<PsiElement>, targetParent: PsiElement) -> Unit
) {
fun showErrorHintByKey(key: String) {
showErrorHintByKey(file.project, editor, key, operationName)
}
fun selectTargetContainer(elements: List<PsiElement>) {
elementValidator(elements)?.let {
showErrorHint(file.project, editor, it, operationName)
return
}
val physicalElements = elements.map { it.substringContextOrThis }
val parent = PsiTreeUtil.findCommonParent(physicalElements)
?: throw AssertionError("Should have at least one parent: ${physicalElements.joinToString("\n")}")
val containers = getContainers(physicalElements, parent)
if (containers.isEmpty()) {
showErrorHintByKey("cannot.refactor.no.container")
return
}
chooseContainerElementIfNecessary(
containers,
editor,
title,
true
) {
continuation(elements, it)
}
}
fun selectMultipleElements() {
val startOffset = editor.selectionModel.selectionStart
val endOffset = editor.selectionModel.selectionEnd
val elements = elementKinds.flatMap { CodeInsightUtils.findElements(file, startOffset, endOffset, it).toList() }
if (elements.isEmpty()) {
return when (elementKinds.singleOrNull()) {
CodeInsightUtils.ElementKind.EXPRESSION -> showErrorHintByKey("cannot.refactor.no.expression")
CodeInsightUtils.ElementKind.TYPE_ELEMENT -> showErrorHintByKey("cannot.refactor.no.type")
else -> showErrorHint(
file.project,
editor,
KotlinBundle.message("text.refactoring.can.t.be.performed.on.the.selected.code.element"),
title
)
}
}
selectTargetContainer(elements)
}
fun selectSingleElement() {
selectElement(editor, file, false, elementKinds) { expr ->
if (expr != null) {
selectTargetContainer(listOf(expr))
} else {
if (!editor.selectionModel.hasSelection()) {
if (elementKinds.singleOrNull() == CodeInsightUtils.ElementKind.EXPRESSION) {
val elementAtCaret = file.findElementAt(editor.caretModel.offset)
elementAtCaret?.getParentOfTypeAndBranch<KtProperty> { nameIdentifier }?.let {
return@selectElement selectTargetContainer(listOf(it))
}
}
editor.selectionModel.selectLineAtCaret()
}
selectMultipleElements()
}
}
}
editor.scrollingModel.scrollToCaret(ScrollType.MAKE_VISIBLE)
selectSingleElement()
}
fun PsiElement.findExpressionByCopyableDataAndClearIt(key: Key<Boolean>): KtExpression? {
val result = findDescendantOfType<KtExpression> { it.getCopyableUserData(key) != null } ?: return null
result.putCopyableUserData(key, null)
return result
}
fun PsiElement.findElementByCopyableDataAndClearIt(key: Key<Boolean>): PsiElement? {
val result = findDescendantOfType<PsiElement> { it.getCopyableUserData(key) != null } ?: return null
result.putCopyableUserData(key, null)
return result
}
fun PsiElement.findExpressionsByCopyableDataAndClearIt(key: Key<Boolean>): List<KtExpression> {
val results = collectDescendantsOfType<KtExpression> { it.getCopyableUserData(key) != null }
results.forEach { it.putCopyableUserData(key, null) }
return results
}
fun findExpressionOrStringFragment(file: KtFile, startOffset: Int, endOffset: Int): KtExpression? {
val entry1 = file.findElementAt(startOffset)?.getNonStrictParentOfType<KtStringTemplateEntry>() ?: return null
val entry2 = file.findElementAt(endOffset - 1)?.getNonStrictParentOfType<KtStringTemplateEntry>() ?: return null
if (entry1 == entry2 && entry1 is KtStringTemplateEntryWithExpression) return entry1.expression
val stringTemplate = entry1.parent as? KtStringTemplateExpression ?: return null
if (entry2.parent != stringTemplate) return null
val templateOffset = stringTemplate.startOffset
if (stringTemplate.getContentRange().equalsToRange(startOffset - templateOffset, endOffset - templateOffset)) return stringTemplate
val prefixOffset = startOffset - entry1.startOffset
if (entry1 !is KtLiteralStringTemplateEntry && prefixOffset > 0) return null
val suffixOffset = endOffset - entry2.startOffset
if (entry2 !is KtLiteralStringTemplateEntry && suffixOffset < entry2.textLength) return null
val prefix = entry1.text.substring(0, prefixOffset)
val suffix = entry2.text.substring(suffixOffset)
return ExtractableSubstringInfo(entry1, entry2, prefix, suffix).createExpression()
}
fun KotlinPsiRange.getPhysicalTextRange(): TextRange {
return (elements.singleOrNull() as? KtExpression)?.extractableSubstringInfo?.contentRange ?: textRange
}
fun ExtractableSubstringInfo.replaceWith(replacement: KtExpression): KtExpression {
return with(this) {
val psiFactory = KtPsiFactory(replacement)
val parent = startEntry.parent
psiFactory.createStringTemplate(prefix).entries.singleOrNull()?.let { parent.addBefore(it, startEntry) }
val refEntry = psiFactory.createBlockStringTemplateEntry(replacement)
val addedRefEntry = parent.addBefore(refEntry, startEntry) as KtStringTemplateEntryWithExpression
psiFactory.createStringTemplate(suffix).entries.singleOrNull()?.let { parent.addAfter(it, endEntry) }
parent.deleteChildRange(startEntry, endEntry)
addedRefEntry.expression!!
}
}
fun KtExpression.mustBeParenthesizedInInitializerPosition(): Boolean {
if (this !is KtBinaryExpression) return false
if (left?.mustBeParenthesizedInInitializerPosition() == true) return true
return PsiChildRange(left, operationReference).any { (it is PsiWhiteSpace) && it.textContains('\n') }
}
fun isObjectOrNonInnerClass(e: PsiElement): Boolean = e is KtObjectDeclaration || (e is KtClass && !e.isInner())
fun <T : KtDeclaration> insertDeclaration(declaration: T, targetSibling: PsiElement): T {
val targetParent = targetSibling.parent
val anchorCandidates = SmartList<PsiElement>()
anchorCandidates.add(targetSibling)
if (targetSibling is KtEnumEntry) {
anchorCandidates.add(targetSibling.siblings().last { it is KtEnumEntry })
}
val anchor = anchorCandidates.minByOrNull { it.startOffset }!!.parentsWithSelf.first { it.parent == targetParent }
val targetContainer = anchor.parent!!
@Suppress("UNCHECKED_CAST")
return (targetContainer.addBefore(declaration, anchor) as T).apply {
targetContainer.addBefore(KtPsiFactory(declaration).createWhiteSpace("\n\n"), anchor)
}
}
internal fun validateExpressionElements(elements: List<PsiElement>): String? {
if (elements.any { it is KtConstructor<*> || it is KtParameter || it is KtTypeAlias || it is KtPropertyAccessor }) {
return KotlinBundle.message("text.refactoring.is.not.applicable.to.this.code.fragment")
}
return null
}
| apache-2.0 | 4ea4637fdd3450ef06265e1f9d9de228 | 41.897541 | 158 | 0.714054 | 5.217846 | false | false | false | false |
spoptchev/kotlin-preconditions | src/test/kotlin/com/github/spoptchev/kotlin/preconditions/AssertionTest.kt | 1 | 767 | package com.github.spoptchev.kotlin.preconditions
import org.junit.Test
import kotlin.test.assertEquals
import kotlin.test.fail
class AssertionTest {
private val boolMatcher = object : Matcher<Boolean>() {
override fun test(condition: Condition<Boolean>): Result = Result(condition.value) { "message" }
}
@Test fun `test run with valid result`() {
val assertion = Assertion(true, "value", ::require)
val result = assertion.run(boolMatcher)
assertEquals(true, result)
}
@Test(expected = IllegalArgumentException::class)
fun `test run with invalid result`() {
val assertion = Assertion(false, "value", ::require)
assertion.run(boolMatcher)
fail("should not be executed")
}
}
| mit | d8ceb520cafe329e7d9b05577a15a3a7 | 24.566667 | 104 | 0.670143 | 4.214286 | false | true | false | false |
Pagejects/pagejects-core | src/main/kotlin/net/pagejects/core/click/ClickUserAction.kt | 1 | 1899 | package net.pagejects.core.click
import com.codeborne.selenide.SelenideElement
import net.pagejects.core.UserAction
import net.pagejects.core.annotation.Click
import net.pagejects.core.impl.wait
import net.pagejects.core.service.PageObjectService
import net.pagejects.core.service.PageObjectServiceAware
import net.pagejects.core.service.SelenideElementService
import net.pagejects.core.service.SelenideElementServiceAware
/**
* Implementation of the [UserAction] for @[Click]
*
* @author Andrey Paslavsky
* @since 0.1
*/
class ClickUserAction(
private val pageObjectName: String,
private val clickAnnotation: Click,
private val returnType: Class<*>? = null
) : UserAction<Any?>, SelenideElementServiceAware, PageObjectServiceAware {
private lateinit var selenideElementService: SelenideElementService
private lateinit var pageObjectService: PageObjectService
override fun aware(service: PageObjectService) {
pageObjectService = service
}
override fun aware(service: SelenideElementService) {
selenideElementService = service
}
override fun perform(params: Array<out Any>?): Any? {
val selenideElement = selenideElementService.get(pageObjectName, clickAnnotation.elementName)
selenideElement.waitBeforeClick()
when (clickAnnotation.type) {
Click.ClickType.CLICK -> selenideElement.click()
Click.ClickType.DOUBLE_CLICK -> selenideElement.doubleClick()
Click.ClickType.CONTEXT_CLICK -> selenideElement.contextClick()
}
selenideElement.waitAfterClick()
return if (returnType == null) Unit else pageObjectService.pageObject(returnType)
}
fun SelenideElement.waitBeforeClick() {
this.wait(clickAnnotation.waiteBefore)
}
fun SelenideElement.waitAfterClick() {
this.wait(clickAnnotation.waiteAfter)
}
} | apache-2.0 | 6548c5e7888d26e1647acbf7aa1a8248 | 32.333333 | 101 | 0.739863 | 4.881748 | false | false | false | false |
gituser9/InvoiceManagement | app/src/main/java/com/user/invoicemanagement/view/adapter/MainSection.kt | 1 | 7245 | package com.user.invoicemanagement.view.adapter
import android.support.v7.widget.RecyclerView
import android.view.View
import com.user.invoicemanagement.model.data.WeightEnum
import com.user.invoicemanagement.model.dto.Product
import com.user.invoicemanagement.model.dto.ProductFactory
import com.user.invoicemanagement.other.Constant
import com.user.invoicemanagement.view.adapter.holder.MainFooterViewHolder
import com.user.invoicemanagement.view.adapter.holder.MainHeaderViewHolder
import com.user.invoicemanagement.view.adapter.holder.MainViewHolder
import com.user.invoicemanagement.view.interfaces.MainView
import io.github.luizgrp.sectionedrecyclerviewadapter.SectionParameters
import io.github.luizgrp.sectionedrecyclerviewadapter.StatelessSection
class MainSection(sectionParameters: SectionParameters, private val factory: ProductFactory, var list: List<Product>, private val mainView: MainView) : StatelessSection(sectionParameters) {
private var footerHolder: MainFooterViewHolder? = null
private var holders = mutableListOf<MainViewHolder>()
override fun getContentItemsTotal(): Int = list.size
override fun getItemViewHolder(view: View): RecyclerView.ViewHolder = MainViewHolder(view)
override fun onBindItemViewHolder(holder: RecyclerView.ViewHolder?, position: Int) {
val itemHolder = holder as MainViewHolder
val product = list[position]
holders.add(itemHolder)
itemHolder.product = product
itemHolder.setListener(View.OnLongClickListener {
if (itemHolder.product != null) {
mainView.deleteProduct(itemHolder.product!!)
}
true
})
itemHolder.edtName.setText(product.name)
itemHolder.btnWeightOnStore.text = product.weightOnStore.toString()
itemHolder.btnWeightInFridge.text = product.weightInFridge.toString()
itemHolder.btnWeightInStorage.text = product.weightInStorage.toString()
itemHolder.btnWeight4.text = product.weight4.toString()
itemHolder.btnWeight5.text = product.weight5.toString()
itemHolder.edtWeightOnStore.setText(product.weightOnStore.toString())
itemHolder.edtWeightInFridge.setText(product.weightInFridge.toString())
itemHolder.edtWeightInStorage.setText(product.weightInStorage.toString())
itemHolder.edtWeight4.setText(product.weight4.toString())
itemHolder.edtWeight5.setText(product.weight5.toString())
if (product.purchasePrice != 0f) {
itemHolder.edtPurchasePrice.setText(product.purchasePrice.toString())
}
if (product.sellingPrice != 0f) {
itemHolder.edtSellingPrice.setText(product.sellingPrice.toString())
}
itemHolder.tvPurchasePriceSummary.text = Constant.priceFormat.format(product.purchasePriceSummary)
itemHolder.tvSellingPriceSummary.text = Constant.priceFormat.format(product.sellingPriceSummary)
itemHolder.btnWeightOnStore.setOnClickListener { mainView.showSetWeightDialog(itemHolder.btnWeightOnStore, product, WeightEnum.WEIGHT_1) }
itemHolder.btnWeightInFridge.setOnClickListener { mainView.showSetWeightDialog(itemHolder.btnWeightInFridge, product, WeightEnum.WEIGHT_2) }
itemHolder.btnWeightInStorage.setOnClickListener { mainView.showSetWeightDialog(itemHolder.btnWeightInStorage, product, WeightEnum.WEIGHT_3) }
itemHolder.btnWeight4.setOnClickListener { mainView.showSetWeightDialog(itemHolder.btnWeight4, product, WeightEnum.WEIGHT_4) }
itemHolder.btnWeight5.setOnClickListener { mainView.showSetWeightDialog(itemHolder.btnWeight5, product, WeightEnum.WEIGHT_5) }
}
override fun getHeaderViewHolder(view: View): RecyclerView.ViewHolder = MainHeaderViewHolder(view)
override fun onBindHeaderViewHolder(holder: RecyclerView.ViewHolder?) {
val itemHolder = holder as MainHeaderViewHolder
itemHolder.tvHeader.text = factory.name
itemHolder.btnAddProduct.setOnClickListener {
mainView.saveAll()
mainView.addNewProduct(factory.id)
}
itemHolder.btnEditName.setOnClickListener {
mainView.saveAll()
mainView.showEditFactoryDialog(factory)
}
itemHolder.btnDelete.setOnClickListener {
mainView.saveAll()
mainView.deleteFactory(factory.id)
}
}
override fun getFooterViewHolder(view: View): RecyclerView.ViewHolder = MainFooterViewHolder(view)
override fun onBindFooterViewHolder(holder: RecyclerView.ViewHolder?) {
val itemHolder = holder as MainFooterViewHolder
footerHolder = itemHolder
setFooterData()
itemHolder.btnAddNew.setOnClickListener {
mainView.saveAll()
mainView.addNewProduct(factory.id)
}
}
fun getViewData(): List<Product> {
val products = mutableListOf<Product>()
for (item in holders) {
if (item.product != null) {
try {
item.product!!.name = item.edtName.text.toString()
item.product!!.weightOnStore = prepareString(item.btnWeightOnStore.text.toString()).toFloatOrNull() ?: 0f
item.product!!.weightInFridge = prepareString(item.btnWeightInFridge.text.toString()).toFloatOrNull() ?: 0f
item.product!!.weightInStorage = prepareString(item.btnWeightInStorage.text.toString()).toFloatOrNull() ?: 0f
item.product!!.weight4 = prepareString(item.btnWeight4.text.toString()).toFloatOrNull() ?: 0f
item.product!!.weight5 = prepareString(item.btnWeight5.text.toString()).toFloatOrNull() ?: 0f
item.product!!.purchasePrice = prepareString(item.edtPurchasePrice.text.toString()).toFloatOrNull() ?: 0f
item.product!!.sellingPrice = prepareString(item.edtSellingPrice.text.toString()).toFloatOrNull() ?: 0f
} catch (e: Exception) {
continue
}
products.add(item.product!!)
}
}
return products
}
fun updateSummaryData() {
for (item in holders) {
if (item.product != null) {
item.tvPurchasePriceSummary.text = Constant.priceFormat.format(item.product!!.purchasePriceSummary)
item.tvSellingPriceSummary.text = Constant.priceFormat.format(item.product!!.sellingPriceSummary)
setFooterData()
}
}
}
private fun setFooterData() {
if (footerHolder == null) {
return
}
var purchaseSummary = 0f
var sellingSummary = 0f
list.forEach { product: Product ->
purchaseSummary += product.purchasePriceSummary
sellingSummary += product.sellingPriceSummary
}
footerHolder?.mainFooterPurchaseSummary?.text = Constant.priceFormat.format(purchaseSummary)
footerHolder?.mainFooterSellingSummary?.text = Constant.priceFormat.format(sellingSummary)
}
private fun prepareString(string: String): String {
return string
.replace(',', '.')
.replace(Constant.whiteSpaceRegex, "")
}
} | mit | 4fcf42c99b37b1105891715257f08ca6 | 44.006211 | 189 | 0.697585 | 5.127389 | false | false | false | false |
vladmm/intellij-community | platform/diff-impl/tests/com/intellij/diff/comparison/ComparisonMergeUtilTestBase.kt | 1 | 5391 | /*
* Copyright 2000-2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.diff.comparison
import com.intellij.diff.DiffTestCase
import com.intellij.diff.util.IntPair
import com.intellij.diff.util.MergeRange
import com.intellij.diff.util.ThreeSide
import com.intellij.openapi.editor.Document
import com.intellij.openapi.editor.impl.DocumentImpl
import com.intellij.openapi.util.Couple
import com.intellij.util.containers.ContainerUtil
import java.util.*
abstract class ComparisonMergeUtilTestBase : DiffTestCase() {
private fun doCharTest(texts: Trio<Document>, expected: List<Change>?, matchings: Trio<BitSet>?) {
val iterable1 = ByChar.compare(texts.data2.charsSequence, texts.data1.charsSequence, INDICATOR)
val iterable2 = ByChar.compare(texts.data2.charsSequence, texts.data3.charsSequence, INDICATOR)
val fragments = ComparisonMergeUtil.buildFair(iterable1, iterable2, INDICATOR)
val actual = convertDiffFragments(fragments)
checkConsistency(actual, texts)
if (matchings != null) checkDiffMatching(actual, matchings)
if (expected != null) checkDiffChanges(actual, expected)
}
private fun checkConsistency(actual: List<Change>, texts: Trio<Document>) {
var lasts = Trio(-1, -1, -1)
for (change in actual) {
val starts = change.starts
val ends = change.ends
var empty = true
var squashed = true
ThreeSide.values.forEach {
val start = starts(it)
val end = ends(it)
val last = lasts(it)
assertTrue(last <= start)
assertTrue(start <= end)
empty = empty && (start == end)
squashed = squashed && (start == last)
}
assertTrue(!empty)
assertTrue(!squashed)
lasts = ends
}
}
private fun checkDiffChanges(actual: List<Change>, expected: List<Change>) {
assertOrderedEquals(expected, actual)
}
private fun checkDiffMatching(changes: List<Change>, matchings: Trio<BitSet>) {
val sets = Trio(BitSet(), BitSet(), BitSet())
for (change in changes) {
sets.forEach({ set: BitSet, side: ThreeSide -> set.set(change.start(side), change.end(side)) })
}
assertEquals(matchings.data1, sets.data1)
assertEquals(matchings.data2, sets.data2)
assertEquals(matchings.data3, sets.data3)
}
private fun convertDiffFragments(fragments: List<MergeRange>): List<Change> {
return fragments.map {
Change(
it.start1, it.end1,
it.start2, it.end2,
it.start3, it.end3)
}
}
private enum class TestType {
CHAR
}
inner class MergeTestBuilder(val type: TestType) {
private var isExecuted: Boolean = false
private var texts: Trio<Document>? = null
private var changes: List<Change>? = null
private var matching: Trio<BitSet>? = null
fun assertExecuted() {
assertTrue(isExecuted)
}
fun test() {
isExecuted = true
assertTrue(changes != null || matching != null)
when (type) {
TestType.CHAR -> doCharTest(texts!!, changes, matching)
}
}
operator fun String.minus(v: String): Couple<String> {
return Couple(this, v)
}
operator fun Couple<String>.minus(v: String): Helper {
return Helper(Trio(this.first, this.second, v))
}
inner class Helper(val texts: Trio<String>) {
init {
val builder = this@MergeTestBuilder
if (builder.texts == null) {
builder.texts = texts.map { it -> DocumentImpl(it) }
}
}
fun matching() {
matching = texts.map { it -> parseMatching(it) }
}
}
fun changes(vararg expected: Change): Unit {
changes = ContainerUtil.list(*expected)
}
fun mod(line1: Int, line2: Int, line3: Int, count1: Int, count2: Int, count3: Int): Change {
return Change(line1, line1 + count1, line2, line2 + count2, line3, line3 + count3)
}
}
fun chars(f: MergeTestBuilder.() -> Unit) {
doTest(TestType.CHAR, f)
}
private fun doTest(type: TestType, f: MergeTestBuilder.() -> Unit) {
val builder = MergeTestBuilder(type)
builder.f()
builder.assertExecuted()
}
class Change(start1: Int, end1: Int, start2: Int, end2: Int, start3: Int, end3: Int)
: Trio<IntPair>(IntPair(start1, end1), IntPair(start2, end2), IntPair(start3, end3)) {
val start1 = start(ThreeSide.LEFT)
val start2 = start(ThreeSide.BASE)
val start3 = start(ThreeSide.RIGHT)
val end1 = end(ThreeSide.LEFT)
val end2 = end(ThreeSide.BASE)
val end3 = end(ThreeSide.RIGHT)
val starts = Trio(start1, start2, start3)
val ends = Trio(end1, end2, end3)
fun start(side: ThreeSide): Int = this(side).val1
fun end(side: ThreeSide): Int = this(side).val2
override fun toString(): String {
return "($start1, $end1) - ($start2, $end2) - ($start3, $end3)"
}
}
}
| apache-2.0 | f5891d0146575a71b2464e6060f88a25 | 28.140541 | 101 | 0.664441 | 3.884006 | false | true | false | false |
neilellis/kontrol | webserver/src/main/kotlin/kontrol/webserver/Response.kt | 1 | 4947 | /*
* Copyright 2014 Cazcade Limited (http://cazcade.com)
*
* 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 kontrol.webserver
import org.apache.commons.io.IOUtils
import java.io.*
import java.text.SimpleDateFormat
import java.util.*
/*
* Copyright 2014 Cazcade Limited (http://cazcade.com)
*
* 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.
*/
/**
* HTTP response. Return one of these from serve().
*/
public open class Response(var status: Status = Status.OK, var mimeType: String = "text/html", text: String? = null, var data: InputStream? = if (text != null) ByteArrayInputStream(text.getBytes("UTF-8")) else null) {
/**
* Headers for the HTTP response. Use addHeader() to add lines.
*/
var header: MutableMap<String, String> = HashMap<String, String>()
/**
* The request method that spawned this response.
*/
var requestMethod: Method? = null
/**
* Use chunkedTransfer
*/
var chunkedTransfer: Boolean = false
/**
* Adds given line to the header.
*/
public open fun addHeader(name: String, value: String): Unit {
header.put(name, value)
}
/**
* Sends given response to the socket.
*/
open fun send(outputStream: OutputStream): Unit {
val mime = mimeType
val gmtFrmt = SimpleDateFormat("E, d MMM yyyy HH:mm:ss 'GMT'", Locale.US)
gmtFrmt.setTimeZone(TimeZone.getTimeZone("GMT"))
try
{
val pw = PrintWriter(outputStream)
pw.print("HTTP/1.1 " + status.getFullDescription() + " \r\n")
pw.print("Content-Type: " + mime + "\r\n")
if ( header.get("Date") == null)
{
pw.print("Date: " + gmtFrmt.format(Date()) + "\r\n")
}
for (key in header.keySet()!!)
{
val value = header.get(key)
pw.print(key + ": " + value + "\r\n")
}
pw.print("Connection: keep-alive\r\n")
if (requestMethod != Method.HEAD && chunkedTransfer)
{
sendAsChunked(outputStream, pw)
}
else
{
sendAsFixedLength(outputStream, pw)
}
outputStream.flush()
IOUtils.closeQuietly(data)
}
catch (ioe: IOException) {
// Couldn't write? No can do.
}
}
private fun sendAsChunked(outputStream: OutputStream, pw: PrintWriter): Unit {
pw.print("Transfer-Encoding: chunked\r\n")
pw.print("\r\n")
pw.flush()
val BUFFER_SIZE = 16 * 1024
val CRLF = "\r\n".getBytes()
val buff = ByteArray(BUFFER_SIZE)
while ( true)
{
val read = data?.read(buff)!!
if (read < 0) {
break
}
outputStream.write("%x\r\n".format(read).getBytes())
outputStream.write(buff, 0, read)
outputStream.write(CRLF)
}
outputStream.write(("0\r\n\r\n".format().getBytes()))
}
private fun sendAsFixedLength(outputStream: OutputStream, pw: PrintWriter): Unit {
var pending: Int = (if (data != null)
data?.available()?:-1
else
0)
pw.print("Content-Length: " + pending + "\r\n")
pw.print("\r\n")
pw.flush()
if (requestMethod != Method.HEAD && data != null)
{
val BUFFER_SIZE = 16 * 1024
val buff = ByteArray(BUFFER_SIZE)
while (pending > 0)
{
val read = data?.read(buff, 0, ((if ((pending > BUFFER_SIZE))
BUFFER_SIZE
else
pending)))!!
if (read <= 0)
{
break
}
outputStream.write(buff, 0, read)
pending -= read
}
}
}
}
| apache-2.0 | 003e7dba12332705a008822350e641ac | 30.916129 | 217 | 0.563978 | 4.25 | false | false | false | false |
paplorinc/intellij-community | platform/diff-impl/src/com/intellij/diff/statistics/DiffUsagesCollector.kt | 2 | 3226 | // Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.diff.statistics
import com.intellij.diff.impl.DiffSettingsHolder.DiffSettings
import com.intellij.diff.tools.external.ExternalDiffSettings
import com.intellij.diff.tools.fragmented.UnifiedDiffTool
import com.intellij.diff.tools.simple.SimpleDiffTool
import com.intellij.diff.tools.util.base.TextDiffSettingsHolder.TextDiffSettings
import com.intellij.diff.util.DiffPlaces
import com.intellij.internal.statistic.beans.UsageDescriptor
import com.intellij.internal.statistic.service.fus.collectors.ApplicationUsagesCollector
import com.intellij.internal.statistic.utils.getBooleanUsage
import com.intellij.internal.statistic.utils.getEnumUsage
import java.util.*
class DiffUsagesCollector : ApplicationUsagesCollector() {
override fun getGroupId(): String {
return "vcs.diff"
}
override fun getUsages(): MutableSet<UsageDescriptor> {
val usages = HashSet<UsageDescriptor>()
val places = listOf(DiffPlaces.DEFAULT,
DiffPlaces.CHANGES_VIEW,
DiffPlaces.VCS_LOG_VIEW,
DiffPlaces.COMMIT_DIALOG,
DiffPlaces.MERGE,
DiffPlaces.TESTS_FAILED_ASSERTIONS)
for (place in places) {
val diffSettings = DiffSettings.getSettings(place)
val textSettings = TextDiffSettings.getSettings(place)
usages.add(getEnumUsage("ignore.policy.$place", textSettings.ignorePolicy))
usages.add(getEnumUsage("highlight.policy.$place", textSettings.highlightPolicy))
usages.add(getEnumUsage("show.warnings.policy.$place", textSettings.highlightingLevel))
usages.add(getBooleanUsage("collapse.unchanged.$place", !textSettings.isExpandByDefault))
usages.add(getBooleanUsage("show.line.numbers.$place", textSettings.isShowLineNumbers))
usages.add(getBooleanUsage("use.soft.wraps.$place", textSettings.isUseSoftWraps))
usages.add(getBooleanUsage("use.unified.diff.$place", isUnifiedToolDefault(diffSettings)))
if (place == DiffPlaces.COMMIT_DIALOG) {
usages.add(getBooleanUsage("enable.read.lock.$place", textSettings.isReadOnlyLock))
}
}
val diffSettings = DiffSettings.getSettings(null)
usages.add(getBooleanUsage("iterate.next.file", diffSettings.isGoToNextFileOnNextDifference))
val externalSettings = ExternalDiffSettings.getInstance()
usages.add(getBooleanUsage("external.diff", externalSettings.isDiffEnabled))
usages.add(getBooleanUsage("external.diff.default", externalSettings.isDiffEnabled && externalSettings.isDiffDefault))
usages.add(getBooleanUsage("external.merge", externalSettings.isMergeEnabled))
return usages
}
private fun isUnifiedToolDefault(settings: DiffSettings): Boolean {
val toolOrder = settings.diffToolsOrder
val defaultToolIndex = toolOrder.indexOf(SimpleDiffTool::class.java.canonicalName)
val unifiedToolIndex = toolOrder.indexOf(UnifiedDiffTool::class.java.canonicalName)
if (unifiedToolIndex == -1) return false
return defaultToolIndex == -1 || unifiedToolIndex < defaultToolIndex
}
}
| apache-2.0 | 7f16681eab02a4a7a058a6227d449605 | 47.878788 | 140 | 0.758524 | 4.814925 | false | false | false | false |
google/intellij-community | plugins/kotlin/j2k/old/src/org/jetbrains/kotlin/j2k/ast/Statements.kt | 2 | 6247 | // 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.j2k.ast
import org.jetbrains.kotlin.j2k.CodeBuilder
import org.jetbrains.kotlin.j2k.append
abstract class Statement : Element() {
object Empty : Statement() {
override fun generateCode(builder: CodeBuilder) { }
override val isEmpty: Boolean get() = true
}
}
class DeclarationStatement(val elements: List<Element>) : Statement() {
override fun generateCode(builder: CodeBuilder) {
builder.append(elements, "\n")
}
}
class ExpressionListStatement(val expressions: List<Expression>) : Expression() {
override fun generateCode(builder: CodeBuilder) {
builder.append(expressions, "\n")
}
}
class LabeledStatement(val name: Identifier, val statement: Element) : Statement() {
override fun generateCode(builder: CodeBuilder) {
builder append name append "@" append " " append statement
}
}
class ReturnStatement(val expression: Expression, val label: Identifier? = null) : Statement() {
override fun generateCode(builder: CodeBuilder) {
builder append "return"
if (label != null) {
builder append "@" append label
}
builder append " " append expression
}
}
class IfStatement(
val condition: Expression,
val thenStatement: Element,
val elseStatement: Element,
singleLine: Boolean
) : Expression() {
private val br = if (singleLine) " " else "\n"
private val brAfterElse = if (singleLine || elseStatement is IfStatement) " " else "\n"
override fun generateCode(builder: CodeBuilder) {
builder append "if (" append condition append ")" append br append thenStatement.wrapToBlockIfRequired()
if (!elseStatement.isEmpty) {
builder append br append "else" append brAfterElse append elseStatement.wrapToBlockIfRequired()
}
else if (thenStatement.isEmpty) {
builder append ";"
}
}
}
// Loops --------------------------------------------------------------------------------------------------
class WhileStatement(val condition: Expression, val body: Element, singleLine: Boolean) : Statement() {
private val br = if (singleLine) " " else "\n"
override fun generateCode(builder: CodeBuilder) {
builder append "while (" append condition append ")" append br append body.wrapToBlockIfRequired()
if (body.isEmpty) {
builder append ";"
}
}
}
class DoWhileStatement(val condition: Expression, val body: Element, singleLine: Boolean) : Statement() {
private val br = if (singleLine) " " else "\n"
override fun generateCode(builder: CodeBuilder) {
builder append "do" append br append body.wrapToBlockIfRequired() append br append "while (" append condition append ")"
}
}
class ForeachStatement(
val variableName: Identifier,
val explicitVariableType: Type?,
val collection: Expression,
val body: Element,
singleLine: Boolean
) : Statement() {
private val br = if (singleLine) " " else "\n"
override fun generateCode(builder: CodeBuilder) {
builder append "for (" append variableName
if (explicitVariableType != null) {
builder append ":" append explicitVariableType
}
builder append " in " append collection append ")" append br append body.wrapToBlockIfRequired()
if (body.isEmpty) {
builder append ";"
}
}
}
class BreakStatement(val label: Identifier = Identifier.Empty) : Statement() {
override fun generateCode(builder: CodeBuilder) {
builder.append("break").appendWithPrefix(label, "@")
}
}
class ContinueStatement(val label: Identifier = Identifier.Empty) : Statement() {
override fun generateCode(builder: CodeBuilder) {
builder.append("continue").appendWithPrefix(label, "@")
}
}
// Exceptions ----------------------------------------------------------------------------------------------
class TryStatement(val block: Block, val catches: List<CatchStatement>, val finallyBlock: Block) : Statement() {
override fun generateCode(builder: CodeBuilder) {
builder.append("try\n").append(block).append("\n").append(catches, "\n").append("\n")
if (!finallyBlock.isEmpty) {
builder append "finally\n" append finallyBlock
}
}
}
class ThrowStatement(val expression: Expression) : Expression() {
override fun generateCode(builder: CodeBuilder) {
builder append "throw " append expression
}
}
class CatchStatement(val variable: FunctionParameter, val block: Block) : Statement() {
override fun generateCode(builder: CodeBuilder) {
builder append "catch (" append variable append ") " append block
}
}
// when --------------------------------------------------------------------------------------------------
class WhenStatement(val subject: Expression, val caseContainers: List<WhenEntry>) : Statement() {
override fun generateCode(builder: CodeBuilder) {
builder.append("when (").append(subject).append(") {\n").append(caseContainers, "\n").append("\n}")
}
}
class WhenEntry(val selectors: List<WhenEntrySelector>, val body: Statement) : Statement() {
override fun generateCode(builder: CodeBuilder) {
builder.append(selectors, ", ").append(" -> ").append(body)
}
}
abstract class WhenEntrySelector : Statement()
class ValueWhenEntrySelector(val expression: Expression) : WhenEntrySelector() {
override fun generateCode(builder: CodeBuilder) {
builder.append(expression)
}
}
class ElseWhenEntrySelector : WhenEntrySelector() {
override fun generateCode(builder: CodeBuilder) {
builder.append("else")
}
}
// Other ------------------------------------------------------------------------------------------------------
class SynchronizedStatement(val expression: Expression, val block: Block) : Statement() {
override fun generateCode(builder: CodeBuilder) {
builder append "synchronized (" append expression append ") " append block
}
}
| apache-2.0 | f48331e27bb99aa37ceafff252d67077 | 34.494318 | 158 | 0.631503 | 4.93834 | false | false | false | false |
apoi/quickbeer-next | app/src/main/java/quickbeer/android/ui/adapter/brewer/BrewerListViewHolder.kt | 2 | 2545 | package quickbeer.android.ui.adapter.brewer
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import quickbeer.android.data.state.State
import quickbeer.android.databinding.BrewerListItemBinding
import quickbeer.android.domain.brewer.Brewer
import quickbeer.android.domain.country.Country
import quickbeer.android.feature.beerdetails.model.Address
import quickbeer.android.ui.adapter.base.ScopeListViewHolder
class BrewerListViewHolder(
private val binding: BrewerListItemBinding
) : ScopeListViewHolder<BrewerListModel>(binding.root) {
override fun bind(item: BrewerListModel, scope: CoroutineScope) {
clear()
scope.launch {
item.getBrewer(item.brewerId).collect {
if (it is State.Loading && it.value?.countryId != null) {
getCountry(it.value, item, scope)
} else if (it is State.Success && it.value.countryId != null) {
getCountry(it.value, item, scope)
}
withContext(Dispatchers.Main) { updateState(it) }
}
}
}
private fun getCountry(brewer: Brewer?, item: BrewerListModel, scope: CoroutineScope) {
if (brewer?.countryId == null) return
scope.launch {
item.getCountry(brewer.countryId)
.map { mergeAddress(brewer, it) }
.collect { withContext(Dispatchers.Main) { setAddress(it) } }
}
}
private fun mergeAddress(brewer: Brewer, country: State<Country>): Address? {
return if (country is State.Success) {
Address.from(brewer, country.value)
} else null
}
private fun updateState(state: State<Brewer>) {
when (state) {
is State.Initial -> Unit
is State.Loading -> state.value?.let(::setBrewer)
is State.Empty -> Unit
is State.Success -> setBrewer(state.value)
is State.Error -> Unit
}
}
private fun setBrewer(brewer: Brewer) {
binding.brewerName.text = brewer.name
}
private fun setAddress(address: Address?) {
if (address == null) return
binding.brewerLocation.text = address.cityAndCountry()
binding.brewerCountry.text = address.code
}
private fun clear() {
binding.brewerName.text = ""
binding.brewerLocation.text = ""
}
}
| gpl-3.0 | af81919fe9c68ee03295b9555682f779 | 32.051948 | 91 | 0.647151 | 4.496466 | false | false | false | false |
RuneSuite/client | updater-mapper/src/main/java/org/runestar/client/updater/mapper/std/classes/ClientError.kt | 1 | 752 | package org.runestar.client.updater.mapper.std.classes
import org.runestar.client.updater.mapper.IdentityMapper
import org.runestar.client.updater.mapper.predicateOf
import org.runestar.client.updater.mapper.type
import org.runestar.client.updater.mapper.Class2
import org.runestar.client.updater.mapper.Field2
class ClientError : IdentityMapper.Class() {
override val predicate = predicateOf<Class2> { it.superType == RuntimeException::class.type }
class cause : IdentityMapper.InstanceField() {
override val predicate = predicateOf<Field2> { it.type == Throwable::class.type }
}
class message : IdentityMapper.InstanceField() {
override val predicate = predicateOf<Field2> { it.type == String::class.type }
}
} | mit | b8d15398c9a05f3a23a76c6bf3277dd1 | 38.631579 | 97 | 0.759309 | 4.177778 | false | false | false | false |
google/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/createFromUsage/callableBuilder/CallableInfo.kt | 2 | 13847 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.quickfix.createFromUsage.callableBuilder
import com.intellij.psi.PsiElement
import com.intellij.util.ArrayUtil
import org.jetbrains.kotlin.cfg.containingDeclarationForPseudocode
import org.jetbrains.kotlin.descriptors.ClassDescriptorWithResolutionScopes
import org.jetbrains.kotlin.descriptors.DescriptorVisibility
import org.jetbrains.kotlin.idea.base.fe10.codeInsight.newDeclaration.Fe10KotlinNameSuggester
import org.jetbrains.kotlin.idea.caches.resolve.resolveToDescriptorIfAny
import org.jetbrains.kotlin.idea.quickfix.createFromUsage.createClass.ClassInfo
import org.jetbrains.kotlin.idea.util.application.withPsiAttachment
import org.jetbrains.kotlin.idea.util.getResolutionScope
import org.jetbrains.kotlin.idea.util.getResolvableApproximations
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.parents
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.DescriptorToSourceUtils
import org.jetbrains.kotlin.resolve.scopes.LexicalScope
import org.jetbrains.kotlin.types.error.ErrorUtils
import org.jetbrains.kotlin.types.KotlinType
import org.jetbrains.kotlin.types.Variance
import org.jetbrains.kotlin.types.typeUtil.makeNotNullable
import org.jetbrains.kotlin.utils.KotlinExceptionWithAttachments
import java.util.*
/**
* Represents a concrete type or a set of types yet to be inferred from an expression.
*/
abstract class TypeInfo(val variance: Variance) {
object Empty : TypeInfo(Variance.INVARIANT) {
override fun getPossibleTypes(builder: CallableBuilder): List<KotlinType> = Collections.emptyList()
}
class ByExpression(val expression: KtExpression, variance: Variance) : TypeInfo(variance) {
override fun getPossibleNamesFromExpression(bindingContext: BindingContext): Array<String> {
return Fe10KotlinNameSuggester.suggestNamesByExpressionOnly(expression, bindingContext, { true }).toTypedArray()
}
override fun getPossibleTypes(builder: CallableBuilder): List<KotlinType> = expression.guessTypes(
context = builder.currentFileContext,
module = builder.currentFileModule,
pseudocode = try {
builder.pseudocode
} catch (stackException: EmptyStackException) {
val originalElement = builder.config.originalElement
val containingDeclarationForPseudocode = originalElement.containingDeclarationForPseudocode
// copy-pasted from org.jetbrains.kotlin.cfg.pseudocode.PseudocodeUtilsKt.getContainingPseudocode
val enclosingPseudocodeDeclaration = (containingDeclarationForPseudocode as? KtFunctionLiteral)?.let { functionLiteral ->
functionLiteral.parents.firstOrNull { it is KtDeclaration && it !is KtFunctionLiteral } as? KtDeclaration
} ?: containingDeclarationForPseudocode
throw KotlinExceptionWithAttachments(stackException.message, stackException)
.withPsiAttachment("original_expression.txt", originalElement)
.withPsiAttachment("containing_declaration.txt", containingDeclarationForPseudocode)
.withPsiAttachment("enclosing_declaration.txt", enclosingPseudocodeDeclaration)
}
).flatMap { it.getPossibleSupertypes(variance, builder) }
}
class ByTypeReference(val typeReference: KtTypeReference, variance: Variance) : TypeInfo(variance) {
override fun getPossibleTypes(builder: CallableBuilder): List<KotlinType> =
builder.currentFileContext[BindingContext.TYPE, typeReference].getPossibleSupertypes(variance, builder)
}
class ByType(val theType: KotlinType, variance: Variance) : TypeInfo(variance) {
override fun getPossibleTypes(builder: CallableBuilder): List<KotlinType> =
theType.getPossibleSupertypes(variance, builder)
}
class ByReceiverType(variance: Variance) : TypeInfo(variance) {
override fun getPossibleTypes(builder: CallableBuilder): List<KotlinType> =
(builder.placement as CallablePlacement.WithReceiver).receiverTypeCandidate.theType.getPossibleSupertypes(variance, builder)
}
class ByExplicitCandidateTypes(val types: List<KotlinType>) : TypeInfo(Variance.INVARIANT) {
override fun getPossibleTypes(builder: CallableBuilder) = types
}
abstract class DelegatingTypeInfo(val delegate: TypeInfo) : TypeInfo(delegate.variance) {
override val substitutionsAllowed: Boolean = delegate.substitutionsAllowed
override fun getPossibleNamesFromExpression(bindingContext: BindingContext) =
delegate.getPossibleNamesFromExpression(bindingContext)
override fun getPossibleTypes(builder: CallableBuilder): List<KotlinType> = delegate.getPossibleTypes(builder)
}
class NoSubstitutions(delegate: TypeInfo) : DelegatingTypeInfo(delegate) {
override val substitutionsAllowed: Boolean = false
}
class StaticContextRequired(delegate: TypeInfo) : DelegatingTypeInfo(delegate) {
override val staticContextRequired: Boolean = true
}
class OfThis(delegate: TypeInfo) : DelegatingTypeInfo(delegate)
val isOfThis: Boolean
get() = when (this) {
is OfThis -> true
is DelegatingTypeInfo -> delegate.isOfThis
else -> false
}
open val substitutionsAllowed: Boolean = true
open val staticContextRequired: Boolean = false
open fun getPossibleNamesFromExpression(bindingContext: BindingContext): Array<String> = ArrayUtil.EMPTY_STRING_ARRAY
abstract fun getPossibleTypes(builder: CallableBuilder): List<KotlinType>
private fun getScopeForTypeApproximation(config: CallableBuilderConfiguration, placement: CallablePlacement?): LexicalScope? {
if (placement == null) return config.originalElement.getResolutionScope()
val containingElement = when (placement) {
is CallablePlacement.NoReceiver -> {
placement.containingElement
}
is CallablePlacement.WithReceiver -> {
val receiverClassDescriptor =
placement.receiverTypeCandidate.theType.constructor.declarationDescriptor
val classDeclaration = receiverClassDescriptor?.let { DescriptorToSourceUtils.getSourceFromDescriptor(it) }
if (!config.isExtension && classDeclaration != null) classDeclaration else config.currentFile
}
}
return when (containingElement) {
is KtClassOrObject -> (containingElement.resolveToDescriptorIfAny() as? ClassDescriptorWithResolutionScopes)?.scopeForMemberDeclarationResolution
is KtBlockExpression -> (containingElement.statements.firstOrNull() ?: containingElement).getResolutionScope()
is KtElement -> containingElement.containingKtFile.getResolutionScope()
else -> null
}
}
protected fun KotlinType?.getPossibleSupertypes(variance: Variance, callableBuilder: CallableBuilder): List<KotlinType> {
if (this == null || ErrorUtils.containsErrorType(this)) {
return Collections.singletonList(callableBuilder.currentFileModule.builtIns.anyType)
}
val scope = getScopeForTypeApproximation(callableBuilder.config, callableBuilder.placement)
val approximations = getResolvableApproximations(scope, checkTypeParameters = false, allowIntersections = true)
return when (variance) {
Variance.IN_VARIANCE -> approximations.toList()
else -> listOf(approximations.firstOrNull() ?: this)
}
}
}
fun TypeInfo(expressionOfType: KtExpression, variance: Variance): TypeInfo = TypeInfo.ByExpression(expressionOfType, variance)
fun TypeInfo(typeReference: KtTypeReference, variance: Variance): TypeInfo = TypeInfo.ByTypeReference(typeReference, variance)
fun TypeInfo(theType: KotlinType, variance: Variance): TypeInfo = TypeInfo.ByType(theType, variance)
fun TypeInfo.noSubstitutions(): TypeInfo = (this as? TypeInfo.NoSubstitutions) ?: TypeInfo.NoSubstitutions(this)
fun TypeInfo.forceNotNull(): TypeInfo {
class ForcedNotNull(delegate: TypeInfo) : TypeInfo.DelegatingTypeInfo(delegate) {
override fun getPossibleTypes(builder: CallableBuilder): List<KotlinType> =
super.getPossibleTypes(builder).map { it.makeNotNullable() }
}
return (this as? ForcedNotNull) ?: ForcedNotNull(this)
}
fun TypeInfo.ofThis() = TypeInfo.OfThis(this)
/**
* Encapsulates information about a function parameter that is going to be created.
*/
class ParameterInfo(
val typeInfo: TypeInfo,
val nameSuggestions: List<String>
) {
constructor(typeInfo: TypeInfo, preferredName: String? = null) : this(typeInfo, listOfNotNull(preferredName))
}
enum class CallableKind {
FUNCTION,
CLASS_WITH_PRIMARY_CONSTRUCTOR,
CONSTRUCTOR,
PROPERTY
}
abstract class CallableInfo(
val name: String,
val receiverTypeInfo: TypeInfo,
val returnTypeInfo: TypeInfo,
val possibleContainers: List<KtElement>,
val typeParameterInfos: List<TypeInfo>,
val isForCompanion: Boolean = false,
val modifierList: KtModifierList? = null
) {
abstract val kind: CallableKind
abstract val parameterInfos: List<ParameterInfo>
val isAbstract get() = modifierList?.hasModifier(KtTokens.ABSTRACT_KEYWORD) == true
abstract fun copy(
receiverTypeInfo: TypeInfo = this.receiverTypeInfo,
possibleContainers: List<KtElement> = this.possibleContainers,
modifierList: KtModifierList? = this.modifierList
): CallableInfo
}
class FunctionInfo(
name: String,
receiverTypeInfo: TypeInfo,
returnTypeInfo: TypeInfo,
possibleContainers: List<KtElement> = Collections.emptyList(),
override val parameterInfos: List<ParameterInfo> = Collections.emptyList(),
typeParameterInfos: List<TypeInfo> = Collections.emptyList(),
isForCompanion: Boolean = false,
modifierList: KtModifierList? = null,
val preferEmptyBody: Boolean = false
) : CallableInfo(name, receiverTypeInfo, returnTypeInfo, possibleContainers, typeParameterInfos, isForCompanion, modifierList) {
override val kind: CallableKind get() = CallableKind.FUNCTION
override fun copy(
receiverTypeInfo: TypeInfo,
possibleContainers: List<KtElement>,
modifierList: KtModifierList?
) = FunctionInfo(
name,
receiverTypeInfo,
returnTypeInfo,
possibleContainers,
parameterInfos,
typeParameterInfos,
isForCompanion,
modifierList
)
}
class ClassWithPrimaryConstructorInfo(
val classInfo: ClassInfo,
expectedTypeInfo: TypeInfo,
modifierList: KtModifierList? = null,
val primaryConstructorVisibility: DescriptorVisibility? = null
) : CallableInfo(
classInfo.name,
TypeInfo.Empty,
expectedTypeInfo.forceNotNull(),
Collections.emptyList(),
classInfo.typeArguments,
false,
modifierList = modifierList
) {
override val kind: CallableKind get() = CallableKind.CLASS_WITH_PRIMARY_CONSTRUCTOR
override val parameterInfos: List<ParameterInfo> get() = classInfo.parameterInfos
override fun copy(
receiverTypeInfo: TypeInfo,
possibleContainers: List<KtElement>,
modifierList: KtModifierList?
) = throw UnsupportedOperationException()
}
class ConstructorInfo(
override val parameterInfos: List<ParameterInfo>,
val targetClass: PsiElement,
val isPrimary: Boolean = false,
modifierList: KtModifierList? = null,
val withBody: Boolean = false
) : CallableInfo("", TypeInfo.Empty, TypeInfo.Empty, Collections.emptyList(), Collections.emptyList(), false, modifierList = modifierList) {
override val kind: CallableKind get() = CallableKind.CONSTRUCTOR
override fun copy(
receiverTypeInfo: TypeInfo,
possibleContainers: List<KtElement>,
modifierList: KtModifierList?
) = throw UnsupportedOperationException()
}
class PropertyInfo(
name: String,
receiverTypeInfo: TypeInfo,
returnTypeInfo: TypeInfo,
val writable: Boolean,
possibleContainers: List<KtElement> = Collections.emptyList(),
typeParameterInfos: List<TypeInfo> = Collections.emptyList(),
val isLateinitPreferred: Boolean = false,
val isConst: Boolean = false,
isForCompanion: Boolean = false,
val annotations: List<KtAnnotationEntry> = emptyList(),
modifierList: KtModifierList? = null,
val initializer: KtExpression? = null
) : CallableInfo(name, receiverTypeInfo, returnTypeInfo, possibleContainers, typeParameterInfos, isForCompanion, modifierList) {
override val kind: CallableKind get() = CallableKind.PROPERTY
override val parameterInfos: List<ParameterInfo> get() = Collections.emptyList()
override fun copy(
receiverTypeInfo: TypeInfo,
possibleContainers: List<KtElement>,
modifierList: KtModifierList?
) = copyProperty(receiverTypeInfo, possibleContainers, modifierList)
fun copyProperty(
receiverTypeInfo: TypeInfo = this.receiverTypeInfo,
possibleContainers: List<KtElement> = this.possibleContainers,
modifierList: KtModifierList? = this.modifierList,
isLateinitPreferred: Boolean = this.isLateinitPreferred
) = PropertyInfo(
name,
receiverTypeInfo,
returnTypeInfo,
writable,
possibleContainers,
typeParameterInfos,
isConst,
isLateinitPreferred,
isForCompanion,
annotations,
modifierList,
initializer
)
}
| apache-2.0 | 16c84739a6de541d1313dc4bfa772daa | 43.098726 | 158 | 0.734888 | 5.647227 | false | false | false | false |
vvv1559/intellij-community | platform/platform-impl/src/com/intellij/openapi/updateSettings/impl/UpdateChecker.kt | 1 | 20677 | /*
* 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.updateSettings.impl
import com.intellij.diagnostic.IdeErrorsDialog
import com.intellij.externalDependencies.DependencyOnPlugin
import com.intellij.externalDependencies.ExternalDependenciesManager
import com.intellij.ide.IdeBundle
import com.intellij.ide.externalComponents.ExternalComponentManager
import com.intellij.ide.externalComponents.UpdatableExternalComponent
import com.intellij.ide.plugins.*
import com.intellij.ide.util.PropertiesComponent
import com.intellij.notification.*
import com.intellij.openapi.application.*
import com.intellij.openapi.application.ex.ApplicationInfoEx
import com.intellij.openapi.diagnostic.IdeaLoggingEvent
import com.intellij.openapi.diagnostic.LogUtil
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.extensions.PluginId
import com.intellij.openapi.progress.EmptyProgressIndicator
import com.intellij.openapi.progress.ProgressIndicator
import com.intellij.openapi.progress.ProgressManager
import com.intellij.openapi.progress.Task
import com.intellij.openapi.project.Project
import com.intellij.openapi.project.ProjectManager
import com.intellij.openapi.ui.Messages
import com.intellij.openapi.util.ActionCallback
import com.intellij.openapi.util.BuildNumber
import com.intellij.openapi.util.SystemInfo
import com.intellij.openapi.util.io.FileUtil
import com.intellij.openapi.util.text.StringUtil
import com.intellij.util.containers.ContainerUtil
import com.intellij.util.containers.MultiMap
import com.intellij.util.io.HttpRequests
import com.intellij.util.io.URLUtil
import com.intellij.util.loadElement
import com.intellij.util.ui.UIUtil
import com.intellij.xml.util.XmlStringUtil
import org.apache.http.client.utils.URIBuilder
import org.jdom.JDOMException
import java.io.File
import java.io.IOException
import java.util.*
/**
* See XML file by [ApplicationInfoEx.getUpdateUrls] for reference.
*
* @author mike
* @since Oct 31, 2002
*/
object UpdateChecker {
private val LOG = Logger.getInstance("#com.intellij.openapi.updateSettings.impl.UpdateChecker")
@JvmField
val NOTIFICATIONS = NotificationGroup(IdeBundle.message("update.notifications.title"), NotificationDisplayType.STICKY_BALLOON, true)
private val DISABLED_UPDATE = "disabled_update.txt"
private var ourDisabledToUpdatePlugins: MutableSet<String>? = null
private val ourAdditionalRequestOptions = hashMapOf<String, String>()
private val ourUpdatedPlugins = hashMapOf<String, PluginDownloader>()
private val ourShownNotifications = MultiMap<NotificationUniqueType, Notification>()
val excludedFromUpdateCheckPlugins = hashSetOf<String>()
private val updateUrl: String
get() = System.getProperty("idea.updates.url") ?: ApplicationInfoEx.getInstanceEx().updateUrls.checkingUrl
/**
* For scheduled update checks.
*/
@JvmStatic
fun updateAndShowResult(): ActionCallback {
val callback = ActionCallback()
ApplicationManager.getApplication().executeOnPooledThread {
doUpdateAndShowResult(null, true, false, UpdateSettings.getInstance(), null, callback)
}
return callback
}
/**
* For manual update checks (Help | Check for Updates, Settings | Updates | Check Now)
* (the latter action may pass customised update settings).
*/
@JvmStatic
fun updateAndShowResult(project: Project?, customSettings: UpdateSettings?) {
val settings = customSettings ?: UpdateSettings.getInstance()
val fromSettings = customSettings != null
ProgressManager.getInstance().run(object : Task.Backgroundable(project, IdeBundle.message("updates.checking.progress"), true) {
override fun run(indicator: ProgressIndicator) = doUpdateAndShowResult(getProject(), fromSettings, true, settings, indicator, null)
override fun isConditionalModal(): Boolean = fromSettings
override fun shouldStartInBackground(): Boolean = !fromSettings
})
}
@JvmStatic
fun doUpdateAndShowResult(project: Project?,
fromSettings: Boolean,
manualCheck: Boolean,
updateSettings: UpdateSettings,
indicator: ProgressIndicator?,
callback: ActionCallback?) {
// check platform update
indicator?.text = IdeBundle.message("updates.checking.platform")
val result = checkPlatformUpdate(updateSettings)
if (result.state == UpdateStrategy.State.CONNECTION_ERROR) {
val e = result.error
if (e != null) LOG.debug(e)
showErrorMessage(manualCheck, IdeBundle.message("updates.error.connection.failed", e?.message ?: "internal error"))
return
}
// check plugins update (with regard to potential platform update)
indicator?.text = IdeBundle.message("updates.checking.plugins")
val buildNumber: BuildNumber? = result.newBuild?.apiVersion
val incompatiblePlugins: MutableCollection<IdeaPluginDescriptor>? = if (buildNumber != null) HashSet<IdeaPluginDescriptor>() else null
val updatedPlugins: Collection<PluginDownloader>?
val externalUpdates: Collection<ExternalUpdate>?
try {
updatedPlugins = checkPluginsUpdate(updateSettings, indicator, incompatiblePlugins, buildNumber)
externalUpdates = updateExternal(manualCheck, updateSettings, indicator)
}
catch (e: IOException) {
showErrorMessage(manualCheck, IdeBundle.message("updates.error.connection.failed", e.message))
return
}
// show result
UpdateSettings.getInstance().saveLastCheckedInfo()
ApplicationManager.getApplication().invokeLater({
showUpdateResult(project, result, updateSettings, updatedPlugins, incompatiblePlugins, externalUpdates, !fromSettings, manualCheck)
callback?.setDone()
}, if (fromSettings) ModalityState.any() else ModalityState.NON_MODAL)
}
private fun checkPlatformUpdate(settings: UpdateSettings): CheckForUpdateResult {
if (!settings.isPlatformUpdateEnabled) {
return CheckForUpdateResult(UpdateStrategy.State.NOTHING_LOADED, null)
}
val updateInfo: UpdatesInfo?
try {
val uriBuilder = URIBuilder(updateUrl)
if (URLUtil.FILE_PROTOCOL != uriBuilder.scheme) {
prepareUpdateCheckArgs(uriBuilder)
}
val updateUrl = uriBuilder.build().toString()
LogUtil.debug(LOG, "load update xml (UPDATE_URL='%s')", updateUrl)
updateInfo = HttpRequests.request(updateUrl)
.forceHttps(settings.canUseSecureConnection())
.connect {
try {
UpdatesInfo(loadElement(it.reader))
}
catch (e: JDOMException) {
// corrupted content, don't bother telling user
LOG.info(e)
null
}
}
}
catch (e: Exception) {
LOG.info(e)
return CheckForUpdateResult(UpdateStrategy.State.CONNECTION_ERROR, e)
}
if (updateInfo == null) {
return CheckForUpdateResult(UpdateStrategy.State.NOTHING_LOADED, null)
}
val strategy = UpdateStrategy(ApplicationInfo.getInstance().build, updateInfo, settings)
return strategy.checkForUpdates()
}
@JvmStatic
fun checkPluginsUpdate(updateSettings: UpdateSettings,
indicator: ProgressIndicator?,
incompatiblePlugins: MutableCollection<IdeaPluginDescriptor>?,
buildNumber: BuildNumber?): Collection<PluginDownloader>? {
val updateable = collectUpdateablePlugins()
if (updateable.isEmpty()) return null
// check custom repositories and the main one for updates
val toUpdate = ContainerUtil.newTroveMap<PluginId, PluginDownloader>()
val hosts = RepositoryHelper.getPluginHosts()
val state = InstalledPluginsState.getInstance()
outer@ for (host in hosts) {
try {
val forceHttps = host == null && updateSettings.canUseSecureConnection()
val list = RepositoryHelper.loadPlugins(host, buildNumber, forceHttps, indicator)
for (descriptor in list) {
val id = descriptor.pluginId
if (updateable.containsKey(id)) {
updateable.remove(id)
state.onDescriptorDownload(descriptor)
val downloader = PluginDownloader.createDownloader(descriptor, host, buildNumber, forceHttps)
checkAndPrepareToInstall(downloader, state, toUpdate, incompatiblePlugins, indicator)
if (updateable.isEmpty()) {
break@outer
}
}
}
}
catch (e: IOException) {
LOG.debug(e)
if (host != null) {
LOG.info("failed to load plugin descriptions from " + host + ": " + e.message)
}
else {
throw e
}
}
}
return if (toUpdate.isEmpty) null else toUpdate.values
}
/**
* Returns a list of plugins which are currently installed or were installed in the previous installation from which
* we're importing the settings.
*/
private fun collectUpdateablePlugins(): MutableMap<PluginId, IdeaPluginDescriptor> {
val updateable = ContainerUtil.newTroveMap<PluginId, IdeaPluginDescriptor>()
updateable += PluginManagerCore.getPlugins().filter { !it.isBundled || it.allowBundledUpdate()}.associateBy { it.pluginId }
val onceInstalled = PluginManager.getOnceInstalledIfExists()
if (onceInstalled != null) {
try {
for (line in FileUtil.loadLines(onceInstalled)) {
val id = PluginId.getId(line.trim { it <= ' ' })
if (id !in updateable) {
updateable.put(id, null)
}
}
}
catch (e: IOException) {
LOG.error(onceInstalled.path, e)
}
//noinspection SSBasedInspection
onceInstalled.deleteOnExit()
}
for (excludedPluginId in excludedFromUpdateCheckPlugins) {
if (!isRequiredForAnyOpenProject(excludedPluginId)) {
updateable.remove(PluginId.getId(excludedPluginId))
}
}
return updateable
}
private fun isRequiredForAnyOpenProject(pluginId: String) =
ProjectManager.getInstance().openProjects.any { isRequiredForProject(it, pluginId) }
private fun isRequiredForProject(project: Project, pluginId: String) =
ExternalDependenciesManager.getInstance(project).getDependencies(DependencyOnPlugin::class.java).any { it.pluginId == pluginId }
@Throws(IOException::class)
@JvmStatic
fun updateExternal(manualCheck: Boolean, updateSettings: UpdateSettings, indicator: ProgressIndicator?) : Collection<ExternalUpdate> {
val result = arrayListOf<ExternalUpdate>()
val manager = ExternalComponentManager.getInstance()
indicator?.text = IdeBundle.message("updates.external.progress")
for (source in manager.componentSources) {
indicator?.checkCanceled()
if (source.name in updateSettings.enabledExternalUpdateSources) {
try {
val siteResult = arrayListOf<UpdatableExternalComponent>()
for (component in source.getAvailableVersions(indicator, updateSettings)) {
if (component.isUpdateFor(manager.findExistingComponentMatching(component, source))) {
siteResult.add(component)
}
}
if (!siteResult.isEmpty()) {
result.add(ExternalUpdate(siteResult, source))
}
}
catch (e: Exception) {
LOG.warn(e)
showErrorMessage(manualCheck, IdeBundle.message("updates.external.error.message", source.name, e.message ?: "internal error"))
}
}
}
return result
}
@Throws(IOException::class)
@JvmStatic
fun checkAndPrepareToInstall(downloader: PluginDownloader,
state: InstalledPluginsState,
toUpdate: MutableMap<PluginId, PluginDownloader>,
incompatiblePlugins: MutableCollection<IdeaPluginDescriptor>?,
indicator: ProgressIndicator?) {
@Suppress("NAME_SHADOWING")
var downloader = downloader
val pluginId = downloader.pluginId
if (PluginManagerCore.getDisabledPlugins().contains(pluginId)) return
val pluginVersion = downloader.pluginVersion
val installedPlugin = PluginManager.getPlugin(PluginId.getId(pluginId))
if (installedPlugin == null || pluginVersion == null || PluginDownloader.compareVersionsSkipBrokenAndIncompatible(installedPlugin, pluginVersion) > 0) {
var descriptor: IdeaPluginDescriptor?
val oldDownloader = ourUpdatedPlugins[pluginId]
if (oldDownloader == null || StringUtil.compareVersionNumbers(pluginVersion, oldDownloader.pluginVersion) > 0) {
descriptor = downloader.descriptor
if (descriptor is PluginNode && descriptor.isIncomplete) {
if (downloader.prepareToInstall(indicator ?: EmptyProgressIndicator())) {
descriptor = downloader.descriptor
}
ourUpdatedPlugins.put(pluginId, downloader)
}
}
else {
downloader = oldDownloader
descriptor = oldDownloader.descriptor
}
if (descriptor != null && PluginManagerCore.isCompatible(descriptor, downloader.buildNumber) && !state.wasUpdated(descriptor.pluginId)) {
toUpdate.put(PluginId.getId(pluginId), downloader)
}
}
//collect plugins which were not updated and would be incompatible with new version
if (incompatiblePlugins != null && installedPlugin != null && installedPlugin.isEnabled &&
!toUpdate.containsKey(installedPlugin.pluginId) &&
PluginManagerCore.isIncompatible(installedPlugin, downloader.buildNumber)) {
incompatiblePlugins.add(installedPlugin)
}
}
private fun showErrorMessage(showDialog: Boolean, message: String) {
LOG.info(message)
if (showDialog) {
UIUtil.invokeLaterIfNeeded { Messages.showErrorDialog(message, IdeBundle.message("updates.error.connection.title")) }
}
}
private fun showUpdateResult(project: Project?,
checkForUpdateResult: CheckForUpdateResult,
updateSettings: UpdateSettings,
updatedPlugins: Collection<PluginDownloader>?,
incompatiblePlugins: Collection<IdeaPluginDescriptor>?,
externalUpdates: Collection<ExternalUpdate>?,
enableLink: Boolean,
alwaysShowResults: Boolean) {
val updatedChannel = checkForUpdateResult.updatedChannel
val newBuild = checkForUpdateResult.newBuild
if (updatedChannel != null && newBuild != null) {
val runnable = {
val patch = checkForUpdateResult.findPatchForBuild(ApplicationInfo.getInstance().build)
val forceHttps = updateSettings.canUseSecureConnection()
UpdateInfoDialog(updatedChannel, newBuild, patch, enableLink, forceHttps, updatedPlugins, incompatiblePlugins).show()
}
ourShownNotifications.remove(NotificationUniqueType.PLATFORM)?.forEach { it.expire() }
if (alwaysShowResults) {
runnable.invoke()
}
else {
val message = IdeBundle.message("updates.ready.message", ApplicationNamesInfo.getInstance().fullProductName)
showNotification(project, message, runnable, NotificationUniqueType.PLATFORM)
}
return
}
var updateFound = false
if (updatedPlugins != null && !updatedPlugins.isEmpty()) {
updateFound = true
val runnable = { PluginUpdateInfoDialog(updatedPlugins, enableLink).show() }
ourShownNotifications.remove(NotificationUniqueType.PLUGINS)?.forEach { it.expire() }
if (alwaysShowResults) {
runnable.invoke()
}
else {
val plugins = updatedPlugins.joinToString { downloader -> downloader.pluginName }
val message = IdeBundle.message("updates.plugins.ready.message", updatedPlugins.size, plugins)
showNotification(project, message, runnable, NotificationUniqueType.PLUGINS)
}
}
if (externalUpdates != null && !externalUpdates.isEmpty()) {
updateFound = true
ourShownNotifications.remove(NotificationUniqueType.EXTERNAL)?.forEach { it.expire() }
for (update in externalUpdates) {
val runnable = { update.source.installUpdates(update.components) }
if (alwaysShowResults) {
runnable.invoke()
}
else {
val updates = update.components.joinToString(", ")
val message = IdeBundle.message("updates.external.ready.message", update.components.size, updates)
showNotification(project, message, runnable, NotificationUniqueType.EXTERNAL)
}
}
}
if (!updateFound && alwaysShowResults) {
NoUpdatesDialog(enableLink).show()
}
}
private fun showNotification(project: Project?, message: String, action: () -> Unit, notificationType: NotificationUniqueType) {
val listener = NotificationListener { notification, event ->
notification.expire()
action.invoke()
}
val title = IdeBundle.message("update.notifications.title")
val notification = NOTIFICATIONS.createNotification(title, XmlStringUtil.wrapInHtml(message), NotificationType.INFORMATION, listener)
notification.whenExpired { ourShownNotifications.remove(notificationType, notification) }
notification.notify(project)
ourShownNotifications.putValue(notificationType, notification)
}
@JvmStatic
fun addUpdateRequestParameter(name: String, value: String) {
ourAdditionalRequestOptions.put(name, value)
}
private fun prepareUpdateCheckArgs(uriBuilder: URIBuilder) {
addUpdateRequestParameter("build", ApplicationInfo.getInstance().build.asString())
addUpdateRequestParameter("uid", PermanentInstallationID.get())
addUpdateRequestParameter("os", SystemInfo.OS_NAME + ' ' + SystemInfo.OS_VERSION)
if (ApplicationInfoEx.getInstanceEx().isEAP) {
addUpdateRequestParameter("eap", "")
}
for ((name, value) in ourAdditionalRequestOptions) {
uriBuilder.addParameter(name, if (StringUtil.isEmpty(value)) null else value)
}
}
@Deprecated("Replaced", ReplaceWith("PermanentInstallationID.get()", "com.intellij.openapi.application.PermanentInstallationID"))
@JvmStatic
@Suppress("unused", "UNUSED_PARAMETER")
fun getInstallationUID(c: PropertiesComponent) = PermanentInstallationID.get()
@JvmStatic
val disabledToUpdatePlugins: Set<String>
get() {
if (ourDisabledToUpdatePlugins == null) {
ourDisabledToUpdatePlugins = TreeSet<String>()
if (!ApplicationManager.getApplication().isUnitTestMode) {
try {
val file = File(PathManager.getConfigPath(), DISABLED_UPDATE)
if (file.isFile) {
FileUtil.loadFile(file)
.split("[\\s]".toRegex())
.map { it.trim() }
.filterTo(ourDisabledToUpdatePlugins!!) { it.isNotEmpty() }
}
}
catch (e: IOException) {
LOG.error(e)
}
}
}
return ourDisabledToUpdatePlugins!!
}
@JvmStatic
fun saveDisabledToUpdatePlugins() {
val plugins = File(PathManager.getConfigPath(), DISABLED_UPDATE)
try {
PluginManagerCore.savePluginsList(disabledToUpdatePlugins, false, plugins)
}
catch (e: IOException) {
LOG.error(e)
}
}
private var ourHasFailedPlugins = false
@JvmStatic
fun checkForUpdate(event: IdeaLoggingEvent) {
if (!ourHasFailedPlugins) {
val app = ApplicationManager.getApplication()
if (app != null && !app.isDisposed && !app.isDisposeInProgress && UpdateSettings.getInstance().isCheckNeeded) {
val pluginDescriptor = PluginManager.getPlugin(IdeErrorsDialog.findPluginId(event.throwable))
if (pluginDescriptor != null && !pluginDescriptor.isBundled) {
ourHasFailedPlugins = true
updateAndShowResult()
}
}
}
}
private enum class NotificationUniqueType { PLATFORM, PLUGINS, EXTERNAL }
} | apache-2.0 | 9c92e27fe60d83be22bc51c6ce23c7f5 | 38.162879 | 156 | 0.694201 | 5.374838 | false | false | false | false |
forkhubs/android | app/src/main/java/com/github/pockethub/android/ui/user/UserViewActivity.kt | 5 | 6832 | /*
* Copyright (c) 2015 PocketHub
*
* 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.pockethub.android.ui.user
import android.content.Intent
import android.content.Intent.FLAG_ACTIVITY_CLEAR_TOP
import android.content.Intent.FLAG_ACTIVITY_SINGLE_TOP
import android.os.Bundle
import android.text.TextUtils
import android.view.Menu
import android.view.MenuItem
import android.view.View
import com.github.pockethub.android.Intents.Builder
import com.github.pockethub.android.Intents.EXTRA_USER
import com.github.pockethub.android.R
import com.github.pockethub.android.accounts.AccountUtils
import com.github.pockethub.android.rx.AutoDisposeUtils
import com.github.pockethub.android.ui.base.BaseActivity
import com.github.pockethub.android.ui.MainActivity
import com.github.pockethub.android.ui.helpers.PagerHandler
import com.github.pockethub.android.util.ToastUtils
import com.meisolsson.githubsdk.core.ServiceGenerator
import com.meisolsson.githubsdk.model.User
import com.meisolsson.githubsdk.service.users.UserFollowerService
import com.meisolsson.githubsdk.service.users.UserService
import io.reactivex.Single
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import kotlinx.android.synthetic.main.pager_with_tabs.*
import kotlinx.android.synthetic.main.tabbed_progress_pager.*
import retrofit2.Response
/**
* Activity to view a user's various pages
*/
class UserViewActivity : BaseActivity(), OrganizationSelectionProvider {
private var user: User? = null
private var isFollowing: Boolean = false
private var followingStatusChecked: Boolean = false
private var pagerHandler: PagerHandler<UserPagerAdapter>? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.tabbed_progress_pager)
user = intent.getParcelableExtra(EXTRA_USER)
val actionBar = supportActionBar!!
actionBar.setDisplayHomeAsUpEnabled(true)
actionBar.title = user!!.login()
if (!TextUtils.isEmpty(user!!.avatarUrl())) {
configurePager()
} else {
pb_loading.visibility = View.VISIBLE
ServiceGenerator.createService(this, UserService::class.java)
.getUser(user!!.login())
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.`as`(AutoDisposeUtils.bindToLifecycle(this))
.subscribe({ response ->
user = response.body()
configurePager()
}, { e ->
ToastUtils.show(this, R.string.error_person_load)
pb_loading.visibility = View.GONE
})
}
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
menuInflater.inflate(R.menu.activity_user_follow, menu)
return super.onCreateOptionsMenu(menu)
}
override fun onPrepareOptionsMenu(menu: Menu): Boolean {
val followItem = menu.findItem(R.id.m_follow)
val isCurrentUser = user!!.login() == AccountUtils.getLogin(this)
followItem.isVisible = followingStatusChecked && !isCurrentUser
followItem.setTitle(if (isFollowing) R.string.unfollow else R.string.follow)
return super.onPrepareOptionsMenu(menu)
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
return when (item.itemId) {
R.id.m_follow -> {
followUser()
true
}
android.R.id.home -> {
val intent = Intent(this, MainActivity::class.java)
intent.addFlags(FLAG_ACTIVITY_CLEAR_TOP or FLAG_ACTIVITY_SINGLE_TOP)
startActivity(intent)
true
}
else -> super.onOptionsItemSelected(item)
}
}
private fun configurePager() {
val adapter = UserPagerAdapter(this)
pagerHandler = PagerHandler(this, vp_pages, adapter)
lifecycle.addObserver(pagerHandler!!)
pagerHandler!!.tabs = sliding_tabs_layout
pb_loading.visibility = View.GONE
pagerHandler!!.setGone(false)
checkFollowingUserStatus()
}
override fun onDestroy() {
super.onDestroy()
lifecycle.removeObserver(pagerHandler!!)
}
override fun addListener(listener: OrganizationSelectionListener): User? {
return user
}
override fun removeListener(
listener: OrganizationSelectionListener
): OrganizationSelectionProvider {
return this
}
private fun followUser() {
val service = ServiceGenerator.createService(this, UserFollowerService::class.java)
val followSingle: Single<Response<Void>>
followSingle = if (isFollowing) {
service.unfollowUser(user!!.login())
} else {
service.followUser(user!!.login())
}
followSingle.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.`as`(AutoDisposeUtils.bindToLifecycle(this))
.subscribe({ aVoid -> isFollowing = !isFollowing },
{ e ->
val message = if (isFollowing)
R.string.error_unfollowing_person
else
R.string.error_following_person
ToastUtils.show(this, message)
})
}
private fun checkFollowingUserStatus() {
followingStatusChecked = false
ServiceGenerator.createService(this, UserFollowerService::class.java)
.isFollowing(user!!.login())
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.`as`(AutoDisposeUtils.bindToLifecycle(this))
.subscribe { response ->
isFollowing = response.code() == 204
followingStatusChecked = true
invalidateOptionsMenu()
}
}
companion object {
/**
* Create intent for this activity
*
* @param user
* @return intent
*/
fun createIntent(user: User): Intent {
return Builder("user.VIEW").user(user).toIntent()
}
}
}
| apache-2.0 | 0f102e8803829c9e7b803293109d1805 | 33.857143 | 91 | 0.653396 | 4.897491 | false | false | false | false |
allotria/intellij-community | python/python-psi-impl/src/com/jetbrains/python/pyi/PyiFile.kt | 2 | 3386 | /*
* 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.jetbrains.python.pyi
import com.intellij.psi.FileViewProvider
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiNamedElement
import com.intellij.psi.ResolveState
import com.intellij.psi.scope.DelegatingScopeProcessor
import com.intellij.psi.scope.PsiScopeProcessor
import com.jetbrains.python.PyNames
import com.jetbrains.python.PythonFileType
import com.jetbrains.python.psi.LanguageLevel
import com.jetbrains.python.psi.PyImportElement
import com.jetbrains.python.psi.PyUtil
import com.jetbrains.python.psi.impl.PyBuiltinCache
import com.jetbrains.python.psi.impl.PyFileImpl
import com.jetbrains.python.psi.resolve.ImportedResolveResult
import com.jetbrains.python.psi.resolve.RatedResolveResult
/**
* @author vlan
*/
class PyiFile(viewProvider: FileViewProvider) : PyFileImpl(viewProvider, PyiLanguageDialect.getInstance()) {
override fun getFileType(): PythonFileType = PyiFileType.INSTANCE
override fun toString(): String = "PyiFile:$name"
override fun getLanguageLevel(): LanguageLevel = LanguageLevel.getLatest()
override fun multiResolveName(name: String, exported: Boolean): List<RatedResolveResult> {
if (name == "function" && PyBuiltinCache.getInstance(this).builtinsFile == this) return emptyList()
if (exported && isPrivateName(name) && !resolvingBuiltinPathLike(name)) return emptyList()
val baseResults = super.multiResolveName(name, exported)
val dunderAll = dunderAll ?: emptyList()
return if (exported)
baseResults.filterNot { isPrivateImport((it as? ImportedResolveResult)?.definer, dunderAll) }
else
baseResults
}
override fun processDeclarations(processor: PsiScopeProcessor,
resolveState: ResolveState,
lastParent: PsiElement?,
place: PsiElement): Boolean {
val dunderAll = dunderAll ?: emptyList()
val wrapper = object : DelegatingScopeProcessor(processor) {
override fun execute(element: PsiElement, state: ResolveState): Boolean = when {
isPrivateImport(element, dunderAll) -> true
element is PsiNamedElement && isPrivateName(element.name) -> true
else -> super.execute(element, state)
}
}
return super.processDeclarations(wrapper, resolveState, lastParent, place)
}
private fun isPrivateName(name: String?) = PyUtil.getInitialUnderscores(name) == 1
private fun isPrivateImport(element: PsiElement?, dunderAll: List<String>): Boolean {
return element is PyImportElement && element.asName == null && element.visibleName !in dunderAll
}
private fun resolvingBuiltinPathLike(name: String): Boolean {
return name == PyNames.BUILTIN_PATH_LIKE && PyBuiltinCache.getInstance(this).builtinsFile == this
}
}
| apache-2.0 | 903e21a6ae8ffa1262ab8eefe9485a84 | 41.325 | 108 | 0.741288 | 4.663912 | false | false | false | false |
Skatteetaten/boober | src/main/kotlin/no/skatteetaten/aurora/boober/model/openshift/AuroraAzureCname.kt | 1 | 1385 | package no.skatteetaten.aurora.boober.model.openshift
import com.fasterxml.jackson.annotation.JsonIgnore
import com.fasterxml.jackson.annotation.JsonIgnoreProperties
import com.fasterxml.jackson.annotation.JsonInclude
import com.fasterxml.jackson.annotation.JsonPropertyOrder
import io.fabric8.kubernetes.api.model.HasMetadata
import io.fabric8.kubernetes.api.model.ObjectMeta
@JsonIgnoreProperties(ignoreUnknown = true)
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonPropertyOrder(value = ["apiVersion", "kind", "metadata", "spec"])
data class AuroraAzureCname(
val spec: AzureCnameSpec,
@JsonIgnore
var _metadata: ObjectMeta?,
@JsonIgnore
val _kind: String = "AuroraAzureCname",
@JsonIgnore
var _apiVersion: String = "skatteetaten.no/v1"
) : HasMetadata {
override fun getMetadata(): ObjectMeta {
return _metadata ?: ObjectMeta()
}
override fun getKind(): String {
return _kind
}
override fun getApiVersion(): String {
return _apiVersion
}
override fun setMetadata(metadata: ObjectMeta?) {
_metadata = metadata
}
override fun setApiVersion(version: String?) {
_apiVersion = apiVersion
}
}
@JsonIgnoreProperties(ignoreUnknown = true)
@JsonInclude(JsonInclude.Include.NON_NULL)
data class AzureCnameSpec(
val host: String,
val cname: String,
val ttl: Int
)
| apache-2.0 | 3f79a495f3c8c12a4e4c267de79f1da4 | 27.265306 | 70 | 0.726354 | 4.261538 | false | false | false | false |
dagi12/eryk-android-common | src/main/java/pl/edu/amu/wmi/erykandroidcommon/di/CommonApplicationModule.kt | 1 | 4321 | package pl.edu.amu.wmi.erykandroidcommon.di
import android.app.Application
import android.content.Context
import android.preference.PreferenceManager
import com.f2prateek.rx.preferences2.RxSharedPreferences
import com.google.gson.ExclusionStrategy
import com.google.gson.FieldAttributes
import com.google.gson.FieldNamingPolicy
import com.google.gson.Gson
import com.google.gson.GsonBuilder
import com.google.gson.annotations.Expose
import com.jakewharton.retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory
import dagger.Module
import dagger.Provides
import okhttp3.ConnectionPool
import okhttp3.Interceptor
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import pl.edu.amu.wmi.erykandroidcommon.location.LocationService
import pl.edu.amu.wmi.erykandroidcommon.service.PicassoCache
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import java.security.SecureRandom
import java.security.cert.X509Certificate
import java.util.concurrent.TimeUnit
import javax.inject.Singleton
import javax.net.ssl.SSLContext
import javax.net.ssl.TrustManager
import javax.net.ssl.X509TrustManager
fun retroFactory(baseUrl: String, gson: Gson, okHttpClient: OkHttpClient): Retrofit =
Retrofit.Builder().baseUrl(baseUrl)
.client(okHttpClient)
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.addConverterFactory(GsonConverterFactory.create(gson))
.build()
fun okHttpFactory(debug: Boolean, interceptor: Interceptor?): OkHttpClient {
val clientBuilder = OkHttpClient.Builder()
interceptor?.let {
clientBuilder.addInterceptor(interceptor)
}
val sslContext = SSLContext.getInstance("SSL")
val connectionPool = ConnectionPool(5, 60, TimeUnit.SECONDS)
val connectionTrustManager = arrayOf<TrustManager>(object : X509TrustManager {
override fun checkServerTrusted(p0: Array<out X509Certificate>?, p1: String?) = Unit
override fun checkClientTrusted(p0: Array<out X509Certificate>?, p1: String?) = Unit
override fun getAcceptedIssuers(): Array<out X509Certificate> = arrayOf()
})
sslContext.init(null, connectionTrustManager, SecureRandom())
clientBuilder.sslSocketFactory(sslContext.socketFactory)
clientBuilder.hostnameVerifier { _, _ -> true }
clientBuilder.connectionPool(connectionPool)
if (debug) {
val loggingInterceptor = HttpLoggingInterceptor()
loggingInterceptor.level = HttpLoggingInterceptor.Level.BODY
clientBuilder.addInterceptor(loggingInterceptor).build()
}
return clientBuilder.build()
}
@Module
class CommonApplicationModule(private val application: CommonApplication) {
@Provides
@Singleton
fun provideContext(): Context = application
@Provides
@Singleton
fun provideApplication(): Application = application
@Provides
@Singleton
fun provideCommonApplication(): CommonApplication = application
@Provides
@Singleton
fun provideGson(): Gson = GsonBuilder()
.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES)
.addSerializationExclusionStrategy(object : ExclusionStrategy {
override fun shouldSkipField(fieldAttributes: FieldAttributes): Boolean {
val expose = fieldAttributes.getAnnotation(Expose::class.java)
return expose != null && !expose.serialize
}
override fun shouldSkipClass(aClass: Class<*>): Boolean = false
})
.addDeserializationExclusionStrategy(object : ExclusionStrategy {
override fun shouldSkipField(fieldAttributes: FieldAttributes): Boolean {
val expose = fieldAttributes.getAnnotation(Expose::class.java)
return expose != null && !expose.deserialize
}
override fun shouldSkipClass(aClass: Class<*>): Boolean = false
})
.create()
@Provides
@Singleton
fun provideCachedImageManager(): PicassoCache = PicassoCache(application)
@Provides
@Singleton
fun provideLocationService(): LocationService = LocationService(application)
@Provides
@Singleton
fun provideSharedPreferences(): RxSharedPreferences = RxSharedPreferences.create(
PreferenceManager.getDefaultSharedPreferences(application))
}
| apache-2.0 | 2357b4bacb866cf51fe3e5f0e89dcb17 | 36.573913 | 92 | 0.751215 | 5.250304 | false | false | false | false |
Kotlin/kotlinx.coroutines | kotlinx-coroutines-core/common/src/CompletionState.kt | 1 | 2411 | /*
* Copyright 2016-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license.
*/
package kotlinx.coroutines
import kotlinx.atomicfu.*
import kotlinx.coroutines.internal.*
import kotlin.coroutines.*
import kotlin.jvm.*
internal fun <T> Result<T>.toState(
onCancellation: ((cause: Throwable) -> Unit)? = null
): Any? = fold(
onSuccess = { if (onCancellation != null) CompletedWithCancellation(it, onCancellation) else it },
onFailure = { CompletedExceptionally(it) }
)
internal fun <T> Result<T>.toState(caller: CancellableContinuation<*>): Any? = fold(
onSuccess = { it },
onFailure = { CompletedExceptionally(recoverStackTrace(it, caller)) }
)
@Suppress("RESULT_CLASS_IN_RETURN_TYPE", "UNCHECKED_CAST")
internal fun <T> recoverResult(state: Any?, uCont: Continuation<T>): Result<T> =
if (state is CompletedExceptionally)
Result.failure(recoverStackTrace(state.cause, uCont))
else
Result.success(state as T)
internal data class CompletedWithCancellation(
@JvmField val result: Any?,
@JvmField val onCancellation: (cause: Throwable) -> Unit
)
/**
* Class for an internal state of a job that was cancelled (completed exceptionally).
*
* @param cause the exceptional completion cause. It's either original exceptional cause
* or artificial [CancellationException] if no cause was provided
*/
internal open class CompletedExceptionally(
@JvmField public val cause: Throwable,
handled: Boolean = false
) {
private val _handled = atomic(handled)
val handled: Boolean get() = _handled.value
fun makeHandled(): Boolean = _handled.compareAndSet(false, true)
override fun toString(): String = "$classSimpleName[$cause]"
}
/**
* A specific subclass of [CompletedExceptionally] for cancelled [AbstractContinuation].
*
* @param continuation the continuation that was cancelled.
* @param cause the exceptional completion cause. If `cause` is null, then a [CancellationException]
* if created on first access to [exception] property.
*/
internal class CancelledContinuation(
continuation: Continuation<*>,
cause: Throwable?,
handled: Boolean
) : CompletedExceptionally(cause ?: CancellationException("Continuation $continuation was cancelled normally"), handled) {
private val _resumed = atomic(false)
fun makeResumed(): Boolean = _resumed.compareAndSet(false, true)
}
| apache-2.0 | ac1f6ca7a05d34c555e0239e0084729d | 35.530303 | 122 | 0.724596 | 4.344144 | false | false | false | false |
leafclick/intellij-community | platform/workspaceModel-ide-tests/testSrc/com/intellij/workspace/jps/ImlSerializationTest.kt | 1 | 1153 | package com.intellij.workspace.jps
import com.intellij.openapi.application.ex.PathManagerEx
import com.intellij.testFramework.ApplicationRule
import com.intellij.workspace.api.TypedEntityStorageBuilder
import com.intellij.workspace.api.verifySerializationRoundTrip
import org.junit.ClassRule
import org.junit.Test
import java.io.File
class ImlSerializationTest {
@Test
fun sampleProject() {
val projectDir = File(PathManagerEx.getCommunityHomePath(), "jps/model-serialization/testData/sampleProject")
serializationRoundTrip(projectDir)
}
@Test
fun communityProject() {
val projectDir = File(PathManagerEx.getCommunityHomePath())
serializationRoundTrip(projectDir)
}
private fun serializationRoundTrip(projectFile: File) {
val storageBuilder = TypedEntityStorageBuilder.create()
JpsProjectEntitiesLoader.loadProject(projectFile.asStoragePlace(), storageBuilder)
val storage = storageBuilder.toStorage()
val byteArray = verifySerializationRoundTrip(storage)
println("Serialized size: ${byteArray.size}")
}
companion object {
@JvmField
@ClassRule
val appRule = ApplicationRule()
}
}
| apache-2.0 | d231924f35acaf5576dbd2fa1c408cd6 | 30.162162 | 113 | 0.786644 | 5.034934 | false | true | false | false |
code-helix/slatekit | src/lib/kotlin/slatekit-db/src/main/kotlin/slatekit/db/builders/PostGresBuilder.kt | 1 | 3571 | /**
* <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.db.builders
import java.rmi.UnexpectedException
import slatekit.common.Types
import slatekit.common.data.DataType
import slatekit.common.data.DataTypeMap
import slatekit.common.data.Encoding
import slatekit.common.newline
/**
* Builds up database tables, indexes and other database components
*/
open class PostGresBuilder : DbBuilder {
val types = listOf(
DataTypeMap(DataType.DTString, "NVARCHAR", Types.JStringClass),
DataTypeMap(DataType.DTBool, "BIT", Types.JBoolClass),
DataTypeMap(DataType.DTShort, "TINYINT", Types.JStringClass),
DataTypeMap(DataType.DTInt, "INTEGER", Types.JStringClass),
DataTypeMap(DataType.DTLong, "BIGINT", Types.JStringClass),
DataTypeMap(DataType.DTFloat, "FLOAT", Types.JStringClass),
DataTypeMap(DataType.DTDouble, "DOUBLE", Types.JStringClass),
DataTypeMap(DataType.DTDecimal, "DECIMAL", Types.JStringClass),
DataTypeMap(DataType.DTLocalDate, "DATE", Types.JStringClass),
DataTypeMap(DataType.DTLocalTime, "TIME", Types.JStringClass),
DataTypeMap(DataType.DTLocalDateTime, "DATETIME", Types.JStringClass),
DataTypeMap(DataType.DTZonedDateTime, "DATETIME", Types.JStringClass),
DataTypeMap(DataType.DTInstant, "INSTANT", Types.JStringClass),
DataTypeMap(DataType.DTDateTime, "DATETIME", Types.JStringClass)
)
/**
* Mapping of normalized types ot postgres type names
*/
val dataToColumnTypes = types.map { Pair(it.metaType, it.dbType) }.toMap()
val langToDataTypes = types.map { Pair(it.langType, it.metaType) }.toMap()
/**
* Builds the drop table DDL for the name supplied.
*/
override fun dropTable(name: String): String = build(name, "DROP TABLE IF EXISTS")
/**
* Builds a delete statement to delete all rows
*/
override fun truncate(name: String): String = build(name, "DELETE FROM")
/**
* Builds an add column DDL sql statement
*/
override fun addCol(name: String, dataType: DataType, required: Boolean, maxLen: Int): String {
val nullText = if (required) "NOT NULL" else ""
val colType = colType(dataType, maxLen)
val colName = colName(name)
val sql = " $newline$colName $colType $nullText"
return sql
}
/**
* Builds a valid column name
*/
override fun colName(name: String): String = "`" + Encoding.ensureField(name) + "`"
/**
* Builds a valid column type
*/
override fun colType(colType: DataType, maxLen: Int): String {
return if (colType == DataType.DTString && maxLen == -1)
"longtext"
else if (colType == DataType.DTString)
"VARCHAR($maxLen)"
else
getColTypeName(colType)
}
private fun build(name: String, prefix: String): String {
val tableName = Encoding.ensureField(name)
val sql = "$prefix `$tableName`;"
return sql
}
private fun getColTypeName(sqlType: DataType): String {
return if (dataToColumnTypes.containsKey(sqlType))
dataToColumnTypes[sqlType] ?: ""
else
throw UnexpectedException("Unexpected db type : $sqlType")
}
}
| apache-2.0 | 7aa7eb8ebe84d553ef6239cbd05a8161 | 34.009804 | 99 | 0.66676 | 4.312802 | false | false | false | false |
leafclick/intellij-community | java/idea-ui/src/com/intellij/internal/SharedIndexesLoader.kt | 1 | 9335 | // Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.internal
import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.databind.node.ArrayNode
import com.fasterxml.jackson.databind.node.ObjectNode
import com.google.common.hash.Hashing
import com.google.common.io.Files
import com.intellij.openapi.application.PathManager
import com.intellij.openapi.components.service
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.progress.*
import com.intellij.openapi.roots.OrderEntry
import com.intellij.openapi.util.io.FileUtil
import com.intellij.openapi.util.registry.Registry
import com.intellij.util.indexing.IndexInfrastructureVersion
import com.intellij.util.indexing.provided.SharedIndexChunkLocator
import com.intellij.util.io.HttpRequests
import org.jetbrains.annotations.TestOnly
import org.tukaani.xz.XZInputStream
import java.io.ByteArrayInputStream
import java.io.File
import java.io.IOException
import java.nio.file.Path
private object SharedIndexesCdn {
private const val innerVersion = "v1"
private val indexesCdnUrl
get() = Registry.stringValue("shared.indexes.url").trimEnd('/')
fun hashIndexUrls(request: SharedIndexRequest) = sequence {
request.run {
if (hash != null) {
yield("$indexesCdnUrl/$innerVersion/$kind/$hash/index.json.xz")
}
for (alias in request.aliases) {
yield("$indexesCdnUrl/$innerVersion/$kind/-$alias/index.json.xz")
}
//TODO[jo] remove prefix!
for (alias in request.aliases) {
yield("$indexesCdnUrl/$innerVersion/$kind/-$kind-$alias/index.json.xz")
}
}
}.toList().distinct()
}
data class SharedIndexRequest(
val kind: String,
val hash: String? = null,
val aliases: List<String> = listOf()
)
data class SharedIndexInfo(
val url: String,
val sha256: String,
val metadata: ObjectNode
)
data class SharedIndexResult(
val kind: String,
val url: String,
val sha256: String,
val version: IndexInfrastructureVersion
) {
val chunkUniqueId get() = "$kind-$sha256-${version.weakVersionHash}"
override fun toString(): String = "SharedIndex sha=${sha256.take(8)}, wv=${version.weakVersionHash.take(8)}"
}
fun SharedIndexResult.toChunkDescriptor(sdkEntries: Collection<OrderEntry>) = object: SharedIndexChunkLocator.ChunkDescriptor {
override fun getChunkUniqueId() = [email protected]
override fun getSupportedInfrastructureVersion() = [email protected]
override fun getOrderEntries() = sdkEntries
override fun downloadChunk(targetFile: Path, indicator: ProgressIndicator) {
SharedIndexesLoader.getInstance().downloadSharedIndex(this@toChunkDescriptor, indicator, targetFile.toFile())
}
}
class SharedIndexesLoader {
private val LOG = logger<SharedIndexesLoader>()
companion object {
@JvmStatic
fun getInstance() = service<SharedIndexesLoader>()
}
fun lookupSharedIndex(request: SharedIndexRequest,
indicator: ProgressIndicator): SharedIndexResult? {
indicator.text = "Looking for Shared Indexes..."
val ourVersion = IndexInfrastructureVersion.getIdeVersion()
for (entries in downloadIndexesList(request, indicator)) {
indicator.checkCanceled()
if (entries.isEmpty()) continue
indicator.pushState()
try {
indicator.text = "Inspecting Shared Indexes..."
val best = SharedIndexMetadata.selectBestSuitableIndex(ourVersion, entries)
if (best == null) {
LOG.info("No matching index found $request")
continue
}
val (info, metadata) = best
LOG.info("Selected index ${info} for $request")
return SharedIndexResult(request.kind, info.url, info.sha256, metadata)
}
finally {
indicator.popState()
}
}
return null
}
fun downloadSharedIndex(info: SharedIndexResult,
indicator: ProgressIndicator,
targetFile: File) {
val downloadFile = selectNewFileName(info, info.version, File(PathManager.getTempPath()), ".ijx.xz")
indicator.text = "Downloading Shared Index..."
indicator.checkCanceled()
try {
downloadSharedIndexXZ(info, downloadFile, indicator)
indicator.text = "Unpacking Shared Index..."
indicator.checkCanceled()
unpackSharedIndexXZ(targetFile, downloadFile)
}
catch (t: Throwable) {
FileUtil.delete(targetFile)
throw t
}
finally {
FileUtil.delete(downloadFile)
}
}
private fun selectNewFileName(info: SharedIndexResult,
version: IndexInfrastructureVersion,
basePath: File,
ext: String): File {
var infix = 0
while (true) {
val name = info.kind + "-" + info.sha256 + "-" + version.weakVersionHash + "-" + infix + ext
val resultFile = File(basePath, name)
if (!resultFile.isFile) {
resultFile.parentFile?.mkdirs()
return resultFile
}
infix++
}
}
fun selectIndexFileDestination(info: SharedIndexResult,
version: IndexInfrastructureVersion) =
selectNewFileName(info, version, File(PathManager.getSystemPath(), "shared-indexes"), ".ijx")
@TestOnly
fun downloadSharedIndexXZ(info: SharedIndexResult,
downloadFile: File,
indicator: ProgressIndicator?) {
val url = info.url
indicator?.pushState()
indicator?.isIndeterminate = false
try {
try {
HttpRequests.request(url)
.productNameAsUserAgent()
.saveToFile(downloadFile, indicator)
}
catch (t: IOException) {
throw RuntimeException("Failed to download JDK from $url. ${t.message}", t)
}
val actualHashCode = Files.asByteSource(downloadFile).hash(Hashing.sha256()).toString()
if (!actualHashCode.equals(info.sha256, ignoreCase = true)) {
throw RuntimeException("SHA-256 checksums does not match. Actual value is $actualHashCode, expected ${info.sha256}")
}
}
catch (e: Exception) {
FileUtil.delete(downloadFile)
if (e !is ProcessCanceledException) throw e
} finally {
indicator?.popState()
}
}
@TestOnly
fun unpackSharedIndexXZ(targetFile: File, downloadFile: File) {
val bufferSize = 1024 * 1024
targetFile.parentFile?.mkdirs()
targetFile.outputStream().use { out ->
downloadFile.inputStream().buffered(bufferSize).use { input ->
XZInputStream(input).use { it.copyTo(out, bufferSize) }
}
}
}
fun downloadIndexesList(request: SharedIndexRequest,
indicator: ProgressIndicator?
): Sequence<List<SharedIndexInfo>> {
val urls = SharedIndexesCdn.hashIndexUrls(request)
return urls.asSequence().mapIndexedNotNull { idx, indexUrl ->
indicator?.pushState()
indicator?.text = when {
urls.size > 1 -> "Looking for shared indexes (${idx + 1} of ${urls.size})"
else -> "Looking for shared indexes"
}
val result = downloadIndexList(request, indexUrl, indicator)
indicator?.popState()
result
}
}
private fun downloadIndexList(request: SharedIndexRequest,
indexUrl: String,
indicator: ProgressIndicator?) : List<SharedIndexInfo> {
LOG.info("Checking index at $indexUrl...")
val rawDataXZ = try {
HttpRequests.request(indexUrl).throwStatusCodeException(true).readBytes(indicator)
}
catch (e: HttpRequests.HttpStatusException) {
LOG.info("No indexes available for $request. ${e.message}", e)
return listOf()
}
val rawData = try {
ByteArrayInputStream(rawDataXZ).use { input ->
XZInputStream(input).use {
it.readBytes()
}
}
}
catch (e: Exception) {
LOG.warn("Failed to unpack index data for $request. ${e.message}", e)
return listOf()
}
LOG.info("Downloaded the $indexUrl...")
val json = try {
ObjectMapper().readTree(rawData)
}
catch (e: Exception) {
LOG.warn("Failed to read index data JSON for $request. ${e.message}", e)
return listOf()
}
val listVersion = json.get("list_version")?.asText()
if (listVersion != "1") {
LOG.warn("Index data version mismatch. The current version is $listVersion")
return listOf()
}
val entries = (json.get("entries") as? ArrayNode) ?: run {
LOG.warn("Index data format is incomplete. Missing 'entries' element")
return listOf()
}
val indexes = entries.elements().asSequence().mapNotNull { node ->
if (node !is ObjectNode) return@mapNotNull null
val url = node.get("url")?.asText() ?: return@mapNotNull null
val sha = node.get("sha256")?.asText() ?: return@mapNotNull null
val data = (node.get("metadata") as? ObjectNode) ?: return@mapNotNull null
SharedIndexInfo(url, sha, data)
}.toList()
LOG.info("Detected ${indexes.size} batches for the $request")
if (indexes.isEmpty()) {
LOG.info("No indexes found $request")
}
return indexes
}
}
| apache-2.0 | 7fe2b34640e725ff0421a0974e3da804 | 31.189655 | 140 | 0.663417 | 4.535957 | false | false | false | false |
JuliusKunze/kotlin-native | backend.native/tests/external/codegen/box/coroutines/intrinsicSemantics/startCoroutineUninterceptedOrReturnInterception.kt | 2 | 2615 | // WITH_RUNTIME
// WITH_COROUTINES
import helpers.*
import kotlin.coroutines.experimental.*
import kotlin.coroutines.experimental.intrinsics.*
import kotlin.test.assertEquals
suspend fun suspendHere(): String = suspendCoroutineOrReturn { x ->
x.resume("OK")
COROUTINE_SUSPENDED
}
suspend fun suspendWithException(): String = suspendCoroutineOrReturn { x ->
x.resumeWithException(RuntimeException("OK"))
COROUTINE_SUSPENDED
}
fun builder(shouldSuspend: Boolean, expectedCount: Int, c: suspend () -> String): String {
var fromSuspension: String? = null
var counter = 0
val result = try {
c.startCoroutineUninterceptedOrReturn(object: Continuation<String> {
override val context: CoroutineContext
get() = ContinuationDispatcher { counter++ }
override fun resumeWithException(exception: Throwable) {
fromSuspension = "Exception: " + exception.message!!
}
override fun resume(value: String) {
fromSuspension = value
}
})
} catch (e: Exception) {
"Exception: ${e.message}"
}
if (counter != expectedCount) throw RuntimeException("fail 0")
if (shouldSuspend) {
if (result !== COROUTINE_SUSPENDED) throw RuntimeException("fail 1")
if (fromSuspension == null) throw RuntimeException("fail 2")
return fromSuspension!!
}
if (result === COROUTINE_SUSPENDED) throw RuntimeException("fail 3")
return result as String
}
class ContinuationDispatcher(val dispatcher: () -> Unit) : AbstractCoroutineContextElement(ContinuationInterceptor), ContinuationInterceptor {
override fun <T> interceptContinuation(continuation: Continuation<T>): Continuation<T> = DispatchedContinuation(dispatcher, continuation)
}
private class DispatchedContinuation<T>(
val dispatcher: () -> Unit,
val continuation: Continuation<T>
): Continuation<T> {
override val context: CoroutineContext = continuation.context
override fun resume(value: T) {
dispatcher()
continuation.resume(value)
}
override fun resumeWithException(exception: Throwable) {
dispatcher()
continuation.resumeWithException(exception)
}
}
fun box(): String {
if (builder(false, 0) { "OK" } != "OK") return "fail 4"
if (builder(true, 1) { suspendHere() } != "OK") return "fail 5"
if (builder(false, 0) { throw RuntimeException("OK") } != "Exception: OK") return "fail 6"
if (builder(true, 1) { suspendWithException() } != "Exception: OK") return "fail 7"
return "OK"
}
| apache-2.0 | 40149d172758f3826e555c523e432763 | 31.6875 | 142 | 0.665774 | 4.711712 | false | false | false | false |
exponent/exponent | android/versioned-abis/expoview-abi43_0_0/src/main/java/abi43_0_0/expo/modules/imagemanipulator/ImageManipulatorModule.kt | 2 | 3415 | package abi43_0_0.expo.modules.imagemanipulator
import android.content.Context
import android.graphics.Bitmap
import android.net.Uri
import android.os.Bundle
import android.util.Base64
import abi43_0_0.expo.modules.imagemanipulator.arguments.Actions
import abi43_0_0.expo.modules.imagemanipulator.arguments.SaveOptions
import abi43_0_0.expo.modules.interfaces.imageloader.ImageLoaderInterface
import abi43_0_0.expo.modules.interfaces.imageloader.ImageLoaderInterface.ResultListener
import abi43_0_0.expo.modules.core.ExportedModule
import abi43_0_0.expo.modules.core.ModuleRegistry
import abi43_0_0.expo.modules.core.ModuleRegistryDelegate
import abi43_0_0.expo.modules.core.Promise
import abi43_0_0.expo.modules.core.arguments.ReadableArguments
import abi43_0_0.expo.modules.core.interfaces.ExpoMethod
import java.io.ByteArrayOutputStream
import java.io.File
import java.io.FileOutputStream
import java.util.*
private const val TAG = "ExpoImageManipulator"
private const val ERROR_TAG = "E_IMAGE_MANIPULATOR"
class ImageManipulatorModule(
context: Context,
private val moduleRegistryDelegate: ModuleRegistryDelegate = ModuleRegistryDelegate()
) : ExportedModule(context) {
private val mImageLoader: ImageLoaderInterface by moduleRegistry()
private inline fun <reified T> moduleRegistry() = moduleRegistryDelegate.getFromModuleRegistry<T>()
override fun getName() = TAG
override fun onCreate(moduleRegistry: ModuleRegistry) {
moduleRegistryDelegate.onCreate(moduleRegistry)
}
@ExpoMethod
fun manipulateAsync(uri: String, actionsRaw: ArrayList<Any?>, saveOptionsRaw: ReadableArguments, promise: Promise) {
val saveOptions = SaveOptions.fromArguments(saveOptionsRaw)
val actions = Actions.fromArgument(actionsRaw)
mImageLoader.loadImageForManipulationFromURL(
uri,
object : ResultListener {
override fun onSuccess(bitmap: Bitmap) {
runActions(bitmap, actions, saveOptions, promise)
}
override fun onFailure(cause: Throwable?) {
// No cleanup required here.
val basicMessage = "Could not get decoded bitmap of $uri"
if (cause != null) {
promise.reject("${ERROR_TAG}_DECODE", "$basicMessage: $cause", cause)
} else {
promise.reject("${ERROR_TAG}_DECODE", "$basicMessage.")
}
}
}
)
}
private fun runActions(bitmap: Bitmap, actions: Actions, saveOptions: SaveOptions, promise: Promise) {
val resultBitmap = actions.actions.fold(bitmap, { acc, action -> action.run(acc) })
val path = FileUtils.generateRandomOutputPath(context, saveOptions.format)
val compression = (saveOptions.compress * 100).toInt()
var base64String: String? = null
FileOutputStream(path).use { fileOut ->
resultBitmap.compress(saveOptions.format, compression, fileOut)
if (saveOptions.base64) {
ByteArrayOutputStream().use { byteOut ->
resultBitmap.compress(saveOptions.format, compression, byteOut)
base64String = Base64.encodeToString(byteOut.toByteArray(), Base64.NO_WRAP)
}
}
}
val result = Bundle().apply {
putString("uri", Uri.fromFile(File(path)).toString())
putInt("width", resultBitmap.width)
putInt("height", resultBitmap.height)
if (base64String != null) {
putString("base64", base64String)
}
}
promise.resolve(result)
}
}
| bsd-3-clause | b0c5dbeb2792bdfdbcafe59856b8ad04 | 36.944444 | 118 | 0.729136 | 4.311869 | false | false | false | false |
smmribeiro/intellij-community | platform/util/ui/src/com/intellij/ui/svg/SvgPrebuiltCacheManager.kt | 2 | 3273 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.ui.svg
import com.intellij.diagnostic.StartUpMeasurer
import com.intellij.ui.icons.IconLoadMeasurer
import com.intellij.util.ImageLoader
import org.jetbrains.annotations.ApiStatus
import org.jetbrains.ikv.Ikv
import org.jetbrains.ikv.UniversalHash
import java.awt.Image
import java.nio.ByteBuffer
import java.nio.file.Path
private val intKeyHash = UniversalHash.IntHash()
@ApiStatus.Internal
class SvgPrebuiltCacheManager(private val dbDir: Path) {
private val lightStores = Stores("")
private val darkStores = Stores("-d")
@Suppress("PropertyName")
private inner class Stores(classifier: String) {
val s1 = StoreContainer(1f, classifier)
val s1_25 = StoreContainer(1.25f, classifier)
val s1_5 = StoreContainer(1.5f, classifier)
val s2 = StoreContainer(2f, classifier)
val s2_5 = StoreContainer(2.5f, classifier)
}
private inner class StoreContainer(private val scale: Float, private val classifier: String) {
@Volatile
private var store: Ikv.SizeUnawareIkv<Int>? = null
fun getOrCreate() = store ?: getSynchronized()
@Synchronized
private fun getSynchronized(): Ikv.SizeUnawareIkv<Int> {
var store = store
if (store == null) {
store = Ikv.loadSizeUnawareIkv(dbDir.resolve("icons-v1-$scale$classifier.db"), intKeyHash)
this.store = store
}
return store
}
}
fun loadFromCache(key: Int, scale: Float, isDark: Boolean, docSize: ImageLoader.Dimension2DDouble): Image? {
val start = StartUpMeasurer.getCurrentTimeIfEnabled()
val list = if (isDark) darkStores else lightStores
// not supported scale
val store = when (scale) {
1f -> list.s1.getOrCreate()
1.25f -> list.s1_25.getOrCreate()
1.5f -> list.s1_5.getOrCreate()
2f -> list.s2.getOrCreate()
2.5f -> list.s2_5.getOrCreate()
else -> return null
}
val data = store.getUnboundedValue(key) ?: return null
val actualWidth: Int
val actualHeight: Int
val format = data.get().toInt() and 0xff
if (format < 254) {
actualWidth = format
actualHeight = format
}
else if (format == 255) {
actualWidth = readVar(data)
actualHeight = actualWidth
}
else {
actualWidth = readVar(data)
actualHeight = readVar(data)
}
docSize.setSize((actualWidth / scale).toDouble(), (actualHeight / scale).toDouble())
val image = SvgCacheManager.readImage(data, actualWidth, actualHeight)
IconLoadMeasurer.svgPreBuiltLoad.end(start)
return image
}
}
private fun readVar(buf: ByteBuffer): Int {
var aByte = buf.get().toInt()
var value: Int = aByte and 127
if (aByte and 128 != 0) {
aByte = buf.get().toInt()
value = value or (aByte and 127 shl 7)
if (aByte and 128 != 0) {
aByte = buf.get().toInt()
value = value or (aByte and 127 shl 14)
if (aByte and 128 != 0) {
aByte = buf.get().toInt()
value = value or (aByte and 127 shl 21)
if (aByte and 128 != 0) {
value = value or (buf.get().toInt() shl 28)
}
}
}
}
return value
} | apache-2.0 | fb6e3d8cfc970e082f87ae69fa77ef29 | 30.480769 | 158 | 0.6685 | 3.805814 | false | false | false | false |
smmribeiro/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/RenameIdentifierFix.kt | 5 | 2312 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.quickfix
import com.intellij.codeInsight.FileModificationService
import com.intellij.codeInspection.LocalQuickFix
import com.intellij.codeInspection.ProblemDescriptor
import com.intellij.ide.DataManager
import com.intellij.openapi.fileEditor.FileEditorManager
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiElement
import com.intellij.refactoring.RefactoringFactory
import com.intellij.refactoring.rename.RenameHandlerRegistry
import org.jetbrains.kotlin.idea.KotlinBundle
open class RenameIdentifierFix : LocalQuickFix {
override fun getName() = KotlinBundle.message("rename.identifier.fix.text")
override fun getFamilyName() = name
override fun startInWriteAction(): Boolean = false
override fun applyFix(project: Project, descriptor: ProblemDescriptor) {
val element = descriptor.psiElement ?: return
val file = element.containingFile ?: return
if (!FileModificationService.getInstance().prepareFileForWrite(file)) return
val editorManager = FileEditorManager.getInstance(project)
val fileEditor = editorManager.getSelectedEditor(file.virtualFile) ?: return renameWithoutEditor(element)
val dataContext = DataManager.getInstance().getDataContext(fileEditor.component)
val renameHandler = RenameHandlerRegistry.getInstance().getRenameHandler(dataContext)
val editor = editorManager.selectedTextEditor
if (editor != null) {
renameHandler?.invoke(project, editor, file, dataContext)
} else {
val elementToRename = getElementToRename(element) ?: return
renameHandler?.invoke(project, arrayOf(elementToRename), dataContext)
}
}
protected open fun getElementToRename(element: PsiElement): PsiElement? = element.parent
private fun renameWithoutEditor(element: PsiElement) {
val elementToRename = getElementToRename(element) ?: return
val factory = RefactoringFactory.getInstance(element.project)
val renameRefactoring = factory.createRename(elementToRename, null, true, true)
renameRefactoring.run()
}
} | apache-2.0 | 32ebfd5781726cb6171af7c40ad5401c | 47.1875 | 158 | 0.762543 | 5.24263 | false | false | false | false |
smmribeiro/intellij-community | plugins/kotlin/uast/uast-kotlin/src/org/jetbrains/uast/kotlin/expressions/KotlinUNamedExpression.kt | 2 | 3121 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.uast.kotlin
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiType
import org.jetbrains.kotlin.psi.ValueArgument
import org.jetbrains.uast.*
import org.jetbrains.uast.kotlin.internal.DelegatedMultiResolve
class KotlinUNamedExpression private constructor(
override val name: String?,
override val sourcePsi: PsiElement?,
givenParent: UElement?,
expressionProducer: (UElement) -> UExpression
) : KotlinAbstractUElement(givenParent), UNamedExpression {
override val expression: UExpression by lz { expressionProducer(this) }
override val uAnnotations: List<UAnnotation> = emptyList()
override val psi: PsiElement? = null
override val javaPsi: PsiElement? = null
companion object {
internal fun create(name: String?, valueArgument: ValueArgument, uastParent: UElement?): UNamedExpression {
val expression = valueArgument.getArgumentExpression()
return KotlinUNamedExpression(name, valueArgument.asElement(), uastParent) { expressionParent ->
expression?.let { expressionParent.getLanguagePlugin().convertOpt<UExpression>(it, expressionParent) }
?: UastEmptyExpression(expressionParent)
}
}
internal fun create(
name: String?,
valueArguments: List<ValueArgument>,
uastParent: UElement?
): UNamedExpression {
return KotlinUNamedExpression(name, null, uastParent) { expressionParent ->
KotlinUVarargExpression(valueArguments, expressionParent)
}
}
}
}
class KotlinUVarargExpression(
private val valueArgs: List<ValueArgument>,
uastParent: UElement?
) : KotlinAbstractUExpression(uastParent), UCallExpressionEx, DelegatedMultiResolve {
override val kind: UastCallKind = UastCallKind.NESTED_ARRAY_INITIALIZER
override val valueArguments: List<UExpression> by lz {
valueArgs.map {
it.getArgumentExpression()?.let { argumentExpression ->
getLanguagePlugin().convert<UExpression>(argumentExpression, this)
} ?: UastEmptyExpression(this)
}
}
override fun getArgumentForParameter(i: Int): UExpression? = valueArguments.getOrNull(i)
override val valueArgumentCount: Int
get() = valueArgs.size
override val psi: PsiElement?
get() = null
override val methodIdentifier: UIdentifier?
get() = null
override val classReference: UReferenceExpression?
get() = null
override val methodName: String?
get() = null
override val typeArgumentCount: Int
get() = 0
override val typeArguments: List<PsiType>
get() = emptyList()
override val returnType: PsiType?
get() = null
override fun resolve() = null
override val receiver: UExpression?
get() = null
override val receiverType: PsiType?
get() = null
}
| apache-2.0 | 3a9852b84df1f4f4095ec379d392a686 | 32.202128 | 158 | 0.686318 | 5.465849 | false | false | false | false |
kickstarter/android-oss | app/src/main/java/com/kickstarter/ui/activities/ThreadActivity.kt | 1 | 9880 | package com.kickstarter.ui.activities
import android.os.Bundle
import android.util.Pair
import androidx.core.view.isVisible
import androidx.recyclerview.widget.ConcatAdapter
import androidx.recyclerview.widget.LinearLayoutManager
import com.kickstarter.R
import com.kickstarter.databinding.ActivityThreadLayoutBinding
import com.kickstarter.libs.BaseActivity
import com.kickstarter.libs.KSString
import com.kickstarter.libs.RecyclerViewPaginator
import com.kickstarter.libs.qualifiers.RequiresActivityViewModel
import com.kickstarter.libs.utils.ApplicationUtils
import com.kickstarter.libs.utils.UrlUtils
import com.kickstarter.libs.utils.extensions.showAlertDialog
import com.kickstarter.models.Comment
import com.kickstarter.ui.adapters.RepliesAdapter
import com.kickstarter.ui.adapters.RepliesStatusAdapter
import com.kickstarter.ui.adapters.RootCommentAdapter
import com.kickstarter.ui.extensions.hideKeyboard
import com.kickstarter.ui.views.OnCommentComposerViewClickedListener
import com.kickstarter.viewmodels.ThreadViewModel
import org.joda.time.DateTime
import rx.android.schedulers.AndroidSchedulers
import java.util.concurrent.TimeUnit
@RequiresActivityViewModel(ThreadViewModel.ViewModel::class)
class ThreadActivity :
BaseActivity<ThreadViewModel.ViewModel>(),
RepliesStatusAdapter.Delegate,
RepliesAdapter.Delegate {
private lateinit var binding: ActivityThreadLayoutBinding
private lateinit var ksString: KSString
/** Replies list adapter **/
private val repliesAdapter = RepliesAdapter(this)
/** Replies cell status viewMore or Error **/
private val repliesStatusAdapter = RepliesStatusAdapter(this)
/** Replies Root comment cell adapter **/
private val rootCommentAdapter = RootCommentAdapter()
/** reverse Layout to bind the replies from bottom **/
private val linearLayoutManager = LinearLayoutManager(this, LinearLayoutManager.VERTICAL, true)
private lateinit var recyclerViewPaginator: RecyclerViewPaginator
var isPaginated = false
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityThreadLayoutBinding.inflate(layoutInflater)
setContentView(binding.root)
ksString = requireNotNull(environment().ksString())
recyclerViewPaginator = RecyclerViewPaginator(binding.commentRepliesRecyclerView, { viewModel.inputs.nextPage() }, viewModel.outputs.isFetchingReplies(), false)
/** use ConcatAdapter to bind adapters to recycler view and replace the section issue **/
binding.commentRepliesRecyclerView.adapter = ConcatAdapter(repliesAdapter, repliesStatusAdapter, rootCommentAdapter)
binding.commentRepliesRecyclerView.layoutManager = linearLayoutManager
this.viewModel.outputs.getRootComment()
.compose(bindToLifecycle())
.observeOn(AndroidSchedulers.mainThread())
.subscribe { comment ->
/** bind root comment by updating the adapter list**/
rootCommentAdapter.updateRootCommentCell(comment)
}
this.viewModel.outputs
.onCommentReplies()
.compose(bindToLifecycle())
.observeOn(AndroidSchedulers.mainThread())
.doOnNext {
linearLayoutManager.stackFromEnd = false
}
.subscribe {
/** bind View more cell if the replies more than 7 or update after refresh initial error state **/
this.repliesStatusAdapter.addViewMoreCell(it.second)
if (it.first.isNotEmpty()) {
this.repliesAdapter.takeData(it.first)
}
}
viewModel.outputs.shouldShowPaginationErrorUI()
.compose(bindToLifecycle())
.observeOn(AndroidSchedulers.mainThread())
.filter { it }
.subscribe {
/** bind Error Pagination cell **/
repliesStatusAdapter.addErrorPaginationCell(it)
}
viewModel.outputs.initialLoadCommentsError()
.compose(bindToLifecycle())
.observeOn(AndroidSchedulers.mainThread())
.filter { it }
.subscribe {
/** bind Error initial loading cell **/
repliesStatusAdapter.addInitiallyLoadingErrorCell(it)
}
viewModel.outputs.isFetchingReplies()
.compose(bindToLifecycle())
.observeOn(AndroidSchedulers.mainThread())
.subscribe {
binding.repliesLoadingIndicator.isVisible = it
}
this.viewModel.shouldFocusOnCompose()
.delay(30, TimeUnit.MILLISECONDS)
.compose(bindToLifecycle())
.observeOn(AndroidSchedulers.mainThread())
.subscribe { shouldOpenKeyboard ->
binding.replyComposer.requestCommentComposerKeyBoard(shouldOpenKeyboard)
}
viewModel.outputs.currentUserAvatar()
.compose(bindToLifecycle())
.observeOn(AndroidSchedulers.mainThread())
.subscribe {
binding.replyComposer.setAvatarUrl(it)
}
viewModel.outputs.replyComposerStatus()
.compose(bindToLifecycle())
.observeOn(AndroidSchedulers.mainThread())
.subscribe {
binding.replyComposer.setCommentComposerStatus(it)
}
viewModel.outputs.scrollToBottom()
.compose(bindToLifecycle())
.delay(500, TimeUnit.MILLISECONDS)
.observeOn(AndroidSchedulers.mainThread())
.subscribe { binding.commentRepliesRecyclerView.smoothScrollToPosition(0) }
viewModel.outputs.showReplyComposer()
.compose(bindToLifecycle())
.observeOn(AndroidSchedulers.mainThread())
.subscribe {
binding.replyComposer.isVisible = it
}
viewModel.outputs.loadMoreReplies()
.compose(bindToLifecycle())
.observeOn(AndroidSchedulers.mainThread())
.subscribe {
recyclerViewPaginator.reload()
}
binding.replyComposer.setCommentComposerActionClickListener(object :
OnCommentComposerViewClickedListener {
override fun onClickActionListener(string: String) {
postReply(string)
hideKeyboard()
}
})
viewModel.outputs.showCommentGuideLinesLink()
.compose(bindToLifecycle())
.observeOn(AndroidSchedulers.mainThread())
.subscribe {
ApplicationUtils.openUrlExternally(
this,
UrlUtils.appendPath(
environment().webEndpoint(),
CommentsActivity.COMMENT_KICKSTARTER_GUIDELINES
)
)
}
viewModel.outputs.hasPendingComments()
.compose(bindToLifecycle())
.observeOn(AndroidSchedulers.mainThread())
.subscribe {
if (it) handleBackAction() else viewModel.inputs.backPressed()
}
viewModel.outputs.closeThreadActivity()
.compose(bindToLifecycle())
.observeOn(AndroidSchedulers.mainThread())
.subscribe {
closeCommentsActivity()
}
}
private fun handleBackAction() {
this.showAlertDialog(
getString(R.string.Your_comment_wasnt_posted),
getString(R.string.You_will_lose_the_comment_if_you_leave_this_page),
getString(R.string.Cancel),
getString(R.string.Leave_page),
false,
positiveAction = {
},
negativeAction = {
viewModel.inputs.backPressed()
}
)
}
override fun back() {
if (binding.replyComposer.isCommentComposerEmpty() == true) {
viewModel.inputs.checkIfThereAnyPendingComments()
} else {
handleBackAction()
}
}
private fun closeCommentsActivity() {
super.back()
this.finishActivity(taskId)
}
fun postReply(comment: String) {
this.viewModel.inputs.insertNewReplyToList(comment, DateTime.now())
this.binding.replyComposer.clearCommentComposer()
}
override fun onStop() {
super.onStop()
hideKeyboard()
}
override fun exitTransition(): Pair<Int, Int>? {
return Pair.create(R.anim.fade_in_slide_in_left, R.anim.slide_out_right)
}
override fun onRetryViewClicked(comment: Comment) {
}
override fun onReplyButtonClicked(comment: Comment) {
}
override fun onFlagButtonClicked(comment: Comment) {
TODO("Not yet implemented")
}
override fun onCommentGuideLinesClicked(comment: Comment) {
viewModel.inputs.onShowGuideLinesLinkClicked()
}
override fun onCommentRepliesClicked(comment: Comment) {
}
override fun onCommentPostedFailed(comment: Comment, position: Int) {
viewModel.inputs.refreshCommentCardInCaseFailedPosted(comment, position)
}
override fun onCommentPostedSuccessFully(comment: Comment, position: Int) {
viewModel.inputs.refreshCommentCardInCaseSuccessPosted(comment, position)
}
override fun loadMoreCallback() {
viewModel.inputs.reloadRepliesPage()
}
override fun retryCallback() {
viewModel.inputs.reloadRepliesPage()
}
override fun onShowCommentClicked(comment: Comment) {
viewModel.inputs.onShowCanceledPledgeComment(comment)
}
override fun onDestroy() {
super.onDestroy()
recyclerViewPaginator.stop()
binding.commentRepliesRecyclerView.adapter = null
this.viewModel = null
}
}
| apache-2.0 | 9a03f546f5512c074fd3c5b99500f273 | 35.323529 | 168 | 0.653543 | 5.528819 | false | false | false | false |
NativeScript/android-runtime | test-app/build-tools/android-metadata-generator/src/src/com/telerik/metadata/parsing/bytecode/methods/NativeMethodBytecodeDescriptor.kt | 1 | 1482 | package com.telerik.metadata.parsing.bytecode.methods
import com.telerik.metadata.parsing.MetadataInfoAnnotationDescriptor
import com.telerik.metadata.parsing.NativeClassDescriptor
import com.telerik.metadata.parsing.NativeMethodDescriptor
import com.telerik.metadata.parsing.NativeTypeDescriptor
import com.telerik.metadata.parsing.bytecode.types.NativeTypeBytecodeDescriptor
import org.apache.bcel.classfile.Method
abstract class NativeMethodBytecodeDescriptor(private val m: Method, override val declaringClass: NativeClassDescriptor) : NativeMethodDescriptor {
override val isSynthetic = m.isSynthetic
override val isStatic = m.isStatic
override val isAbstract = m.isAbstract
override val name: String = m.name
override val signature: String = m.signature
override val argumentTypes: Array<NativeTypeDescriptor>
get() {
val ts = m.argumentTypes
return Array(ts.size) {
NativeTypeBytecodeDescriptor(ts[it])
}
}
override val returnType = NativeTypeBytecodeDescriptor(m.returnType)
override val metadataInfoAnnotation: MetadataInfoAnnotationDescriptor? = null
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other == null || javaClass != other.javaClass) return false
return other is NativeMethodBytecodeDescriptor && m == other.m
}
override fun hashCode(): Int {
return m.hashCode()
}
}
| apache-2.0 | 62f49c95bebabb5f4a7912a79be2bae8 | 32.681818 | 147 | 0.735493 | 5.023729 | false | false | false | false |
kivensolo/UiUsingListView | library/player/src/main/java/com/kingz/library/player/TrackInfo.kt | 1 | 359 | package com.kingz.library.player
/**
* Track信息
*/
class TrackInfo {
enum class TrackType {
AUDIO, SUBTITLE
}
var trackType: TrackType? = null
var index = 0
var language: String? = null
override fun toString(): String {
return "TrackInfo{mTrackType = $trackType, mIndex = $index, mLanguage = $language}"
}
} | gpl-2.0 | afd6454de654d126f6db78c47a77cc01 | 18.777778 | 91 | 0.625352 | 3.944444 | false | false | false | false |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.