repo_name
stringlengths 7
79
| path
stringlengths 8
206
| copies
stringclasses 36
values | size
stringlengths 2
6
| content
stringlengths 55
523k
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 7.18
99.5
| line_max
int64 16
979
| alpha_frac
float64 0.3
0.87
| ratio
float64 2.01
8.07
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
newbieandroid/AppBase | app/src/main/java/com/fuyoul/sanwenseller/utils/GlideUtils.kt | 1 | 7234 | package com.fuyoul.sanwenseller.utils
import android.content.Context
import android.content.res.Resources
import android.graphics.*
import android.support.annotation.ColorRes
import android.widget.ImageView
import com.bumptech.glide.DrawableRequestBuilder
import com.bumptech.glide.Glide
import com.bumptech.glide.load.engine.bitmap_recycle.BitmapPool
import com.bumptech.glide.load.resource.bitmap.BitmapTransformation
import com.bumptech.glide.load.resource.drawable.GlideDrawable
import com.bumptech.glide.request.RequestListener
import com.bumptech.glide.request.target.Target
import com.fuyoul.sanwenseller.R
import jp.wasabeef.glide.transformations.RoundedCornersTransformation
import java.lang.Exception
/**
* Auther: chen
* Creat at: 2017\8\14 0014
* Desc:
*/
object GlideUtils {
private val ERRORIMG = R.mipmap.icon_imgloading
private val LOADINGIMG = R.mipmap.icon_imgloading
/**
* 加载圆形图片,带边框
*/
fun <T> loadCircleImg(context: Context, path: T, imageView: ImageView, isBord: Boolean, @ColorRes bordColor: Int, loadingImgRes: Int, errorImgRes: Int) {
val builder: DrawableRequestBuilder<T> = Glide.with(context)
.load(path)
.thumbnail(0.1f)
.placeholder(loadingImgRes)
.error(errorImgRes)
.centerCrop()
.listener(object : RequestListener<T, GlideDrawable> {
override fun onException(e: Exception?, model: T?, target: Target<GlideDrawable>?, isFirstResource: Boolean): Boolean {
loadCircleImg(context, errorImgRes, imageView, isBord, bordColor, loadingImgRes, errorImgRes)
return true
}
override fun onResourceReady(resource: GlideDrawable?, model: T?, target: Target<GlideDrawable>?, isFromMemoryCache: Boolean, isFirstResource: Boolean): Boolean = false
})
if (isBord) {
builder.bitmapTransform(GlideCircleTransform(context, bordColor)).into(imageView)
} else {
builder.bitmapTransform(GlideCircleTransform(context)).into(imageView)
}
}
fun <T> loadCircleImg(context: Context, path: T, imageView: ImageView, isBord: Boolean, @ColorRes bordColor: Int) {
loadCircleImg(context, path, imageView, isBord, bordColor, LOADINGIMG, ERRORIMG)
}
/**
* 加载圆形图片,不带边框
*/
fun <T> loadCircleImg(context: Context, path: T, imageView: ImageView, loadingImgRes: Int, errorImgRes: Int) {
loadCircleImg(context, path, imageView, false, 0, loadingImgRes, errorImgRes)
}
fun <T> loadCircleImg(context: Context, path: T, imageView: ImageView) {
loadCircleImg(context, path, imageView, false, 0, LOADINGIMG, ERRORIMG)
}
/**
* 加载本地或者网络圆角图片
*/
fun <T> loadRoundCornerImg(context: Context, path: T, imageView: ImageView) {
loadRoundCornerImg(context, path, imageView, LOADINGIMG, ERRORIMG)
}
fun <T> loadRoundCornerImg(context: Context, path: T, imageView: ImageView, loadingImgRes: Int, errorImgRes: Int) {
Glide.with(context)
.load(path)
.thumbnail(0.1f)
.placeholder(loadingImgRes)
.error(errorImgRes)
.fitCenter()
.bitmapTransform(RoundedCornersTransformation(context, 30, 0, RoundedCornersTransformation.CornerType.ALL))
// .listener(object : RequestListener<T, GlideDrawable> {
// override fun onException(e: Exception?, model: T?, target: Target<GlideDrawable>?, isFirstResource: Boolean): Boolean {
// loadRoundCornerImg(context, errorImgRes, imageView)
// return true
// }
//
// override fun onResourceReady(resource: GlideDrawable?, model: T?, target: Target<GlideDrawable>?, isFromMemoryCache: Boolean, isFirstResource: Boolean): Boolean = false
//
// })
.into(imageView)
}
/**
* 加载本地或者网络普通图片
*/
fun <T> loadNormalImg(context: Context, path: T, imageView: ImageView) {
loadNormalImg(context, path, imageView, LOADINGIMG, ERRORIMG)
}
fun <T> loadNormalImg(context: Context, path: T, imageView: ImageView, loadingImgRes: Int, errorImgRes: Int) {
Glide.with(context)
.load(path)
.thumbnail(0.1f)
.placeholder(loadingImgRes)
.error(errorImgRes)
.centerCrop()
// .listener(object : RequestListener<T, GlideDrawable> {
// override fun onException(e: Exception?, model: T?, target: Target<GlideDrawable>?, isFirstResource: Boolean): Boolean {
// loadNormalImg(context, ERRORIMG, imageView)
// return true
// }
//
// override fun onResourceReady(resource: GlideDrawable?, model: T?, target: Target<GlideDrawable>?, isFromMemoryCache: Boolean, isFirstResource: Boolean): Boolean = false
//
// })
.into(imageView)
}
private class GlideCircleTransform(context: Context) : BitmapTransformation(context) {
private var mBorderPaint: Paint? = null
private var mBorderWidth: Float = 0.toFloat()
constructor(context: Context, @ColorRes borderColor: Int) : this(context) {
mBorderWidth = Resources.getSystem().displayMetrics.density
mBorderPaint = Paint()
mBorderPaint!!.isDither = true
mBorderPaint!!.isAntiAlias = true
mBorderPaint!!.color = context.resources.getColor(borderColor)
mBorderPaint!!.style = Paint.Style.STROKE
mBorderPaint!!.strokeWidth = mBorderWidth
}
override fun getId(): String = "${System.currentTimeMillis()}"
override fun transform(pool: BitmapPool?, toTransform: Bitmap?, outWidth: Int, outHeight: Int): Bitmap = circleCrop(pool!!, toTransform)!!
private fun circleCrop(pool: BitmapPool, source: Bitmap?): Bitmap? {
if (source == null) return null
val size = (Math.min(source.width, source.height) - mBorderWidth / 2).toInt()
val x = (source.width - size) / 2
val y = (source.height - size) / 2
val squared = Bitmap.createBitmap(source, x, y, size, size)
var result: Bitmap? = pool.get(size, size, Bitmap.Config.ARGB_8888)
if (result == null) {
result = Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888)
}
val canvas = Canvas(result)
val paint = Paint()
paint.shader = BitmapShader(squared, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP)
paint.isAntiAlias = true
val r = size / 2f
canvas.drawCircle(r, r, r, paint)
if (mBorderPaint != null) {
val borderRadius = r - mBorderWidth / 2
canvas.drawCircle(r, r, borderRadius, mBorderPaint)
}
return result
}
}
} | apache-2.0 | b6004557700a8a68b62ff1ff98a20fcf | 38.065574 | 190 | 0.621433 | 4.442511 | false | false | false | false |
siper/AdapterX | sample/src/main/java/pro/siper/adapterx/model/api/CoverPhoto.kt | 1 | 1002 | package pro.siper.adapterx.model.api
import com.google.gson.annotations.Expose
import com.google.gson.annotations.SerializedName
import pro.siper.adapterx.model.api.Category
class CoverPhoto {
@SerializedName("id")
@Expose
var id: String? = null
@SerializedName("width")
@Expose
var width: Int? = null
@SerializedName("height")
@Expose
var height: Int? = null
@SerializedName("color")
@Expose
var color: String? = null
@SerializedName("likes")
@Expose
var likes: Int? = null
@SerializedName("liked_by_user")
@Expose
var likedByUser: Boolean? = null
@SerializedName("description")
@Expose
var description: String? = null
@SerializedName("user")
@Expose
var user: User? = null
@SerializedName("urls")
@Expose
var urls: Urls? = null
@SerializedName("categories")
@Expose
var categories: List<Category>? = null
@SerializedName("links")
@Expose
var links: Links? = null
} | mit | 8c072c32bb16c9f87376c6b7eb6f6ab5 | 22.325581 | 49 | 0.654691 | 3.944882 | false | false | false | false |
Cardstock/Cardstock | src/test/kotlin/xyz/cardstock/cardstock/implementations/games/DummyGameWithRounds.kt | 1 | 1302 | /*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
package xyz.cardstock.cardstock.implementations.games
import org.kitteh.irc.client.library.element.Channel
import org.kitteh.irc.client.library.element.User
import xyz.cardstock.cardstock.Cardstock
import xyz.cardstock.cardstock.games.GameWithRounds
import xyz.cardstock.cardstock.implementations.players.DummyPlayer
import xyz.cardstock.cardstock.interfaces.states.State
internal class DummyGameWithRounds(cardstock: Cardstock, channel: Channel) : GameWithRounds<DummyPlayer>(cardstock, channel) {
override fun getPlayer(user: User, create: Boolean): DummyPlayer? {
val current = this._players.firstOrNull { it.user == user }
if (current != null) {
return current
}
if (!create) {
return null
}
return DummyPlayer(user).apply { this@DummyGameWithRounds._players.add(this) }
}
override var state: State
get() = throw UnsupportedOperationException()
set(value) {
}
override val stateListeners: MutableList<(State) -> Unit>
get() = throw UnsupportedOperationException()
}
| mpl-2.0 | d1f7b4734319027e06b8427482b3cce8 | 38.454545 | 126 | 0.709677 | 4.227273 | false | false | false | false |
LorittaBot/Loritta | discord/loritta-bot-common/src/main/kotlin/net/perfectdreams/loritta/morenitta/parallax/wrappers/ParallaxEmbed.kt | 1 | 4376 | package net.perfectdreams.loritta.morenitta.parallax.wrappers
import com.google.gson.annotations.SerializedName
import net.perfectdreams.loritta.morenitta.utils.Constants
import net.perfectdreams.loritta.morenitta.utils.extensions.isValidUrl
import net.perfectdreams.loritta.morenitta.utils.substringIfNeeded
import net.dv8tion.jda.api.EmbedBuilder
import net.dv8tion.jda.api.entities.MessageEmbed
import java.awt.Color
class ParallaxEmbed {
var rgb: ParallaxColor? = null
var color: Int? = null
var hex: String? = null
var title: String? = null
var url: String? = null
var description: String? = null
var author: ParallaxEmbedAuthor? = null
var thumbnail: ParallaxEmbedImage? = null
var image: ParallaxEmbedImage? = null
var footer: ParallaxEmbedFooter? = null
var fields: MutableList<ParallaxEmbedField>? = null
@JvmOverloads
fun addBlankField(inline: Boolean = false): ParallaxEmbed {
if (fields == null)
fields = mutableListOf()
fields!!.add(ParallaxEmbedField(" ", " ", inline))
return this
}
@JvmOverloads
fun addField(name: String, value: String, inline: Boolean = false): ParallaxEmbed {
if (fields == null)
fields = mutableListOf()
fields!!.add(ParallaxEmbedField(name, value, inline))
return this
}
// TODO: attachFile
// TODO: attachFiles
@JvmOverloads
fun setAuthor(name: String, icon: String? = null, url: String? = null): ParallaxEmbed {
author = ParallaxEmbedAuthor(name, icon, url)
return this
}
// TODO: setColor
fun setColor(color: Color): ParallaxEmbed {
this.color = (color.rgb + 16777216)
return this
}
fun setDescription(description: String): ParallaxEmbed {
this.description = description
return this
}
@JvmOverloads
fun setFooter(text: String, icon: String? = null): ParallaxEmbed {
this.footer = ParallaxEmbedFooter(text, icon)
return this
}
fun setImage(url: String): ParallaxEmbed {
this.image = ParallaxEmbedImage(url)
return this
}
fun setThumbnail(url: String): ParallaxEmbed {
this.thumbnail = ParallaxEmbedImage(url)
return this
}
// TODO: setTimestamp
fun setTitle(title: String): ParallaxEmbed {
this.title = title
return this
}
fun setURL(url: String): ParallaxEmbed {
this.url = url
return this
}
fun toDiscordEmbed(safe: Boolean = false): MessageEmbed {
val embed = EmbedBuilder()
fun processString(text: String?, maxSize: Int): String? {
if (safe && text != null) {
return text.substringIfNeeded(0 until maxSize)
}
return text
}
fun processImageUrl(url: String?): String? {
if (safe && url != null) {
if (!url.isValidUrl())
return Constants.INVALID_IMAGE_URL
}
return url
}
fun processUrl(url: String?): String? {
if (safe && url != null) {
if (!url.isValidUrl())
return null
}
return url
}
if (color != null) {
val red = color!! shr 16 and 0xFF
val green = color!! shr 8 and 0xFF
val blue = color!! and 0xFF
embed.setColor(Color(red, green, blue))
}
if (rgb != null) {
val rgb = rgb!!
embed.setColor(Color(rgb.r, rgb.b, rgb.g))
}
if (hex != null) {
embed.setColor(Color.decode(hex))
}
if (description != null) {
embed.setDescription(processString(description!!, 2048))
}
if (title != null) {
embed.setTitle(processString(title, 256), processUrl(url))
}
if (author != null) {
embed.setAuthor(processString(author!!.name, 256), processUrl(author!!.url), processImageUrl(author!!.iconUrl))
}
if (footer != null) {
embed.setFooter(processString(footer!!.text, 256), processImageUrl(footer!!.iconUrl))
}
if (image != null) {
embed.setImage(processImageUrl(image!!.url))
}
if (thumbnail != null) {
embed.setThumbnail(processImageUrl(thumbnail!!.url))
}
if (fields != null) {
fields!!.forEach {
val fieldName = it.name
val fieldValue = it.value
if (fieldName != null && fieldValue != null)
embed.addField(fieldName, fieldValue, it.inline)
}
}
return embed.build()
}
class ParallaxEmbedAuthor(
var name: String?,
var url: String?,
@SerializedName("icon_url")
var iconUrl: String?
)
class ParallaxEmbedImage(
var url: String?
)
class ParallaxEmbedFooter(
var text: String?,
@SerializedName("icon_url")
var iconUrl: String?
)
class ParallaxEmbedField(
var name: String?,
var value: String?,
var inline: Boolean = false
)
} | agpl-3.0 | ea9dfd3968b9cdd4abca08d6a21e8a1c | 22.281915 | 114 | 0.689671 | 3.260805 | false | false | false | false |
proxer/ProxerAndroid | src/main/kotlin/me/proxer/app/profile/settings/ProfileSettingsViewModel.kt | 1 | 2744 | package me.proxer.app.profile.settings
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.Disposable
import io.reactivex.schedulers.Schedulers
import me.proxer.app.util.ErrorUtils
import me.proxer.app.util.data.ResettingMutableLiveData
import me.proxer.app.util.data.StorageHelper
import me.proxer.app.util.extension.buildSingle
import me.proxer.app.util.extension.safeInject
import me.proxer.app.util.extension.subscribeAndLogErrors
import me.proxer.app.util.extension.toLocalSettings
import me.proxer.library.ProxerApi
/**
* @author Ruben Gees
*/
class ProfileSettingsViewModel : ViewModel() {
val data = MutableLiveData<LocalProfileSettings>()
val error = ResettingMutableLiveData<ErrorUtils.ErrorAction>()
val updateError = ResettingMutableLiveData<ErrorUtils.ErrorAction>()
private val api by safeInject<ProxerApi>()
private val storageHelper by safeInject<StorageHelper>()
private var disposable: Disposable? = null
init {
data.value = storageHelper.profileSettings
refresh()
}
override fun onCleared() {
disposable?.dispose()
disposable = null
super.onCleared()
}
fun refresh() {
disposable?.dispose()
disposable = api.ucp.settings()
.buildSingle()
.map { it.toLocalSettings() }
.doOnSuccess { storageHelper.profileSettings = it }
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.doOnSubscribe {
error.value = null
updateError.value = null
}
.subscribeAndLogErrors(
{
data.value = it
},
{
error.value = ErrorUtils.handle(it)
}
)
}
fun update(newData: LocalProfileSettings) {
data.value = newData
disposable?.dispose()
disposable = api.ucp.setSettings(newData.toNonLocalSettings())
.buildSingle()
.doOnSuccess { storageHelper.profileSettings = newData }
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.doOnSubscribe {
error.value = null
updateError.value = null
}
.subscribeAndLogErrors(
{},
{
updateError.value = ErrorUtils.handle(it)
}
)
}
fun retryUpdate() {
val safeData = data.value
if (safeData != null) {
update(safeData)
}
}
}
| gpl-3.0 | 6e1122e649f208eaf8c7f2acb593e710 | 28.191489 | 72 | 0.612245 | 5.138577 | false | false | false | false |
mua-uniandes/weekly-problems | codeforces/292/292B.kt | 1 | 752 | package codeforces
import java.io.BufferedReader
import java.io.InputStreamReader
fun main() {
val In = BufferedReader(InputStreamReader(System.`in`))
val graph = In.readLine()!!.split(" ").map {it.toInt()}
val n = graph[0]
val m = graph[1]
val arr = List(n){0}.toMutableList()
for( i in 0..m) {
val edges = In.readLine()!!.split(" ").map {it.toInt()}
arr[edges[0]] += 1
arr[edges[1]] += 1
}
arr.sortedDescending()
if(arr[0] > 2 && arr[1] == 1 && arr[n-1] == 1)
println("star topology")
else if(arr[0] == 2 && arr[n-1] == 1)
println("bus topology")
else if(arr[0] == 2 && arr[n-1] == 2)
println("ring topology")
else
println("unknown topology")
} | gpl-3.0 | 4183ac7f9400cdc0a443fdb6d8c497a8 | 27.961538 | 63 | 0.551862 | 3.312775 | false | false | false | false |
ngageoint/mage-android | mage/src/main/java/mil/nga/giat/mage/map/MapAndViewProvider.kt | 1 | 1422 | package mil.nga.giat.mage.map
import android.view.View
import android.view.ViewTreeObserver.OnGlobalLayoutListener
import com.google.android.gms.maps.GoogleMap
import com.google.android.gms.maps.OnMapReadyCallback
import com.google.android.gms.maps.SupportMapFragment
class MapAndViewProvider(
private val mapFragment: SupportMapFragment
) : OnGlobalLayoutListener, OnMapReadyCallback {
private lateinit var listener: OnMapAndViewReadyListener
private val mapView: View? = mapFragment.view
private var isViewReady = false
private var isMapReady = false
private var map: GoogleMap? = null
interface OnMapAndViewReadyListener {
fun onMapAndViewReady(googleMap: GoogleMap?)
}
fun getMapAndViewAsync(listener: OnMapAndViewReadyListener) {
this.listener = listener
if (mapView?.width != 0 && mapView?.height != 0) {
isViewReady = true
} else {
mapView.viewTreeObserver.addOnGlobalLayoutListener(this)
}
mapFragment.getMapAsync(this)
}
override fun onMapReady(googleMap: GoogleMap) {
map = googleMap
isMapReady = true
checkReady()
}
override fun onGlobalLayout() {
mapView?.viewTreeObserver?.removeOnGlobalLayoutListener(this)
isViewReady = true
checkReady()
}
private fun checkReady() {
if (isViewReady && isMapReady) {
listener.onMapAndViewReady(map)
}
}
} | apache-2.0 | 5627c9b26e0d5fe4b17b6c60f1392235 | 25.849057 | 67 | 0.718003 | 4.9375 | false | false | false | false |
kyegupov/ido_web_dictionary | conversion_tools/backend/src/main/kotlin/org/kyegupov/dictionary/tools/generate_stardict_dictionary.kt | 1 | 2597 | package org.kyegupov.dictionary.tools
import org.kyegupov.dictionary.common.languageToDirections
import org.kyegupov.dictionary.common.loadDataFromAlphabetizedShards
import java.io.DataOutputStream
import java.io.File
import java.nio.charset.StandardCharsets
import java.nio.file.Files
import java.nio.file.Paths
fun main(args : Array<String>) {
for ((_, directions) in languageToDirections) {
for (direction in directions) {
val data = loadDataFromAlphabetizedShards("dictionaries_by_letter/${direction.s}")
val targetPath = "backend/src/main/resources/stardict/${direction.s}"
File(targetPath).deleteRecursively()
Files.createDirectories(Paths.get(targetPath))
val dictFileStream = Files.newOutputStream(Paths.get(targetPath).resolve(direction.s + ".dict"))
val idxData = mutableListOf<Pair<Int, Int>>()
var offset = 0
for (article in data.entries) {
val bytes = article.toByteArray(StandardCharsets.UTF_8)
dictFileStream.write(bytes)
idxData.add(Pair(offset, bytes.size))
offset += bytes.size
}
dictFileStream.close()
val idxFileStream = DataOutputStream(Files.newOutputStream(Paths.get(targetPath).resolve(direction.s + ".idx")))
val allWords = data.compactIndex.keys.sortedBy {
// Emulate g_ascii_strcasecmp
// TODO: better emulation
it.toByteArray(StandardCharsets.US_ASCII).toString(StandardCharsets.US_ASCII).toLowerCase() }
var idxSize = 0
for (word in allWords) {
val articleIds = data.compactIndex[word]!!
for (articleId in articleIds) {
val wordBytes = word.toByteArray(StandardCharsets.UTF_8)
idxFileStream.write(wordBytes)
idxFileStream.write(0)
idxFileStream.writeInt(idxData[articleId].first)
idxFileStream.writeInt(idxData[articleId].second)
idxSize += wordBytes.size + 9
}
}
idxFileStream.close()
val ifoFileWriter = Files.newOutputStream(Paths.get(targetPath).resolve(direction.s + ".ifo")).writer(StandardCharsets.UTF_8)
ifoFileWriter.write("""StarDict's dict ifo file
version=3.0.0
[options]
bookname=${direction.s}
wordcount=${allWords.size}
idxfilesize=${idxSize}
sametypesequence=h
"""
)
ifoFileWriter.close()
}
}
}
| mit | e2fd3589f89f466837efcf7d79a33d4c | 38.348485 | 137 | 0.623412 | 4.364706 | false | false | false | false |
mozilla-mobile/focus-android | app/src/test/java/org/mozilla/focus/whatsnew/WhatsNewStorageTest.kt | 1 | 1567 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
package org.mozilla.focus.whatsnew
import android.app.Application
import androidx.preference.PreferenceManager
import androidx.test.core.app.ApplicationProvider
import org.junit.Assert.assertEquals
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
@RunWith(RobolectricTestRunner::class)
class WhatsNewStorageTest {
@Before
fun setUp() {
// Reset all saved and cached values before running a test
PreferenceManager.getDefaultSharedPreferences(ApplicationProvider.getApplicationContext())
.edit()
.clear()
.apply()
}
@Test
fun testGettingAndSettingAVersion() {
val storage = SharedPreferenceWhatsNewStorage(ApplicationProvider.getApplicationContext() as Application)
val version = WhatsNewVersion("3.0")
storage.setVersion(version)
val storedVersion = storage.getVersion()
assertEquals(version, storedVersion)
}
@Test
fun testGettingAndSettingTheSessionCounter() {
val storage = SharedPreferenceWhatsNewStorage(ApplicationProvider.getApplicationContext() as Application)
val expected = 3
storage.setSessionCounter(expected)
val storedCounter = storage.getSessionCounter()
assertEquals(expected, storedCounter)
}
}
| mpl-2.0 | 2f94f82d1e903dcf6fdec7b46ba7b156 | 31.645833 | 113 | 0.728781 | 4.83642 | false | true | false | false |
robinverduijn/gradle | buildSrc/subprojects/profiling/src/main/kotlin/org/gradle/gradlebuild/profiling/buildscan/BuildScanPlugin.kt | 1 | 11744 | /*
* Copyright 2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gradle.gradlebuild.profiling.buildscan
import com.gradle.scan.plugin.BuildScanExtension
import org.gradle.api.Plugin
import org.gradle.api.Project
import org.gradle.api.Task
import org.gradle.api.plugins.quality.Checkstyle
import org.gradle.api.plugins.quality.CodeNarc
import org.gradle.api.reporting.Reporting
import org.gradle.api.tasks.compile.AbstractCompile
import org.gradle.build.ClasspathManifest
import org.gradle.build.docs.CacheableAsciidoctorTask
import org.gradle.gradlebuild.BuildEnvironment.isCiServer
import org.gradle.gradlebuild.BuildEnvironment.isJenkins
import org.gradle.gradlebuild.BuildEnvironment.isTravis
import org.gradle.kotlin.dsl.*
import org.jsoup.Jsoup
import org.jsoup.parser.Parser
import java.net.URLEncoder
import java.util.concurrent.atomic.AtomicBoolean
import kotlin.collections.component1
import kotlin.collections.component2
import kotlin.collections.filter
import kotlin.collections.forEach
const val serverUrl = "https://e.grdev.net"
private
const val gitCommitName = "Git Commit ID"
private
const val ciBuildTypeName = "CI Build Type"
@Suppress("unused") // consumed as plugin gradlebuild.buildscan
open class BuildScanPlugin : Plugin<Project> {
private
lateinit var buildScan: BuildScanExtension
private
val cacheMissTagged = AtomicBoolean(false)
override fun apply(project: Project): Unit = project.run {
apply(plugin = "com.gradle.build-scan")
buildScan = the()
extractCiOrLocalData()
extractVcsData()
if (isCiServer && !isTravis && !isJenkins) {
extractAllReportsFromCI()
monitorUnexpectedCacheMisses()
}
extractCheckstyleAndCodenarcData()
extractBuildCacheData()
}
private
fun Project.monitorUnexpectedCacheMisses() {
gradle.taskGraph.afterTask {
if (buildCacheEnabled() && isCacheMiss() && isNotTaggedYet()) {
buildScan.tag("CACHE_MISS")
}
}
}
private
fun Project.buildCacheEnabled() = gradle.startParameter.isBuildCacheEnabled
private
fun isNotTaggedYet() = cacheMissTagged.compareAndSet(false, true)
private
fun Task.isCacheMiss() = !state.skipped && (isCompileCacheMiss() || isAsciidoctorCacheMiss())
private
fun Task.isCompileCacheMiss() = isMonitoredCompileTask() && !isExpectedCompileCacheMiss()
private
fun Task.isAsciidoctorCacheMiss() = isMonitoredAsciidoctorTask() && !isExpectedAsciidoctorCacheMiss()
private
fun Task.isMonitoredCompileTask() = this is AbstractCompile || this is ClasspathManifest
private
fun Task.isMonitoredAsciidoctorTask() = this is CacheableAsciidoctorTask
private
fun Task.isExpectedAsciidoctorCacheMiss() =
// Expected cache-miss for asciidoctor task:
// 1. CompileAll is the seed build for docs:distDocs
// 2. Gradle_Check_BuildDistributions is the seed build for other asciidoctor tasks
// 3. buildScanPerformance test, which doesn't depend on compileAll
// 4. buildScanPerformance test, which doesn't depend on compileAll
isInBuild(
"Gradle_Check_CompileAll",
"Gradle_Check_BuildDistributions",
"Enterprise_Master_Components_GradleBuildScansPlugin_Performance_PerformanceLinux",
"Enterprise_Release_Components_BuildScansPlugin_Performance_PerformanceLinux"
)
private
fun Task.isExpectedCompileCacheMiss() =
// Expected cache-miss:
// 1. CompileAll is the seed build
// 2. Gradleception which re-builds Gradle with a new Gradle version
// 3. buildScanPerformance test, which doesn't depend on compileAll
// 4. buildScanPerformance test, which doesn't depend on compileAll
isInBuild(
"Gradle_Check_CompileAll",
"Enterprise_Master_Components_GradleBuildScansPlugin_Performance_PerformanceLinux",
"Enterprise_Release_Components_BuildScansPlugin_Performance_PerformanceLinux",
"Gradle_Check_Gradleception"
)
private
fun Task.isInBuild(vararg buildTypeIds: String) = System.getenv("BUILD_TYPE_ID") in buildTypeIds
private
fun Project.extractCheckstyleAndCodenarcData() {
gradle.taskGraph.afterTask {
if (state.failure != null) {
if (this is Checkstyle && reports.xml.destination.exists()) {
val checkstyle = Jsoup.parse(reports.xml.destination.readText(), "", Parser.xmlParser())
val errors = checkstyle.getElementsByTag("file").flatMap { file ->
file.getElementsByTag("error").map { error ->
val filePath = rootProject.relativePath(file.attr("name"))
"$filePath:${error.attr("line")}:${error.attr("column")} \u2192 ${error.attr("message")}"
}
}
errors.forEach { buildScan.value("Checkstyle Issue", it) }
}
if (this is CodeNarc && reports.xml.destination.exists()) {
val codenarc = Jsoup.parse(reports.xml.destination.readText(), "", Parser.xmlParser())
val errors = codenarc.getElementsByTag("Package").flatMap { codenarcPackage ->
codenarcPackage.getElementsByTag("File").flatMap { file ->
file.getElementsByTag("Violation").map { violation ->
val filePath = rootProject.relativePath(file.attr("name"))
val message = violation.run {
getElementsByTag("Message").first()
?: getElementsByTag("SourceLine").first()
}
"$filePath:${violation.attr("lineNumber")} \u2192 ${message.text()}"
}
}
}
errors.forEach { buildScan.value("CodeNarc Issue", it) }
}
}
}
}
private
fun Project.extractCiOrLocalData() {
if (isCiServer) {
buildScan {
tag("CI")
when {
isTravis -> {
link("Travis Build", System.getenv("TRAVIS_BUILD_WEB_URL"))
value("Build ID", System.getenv("TRAVIS_BUILD_ID"))
setCommitId(System.getenv("TRAVIS_COMMIT"))
}
isJenkins -> {
link("Jenkins Build", System.getenv("BUILD_URL"))
value("Build ID", System.getenv("BUILD_ID"))
setCommitId(System.getenv("GIT_COMMIT"))
}
else -> {
link("TeamCity Build", System.getenv("BUILD_URL"))
value("Build ID", System.getenv("BUILD_ID"))
setCommitId(System.getenv("BUILD_VCS_NUMBER"))
}
}
whenEnvIsSet("BUILD_TYPE_ID") { buildType ->
value(ciBuildTypeName, buildType)
link("Build Type Scans", customValueSearchUrl(mapOf(ciBuildTypeName to buildType)))
}
}
} else {
buildScan.tag("LOCAL")
if (listOf("idea.registered", "idea.active", "idea.paths.selector").map(System::getProperty).filterNotNull().isNotEmpty()) {
buildScan.tag("IDEA")
System.getProperty("idea.paths.selector")?.let { ideaVersion ->
buildScan.value("IDEA version", ideaVersion)
}
}
}
}
private
fun BuildScanExtension.whenEnvIsSet(envName: String, action: BuildScanExtension.(envValue: String) -> Unit) {
val envValue: String? = System.getenv(envName)
if (!envValue.isNullOrEmpty()) {
action(envValue)
}
}
private
fun Project.extractVcsData() {
buildScan {
if (!isCiServer) {
background {
setCommitId(execAndGetStdout("git", "rev-parse", "--verify", "HEAD"))
}
}
background {
execAndGetStdout("git", "status", "--porcelain").takeIf { it.isNotEmpty() }?.let { status ->
tag("dirty")
value("Git Status", status)
}
}
background {
execAndGetStdout("git", "rev-parse", "--abbrev-ref", "HEAD").takeIf { it.isNotEmpty() && it != "HEAD" }?.let { branchName ->
tag(branchName)
value("Git Branch Name", branchName)
}
}
}
}
private
fun Project.extractBuildCacheData() {
if (gradle.startParameter.isBuildCacheEnabled) {
buildScan.tag("CACHED")
}
}
private
fun Project.extractAllReportsFromCI() {
val capturedReportingTypes = listOf("html") // can add xml, text, junitXml if wanted
val basePath = "${System.getenv("BUILD_SERVER_URL")}/repository/download/${System.getenv("BUILD_TYPE_ID")}/${System.getenv("BUILD_ID")}:id"
gradle.taskGraph.afterTask {
if (state.failure != null && this is Reporting<*>) {
this.reports.filter { it.name in capturedReportingTypes && it.isEnabled && it.destination.exists() }
.forEach { report ->
val linkName = "${this::class.java.simpleName.split("_")[0]} Report ($path)" // Strip off '_Decorated' addition to class names
// see: ciReporting.gradle
val reportPath =
if (report.destination.isDirectory) "report-${project.name}-${report.destination.name}.zip"
else "report-${project.name}-${report.destination.parentFile.name}-${report.destination.name}"
val reportLink = "$basePath/$reportPath"
buildScan.link(linkName, reportLink)
}
}
}
}
private
fun BuildScanExtension.setCommitId(commitId: String) {
value(gitCommitName, commitId)
link("Source", "https://github.com/gradle/gradle/commit/$commitId")
if (!isTravis) {
link("Git Commit Scans", customValueSearchUrl(mapOf(gitCommitName to commitId)))
link("CI CompileAll Scan", customValueSearchUrl(mapOf(gitCommitName to commitId)) + "&search.tags=CompileAll")
}
}
private
inline fun buildScan(configure: BuildScanExtension.() -> Unit) {
buildScan.apply(configure)
}
}
private
fun customValueSearchUrl(search: Map<String, String>): String {
val query = search.map { (name, value) ->
"search.names=${name.urlEncode()}&search.values=${value.urlEncode()}"
}.joinToString("&")
return "$serverUrl/scans?$query"
}
private
fun String.urlEncode() = URLEncoder.encode(this, Charsets.UTF_8.name())
| apache-2.0 | 51716c0f5c3c7c7e87b23d18c91b294e | 37.631579 | 150 | 0.599796 | 4.69948 | false | false | false | false |
corenting/EDCompanion | app/src/main/java/fr/corenting/edcompanion/adapters/AutoCompleteAdapter.kt | 1 | 2904 | package fr.corenting.edcompanion.adapters
import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.BaseAdapter
import android.widget.Filter
import android.widget.Filterable
import android.widget.TextView
import fr.corenting.edcompanion.network.AutoCompleteNetwork
import java.util.*
class AutoCompleteAdapter(private val context: Context, private val autocompleteType: Int) :
BaseAdapter(), Filterable {
private var resultList: List<String> = ArrayList()
override fun getCount(): Int {
return resultList.size
}
override fun getItem(index: Int): String {
return resultList[index]
}
override fun getItemId(position: Int): Long {
return position.toLong()
}
override fun getView(position: Int, convertView: View?, parent: ViewGroup): View {
val view:View? = if (convertView == null) {
val inflater = context.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater
inflater.inflate(android.R.layout.simple_dropdown_item_1line, parent,
false)
}
else {
convertView
}
(view?.findViewById<View>(android.R.id.text1) as TextView).text = getItem(position)
return view
}
override fun getFilter(): Filter {
return object : Filter() {
override fun performFiltering(constraint: CharSequence?): FilterResults {
val filterResults = FilterResults()
if (constraint != null) {
val results: List<String> = when (autocompleteType) {
TYPE_AUTOCOMPLETE_SYSTEMS -> AutoCompleteNetwork.searchSystems(context, constraint.toString())
TYPE_AUTOCOMPLETE_SHIPS -> AutoCompleteNetwork.searchShips(context, constraint.toString())
else -> AutoCompleteNetwork.searchCommodities(context, constraint.toString())
}
// Assign the data to the FilterResults
filterResults.values = results
filterResults.count = results.size
}
return filterResults
}
override fun publishResults(constraint: CharSequence?, results: FilterResults?) {
if (results != null && results.count > 0) {
val castedResults = (results.values as List<*>).filterIsInstance<String>()
if (castedResults.isNotEmpty()) {
resultList = castedResults
}
}
notifyDataSetInvalidated()
}
}
}
companion object {
const val TYPE_AUTOCOMPLETE_SYSTEMS = 0
const val TYPE_AUTOCOMPLETE_SHIPS = 1
const val TYPE_AUTOCOMPLETE_COMMODITIES = 2
}
}
| mit | 2618515b73b1c30e30e45ab6b9744e98 | 35.759494 | 118 | 0.613292 | 5.308958 | false | false | false | false |
wordpress-mobile/WordPress-FluxC-Android | example/src/test/java/org/wordpress/android/fluxc/store/ReactNativeStoreWpComTest.kt | 1 | 3060 | package org.wordpress.android.fluxc.store
import android.net.Uri
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.mockito.kotlin.mock
import org.mockito.kotlin.whenever
import org.robolectric.RobolectricTestRunner
import org.robolectric.annotation.Config
import org.wordpress.android.fluxc.TestSiteSqlUtils
import org.wordpress.android.fluxc.model.SiteModel
import org.wordpress.android.fluxc.network.BaseRequest.GenericErrorType.UNKNOWN
import org.wordpress.android.fluxc.network.discovery.DiscoveryWPAPIRestClient
import org.wordpress.android.fluxc.network.rest.wpapi.NonceRestClient
import org.wordpress.android.fluxc.network.rest.wpcom.reactnative.ReactNativeWPComRestClient
import org.wordpress.android.fluxc.store.ReactNativeFetchResponse.Error
import org.wordpress.android.fluxc.store.ReactNativeFetchResponse.Success
import org.wordpress.android.fluxc.test
import org.wordpress.android.fluxc.tools.initCoroutineEngine
import kotlin.test.assertEquals
import kotlin.test.assertNull
@Config(manifest = Config.NONE)
@RunWith(RobolectricTestRunner::class)
class ReactNativeStoreWpComTest {
private val wpComRestClient = mock<ReactNativeWPComRestClient>()
private val discoveryWPAPIRestClient = mock<DiscoveryWPAPIRestClient>()
private val nonceRestClient = mock<NonceRestClient>()
private lateinit var store: ReactNativeStore
@Before
fun setup() {
store = ReactNativeStore(
wpComRestClient,
mock(),
nonceRestClient,
discoveryWPAPIRestClient,
TestSiteSqlUtils.siteSqlUtils,
initCoroutineEngine()
)
}
@Test
fun `makes call to WPcom`() = test {
val expectedResponse = mock<ReactNativeFetchResponse>()
val site = mock<SiteModel>()
whenever(site.siteId).thenReturn(123456L)
whenever(site.isUsingWpComRestApi).thenReturn(true)
val expectedUrl = "https://public-api.wordpress.com/wp/v2/sites/${site.siteId}/media"
whenever(wpComRestClient.fetch(expectedUrl, mapOf("paramKey" to "paramValue"), ::Success, ::Error))
.thenReturn(expectedResponse)
val actualResponse = store.executeRequest(site, "/wp/v2/media?paramKey=paramValue")
assertEquals(expectedResponse, actualResponse)
}
@Test
fun `handles failure to parse path`() = test {
val mockUri = mock<Uri>()
assertNull(mockUri.path, "path must be null to represent failure to parse the path in this test")
val uriParser = { _: String -> mockUri }
store = ReactNativeStore(
wpComRestClient,
mock(),
nonceRestClient,
discoveryWPAPIRestClient,
TestSiteSqlUtils.siteSqlUtils,
initCoroutineEngine(),
uriParser = uriParser)
val response = store.executeRequest(mock(), "")
val errorType = (response as? Error)?.error?.type
assertEquals(UNKNOWN, errorType)
}
}
| gpl-2.0 | 1ffb49b27f2b9e161e1102a91f0d6e0c | 37.25 | 107 | 0.710131 | 4.664634 | false | true | false | false |
vase4kin/TeamCityApp | app/src/main/java/com/github/vase4kin/teamcityapp/login/view/LoginViewImpl.kt | 1 | 11391 | /*
* Copyright 2020 Andrey Tolpeev
*
* 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.vase4kin.teamcityapp.login.view
import android.app.Activity
import android.content.Context
import android.view.View
import android.view.inputmethod.EditorInfo
import android.view.inputmethod.InputMethodManager
import android.widget.Button
import android.widget.EditText
import android.widget.ProgressBar
import android.widget.Switch
import androidx.annotation.StringRes
import androidx.core.text.HtmlCompat
import butterknife.BindView
import butterknife.ButterKnife
import butterknife.Unbinder
import com.afollestad.materialdialogs.MaterialDialog
import com.github.vase4kin.teamcityapp.R
import com.google.android.material.button.MaterialButton
import com.google.android.material.textfield.TextInputLayout
class LoginViewImpl(private val activity: Activity) : LoginView {
@BindView(R.id.teamcity_url)
lateinit var serverUrl: EditText
@BindView(R.id.teamcity_url_wrapper)
lateinit var serverUrlWrapperLayout: TextInputLayout
@BindView(R.id.user_field_wrapper)
lateinit var userNameWrapperLayout: TextInputLayout
@BindView(R.id.user_name)
lateinit var userName: EditText
@BindView(R.id.password_field_wrapper)
lateinit var passwordWrapperLayout: TextInputLayout
@BindView(R.id.password)
lateinit var password: EditText
@BindView(R.id.guest_user_switch)
lateinit var guestUserSwitch: Switch
@BindView(R.id.disable_ssl_switch)
lateinit var disableSslSwitch: Switch
@BindView(R.id.btn_login)
lateinit var loginButton: Button
@BindView(R.id.give_it_a_try_view)
lateinit var tryItOutTextView: View
@BindView(R.id.give_it_a_try_progress)
lateinit var progressBar: ProgressBar
@BindView(R.id.btn_try_it_out)
lateinit var tryItOutTextButton: MaterialButton
private lateinit var unbinder: Unbinder
private lateinit var progressDialog: MaterialDialog
private var listener: LoginView.ViewListener? = null
/**
* {@inheritDoc}
*/
override fun initViews(listener: LoginView.ViewListener) {
unbinder = ButterKnife.bind(this, activity)
this.listener = listener
progressDialog = MaterialDialog.Builder(activity)
.content(R.string.text_progress_bar_loading)
.progress(true, 0)
.autoDismiss(false)
.build()
progressDialog.setCancelable(false)
progressDialog.setCanceledOnTouchOutside(false)
password.setOnEditorActionListener { _, actionId, _ ->
if (actionId == EditorInfo.IME_ACTION_DONE) {
listener.onUserLoginButtonClick(
serverUrl.text.toString().trim { it <= ' ' },
userName.text.toString().trim { it <= ' ' },
password.text.toString().trim { it <= ' ' },
disableSslSwitch.isChecked
)
}
true
}
guestUserSwitch.setOnCheckedChangeListener { _, b ->
userName.visibility = if (b) View.GONE else View.VISIBLE
userNameWrapperLayout.visibility = if (b) View.GONE else View.VISIBLE
password.visibility = if (b) View.GONE else View.VISIBLE
passwordWrapperLayout.visibility = if (b) View.GONE else View.VISIBLE
setupViewsRegardingUserType(b, listener)
hideKeyboard()
}
setupViewsRegardingUserType(false, listener)
// Set text selection to the end
serverUrl.setSelection(serverUrl.text.length)
disableSslSwitch.setOnCheckedChangeListener { _, isChecked ->
if (isChecked) {
listener.onDisableSslSwitchClick()
}
}
tryItOutTextButton.setOnClickListener { listener.onTryItOutTextClick() }
}
/**
* Setup views regarding user type
*
* @param isGuestUser - Is guest user enabled
* @param listener - listener
*/
private fun setupViewsRegardingUserType(
isGuestUser: Boolean,
listener: LoginView.ViewListener
) {
if (isGuestUser) {
// guest user
serverUrl.imeOptions = EditorInfo.IME_ACTION_DONE
serverUrl.setOnEditorActionListener { v, actionId, _ ->
if (actionId == EditorInfo.IME_ACTION_DONE) {
listener.onGuestUserLoginButtonClick(
v.text.toString().trim { it <= ' ' }, disableSslSwitch.isChecked
)
}
true
}
loginButton.setOnClickListener {
listener.onGuestUserLoginButtonClick(
serverUrl.text.toString().trim { it <= ' ' },
disableSslSwitch.isChecked
)
}
} else {
// not guest user
serverUrl.imeOptions = EditorInfo.IME_ACTION_NEXT
serverUrl.setOnEditorActionListener(null)
loginButton.setOnClickListener {
listener.onUserLoginButtonClick(
serverUrl.text.toString().trim { it <= ' ' },
userName.text.toString().trim { it <= ' ' },
password.text.toString().trim { it <= ' ' },
disableSslSwitch.isChecked
)
}
}
}
/**
* {@inheritDoc}
*/
override fun close() {
activity.finish()
}
/**
* {@inheritDoc}
*/
override fun showProgressDialog() {
progressDialog.show()
}
/**
* {@inheritDoc}
*/
override fun dismissProgressDialog() {
progressDialog.dismiss()
}
/**
* {@inheritDoc}
*/
override fun unbindViews() {
listener = null
dismissAllDialogsOnDestroy()
unbinder.unbind()
}
/**
* {@inheritDoc}
*/
override fun showError(errorMessage: String) {
serverUrlWrapperLayout.error = errorMessage
}
override fun hideError() {
serverUrlWrapperLayout.error = null
}
/**
* {@inheritDoc}
*/
override fun showServerUrlCanNotBeEmptyError() {
setError(R.string.server_cannot_be_empty)
}
/**
* {@inheritDoc}
*/
override fun showUserNameCanNotBeEmptyError() {
setError(R.string.server_user_name_cannot_be_empty)
}
/**
* {@inheritDoc}
*/
override fun showPasswordCanNotBeEmptyError() {
setError(R.string.server_password_cannot_be_empty)
}
/**
* {@inheritDoc}
*/
override fun showCouldNotSaveUserError() {
setError(R.string.error_save_account)
}
/**
* {@inheritDoc}
*/
override fun hideKeyboard() {
val view = activity.currentFocus
if (view != null) {
val imm = activity.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
imm.hideSoftInputFromWindow(view.windowToken, 0)
}
}
/**
* {@inheritDoc}
*/
override fun showUnauthorizedInfoDialog() {
MaterialDialog.Builder(activity)
.title(R.string.info_unauthorized_dialog_title)
.content(R.string.info_unauthorized_dialog_content)
.positiveText(R.string.dialog_ok_title)
.show()
}
/**
* {@inheritDoc}
*/
override fun showTryItOutDialog(url: String) {
val content = activity.getString(R.string.info_try_it_out_dialog_content, url)
val formattedContent = HtmlCompat.fromHtml(content, HtmlCompat.FROM_HTML_MODE_COMPACT)
MaterialDialog.Builder(activity)
.title(R.string.info_try_it_out_title)
.content(formattedContent)
.positiveText(R.string.dialog_try_it_out_title)
.negativeText(R.string.warning_ssl_dialog_negative)
.onPositive { dialog, _ ->
listener?.onTryItOutActionClick()
dialog.dismiss()
}
.onNegative { dialog, _ ->
listener?.onDeclineTryItOutActionClick()
dialog.dismiss()
}
.canceledOnTouchOutside(false)
.autoDismiss(false)
.cancelable(false)
.show()
}
/**
* {@inheritDoc}
*/
override fun showDisableSslWarningDialog() {
MaterialDialog.Builder(activity)
.title(R.string.warning_ssl_dialog_title)
.content(R.string.warning_ssl_dialog_content)
.positiveText(R.string.dialog_ok_title)
.negativeText(R.string.warning_ssl_dialog_negative)
.onPositive { dialog, _ ->
disableSslSwitch.isChecked = true
dialog.dismiss()
}
.onNegative { dialog, _ ->
disableSslSwitch.isChecked = false
dialog.dismiss()
}
.canceledOnTouchOutside(false)
.autoDismiss(false)
.cancelable(false)
.show()
}
/**
* {@inheritDoc}
*/
override fun showNotSecureConnectionDialog(isGuest: Boolean) {
MaterialDialog.Builder(activity)
.title(R.string.warning_ssl_dialog_title)
.content(R.string.server_not_secure_http)
.positiveText(R.string.dialog_ok_title)
.negativeText(R.string.warning_ssl_dialog_negative)
.onPositive { dialog, _ ->
listener?.onAcceptNotSecureConnectionClick(isGuest)
dialog.dismiss()
}
.onNegative { dialog, _ ->
listener?.onCancelNotSecureConnectionClick()
dialog.dismiss()
}
.canceledOnTouchOutside(false)
.autoDismiss(false)
.cancelable(false)
.show()
}
/**
* {@inheritDoc}
*/
override fun showTryItOutLoading() {
progressBar.visibility = View.VISIBLE
}
/**
* {@inheritDoc}
*/
override fun hideTryItOutLoading() {
if (::progressBar.isInitialized) {
progressBar.visibility = View.GONE
}
}
/**
* {@inheritDoc}
*/
override fun showTryItOut() {
if (::tryItOutTextView.isInitialized) {
tryItOutTextView.visibility = View.VISIBLE
}
}
/**
* Set error with string resource id
*
* @param errorMessage - Error message resource id
*/
private fun setError(@StringRes errorMessage: Int) {
val errorMessageString = activity.getString(errorMessage)
serverUrlWrapperLayout.error = errorMessageString
}
/**
* Dismiss all dialogs on destroy
*/
private fun dismissAllDialogsOnDestroy() {
if (::progressDialog.isInitialized && progressDialog.isShowing) {
progressDialog.dismiss()
}
}
}
| apache-2.0 | 8a8b75d43d4b58c1247d16a8512b0c08 | 29.953804 | 99 | 0.60539 | 4.748228 | false | false | false | false |
siosio/upsource-kotlin-api | src/main/java/com/github/siosio/upsource/ProjectManager.kt | 1 | 3449 | package com.github.siosio.upsource
import com.github.siosio.upsource.bean.*
import com.github.siosio.upsource.exception.*
import com.github.siosio.upsource.internal.*
class ProjectManager internal constructor(private val upsourceApi: UpsourceApi) {
fun allProjects(): List<Project> {
val projectInfoList = upsourceApi.send(GetAllProjectCommand())
return projectInfoList.project
}
fun allProjects(block: (Project) -> Unit) {
allProjects().forEach {
block(it)
}
}
/**
* get project
*/
operator fun get(projectId: String) = getProjectInfo(projectId)
fun getProjectInfo(projectId: String): ProjectInfo {
return upsourceApi.send(GetProjectInfoCommand(projectId)) ?: throw ProjectNotFoundException(projectId)
}
/**
* create project
*/
operator fun CreateProjectRequest.unaryPlus() {
upsourceApi.send(CreateProjectCommand(this))
}
fun project(
projectId: String,
projectName: String,
projectType: ProjectType,
pathToModel: String? = null,
defaultJdkId: String? = null,
codeReviewIdPattern: String,
checkIntervalSeconds: Long = 300L,
vcs: VcsSettings.() -> Unit,
runInspections: Boolean = true,
mavenSettings: String? = null,
mavenProfiles: String? = null,
mavenJdkName: String? = null,
links: ExternalLinks.() -> Unit = {},
createUserGroups: Boolean? = null,
userManagementUrl: String? = null,
defaultEncoding: String? = null,
defaultBranch: String? = null,
autoAddRevisionsToReview: Boolean? = null
): CreateProjectRequest {
val vcsSettings = VcsSettings()
vcsSettings.vcs()
val externalLinks = ExternalLinks()
externalLinks.links()
return CreateProjectRequest(
newProjectId = projectId,
settings = ProjectSettings(
projectName = projectName,
codeReviewIdPattern = codeReviewIdPattern,
checkIntervalSeconds = checkIntervalSeconds,
vcsSettings = toJson(mapOf("mappings" to vcsSettings.vcsSettings)),
runInspections = runInspections,
projectModel = ProjectModel(projectType.value, pathToModel, defaultJdkId),
mavenSettings = mavenSettings,
mavenProfiles = mavenProfiles,
mavenJdkName = mavenJdkName,
externalLinks = externalLinks.externalLinks,
createUserGroups = createUserGroups,
userManagementUrl = userManagementUrl,
defaultBranch = defaultBranch,
defaultEncoding = defaultEncoding,
autoAddRevisionsToReview = autoAddRevisionsToReview
)
)
}
/**
* delete project
*/
operator fun String.unaryMinus() {
upsourceApi.send(DeleteProjectCommand(ProjectId(this)))
}
private fun toJson(obj: Any): String {
return ObjectMapperCreator.create().writeValueAsString(obj)
}
}
class VcsSettings {
val vcsSettings: MutableList<VcsSetting> = mutableListOf()
fun repository(id: String, vcs: Vcs, url: String) = VcsSetting(id, vcs.value, url)
operator fun VcsSetting.unaryPlus() {
vcsSettings.add(this)
}
}
data class VcsSetting(val id: String, val vcs: String, val url: String)
class ExternalLinks {
val externalLinks: MutableList<ExternalLink> = mutableListOf()
fun link(url: String, prefix: String) = ExternalLink(url, prefix)
operator fun ExternalLink.unaryPlus() {
externalLinks.add(this)
}
}
| mit | 824a49e8d733cb54d280702559e24f42 | 28.228814 | 106 | 0.682807 | 4.508497 | false | false | false | false |
jmesserli/discord-bernbot | discord-bot/src/main/kotlin/nu/peg/discord/service/internal/DefaultMessageReadService.kt | 1 | 1152 | package nu.peg.discord.service.internal
import nu.peg.discord.service.MessageReadService
import nu.peg.discord.util.DiscordClientListener
import org.slf4j.LoggerFactory
import org.springframework.stereotype.Service
import sx.blah.discord.api.IDiscordClient
import sx.blah.discord.handle.obj.IChannel
import sx.blah.discord.handle.obj.IMessage
import java.time.LocalDateTime
import java.time.ZoneId
@Service
class DefaultMessageReadService : MessageReadService, DiscordClientListener {
companion object {
private val LOGGER = LoggerFactory.getLogger(DefaultMessageReadService::class.java)
}
private var discordClient: IDiscordClient? = null
override fun discordClientAvailable(client: IDiscordClient) {
discordClient = client
}
override fun readMessages(channel: IChannel, before: LocalDateTime): Iterator<IMessage> {
if (discordClient == null) {
LOGGER.info("No discord client set, not reading messages")
return emptyList<IMessage>().iterator()
}
return channel.getMessageHistoryFrom(before.atZone(ZoneId.systemDefault()).toInstant(), 100).iterator()
}
} | mit | 5a42ea79352d8db49e6a0256713276ed | 33.939394 | 111 | 0.757813 | 4.517647 | false | false | false | false |
noties/Markwon | app-sample/src/main/java/io/noties/markwon/app/samples/tasklist/TaskListMutateNestedSample.kt | 1 | 5019 | package io.noties.markwon.app.samples.tasklist
import android.text.style.ClickableSpan
import android.view.View
import io.noties.debug.Debug
import io.noties.markwon.AbstractMarkwonPlugin
import io.noties.markwon.Markwon
import io.noties.markwon.MarkwonVisitor
import io.noties.markwon.SoftBreakAddsNewLinePlugin
import io.noties.markwon.SpannableBuilder
import io.noties.markwon.app.sample.ui.MarkwonTextViewSample
import io.noties.markwon.ext.tasklist.TaskListItem
import io.noties.markwon.ext.tasklist.TaskListPlugin
import io.noties.markwon.ext.tasklist.TaskListProps
import io.noties.markwon.ext.tasklist.TaskListSpan
import io.noties.markwon.sample.annotations.MarkwonArtifact
import io.noties.markwon.sample.annotations.MarkwonSampleInfo
import io.noties.markwon.sample.annotations.Tag
import org.commonmark.node.AbstractVisitor
import org.commonmark.node.Block
import org.commonmark.node.HardLineBreak
import org.commonmark.node.Node
import org.commonmark.node.Paragraph
import org.commonmark.node.SoftLineBreak
import org.commonmark.node.Text
@MarkwonSampleInfo(
id = "20201228120444",
title = "Task list mutate nested",
description = "Task list mutation with nested items",
artifacts = [MarkwonArtifact.EXT_TASKLIST],
tags = [Tag.plugin]
)
class TaskListMutateNestedSample : MarkwonTextViewSample() {
override fun render() {
val md = """
# Task list
- [ ] not done
- [X] done
- [ ] nested not done
and text and textand text and text
- [X] nested done
""".trimIndent()
val markwon = Markwon.builder(context)
.usePlugin(TaskListPlugin.create(context))
.usePlugin(SoftBreakAddsNewLinePlugin.create())
.usePlugin(object : AbstractMarkwonPlugin() {
override fun configureVisitor(builder: MarkwonVisitor.Builder) {
builder.on(TaskListItem::class.java) { visitor, node ->
val length = visitor.length()
visitor.visitChildren(node)
TaskListProps.DONE.set(visitor.renderProps(), node.isDone)
val spans = visitor.configuration()
.spansFactory()
.get(TaskListItem::class.java)
?.getSpans(visitor.configuration(), visitor.renderProps())
if (spans != null) {
val taskListSpan = if (spans is Array<*>) {
spans.first { it is TaskListSpan } as? TaskListSpan
} else {
spans as? TaskListSpan
}
Debug.i("#### ${visitor.builder().substring(length, length + 3)}")
val content = TaskListContextVisitor.contentLength(node)
Debug.i("#### content: $content, '${visitor.builder().subSequence(length, length + content)}'")
if (content > 0 && taskListSpan != null) {
// maybe additionally identify this task list (for persistence)
visitor.builder().setSpan(
ToggleTaskListSpan(taskListSpan, visitor.builder().substring(length, length + content)),
length,
length + content
)
}
}
SpannableBuilder.setSpans(
visitor.builder(),
spans,
length,
visitor.length()
)
if (visitor.hasNext(node)) {
visitor.ensureNewLine()
}
}
}
})
.build()
markwon.setMarkdown(textView, md)
}
class TaskListContextVisitor : AbstractVisitor() {
companion object {
fun contentLength(node: Node): Int {
val visitor = TaskListContextVisitor()
visitor.visitChildren(node)
return visitor.contentLength
}
}
var contentLength: Int = 0
override fun visit(text: Text) {
super.visit(text)
contentLength += text.literal.length
}
// NB! if count both soft and hard breaks as having length of 1
override fun visit(softLineBreak: SoftLineBreak?) {
super.visit(softLineBreak)
contentLength += 1
}
// NB! if count both soft and hard breaks as having length of 1
override fun visit(hardLineBreak: HardLineBreak?) {
super.visit(hardLineBreak)
contentLength += 1
}
override fun visitChildren(parent: Node) {
var node = parent.firstChild
while (node != null) {
// A subclass of this visitor might modify the node, resulting in getNext returning a different node or no
// node after visiting it. So get the next node before visiting.
val next = node.next
if (node is Block && node !is Paragraph) {
break
}
node.accept(this)
node = next
}
}
}
class ToggleTaskListSpan(
val span: TaskListSpan,
val content: String
) : ClickableSpan() {
override fun onClick(widget: View) {
span.isDone = !span.isDone
widget.invalidate()
Debug.i("task-list click, isDone: ${span.isDone}, content: '$content'")
}
}
} | apache-2.0 | a84ce9a0ff2c3f2cae32accf01c566c6 | 30.974522 | 114 | 0.639171 | 4.533875 | false | false | false | false |
Jire/Strukt | src/main/kotlin/org/jire/strukt/CharField.kt | 1 | 1266 | /*
* Copyright 2020 Thomas Nappo (Jire)
*
* 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.jire.strukt
interface CharField : Field {
override val size get() = 2L
val default: Char
override fun writeDefault(address: Long) = set(address, default)
override fun getBoxed(address: Long) = get(address)
override fun setBoxed(address: Long, value: Any?) = set(address, value as Char)
operator fun get(address: Long) = threadSafeType.run { readChar(pointer(address)) }
operator fun set(address: Long, value: Char) = threadSafeType.run { writeChar(pointer(address), value) }
operator fun invoke(address: Long) = get(address)
operator fun invoke(address: Long, value: Char) = set(address, value)
} | apache-2.0 | 28bdcab3a5cdd0a78e128ba9736bf14a | 34.194444 | 105 | 0.71406 | 3.767857 | false | false | false | false |
http4k/http4k | http4k-aws/src/test/kotlin/org/http4k/aws/AwsRealMultipartTest.kt | 1 | 4057 | package org.http4k.aws
import com.natpryce.hamkrest.assertion.assertThat
import com.natpryce.hamkrest.containsSubstring
import com.natpryce.hamkrest.equalTo
import org.http4k.client.ApacheClient
import org.http4k.core.BodyMode
import org.http4k.core.HttpHandler
import org.http4k.core.Method.DELETE
import org.http4k.core.Method.GET
import org.http4k.core.Method.POST
import org.http4k.core.Method.PUT
import org.http4k.core.Request
import org.http4k.core.Status.Companion.NO_CONTENT
import org.http4k.core.Status.Companion.OK
import org.http4k.core.query
import org.http4k.core.then
import org.http4k.filter.Payload
import org.junit.jupiter.api.Test
class AwsRealMultipartTest : AbstractAwsRealS3TestCase() {
@Test
fun `default usage`() {
val client = awsClientFilter(Payload.Mode.Signed)
.then(ApacheClient(requestBodyMode = BodyMode.Memory))
bucketLifecycle((client))
}
private fun bucketLifecycle(client: HttpHandler) {
val contentOriginal = (1..5 * 1024 * 1024).map { 'a' }.joinToString("")
assertThat(
"Bucket should not exist in root listing",
client(Request(GET, s3Root)).bodyString(),
!containsSubstring(bucketName))
assertThat(
"Put of bucket should succeed",
client(Request(PUT, bucketUrl)).status,
equalTo(OK))
assertThat(
"Bucket should exist in root listing",
client(Request(GET, s3Root)).bodyString(),
containsSubstring(bucketName))
assertThat(
"Key should not exist in bucket listing",
client(Request(GET, bucketUrl)).bodyString(),
!containsSubstring(key))
/* initialise multipart */
val initialiseUpload = client(Request(POST, keyUrl.query("uploads", "")))
assertThat("Initialise of key should succeed", initialiseUpload.status, equalTo(OK))
val uploadId = UploadId.from(initialiseUpload)
/* upload a part */
val firstPart = client(Request(PUT, keyUrl
.query("partNumber", "1")
.query("uploadId", uploadId.value))
.body(contentOriginal.byteInputStream(), contentOriginal.length.toLong())
)
assertThat("First part upload", firstPart.status, equalTo(OK))
val etag1 = firstPart.header("ETag")!!
/* upload another part */
val secondPart = client(Request(PUT, keyUrl
.query("partNumber", "2")
.query("uploadId", uploadId.value))
.body(contentOriginal.byteInputStream(), contentOriginal.length.toLong())
)
assertThat("Second part upload", secondPart.status, equalTo(OK))
val etag2 = secondPart.header("ETag")!!
/* finalise multipart */
val finaliseUpload = client(Request(POST, keyUrl.query("uploadId", uploadId.value))
.body(listOf(etag1, etag2).asSequence().toCompleteMultipartUploadXml()))
assertThat("Finalize of key should succeed", finaliseUpload.status, equalTo(OK))
assertThat(
"Key should appear in bucket listing",
client(Request(GET, bucketUrl)).bodyString(),
containsSubstring(key))
assertThat(
"Key contents should be as expected",
client(Request(GET, keyUrl)).bodyString(),
equalTo(contentOriginal + contentOriginal))
assertThat(
"Delete of key should succeed",
client(Request(DELETE, keyUrl)).status,
equalTo(NO_CONTENT))
assertThat(
"Key should no longer appear in bucket listing",
client(Request(GET, bucketUrl)).bodyString(),
!containsSubstring(key))
assertThat(
"Delete of bucket should succeed",
client(Request(DELETE, bucketUrl)).status,
equalTo(NO_CONTENT))
assertThat(
"Bucket should no longer exist in root listing",
client(Request(GET, s3Root)).bodyString(),
!containsSubstring(bucketName))
}
}
| apache-2.0 | cd0e239df7d67a1b9a3241442becae99 | 38.38835 | 92 | 0.643579 | 4.438731 | false | false | false | false |
laurencegw/jenjin | jenjin-spine/src/main/kotlin/com/binarymonks/jj/spine/collisions/TriggerRagDollCollision.kt | 1 | 1995 | package com.binarymonks.jj.spine.collisions
import com.badlogic.gdx.physics.box2d.Contact
import com.badlogic.gdx.physics.box2d.Fixture
import com.binarymonks.jj.core.JJ
import com.binarymonks.jj.core.async.OneTimeTask
import com.binarymonks.jj.core.physics.CollisionHandler
import com.binarymonks.jj.core.pools.Poolable
import com.binarymonks.jj.core.pools.new
import com.binarymonks.jj.core.pools.recycle
import com.binarymonks.jj.spine.components.SpineBoneComponent
import com.binarymonks.jj.core.scenes.Scene
class TriggerRagDollCollision : CollisionHandler() {
var all = true
var gravity = 1f
override fun collision(me: Scene, myFixture: Fixture, other: Scene, otherFixture: Fixture, contact: Contact): Boolean {
val boneComponent: SpineBoneComponent = checkNotNull(me.getComponent(SpineBoneComponent::class).first())
JJ.tasks.addPostPhysicsTask(new(DelayedTriggerRagDoll::class).set(all, gravity, boneComponent, other))
return false
}
override fun clone(): CollisionHandler {
return TriggerRagDollCollision()
}
class DelayedTriggerRagDoll : OneTimeTask(), Poolable {
internal var spineBone: SpineBoneComponent? = null
internal var other: Scene? = null
internal var all = false
internal var gravity = 1f
operator fun set(all: Boolean, gravity: Float, spineBoneComponent: SpineBoneComponent, other: Scene): DelayedTriggerRagDoll {
this.spineBone = spineBoneComponent
this.other = other
this.all = all
this.gravity = gravity
return this
}
override fun doOnce() {
if (all)
spineBone!!.spineParent!!.triggerRagDoll(gravity)
else
spineBone!!.triggerRagDoll(gravity)
recycle(this)
}
override fun reset() {
spineBone = null
other = null
all = false
gravity = 1f
}
}
}
| apache-2.0 | fd3c87d2a24a30a382bd3525143e324c | 33.396552 | 133 | 0.672682 | 4.384615 | false | false | false | false |
dexbleeker/hamersapp | hamersapp/src/main/java/nl/ecci/hamers/ui/activities/NewMeetingActivity.kt | 1 | 3387 | package nl.ecci.hamers.ui.activities
import android.os.Bundle
import android.view.View
import android.widget.DatePicker
import com.android.volley.VolleyError
import kotlinx.android.synthetic.main.activity_general.*
import kotlinx.android.synthetic.main.stub_new_meeting.*
import nl.ecci.hamers.R
import nl.ecci.hamers.data.Loader
import nl.ecci.hamers.data.PostCallback
import nl.ecci.hamers.models.Meeting
import nl.ecci.hamers.ui.fragments.DatePickerFragment
import org.json.JSONException
import org.json.JSONObject
import java.text.SimpleDateFormat
import java.util.*
class NewMeetingActivity : HamersNewItemActivity() {
private var meeting: Meeting? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
initToolbar()
stub.layoutResource = R.layout.stub_new_meeting
stub.inflate()
meeting = gson.fromJson(intent.getStringExtra(Meeting.MEETING), Meeting::class.java)
val calendar = Calendar.getInstance()
val dateFormat = SimpleDateFormat("dd-MM-yyyy", MainActivity.locale)
if (meeting != null && meeting_subject != null && meeting_agenda != null) {
meeting_subject.setText(meeting!!.subject)
meeting_agenda.setText(meeting!!.agenda)
meeting_date_button.text = dateFormat.format(meeting!!.date)
} else {
meeting_date_button.text = dateFormat.format(calendar.time)
}
}
override fun postItem() {
if (meeting_date_button != null) {
val subject = meeting_subject.text.toString()
val agenda = meeting_agenda.text.toString()
val notes = meeting_notes.text.toString()
val date = meeting_date_button.text.toString()
val body = JSONObject()
try {
body.put("onderwerp", subject)
body.put("agenda", agenda)
body.put("notes", notes)
body.put("date", date)
if (meeting != null) {
Loader.postOrPatchData(this, Loader.MEETINGURL, body, meeting!!.id, object : PostCallback {
override fun onSuccess(response: JSONObject) {
finish()
}
override fun onError(error: VolleyError) {
disableLoadingAnimation()
}
})
} else {
Loader.postOrPatchData(this, Loader.MEETINGURL, body, -1, object : PostCallback {
override fun onSuccess(response: JSONObject) {
finish()
}
override fun onError(error: VolleyError) {
disableLoadingAnimation()
}
})
}
} catch (ignored: JSONException) {
}
}
}
fun showDatePickerDialog(v: View) {
DatePickerFragment().show(supportFragmentManager, "vergaderdatum")
}
override fun onDateSet(view: DatePicker, year: Int, month: Int, day: Int) {
val date = day.toString() + "-" + (month + 1) + "-" + year
if (supportFragmentManager.findFragmentByTag("vergaderdatum") != null) {
meeting_date_button?.text = date
}
}
}
| gpl-3.0 | 50bb54f99e5d1b4a5fdfbe02c9bff060 | 33.917526 | 111 | 0.580159 | 4.783898 | false | false | false | false |
afollestad/material-dialogs | datetime/src/main/java/com/afollestad/materialdialogs/datetime/utils/ViewExt.kt | 2 | 1841 | /**
* 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.
*/
@file:Suppress("DEPRECATION")
package com.afollestad.materialdialogs.datetime.utils
import android.os.Build
import android.widget.TimePicker
import androidx.viewpager.widget.ViewPager
import com.afollestad.date.DatePicker
import com.afollestad.materialdialogs.MaterialDialog
import com.afollestad.materialdialogs.datetime.R
import com.afollestad.viewpagerdots.DotsIndicator
internal fun TimePicker.hour(): Int = if (isNougat()) hour else currentHour
internal fun TimePicker.minute(): Int = if (isNougat()) minute else currentMinute
internal fun TimePicker.hour(value: Int) {
if (isNougat()) hour = value else currentHour = value
}
internal fun TimePicker.minute(value: Int) {
if (isNougat()) minute = value else currentMinute = value
}
internal fun MaterialDialog.getDatePicker() = findViewById<DatePicker>(R.id.datetimeDatePicker)
internal fun MaterialDialog.getTimePicker() = findViewById<TimePicker>(R.id.datetimeTimePicker)
internal fun MaterialDialog.getPager() = findViewById<ViewPager>(R.id.dateTimePickerPager)
internal fun MaterialDialog.getPageIndicator() =
findViewById<DotsIndicator?>(R.id.datetimePickerPagerDots)
private fun isNougat() = Build.VERSION.SDK_INT >= Build.VERSION_CODES.N
| apache-2.0 | 1b23917032ca37e1fd03de415abdea9a | 36.571429 | 95 | 0.783813 | 4.203196 | false | false | false | false |
udevbe/westmalle | compositor/src/main/kotlin/org/westford/nativ/libdrm/drmModePlaneRes.kt | 3 | 467 | package org.westford.nativ.libdrm
import org.freedesktop.jaccall.CType
import org.freedesktop.jaccall.Field
import org.freedesktop.jaccall.Struct
@Struct(value = *arrayOf(Field(name = "count_planes",
type = CType.UNSIGNED_INT),
Field(name = "planes",
type = CType.POINTER,
dataType = Int::class))) class drmModePlaneRes : Struct_drmModePlaneRes()
| agpl-3.0 | 4a96acc92f5ffbf4449def72533a1a8e | 41.454545 | 104 | 0.582441 | 4.67 | false | false | false | false |
fossasia/open-event-android | app/src/main/java/org/fossasia/openevent/general/ticket/TicketViewHolder.kt | 1 | 11437 | package org.fossasia.openevent.general.ticket
import android.graphics.Color
import android.graphics.Paint
import android.text.Editable
import android.text.Html
import android.text.TextWatcher
import android.view.View
import android.view.ViewGroup
import android.widget.AdapterView
import android.widget.ArrayAdapter
import android.widget.TextView
import androidx.core.view.isVisible
import androidx.recyclerview.widget.RecyclerView
import java.util.Date
import kotlin.collections.ArrayList
import kotlinx.android.synthetic.main.item_ticket.view.description
import kotlinx.android.synthetic.main.item_ticket.view.discountPrice
import kotlinx.android.synthetic.main.item_ticket.view.donationInput
import kotlinx.android.synthetic.main.item_ticket.view.moreInfoSection
import kotlinx.android.synthetic.main.item_ticket.view.order
import kotlinx.android.synthetic.main.item_ticket.view.orderQtySection
import kotlinx.android.synthetic.main.item_ticket.view.orderRange
import kotlinx.android.synthetic.main.item_ticket.view.price
import kotlinx.android.synthetic.main.item_ticket.view.priceInfo
import kotlinx.android.synthetic.main.item_ticket.view.priceSection
import kotlinx.android.synthetic.main.item_ticket.view.saleInfo
import kotlinx.android.synthetic.main.item_ticket.view.seeMoreInfoText
import kotlinx.android.synthetic.main.item_ticket.view.taxInfo
import kotlinx.android.synthetic.main.item_ticket.view.ticketDateText
import kotlinx.android.synthetic.main.item_ticket.view.ticketName
import org.fossasia.openevent.general.R
import org.fossasia.openevent.general.data.Resource
import org.fossasia.openevent.general.discount.DiscountCode
import org.fossasia.openevent.general.event.EventUtils
import org.fossasia.openevent.general.event.EventUtils.getFormattedDate
import org.fossasia.openevent.general.event.tax.Tax
import org.threeten.bp.DateTimeUtils
const val AMOUNT = "amount"
const val TICKET_TYPE_FREE = "free"
const val TICKET_TYPE_PAID = "paid"
const val TICKET_TYPE_DONATION = "donation"
class TicketViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
private val resource = Resource()
fun bind(
ticket: Ticket,
selectedListener: TicketSelectedListener?,
eventCurrency: String?,
eventTimeZone: String?,
ticketQuantity: Int,
donationAmount: Float,
discountCode: DiscountCode? = null,
tax: Tax?
) {
itemView.ticketName.text = ticket.name
setupTicketSaleDate(ticket, eventTimeZone)
setMoreInfoText()
itemView.seeMoreInfoText.setOnClickListener {
itemView.moreInfoSection.isVisible = !itemView.moreInfoSection.isVisible
setMoreInfoText()
}
var minQty = ticket.minOrder
var maxQty = ticket.maxOrder
if (discountCode?.minQuantity != null)
minQty = discountCode.minQuantity
if (discountCode?.maxQuantity != null)
maxQty = discountCode.maxQuantity
if (discountCode == null) {
minQty = ticket.minOrder
maxQty = ticket.maxOrder
itemView.discountPrice.visibility = View.GONE
itemView.price.paintFlags = 0
}
itemView.order.setOnClickListener {
itemView.orderRange.performClick()
}
var ticketPrice = ticket.price
if (tax?.rate != null) {
if (!tax.isTaxIncludedInPrice) {
val taxPrice = (ticketPrice * tax.rate / 100)
ticketPrice += taxPrice
itemView.taxInfo.text = "(+ $eventCurrency${"%.2f".format(taxPrice)} ${tax.name})"
} else {
val taxPrice = (ticket.price * tax.rate) / (100 + tax.rate)
itemView.taxInfo.text = "( $eventCurrency${"%.2f".format(taxPrice)} ${tax.name} included)"
}
}
when (ticket.type) {
TICKET_TYPE_DONATION -> {
itemView.price.text = resource.getString(R.string.donation)
itemView.priceSection.isVisible = false
itemView.donationInput.isVisible = true
if (donationAmount > 0F) itemView.donationInput.setText(donationAmount.toString())
setupDonationTicketPicker()
}
TICKET_TYPE_FREE -> {
itemView.price.text = resource.getString(R.string.free)
itemView.priceSection.isVisible = true
itemView.donationInput.isVisible = false
}
TICKET_TYPE_PAID -> {
itemView.price.text = "$eventCurrency${"%.2f".format(ticketPrice)}"
itemView.priceSection.isVisible = true
itemView.donationInput.isVisible = false
}
}
setupQtyPicker(minQty, maxQty, selectedListener, ticket, ticketQuantity, ticket.type)
val price = if (tax?.rate != null && tax.isTaxIncludedInPrice) (ticket.price * 100) / (100 + tax.rate)
else ticket.price
val priceDetail = if (price > 0) "$eventCurrency${"%.2f".format(price)}"
else resource.getString(R.string.free)
val priceInfo = "<b>${resource.getString(R.string.price)}:</b> $priceDetail"
itemView.priceInfo.text = Html.fromHtml(priceInfo)
if (ticket.description.isNullOrEmpty()) {
itemView.description.isVisible = false
} else {
itemView.description.isVisible = true
itemView.description.text = ticket.description
}
if (discountCode?.value != null && ticket.price != 0.toFloat()) {
itemView.discountPrice.visibility = View.VISIBLE
itemView.price.paintFlags = Paint.STRIKE_THRU_TEXT_FLAG
itemView.discountPrice.text =
if (discountCode.type == AMOUNT) "$eventCurrency${ticketPrice - discountCode.value}"
else "$eventCurrency${"%.2f".format(ticketPrice - (ticketPrice * discountCode.value / 100))}"
}
}
private fun setupDonationTicketPicker() {
itemView.donationInput.addTextChangedListener(object : TextWatcher {
override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) { /*Do Nothing*/ }
override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) { /*Do Nothing*/ }
override fun afterTextChanged(s: Editable?) {
val donationEntered = s.toString()
if (donationEntered.isNotBlank() && donationEntered.toFloat() > 0) {
if (itemView.orderRange.selectedItemPosition == 0)
itemView.orderRange.setSelection(1)
} else {
itemView.orderRange.setSelection(0)
}
}
})
}
private fun setupQtyPicker(
minQty: Int,
maxQty: Int,
selectedListener: TicketSelectedListener?,
ticket: Ticket,
ticketQuantity: Int,
ticketType: String?
) {
if (minQty > 0 && maxQty > 0) {
val spinnerList = ArrayList<String>()
spinnerList.add("0")
for (i in minQty..maxQty) {
spinnerList.add(i.toString())
}
itemView.orderRange.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
override fun onItemSelected(parent: AdapterView<*>, view: View, pos: Int, id: Long) {
val donationEntered = itemView.donationInput.text.toString()
val donation = if (donationEntered.isEmpty()) 0F else donationEntered.toFloat()
itemView.order.text = spinnerList[pos]
selectedListener?.onSelected(ticket.id, spinnerList[pos].toInt(), donation)
}
override fun onNothingSelected(parent: AdapterView<*>) {
}
}
val arrayAdapter = object : ArrayAdapter<String>(itemView.context,
android.R.layout.select_dialog_singlechoice, spinnerList) {
override fun isEnabled(position: Int): Boolean {
if (TICKET_TYPE_DONATION == ticketType) {
val donationEntered = itemView.donationInput.text.toString()
val donation = if (donationEntered.isEmpty()) 0F else donationEntered.toFloat()
return if (donation > 0F)
position != 0
else
position == 0
}
return super.isEnabled(position)
}
override fun getDropDownView(position: Int, convertView: View?, parent: ViewGroup): View {
val view = super.getDropDownView(position, convertView, parent)
if (TICKET_TYPE_DONATION == ticketType) {
if (view is TextView) {
val donationEntered = itemView.donationInput.text.toString()
val donation = if (donationEntered.isEmpty()) 0F else donationEntered.toFloat()
if (donation > 0F)
view.setTextColor(if (position == 0) Color.GRAY else Color.BLACK)
else
view.setTextColor(if (position == 0) Color.BLACK else Color.GRAY)
}
}
return view
}
}
itemView.orderRange.adapter = arrayAdapter
val currentQuantityPosition = spinnerList.indexOf(ticketQuantity.toString())
if (currentQuantityPosition != -1) {
itemView.orderRange.setSelection(currentQuantityPosition)
itemView.order.text = ticketQuantity.toString()
}
}
}
private fun setMoreInfoText() {
itemView.seeMoreInfoText.text = resource.getString(
if (itemView.moreInfoSection.isVisible) R.string.see_less else R.string.see_more)
}
private fun setupTicketSaleDate(ticket: Ticket, timeZone: String?) {
val startAt = ticket.salesStartsAt
val endAt = ticket.salesEndsAt
if (startAt != null && endAt != null && timeZone != null) {
val startsAt = EventUtils.getEventDateTime(startAt, timeZone)
val endsAt = EventUtils.getEventDateTime(endAt, timeZone)
val startDate = DateTimeUtils.toDate(startsAt.toInstant())
val endDate = DateTimeUtils.toDate(endsAt.toInstant())
val currentDate = Date()
if (currentDate < startDate) {
itemView.ticketDateText.isVisible = true
itemView.ticketDateText.text = resource.getString(R.string.not_open)
itemView.orderQtySection.isVisible = false
} else if (startDate < currentDate && currentDate < endDate) {
itemView.ticketDateText.isVisible = false
itemView.orderQtySection.isVisible = true
} else {
itemView.ticketDateText.text = resource.getString(R.string.ended)
itemView.ticketDateText.isVisible = true
itemView.orderQtySection.isVisible = false
}
val salesEnd = "<b>${resource.getString(R.string.sales_end)}</b> ${getFormattedDate(endsAt)}"
itemView.saleInfo.text = Html.fromHtml(salesEnd)
}
}
}
| apache-2.0 | 9d5a9c0877b4c0d41d65f100e121c95a | 44.205534 | 115 | 0.621667 | 4.825738 | false | false | false | false |
ekamp/KotlinWeather | app/src/main/java/weather/ekamp/com/weatherappkotlin/view/Splash.kt | 1 | 2151 | package weather.ekamp.com.weatherappkotlin.view
import android.app.Activity
import android.content.Intent
import android.content.pm.PackageManager
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import toothpick.Scope
import toothpick.Toothpick
import weather.ekamp.com.weatherappkotlin.R
import weather.ekamp.com.weatherappkotlin.model.location.LocationPermissionManager
import weather.ekamp.com.weatherappkotlin.presenter.SplashPresenter
import javax.inject.Inject
class Splash : AppCompatActivity(), SplashView {
val ERROR_DIALOG_TAG = "location_permission_error_dialog"
@Inject lateinit var presenter : SplashPresenter
lateinit var activityScope : Scope
lateinit var errorDialog : ErrorDialog
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
activityScope = Toothpick.openScopes(application, this)
Toothpick.inject(this, activityScope)
setContentView(R.layout.activity_splash)
presenter.onAttachView(this)
}
override fun getActivityReference(): Activity {
return this
}
override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
if (requestCode == LocationPermissionManager.PERMISSIONS_REQUEST_LOCATION) {
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
presenter.onLocationPermissionGranted()
} else {
presenter.onLocationPermissionDenied()
}
}
}
override fun startLanding() {
val activityIntent = Intent(this, Landing::class.java)
activityIntent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
startActivity(activityIntent)
}
override fun showLocationPermissionRationaleDialog() {
errorDialog = ErrorDialog.newInstance(getString(R.string.location_permission_rationale_message))
errorDialog.show(supportFragmentManager, ERROR_DIALOG_TAG)
}
override fun onDestroy() {
super.onDestroy()
if (errorDialog.isVisible) {
errorDialog.dismiss()
}
}
}
| apache-2.0 | 182e22765c639818e50e179bd502b0ee | 34.262295 | 119 | 0.72292 | 5.013986 | false | false | false | false |
WindSekirun/RichUtilsKt | demo/src/main/java/pyxis/uzuki/live/richutilskt/demo/set/BitmapSet.kt | 1 | 2282 | package pyxis.uzuki.live.richutilskt.demo.set
import android.content.Context
import pyxis.uzuki.live.richutilskt.demo.R
import pyxis.uzuki.live.richutilskt.demo.item.CategoryItem
import pyxis.uzuki.live.richutilskt.demo.item.ExecuteItem
import pyxis.uzuki.live.richutilskt.demo.item.generateExecuteItem
fun Context.getBitmapSet(): ArrayList<ExecuteItem> {
val list = arrayListOf<ExecuteItem>()
val getBitmap = generateExecuteItem(CategoryItem.BITMAP, "getBitmap",
getString(R.string.bitmap_message_getbitmap),
"realPath.getBitmap()",
"RichUtils.getBitmap(realPath)")
list.add(getBitmap)
val toRoundCorner = generateExecuteItem(CategoryItem.BITMAP, "toRoundCorner",
getString(R.string.bitmap_message_toroundcorner),
"bitmap.toRoundCorner(10f)",
"RichUtils.toRoundCorner(bitmap, 10f);")
list.add(toRoundCorner)
val saveBitmapToFile = generateExecuteItem(CategoryItem.BITMAP, "saveBitmapToFile",
getString(R.string.bitmap_message_savebitmaptofile),
"saveBitmapToFile(bitmap)",
"RichUtils.saveBitmapToFile(this, bitmap)")
list.add(saveBitmapToFile)
val drawableToBitmap = generateExecuteItem(CategoryItem.BITMAP, "drawableToBitmap",
getString(R.string.bitmap_message_drawabletobitmap),
"drawableToBitmap(drawable)",
"RichUtils.drawableToBitmap(drawable);")
list.add(drawableToBitmap)
val requestMediaScanner = generateExecuteItem(CategoryItem.BITMAP, "requestMediaScanner",
getString(R.string.bitmap_message_mediascanning),
"requestMediaScanner(realPath)",
"RichUtils.requestMediaScanner(this, realPath);")
list.add(requestMediaScanner)
val downloadBitmap = generateExecuteItem(CategoryItem.BITMAP, "downloadBitmap",
getString(R.string.bitmap_message_downloadbitmap),
"downloadBitmap(url)",
"RichUtils.downloadBitmap(url);")
list.add(downloadBitmap)
val resize = generateExecuteItem(CategoryItem.BITMAP, "resize",
getString(R.string.bitmap_message_resize),
"bitmap.resize(100, 100)",
"RichUtils.resize(bitmap, 100, 100)")
list.add(resize)
return list
} | apache-2.0 | 07221295b384629becc340239630f545 | 35.238095 | 93 | 0.70333 | 4.536779 | false | false | false | false |
WindSekirun/RichUtilsKt | RichUtils/src/main/java/pyxis/uzuki/live/richutilskt/module/image/OrientationFixer.kt | 1 | 1071 | package pyxis.uzuki.live.richutilskt.module.image
import android.content.Context
import android.graphics.BitmapFactory
import pyxis.uzuki.live.richutilskt.utils.*
import java.io.File
/**
* RichUtilsKt
* Class: OrientationFixer
* Created by pyxis on 18. 5. 14.
*
* Description:
*/
object OrientationFixer {
@JvmStatic
fun execute(path: String, context: Context) = execute(path.toFile(), context)
/**
* execute OrientationFixer to fix orientation with detection
*/
@JvmStatic
fun execute(file: File, context: Context): String {
val orientation = getPhotoOrientationDegree(file.absolutePath)
if (orientation == 0) {
return file.absolutePath
}
var bitmap = BitmapFactory.decodeFile(file.absolutePath)
bitmap = rotate(bitmap, orientation)
val newFile: File = context.saveBitmapToFile(bitmap) ?: file
context.requestMediaScanner(newFile.absolutePath)
if (!bitmap.isRecycled) {
bitmap.recycle()
}
return newFile.absolutePath
}
} | apache-2.0 | c5ea35aad58806bb7213e0a621080e2b | 25.8 | 81 | 0.676004 | 4.518987 | false | false | false | false |
Mithrandir21/Duopoints | app/src/main/java/com/duopoints/android/ui/views/RelationshipProfileView.kt | 1 | 3824 | package com.duopoints.android.ui.views
import android.content.Context
import android.os.CountDownTimer
import android.support.annotation.DrawableRes
import android.util.AttributeSet
import android.view.View
import android.widget.FrameLayout
import com.duopoints.android.R
import com.duopoints.android.fragments.relprofile.BreakupCountDownListener
import com.duopoints.android.rest.models.composites.CompositeRelationship
import kotlinx.android.synthetic.main.custom_view_relationship_profile_view.view.*
import org.joda.time.DateTime
class RelationshipProfileView @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0) :
FrameLayout(context, attrs, defStyleAttr), BreakupCountDownListener {
private var breakupTimeListener: BreakupTimeListener? = null
private var breakupCountDown: BreakupCountDown? = null
var breakupRequestExists = false
init {
View.inflate(context, R.layout.custom_view_relationship_profile_view, this)
}
fun setupProfile(compositeRelationship: CompositeRelationship, clickOne: View.OnClickListener, clickTwo: View.OnClickListener, breakupTimeListener: BreakupTimeListener? = null) {
this.breakupTimeListener = breakupTimeListener
relationshipProfileOne.setUserData(compositeRelationship.userOne)
relationshipProfileOne.setOnClickListener(clickOne)
relationshipProfileTwo.setUserData(compositeRelationship.userTwo)
relationshipProfileTwo.setOnClickListener(clickTwo)
relationshipProfileLabelsRP.setPoints(compositeRelationship.relationshipTotalPoints)
}
fun hideProfileActionBtn() {
relationshipProfileActionBtn.visibility = View.GONE
}
fun createBreakupCountDown(text: String?, breakupRequested: DateTime) {
breakupCountDown = BreakupCountDown(this, text, breakupRequested.minus(DateTime.now().millis).millis).start() as BreakupCountDown?
}
fun configProfileActionBtn(@DrawableRes backgroundResource: Int? = null, gone: Boolean? = null, onClickListener: OnClickListener? = null, text: String? = null) {
backgroundResource?.let { relationshipProfileActionBtn.setBackgroundResource(it) }
gone?.let { relationshipProfileActionBtn.visibility = if (it) View.GONE else View.VISIBLE }
relationshipProfileActionBtn.setOnClickListener(onClickListener) // Can be null
text?.let { relationshipProfileActionBtn.text = it }
}
fun cancelBreakupCountDown() {
breakupCountDown?.cancel()
}
fun onDestroy() {
breakupTimeListener = null
cancelBreakupCountDown()
}
/******************
* TIMER CALLBACKS
******************/
override fun tickElapsed(buttonText: String?, millisUntilFinished: Long) {
val second = millisUntilFinished / 1000 % 60
val minute = millisUntilFinished / (1000 * 60) % 60
val hour = millisUntilFinished / (1000 * 60 * 60)
val time = String.format("%d:%02d:%02d", hour, minute, second)
buttonText?.let {
relationshipProfileActionBtn.text = "$time - $it"
} ?: run {
relationshipProfileActionBtn.text = time
}
}
override fun timeElapsed() {
breakupTimeListener?.relationshipBreakupTimeElapsed()
breakupCountDown?.cancel()
}
class BreakupCountDown(private val listener: BreakupCountDownListener, private val buttonText: String?, millisUntilFinished: Long) : CountDownTimer(millisUntilFinished, 1000) {
override fun onTick(millisUntilFinished: Long) {
listener.tickElapsed(buttonText, millisUntilFinished)
}
override fun onFinish() {
listener.timeElapsed()
}
}
interface BreakupTimeListener {
fun relationshipBreakupTimeElapsed()
}
} | gpl-3.0 | c67d5fb76e75bafb7db9e3a14a6825de | 38.030612 | 182 | 0.724111 | 4.623942 | false | false | false | false |
sephiroth74/AndroidUIGestureRecognizer | uigesturerecognizer/src/main/java/it/sephiroth/android/library/uigestures/UIScreenEdgePanGestureRecognizer.kt | 1 | 14028 | package it.sephiroth.android.library.uigestures
import android.content.Context
import android.graphics.PointF
import android.os.Message
import android.util.Log
import android.view.MotionEvent
import android.view.VelocityTracker
import android.view.ViewConfiguration
/**
* UIPanGestureRecognizer is a subclass of UIGestureRecognizer that looks for panning (dragging) gestures. The user must
* be pressing one or more fingers on a view while they pan it. Clients implementing the action method for this gesture
* recognizer can ask it for the current translation and velocity of the gesture.
*
* @author alessandro crugnola
* @see [
* https://developer.apple.com/reference/uikit/uipangesturerecognizer](https://developer.apple.com/reference/uikit/uipangesturerecognizer)
*/
@Suppress("MemberVisibilityCanBePrivate")
open class UIScreenEdgePanGestureRecognizer(context: Context) : UIGestureRecognizer(context), UIContinuousRecognizer {
/**
* The minimum number of fingers that can be touching the view for this gesture to be recognized.
* The default value is 1
*
* @since 1.0.0
*/
var minimumNumberOfTouches: Int = 1
/**
* @ The maximum number of fingers that can be touching the view for this gesture to be recognized.
* @since 1.0.0
*/
var maximumNumberOfTouches: Int = Integer.MAX_VALUE
var scrollX: Float = 0.toFloat()
private set
var scrollY: Float = 0.toFloat()
private set
/**
* @since 1.0.0
*/
var translationX: Float = 0.toFloat()
private set
/**
* @since 1.0.0
*/
var translationY: Float = 0.toFloat()
private set
/**
* @since 1.0.0
*/
var yVelocity: Float = 0.toFloat()
private set
/**
* @since 1.0.0
*/
var xVelocity: Float = 0.toFloat()
private set
/**
* @return the relative scroll x between gestures
* @since 1.1.2
*/
val relativeScrollX: Float get() = -scrollX
/**
* @return the relative scroll y between gestures
* @since 1.0.0
*/
val relativeScrollY: Float get() = -scrollY
/**
* Screen sdge to be considered for this gesture to be recognized
* @since 1.0.0
*/
var edge = UIRectEdge.LEFT
/**
* Minimum finger movement before the touch can be considered a pan
* @since 1.2.5
*/
var scaledTouchSlop: Int
/**
* Edge limits (in pixels) after which the gesture will fail
* @since 1.2.7
*/
var edgeLimit: Float
private var mStarted: Boolean = false
private var mDown: Boolean = false
private var mVelocityTracker: VelocityTracker? = null
private var mLastFocusLocation = PointF()
private var mDownFocusLocation = PointF()
init {
val configuration = ViewConfiguration.get(context)
scaledTouchSlop = configuration.scaledTouchSlop
edgeLimit = context.resources.getDimension(R.dimen.gestures_screen_edge_limit)
}
override fun handleMessage(msg: Message) {
when (msg.what) {
MESSAGE_RESET -> handleReset()
else -> {
}
}
}
override fun reset() {
super.reset()
handleReset()
}
private fun handleReset() {
mStarted = false
mDown = false
setBeginFiringEvents(false)
state = State.Possible
}
override fun onStateChanged(recognizer: UIGestureRecognizer) {
if (recognizer.state === State.Failed && state === State.Began) {
stopListenForOtherStateChanges()
fireActionEventIfCanRecognizeSimultaneously()
} else if (recognizer.inState(State.Began, State.Ended) &&
mStarted && mDown && inState(State.Possible, State.Began)) {
stopListenForOtherStateChanges()
removeMessages()
state = State.Failed
setBeginFiringEvents(false)
mStarted = false
mDown = false
}
}
override fun onTouchEvent(event: MotionEvent): Boolean {
super.onTouchEvent(event)
if (!isEnabled) {
return false
}
val action = event.actionMasked
if (mVelocityTracker == null) {
mVelocityTracker = VelocityTracker.obtain()
}
val rawX = event.rawX
val rawY = event.rawY
when (action) {
MotionEvent.ACTION_POINTER_DOWN -> {
mLastFocusLocation.set(mCurrentLocation)
mDownFocusLocation.set(mCurrentLocation)
if (state == State.Possible) {
if (numberOfTouches > maximumNumberOfTouches) {
state = State.Failed
removeMessages(MESSAGE_RESET)
}
}
}
MotionEvent.ACTION_POINTER_UP -> {
mLastFocusLocation.set(mCurrentLocation)
mDownFocusLocation.set(mCurrentLocation)
mVelocityTracker!!.computeCurrentVelocity(1000, 0f)
val upIndex = event.actionIndex
val id1 = event.getPointerId(upIndex)
val x1 = mVelocityTracker!!.getXVelocity(id1)
val y1 = mVelocityTracker!!.getYVelocity(id1)
for (i in 0 until event.pointerCount) {
if (i == upIndex) {
continue
}
val id2 = event.getPointerId(i)
val x = x1 * mVelocityTracker!!.getXVelocity(id2)
val y = y1 * mVelocityTracker!!.getYVelocity(id2)
val dot = x + y
if (dot < 0) {
mVelocityTracker!!.clear()
break
}
}
if (state == State.Possible) {
if (numberOfTouches < minimumNumberOfTouches) {
state = State.Failed
removeMessages(MESSAGE_RESET)
}
}
}
MotionEvent.ACTION_DOWN -> {
if (delegate?.shouldReceiveTouch?.invoke(this)!!) {
mLastFocusLocation.set(mCurrentLocation)
mDownFocusLocation.set(mCurrentLocation)
mVelocityTracker!!.clear()
mVelocityTracker!!.addMovement(event)
mStarted = false
mDown = true
stopListenForOtherStateChanges()
removeMessages(MESSAGE_RESET)
state = if (!computeState(rawX, rawY)) {
logMessage(Log.WARN, "outside edge limits")
State.Failed
} else {
State.Possible
}
setBeginFiringEvents(false)
}
}
MotionEvent.ACTION_MOVE -> {
scrollX = mLastFocusLocation.x - mCurrentLocation.x
scrollY = mLastFocusLocation.y - mCurrentLocation.y
mVelocityTracker!!.addMovement(event)
if (mDown && state == State.Possible && !mStarted) {
val distance = mCurrentLocation.distance(mDownFocusLocation)
if (distance > scaledTouchSlop) {
mVelocityTracker!!.computeCurrentVelocity(1000, java.lang.Float.MAX_VALUE)
yVelocity = mVelocityTracker!!.yVelocity
xVelocity = mVelocityTracker!!.xVelocity
logMessage(Log.INFO, "velocity: $xVelocity, $yVelocity")
translationX -= scrollX
translationY -= scrollY
mLastFocusLocation.set(mCurrentLocation)
mStarted = true
if (numberOfTouches in minimumNumberOfTouches..maximumNumberOfTouches
&& delegate?.shouldBegin?.invoke(this)!!
&& getTouchDirection(mDownFocusLocation.x, mDownFocusLocation.y,
mCurrentLocation.x, mCurrentLocation.y, xVelocity, yVelocity) == edge) {
state = State.Began
if (null == requireFailureOf) {
fireActionEventIfCanRecognizeSimultaneously()
} else {
when {
requireFailureOf!!.state === State.Failed -> fireActionEventIfCanRecognizeSimultaneously()
requireFailureOf!!.inState(State.Began, State.Ended, State.Changed) ->
state = State.Failed
else -> {
listenForOtherStateChanges()
setBeginFiringEvents(false)
logMessage(Log.DEBUG, "waiting...")
}
}
}
} else {
state = State.Failed
}
}
} else if (inState(State.Began, State.Changed)) {
translationX -= scrollX
translationY -= scrollY
val pointerId = event.getPointerId(0)
mVelocityTracker!!.computeCurrentVelocity(1000, java.lang.Float.MAX_VALUE)
yVelocity = mVelocityTracker!!.getYVelocity(pointerId)
xVelocity = mVelocityTracker!!.getXVelocity(pointerId)
if (hasBeganFiringEvents()) {
state = State.Changed
fireActionEvent()
}
mLastFocusLocation.set(mCurrentLocation)
}
}
MotionEvent.ACTION_UP -> {
mDown = false
if (inState(State.Began, State.Changed)) {
if (state == State.Changed) {
scrollX = mLastFocusLocation.x - mCurrentLocation.x
scrollY = mLastFocusLocation.y - mCurrentLocation.y
translationX -= scrollX
translationY -= scrollY
}
val began = hasBeganFiringEvents()
state = State.Ended
if (began) {
fireActionEvent()
}
}
if (state == State.Possible || !mStarted) {
yVelocity = 0f
xVelocity = yVelocity
} else {
// TODO: verify this. it seems to send random values here
// VelocityTracker velocityTracker = mVelocityTracker;
// final int pointerId = ev.getPointerId(0);
// velocityTracker.computeCurrentVelocity(1000, mMaximumFlingVelocity);
// mVelocityY = velocityTracker.getYVelocity(pointerId);
// mVelocityX = velocityTracker.getXVelocity(pointerId);
}
if (mVelocityTracker != null) {
mVelocityTracker!!.recycle()
mVelocityTracker = null
}
mHandler.sendEmptyMessage(MESSAGE_RESET)
}
MotionEvent.ACTION_CANCEL -> {
removeMessages(MESSAGE_RESET)
state = State.Cancelled
setBeginFiringEvents(false)
mHandler.sendEmptyMessage(MESSAGE_RESET)
}
else -> {
}
}
return cancelsTouchesInView
}
private fun fireActionEventIfCanRecognizeSimultaneously() {
if (inState(State.Changed, State.Ended)) {
setBeginFiringEvents(true)
fireActionEvent()
} else {
if (delegate!!.shouldRecognizeSimultaneouslyWithGestureRecognizer(this)) {
setBeginFiringEvents(true)
fireActionEvent()
}
}
}
override fun hasBeganFiringEvents(): Boolean {
return super.hasBeganFiringEvents() && inState(State.Began, State.Changed)
}
override fun removeMessages() {
removeMessages(MESSAGE_RESET)
}
@Suppress("UNUSED_PARAMETER")
private fun getTouchDirection(
x1: Float, y1: Float, x2: Float, y2: Float, velocityX: Float, velocityY: Float): UIRectEdge {
val diffY = y2 - y1
val diffX = x2 - x1
if (Math.abs(diffX) > Math.abs(diffY)) {
if (Math.abs(diffX) > 0.toFloat()) {
return if (diffX > 0) {
UIRectEdge.LEFT
} else {
UIRectEdge.RIGHT
}
}
} else if (Math.abs(diffY) > 0.toFloat()) {
return if (diffY > 0) {
UIRectEdge.TOP
} else {
UIRectEdge.BOTTOM
}
}
return UIRectEdge.NONE
}
private fun computeState(x: Float, y: Float): Boolean {
val context = context ?: return false
if (edge == UIRectEdge.LEFT && x > edgeLimit) {
return false
} else if (edge == UIRectEdge.RIGHT) {
val w = context.resources.displayMetrics.widthPixels
return x >= w - edgeLimit
} else if (edge == UIRectEdge.TOP && y > edgeLimit) {
return false
} else if (edge == UIRectEdge.BOTTOM) {
val h = context.resources.displayMetrics.heightPixels
return y >= h - edgeLimit
} else if (edge == UIRectEdge.NONE) {
return false
}
return true
}
companion object {
private const val MESSAGE_RESET = 4
}
} | mit | fd7495f3a54cfc00b1b6e69264a3902a | 32.32304 | 138 | 0.520459 | 5.635998 | false | false | false | false |
FHannes/intellij-community | java/java-tests/testSrc/com/intellij/codeInsight/daemon/inlays/ToggleInlineHintsActionTest.kt | 3 | 2470 | /*
* 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.codeInsight.daemon.inlays
import com.intellij.codeInsight.hints.isPossibleHintNearOffset
import com.intellij.openapi.editor.ex.EditorSettingsExternalizable
import com.intellij.testFramework.fixtures.LightCodeInsightFixtureTestCase
import org.assertj.core.api.Assertions.assertThat
class ToggleInlineHintsActionTest : LightCodeInsightFixtureTestCase() {
private var before: Boolean = false
override fun setUp() {
super.setUp()
before = EditorSettingsExternalizable.getInstance().isShowParameterNameHints
EditorSettingsExternalizable.getInstance().isShowParameterNameHints = false
}
override fun tearDown() {
EditorSettingsExternalizable.getInstance().isShowParameterNameHints = before
super.tearDown()
}
fun `test is enabled near method with possible hints`() {
myFixture.configureByText("A.java", """"
class Test {
Test(int time) {}
void initialize(int loadTime) {}
static void s_test() {
Test test = new T<caret>est(<caret>10);
test.initial<caret>ize(100<caret>00);
}
}
""")
val file = myFixture.file
val caretModel = myFixture.editor.caretModel
assertThat(caretModel.caretCount).isEqualTo(4)
editor.caretModel.allCarets.forEach {
val hintCanBeAtCaret = isPossibleHintNearOffset(file, it.offset)
assertThat(hintCanBeAtCaret).isTrue()
}
}
fun `test is disabled in random places`() {
myFixture.configureByText("A.java", """"
class Test {
static void s_<caret>test() {
int a <caret>= 2;
Li<caret>st<String> list = null;
}
}
""")
val file = myFixture.file
val caretModel = myFixture.editor.caretModel
assertThat(caretModel.caretCount).isEqualTo(3)
editor.caretModel.allCarets.forEach {
val hintCanBeAtCaret = isPossibleHintNearOffset(file, it.offset)
assertThat(hintCanBeAtCaret).isFalse()
}
}
} | apache-2.0 | 19af436eff7f10eeb772d605dac7c47e | 29.134146 | 80 | 0.734818 | 4.356261 | false | true | false | false |
WonderBeat/suchmarines | src/main/kotlin/org/wow/evaluation/UserPowerEvaluator.kt | 1 | 1059 | package org.wow.evaluation
import org.wow.logger.GameTurn
/**
* Considers some different values with coefficients when evaluates player's power.
* Now it considers total player's units amount, player's planets amount and average (by palnets) regeneration rate.
* Considered values and coefficients may be changed
*/
public class UserPowerEvaluator : Evaluator {
private val unitsCoefficient = 0.2
private val planetsCoefficient = 0.8
override fun evaluate(playerName: String, world: GameTurn): Double {
var units: Double = 0.0
var planets: Double = 0.0
var maxPossibleUnits = world.planets.fold(0, { (acc, planet) -> acc + planet.getType()!!.getLimit() })
var maxPossiblePlanets = world.planets.size()
var playersPlanets = world.planets.filter { it.getOwner() == playerName }
playersPlanets.forEach {
units += it.getUnits()
planets++
}
return unitsCoefficient * units / maxPossibleUnits + planetsCoefficient * planets / maxPossiblePlanets
}
}
| mit | 800a3dac35be3c2c7219dee336eb320a | 36.821429 | 117 | 0.686497 | 4.236 | false | false | false | false |
alphafoobar/intellij-community | platform/configuration-store-impl/src/StateMap.kt | 6 | 5470 | /*
* Copyright 2000-2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.configurationStore
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.util.JDOMUtil
import com.intellij.openapi.util.io.BufferExposingByteArrayOutputStream
import com.intellij.openapi.util.text.StringUtil
import com.intellij.openapi.vfs.CharsetToolkit
import com.intellij.util.ArrayUtil
import com.intellij.util.SystemProperties
import gnu.trove.THashMap
import org.iq80.snappy.SnappyInputStream
import org.iq80.snappy.SnappyOutputStream
import org.jdom.Element
import org.jdom.output.Format
import java.io.ByteArrayInputStream
import java.io.OutputStreamWriter
import java.util.Arrays
import java.util.TreeMap
import java.util.concurrent.atomic.AtomicReferenceArray
class StateMap private constructor(private val names: Array<String>, private val states: AtomicReferenceArray<Any>) {
companion object {
private val LOG = Logger.getInstance(javaClass<StateMap>())
private val XML_FORMAT = Format.getRawFormat().setTextMode(Format.TextMode.TRIM).setOmitEncoding(true).setOmitDeclaration(true)
val EMPTY = StateMap(emptyArray(), AtomicReferenceArray(0))
public fun fromMap(map: Map<String, Any>): StateMap {
if (map.isEmpty()) {
return EMPTY
}
val names = map.keySet().toTypedArray()
if (map !is TreeMap) {
Arrays.sort(names)
}
val states = AtomicReferenceArray<Any>(names.size())
for (i in names.indices) {
states.set(i, map.get(names[i]))
}
return StateMap(names, states)
}
public fun stateToElement(key: String, state: Any?, newLiveStates: Map<String, Element>? = null): Element {
if (state is Element) {
return state.clone()
}
else {
return newLiveStates?.get(key) ?: unarchiveState(state as ByteArray)
}
}
public fun getNewByteIfDiffers(key: String, newState: Any, oldState: ByteArray): ByteArray? {
val newBytes = if (newState is Element) archiveState(newState) else newState as ByteArray
if (Arrays.equals(newBytes, oldState)) {
return null
}
else if (LOG.isDebugEnabled() && SystemProperties.getBooleanProperty("idea.log.changed.components", false)) {
fun stateToString(state: Any) = JDOMUtil.writeParent(state as? Element ?: unarchiveState(state as ByteArray), "\n")
val before = stateToString(oldState)
val after = stateToString(newState)
if (before == after) {
LOG.debug("Serialization error: serialized are different, but unserialized are equal")
}
else {
LOG.debug("$key ${StringUtil.repeat("=", 80 - key.length())}\nBefore:\n$before\nAfter:\n$after")
}
}
return newBytes
}
private fun archiveState(state: Element): ByteArray {
val byteOut = BufferExposingByteArrayOutputStream()
OutputStreamWriter(SnappyOutputStream(byteOut), CharsetToolkit.UTF8_CHARSET).use {
val xmlOutputter = JDOMUtil.MyXMLOutputter()
xmlOutputter.setFormat(XML_FORMAT)
xmlOutputter.output(state, it)
}
return ArrayUtil.realloc(byteOut.getInternalBuffer(), byteOut.size())
}
private fun unarchiveState(state: ByteArray) = JDOMUtil.load(SnappyInputStream(ByteArrayInputStream(state)))
}
public fun toMutableMap(): MutableMap<String, Any> {
val map = THashMap<String, Any>(names.size())
for (i in names.indices) {
map.put(names[i], states.get(i))
}
return map
}
/**
* Sorted by name.
*/
fun keys() = names
public fun get(key: String): Any? {
val index = Arrays.binarySearch(names, key)
return if (index < 0) null else states.get(index)
}
fun getElement(key: String, newLiveStates: Map<String, Element>) = stateToElement(key, get(key), newLiveStates)
fun isEmpty() = names.isEmpty()
fun getState(key: String) = get(key) as? Element
fun hasState(key: String) = get(key) is Element
public fun hasStates(): Boolean {
if (isEmpty()) {
return false
}
for (i in names.indices) {
if (states.get(i) is Element) {
return true
}
}
return false
}
public fun compare(key: String, newStates: StateMap, diffs: MutableSet<String>) {
val oldState = get(key)
val newState = newStates.get(key)
if (oldState is Element) {
if (!JDOMUtil.areElementsEqual(oldState as Element?, newState as Element?)) {
diffs.add(key)
}
}
else if (getNewByteIfDiffers(key, newState!!, oldState as ByteArray) != null) {
diffs.add(key)
}
}
public fun getStateAndArchive(key: String): Element? {
val index = Arrays.binarySearch(names, key)
if (index < 0) {
return null
}
val state = states.get(index) as? Element ?: return null
return if (states.compareAndSet(index, state, archiveState(state))) state else getStateAndArchive(key)
}
} | apache-2.0 | 3643d1841bde1e8d57f61f633ecf4c51 | 32.359756 | 131 | 0.689031 | 4.109692 | false | false | false | false |
sys1yagi/mastodon4j | mastodon4j/src/test/java/com/sys1yagi/mastodon4j/api/method/PublicTest.kt | 1 | 3820 | package com.sys1yagi.mastodon4j.api.method
import com.sys1yagi.mastodon4j.api.exception.Mastodon4jRequestException
import com.sys1yagi.mastodon4j.testtool.MockClient
import org.amshove.kluent.shouldEqualTo
import org.junit.Test
import java.util.concurrent.atomic.AtomicInteger
class PublicTest {
@Test
fun getInstance() {
val client = MockClient.mock("instance.json")
val publicMethod = Public(client)
val instance = publicMethod.getInstance().execute()
instance.uri shouldEqualTo "test.com"
instance.title shouldEqualTo "test.com"
instance.description shouldEqualTo "description"
instance.email shouldEqualTo "[email protected]"
instance.version shouldEqualTo "1.3.2"
}
@Test
fun getInstanceWithJson() {
val client = MockClient.mock("instance.json")
val publicMethod = Public(client)
publicMethod.getInstance()
.doOnJson {
it shouldEqualTo """{
"uri": "test.com",
"title": "test.com",
"description": "description",
"email": "[email protected]",
"version": "1.3.2"
}
"""
}
.execute()
}
@Test(expected = Mastodon4jRequestException::class)
fun getInstanceWithException() {
val client = MockClient.ioException()
val publicMethod = Public(client)
publicMethod.getInstance().execute()
}
@Test
fun getSearch() {
val client = MockClient.mock("search.json")
val publicMethod = Public(client)
val result = publicMethod.getSearch("test").execute()
result.statuses.size shouldEqualTo 0
result.accounts.size shouldEqualTo 6
result.hashtags.size shouldEqualTo 5
result.hashtags.size shouldEqualTo 5
}
@Test(expected = Mastodon4jRequestException::class)
fun getSearchWithException() {
val client = MockClient.ioException()
val publicMethod = Public(client)
publicMethod.getSearch("test").execute()
}
@Test
fun getLocalPublic() {
val client = MockClient.mock("public_timeline.json", maxId = 3L, sinceId = 1L)
val publicMethod = Public(client)
val statuses = publicMethod.getLocalPublic().execute()
statuses.part.size shouldEqualTo 20
statuses.link?.let {
it.nextPath shouldEqualTo "<https://mstdn.jp/api/v1/timelines/public?limit=20&local=true&max_id=3>"
it.maxId shouldEqualTo 3L
it.prevPath shouldEqualTo "<https://mstdn.jp/api/v1/timelines/public?limit=20&local=true&since_id=1>"
it.sinceId shouldEqualTo 1L
}
}
@Test
fun getLocalPublicWithJson() {
val atomicInt = AtomicInteger(0)
val client = MockClient.mock("public_timeline.json", maxId = 3L, sinceId = 1L)
val publicMethod = Public(client)
publicMethod.getLocalPublic()
.doOnJson {
atomicInt.incrementAndGet()
}
.execute()
atomicInt.get() shouldEqualTo 20
}
@Test(expected = Mastodon4jRequestException::class)
fun getLocalPublicWithException() {
val client = MockClient.ioException()
val publicMethod = Public(client)
publicMethod.getLocalPublic().execute()
}
@Test
fun getLocalTag() {
val client = MockClient.mock("tag.json", maxId = 3L, sinceId = 1L)
val publicMethod = Public(client)
val statuses = publicMethod.getLocalTag("mastodon").execute()
statuses.part.size shouldEqualTo 20
}
@Test(expected = Mastodon4jRequestException::class)
fun getLocalTagWithException() {
val client = MockClient.ioException()
val publicMethod = Public(client)
publicMethod.getLocalTag("mastodon").execute()
}
}
| mit | c5e92f76a42fbd68a2b949b259171b27 | 31.931034 | 113 | 0.642147 | 4.478312 | false | true | false | false |
cwoolner/flex-poker | src/main/kotlin/com/flexpoker/table/command/aggregate/eventproducers/AddRemovePlayerEventProducer.kt | 1 | 1443 | package com.flexpoker.table.command.aggregate.eventproducers
import com.flexpoker.table.command.aggregate.RandomNumberGenerator
import com.flexpoker.table.command.aggregate.TableState
import com.flexpoker.table.command.events.PlayerAddedEvent
import com.flexpoker.table.command.events.PlayerRemovedEvent
import com.flexpoker.table.command.events.TableEvent
import java.util.UUID
fun addPlayer(state: TableState, playerId: UUID, chips: Int, randomNumberGenerator: RandomNumberGenerator): List<TableEvent> {
require(!state.seatMap.values.contains(playerId)) { "player already at this table" }
val newPlayerPosition = findRandomOpenSeat(state, randomNumberGenerator)
return listOf(PlayerAddedEvent(state.aggregateId, state.gameId, playerId, chips, newPlayerPosition))
}
fun removePlayer(state: TableState, playerId: UUID): List<TableEvent> {
require(state.seatMap.values.contains(playerId)) { "player not at this table" }
require(state.currentHand == null) { "can't remove a player while in a hand" }
return listOf(PlayerRemovedEvent(state.aggregateId, state.gameId, playerId))
}
private fun findRandomOpenSeat(state: TableState, randomNumberGenerator: RandomNumberGenerator): Int {
while (true) {
val potentialNewPlayerPosition = randomNumberGenerator.int(state.seatMap.size)
if (state.seatMap[potentialNewPlayerPosition] == null) {
return potentialNewPlayerPosition
}
}
}
| gpl-2.0 | bcbc3303c229aafa6eba5ca450120595 | 48.758621 | 126 | 0.783091 | 4.231672 | false | false | false | false |
michaelgallacher/intellij-community | platform/script-debugger/backend/src/util.kt | 1 | 3692 | /*
* 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.debugger
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.util.io.FileUtil
import com.intellij.openapi.util.registry.Registry
import com.intellij.util.io.CharSequenceBackedByChars
import com.intellij.util.io.addChannelListener
import io.netty.buffer.ByteBuf
import io.netty.channel.Channel
import org.jetbrains.annotations.PropertyKey
import java.io.File
import java.io.FileOutputStream
import java.nio.CharBuffer
import java.text.SimpleDateFormat
import java.util.concurrent.ConcurrentLinkedQueue
internal class LogEntry(val message: Any, val marker: String) {
internal val time = System.currentTimeMillis()
}
class MessagingLogger internal constructor(private val queue: ConcurrentLinkedQueue<LogEntry>) {
internal @Volatile var closed = false
fun add(inMessage: CharSequence, marker: String = "IN") {
queue.add(LogEntry(inMessage, marker))
}
fun add(outMessage: ByteBuf, marker: String = "OUT") {
queue.add(LogEntry(outMessage.copy(), marker))
}
fun close() {
closed = true
}
fun closeOnChannelClose(channel: Channel) {
channel.closeFuture().addChannelListener {
try {
add("\"Closed\"", "Channel")
}
finally {
close()
}
}
}
}
fun createDebugLogger(@PropertyKey(resourceBundle = Registry.REGISTRY_BUNDLE) key: String, suffix: String = ""): MessagingLogger? {
var debugFile = Registry.stringValue(key)
if (debugFile.isNullOrEmpty()) {
return null
}
if (!suffix.isNullOrEmpty()) {
debugFile = debugFile.replace(".json", suffix + ".json")
}
val queue = ConcurrentLinkedQueue<LogEntry>()
val logger = MessagingLogger(queue)
ApplicationManager.getApplication().executeOnPooledThread {
val file = File(FileUtil.expandUserHome(debugFile))
val out = FileOutputStream(file)
val writer = out.writer()
writer.write("[\n")
writer.flush()
val fileChannel = out.channel
val dateFormatter = SimpleDateFormat("HH.mm.ss,SSS")
while (true) {
val entry = queue.poll() ?: if (logger.closed) {
break
}
else {
continue
}
writer.write("""{"timestamp": "${dateFormatter.format(entry.time)}", """)
val message = entry.message
when (message) {
is CharSequence -> {
writer.write("\"${entry.marker}\": ")
writer.flush()
if (message is CharSequenceBackedByChars) {
fileChannel.write(message.byteBuffer)
}
else {
fileChannel.write(Charsets.UTF_8.encode(CharBuffer.wrap(message)))
}
writer.write("},\n")
writer.flush()
}
is ByteBuf -> {
writer.write("\"${entry.marker}\": ")
writer.flush()
message.getBytes(message.readerIndex(), out, message.readableBytes())
message.release()
writer.write("},\n")
writer.flush()
}
else -> throw RuntimeException("Unknown message type")
}
}
writer.write("]")
out.close()
}
return logger
}
| apache-2.0 | 4662cf5461e9e7bf45bb2569ae1703d7 | 28.070866 | 131 | 0.668202 | 4.313084 | false | false | false | false |
nickthecoder/paratask | paratask-core/src/main/kotlin/uk/co/nickthecoder/paratask/parameters/fields/ChoiceField.kt | 1 | 3413 | /*
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.parameters.fields
import javafx.beans.property.SimpleObjectProperty
import javafx.scene.control.ComboBox
import javafx.util.StringConverter
import uk.co.nickthecoder.paratask.parameters.ChoiceParameter
import uk.co.nickthecoder.paratask.parameters.ParameterEvent
import uk.co.nickthecoder.paratask.parameters.ParameterEventType
// Note. JavaFX cannot handle null values in ComboBox correctly
// See : http://stackoverflow.com/questions/25877323/no-select-item-on-javafx-combobox
// So I've added a "special" value, and made the generic type "ANY?"
// and added a bodgeProperty, which forwards get/sets to the parameter's property
private val FAKE_NULL = "FAKE_NULL"
class ChoiceField<T>(val choiceParameter: ChoiceParameter<T>)
: ParameterField(choiceParameter) {
private var dirty = false
val comboBox = ComboBox<Any?>()
val converter = object : StringConverter<Any?>() {
override fun fromString(label: String): Any? {
return choiceParameter.getValueForLabel(label) ?: FAKE_NULL
}
override fun toString(obj: Any?): String {
@Suppress("UNCHECKED_CAST")
return choiceParameter.getLabelForValue(if (obj === FAKE_NULL) null else obj as T) ?: ""
}
}
val bodgeProperty = object : SimpleObjectProperty <Any?>(FAKE_NULL) {
override fun get(): Any? {
if (choiceParameter.value == null) {
return FAKE_NULL
} else {
return choiceParameter.value!!
}
}
override fun set(value: Any?) {
if (value == null || value === FAKE_NULL) {
choiceParameter.value = null
} else {
@Suppress("UNCHECKED_CAST")
choiceParameter.value = value as T?
}
}
}
override fun createControl(): ComboBox<*> {
comboBox.converter = converter
updateChoices()
comboBox.valueProperty().bindBidirectional(bodgeProperty)
return comboBox
}
private fun updateChoices() {
val pValue = choiceParameter.value
comboBox.items.clear()
choiceParameter.choices().map { it.value ?: FAKE_NULL }.forEach {
comboBox.items.add(it)
}
comboBox.value = pValue
}
override fun isDirty(): Boolean = dirty
override fun parameterChanged(event: ParameterEvent) {
super.parameterChanged(event)
if (event.type == ParameterEventType.STRUCTURAL) {
updateChoices()
} else if (event.type == ParameterEventType.VALUE) {
comboBox.value = choiceParameter.value
}
showOrClearError(choiceParameter.errorMessage())
}
}
| gpl-3.0 | 3160ff7e109e04946156ad7e9921f476 | 31.198113 | 100 | 0.667741 | 4.59973 | false | false | false | false |
nickthecoder/paratask | paratask-app/src/main/kotlin/uk/co/nickthecoder/paratask/AbstractTool.kt | 1 | 4659 | /*
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
import javafx.application.Platform
import javafx.beans.property.SimpleObjectProperty
import javafx.beans.property.SimpleStringProperty
import javafx.scene.image.Image
import uk.co.nickthecoder.paratask.gui.DropHelper
import uk.co.nickthecoder.paratask.options.OptionsRunner
import uk.co.nickthecoder.paratask.parameters.Parameter
import uk.co.nickthecoder.paratask.project.Results
import uk.co.nickthecoder.paratask.project.ThreadedToolRunner
import uk.co.nickthecoder.paratask.project.ToolPane
import uk.co.nickthecoder.paratask.project.ToolPane_Impl
import uk.co.nickthecoder.paratask.util.HasDirectory
import uk.co.nickthecoder.paratask.util.focusNext
import uk.co.nickthecoder.paratask.util.uncamel
abstract class AbstractTool : Tool {
override val taskRunner by lazy { ThreadedToolRunner(this) }
override var toolPane: ToolPane? = null
override val shortTitleProperty by lazy { SimpleStringProperty(defaultShortTitle()) }
override var shortTitle: String
get() = shortTitleProperty.get()
set(value) {
Platform.runLater { shortTitleProperty.set(value) }
}
override val longTitleProperty by lazy { SimpleStringProperty(defaultLongTitle()) }
override var longTitle: String
get() = longTitleProperty.get()
set(value) {
Platform.runLater { longTitleProperty.set(value) }
}
override val optionsName: String by lazy { taskD.name }
override val optionsRunner by lazy { OptionsRunner(this) }
override var resultsList: List<Results> = listOf()
override var resolver: ParameterResolver = CompoundParameterResolver()
override var tabDropHelper: DropHelper?
get() = tabDropHelperProperty.get()
set(v) {
tabDropHelperProperty.set(v)
}
override val tabDropHelperProperty = SimpleObjectProperty<DropHelper>()
protected fun defaultShortTitle() = taskD.name.uncamel()
protected fun defaultLongTitle() = taskD.name.uncamel()
override fun attached(toolPane: ToolPane) {
this.toolPane = toolPane
val r = resolver
if (r is CompoundParameterResolver) {
r.add(toolPane.halfTab.projectTab.projectTabs.projectWindow.project.resolver)
if (this is HasDirectory) {
r.add(HasDirectoryResolver(this))
}
}
}
override fun detaching() {
tabDropHelper?.cancel()
for (results in resultsList) {
results.detaching()
}
toolPane = null
resultsList = listOf<Results>()
}
override fun check() {
taskD.root.check()
customCheck()
}
fun ensureToolPane(): ToolPane {
return toolPane ?: ToolPane_Impl(this)
}
override fun customCheck() {}
override val icon: Image? by lazy {
ParaTask.imageResource("tools/${iconName()}.png")
}
open fun iconName(): String = taskD.name
override fun updateResults() {
val oldResults = resultsList
val newResults = createResults()
toolPane?.replaceResults(newResults, resultsList)
resultsList = newResults
for (results in oldResults) {
results.detaching()
}
}
protected fun singleResults(results: Results?): List<Results> {
if (results == null) {
return listOf()
} else {
return listOf(results)
}
}
fun focusOnParameter(parameter: Parameter) {
toolPane?.parametersTab?.isSelected = true
// Need to run later, otherwise the focus doesn't happen. Another JavaFX weirdness. Grr.
Platform.runLater {
val field = toolPane?.parametersPane?.taskForm?.form?.findField(parameter)
ParaTaskApp.logFocus("AbstractTool.focusOnParameter. field?.focusNext()")
field?.controlContainer?.focusNext()
}
}
override fun toString(): String {
return "Tool : $taskD"
}
}
| gpl-3.0 | 0e7830c7ff10fdec1d6182c929f51854 | 30.47973 | 96 | 0.687701 | 4.554252 | false | false | false | false |
aglne/mycollab | mycollab-services/src/main/java/com/mycollab/module/project/ProjectRolePermissionCollections.kt | 3 | 1620 | /**
* Copyright © MyCollab
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.mycollab.module.project
/**
* @author MyCollab Ltd.
* @since 1.0
*/
object ProjectRolePermissionCollections {
const val MESSAGES = "Message"
const val MILESTONES = "Milestone"
const val INVOICE = "Invoice"
const val TIME = "Time"
const val FINANCE = "Finance"
const val TASKS = "Task"
const val BUGS = "Bug"
const val VERSIONS = "Version"
const val COMPONENTS = "Component"
const val RISKS = "Risk"
const val SPIKE = "Spike"
const val USERS = "User"
const val ROLES = "Role"
const val FILES = "File"
const val PAGES = "Page"
const val PROJECT = "Project"
const val APPROVE_TIMESHEET = "Approve_Timesheet"
@JvmField
val PROJECT_PERMISSIONS = arrayOf(MESSAGES, MILESTONES, TASKS, BUGS, COMPONENTS, VERSIONS, FILES, PAGES, RISKS, TIME, INVOICE,
USERS, ROLES, PROJECT, FINANCE, APPROVE_TIMESHEET)
}
| agpl-3.0 | 61d11f3485dc347cace6ac00b25b04a1 | 25.112903 | 130 | 0.69055 | 3.910628 | false | false | false | false |
LarsKrogJensen/graphql-kotlin | src/main/kotlin/graphql/util/either.kt | 1 | 646 | package graphql.util
sealed class Either<out L, out R>
data class Left<out T>(val value: T) : Either<T, Nothing>()
data class Right<out T>(val value: T) : Either<Nothing, T>()
inline fun <L, R, T> Either<L, R>.fold(left: (L) -> T, right: (R) -> T): T =
when (this) {
is Left -> left(value)
is Right -> right(value)
}
inline fun <L, R, T> Either<L, R>.flatMap(f: (R) -> Either<L, T>): Either<L, T> =
fold({ this as Left }, f)
inline fun <L, R, T> Either<L, R>.map(f: (R) -> T): Either<L, T> =
flatMap { Right(f(it)) }
fun <L, R> eitherOf(left: L?, right: R?) = if (right != null) Right(right) else Left(left) | mit | f6558264136ea5c73ffc367e0f962dde | 31.35 | 90 | 0.569659 | 2.636735 | false | false | false | false |
olonho/carkot | proto/compiler/google/src/google/protobuf/compiler/kotlin/protoc-tests/kt_js_tests/src/tests/VarintsTest.kt | 1 | 1665 | package tests
import MessageVarints
import CodedInputStream
object VarintsTest {
fun generateKtVarint(): MessageVarints {
val int = Util.nextInt()
val long = Util.nextLong()
val sint = Util.nextInt()
val slong = Util.nextLong()
val bl = Util.nextBoolean()
val uint = Util.nextInt(0, Int.MAX_VALUE)
val ulong = Util.nextLong(0, Long.MAX_VALUE)
val enum = MessageVarints.TestEnum.firstVal
return MessageVarints.BuilderMessageVarints(
int, long, sint, slong, bl, enum, uint, ulong
).build()
}
fun compareVarints(kt1: MessageVarints, kt2: MessageVarints): Boolean {
return kt1.int == kt2.int &&
kt1.long.toString() == kt2.long.toString() &&
kt1.sint == kt2.sint &&
kt1.slong.toString() == kt2.slong.toString() &&
kt1.bl == kt2.bl &&
kt1.uint == kt2.uint &&
kt1.ulong.toString() == kt2.ulong.toString() &&
kt1.enumField.id == kt2.enumField.id
}
fun ktToKtOnce() {
val msg = generateKtVarint()
val outs = Util.getKtOutputStream(msg.getSizeNoTag())
msg.writeTo(outs)
val ins = CodedInputStream(outs.buffer)
val readMsg = MessageVarints.BuilderMessageVarints(0, 0L, 0, 0L, false, MessageVarints.TestEnum.firstVal, 0, 0L)
.parseFrom(ins).build()
Util.assert(readMsg.errorCode == 0)
Util.assert(compareVarints(msg, readMsg))
}
val testRuns = 1000
fun runTests() {
for (i in 0..testRuns) {
ktToKtOnce()
}
}
} | mit | 0c4037f1fd5a2c350fbe05d0f55b450f | 31.038462 | 120 | 0.572372 | 3.667401 | false | true | false | false |
DankBots/Mega-Gnar | src/main/kotlin/gg/octave/bot/commands/general/Help.kt | 1 | 4227 | package gg.octave.bot.commands.general
import gg.octave.bot.utils.extensions.config
import gg.octave.bot.utils.extensions.data
import me.devoxin.flight.api.CommandFunction
import me.devoxin.flight.api.Context
import me.devoxin.flight.api.annotations.Command
import me.devoxin.flight.api.entities.Cog
class Help : Cog {
private val categoryAlias = mapOf("Search" to "Music", "Dj" to "Music")
@Command
fun help(ctx: Context, command: String?) {
if (command == null) {
return sendCommands(ctx)
}
val cmd = ctx.commandClient.commands.findCommandByName(command)
?: ctx.commandClient.commands.findCommandByAlias(command)
if (cmd != null) {
return sendCommandHelp(ctx, cmd)
}
val category = ctx.commandClient.commands.values
.filter { categoryAlias.getOrDefault(it.category, it.category) == command }
.takeIf { it.isNotEmpty() }
?: return ctx.send("No categories found with that name. Category names are case-sensitive.")
sendCategoryCommands(ctx, category)
}
fun sendCommands(ctx: Context) {
val guildTrigger = ctx.data.command.prefix ?: ctx.config.prefix
val categories = ctx.commandClient.commands.values
.groupBy { categoryAlias[it.category] ?: it.category }
.filter { ctx.author.idLong in ctx.commandClient.ownerIds || it.key != "Admin" }
ctx.send {
setColor(0x9571D3)
setTitle("Bot Commands")
setDescription("The prefix of the bot on this server is `$guildTrigger`")
for ((key, commands) in categories) {
val fieldName = "$key — ${commands.size}"
val commandList = commands.joinToString("`, `", prefix = "`", postfix = "`") { it.name }
addField(fieldName, commandList, false)
}
setFooter("For more information try ${guildTrigger}help (command) " +
"or ${guildTrigger}help (category), ex: ${guildTrigger}help bassboost or ${guildTrigger}help play")
}
}
fun sendCommandHelp(ctx: Context, command: CommandFunction) {
val description = buildString {
appendln(command.properties.description)
appendln()
val triggerList = listOf(command.name, *command.properties.aliases)
appendln("**Triggers:** ${triggerList.joinToString(", ")}")
append("**Usage:** `${ctx.trigger}")
append(command.name)
if (command.arguments.isNotEmpty()) {
appendln(" ${command.arguments.joinToString(" ") { it.format(false) }}`")
} else {
appendln("`")
}
appendln()
appendln("**Subcommands:**")
if (command.subcommands.isNotEmpty()) {
val padEnd = command.subcommands.values.maxBy { it.name.length }?.name?.length ?: 15
for (sc in command.subcommands.values.toSet()) {
appendln("`${sc.name.padEnd(padEnd, ' ')}:` ${sc.properties.description}")
}
} else {
appendln("*None.*")
}
}
ctx.send {
setColor(0x9570D3)
setTitle("Help | ${command.name}")
setDescription(description)
}
}
fun sendCategoryCommands(ctx: Context, commands: List<CommandFunction>) {
val guildTrigger = ctx.data.command.prefix ?: ctx.config.prefix
val categoryName = categoryAlias.getOrDefault(commands[0].category, commands[0].category)
ctx.send {
setColor(0x9571D3)
setTitle("$categoryName Commands")
setDescription("The prefix of the bot on this server is `$guildTrigger`")
val fieldName = "$categoryName — ${commands.size}"
val commandList = commands.joinToString("`, `", prefix = "`", postfix = "`") { it.name }
addField(fieldName, commandList, false)
setFooter("For more information try ${guildTrigger}help (command) " +
"or ${guildTrigger}help (category), ex: ${guildTrigger}help bassboost or ${guildTrigger}help play")
}
}
}
| mit | 0f29c41b1a0a6416a51c16a2bbf58f28 | 40 | 115 | 0.591759 | 4.492553 | false | false | false | false |
BOINC/boinc | android/BOINC/app/src/main/java/edu/berkeley/boinc/rpc/WorkUnit.kt | 4 | 2708 | /*
* This file is part of BOINC.
* http://boinc.berkeley.edu
* Copyright (C) 2020 University of California
*
* BOINC is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License
* as published by the Free Software Foundation,
* either version 3 of the License, or (at your option) any later version.
*
* BOINC is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with BOINC. If not, see <http://www.gnu.org/licenses/>.
*/
package edu.berkeley.boinc.rpc
import android.os.Parcel
import android.os.Parcelable
data class WorkUnit(
var name: String = "",
var appName: String = "",
var versionNum: Int = 0,
var rscFloatingPointOpsEst: Double = 0.0,
var rscFloatingPointOpsBound: Double = 0.0,
var rscMemoryBound: Double = 0.0,
var rscDiskBound: Double = 0.0,
var project: Project? = null,
var app: App? = null
) : Parcelable {
private constructor(parcel: Parcel) :
this(parcel.readString() ?: "", parcel.readString() ?: "",
parcel.readInt(), parcel.readDouble(), parcel.readDouble(), parcel.readDouble(),
parcel.readDouble(), parcel.readValue(Project::class.java.classLoader) as Project?,
parcel.readValue(App::class.java.classLoader) as App?)
override fun describeContents() = 0
override fun writeToParcel(dest: Parcel, flags: Int) {
dest.writeString(name)
dest.writeString(appName)
dest.writeInt(versionNum)
dest.writeDouble(rscFloatingPointOpsEst)
dest.writeDouble(rscFloatingPointOpsBound)
dest.writeDouble(rscMemoryBound)
dest.writeDouble(rscDiskBound)
dest.writeValue(project)
dest.writeValue(app)
}
object Fields {
const val APP_NAME = "app_name"
const val VERSION_NUM = "version_num"
const val RSC_FPOPS_EST = "rsc_fpops_est"
const val RSC_FPOPS_BOUND = "rsc_fpops_bound"
const val RSC_MEMORY_BOUND = "rsc_memory_bound"
const val RSC_DISK_BOUND = "rsc_disk_bound"
}
companion object {
@JvmField
val CREATOR: Parcelable.Creator<WorkUnit> = object : Parcelable.Creator<WorkUnit> {
override fun createFromParcel(parcel: Parcel) = WorkUnit(parcel)
override fun newArray(size: Int) = arrayOfNulls<WorkUnit>(size)
}
}
}
| lgpl-3.0 | 6f641209d46b742e48645fbeb8f049d9 | 36.611111 | 103 | 0.658789 | 4.05997 | false | false | false | false |
DemonWav/IntelliJBukkitSupport | src/main/kotlin/translations/intentions/TranslationFileAnnotator.kt | 1 | 2875 | /*
* Minecraft Dev for IntelliJ
*
* https://minecraftdev.org
*
* Copyright (c) 2021 minecraft-dev
*
* MIT License
*/
package com.demonwav.mcdev.translations.intentions
import com.demonwav.mcdev.translations.Translation
import com.demonwav.mcdev.translations.TranslationFiles
import com.demonwav.mcdev.translations.index.TranslationIndex
import com.demonwav.mcdev.translations.lang.gen.psi.LangTypes
import com.demonwav.mcdev.util.mcDomain
import com.intellij.lang.annotation.AnnotationHolder
import com.intellij.lang.annotation.Annotator
import com.intellij.lang.annotation.HighlightSeverity
import com.intellij.psi.PsiElement
class TranslationFileAnnotator : Annotator {
override fun annotate(element: PsiElement, annotations: AnnotationHolder) {
val translation = TranslationFiles.toTranslation(element)
if (translation != null) {
checkEntryKey(element, translation, annotations)
checkEntryDuplicates(element, translation, annotations)
checkEntryMatchesDefault(element, translation, annotations)
}
if (element.node.elementType == LangTypes.DUMMY) {
annotations.newAnnotation(HighlightSeverity.ERROR, "Translations must not contain incomplete entries.")
.range(element)
.create()
}
}
private fun checkEntryKey(element: PsiElement, translation: Translation, annotations: AnnotationHolder) {
if (translation.key != translation.trimmedKey) {
annotations.newAnnotation(HighlightSeverity.WARNING, "Translation key contains whitespace at start or end.")
.range(element)
.newFix(TrimKeyIntention()).registerFix()
.create()
}
}
private fun checkEntryDuplicates(element: PsiElement, translation: Translation, annotations: AnnotationHolder) {
val count = TranslationIndex.getTranslations(element.containingFile).count { it.key == translation.key }
if (count > 1) {
annotations.newAnnotation(HighlightSeverity.WARNING, "Duplicate translation keys \"${translation.key}\".")
.newFix(RemoveDuplicatesIntention(translation)).registerFix()
.create()
}
}
private fun checkEntryMatchesDefault(element: PsiElement, translation: Translation, annotations: AnnotationHolder) {
val domain = element.containingFile?.virtualFile?.mcDomain
val defaultEntries = TranslationIndex.getAllDefaultEntries(element.project, domain)
if (defaultEntries.any { it.contains(translation.key) }) {
return
}
val warningText = "Translation key not included in default localization file."
annotations.newAnnotation(HighlightSeverity.WARNING, warningText)
.newFix(RemoveUnmatchedEntryIntention()).registerFix()
.create()
}
}
| mit | c3f1634d58c13a38605c4ca2ff631e0f | 41.910448 | 120 | 0.706435 | 5.017452 | false | false | false | false |
oboehm/jfachwert | src/main/kotlin/de/jfachwert/AbstractFachwert.kt | 1 | 3690 | /*
* Copyright (c) 2017-2020 by Oliver Boehm
*
* 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 orimplied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* (c)reated 14.03.2017 by oboehm ([email protected])
*/
package de.jfachwert
import com.fasterxml.jackson.databind.annotation.JsonSerialize
import com.fasterxml.jackson.databind.ser.std.ToStringSerializer
import de.jfachwert.pruefung.NullValidator
import java.io.Serializable
import java.util.*
import javax.validation.constraints.NotNull
/**
* Die meisten Fachwerte sind nur ein ganz duenner Wrapper um ein Attribut vom
* Typ 'String' (oder allgemein vom Typ 'T'). Fuer diese Fachwerte duerfte
* diese Implementierung ausreichen.
*
* @author oboehm
* @since 14.03.2017
* @since 0.0.2
*/
@JsonSerialize(using = ToStringSerializer::class)
abstract class AbstractFachwert<T : Serializable, S : AbstractFachwert<T, S>> protected constructor(code: T, validator: KSimpleValidator<T> = NullValidator()) : KFachwert, Comparable<S> {
/**
* Liefert die interne Praesentation fuer die abgeleiteten Klassen. Sie
* ist nicht fuer den direkten Aufruf vorgesehen, weswegen die Methode auch
* 'final' ist.
*
* @return die interne Repraesentation
*/
val code: T
init {
this.code = validator.verify(code)
}
override fun hashCode(): Int {
return code.hashCode()
}
/**
* Zwei Fachwerte sind nur dann gleich, wenn sie vom gleichen Typ sind und
* den gleichen Wert besitzen.
*
* @param other zu vergleichender Fachwert
* @return true bei Gleichheit
* @see java.lang.Object.equals
*/
override fun equals(other: Any?): Boolean {
if (other !is AbstractFachwert<*, *> || !this.javaClass.isAssignableFrom(other.javaClass)) {
return false
}
return code == other.code
}
/**
* Fuer die meisten Fachwerte reicht es, einfach den internen Code als
* String auszugeben.
*
* @return den internen code
*/
override fun toString(): String {
return Objects.toString(code)
}
/**
* Liefert die einzelnen Attribute eines Fachwertes als Map. Bei einem
* einzelnen Wert wird als Default-Implementierung der Klassenname und
* die toString()-Implementierung herangezogen.
*
* @return Attribute als Map
*/
override fun toMap(): Map<String, Any> {
val map: MutableMap<String, Any> = HashMap()
map[this.javaClass.simpleName.lowercase()] = toString()
return map
}
/**
* Dient zum Vergleich und Sortierung zweier Fachwerte.
*
* @param other der andere Fachwert
* @return negtive Zahl, falls this < other, 0 bei Gleichheit, ansonsten
* positive Zahl.
* @since 3.0
*/
override fun compareTo(@NotNull other: S): Int {
if (this == other) {
return 0
}
val otherCode = other.code
return if (otherCode is Comparable<*>) {
val thisValue = code as S
val otherValue = otherCode as S
thisValue.compareTo(otherValue)
} else {
throw UnsupportedOperationException("not implemented for " + this.javaClass)
}
}
} | apache-2.0 | bc6dcdba511e3672ba2fb3a2f34592ca | 30.818966 | 187 | 0.662602 | 3.827801 | false | false | false | false |
android/health-samples | health-services/ExerciseSample/app/src/main/java/com/example/exercise/HealthServicesManager.kt | 1 | 8609 | /*
* Copyright 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.exercise
import android.util.Log
import androidx.concurrent.futures.await
import androidx.health.services.client.ExerciseUpdateCallback
import androidx.health.services.client.HealthServicesClient
import androidx.health.services.client.data.*
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.channels.awaitClose
import kotlinx.coroutines.channels.trySendBlocking
import kotlinx.coroutines.flow.callbackFlow
import javax.inject.Inject
/**
* Entry point for [HealthServicesClient] APIs, wrapping them in coroutine-friendly APIs.
*/
class HealthServicesManager @Inject constructor(
healthServicesClient: HealthServicesClient,
coroutineScope: CoroutineScope
) {
private val exerciseClient = healthServicesClient.exerciseClient
private var exerciseCapabilities: ExerciseTypeCapabilities? = null
private var capabilitiesLoaded = false
suspend fun getExerciseCapabilities(): ExerciseTypeCapabilities? {
if (!capabilitiesLoaded) {
val capabilities = exerciseClient.getCapabilitiesAsync().await()
if (ExerciseType.RUNNING in capabilities.supportedExerciseTypes) {
exerciseCapabilities =
capabilities.getExerciseTypeCapabilities(ExerciseType.RUNNING)
}
capabilitiesLoaded = true
}
return exerciseCapabilities
}
suspend fun hasExerciseCapability(): Boolean {
return getExerciseCapabilities() != null
}
suspend fun isExerciseInProgress(): Boolean {
val exerciseInfo = exerciseClient.getCurrentExerciseInfoAsync().await()
return exerciseInfo.exerciseTrackedStatus == ExerciseTrackedStatus.OWNED_EXERCISE_IN_PROGRESS
}
suspend fun isTrackingExerciseInAnotherApp(): Boolean {
val exerciseInfo = exerciseClient.getCurrentExerciseInfoAsync().await()
return exerciseInfo.exerciseTrackedStatus == ExerciseTrackedStatus.OTHER_APP_IN_PROGRESS
}
/***
* Note: don't call this method from outside of foreground service (ie. [ExerciseService])
* when acquiring calories or distance.
*/
suspend fun startExercise() {
Log.d(TAG, "Starting exercise")
// Types for which we want to receive metrics. Only ask for ones that are supported.
val capabilities = getExerciseCapabilities() ?: return
val dataTypes = setOf(
DataType.HEART_RATE_BPM,
DataType.CALORIES_TOTAL,
DataType.DISTANCE
).intersect(capabilities.supportedDataTypes)
val exerciseGoals = mutableListOf<ExerciseGoal<Double>>()
if (supportsCalorieGoal(capabilities)) {
// Create a one-time goal.
exerciseGoals.add(
ExerciseGoal.createOneTimeGoal(
DataTypeCondition(
dataType = DataType.CALORIES_TOTAL,
threshold = CALORIES_THRESHOLD,
comparisonType = ComparisonType.GREATER_THAN_OR_EQUAL
)
)
)
}
if (supportsDistanceMilestone(capabilities)) {
// Create a milestone goal. To make a milestone for every kilometer, set the initial
// threshold to 1km and the period to 1km.
exerciseGoals.add(
ExerciseGoal.createMilestone(
condition = DataTypeCondition(
dataType = DataType.DISTANCE_TOTAL,
threshold = DISTANCE_THRESHOLD,
comparisonType = ComparisonType.GREATER_THAN_OR_EQUAL
),
period = DISTANCE_THRESHOLD
)
)
}
val config = ExerciseConfig(
exerciseType = ExerciseType.RUNNING,
dataTypes = dataTypes,
isAutoPauseAndResumeEnabled = false,
isGpsEnabled = true,
exerciseGoals = exerciseGoals
)
exerciseClient.startExerciseAsync(config).await()
}
private fun supportsCalorieGoal(capabilities: ExerciseTypeCapabilities): Boolean {
val supported = capabilities.supportedGoals[DataType.CALORIES_TOTAL]
return supported != null && ComparisonType.GREATER_THAN_OR_EQUAL in supported
}
private fun supportsDistanceMilestone(capabilities: ExerciseTypeCapabilities): Boolean {
val supported = capabilities.supportedMilestones[DataType.DISTANCE_TOTAL]
return supported != null && ComparisonType.GREATER_THAN_OR_EQUAL in supported
}
/***
* Note: don't call this method from outside of [ExerciseService]
* when acquiring calories or distance.
*/
suspend fun prepareExercise() {
Log.d(TAG, "Preparing an exercise")
// TODO Handle various exerciseTrackedStatus states, especially OWNED_EXERCISE_IN_PROGRESS
// and OTHER_APP_IN_PROGRESS
val warmUpConfig = WarmUpConfig(
ExerciseType.RUNNING,
setOf(
DataType.HEART_RATE_BPM,
DataType.LOCATION
)
)
try {
exerciseClient.prepareExerciseAsync(warmUpConfig).await()
} catch (e: Exception) {
Log.e(TAG, "Prepare exercise failed - ${e.message}")
}
}
suspend fun endExercise() {
Log.d(TAG, "Ending exercise")
exerciseClient.endExerciseAsync().await()
}
suspend fun pauseExercise() {
Log.d(TAG, "Pausing exercise")
exerciseClient.pauseExerciseAsync().await()
}
suspend fun resumeExercise() {
Log.d(TAG, "Resuming exercise")
exerciseClient.resumeExerciseAsync().await()
}
suspend fun markLap() {
if (isExerciseInProgress()) {
exerciseClient.markLapAsync().await()
}
}
/**
* A flow for [ExerciseUpdate]s.
*
* When the flow starts, it will register an [ExerciseUpdateCallback] and start to emit
* messages.
*
* [callbackFlow] is used to bridge between a callback-based API and Kotlin flows.
*/
@OptIn(ExperimentalCoroutinesApi::class)
val exerciseUpdateFlow = callbackFlow {
val callback = object : ExerciseUpdateCallback {
override fun onExerciseUpdateReceived(update: ExerciseUpdate) {
coroutineScope.runCatching {
trySendBlocking(ExerciseMessage.ExerciseUpdateMessage(update))
}
}
override fun onLapSummaryReceived(lapSummary: ExerciseLapSummary) {
coroutineScope.runCatching {
trySendBlocking(ExerciseMessage.LapSummaryMessage(lapSummary))
}
}
override fun onRegistered() {
}
override fun onRegistrationFailed(throwable: Throwable) {
TODO("Not yet implemented")
}
override fun onAvailabilityChanged(
dataType: DataType<*, *>,
availability: Availability
) {
if (availability is LocationAvailability) {
coroutineScope.runCatching {
trySendBlocking(ExerciseMessage.LocationAvailabilityMessage(availability))
}
}
}
}
exerciseClient.setUpdateCallback(callback)
awaitClose {
exerciseClient.clearUpdateCallbackAsync(callback)
}
}
private companion object {
const val CALORIES_THRESHOLD = 250.0
const val DISTANCE_THRESHOLD = 1_000.0 // meters
}
}
sealed class ExerciseMessage {
class ExerciseUpdateMessage(val exerciseUpdate: ExerciseUpdate) : ExerciseMessage()
class LapSummaryMessage(val lapSummary: ExerciseLapSummary) : ExerciseMessage()
class LocationAvailabilityMessage(val locationAvailability: LocationAvailability) :
ExerciseMessage()
}
| apache-2.0 | 7d19788a63186afbe786ca3a9a3bcc5a | 35.478814 | 101 | 0.646533 | 5.284837 | false | false | false | false |
ffc-nectec/FFC | ffc/src/main/kotlin/ffc/app/location/HouseActivity.kt | 1 | 7138 | /*
* Copyright (c) 2018 NECTEC
* National Electronics and Computer Technology Center, Thailand
*
* 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 ffc.app.location
import android.app.Activity
import android.arch.lifecycle.MutableLiveData
import android.arch.lifecycle.ViewModel
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.support.v7.widget.LinearLayoutManager
import android.transition.Slide
import android.view.Gravity
import android.view.Menu
import android.view.MenuItem
import android.widget.ImageView
import ffc.android.allowTransitionOverlap
import ffc.android.enter
import ffc.android.excludeSystemView
import ffc.android.exit
import ffc.android.load
import ffc.android.observe
import ffc.android.setTransition
import ffc.android.viewModel
import ffc.app.FamilyFolderActivity
import ffc.app.R
import ffc.app.dev
import ffc.app.person.PersonAdapter
import ffc.app.person.startPersonActivityOf
import ffc.app.photo.PhotoType
import ffc.app.photo.REQUEST_TAKE_PHOTO
import ffc.app.photo.startTakePhotoActivity
import ffc.app.photo.urls
import ffc.app.util.Analytics
import ffc.app.util.alert.handle
import ffc.app.util.alert.toast
import ffc.entity.Person
import ffc.entity.gson.toJson
import ffc.entity.place.House
import ffc.entity.update
import ffc.entity.util.URLs
import ffc.entity.util.generateTempId
import kotlinx.android.synthetic.main.activity_house.appbar
import kotlinx.android.synthetic.main.activity_house.collapsingToolbar
import kotlinx.android.synthetic.main.activity_house.emptyView
import kotlinx.android.synthetic.main.activity_house.recycleView
import kotlinx.android.synthetic.main.activity_house.toolbarImage
import org.jetbrains.anko.find
import org.jetbrains.anko.startActivity
class HouseActivity : FamilyFolderActivity() {
val houseId: String?
get() = intent.getStringExtra("houseId")
lateinit var viewModel: HouseViewModel
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_house)
setTransition {
enterTransition = Slide(Gravity.BOTTOM).enter().excludeSystemView()
exitTransition = Slide(Gravity.START).exit()
reenterTransition = Slide(Gravity.START).enter()
allowTransitionOverlap = false
}
dev {
if (houseId == null) intent.putExtra("houseId", generateTempId())
}
supportActionBar?.setDisplayHomeAsUpEnabled(true)
supportActionBar?.title = "บ้านเลขที่ ?"
viewModel = viewModel()
observe(viewModel.house) { house ->
if (house != null) {
bind(house)
house.resident(org!!.id) {
onFound { viewModel.resident.value = it }
onNotFound { viewModel.resident.value = null }
onFail { viewModel.exception.value = it }
}
Analytics.instance?.view(house)
} else {
emptyView.error(Error("ไม่พบข้อมูล")).show()
finish()
}
photoMenu?.isEnabled = house != null
locationMenu?.isEnabled = house != null
}
observe(viewModel.resident) {
if (!it.isNullOrEmpty()) {
(recycleView.adapter as PersonAdapter).update(it.sortedByDescending { it.age })
emptyView.content().show()
} else {
emptyView.empty().show()
}
}
observe(viewModel.exception) { t ->
t?.let {
handle(it)
emptyView.error(it).show()
}
}
emptyView.loading().show()
with(recycleView) {
layoutManager = LinearLayoutManager(context)
adapter = PersonAdapter(listOf()) {
onItemClick {
startPersonActivityOf(it, viewModel.house.value,
appbar to getString(R.string.transition_appbar),
find<ImageView>(R.id.personImageView) to getString(R.string.transition_person_profile)
)
}
}
}
}
fun bind(house: House) {
collapsingToolbar!!.title = "บ้านเลขที่ ${house.no}"
supportActionBar!!.title = "บ้านเลขที่ ${house.no}"
house.avatarUrl?.let { toolbarImage.load(Uri.parse(it)) }
}
override fun onResume() {
super.onResume()
housesOf(org!!).house(houseId!!) {
onFound { viewModel.house.value = it }
onNotFound { viewModel.house.value = null }
onFail { viewModel.exception.value = it }
}
}
var photoMenu: MenuItem? = null
var locationMenu: MenuItem? = null
override fun onCreateOptionsMenu(menu: Menu): Boolean {
menuInflater.inflate(R.menu.house_option, menu)
photoMenu = menu.findItem(R.id.photoMenu)
photoMenu!!.isEnabled = false
locationMenu = menu.findItem(R.id.locationMenu)
locationMenu!!.isEnabled = false
return super.onCreateOptionsMenu(menu)
}
override fun onOptionsItemSelected(item: MenuItem?): Boolean {
when (item?.itemId) {
R.id.photoMenu -> startTakePhotoActivity(PhotoType.PLACE, viewModel.house.value?.imagesUrl)
R.id.locationMenu -> startActivity<MarkLocationActivity>("house" to viewModel.house.value?.toJson())
}
return super.onOptionsItemSelected(item)
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
when (requestCode) {
REQUEST_TAKE_PHOTO -> {
if (resultCode == Activity.RESULT_OK) {
viewModel.house.value?.update {
imagesUrl = data!!.urls!!.mapTo(URLs()) { it }
}?.pushTo(org!!) {
onComplete {
toast("ปรับปรุงข้อมูลแล้ว")
viewModel.house.value = it
}
onFail { handle(it) }
}
}
}
}
}
class HouseViewModel : ViewModel() {
var house: MutableLiveData<House> = MutableLiveData()
var resident: MutableLiveData<List<Person>> = MutableLiveData()
var exception: MutableLiveData<Throwable> = MutableLiveData()
}
}
| apache-2.0 | 9341196a4988e2a28fd456ae54a2738d | 35 | 112 | 0.63604 | 4.38476 | false | false | false | false |
vondear/RxTools | RxUI/src/main/java/com/tamsiree/rxui/view/dialog/wheel/AbstractWheelTextAdapter.kt | 1 | 5558 | package com.tamsiree.rxui.view.dialog.wheel
import android.content.Context
import android.graphics.Typeface
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import com.tamsiree.rxkit.TLog.e
/**
* @author tamsiree
* @date 2018/6/11 11:36:40 整合修改
* Abstract wheel adapter provides common functionality for adapters.
*/
abstract class AbstractWheelTextAdapter protected constructor(
// Current context
protected var context: Context,
/**
* Sets resource Id for items views
* @param itemResourceId the resource Id to set
*/
// Items resources
var itemResource: Int = TEXT_VIEW_ITEM_RESOURCE,
/**
* Sets resource Id for text view in item layout
* @param itemTextResourceId the item text resource Id to set
*/
var itemTextResource: Int = NO_RESOURCE) : AbstractWheelAdapter() {
/**
* Gets text color
* @return the text color
*/
/**
* Sets text color
* @param textColor the text color to set
*/
// Text settings
var textColor = DEFAULT_TEXT_COLOR
/**
* Gets text size
* @return the text size
*/
/**
* Sets text size
* @param textSize the text size to set
*/
var textSize = DEFAULT_TEXT_SIZE
// Layout inflater
protected var inflater: LayoutInflater = context.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater
/**
* Gets resource Id for items views
* @return the item resource Id
*/
/**
* Gets resource Id for text view in item layout
* @return the item text resource Id
*/
/**
* Gets resource Id for empty items views
* @return the empty item resource Id
*/
/**
* Sets resource Id for empty items views
* @param emptyItemResourceId the empty item resource Id to set
*/
// Empty items resources
var emptyItemResource = 0
/**
* Returns text for specified item
* @param index the item index
* @return the text of specified items
*/
protected abstract fun getItemText(index: Int): CharSequence?
override fun getItem(index: Int, convertView: View?, parent: ViewGroup?): View? {
var convertView1 = convertView
if (index in 0 until itemsCount) {
if (convertView1 == null) {
convertView1 = getView(itemResource, parent)
}
val textView = getTextView(convertView1, itemTextResource)
if (textView != null) {
var text = getItemText(index)
if (text == null) {
text = ""
}
textView.text = text
if (itemResource == TEXT_VIEW_ITEM_RESOURCE) {
configureTextView(textView)
}
}
return convertView1
}
return null
}
override fun getEmptyItem(convertView: View?, parent: ViewGroup?): View? {
var convertView1 = convertView
if (convertView1 == null) {
convertView1 = getView(emptyItemResource, parent)
}
if (emptyItemResource == TEXT_VIEW_ITEM_RESOURCE && convertView1 is TextView) {
configureTextView(convertView1)
}
return convertView1
}
/**
* Configures text view. Is called for the TEXT_VIEW_ITEM_RESOURCE views.
* @param view the text view to be configured
*/
protected open fun configureTextView(view: TextView) {
view.setTextColor(textColor)
view.gravity = Gravity.CENTER
view.textSize = textSize.toFloat()
view.setLines(1)
view.setTypeface(Typeface.SANS_SERIF, Typeface.BOLD)
}
/**
* Loads a text view from view
* @param view the text view or layout containing it
* @param textResource the text resource Id in layout
* @return the loaded text view
*/
private fun getTextView(view: View?, textResource: Int): TextView? {
var text: TextView? = null
try {
if (textResource == NO_RESOURCE && view is TextView) {
text = view
} else if (textResource != NO_RESOURCE) {
text = view?.findViewById(textResource)
}
} catch (e: ClassCastException) {
e("AbstractWheelAdapter", "You must supply a resource ID for a TextView")
throw IllegalStateException(
"AbstractWheelAdapter requires the resource ID to be a TextView", e)
}
return text
}
/**
* Loads view from resources
* @param resource the resource Id
* @return the loaded view or null if resource is not set
*/
private fun getView(resource: Int, parent: ViewGroup?): View? {
return when (resource) {
NO_RESOURCE -> null
TEXT_VIEW_ITEM_RESOURCE -> TextView(context)
else -> inflater.inflate(resource, parent, false)
}
}
companion object {
/** Text view resource. Used as a default view for adapter. */
const val TEXT_VIEW_ITEM_RESOURCE = -1
/** No resource constant. */
protected const val NO_RESOURCE = 0
/** Default text color */
const val DEFAULT_TEXT_COLOR = -0xefeff0
/** Default text color */
const val LABEL_COLOR = -0x8fff90
/** Default text size */
const val DEFAULT_TEXT_SIZE = 24
}
} | apache-2.0 | 93d308f23bff19e1e67bff4645fad3c3 | 29.5 | 120 | 0.598378 | 4.739539 | false | false | false | false |
stripe/stripe-android | wechatpay/src/test/java/com/stripe/android/payments/wechatpay/PaymentIntentFixtures.kt | 1 | 6596 | package com.stripe.android.payments.wechatpay
import com.stripe.android.model.parsers.PaymentIntentJsonParser
import org.json.JSONObject
object PaymentIntentFixtures {
private val PARSER = PaymentIntentJsonParser()
private val PI_REQUIRES_BLIK_AUTHORIZE_JSON = JSONObject(
"""
{
"id": "pi_1IVmwXFY0qyl6XeWwxGWA04D",
"object": "payment_intent",
"amount": 1099,
"amount_capturable": 0,
"amount_received": 0,
"amount_subtotal": 1099,
"application": null,
"application_fee_amount": null,
"canceled_at": null,
"cancellation_reason": null,
"capture_method": "automatic",
"charges": {
"object": "list",
"data": [
],
"has_more": false,
"total_count": 0,
"url": "/v1/charges?payment_intent=pi_1IVmwXFY0qyl6XeWwxGWA04D"
},
"client_secret": "pi_1IVmwXFY0qyl6XeWwxGWA04D_secret_4U8cSCdPefr8LHtPsKvA3mcQz",
"confirmation_method": "automatic",
"created": 1615939737,
"currency": "pln",
"customer": null,
"description": null,
"invoice": null,
"last_payment_error": null,
"livemode": false,
"metadata": {
},
"next_action": {
"type": "blik_authorize"
},
"on_behalf_of": null,
"payment_method": "pm_1IVnI3FY0qyl6XeWxJFdBh2g",
"payment_method_options": {
"blik": {
}
},
"payment_method_types": [
"blik"
],
"receipt_email": null,
"review": null,
"setup_future_usage": null,
"shipping": null,
"source": null,
"statement_descriptor": null,
"statement_descriptor_suffix": null,
"status": "requires_action",
"total_details": {
"amount_discount": 0,
"amount_tax": 0
},
"transfer_data": null,
"transfer_group": null
}
""".trimIndent()
)
internal val PI_REQUIRES_BLIK_AUTHORIZE = PARSER.parse(PI_REQUIRES_BLIK_AUTHORIZE_JSON)!!
private val PI_REQUIRES_WECHAT_PAY_AUTHORIZE_JSON = JSONObject(
"""
{
"id": "pi_1IlJH7BNJ02ErVOjm37T3OUt",
"object": "payment_intent",
"amount": 1099,
"amount_capturable": 0,
"amount_received": 0,
"application": null,
"application_fee_amount": null,
"canceled_at": null,
"cancellation_reason": null,
"capture_method": "automatic",
"charges": {
"object": "list",
"data": [
],
"has_more": false,
"total_count": 0,
"url": "/v1/charges?payment_intent=pi_1IlJH7BNJ02ErVOjm37T3OUt"
},
"client_secret": "pi_1IlJH7BNJ02ErVOjm37T3OUt_secret_vgMExmjvESdtPqddHOSSSDip2",
"confirmation_method": "automatic",
"created": 1619638941,
"currency": "usd",
"customer": null,
"description": null,
"invoice": null,
"last_payment_error": null,
"livemode": false,
"metadata": {
},
"next_action": {
"type": "wechat_pay_redirect_to_android_app",
"wechat_pay_redirect_to_android_app": {
"app_id": "wx65997d6307c3827d",
"nonce_str": "some_random_string",
"package": "Sign=WXPay",
"partner_id": "wx65997d6307c3827d",
"prepay_id": "test_transaction",
"sign": "8B26124BABC816D7140034DDDC7D3B2F1036CCB2D910E52592687F6A44790D5E",
"timestamp": "1619638941"
}
},
"on_behalf_of": null,
"payment_method": "pm_1IlJH7BNJ02ErVOjxKQu1wfH",
"payment_method_options": {
"wechat_pay": {
}
},
"payment_method_types": [
"wechat_pay"
],
"receipt_email": null,
"review": null,
"setup_future_usage": null,
"shipping": null,
"source": null,
"statement_descriptor": null,
"statement_descriptor_suffix": null,
"status": "requires_action",
"transfer_data": null,
"transfer_group": null
}
""".trimIndent()
)
internal val PI_REQUIRES_WECHAT_PAY_AUTHORIZE =
PARSER.parse(PI_REQUIRES_WECHAT_PAY_AUTHORIZE_JSON)!!
private val PI_NO_NEXT_ACTION_DATA_JSON = JSONObject(
"""
{
"id": "pi_1IVmwXFY0qyl6XeWwxGWA04D",
"object": "payment_intent",
"amount": 1099,
"amount_capturable": 0,
"amount_received": 0,
"amount_subtotal": 1099,
"application": null,
"application_fee_amount": null,
"canceled_at": null,
"cancellation_reason": null,
"capture_method": "automatic",
"charges": {
"object": "list",
"data": [
],
"has_more": false,
"total_count": 0,
"url": "/v1/charges?payment_intent=pi_1IVmwXFY0qyl6XeWwxGWA04D"
},
"client_secret": "pi_1IVmwXFY0qyl6XeWwxGWA04D_secret_4U8cSCdPefr8LHtPsKvA3mcQz",
"confirmation_method": "automatic",
"created": 1615939737,
"currency": "pln",
"customer": null,
"description": null,
"invoice": null,
"last_payment_error": null,
"livemode": false,
"metadata": {
},
"next_action": {
},
"on_behalf_of": null,
"payment_method": "pm_1IVnI3FY0qyl6XeWxJFdBh2g",
"payment_method_options": {
"blik": {
}
},
"payment_method_types": [
"blik"
],
"receipt_email": null,
"review": null,
"setup_future_usage": null,
"shipping": null,
"source": null,
"statement_descriptor": null,
"statement_descriptor_suffix": null,
"status": "requires_action",
"total_details": {
"amount_discount": 0,
"amount_tax": 0
},
"transfer_data": null,
"transfer_group": null
}
""".trimIndent()
)
internal val PI_NO_NEXT_ACTION_DATA = PARSER.parse(PI_NO_NEXT_ACTION_DATA_JSON)!!
}
| mit | 2c3baf10cf01ddc53789b4ddf9e414a7 | 30.409524 | 93 | 0.495755 | 3.720248 | false | false | false | false |
codeka/wwmmo | common/src/main/kotlin/au/com/codeka/warworlds/common/Vector2.kt | 1 | 3141 | package au.com.codeka.warworlds.common
import java.util.*
import kotlin.math.*
/** Represents a 2-dimensional vector. */
class Vector2 {
var x: Double
var y: Double
constructor() {
y = 0.0
x = y
}
constructor(x: Double, y: Double) {
this.x = x
this.y = y
}
constructor(other: Vector2) {
x = other.x
y = other.y
}
fun reset(x: Double, y: Double): Vector2 {
this.x = x
this.y = y
return this
}
fun reset(other: Vector2): Vector2 {
x = other.x
y = other.y
return this
}
/**
* Gets the distance squared to the given other point. This is faster than [distanceTo] (since
* no sqrt() is required) and still good enough for many purposes.
*/
fun distanceTo2(other: Vector2): Double {
val dx = other.x - x
val dy = other.y - y
return dx * dx + dy * dy
}
fun distanceTo(other: Vector2?): Double {
val dx = other!!.x - x
val dy = other.y - y
return Math.sqrt(dx * dx + dy * dy)
}
fun distanceTo2(x: Double, y: Double): Double {
val dx = x - this.x
val dy = y - this.y
return dx * dx + dy * dy
}
fun distanceTo(x: Double, y: Double): Double {
val dx = x - this.x
val dy = y - this.y
return Math.sqrt(dx * dx + dy * dy)
}
fun length2(): Double {
return x * x + y * y
}
fun length(): Double {
return sqrt(length2())
}
fun add(other: Vector2) {
x += other.x
y += other.y
}
fun add(x: Float, y: Float) {
this.x += x.toDouble()
this.y += y.toDouble()
}
fun subtract(other: Vector2) {
x -= other.x
y -= other.y
}
fun subtract(x: Float, y: Float) {
this.x -= x.toDouble()
this.y -= y.toDouble()
}
fun rotate(radians: Double) {
val nx = x * cos(radians) - y * sin(radians)
val ny = y * cos(radians) + x * sin(radians)
x = nx
y = ny
}
fun normalize() {
scale(1.0 / length())
}
fun scale(s: Double) {
x *= s
y *= s
}
fun scale(sx: Double, sy: Double) {
x *= sx
y *= sy
}
override fun hashCode(): Int {
// this avoids the boxing that "new Double(x).hashCode()" would require
val lx = java.lang.Double.doubleToRawLongBits(x)
val ly = java.lang.Double.doubleToRawLongBits(y)
return (lx xor ly).toInt()
}
override fun toString(): String {
return String.format(Locale.ENGLISH, "(%.4f, %.4f)", x, y)
}
override fun equals(other: Any?): Boolean {
if (other !is Vector2) {
return false
}
val ov = other
return x == ov.x && y == ov.y
}
fun equals(other: Vector2?, epsilon: Double): Boolean {
return abs(other!!.x - x) < epsilon && abs(other.y - y) < epsilon
}
companion object {
/**
* Find the angle between "a" and "b"
* see: http://www.gamedev.net/topic/487576-angle-between-two-lines-clockwise/
*/
fun angleBetween(a: Vector2, b: Vector2): Float {
return atan2(a.x * b.y - a.y * b.x,
a.x * b.x + a.y * b.y).toFloat()
}
fun angleBetweenCcw(a: Vector2, b: Vector2): Float {
return atan2(a.x * b.x + a.y * b.y,
a.x * b.y - a.y * b.x).toFloat()
}
}
} | mit | f5d3e395810d6a3b65612a8dcc5ef9cb | 19.535948 | 96 | 0.557466 | 3.085462 | false | false | false | false |
MeilCli/Twitter4HK | library/src/main/kotlin/com/twitter/meil_mitu/twitter4hk/util/EntityUtils.kt | 1 | 17353 | package com.twitter.meil_mitu.twitter4hk.util
import android.graphics.Color
import android.text.Spannable
import android.text.SpannableStringBuilder
import android.text.Spanned
import android.text.style.ForegroundColorSpan
import android.text.style.URLSpan
import com.twitter.meil_mitu.twitter4hk.data.*
import java.util.*
object EntityUtils {
private val color = Color.parseColor("#DE1E88E5")
fun toLinkHtml(text: String, entities: Entities): SpannableStringBuilder {
return toLinkHtml(text, makeEntity(entities))
}
internal fun toLinkHtml(text: String, entities: Array<Entity>): SpannableStringBuilder {
val sb = SpannableStringBuilder()
var currentEntityIndex = 0
var index = 0
var semicolonIndex: Int
val size = text.length
var spanStart: Int
var escapedText: String
var spanText: String
var escapeChar: Char?
while (index < size) {
if (currentEntityIndex < entities.size) {
if (entities[currentEntityIndex].start == index) {
spanStart = sb.length
if (entities[currentEntityIndex].type == EntityType.URL) {
spanText = entities[currentEntityIndex].to
} else {
spanText = text[index] + entities[currentEntityIndex].to
}
sb.append(spanText)
sb.setSpan(URLSpan(spanText), spanStart, sb.length, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
sb.setSpan(ForegroundColorSpan(color), spanStart, sb.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
index += entities[currentEntityIndex].end - entities[currentEntityIndex].start
currentEntityIndex++
continue
}
}
if (text[index] == '&') {
semicolonIndex = text.indexOf(';', index)
if (semicolonIndex != -1) {
escapedText = text.substring(index, semicolonIndex + 1)
escapeChar = escapeMap[escapedText]
if (escapeChar != null) {
sb.append(escapeChar)
index += escapedText.length
continue
}
}
}
sb.append(text[index])
index++
}
return sb
}
fun toLinkURL(text: String, entities: Entities): String {
return toLinkURL(text, makeEntity2(entities))
}
internal fun toLinkURL(text: String, entities: Array<Entity>): String {
val sb = StringBuilder()
var currentEntityIndex = 0
var index = 0
var semicolonIndex: Int
val size = text.length
var escapedText: String
var escapeChar: Char?
while (index < size) {
if (currentEntityIndex < entities.size) {
if (entities[currentEntityIndex].start == index) {
if (entities[currentEntityIndex].type != EntityType.URL) {
currentEntityIndex++
continue
}
sb.append(entities[currentEntityIndex].to)
index += entities[currentEntityIndex].end - entities[currentEntityIndex].start
currentEntityIndex++
continue
}
}
if (text[index] == '&') {
semicolonIndex = text.indexOf(';', index)
if (semicolonIndex != -1) {
escapedText = text.substring(index, semicolonIndex + 1)
escapeChar = escapeMap[escapedText]
if (escapeChar != null) {
sb.append(escapeChar)
index += escapedText.length
continue
}
}
}
sb.append(text[index])
index++
}
return sb.toString()
}
private fun makeEntity(data: Entities): Array<Entity> {
val list = ArrayList<Entity>()
setEntity(list, data.URL)
setEntity(list, data.Media)
setEntity(list, data.UserMention)
setEntity(list, data.Hashtag)
setEntity(list, data.Symbol)
Collections.sort(list, comparator)
return list.toArray<Entity>(arrayOfNulls<Entity>(list.size))
}
private fun makeEntity2(data: Entities): Array<Entity> {
val list = ArrayList<Entity>()
setEntity2(list, data.URL)
setEntity2(list, data.Media)
return list.toArray<Entity>(arrayOfNulls<Entity>(list.size))
}
private fun setEntity(list: ArrayList<Entity>, data: Array<URLEntity>?) {
data?.forEach {
e ->
list.add(Entity(EntityType.URL, e.displayUrl, e.start, e.end))
}
}
private fun setEntity(list: ArrayList<Entity>, data: Array<MediaEntity>?) {
data?.forEach {
e ->
list.add(Entity(EntityType.URL, e.displayUrl, e.start, e.end))
}
}
private fun setEntity(list: ArrayList<Entity>, data: Array<UserMentionEntity>?) {
data?.forEach {
e ->
list.add(Entity(EntityType.ID, e.screenName, e.start, e.end))
}
}
private fun setEntity(list: ArrayList<Entity>, data: Array<HashtagEntity>?) {
data?.forEach {
e ->
list.add(Entity(EntityType.TAG, e.text, e.start, e.end))
}
}
private fun setEntity(list: ArrayList<Entity>, data: Array<SymbolEntity>?) {
data?.forEach {
e ->
list.add(Entity(EntityType.SYMBOL, e.text, e.start, e.end))
}
}
private fun setEntity2(list: ArrayList<Entity>, data: Array<URLEntity>?) {
data?.forEach {
e ->
list.add(Entity(EntityType.URL, e.expandedUrl, e.start, e.end))
}
}
private fun setEntity2(list: ArrayList<Entity>, data: Array<MediaEntity>?) {
data?.forEach {
e ->
list.add(Entity(EntityType.URL, e.expandedUrl, e.start, e.end))
}
}
private val comparator = EntityComparator()
private class EntityComparator : Comparator<Entity> {
override fun compare(s: Entity, t: Entity): Int {
return (s.start - t.start)
}
}
internal class Entity(internal val type: EntityType, internal val to: String, internal val start: Int, internal val end: Int)
internal enum class EntityType {
URL, ID, TAG, SYMBOL
}
private val escapeMap = HashMap<String, Char>()
init {
escapeMap.put(""", '\u0022')
escapeMap.put("&", '\u0026')
escapeMap.put("<", '\u003C')
escapeMap.put(">", '\u003E')
escapeMap.put(" ", '\u00A0')
escapeMap.put("¡", '\u00A1')
escapeMap.put("¢", '\u00A2')
escapeMap.put("£", '\u00A3')
escapeMap.put("¤", '\u00A4')
escapeMap.put("¥", '\u00A5')
escapeMap.put("¦", '\u00A6')
escapeMap.put("§", '\u00A7')
escapeMap.put("¨", '\u00A8')
escapeMap.put("©", '\u00A9')
escapeMap.put("ª", '\u00AA')
escapeMap.put("«", '\u00AB')
escapeMap.put("¬", '\u00AC')
escapeMap.put("­", '\u00AD')
escapeMap.put("®", '\u00AE')
escapeMap.put("¯", '\u00AF')
escapeMap.put("°", '\u00B0')
escapeMap.put("±", '\u00B1')
escapeMap.put("²", '\u00B2')
escapeMap.put("³", '\u00B3')
escapeMap.put("´", '\u00B4')
escapeMap.put("µ", '\u00B5')
escapeMap.put("¶", '\u00B6')
escapeMap.put("·", '\u00B7')
escapeMap.put("¸", '\u00B8')
escapeMap.put("¹", '\u00B9')
escapeMap.put("º", '\u00BA')
escapeMap.put("»", '\u00BB')
escapeMap.put("¼", '\u00BC')
escapeMap.put("½", '\u00BD')
escapeMap.put("¾", '\u00BE')
escapeMap.put("¿", '\u00BF')
escapeMap.put("À", '\u00C0')
escapeMap.put("Á", '\u00C1')
escapeMap.put("Â", '\u00C2')
escapeMap.put("Ã", '\u00C3')
escapeMap.put("Ä", '\u00C4')
escapeMap.put("Å", '\u00C5')
escapeMap.put("Æ", '\u00C6')
escapeMap.put("Ç", '\u00C7')
escapeMap.put("È", '\u00C8')
escapeMap.put("É", '\u00C9')
escapeMap.put("Ê", '\u00CA')
escapeMap.put("Ë", '\u00CB')
escapeMap.put("Ì", '\u00CC')
escapeMap.put("Í", '\u00CD')
escapeMap.put("Î", '\u00CE')
escapeMap.put("Ï", '\u00CF')
escapeMap.put("Ð", '\u00D0')
escapeMap.put("Ñ", '\u00D1')
escapeMap.put("Ò", '\u00D2')
escapeMap.put("Ó", '\u00D3')
escapeMap.put("Ô", '\u00D4')
escapeMap.put("Õ", '\u00D5')
escapeMap.put("Ö", '\u00D6')
escapeMap.put("×", '\u00D7')
escapeMap.put("Ø", '\u00D8')
escapeMap.put("Ù", '\u00D9')
escapeMap.put("Ú", '\u00DA')
escapeMap.put("Û", '\u00DB')
escapeMap.put("Ü", '\u00DC')
escapeMap.put("Ý", '\u00DD')
escapeMap.put("Þ", '\u00DE')
escapeMap.put("ß", '\u00DF')
escapeMap.put("à", '\u00E0')
escapeMap.put("á", '\u00E1')
escapeMap.put("â", '\u00E2')
escapeMap.put("ã", '\u00E3')
escapeMap.put("ä", '\u00E4')
escapeMap.put("å", '\u00E5')
escapeMap.put("æ", '\u00E6')
escapeMap.put("ç", '\u00E7')
escapeMap.put("è", '\u00E8')
escapeMap.put("é", '\u00E9')
escapeMap.put("ê", '\u00EA')
escapeMap.put("ë", '\u00EB')
escapeMap.put("ì", '\u00EC')
escapeMap.put("í", '\u00ED')
escapeMap.put("î", '\u00EE')
escapeMap.put("ï", '\u00EF')
escapeMap.put("ð", '\u00F0')
escapeMap.put("ñ", '\u00F1')
escapeMap.put("ò", '\u00F2')
escapeMap.put("ó", '\u00F3')
escapeMap.put("ô", '\u00F4')
escapeMap.put("õ", '\u00F5')
escapeMap.put("ö", '\u00F6')
escapeMap.put("÷", '\u00F7')
escapeMap.put("ø", '\u00F8')
escapeMap.put("ù", '\u00F9')
escapeMap.put("ú", '\u00FA')
escapeMap.put("û", '\u00FB')
escapeMap.put("ü", '\u00FC')
escapeMap.put("ý", '\u00FD')
escapeMap.put("þ", '\u00FE')
escapeMap.put("ÿ", '\u00FF')
escapeMap.put("Œ", '\u0152')
escapeMap.put("œ", '\u0153')
escapeMap.put("Š", '\u0160')
escapeMap.put("š", '\u0161')
escapeMap.put("Ÿ", '\u0178')
escapeMap.put("ƒ", '\u0192')
escapeMap.put("ˆ", '\u02C6')
escapeMap.put("˜", '\u02DC')
escapeMap.put("Α", '\u0391')
escapeMap.put("Β", '\u0392')
escapeMap.put("Γ", '\u0393')
escapeMap.put("Δ", '\u0394')
escapeMap.put("Ε", '\u0395')
escapeMap.put("Ζ", '\u0396')
escapeMap.put("Η", '\u0397')
escapeMap.put("Θ", '\u0398')
escapeMap.put("Ι", '\u0399')
escapeMap.put("Κ", '\u039A')
escapeMap.put("Λ", '\u039B')
escapeMap.put("Μ", '\u039C')
escapeMap.put("Ν", '\u039D')
escapeMap.put("Ξ", '\u039E')
escapeMap.put("Ο", '\u039F')
escapeMap.put("Π", '\u03A0')
escapeMap.put("Ρ", '\u03A1')
escapeMap.put("Σ", '\u03A3')
escapeMap.put("Τ", '\u03A4')
escapeMap.put("Υ", '\u03A5')
escapeMap.put("Φ", '\u03A6')
escapeMap.put("Χ", '\u03A7')
escapeMap.put("Ψ", '\u03A8')
escapeMap.put("Ω", '\u03A9')
escapeMap.put("α", '\u03B1')
escapeMap.put("β", '\u03B2')
escapeMap.put("γ", '\u03B3')
escapeMap.put("δ", '\u03B4')
escapeMap.put("ε", '\u03B5')
escapeMap.put("ζ", '\u03B6')
escapeMap.put("η", '\u03B7')
escapeMap.put("θ", '\u03B8')
escapeMap.put("ι", '\u03B9')
escapeMap.put("κ", '\u03BA')
escapeMap.put("λ", '\u03BB')
escapeMap.put("μ", '\u03BC')
escapeMap.put("ν", '\u03BD')
escapeMap.put("ξ", '\u03BE')
escapeMap.put("ο", '\u03BF')
escapeMap.put("π", '\u03C0')
escapeMap.put("ρ", '\u03C1')
escapeMap.put("ς", '\u03C2')
escapeMap.put("σ", '\u03C3')
escapeMap.put("τ", '\u03C4')
escapeMap.put("υ", '\u03C5')
escapeMap.put("φ", '\u03C6')
escapeMap.put("χ", '\u03C7')
escapeMap.put("ψ", '\u03C8')
escapeMap.put("ω", '\u03C9')
escapeMap.put("ϑ", '\u03D1')
escapeMap.put("ϒ", '\u03D2')
escapeMap.put("ϖ", '\u03D6')
escapeMap.put("•", '\u2022')
escapeMap.put("…", '\u2026')
escapeMap.put("′", '\u2032')
escapeMap.put("″", '\u2033')
escapeMap.put("‾", '\u203E')
escapeMap.put("⁄", '\u2044')
escapeMap.put("℘", '\u2118')
escapeMap.put("ℑ", '\u2111')
escapeMap.put("ℜ", '\u211C')
escapeMap.put("™", '\u2122')
escapeMap.put("ℵ", '\u2135')
escapeMap.put("←", '\u2190')
escapeMap.put("↑", '\u2191')
escapeMap.put("→", '\u2192')
escapeMap.put("↓", '\u2193')
escapeMap.put("↔", '\u2194')
escapeMap.put("↵", '\u21B5')
escapeMap.put("⇐", '\u21D0')
escapeMap.put("⇑", '\u21D1')
escapeMap.put("⇒", '\u21D2')
escapeMap.put("⇓", '\u21D3')
escapeMap.put("⇔", '\u21D4')
escapeMap.put("∀", '\u2200')
escapeMap.put("∂", '\u2202')
escapeMap.put("∃", '\u2203')
escapeMap.put("∅", '\u2205')
escapeMap.put("∇", '\u2207')
escapeMap.put("∈", '\u2208')
escapeMap.put("∉", '\u2209')
escapeMap.put("∋", '\u220B')
escapeMap.put("∏", '\u220F')
escapeMap.put("∑", '\u2211')
escapeMap.put("−", '\u2212')
escapeMap.put("∗", '\u2217')
escapeMap.put("√", '\u221A')
escapeMap.put("∝", '\u221D')
escapeMap.put("∞", '\u221E')
escapeMap.put("∠", '\u2220')
escapeMap.put("∧", '\u2227')
escapeMap.put("∨", '\u2228')
escapeMap.put("∩", '\u2229')
escapeMap.put("∪", '\u222A')
escapeMap.put("∫", '\u222B')
escapeMap.put("∴", '\u2234')
escapeMap.put("∼", '\u223C')
escapeMap.put("≅", '\u2245')
escapeMap.put("≈", '\u2248')
escapeMap.put("≠", '\u2260')
escapeMap.put("≡", '\u2261')
escapeMap.put("≤", '\u2264')
escapeMap.put("≥", '\u2265')
escapeMap.put("⊂", '\u2282')
escapeMap.put("⊃", '\u2283')
escapeMap.put("⊄", '\u2284')
escapeMap.put("⊆", '\u2286')
escapeMap.put("⊇", '\u2287')
escapeMap.put("⊕", '\u2295')
escapeMap.put("⊗", '\u2297')
escapeMap.put("⊥", '\u22A5')
escapeMap.put("⋅", '\u22C5')
escapeMap.put("⌈", '\u2308')
escapeMap.put("⌉", '\u2309')
escapeMap.put("⌊", '\u230A')
escapeMap.put("⌋", '\u230B')
escapeMap.put("⟨", '\u2329')
escapeMap.put("⟩", '\u232A')
escapeMap.put("◊", '\u25CA')
escapeMap.put("♠", '\u2660')
escapeMap.put("♣", '\u2663')
escapeMap.put("♥", '\u2665')
escapeMap.put("♦", '\u2666')
escapeMap.put(" ", '\u2002')
escapeMap.put(" ", '\u2003')
escapeMap.put(" ", '\u2009')
escapeMap.put("‌", '\u200C')
escapeMap.put("‍", '\u200D')
escapeMap.put("‎", '\u200E')
escapeMap.put("‏", '\u200F')
escapeMap.put("–", '\u2013')
escapeMap.put("—", '\u2014')
escapeMap.put("‘", '\u2018')
escapeMap.put("’", '\u2019')
escapeMap.put("‚", '\u201A')
escapeMap.put("“", '\u201C')
escapeMap.put("”", '\u201D')
escapeMap.put("„", '\u201E')
escapeMap.put("†", '\u2020')
escapeMap.put("‡", '\u2021')
escapeMap.put("‰", '\u2030')
escapeMap.put("‹", '\u2039')
}
}
| mit | 791910d23a869f656ab5dd3e3c415e96 | 37.995506 | 129 | 0.525039 | 3.497883 | false | false | false | false |
kiruto/debug-bottle | components/src/main/kotlin/com/exyui/android/debugbottle/components/injector/AllActivities.kt | 1 | 1012 | package com.exyui.android.debugbottle.components.injector
import android.app.Activity
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.pm.ActivityInfo
import android.content.pm.PackageInfo
import android.content.pm.PackageManager
import com.exyui.android.debugbottle.components.DTInstaller
import com.exyui.android.debugbottle.components.injector.__IntentInjectorImpl
/**
* Created by yuriel on 8/15/16.
*/
internal class AllActivities(activity: Activity): __IntentInjectorImpl() {
init {
setActivity(activity)
val mgr = activity.packageManager
val packageName = activity.application.packageName
val info: PackageInfo = mgr.getPackageInfo(packageName, PackageManager.GET_ACTIVITIES)
val list = info.activities
for (a in list) {
val intent = Intent()
intent.setClassName(a.packageName, a.name)
put(a.name.split(".").last(), intent)
}
}
} | apache-2.0 | f0412e107cbfac7aa23180850a1ad26b | 33.931034 | 94 | 0.730237 | 4.438596 | false | false | false | false |
HabitRPG/habitrpg-android | Habitica/src/main/java/com/habitrpg/android/habitica/models/inventory/QuestBossRage.kt | 2 | 481 | package com.habitrpg.android.habitica.models.inventory
import com.habitrpg.android.habitica.models.BaseObject
import io.realm.RealmObject
import io.realm.annotations.PrimaryKey
open class QuestBossRage : RealmObject(), BaseObject {
@PrimaryKey
var key: String? = null
var title: String? = null
var description: String? = null
var value: Double = 0.toDouble()
var tavern: String? = null
var stables: String? = null
var market: String? = null
}
| gpl-3.0 | 6df03546a16bd7d72479f8951433fd57 | 23.05 | 54 | 0.719335 | 3.975207 | false | false | false | false |
deva666/anko | anko/library/generator/src/org/jetbrains/android/anko/sources/sourceProviders.kt | 4 | 1626 | /*
* Copyright 2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.android.anko.sources
import com.github.javaparser.JavaParser
import com.github.javaparser.ast.CompilationUnit
import org.jetbrains.android.anko.utils.getPackageName
import java.io.File
interface SourceProvider {
fun parse(fqName: String): CompilationUnit?
}
class AndroidHomeSourceProvider(androidSdkLocation: File, version: Int) : SourceProvider {
private val baseDir = File(androidSdkLocation, "sources/android-$version")
init {
if (!baseDir.exists()) throw IllegalStateException("${baseDir.absolutePath} does not exist")
}
override fun parse(fqName: String): CompilationUnit? {
val packageName = getPackageName(fqName)
val packageDir = File(baseDir, packageName.replace('.', '/'))
if (!packageDir.exists()) return null
val filename = fqName.substring(packageName.length + 1).substringBefore('.') + ".java"
val file = File(packageDir, filename)
if (!file.exists()) return null
return JavaParser.parse(file)
}
} | apache-2.0 | 64b14e712c2decbf7b34a57d3e70aca9 | 34.369565 | 100 | 0.723247 | 4.382749 | false | false | false | false |
androidx/androidx | compose/integration-tests/material-catalog/src/main/java/androidx/compose/material/catalog/ui/specification/Specification.kt | 3 | 3242 | /*
* Copyright 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.compose.material.catalog.ui.specification
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.WindowInsets
import androidx.compose.foundation.layout.WindowInsetsSides
import androidx.compose.foundation.layout.add
import androidx.compose.foundation.layout.asPaddingValues
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.only
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.safeDrawing
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material.catalog.R
import androidx.compose.material.catalog.model.Specification
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.dp
@Composable
@OptIn(ExperimentalFoundationApi::class)
fun Specification(
specifications: List<Specification>,
onSpecificationClick: (specification: Specification) -> Unit
) {
SpecificationScaffold(
topBarTitle = stringResource(id = R.string.compose_material_catalog)
) { paddingValues ->
LazyColumn(
content = {
item {
Text(
text = stringResource(id = R.string.specifications),
style = MaterialTheme.typography.bodyLarge
)
Spacer(modifier = Modifier.height(SpecificationPadding))
}
items(specifications) { specification ->
SpecificationItem(
specification = specification,
onClick = onSpecificationClick
)
Spacer(modifier = Modifier.height(SpecificationItemPadding))
}
},
contentPadding = WindowInsets.safeDrawing
.only(WindowInsetsSides.Horizontal + WindowInsetsSides.Top)
.add(
WindowInsets(
left = SpecificationPadding,
top = SpecificationPadding,
right = SpecificationPadding,
)
)
.asPaddingValues(),
modifier = Modifier.padding(paddingValues)
)
}
}
private val SpecificationPadding = 16.dp
private val SpecificationItemPadding = 8.dp
| apache-2.0 | 210959c1aeb5b4014b9ed544ec2493b4 | 38.536585 | 80 | 0.679519 | 5.229032 | false | false | false | false |
bsmr-java/lwjgl3 | modules/templates/src/main/kotlin/org/lwjgl/vulkan/templates/AMD_shader_explicit_vertex_parameter.kt | 1 | 4353 | /*
* Copyright LWJGL. All rights reserved.
* License terms: https://www.lwjgl.org/license
*/
package org.lwjgl.vulkan.templates
import org.lwjgl.generator.*
import org.lwjgl.vulkan.*
val AMD_shader_explicit_vertex_parameter = "AMDShaderExplicitVertexParameter".nativeClassVK("AMD_shader_explicit_vertex_parameter", postfix = AMD) {
documentation =
"""
When the {@code VK_AMD_shader_explicit_vertex_parameter} device extension is enabled the application $can pass a SPIR-V module to
#CreateShaderModule() that uses the {@code SPV_AMD_shader_explicit_vertex_parameter} SPIR-V extension.
When the {@code VK_AMD_shader_explicit_vertex_parameter} device extension is enabled the {@code CustomInterpAMD} interpolation decoration $can also be
used with fragment shader inputs which indicate that the decorated inputs $can only be accessed by the extended instruction
{@code InterpolateAtVertexAMD} and allows accessing the value of the inputs for individual vertices of the primitive.
When the {@code VK_AMD_shader_explicit_vertex_parameter} device extension is enabled inputs $can be also decorated with the {@code CustomInterpAMD}
interpolation decoration, including fragment shader inputs that are signed or unsigned integers, integer vectors, or any double-precision
floating-point type. Inputs decorated with {@code CustomInterpAMD} $can only be accessed by the extended instruction {@code InterpolateAtVertexAMD} and
allows accessing the value of the input for individual vertices of the primitive.
The {@code BaryCoordNoPerspAMD} decoration $can be used to decorate a fragment shader input variable. This variable will contain the (I,J) pair of the
barycentric coordinates corresponding to the fragment evaluated using linear interpolation at the pixel's center. The K coordinate of the barycentric
coordinates $can be derived given the identity I + J + K = 1.0.
The {@code BaryCoordNoPerspCentroidAMD} decoration $can be used to decorate a fragment shader input variable. This variable will contain the (I,J) pair
of the barycentric coordinates corresponding to the fragment evaluated using linear interpolation at the centroid. The K coordinate of the barycentric
coordinates $can be derived given the identity I + J + K = 1.0.
The {@code BaryCoordNoPerspCentroidAMD} decoration $can be used to decorate a fragment shader input variable. This variable will contain the (I,J) pair
of the barycentric coordinates corresponding to the fragment evaluated using linear interpolation at each covered sample. The K coordinate of the
barycentric coordinates $can be derived given the identity I + J + K = 1.0.
The {@code BaryCoordPullModelAMD} decoration $can be used to decorate a fragment shader input variable. This variable will contain (1/W, 1/I, 1/J)
evaluated at the pixel center and $can be used to calculate gradients and then interpolate I, J, and W at any desired sample location.
The {@code BaryCoordSmoothAMD} decoration $can be used to decorate a fragment shader input variable. This variable will contain the (I,J) pair of the
barycentric coordinates corresponding to the fragment evaluated using perspective interpolation at the pixel's center. The K coordinate of the
barycentric coordinates $can be derived given the identity I + J + K = 1.0.
The {@code BaryCoordSmoothCentroidAMD} decoration $can be used to decorate a fragment shader input variable. This variable will contain the (I,J) pair
of the barycentric coordinates corresponding to the fragment evaluated using perspective interpolation at the centroid. The K coordinate of the
barycentric coordinates can: be derived given the identity I + J + K = 1.0.
The {@code BaryCoordSmoothCentroidAMD} decoration $can be used to decorate a fragment shader input variable. This variable will contain the (I,J) pair
of the barycentric coordinates corresponding to the fragment evaluated using perspective interpolation at each covered sample. The K coordinate of the
barycentric coordinates can: be derived given the identity I + J + K = 1.0.
"""
IntConstant(
"The extension specification version.",
"AMD_SHADER_EXPLICIT_VERTEX_PARAMETER_SPEC_VERSION".."1"
)
StringConstant(
"The extension name.",
"AMD_SHADER_EXPLICIT_VERTEX_PARAMETER_EXTENSION_NAME".."VK_AMD_shader_explicit_vertex_parameter"
)
} | bsd-3-clause | 01ce545cbccdfcd87beb17537faab385 | 67.03125 | 153 | 0.786354 | 4.246829 | false | false | false | false |
rosenpin/QuickDrawEverywhere | app/src/main/java/com/tomer/draw/gallery/GridSpacingItemDecoration.kt | 1 | 971 | package com.tomer.draw.gallery
import android.graphics.Rect
import android.support.v7.widget.RecyclerView
import android.view.View
/**
* DrawEverywhere
* Created by Tomer Rosenfeld on 7/29/17.
*/
class GridSpacingItemDecoration(private val spanCount: Int, private val spacing: Int, private val includeEdge: Boolean) : RecyclerView.ItemDecoration() {
override fun getItemOffsets(outRect: Rect, view: View, parent: RecyclerView, state: RecyclerView.State?) {
val position = parent.getChildAdapterPosition(view)
val column = position % spanCount
if (includeEdge) {
outRect.left = spacing - column * spacing / spanCount
outRect.right = (column + 1) * spacing / spanCount
if (position < spanCount) {
outRect.top = spacing
}
outRect.bottom = spacing
} else {
outRect.left = column * spacing / spanCount
outRect.right = spacing - (column + 1) * spacing / spanCount
if (position >= spanCount) {
outRect.top = spacing
}
}
}
}
| gpl-3.0 | 123b0ea8c09c9da7c34f803ea5902154 | 30.322581 | 153 | 0.715757 | 3.763566 | false | false | false | false |
pedpess/aurinkoapp | app/src/main/java/com/ppes/aurinkoapp/data/ForecastRequest.kt | 1 | 630 | package com.ppes.aurinkoapp.data
import com.google.gson.Gson
import java.net.URL
/**
* Created by ppes on 19/08/2017.
*/
class ForecastRequest(val zipCode: String) {
companion object {
private val APP_ID = "15646a06818f61f7b8d7823ca833e1ce"
private val URL = "http://api.openweathermap.org/data/2.5/forecast/daily?mode=json&units=metric&cnt=7"
private val COMPLETE_URL = "$URL&APPID=$APP_ID&q="
}
fun execute(): ForecastResult {
val forecastJsonString = URL(COMPLETE_URL + zipCode).readText()
return Gson().fromJson(forecastJsonString, ForecastResult::class.java)
}
} | apache-2.0 | cbbe5a76f1a793bb554b5abb991c5282 | 27.681818 | 110 | 0.690476 | 3.264249 | false | false | false | false |
adgvcxz/Diycode | app/src/main/java/com/adgvcxz/diycode/binding/RecyclerViewBinding.kt | 1 | 3404 | package com.adgvcxz.diycode.binding
import android.databinding.BindingAdapter
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import com.adgvcxz.diycode.binding.base.BaseViewModel
import com.adgvcxz.diycode.binding.base.LoadingViewModel
import com.adgvcxz.diycode.binding.recycler.BaseRecyclerViewAdapter
import com.adgvcxz.diycode.binding.recycler.LayoutManagerFactory
import com.adgvcxz.diycode.binding.recycler.OnLoadMoreListener
import com.adgvcxz.diycode.binding.recycler.OnRecyclerViewItemClickListener
import io.reactivex.Observable
import java.util.*
/**
* zhaowei
* Created by zhaowei on 2017/2/17.
*/
fun <T : BaseViewModel> RecyclerView.ensureAdapterNotNull() {
if (adapter == null) {
adapter = BaseRecyclerViewAdapter<T>()
}
}
@Suppress("UNCHECKED_CAST")
@BindingAdapter("items")
fun <T : BaseViewModel> RecyclerView.loadData(items: ArrayList<T>?) {
if (items != null) {
ensureAdapterNotNull<T>()
(adapter as BaseRecyclerViewAdapter<T>).setList(items)
}
}
@BindingAdapter("layoutManager")
fun RecyclerView.setLayoutManager(factory: LayoutManagerFactory?) {
if (this.layoutManager == null) {
post {
this.layoutManager = factory?.createLayoutManager(this)
}
}
}
@BindingAdapter("loadMore")
fun <T : BaseViewModel> RecyclerView.setLoadMore(loadMore: Boolean) {
ensureAdapterNotNull<T>()
Observable.just(adapter).ofType(BaseRecyclerViewAdapter::class.java)
.filter { it.loadMore != loadMore }
.subscribe {
it.loadMore = loadMore
}
}
@BindingAdapter("loadAll")
fun <T : BaseViewModel> RecyclerView.setLoadAll(loadAll: Boolean) {
ensureAdapterNotNull<T>()
Observable.just(adapter).ofType(BaseRecyclerViewAdapter::class.java)
.filter { it.loadAll != loadAll }
.subscribe {
it.loadAll = loadAll
}
}
@Suppress("UNCHECKED_CAST")
@BindingAdapter("loadMoreListener")
fun <T : BaseViewModel> RecyclerView.setLoadMoreListener(listener: OnLoadMoreListener?) {
ensureAdapterNotNull<T>()
if (listener != null) {
(adapter as BaseRecyclerViewAdapter<T>).loadMoreListener = listener
}
}
@BindingAdapter("loadingStatus")
fun <T : BaseViewModel> RecyclerView.setLoadSuccess(status: Int) {
ensureAdapterNotNull<T>()
Observable.just(adapter).ofType(BaseRecyclerViewAdapter::class.java)
.filter {
it.isNotEmpty() && it.loadingModel.status.get() != status
&& it.loadingModel.status.get() == LoadingViewModel.Loading
}
.subscribe { it.loadingModel.status.set(status) }
}
@BindingAdapter("firstTopMargin")
fun <T : BaseViewModel> RecyclerView.setTopMargin(margin: Int) {
ensureAdapterNotNull<T>()
Observable.just(adapter).ofType(BaseRecyclerViewAdapter::class.java)
.filter { it.firstTopMargin != margin }
.subscribe { it.firstTopMargin = margin }
}
@Suppress("UNCHECKED_CAST")
@BindingAdapter("onClickItemListener")
fun <T : BaseViewModel> RecyclerView.setOnClickItemListener(listener: OnRecyclerViewItemClickListener<T>) {
ensureAdapterNotNull<T>()
Observable.just(adapter).ofType(BaseRecyclerViewAdapter::class.java)
.subscribe { (it as BaseRecyclerViewAdapter<T>).onClickItemListener = listener }
} | apache-2.0 | 5d0fe1b57ee5aa1745eae309bdf656c3 | 33.393939 | 107 | 0.708872 | 4.461337 | false | false | false | false |
develar/mapsforge-tile-server | pixi/src/PixiPath.kt | 1 | 1158 | package org.develar.mapsforgeTileServer.pixi
import org.mapsforge.core.graphics.FillRule
import org.mapsforge.core.graphics.Path
class PixiPath() : Path {
val out = ByteArrayOutput()
public fun build():ByteArray = out.toByteArray()
private var lineToCount = 0
private var lineToCountOffset = -1
private var prevX:Float = 0.toFloat()
private var prevY:Float = 0.toFloat()
override fun clear() = out.reset()
override fun lineTo(x:Float, y:Float) {
if (lineToCount == 0) {
out.writeCommand(PixiCommand.POLYLINE)
lineToCountOffset = out.allocateShort()
prevX = 0f
prevY = 0f
}
lineToCount++
out.writeAsTwips(x - prevX)
out.writeAsTwips(y - prevY)
prevX = x
prevY = y
}
override fun moveTo(x:Float, y:Float) {
closePolyline()
out.moveToOrLineTo(PixiCommand.MOVE_TO, x, y)
}
fun closePolyline() {
if (lineToCount != 0) {
assert(lineToCountOffset > 0)
out.writeShort(lineToCount, lineToCountOffset)
lineToCount = 0
lineToCountOffset = -1
}
}
override fun setFillRule(fillRule:FillRule):Unit = throw UnsupportedOperationException()
} | mit | 6c15eadc7ebaeb4c6504f4f3b62c41d2 | 21.72549 | 90 | 0.677893 | 3.61875 | false | false | false | false |
wax911/AniTrendApp | app/src/main/java/com/mxt/anitrend/util/date/DateUtil.kt | 1 | 8455 | package com.mxt.anitrend.util.date
import androidx.annotation.IntRange
import com.annimon.stream.Collectors
import com.annimon.stream.IntStream
import com.mxt.anitrend.model.entity.anilist.meta.AiringSchedule
import com.mxt.anitrend.model.entity.anilist.meta.FuzzyDate
import com.mxt.anitrend.util.CompatUtil
import com.mxt.anitrend.util.KeyUtil
import org.ocpsoft.prettytime.PrettyTime
import java.text.ParseException
import java.text.SimpleDateFormat
import java.util.*
import java.util.concurrent.TimeUnit
/**
* Created by max on 2017/06/09.
* Class to provide any calendar functionality
*/
object DateUtil {
private val seasons by lazy {
arrayOf(
KeyUtil.WINTER,
KeyUtil.WINTER,
KeyUtil.SPRING,
KeyUtil.SPRING,
KeyUtil.SPRING,
KeyUtil.SUMMER,
KeyUtil.SUMMER,
KeyUtil.SUMMER,
KeyUtil.FALL,
KeyUtil.FALL,
KeyUtil.FALL,
KeyUtil.WINTER
)
}
private const val dateOutputFormat = "MMM dd, yyyy"
private const val dateInputFormat = "yyyy/MM/dd"
/**
* Gets current season title
* <br></br>
*
* @return Season name
*/
val currentSeason: String
@KeyUtil.MediaSeason get() {
val month = Calendar.getInstance().get(Calendar.MONTH)
return seasons[month]
}
/**
* Gets the current season title for menu
* <br></br>
*
* @return Season name
*/
val menuSelect: Int
@IntRange(from = 0, to = 4) get() {
val season = seasons[Calendar.getInstance().get(Calendar.MONTH)]
return CompatUtil.constructListFrom(*KeyUtil.MediaSeason)
.indexOf(season)
}
/**
* Returns the current month
*/
val month: Int
@IntRange(from = 0, to = 11) get() =
Calendar.getInstance().get(Calendar.MONTH)
/**
* Returns the current date
*/
val date: Int
@IntRange(from = 0, to = 31) get() =
Calendar.getInstance().get(Calendar.DATE)
/**
* Returns the current year
*/
val year: Int
get() = Calendar.getInstance().get(Calendar.YEAR)
/**
* Get the current fuzzy date
*/
val currentDate: FuzzyDate
get() = FuzzyDate(
date, month + 1,
year
)
fun getMediaSeason(fuzzyDate: FuzzyDate): String {
val format = SimpleDateFormat(dateInputFormat, Locale.getDefault())
try {
val converted = format.parse(fuzzyDate.toString())
val calendar = GregorianCalendar(Locale.getDefault())
if (converted != null)
calendar.time = converted
return String.format(Locale.getDefault(), "%s %d",
CompatUtil.capitalizeWords(
seasons[calendar.get(
Calendar.MONTH
)]
),
calendar.get(Calendar.YEAR))
} catch (e: ParseException) {
e.printStackTrace()
}
return fuzzyDate.toString()
}
/**
* Gets the current year + delta, if the season for the year is winter later in the year
* then the result would be the current year plus the delta
* <br></br>
*
* @return current year with a given delta
*/
fun getCurrentYear(delta: Int = 0): Int {
return if (month >= 11 && currentSeason == KeyUtil.WINTER)
year + delta
else year
}
/**
* Converts unix time representation into current readable time
* <br></br>
*
* @return A time format of [DateUtil.dateOutputFormat]
*/
fun convertDate(value: Long): String? {
try {
if (value != 0L)
return SimpleDateFormat(dateOutputFormat, Locale.getDefault()).format(Date(value * 1000L))
} catch (ex: Exception) {
ex.printStackTrace()
}
return null
}
/**
* Converts unix time representation into current readable time
* <br></br>
*
* @return A time format of [DateUtil.dateOutputFormat]
*/
fun convertDate(fuzzyDate: FuzzyDate?): String? {
try {
if (fuzzyDate != null && fuzzyDate.isValidDate) {
val simpleDateFormat = SimpleDateFormat(dateInputFormat, Locale.getDefault())
val converted = simpleDateFormat.parse(fuzzyDate.toString())
if (converted != null)
return SimpleDateFormat(dateOutputFormat, Locale.getDefault()).format(converted)
}
} catch (ex: Exception) {
ex.printStackTrace()
}
return "TBA"
}
/**
* Checks if the given data is newer than the current data on the device
*/
@Throws(ParseException::class)
private fun isNewerDate(fuzzyDate: FuzzyDate): Boolean {
val format = SimpleDateFormat(dateInputFormat, Locale.getDefault())
val converted = format.parse(fuzzyDate.toString())
return (converted?.time ?: 0) > System.currentTimeMillis()
}
/**
* Returns appropriate title for ends or ended
* <br></br>
* @param fuzzyDate - fuzzy date
*/
fun getEndTitle(fuzzyDate: FuzzyDate?): String {
if (fuzzyDate == null || !fuzzyDate.isValidDate)
return "Ends"
try {
return if (isNewerDate(fuzzyDate)) "Ends" else "Ended"
} catch (e: ParseException) {
e.printStackTrace()
}
return "Ends"
}
/**
* Returns appropriate title for starts or started
* <br></br>
* @param fuzzyDate - fuzzy date
*/
fun getStartTitle(fuzzyDate: FuzzyDate?): String {
if (fuzzyDate == null || !fuzzyDate.isValidDate)
return "Starts"
try {
return if (isNewerDate(fuzzyDate)) "Starts" else "Started"
} catch (e: ParseException) {
e.printStackTrace()
}
return "Starts"
}
/**
* Formats the epotch time to a pretty data
* <br></br>
* @return string such as "EP 6 AiringSchedule in 2 hours"
* @param airingSchedule - the current airingSchedule object of a series
*/
fun getNextEpDate(airingSchedule: AiringSchedule): String {
val prettyTime = PrettyTime(Locale.getDefault())
val fromNow = prettyTime.format(Date(
System.currentTimeMillis() + airingSchedule.timeUntilAiring * 1000L)
)
return String.format(Locale.getDefault(), "EP %d: %s", airingSchedule.episode, fromNow)
}
/**
* Unix time stamps dates
* <br></br>
* @param date - a unix timestamp
*/
fun getPrettyDateUnix(date: Long): String {
val prettyTime = PrettyTime(Locale.getDefault())
return prettyTime.format(Date(date * 1000L))
}
/**
* Creates a range of years from the given begin year to the end delta
* @param start Starting year
* @param endDelta End difference plus or minus the current year
*/
fun getYearRanges(start: Int, endDelta: Int): List<Int> {
return IntStream.rangeClosed(start,
getCurrentYear(endDelta)
)
.boxed().collect(Collectors.toList())
}
/**
* Checks if the time given has a difference greater than or equal to the target time
* <br></br>
* @param conversionTarget type of comparison between the epoch time and target
* @param epochTime time to compare against the current system clock
* @param target unit to compare against
*/
fun timeDifferenceSatisfied(@KeyUtil.TimeTargetType conversionTarget: Int, epochTime: Long, target: Int): Boolean {
val currentTime = System.currentTimeMillis()
val defaultSystemUnit = TimeUnit.MILLISECONDS
when (conversionTarget) {
KeyUtil.TIME_UNIT_DAYS ->
return defaultSystemUnit.toDays(currentTime - epochTime) >= target
KeyUtil.TIME_UNIT_HOURS ->
return defaultSystemUnit.toHours(currentTime - epochTime) >= target
KeyUtil.TIME_UNIT_MINUTES ->
return defaultSystemUnit.toMinutes(currentTime - epochTime) >= target
KeyUtil.TIME_UNITS_SECONDS ->
return defaultSystemUnit.toSeconds(currentTime - epochTime) >= target
}
return false
}
}
| lgpl-3.0 | 9a3d5fda75c897de95e0fe1ff3921d03 | 29.745455 | 119 | 0.592194 | 4.562871 | false | false | false | false |
TCA-Team/TumCampusApp | app/src/main/java/de/tum/in/tumcampusapp/component/ui/transportation/DepartureView.kt | 1 | 6046 | package de.tum.`in`.tumcampusapp.component.ui.transportation
import android.animation.ValueAnimator
import android.content.Context
import android.content.res.ColorStateList
import android.graphics.Color
import android.os.Handler
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.animation.AccelerateInterpolator
import android.view.animation.AnimationUtils
import android.widget.LinearLayout
import android.widget.TextSwitcher
import android.widget.TextView
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleObserver
import androidx.lifecycle.OnLifecycleEvent
import de.tum.`in`.tumcampusapp.R
import de.tum.`in`.tumcampusapp.utils.Utils
import org.joda.time.DateTime
import org.joda.time.Seconds
import java.util.*
/**
* Custom view that shows a departure.
* Holds an icon of the subway public transfer line, the line name and an animated
* automatically down counting departure time
*/
class DepartureView
@JvmOverloads constructor(context: Context, private val useCompactView: Boolean = true) : LinearLayout(context), LifecycleObserver {
private val symbolView: TextView by lazy { findViewById<TextView>(R.id.line_symbol) }
private val lineView: TextView by lazy { findViewById<TextView>(R.id.nameTextView) }
private val timeSwitcher: TextSwitcher by lazy { findViewById<TextSwitcher>(R.id.line_switcher) }
private val countdownHandler: Handler
private var valueAnimator: ValueAnimator? = null
private var departureTime: DateTime? = null
val symbol: String
get() = symbolView.text.toString()
init {
orientation = HORIZONTAL
gravity = Gravity.CENTER_VERTICAL
val inflater = LayoutInflater.from(context)
if (useCompactView) {
inflater.inflate(R.layout.departure_line_small, this, true)
} else {
inflater.inflate(R.layout.departure_line_big, this, true)
}
timeSwitcher.inAnimation = AnimationUtils.loadAnimation(getContext(), android.R.anim.slide_in_left)
timeSwitcher.outAnimation = AnimationUtils.loadAnimation(getContext(), android.R.anim.slide_out_right)
countdownHandler = Handler()
}
/**
* Sets the line symbol name
*
* @param symbol Symbol e.g. U6, S1, T14
*/
fun setSymbol(symbol: String, highlight: Boolean) {
val mvvSymbol = MVVSymbol(symbol, context)
symbolView.setTextColor(mvvSymbol.textColor)
symbolView.text = symbol
symbolView.backgroundTintList = ColorStateList.valueOf(mvvSymbol.backgroundColor)
if (highlight) {
if (useCompactView) {
setBackgroundColor(mvvSymbol.getHighlight())
} else {
setBackgroundColor(mvvSymbol.backgroundColor)
lineView.setTextColor(Color.WHITE)
for (index in 0 until timeSwitcher.childCount) {
val tw = timeSwitcher.getChildAt(index) as TextView
tw.setTextColor(Color.WHITE)
}
}
} else {
setBackgroundColor(mvvSymbol.textColor)
lineView.setTextColor(Color.BLACK)
for (index in 0 until timeSwitcher.childCount) {
val tw = timeSwitcher.getChildAt(index) as TextView
tw.setTextColor(Color.GRAY)
}
}
}
/**
* Sets the line name
*
* @param line Line name e.g. Klinikum Großhadern
*/
fun setLine(line: CharSequence) {
lineView.text = line
}
/**
* Sets the departure time
*
* @param departureTime Timestamp in milliseconds, when transport leaves
*/
fun setTime(departureTime: DateTime) {
this.departureTime = departureTime
updateDepartureTime()
}
private fun updateDepartureTime() {
val departureOffset = Seconds.secondsBetween(DateTime.now(), departureTime ?: DateTime.now()).seconds
if (departureOffset > 0) {
val hours = departureOffset / ONE_HOUR_IN_SECONDS
val minutes = departureOffset / ONE_MINUTE_IN_SECONDS % MINUTES_PER_HOUR
val seconds = departureOffset % ONE_MINUTE_IN_SECONDS
val text = if (hours > 0) {
String.format(Locale.getDefault(), "%2d:%02d:%02d", hours, minutes, seconds)
} else {
String.format(Locale.getDefault(), "%2d:%02d", minutes, seconds)
}
timeSwitcher.setCurrentText(text)
} else {
animateOut()
return
}
// Keep countDown approximately in sync.
countdownHandler.postDelayed(this::updateDepartureTime, 1000)
}
private fun animateOut() {
valueAnimator = ValueAnimator.ofFloat(0.0f, 1.0f)
.setDuration(500).apply {
addUpdateListener(SlideOutAnimator())
interpolator = AccelerateInterpolator()
start()
}
}
@OnLifecycleEvent(Lifecycle.Event.ON_STOP)
fun stop() {
Utils.log("departureView: stopped")
countdownHandler.removeCallbacksAndMessages(null)
valueAnimator?.apply {
cancel()
removeAllUpdateListeners()
}
}
private inner class SlideOutAnimator : ValueAnimator.AnimatorUpdateListener {
override fun onAnimationUpdate(animator: ValueAnimator) {
val value = animator.animatedValue as Float
if (layoutParams != null) {
translationX = value * width
layoutParams.height = ((1.0f - value) * height).toInt()
alpha = 1.0f - value
requestLayout()
if (value >= 1.0f) {
visibility = View.GONE
}
}
}
}
companion object {
private const val ONE_HOUR_IN_SECONDS = 3600
private const val MINUTES_PER_HOUR = 60
private const val ONE_MINUTE_IN_SECONDS = 60
}
} | gpl-3.0 | 16fce4d2af63db45d160e316f057b780 | 33.352273 | 132 | 0.639371 | 4.756098 | false | false | false | false |
fredyw/leetcode | src/main/kotlin/leetcode/Problem1536.kt | 1 | 1276 | package leetcode
/**
* https://leetcode.com/problems/minimum-swaps-to-arrange-a-binary-grid/
*/
class Problem1536 {
fun minSwaps(grid: Array<IntArray>): Int {
val zeroCounts = IntArray(grid.size)
val set = mutableSetOf<Int>()
for ((i, r) in grid.withIndex()) {
var count = 0
var j = r.size - 1
while (j >= 0 && r[j] == 0) {
count++
j--
}
for (k in grid.size - 1 downTo 0) {
if (count >= k && k !in set) {
set += k
zeroCounts[i] = grid.size - 1 - k
break
}
}
}
if (set.size != grid.size) {
return -1
}
var answer = 0
// Bubble sort.
var swapped = true
while (swapped) {
swapped = false
for (i in 1 until zeroCounts.size) {
if (zeroCounts[i] < zeroCounts[i - 1]) {
swapped = true
answer++
val tmp = zeroCounts[i]
zeroCounts[i] = zeroCounts[i - 1]
zeroCounts[i - 1] = tmp
}
}
}
return answer
}
}
| mit | 4c00e4136ded75d52d71c20d8767c24a | 27.355556 | 72 | 0.396552 | 4.239203 | false | false | false | false |
Tait4198/hi_pixiv | app/src/main/java/info/hzvtc/hipixiv/vm/ImageViewModel.kt | 1 | 2101 | package info.hzvtc.hipixiv.vm
import android.support.v4.content.ContextCompat
import com.hippo.glgallery.GalleryView
import com.hippo.glgallery.SimpleAdapter
import info.hzvtc.hipixiv.R
import info.hzvtc.hipixiv.databinding.ActivityImageBinding
import info.hzvtc.hipixiv.util.ImageGalleryProvider
import info.hzvtc.hipixiv.view.ImageActivity
import javax.inject.Inject
class ImageViewModel @Inject constructor(): BaseViewModel<ImageActivity, ActivityImageBinding>(), GalleryView.Listener {
private var urls = ArrayList<String>()
private lateinit var galleryProvider : ImageGalleryProvider
override fun initViewModel() {
urls = mView.intent.getStringArrayListExtra(getString(R.string.extra_list))
val nowPosition = mView.intent.getIntExtra(getString(R.string.extra_int),2)
val edgeColorId = if (urls.size > 1) R.color.colorEdge else R.color.colorEdgeTra
galleryProvider = ImageGalleryProvider(urls,mView)
val imageAdapter = SimpleAdapter(mBind.glRootView,galleryProvider)
imageAdapter.setShowIndex(urls.size > 1)
val galleryView = GalleryView.Builder(mView,imageAdapter)
.setListener(this)
.setStartPage(nowPosition)
.setProgressColor(getColor(R.color.primary))
.setProgressSize(120)
.setEdgeColor(getColor(edgeColorId))
.setErrorTextSize(64)
.setErrorTextColor(getColor(R.color.md_red_500))
.setBackgroundColor(getColor(R.color.md_grey_850))
.build()
mBind.glRootView.setContentPane(galleryView)
galleryProvider.setListener(imageAdapter)
galleryProvider.setGLRoot(mBind.glRootView)
galleryProvider.start()
}
override fun onLongPressPage(index: Int) {
}
override fun onTapSliderArea() {
}
override fun onTapMenuArea() {
}
override fun onUpdateCurrentIndex(index: Int) {
}
private fun getColor(resId : Int) : Int = ContextCompat.getColor(mView,resId)
fun stop(){
galleryProvider.stop()
}
} | mit | 5c0e5ca2607f20798b54c1d975cc4878 | 33.459016 | 120 | 0.700143 | 4.349896 | false | false | false | false |
Tait4198/hi_pixiv | app/src/main/java/info/hzvtc/hipixiv/view/fragment/ViewPagerFragment.kt | 1 | 2295 | package info.hzvtc.hipixiv.view.fragment
import android.annotation.SuppressLint
import android.support.design.widget.TabLayout
import android.support.v4.view.ViewPager
import android.view.View
import info.hzvtc.hipixiv.R
import info.hzvtc.hipixiv.adapter.ViewPagerAdapter
import info.hzvtc.hipixiv.data.ViewPagerBundle
import info.hzvtc.hipixiv.databinding.FragmentViewPagerBinding
@SuppressLint("ValidFragment")
class ViewPagerFragment(val bundle : ViewPagerBundle<BaseFragment<*>>) : BindingFragment<FragmentViewPagerBinding>(){
private lateinit var pagerAdapter : ViewPagerAdapter<BaseFragment<*>>
override fun getLayoutId(): Int = R.layout.fragment_view_pager
override fun initView(binding: FragmentViewPagerBinding): View {
pagerAdapter = ViewPagerAdapter(bundle.pagers,bundle.titles,childFragmentManager)
binding.viewPager.adapter = pagerAdapter
binding.viewPager.offscreenPageLimit = pagerAdapter.count
binding.tabLayout.setupWithViewPager(binding.viewPager)
binding.tabLayout.tabMode = TabLayout.MODE_FIXED
binding.viewPager.addOnPageChangeListener(object : ViewPager.OnPageChangeListener{
override fun onPageScrollStateChanged(state: Int) {
//
}
override fun onPageScrolled(position: Int, positionOffset: Float, positionOffsetPixels: Int) {
//
}
override fun onPageSelected(position: Int) {
bundle.fabShow(position)
}
})
return binding.root
}
fun updateBundle(bundle : ViewPagerBundle<BaseFragment<*>>){
pagerAdapter = ViewPagerAdapter(bundle.pagers,bundle.titles,childFragmentManager)
mBinding.viewPager.adapter = pagerAdapter
mBinding.viewPager.offscreenPageLimit = pagerAdapter.count
mBinding.viewPager.addOnPageChangeListener(object : ViewPager.OnPageChangeListener{
override fun onPageScrollStateChanged(state: Int) {
//
}
override fun onPageScrolled(position: Int, positionOffset: Float, positionOffsetPixels: Int) {
//
}
override fun onPageSelected(position: Int) {
bundle.fabShow(position)
}
})
}
}
| mit | fc480cc821e6bb50a57a24fcb4aabe37 | 37.25 | 117 | 0.694989 | 5.490431 | false | false | false | false |
walleth/walleth | app/src/androidTest/java/org/walleth/tests/TheTransactionActivity.kt | 1 | 4141 | package org.walleth.tests
import android.content.Context
import androidx.test.core.app.ApplicationProvider
import androidx.test.espresso.Espresso.onView
import androidx.test.espresso.assertion.ViewAssertions.matches
import androidx.test.espresso.matcher.ViewMatchers.withId
import androidx.test.espresso.matcher.ViewMatchers.withText
import org.hamcrest.Matchers.allOf
import org.hamcrest.Matchers.containsString
import org.junit.Rule
import org.junit.Test
import org.kethereum.model.ChainId
import org.kethereum.model.createTransactionWithDefaults
import org.komputing.khex.extensions.hexToByteArray
import org.komputing.khex.model.HexString
import org.ligi.trulesk.TruleskActivityRule
import org.walleth.R
import org.walleth.data.ETH_IN_WEI
import org.walleth.data.transactions.TransactionState
import org.walleth.data.transactions.toEntity
import org.walleth.infrastructure.TestApp
import org.walleth.testdata.DEFAULT_TEST_ADDRESS
import org.walleth.testdata.Room77
import org.walleth.testdata.ShapeShift
import org.walleth.testdata.addTestAddresses
import org.walleth.transactions.ViewTransactionActivity
import org.walleth.transactions.getTransactionActivityIntentForHash
import java.math.BigInteger
private val DEFAULT_NONCE = BigInteger("11")
private val DEFAULT_CHAIN = ChainId(4L)
private val DEFAULT_TX = createTransactionWithDefaults(value = ETH_IN_WEI,
from = DEFAULT_TEST_ADDRESS,
to = DEFAULT_TEST_ADDRESS,
nonce = DEFAULT_NONCE,
txHash = "0xFOO",
chain = DEFAULT_CHAIN
)
class TheTransactionActivity {
@get:Rule
var rule = TruleskActivityRule(ViewTransactionActivity::class.java, false)
@Test
fun nonceIsDisplayedCorrectly() {
TestApp.testDatabase.transactions.upsert(DEFAULT_TX.toEntity(null, TransactionState()))
TestApp.testDatabase.addressBook.addTestAddresses()
rule.launchActivity(ApplicationProvider.getApplicationContext<Context>().getTransactionActivityIntentForHash("0xFOO"))
onView(withId(R.id.nonce)).check(matches(withText("11")))
}
@Test
fun isLabeledToWhenWeReceive() {
TestApp.testDatabase.addressBook.addTestAddresses()
val transaction = DEFAULT_TX.copy(from = DEFAULT_TEST_ADDRESS, to = Room77)
TestApp.testDatabase.transactions.upsert(transaction.toEntity(null, TransactionState()))
rule.launchActivity(ApplicationProvider.getApplicationContext<Context>().getTransactionActivityIntentForHash(transaction.txHash!!))
onView(withId(R.id.from_to_title)).check(matches(withText(R.string.transaction_to_label)))
onView(withId(R.id.from_to)).check(matches(withText("Room77")))
}
@Test
fun isLabeledFromWhenWeReceive() {
TestApp.testDatabase.addressBook.addTestAddresses()
val transaction = DEFAULT_TX.copy(from = ShapeShift, to = DEFAULT_TEST_ADDRESS)
TestApp.testDatabase.transactions.upsert(transaction.toEntity(null, TransactionState()))
rule.launchActivity(ApplicationProvider.getApplicationContext<Context>().getTransactionActivityIntentForHash(transaction.txHash!!))
onView(withId(R.id.from_to_title)).check(matches(withText(R.string.transaction_from_label)))
onView(withId(R.id.from_to)).check(matches(withText("ShapeShift")))
}
@Test
fun showsTheCorrectMethodSignature() {
val transaction = DEFAULT_TX.copy(from = ShapeShift, to = DEFAULT_TEST_ADDRESS,
input = HexString("0xdeafbeef000000000000000000000000f44f28b5ca7808b9ad782c759ab8efb041de64d2").hexToByteArray())
TestApp.testDatabase.runInTransaction {
TestApp.testDatabase.addressBook.addTestAddresses()
TestApp.testDatabase.transactions.upsert(transaction.toEntity(null, TransactionState()))
}
rule.launchActivity(ApplicationProvider.getApplicationContext<Context>().getTransactionActivityIntentForHash(transaction.txHash!!))
onView(withId(R.id.function_call)).check(matches(withText(
allOf(containsString(TestApp.contractFunctionTextSignature1), containsString(TestApp.contractFunctionTextSignature2)))))
}
}
| gpl-3.0 | 4dc0b706665f2cfc9b0b8e1b5fd46de1 | 41.255102 | 139 | 0.771311 | 4.354364 | false | true | false | false |
CarlosEsco/tachiyomi | app/src/main/java/eu/kanade/presentation/more/settings/widget/TextPreferenceWidget.kt | 1 | 2523 | package eu.kanade.presentation.more.settings.widget
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.padding
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Preview
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.tooling.preview.Preview
import eu.kanade.presentation.util.secondaryItemAlpha
@Composable
fun TextPreferenceWidget(
modifier: Modifier = Modifier,
title: String? = null,
subtitle: String? = null,
icon: ImageVector? = null,
iconTint: Color = MaterialTheme.colorScheme.primary,
widget: @Composable (() -> Unit)? = null,
onPreferenceClick: (() -> Unit)? = null,
) {
BasePreferenceWidget(
modifier = modifier,
title = title,
subcomponent = if (!subtitle.isNullOrBlank()) {
{
Text(
text = subtitle,
modifier = Modifier
.padding(horizontal = PrefsHorizontalPadding)
.secondaryItemAlpha(),
style = MaterialTheme.typography.bodySmall,
maxLines = 10,
)
}
} else {
null
},
icon = if (icon != null) {
{
Icon(
imageVector = icon,
tint = iconTint,
contentDescription = null,
)
}
} else {
null
},
onClick = onPreferenceClick,
widget = widget,
)
}
@Preview
@Composable
private fun TextPreferenceWidgetPreview() {
MaterialTheme {
Surface {
Column {
TextPreferenceWidget(
title = "Text preference with icon",
subtitle = "Text preference summary",
icon = Icons.Default.Preview,
onPreferenceClick = {},
)
TextPreferenceWidget(
title = "Text preference",
subtitle = "Text preference summary",
onPreferenceClick = {},
)
}
}
}
}
| apache-2.0 | e084aaf33a5320575cd87a9934536c10 | 30.148148 | 69 | 0.566786 | 5.30042 | false | false | false | false |
Heiner1/AndroidAPS | omnipod-eros/src/androidTest/java/info/nightscout/androidaps/plugins/pump/omnipod/eros/history/ErosHistoryTest.kt | 1 | 2135 | package info.nightscout.androidaps.plugins.pump.omnipod.eros.history
import android.content.Context
import androidx.room.Room
import androidx.test.core.app.ApplicationProvider
import androidx.test.ext.junit.runners.AndroidJUnit4
import info.nightscout.androidaps.plugins.pump.omnipod.eros.definition.PodHistoryEntryType
import info.nightscout.androidaps.plugins.pump.omnipod.eros.history.database.ErosHistoryDatabase
import info.nightscout.androidaps.plugins.pump.omnipod.eros.history.database.ErosHistoryRecordDao
import info.nightscout.androidaps.plugins.pump.omnipod.eros.history.database.ErosHistoryRecordEntity
import org.junit.After
import org.junit.Assert.assertNotNull
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
@RunWith(AndroidJUnit4::class)
class ErosHistoryTest {
private lateinit var dao: ErosHistoryRecordDao
private lateinit var database: ErosHistoryDatabase
private lateinit var erosHistory: ErosHistory
@Before
fun setUp() {
val context = ApplicationProvider.getApplicationContext<Context>()
database = Room.inMemoryDatabaseBuilder(
context,
ErosHistoryDatabase::class.java
).build()
dao = database.historyRecordDao()
erosHistory = ErosHistory(dao)
}
@Test
fun testInsertionAndRetrieval() {
var history = erosHistory.getAllErosHistoryRecordsFromTimestamp(0L)
assert(history.isEmpty())
val type = PodHistoryEntryType.SET_BOLUS.code.toLong()
val entity = ErosHistoryRecordEntity(1000L, type)
erosHistory.create(entity)
erosHistory.create(ErosHistoryRecordEntity(3000L, PodHistoryEntryType.CANCEL_BOLUS.code.toLong()))
history = erosHistory.getAllErosHistoryRecordsFromTimestamp(0L)
assert(history.size == 2)
assert(type == history.first().podEntryTypeCode)
val returnedEntity = erosHistory.findErosHistoryRecordByPumpId(entity.pumpId)
assertNotNull(returnedEntity)
assert(type == returnedEntity?.podEntryTypeCode)
}
@After
fun tearDown() {
database.close()
}
}
| agpl-3.0 | 75cb4c4b7c622ccf9e2c5c6e95abf455 | 35.810345 | 106 | 0.755035 | 4.402062 | false | true | false | false |
Heiner1/AndroidAPS | automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/actions/Action.kt | 1 | 5005 | package info.nightscout.androidaps.plugins.general.automation.actions
import android.widget.LinearLayout
import androidx.annotation.DrawableRes
import dagger.android.HasAndroidInjector
import info.nightscout.shared.logging.AAPSLogger
import info.nightscout.androidaps.plugins.general.automation.triggers.Trigger
import info.nightscout.androidaps.queue.Callback
import info.nightscout.androidaps.interfaces.ResourceHelper
import org.json.JSONException
import org.json.JSONObject
import javax.inject.Inject
abstract class Action(val injector: HasAndroidInjector) {
@Inject lateinit var aapsLogger: AAPSLogger
@Inject lateinit var rh: ResourceHelper
var precondition: Trigger? = null
abstract fun friendlyName(): Int
abstract fun shortDescription(): String
abstract fun doAction(callback: Callback)
abstract fun isValid(): Boolean
@DrawableRes abstract fun icon(): Int
var title = ""
init {
injector.androidInjector().inject(this)
}
open fun generateDialog(root: LinearLayout) {}
open fun hasDialog(): Boolean = false
open fun toJSON(): String =
JSONObject().put("type", this.javaClass.simpleName).toString()
open fun fromJSON(data: String): Action = this
fun apply(a: Action) {
val obj = JSONObject(a.toJSON())
val type = obj.getString("type")
val data = obj.getJSONObject("data")
if (type == javaClass.name) fromJSON(data.toString())
}
fun instantiate(obj: JSONObject): Action? {
try {
val type = obj.getString("type")
val data = if (obj.has("data")) obj.getJSONObject("data") else JSONObject()
return when (type) {
ActionAlarm::class.java.name, // backward compatibility
ActionAlarm::class.java.simpleName -> ActionAlarm(injector).fromJSON(data.toString())
ActionCarePortalEvent::class.java.name,
ActionCarePortalEvent::class.java.simpleName -> ActionCarePortalEvent(injector).fromJSON(data.toString())
ActionDummy::class.java.name,
ActionDummy::class.java.simpleName -> ActionDummy(injector).fromJSON(data.toString())
ActionLoopDisable::class.java.name,
ActionLoopDisable::class.java.simpleName -> ActionLoopDisable(injector).fromJSON(data.toString())
ActionLoopEnable::class.java.name,
ActionLoopEnable::class.java.simpleName -> ActionLoopEnable(injector).fromJSON(data.toString())
ActionLoopResume::class.java.name,
ActionLoopResume::class.java.simpleName -> ActionLoopResume(injector).fromJSON(data.toString())
ActionLoopSuspend::class.java.name,
ActionLoopSuspend::class.java.simpleName -> ActionLoopSuspend(injector).fromJSON(data.toString())
ActionNotification::class.java.name,
ActionNotification::class.java.simpleName -> ActionNotification(injector).fromJSON(data.toString())
ActionProfileSwitch::class.java.name,
ActionProfileSwitch::class.java.simpleName -> ActionProfileSwitch(injector).fromJSON(data.toString())
ActionProfileSwitchPercent::class.java.name,
ActionProfileSwitchPercent::class.java.simpleName -> ActionProfileSwitchPercent(injector).fromJSON(data.toString())
ActionRunAutotune::class.java.name,
ActionRunAutotune::class.java.simpleName -> ActionRunAutotune(injector).fromJSON(data.toString())
ActionSendSMS::class.java.name,
ActionSendSMS::class.java.simpleName -> ActionSendSMS(injector).fromJSON(data.toString())
ActionStartTempTarget::class.java.name,
ActionStartTempTarget::class.java.simpleName -> ActionStartTempTarget(injector).fromJSON(data.toString())
ActionStopTempTarget::class.java.name,
ActionStopTempTarget::class.java.simpleName -> ActionStopTempTarget(injector).fromJSON(data.toString())
else -> throw ClassNotFoundException(type)
}
//val clazz = Class.forName(type).kotlin
//return (clazz.primaryConstructor?.call(injector) as Action).fromJSON(data?.toString()
// ?: "")
//return (clazz.newInstance() as Action).fromJSON(data?.toString() ?: "")
} catch (e: ClassNotFoundException) {
aapsLogger.error("Unhandled exception", e)
} catch (e: InstantiationException) {
aapsLogger.error("Unhandled exception", e)
} catch (e: IllegalAccessException) {
aapsLogger.error("Unhandled exception", e)
} catch (e: JSONException) {
aapsLogger.error("Unhandled exception", e)
}
return null
}
} | agpl-3.0 | da410d64283e21c5db3873bf6b26dbb4 | 49.565657 | 131 | 0.644555 | 5.030151 | false | false | false | false |
Adventech/sabbath-school-android-2 | features/lessons/src/main/java/com/cryart/sabbathschool/lessons/ui/readings/SSReadingViewModel.kt | 1 | 14492 | /*
* Copyright (c) 2020 Adventech <[email protected]>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.cryart.sabbathschool.lessons.ui.readings
import android.app.Activity
import android.content.Context
import android.os.Build
import android.util.DisplayMetrics
import android.view.View
import android.view.ViewGroup
import androidx.core.view.isVisible
import androidx.core.widget.NestedScrollView
import androidx.databinding.BindingAdapter
import androidx.databinding.ObservableInt
import androidx.fragment.app.FragmentActivity
import androidx.lifecycle.ViewTreeLifecycleOwner
import androidx.lifecycle.lifecycleScope
import app.ss.bible.BibleVersesActivity
import app.ss.lessons.data.model.SSContextMenu
import app.ss.lessons.data.repository.lessons.LessonsRepository
import app.ss.models.SSLessonInfo
import app.ss.models.SSRead
import app.ss.models.SSReadComments
import app.ss.models.SSReadHighlights
import com.cryart.sabbathschool.core.extensions.context.colorPrimary
import com.cryart.sabbathschool.core.extensions.context.colorPrimaryDark
import com.cryart.sabbathschool.core.extensions.context.isDarkTheme
import com.cryart.sabbathschool.core.extensions.coroutines.debounceUntilLast
import com.cryart.sabbathschool.core.misc.DateHelper
import com.cryart.sabbathschool.core.misc.SSConstants
import com.cryart.sabbathschool.core.misc.SSEvent
import com.cryart.sabbathschool.core.misc.SSHelper
import com.cryart.sabbathschool.core.model.SSReadingDisplayOptions
import com.cryart.sabbathschool.core.model.colorTheme
import com.cryart.sabbathschool.lessons.R
import com.cryart.sabbathschool.lessons.databinding.SsReadingActivityBinding
import com.cryart.sabbathschool.lessons.ui.readings.options.SSReadingDisplayOptionsView
import dagger.assisted.Assisted
import dagger.assisted.AssistedFactory
import dagger.assisted.AssistedInject
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.MainScope
import kotlinx.coroutines.launch
import org.joda.time.DateTime
import timber.log.Timber
class SSReadingViewModel @AssistedInject constructor(
private val lessonsRepository: LessonsRepository,
@Assisted private val ssLessonIndex: String,
@Assisted private val dataListener: DataListener,
@Assisted private val ssReadingActivityBinding: SsReadingActivityBinding,
@Assisted private val activity: FragmentActivity
) : SSReadingView.ContextMenuCallback,
SSReadingView.HighlightsCommentsCallback,
CoroutineScope by MainScope() {
private val context: Context = activity
private var ssLessonInfo: SSLessonInfo? = null
private var ssReadIndexInt = 0
private val ssReads: ArrayList<SSRead> = arrayListOf()
private val ssReadHighlights: ArrayList<SSReadHighlights> = arrayListOf()
private val ssReadComments: ArrayList<SSReadComments> = arrayListOf()
private var ssTotalReadsCount = 0
private var ssReadsDownloaded = false
private var highlightId = 0
val lessonTitle: String get() = ssLessonInfo?.lesson?.title ?: ""
val lessonShareIndex: String get() = ssLessonInfo?.shareIndex() ?: ""
val ssLessonLoadingVisibility = ObservableInt(View.INVISIBLE)
val ssLessonOfflineStateVisibility = ObservableInt(View.INVISIBLE)
val ssLessonErrorStateVisibility = ObservableInt(View.INVISIBLE)
val ssLessonCoordinatorVisibility = ObservableInt(View.INVISIBLE)
val primaryColor: Int
get() = context.colorPrimary
val secondaryColor: Int
get() = context.colorPrimaryDark
private val currentSSReadingView: SSReadingView?
get() {
val view = ssReadingActivityBinding.ssReadingViewPager
.findViewWithTag<View>("ssReadingView_" + ssReadingActivityBinding.ssReadingViewPager.currentItem)
return view?.findViewById(R.id.ss_reading_view)
}
val cover: String
get() = ssLessonInfo?.lesson?.cover ?: ""
init {
loadLessonInfo()
}
private val verseClickWithDebounce: (verse: String) -> Unit =
debounceUntilLast(
scope = ViewTreeLifecycleOwner.get(ssReadingActivityBinding.root)?.lifecycleScope ?: MainScope()
) { verse ->
val intent = BibleVersesActivity.launchIntent(
context,
verse,
ssReads[ssReadingActivityBinding.ssReadingViewPager.currentItem].index
)
context.startActivity(intent)
}
private fun loadLessonInfo() = launch {
ssLessonLoadingVisibility.set(View.VISIBLE)
ssLessonOfflineStateVisibility.set(View.INVISIBLE)
ssLessonErrorStateVisibility.set(View.INVISIBLE)
ssLessonCoordinatorVisibility.set(View.INVISIBLE)
val lessonInfoResource = lessonsRepository.getLessonInfo(ssLessonIndex)
val lessonInfo = lessonInfoResource.data ?: run {
ssLessonErrorStateVisibility.set(View.VISIBLE)
ssLessonLoadingVisibility.set(View.INVISIBLE)
ssLessonOfflineStateVisibility.set(View.INVISIBLE)
ssLessonCoordinatorVisibility.set(View.INVISIBLE)
return@launch
}
ssLessonInfo = lessonInfo
dataListener.onLessonInfoChanged(lessonInfo)
ssTotalReadsCount = lessonInfo.days.size
val today = DateTime.now().withTimeAtStartOfDay()
for ((idx, ssDay) in lessonInfo.days.withIndex()) {
val startDate = DateHelper.parseDate(ssDay.date)
if (startDate?.isEqual(today) == true && ssReadIndexInt < 6) {
ssReadIndexInt = idx
}
loadComments(ssDay.index, idx)
loadHighlights(ssDay.index, idx)
val resource = lessonsRepository.getDayRead(ssDay)
resource.data?.let { ssReads.add(it) }
}
ssReadsDownloaded = true
dataListener.onReadsDownloaded(ssReads, ssReadHighlights, ssReadComments, ssReadIndexInt)
try {
ssLessonCoordinatorVisibility.set(View.VISIBLE)
ssLessonLoadingVisibility.set(View.INVISIBLE)
ssLessonOfflineStateVisibility.set(View.INVISIBLE)
ssLessonErrorStateVisibility.set(View.INVISIBLE)
} catch (e: Exception) {
Timber.e(e)
}
}
private suspend fun loadComments(dayIndex: String, index: Int) {
val resource = lessonsRepository.getComments(dayIndex)
val comments = resource.data ?: SSReadComments(dayIndex, emptyList())
ssReadComments.add(index, comments)
}
private suspend fun loadHighlights(dayIndex: String, index: Int) {
val resource = lessonsRepository.getReadHighlights(dayIndex)
val highlights = resource.data ?: SSReadHighlights(dayIndex)
ssReadHighlights.add(index, highlights)
}
override fun onSelectionStarted(x: Float, y: Float, highlightId: Int) {
onSelectionStarted(x, y)
this.highlightId = highlightId
}
@Suppress("DEPRECATION")
override fun onSelectionStarted(posX: Float, posY: Float) {
val scrollView: NestedScrollView = ssReadingActivityBinding.ssReadingViewPager
.findViewWithTag("ssReadingView_" + ssReadingActivityBinding.ssReadingViewPager.currentItem)
val y = posY - scrollView.scrollY + ssReadingActivityBinding.ssReadingViewPager.top
val metrics = DisplayMetrics()
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
context.display?.getRealMetrics(metrics)
} else {
(context as? Activity)?.windowManager?.defaultDisplay?.getMetrics(metrics)
}
val params = ssReadingActivityBinding.ssContextMenu.ssReadingContextMenu.layoutParams as ViewGroup.MarginLayoutParams
val contextMenuWidth = ssReadingActivityBinding.ssContextMenu.ssReadingContextMenu.width
val contextMenuHeight = ssReadingActivityBinding.ssContextMenu.ssReadingContextMenu.height
val screenWidth: Int = metrics.widthPixels
val margin: Int = SSHelper.convertDpToPixels(context, 50)
val jumpMargin: Int = SSHelper.convertDpToPixels(context, 60)
var contextMenuX = posX.toInt() - contextMenuWidth / 2
var contextMenuY = scrollView.top + y.toInt() - contextMenuHeight - margin
if (contextMenuX - margin < 0) {
contextMenuX = margin
}
if (contextMenuX + contextMenuWidth + margin > screenWidth) {
contextMenuX = screenWidth - margin - contextMenuWidth
}
if (contextMenuY - margin < 0) {
contextMenuY += contextMenuHeight + jumpMargin
}
params.setMargins(contextMenuX, contextMenuY, 0, 0)
ssReadingActivityBinding.ssContextMenu.ssReadingContextMenu.layoutParams = params
ssReadingActivityBinding.ssContextMenu.ssReadingContextMenu.visibility = View.VISIBLE
highlightId = 0
}
override fun onSelectionFinished() {
ssReadingActivityBinding.ssContextMenu.ssReadingContextMenu.visibility = View.INVISIBLE
}
override fun onHighlightsReceived(ssReadHighlights: SSReadHighlights) {
launch { lessonsRepository.saveHighlights(ssReadHighlights) }
}
override fun onCommentsReceived(ssReadComments: SSReadComments) {
launch { lessonsRepository.saveComments(ssReadComments) }
}
override fun onVerseClicked(verse: String) = verseClickWithDebounce(verse)
interface DataListener {
fun onLessonInfoChanged(ssLessonInfo: SSLessonInfo)
fun onReadsDownloaded(ssReads: List<SSRead>, ssReadHighlights: List<SSReadHighlights>, ssReadComments: List<SSReadComments>, ssReadIndex: Int)
}
fun onDisplayOptionsClick() {
val ssReadingDisplayOptionsView = SSReadingDisplayOptionsView()
val fragmentManager = (context as? FragmentActivity)?.supportFragmentManager ?: return
ssReadingDisplayOptionsView.show(fragmentManager, ssReadingDisplayOptionsView.tag)
val index = ssReads.getOrNull(ssReadingActivityBinding.ssReadingViewPager.currentItem) ?: return
SSEvent.track(
context,
SSConstants.SS_EVENT_READ_OPTIONS_OPEN,
hashMapOf(SSConstants.SS_EVENT_PARAM_READ_INDEX to index)
)
}
fun highlightYellow() {
highlightSelection(SSContextMenu.HIGHLIGHT_YELLOW)
}
fun highlightOrange() {
highlightSelection(SSContextMenu.HIGHLIGHT_ORANGE)
}
fun highlightGreen() {
highlightSelection(SSContextMenu.HIGHLIGHT_GREEN)
}
fun highlightBlue() {
highlightSelection(SSContextMenu.HIGHLIGHT_BLUE)
}
fun underline() {
highlightSelection(SSContextMenu.UNDERLINE)
}
fun unHighlightSelection() {
val ssReadingView = currentSSReadingView
if (ssReadingView != null) {
ssReadingView.ssReadViewBridge.unHighlightSelection(highlightId)
ssReadingView.selectionFinished()
}
}
private fun highlightSelection(color: String) {
val ssReadingView = currentSSReadingView
if (ssReadingView != null) {
ssReadingView.ssReadViewBridge.highlightSelection(color, highlightId)
ssReadingView.selectionFinished()
}
highlightId = 0
}
fun copy() {
val ssReadingView = currentSSReadingView
if (ssReadingView != null) {
ssReadingView.ssReadViewBridge.copy()
ssReadingView.selectionFinished()
}
}
fun paste() {
val ssReadingView = currentSSReadingView
ssReadingView?.ssReadViewBridge?.paste()
}
fun share() {
val ssReadingView = currentSSReadingView
if (ssReadingView != null) {
ssReadingView.ssReadViewBridge.share()
ssReadingView.selectionFinished()
}
}
fun search() {
currentSSReadingView?.apply {
ssReadViewBridge.search()
selectionFinished()
}
}
fun onSSReadingDisplayOptions(ssReadingDisplayOptions: SSReadingDisplayOptions) {
currentSSReadingView?.updateReadingDisplayOptions(ssReadingDisplayOptions)
val parent = currentSSReadingView?.parent as? ViewGroup
parent?.setBackgroundColor(ssReadingDisplayOptions.colorTheme(parent.context))
for (i in 0 until ssTotalReadsCount) {
if (i == ssReadingActivityBinding.ssReadingViewPager.currentItem) continue
val view = ssReadingActivityBinding.ssReadingViewPager.findViewWithTag<View?>("ssReadingView_$i")
if (view != null) {
val readingView = view.findViewById<SSReadingView>(R.id.ss_reading_view)
readingView.updateReadingDisplayOptions(ssReadingDisplayOptions)
}
}
}
fun reloadContent() {
loadLessonInfo()
}
companion object {
/**
* Pass true if this view should be visible in light theme
* false if it should be visible in dark theme
*/
@JvmStatic
@BindingAdapter("showInLightTheme")
fun setVisibility(view: View, show: Boolean) {
val isLightTheme = !view.context.isDarkTheme()
view.isVisible = (show && isLightTheme) || (!show && !isLightTheme)
}
}
}
@AssistedFactory
interface ReadingViewModelFactory {
fun create(
lessonIndex: String,
dataListener: SSReadingViewModel.DataListener,
ssReadingActivityBinding: SsReadingActivityBinding,
activity: FragmentActivity
): SSReadingViewModel
}
| mit | 8458d6872fa652d7e1c42f76f2642da3 | 39.033149 | 150 | 0.714946 | 4.734401 | false | false | false | false |
Maccimo/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/actions/internal/refactoringTesting/MoveRefactoringActionDialog.kt | 2 | 4697 | // 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.actions.internal.refactoringTesting
import com.intellij.ide.util.PropertiesComponent
import com.intellij.openapi.fileChooser.FileChooserDescriptorFactory
import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.DialogWrapper
import com.intellij.openapi.ui.TextFieldWithBrowseButton
import com.intellij.openapi.util.Disposer
import com.intellij.refactoring.copy.CopyFilesOrDirectoriesDialog
import com.intellij.ui.components.JBLabelDecorator
import com.intellij.ui.components.JBTextField
import com.intellij.util.ui.FormBuilder
import com.intellij.util.ui.UIUtil
import org.jetbrains.kotlin.idea.base.util.onTextChange
import org.jetbrains.kotlin.idea.KotlinBundle
import javax.swing.InputVerifier
import javax.swing.JComponent
import kotlin.io.path.Path
import kotlin.io.path.exists
import kotlin.io.path.isDirectory
class MoveRefactoringActionDialog(
private val project: Project, private val defaultDirectory: String
) : DialogWrapper(project, true) {
companion object {
val WINDOW_TITLE get() = KotlinBundle.message("move.refactoring.test")
val COUNT_LABEL_TEXT get() = KotlinBundle.message("maximum.count.of.applied.refactoring.before.validity.check")
val LOG_FILE_WILL_BE_PLACED_HERE get() = KotlinBundle.message("test.result.log.file.will.be.placed.here")
const val RECENT_SELECTED_PATH = "org.jetbrains.kotlin.idea.actions.internal.refactoringTesting.RECENT_SELECTED_PATH"
const val RECENT_SELECTED_RUN_COUNT = "org.jetbrains.kotlin.idea.actions.internal.refactoringTesting.RECENT_SELECTED_RUN_COUNT"
}
private val nameLabel = JBLabelDecorator.createJBLabelDecorator().setBold(true)
private val tfTargetDirectory = TextFieldWithBrowseButton()
private val tfRefactoringRunCount = JBTextField()
init {
title = WINDOW_TITLE
init()
initializeData()
}
override fun createActions() = arrayOf(okAction, cancelAction)
override fun getPreferredFocusedComponent() = tfTargetDirectory.childComponent
override fun createCenterPanel(): JComponent? = null
override fun createNorthPanel(): JComponent {
val descriptor = FileChooserDescriptorFactory.createSingleFolderDescriptor()
tfTargetDirectory.addBrowseFolderListener(
WINDOW_TITLE,
LOG_FILE_WILL_BE_PLACED_HERE,
project,
descriptor
)
tfTargetDirectory.setTextFieldPreferredWidth(CopyFilesOrDirectoriesDialog.MAX_PATH_LENGTH)
tfTargetDirectory.textField.onTextChange { validateOKButton() }
Disposer.register(disposable, tfTargetDirectory)
tfRefactoringRunCount.inputVerifier = object : InputVerifier() {
override fun verify(input: JComponent?) = tfRefactoringRunCount.text.toIntOrNull()?.let { it > 0 } ?: false
}
tfRefactoringRunCount.onTextChange { validateOKButton() }
return FormBuilder.createFormBuilder()
.addComponent(nameLabel)
.addLabeledComponent(LOG_FILE_WILL_BE_PLACED_HERE, tfTargetDirectory, UIUtil.LARGE_VGAP)
.addLabeledComponent(COUNT_LABEL_TEXT, tfRefactoringRunCount)
.panel
}
private fun initializeData() {
tfTargetDirectory.childComponent.text = PropertiesComponent.getInstance().getValue(RECENT_SELECTED_PATH, defaultDirectory)
tfRefactoringRunCount.text =
PropertiesComponent.getInstance().getValue(RECENT_SELECTED_RUN_COUNT, "1")
.toIntOrNull()
?.let { if (it < 1) "1" else it.toString() }
validateOKButton()
}
private fun validateOKButton() {
val isCorrectCount = tfRefactoringRunCount.text.toIntOrNull()?.let { it > 0 } ?: false
if (!isCorrectCount) {
isOKActionEnabled = false
return
}
val isCorrectPath = tfTargetDirectory.childComponent.text
?.let { it.isNotEmpty() && Path(it).let { path -> path.exists() && path.isDirectory() } }
?: false
isOKActionEnabled = isCorrectPath
}
val selectedDirectoryName get() = tfTargetDirectory.childComponent.text!!
val selectedCount get() = tfRefactoringRunCount.text.toInt()
override fun doOKAction() {
PropertiesComponent.getInstance().setValue(RECENT_SELECTED_PATH, selectedDirectoryName)
PropertiesComponent.getInstance().setValue(RECENT_SELECTED_RUN_COUNT, tfRefactoringRunCount.text)
close(OK_EXIT_CODE, /* isOk = */ true)
}
} | apache-2.0 | bd638bf6c12585d34e5905716b5becb9 | 39.5 | 158 | 0.725357 | 4.697 | false | false | false | false |
futurice/freesound-android | app/src/test/java/com/futurice/freesound/test/assertion/livedata/LiveDataAssertion.kt | 1 | 4704 | /*
* Copyright 2018 Futurice GmbH
*
* 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.futurice.freesound.test.assertion.livedata
import android.arch.lifecycle.Observer
import junit.framework.Assert.assertTrue
import junit.framework.TestCase.assertEquals
class TestObserver<T> : Observer<T>, LiveDataAssertion<T> {
private val mutableValues: MutableList<T?>
constructor() {
mutableValues = ArrayList()
}
private constructor(values: MutableList<T?>) {
TestObserver<T>()
this.mutableValues = values
}
val values
get() = mutableValues.toList()
override fun onChanged(t: T?) {
mutableValues.add(t)
}
fun getValue(): T? {
return values.last()
}
fun skip(count: Int = 1): TestObserver<T> {
if (count < 0) {
throw IllegalArgumentException("Skip count parameter must be non-negative")
}
assertValueCountAtLeast("Cannot skip: $count value(s), when only: ${mutableValues.size} values", count + 1)
return TestObserver(mutableValues.subList(count, mutableValues.lastIndex))
}
override fun assertValueCount(expectedCount: Int): LiveDataAssertion<T> {
if (expectedCount < 0) {
throw IllegalArgumentException("Expected count parameter must be non-negative")
}
return assertValueCount("Expected: $expectedCount values, but has: $1", expectedCount)
}
override fun assertOnlyValue(expected: T): LiveDataAssertion<T> {
assertValueCount("Expected a single value, but has: $1", 1)
val actual = values.last()
assertEquals(expected, actual)
return this
}
override fun assertValue(expected: T): LiveDataAssertion<T> {
assertAtLeastSingleValueCount()
val actual = values.last()
assertEquals(expected, actual)
return this
}
override fun assertValue(expectedPredicate: (T) -> Boolean): LiveDataAssertion<T> {
assertAtLeastSingleValueCount()
val actual = values.last()!!
assertTrue(expectedPredicate(actual))
return this
}
override fun assertValueAt(index: Int, expected: T): LiveDataAssertion<T> {
val atLeastValueCount = index + 1
assertValueCountAtLeast("Expected at least: $atLeastValueCount values, but has: $1", atLeastValueCount)
val actual = values[index]
assertEquals(expected, actual)
return this
}
override fun assertNoValues(): LiveDataAssertion<T> {
return assertValueCount("Expected no values, but has: $1", 0)
}
override fun assertValues(vararg expected: T): LiveDataAssertion<T> {
assertEquals(expected, values)
return this
}
override fun assertOnlyValues(vararg expected: T): LiveDataAssertion<T> {
assertEquals(expected, values)
return this
}
//
// Internal Helpers
//
private fun assertValueCount(msg: String, expectedCount: Int): LiveDataAssertion<T> {
val actualCount = values.size
assertEquals(msg.format(actualCount), expectedCount, actualCount)
return this
}
private fun assertValueCountAtLeast(msg: String, expectedCount: Int): LiveDataAssertion<T> {
if (expectedCount < 0) {
throw IllegalArgumentException("Expected count parameter must be non-negative")
}
val actualCount = values.size
assertTrue(msg.format(actualCount), expectedCount <= actualCount)
return this
}
private fun assertAtLeastSingleValueCount() {
assertValueCountAtLeast("Expected at least one value.", 1)
}
}
interface LiveDataAssertion<T> {
fun assertNoValues(): LiveDataAssertion<T>
fun assertValueCount(expectedCount: Int): LiveDataAssertion<T>
fun assertValueAt(index: Int, expected: T): LiveDataAssertion<T>
fun assertOnlyValue(expected: T): LiveDataAssertion<T>
fun assertOnlyValues(vararg expected: T): LiveDataAssertion<T>
fun assertValue(expected: T): LiveDataAssertion<T>
fun assertValue(expectedPredicate: (T) -> Boolean): LiveDataAssertion<T>
fun assertValues(vararg expected: T): LiveDataAssertion<T>
}
| apache-2.0 | 9ef29e800e98f1af96f12f4366992073 | 30.783784 | 115 | 0.681122 | 4.575875 | false | false | false | false |
DuncanCasteleyn/DiscordModBot | src/main/kotlin/be/duncanc/discordmodbot/bot/services/WeeklyActivityReport.kt | 1 | 10137 | /*
* Copyright 2018 Duncan Casteleyn
*
* 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 be.duncanc.discordmodbot.bot.services
import be.duncanc.discordmodbot.bot.commands.CommandModule
import be.duncanc.discordmodbot.bot.sequences.MessageSequence
import be.duncanc.discordmodbot.bot.sequences.Sequence
import be.duncanc.discordmodbot.data.entities.ActivityReportSettings
import be.duncanc.discordmodbot.data.repositories.jpa.ActivityReportSettingsRepository
import net.dv8tion.jda.api.JDA
import net.dv8tion.jda.api.MessageBuilder
import net.dv8tion.jda.api.Permission
import net.dv8tion.jda.api.entities.Member
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.ReadyEvent
import net.dv8tion.jda.api.events.ShutdownEvent
import net.dv8tion.jda.api.events.message.MessageReceivedEvent
import net.dv8tion.jda.api.exceptions.PermissionException
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import org.springframework.stereotype.Component
import java.time.Duration
import java.time.OffsetDateTime
import java.util.concurrent.TimeUnit
@Component
class WeeklyActivityReport(
private val activityReportSettingsRepository: ActivityReportSettingsRepository
) : CommandModule(
arrayOf("WeeklyActivitySettings"),
null,
"Allows you to configure weekly reports on amount of message per channel for certain users (in a role)"
) {
companion object {
val LOG: Logger = LoggerFactory.getLogger(WeeklyActivityReport::class.java)
}
val instances = HashSet<JDA>()
override fun onReady(event: ReadyEvent) {
instances.add(event.jda)
}
override fun onShutdown(event: ShutdownEvent) {
instances.remove(event.jda)
}
override fun commandExec(event: MessageReceivedEvent, command: String, arguments: String?) {
if (event.member?.hasPermission(Permission.ADMINISTRATOR) == true) {
event.jda.addEventListener(WeeklyReportConfigurationSequence(event.author, event.channel))
} else {
throw PermissionException("You need administrator permissions.")
}
}
@Deprecated("Broken needs to be fixed")
fun sendReports() {
val statsCollectionStartTime = OffsetDateTime.now()
activityReportSettingsRepository.findAll().forEach { reportSettings ->
val guild = reportSettings.guildId.let { guildId ->
instances.stream().filter { jda ->
jda.getGuildById(guildId) != null
}.findFirst().orElse(null)?.getGuildById(guildId)
}
if (guild != null) {
val textChannel = reportSettings.reportChannel?.let { guild.getTextChannelById(it) }
if (textChannel != null) {
val trackedMembers = HashSet<Member>()
reportSettings.trackedRoleOrMember.forEach {
val role = guild.getRoleById(it)
if (role != null) {
val members = guild.getMembersWithRoles(role)
trackedMembers.addAll(members)
} else {
val member = guild.getMemberById(it)!!
trackedMembers.add(member)
}
}
if (trackedMembers.isEmpty()) {
return@forEach
}
val stats = HashMap<TextChannel, HashMap<Member, Long>>()
guild.textChannels.forEach {
val channelStats = HashMap<Member, Long>()
trackedMembers.forEach { trackedMember -> channelStats[trackedMember] = 0L }
try {
for (message in it.iterableHistory) {
if (trackedMembers.contains(message.member)) {
channelStats[message.member!!] = (channelStats[message.member!!] ?: 0L) + 1L
}
if (Duration.between(message.timeCreated, statsCollectionStartTime).toDays() >= 7) {
break
}
}
stats[it] = channelStats
} catch (e: PermissionException) {
LOG.warn("Insufficient permissions to retrieve history from $it")
}
}
val message = MessageBuilder()
message.append("**Message statistics of the past 7 days**\n")
stats.forEach { (channel, channelStats) ->
message.append("\n***${channel.asMention}***\n\n")
channelStats.forEach { (member, count) ->
message.append("${member.user.name}: $count\n")
}
}
message.buildAll(MessageBuilder.SplitPolicy.NEWLINE).forEach {
textChannel.sendMessage(it).queue()
}
} else {
LOG.warn("The text channel with id ${reportSettings.reportChannel} was not found on the server/guild. Configure another channel.")
}
} else {
LOG.warn("The guild with id ${reportSettings.guildId} was not found, maybe the bot was removed or maybe you shut down the bot responsible for this server.")
}
}
}
inner class WeeklyReportConfigurationSequence(
user: User,
channel: MessageChannel
) : Sequence(
user,
channel,
true,
true
), MessageSequence {
private var sequenceNumber: Byte = 0
init {
channel.sendMessage(
"Please selection the action you want to perform:\n\n" +
"0. Set report channel\n" +
"1. add tracked member or role\n" +
"2. remove tracked member or role"
).queue { addMessageToCleaner(it) }
}
override fun onMessageReceivedDuringSequence(event: MessageReceivedEvent) {
when (sequenceNumber) {
0.toByte() -> {
when (event.message.contentRaw.toByte()) {
0.toByte() -> {
sequenceNumber = 1
channel.sendMessage("Please mention the channel or send the id of the channel")
.queue { addMessageToCleaner(it) }
}
1.toByte() -> {
sequenceNumber = 2
channel.sendMessage("Please mention the user or role or send the id of the role or user")
.queue { addMessageToCleaner(it) }
}
2.toByte() -> {
sequenceNumber = 3
channel.sendMessage("Please mention the user or role or send the id of the role or user")
.queue { addMessageToCleaner(it) }
}
}
}
1.toByte() -> {
val channelId = event.message.contentRaw.replace("<#", "").replace(">", "").toLong()
val guildId = event.guild.idLong
val activityReportSettings =
activityReportSettingsRepository.findById(guildId).orElse(ActivityReportSettings(guildId))
activityReportSettings.reportChannel = channelId
activityReportSettingsRepository.save(activityReportSettings)
channel.sendMessage("Channel configured.").queue { it.delete().queueAfter(1, TimeUnit.MINUTES) }
destroy()
}
2.toByte() -> {
val roleOrMemberId = getRoleOrMemberIdFromString(event)
val guildId = event.guild.idLong
val activityReportSettings =
activityReportSettingsRepository.findById(guildId).orElse(ActivityReportSettings(guildId))
activityReportSettings.trackedRoleOrMember.add(roleOrMemberId)
activityReportSettingsRepository.save(activityReportSettings)
channel.sendMessage("Role or member added.").queue { it.delete().queueAfter(1, TimeUnit.MINUTES) }
destroy()
}
3.toByte() -> {
val guildId = event.guild.idLong
val roleOrMemberId = getRoleOrMemberIdFromString(event)
val activityReportSettings =
activityReportSettingsRepository.findById(guildId).orElse(ActivityReportSettings(guildId))
activityReportSettings.trackedRoleOrMember.remove(roleOrMemberId)
activityReportSettingsRepository.save(activityReportSettings)
channel.sendMessage("Role or member removed.").queue { it.delete().queueAfter(1, TimeUnit.MINUTES) }
destroy()
}
}
}
}
private fun getRoleOrMemberIdFromString(event: MessageReceivedEvent) =
event.message.contentRaw
.replace("<@", "")
.replace("&", "")
.replace(">", "")
.toLong()
}
| apache-2.0 | fa6788ff42a5ceab6566c9381a27291e | 45.714286 | 172 | 0.566045 | 5.360656 | false | false | false | false |
JetBrains/ideavim | src/test/java/org/jetbrains/plugins/ideavim/group/motion/MotionGroup_scrolloff_scrolljump_Test.kt | 1 | 17136 | /*
* 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.
*/
@file:Suppress("ClassName")
package org.jetbrains.plugins.ideavim.group.motion
import com.maddyhome.idea.vim.VimPlugin
import com.maddyhome.idea.vim.api.injector
import com.maddyhome.idea.vim.helper.VimBehaviorDiffers
import com.maddyhome.idea.vim.options.OptionConstants
import com.maddyhome.idea.vim.options.OptionScope
import com.maddyhome.idea.vim.vimscript.model.datatypes.VimInt
import org.jetbrains.plugins.ideavim.OptionValueType
import org.jetbrains.plugins.ideavim.SkipNeovimReason
import org.jetbrains.plugins.ideavim.TestWithoutNeovim
import org.jetbrains.plugins.ideavim.VimOptionTestCase
import org.jetbrains.plugins.ideavim.VimOptionTestConfiguration
import org.jetbrains.plugins.ideavim.VimTestOption
// These tests are sanity tests for scrolloff and scrolljump, with actions that move the cursor. Other actions that are
// affected by scrolloff or scrolljump should include that in the action specific tests
class MotionGroup_scrolloff_Test : VimOptionTestCase(OptionConstants.scrolloffName) {
@TestWithoutNeovim(SkipNeovimReason.OPTION)
@VimOptionTestConfiguration(VimTestOption(OptionConstants.scrolloffName, OptionValueType.NUMBER, "0"))
fun `test move up shows no context with scrolloff=0`() {
configureByPages(5)
setPositionAndScroll(25, 25)
typeText(injector.parser.parseKeys("k"))
assertPosition(24, 0)
assertVisibleArea(24, 58)
}
@TestWithoutNeovim(SkipNeovimReason.OPTION)
@VimOptionTestConfiguration(VimTestOption(OptionConstants.scrolloffName, OptionValueType.NUMBER, "1"))
fun `test move up shows context line with scrolloff=1`() {
configureByPages(5)
setPositionAndScroll(25, 26)
typeText(injector.parser.parseKeys("k"))
assertPosition(25, 0)
assertVisibleArea(24, 58)
}
@TestWithoutNeovim(SkipNeovimReason.OPTION)
@VimOptionTestConfiguration(VimTestOption(OptionConstants.scrolloffName, OptionValueType.NUMBER, "10"))
fun `test move up shows context lines with scrolloff=10`() {
configureByPages(5)
setPositionAndScroll(25, 35)
typeText(injector.parser.parseKeys("k"))
assertPosition(34, 0)
assertVisibleArea(24, 58)
}
@TestWithoutNeovim(SkipNeovimReason.OPTION)
@VimOptionTestConfiguration(VimTestOption(OptionConstants.scrolloffName, OptionValueType.NUMBER, "15"))
fun `test move up when scrolloff is slightly less than half screen height`() {
// Screen height = 35. scrolloff=15. This gives 5 possible caret lines without scrolling (48, 49, 50, 51 + 52)
configureByPages(5)
setPositionAndScroll(33, 52)
typeText(injector.parser.parseKeys("k"))
assertPosition(51, 0)
assertVisibleArea(33, 67)
typeText(injector.parser.parseKeys("k"))
assertPosition(50, 0)
assertVisibleArea(33, 67)
typeText(injector.parser.parseKeys("k"))
assertPosition(49, 0)
assertVisibleArea(33, 67)
typeText(injector.parser.parseKeys("k"))
assertPosition(48, 0)
assertVisibleArea(33, 67)
// Scroll
typeText(injector.parser.parseKeys("k"))
assertPosition(47, 0)
assertVisibleArea(32, 66)
}
@TestWithoutNeovim(SkipNeovimReason.OPTION)
@VimOptionTestConfiguration(VimTestOption(OptionConstants.scrolloffName, OptionValueType.NUMBER, "16"))
fun `test move up when scrolloff is slightly less than half screen height 2`() {
// Screen height = 35. scrolloff=16. This gives 3 possible caret lines without scrolling (49, 50 + 51)
configureByPages(5)
setPositionAndScroll(33, 51)
typeText(injector.parser.parseKeys("k"))
assertPosition(50, 0)
assertVisibleArea(33, 67)
typeText(injector.parser.parseKeys("k"))
assertPosition(49, 0)
assertVisibleArea(33, 67)
// Scroll
typeText(injector.parser.parseKeys("k"))
assertPosition(48, 0)
assertVisibleArea(32, 66)
}
@TestWithoutNeovim(SkipNeovimReason.OPTION)
@VimOptionTestConfiguration(VimTestOption(OptionConstants.scrolloffName, OptionValueType.NUMBER, "16"))
fun `test move up when scrolloff is slightly less than half screen height 3`() {
// Screen height = 34. scrolloff=16
// Even numbers. 2 possible caret lines without scrolling (49 + 50)
configureByPages(5)
setEditorVisibleSize(screenWidth, 34)
setPositionAndScroll(33, 50)
typeText(injector.parser.parseKeys("k"))
assertPosition(49, 0)
assertVisibleArea(33, 66)
// Scroll
typeText(injector.parser.parseKeys("k"))
assertPosition(48, 0)
assertVisibleArea(32, 65)
}
@TestWithoutNeovim(SkipNeovimReason.OPTION)
@VimOptionTestConfiguration(VimTestOption(OptionConstants.scrolloffName, OptionValueType.NUMBER, "17"))
@VimBehaviorDiffers(description = "Moving up in Vim will always have 16 lines above the caret line. IdeaVim keeps 17")
fun `test move up when scrolloff is exactly screen height`() {
// Page height = 34. scrolloff=17
// 2 possible caret lines without scrolling (49 + 50)
configureByPages(5)
setEditorVisibleSize(screenWidth, 34)
setPositionAndScroll(33, 50)
typeText(injector.parser.parseKeys("k"))
assertPosition(49, 0)
assertVisibleArea(33, 66)
// Scroll
typeText(injector.parser.parseKeys("k"))
assertPosition(48, 0)
assertVisibleArea(32, 65)
}
@TestWithoutNeovim(SkipNeovimReason.OPTION)
@VimOptionTestConfiguration(VimTestOption(OptionConstants.scrolloffName, OptionValueType.NUMBER, "17"))
fun `test move up when scrolloff is slightly greater than screen height keeps cursor in centre of screen`() {
// Page height = 35. scrolloff=17
configureByPages(5)
setPositionAndScroll(33, 50)
typeText(injector.parser.parseKeys("k"))
assertPosition(49, 0)
assertVisibleArea(32, 66)
}
@TestWithoutNeovim(SkipNeovimReason.OPTION)
@VimOptionTestConfiguration(VimTestOption(OptionConstants.scrolloffName, OptionValueType.NUMBER, "22"))
fun `test move up when scrolloff is slightly greater than screen height keeps cursor in centre of screen 2`() {
// Page height = 35. scrolloff=17
configureByPages(5)
setPositionAndScroll(33, 50)
typeText(injector.parser.parseKeys("k"))
assertPosition(49, 0)
assertVisibleArea(32, 66)
}
@TestWithoutNeovim(SkipNeovimReason.OPTION)
@VimOptionTestConfiguration(VimTestOption(OptionConstants.scrolloffName, OptionValueType.NUMBER, "0"))
fun `test move down shows no context with scrolloff=0`() {
configureByPages(5)
setPositionAndScroll(25, 59)
typeText(injector.parser.parseKeys("j"))
assertPosition(60, 0)
assertVisibleArea(26, 60)
}
@TestWithoutNeovim(SkipNeovimReason.OPTION)
@VimOptionTestConfiguration(VimTestOption(OptionConstants.scrolloffName, OptionValueType.NUMBER, "1"))
fun `test move down shows context line with scrolloff=1`() {
configureByPages(5)
setPositionAndScroll(25, 58)
typeText(injector.parser.parseKeys("j"))
assertPosition(59, 0)
assertVisibleArea(26, 60)
}
@TestWithoutNeovim(SkipNeovimReason.OPTION)
@VimOptionTestConfiguration(VimTestOption(OptionConstants.scrolloffName, OptionValueType.NUMBER, "10"))
fun `test move down shows context lines with scrolloff=10`() {
configureByPages(5)
setPositionAndScroll(25, 49)
typeText(injector.parser.parseKeys("j"))
assertPosition(50, 0)
assertVisibleArea(26, 60)
}
@TestWithoutNeovim(SkipNeovimReason.OPTION)
@VimOptionTestConfiguration(VimTestOption(OptionConstants.scrolloffName, OptionValueType.NUMBER, "15"))
fun `test move down when scrolloff is slightly less than half screen height`() {
// Screen height = 35. scrolloff=15. This gives 5 possible caret lines without scrolling (48, 49, 50, 51 + 52)
configureByPages(5)
setPositionAndScroll(33, 48)
typeText(injector.parser.parseKeys("j"))
assertPosition(49, 0)
assertVisibleArea(33, 67)
typeText(injector.parser.parseKeys("j"))
assertPosition(50, 0)
assertVisibleArea(33, 67)
typeText(injector.parser.parseKeys("j"))
assertPosition(51, 0)
assertVisibleArea(33, 67)
typeText(injector.parser.parseKeys("j"))
assertPosition(52, 0)
assertVisibleArea(33, 67)
// Scroll
typeText(injector.parser.parseKeys("j"))
assertPosition(53, 0)
assertVisibleArea(34, 68)
}
@TestWithoutNeovim(SkipNeovimReason.OPTION)
@VimOptionTestConfiguration(VimTestOption(OptionConstants.scrolloffName, OptionValueType.NUMBER, "16"))
fun `test move down when scrolloff is slightly less than half screen height 2`() {
// Screen height = 35. scrolloff=16. This gives 3 possible caret lines without scrolling (49, 50 + 51)
configureByPages(5)
setPositionAndScroll(33, 49)
typeText(injector.parser.parseKeys("j"))
assertPosition(50, 0)
assertVisibleArea(33, 67)
typeText(injector.parser.parseKeys("j"))
assertPosition(51, 0)
assertVisibleArea(33, 67)
// Scroll
typeText(injector.parser.parseKeys("j"))
assertPosition(52, 0)
assertVisibleArea(34, 68)
}
@TestWithoutNeovim(SkipNeovimReason.OPTION)
@VimOptionTestConfiguration(VimTestOption(OptionConstants.scrolloffName, OptionValueType.NUMBER, "16"))
fun `test move down when scrolloff is slightly less than half screen height 3`() {
// Screen height = 34. scrolloff=16
// Even numbers. 2 possible caret lines without scrolling (49 + 50)
configureByPages(5)
setEditorVisibleSize(screenWidth, 34)
setPositionAndScroll(33, 49)
typeText(injector.parser.parseKeys("j"))
assertPosition(50, 0)
assertVisibleArea(33, 66)
// Scroll
typeText(injector.parser.parseKeys("j"))
assertPosition(51, 0)
assertVisibleArea(34, 67)
}
@TestWithoutNeovim(SkipNeovimReason.OPTION)
@VimOptionTestConfiguration(VimTestOption(OptionConstants.scrolloffName, OptionValueType.NUMBER, "17"))
fun `test move down when scrolloff is exactly screen height`() {
// Page height = 34. scrolloff=17
// 2 possible caret lines without scrolling (49 + 50), but moving to line 51 will scroll 2 lines!
configureByPages(5)
setEditorVisibleSize(screenWidth, 34)
setPositionAndScroll(33, 49)
typeText(injector.parser.parseKeys("j"))
assertPosition(50, 0)
assertVisibleArea(33, 66)
// Scroll. By 2 lines!
typeText(injector.parser.parseKeys("j"))
assertPosition(51, 0)
assertVisibleArea(35, 68)
}
@TestWithoutNeovim(SkipNeovimReason.OPTION)
@VimOptionTestConfiguration(VimTestOption(OptionConstants.scrolloffName, OptionValueType.NUMBER, "17"))
fun `test move down when scrolloff is slightly greater than half screen height keeps cursor in centre of screen`() {
// Page height = 35. scrolloff=17
configureByPages(5)
setPositionAndScroll(33, 50)
typeText(injector.parser.parseKeys("j"))
assertPosition(51, 0)
assertVisibleArea(34, 68)
}
@TestWithoutNeovim(SkipNeovimReason.OPTION)
@VimOptionTestConfiguration(VimTestOption(OptionConstants.scrolloffName, OptionValueType.NUMBER, "22"))
fun `test move down when scrolloff is slightly greater than half screen height keeps cursor in centre of screen 2`() {
// Page height = 35. scrolloff=17
configureByPages(5)
setPositionAndScroll(33, 50)
typeText(injector.parser.parseKeys("j"))
assertPosition(51, 0)
assertVisibleArea(34, 68)
}
@TestWithoutNeovim(SkipNeovimReason.OPTION)
@VimOptionTestConfiguration(VimTestOption(OptionConstants.scrolloffName, OptionValueType.NUMBER, "999"))
fun `test scrolloff=999 keeps cursor in centre of screen`() {
configureByPages(5)
setPositionAndScroll(25, 42)
typeText(injector.parser.parseKeys("j"))
assertPosition(43, 0)
assertVisibleArea(26, 60)
typeText(injector.parser.parseKeys("k"))
assertPosition(42, 0)
assertVisibleArea(25, 59)
}
@TestWithoutNeovim(SkipNeovimReason.OPTION)
@VimOptionTestConfiguration(VimTestOption(OptionConstants.scrolloffName, OptionValueType.NUMBER, "999"))
fun `test scrolloff=999 keeps cursor in centre of screen with even screen height`() {
configureByPages(5)
setEditorVisibleSize(screenWidth, 34)
setPositionAndScroll(26, 42)
typeText(injector.parser.parseKeys("j"))
assertPosition(43, 0)
assertVisibleArea(27, 60)
typeText(injector.parser.parseKeys("k"))
assertPosition(42, 0)
assertVisibleArea(26, 59)
}
@TestWithoutNeovim(SkipNeovimReason.OPTION)
@VimOptionTestConfiguration(VimTestOption(OptionConstants.scrolloffName, OptionValueType.NUMBER, "0"))
fun `test reposition cursor when scrolloff is set`() {
configureByPages(5)
setPositionAndScroll(50, 50)
VimPlugin.getOptionService().setOptionValue(OptionScope.GLOBAL, OptionConstants.scrolloffName, VimInt(999))
assertPosition(50, 0)
assertVisibleArea(33, 67)
}
}
class MotionGroup_scrolljump_Test : VimOptionTestCase(OptionConstants.scrolljumpName) {
@TestWithoutNeovim(SkipNeovimReason.OPTION)
@VimOptionTestConfiguration(VimTestOption(OptionConstants.scrolljumpName, OptionValueType.NUMBER, "0"))
fun `test move up scrolls single line with scrolljump=0`() {
configureByPages(5)
setPositionAndScroll(25, 25)
typeText(injector.parser.parseKeys("k"))
assertPosition(24, 0)
assertVisibleArea(24, 58)
}
@TestWithoutNeovim(SkipNeovimReason.OPTION)
@VimOptionTestConfiguration(VimTestOption(OptionConstants.scrolljumpName, OptionValueType.NUMBER, "1"))
fun `test move up scrolls single line with scrolljump=1`() {
configureByPages(5)
setPositionAndScroll(25, 25)
typeText(injector.parser.parseKeys("k"))
assertPosition(24, 0)
assertVisibleArea(24, 58)
}
@TestWithoutNeovim(SkipNeovimReason.OPTION)
@VimOptionTestConfiguration(VimTestOption(OptionConstants.scrolljumpName, OptionValueType.NUMBER, "10"))
fun `test move up scrolls multiple lines with scrolljump=10`() {
configureByPages(5)
setPositionAndScroll(25, 25)
typeText(injector.parser.parseKeys("k"))
assertPosition(24, 0)
assertVisibleArea(15, 49)
}
@TestWithoutNeovim(SkipNeovimReason.OPTION)
@VimOptionTestConfiguration(VimTestOption(OptionConstants.scrolljumpName, OptionValueType.NUMBER, "0"))
fun `test move down scrolls single line with scrolljump=0`() {
configureByPages(5)
setPositionAndScroll(25, 59)
typeText(injector.parser.parseKeys("j"))
assertPosition(60, 0)
assertVisibleArea(26, 60)
}
@TestWithoutNeovim(SkipNeovimReason.OPTION)
@VimOptionTestConfiguration(VimTestOption(OptionConstants.scrolljumpName, OptionValueType.NUMBER, "1"))
fun `test move down scrolls single line with scrolljump=1`() {
configureByPages(5)
setPositionAndScroll(25, 59)
typeText(injector.parser.parseKeys("j"))
assertPosition(60, 0)
assertVisibleArea(26, 60)
}
@TestWithoutNeovim(SkipNeovimReason.OPTION)
@VimOptionTestConfiguration(VimTestOption(OptionConstants.scrolljumpName, OptionValueType.NUMBER, "10"))
fun `test move down scrolls multiple lines with scrolljump=10`() {
configureByPages(5)
setPositionAndScroll(25, 59)
typeText(injector.parser.parseKeys("j"))
assertPosition(60, 0)
assertVisibleArea(35, 69)
}
@TestWithoutNeovim(SkipNeovimReason.OPTION)
@VimOptionTestConfiguration(VimTestOption(OptionConstants.scrolljumpName, OptionValueType.NUMBER, "-50"))
fun `test negative scrolljump treated as percentage 1`() {
configureByPages(5)
setPositionAndScroll(39, 39)
typeText(injector.parser.parseKeys("k"))
assertPosition(38, 0)
assertVisibleArea(22, 56)
}
@TestWithoutNeovim(SkipNeovimReason.OPTION)
@VimOptionTestConfiguration(VimTestOption(OptionConstants.scrolljumpName, OptionValueType.NUMBER, "-10"))
fun `test negative scrolljump treated as percentage 2`() {
configureByPages(5)
setPositionAndScroll(39, 39)
typeText(injector.parser.parseKeys("k"))
assertPosition(38, 0)
assertVisibleArea(36, 70)
}
}
class MotionGroup_scrolloff_scrolljump_Test : VimOptionTestCase(OptionConstants.scrolljumpName, OptionConstants.scrolloffName) {
@TestWithoutNeovim(SkipNeovimReason.OPTION)
@VimOptionTestConfiguration(
VimTestOption(OptionConstants.scrolljumpName, OptionValueType.NUMBER, "10"),
VimTestOption(OptionConstants.scrolloffName, OptionValueType.NUMBER, "5")
)
fun `test scroll up with scrolloff and scrolljump set`() {
configureByPages(5)
setPositionAndScroll(50, 55)
typeText(injector.parser.parseKeys("k"))
assertPosition(54, 0)
assertVisibleArea(40, 74)
}
@TestWithoutNeovim(SkipNeovimReason.OPTION)
@VimOptionTestConfiguration(
VimTestOption(OptionConstants.scrolljumpName, OptionValueType.NUMBER, "10"),
VimTestOption(OptionConstants.scrolloffName, OptionValueType.NUMBER, "5")
)
fun `test scroll down with scrolloff and scrolljump set`() {
configureByPages(5)
setPositionAndScroll(50, 79)
typeText(injector.parser.parseKeys("j"))
assertPosition(80, 0)
assertVisibleArea(60, 94)
}
}
| mit | dca0c8ca2f8f539c633d9b610019309c | 35.772532 | 128 | 0.748133 | 4.307692 | false | true | false | false |
DiUS/pact-jvm | provider/maven/src/main/kotlin/au/com/dius/pact/provider/maven/PactPublishMojo.kt | 1 | 3985 | package au.com.dius.pact.provider.maven
import au.com.dius.pact.core.pactbroker.PactBrokerClient
import au.com.dius.pact.core.pactbroker.RequestFailedException
import au.com.dius.pact.core.support.isNotEmpty
import com.github.michaelbull.result.Err
import com.github.michaelbull.result.Ok
import org.apache.maven.plugin.MojoExecutionException
import org.apache.maven.plugins.annotations.Mojo
import org.apache.maven.plugins.annotations.Parameter
import java.io.File
/**
* Task to push pact files to a pact broker
*/
@Mojo(name = "publish")
open class PactPublishMojo : PactBaseMojo() {
@Parameter(defaultValue = "false", expression = "\${skipPactPublish}")
private var skipPactPublish: Boolean = false
@Parameter(required = true, defaultValue = "\${project.version}", property = "pact.projectVersion")
private lateinit var projectVersion: String
@Parameter(defaultValue = "false", property = "pact.trimSnapshot")
private var trimSnapshot: Boolean = false
@Parameter(defaultValue = "\${project.build.directory}/pacts", property = "pact.pactDirectory")
private lateinit var pactDirectory: String
private var brokerClient: PactBrokerClient? = null
@Parameter
private var tags: MutableList<String> = mutableListOf()
@Parameter
private var excludes: MutableList<String> = mutableListOf()
override fun execute() {
if (skipPactPublish) {
println("'skipPactPublish' is set to true, skipping uploading of pacts")
return
}
if (pactBrokerUrl.isNullOrEmpty() && brokerClient == null) {
throw MojoExecutionException("pactBrokerUrl is required")
}
val snapShotDefinitionString = "-SNAPSHOT"
if (trimSnapshot && projectVersion.contains(snapShotDefinitionString)) {
val snapshotRegex = Regex(".*($snapShotDefinitionString)")
projectVersion = projectVersion.removeRange(snapshotRegex.find(projectVersion)!!.groups[1]!!.range)
}
if (brokerClient == null) {
brokerClient = PactBrokerClient(pactBrokerUrl!!, brokerClientOptions())
}
val pactDirectory = File(pactDirectory)
if (!pactDirectory.exists()) {
println("Pact directory $pactDirectory does not exist, skipping uploading of pacts")
} else {
val excludedList = this.excludes.map { Regex(it) }
var anyFailed = false
pactDirectory.walkTopDown().filter { it.isFile && it.extension == "json" }.forEach { pactFile ->
if (pactFileIsExcluded(excludedList, pactFile)) {
println("Not publishing '${pactFile.name}' as it matches an item in the excluded list")
} else {
val tagsToPublish = calculateTags()
if (tagsToPublish.isNotEmpty()) {
print("Publishing '${pactFile.name}' with tags '${tagsToPublish.joinToString(", ")}' ... ")
} else {
print("Publishing '${pactFile.name}' ... ")
}
when (val result = brokerClient!!.uploadPactFile(pactFile, projectVersion, tagsToPublish)) {
is Ok -> println("OK")
is Err -> {
val error = result.error
println("Failed - ${result.error.message}")
if (error is RequestFailedException && error.body.isNotEmpty()) {
println(error.body)
}
anyFailed = true
}
}
}
}
if (anyFailed) {
throw MojoExecutionException("One or more of the pact files were rejected by the pact broker")
}
}
}
private fun calculateTags(): List<String> {
val property = System.getProperty("pact.consumer.tags")
return if (property.isNotEmpty()) {
property.split(',').map { it.trim() }
} else {
tags
}
}
private fun pactFileIsExcluded(exclusions: List<Regex>, pactFile: File) =
exclusions.any { it.matches(pactFile.nameWithoutExtension) }
}
| apache-2.0 | 470b1655afce64d6059ac03a4e2a8320 | 36.242991 | 107 | 0.645671 | 4.507919 | false | false | false | false |
ingokegel/intellij-community | platform/workspaceModel/storage/testEntities/gen/com/intellij/workspaceModel/storage/entities/test/api/RightEntityImpl.kt | 1 | 13199 | package com.intellij.workspaceModel.storage.entities.test.api
import com.intellij.workspaceModel.storage.*
import com.intellij.workspaceModel.storage.EntityInformation
import com.intellij.workspaceModel.storage.EntitySource
import com.intellij.workspaceModel.storage.EntityStorage
import com.intellij.workspaceModel.storage.GeneratedCodeApiVersion
import com.intellij.workspaceModel.storage.GeneratedCodeImplVersion
import com.intellij.workspaceModel.storage.ModifiableWorkspaceEntity
import com.intellij.workspaceModel.storage.MutableEntityStorage
import com.intellij.workspaceModel.storage.WorkspaceEntity
import com.intellij.workspaceModel.storage.impl.ConnectionId
import com.intellij.workspaceModel.storage.impl.EntityLink
import com.intellij.workspaceModel.storage.impl.ModifiableWorkspaceEntityBase
import com.intellij.workspaceModel.storage.impl.UsedClassesCollector
import com.intellij.workspaceModel.storage.impl.WorkspaceEntityBase
import com.intellij.workspaceModel.storage.impl.WorkspaceEntityData
import com.intellij.workspaceModel.storage.impl.extractOneToAbstractManyChildren
import com.intellij.workspaceModel.storage.impl.extractOneToAbstractManyParent
import com.intellij.workspaceModel.storage.impl.extractOneToAbstractOneParent
import com.intellij.workspaceModel.storage.impl.extractOneToManyChildren
import com.intellij.workspaceModel.storage.impl.updateOneToAbstractManyChildrenOfParent
import com.intellij.workspaceModel.storage.impl.updateOneToAbstractManyParentOfChild
import com.intellij.workspaceModel.storage.impl.updateOneToAbstractOneParentOfChild
import org.jetbrains.deft.ObjBuilder
import org.jetbrains.deft.Type
import org.jetbrains.deft.annotations.Abstract
import org.jetbrains.deft.annotations.Child
@GeneratedCodeApiVersion(1)
@GeneratedCodeImplVersion(1)
open class RightEntityImpl : RightEntity, WorkspaceEntityBase() {
companion object {
internal val PARENTENTITY_CONNECTION_ID: ConnectionId = ConnectionId.create(CompositeBaseEntity::class.java, BaseEntity::class.java,
ConnectionId.ConnectionType.ONE_TO_ABSTRACT_MANY, true)
internal val CHILDREN_CONNECTION_ID: ConnectionId = ConnectionId.create(CompositeBaseEntity::class.java, BaseEntity::class.java,
ConnectionId.ConnectionType.ONE_TO_ABSTRACT_MANY, true)
internal val PARENT_CONNECTION_ID: ConnectionId = ConnectionId.create(HeadAbstractionEntity::class.java,
CompositeBaseEntity::class.java,
ConnectionId.ConnectionType.ABSTRACT_ONE_TO_ONE, true)
val connections = listOf<ConnectionId>(
PARENTENTITY_CONNECTION_ID,
CHILDREN_CONNECTION_ID,
PARENT_CONNECTION_ID,
)
}
override val parentEntity: CompositeBaseEntity?
get() = snapshot.extractOneToAbstractManyParent(PARENTENTITY_CONNECTION_ID, this)
override val children: List<BaseEntity>
get() = snapshot.extractOneToAbstractManyChildren<BaseEntity>(CHILDREN_CONNECTION_ID, this)!!.toList()
override val parent: HeadAbstractionEntity?
get() = snapshot.extractOneToAbstractOneParent(PARENT_CONNECTION_ID, this)
override fun connectionIdList(): List<ConnectionId> {
return connections
}
class Builder(val result: RightEntityData?) : ModifiableWorkspaceEntityBase<RightEntity>(), RightEntity.Builder {
constructor() : this(RightEntityData())
override fun applyToBuilder(builder: MutableEntityStorage) {
if (this.diff != null) {
if (existsInBuilder(builder)) {
this.diff = builder
return
}
else {
error("Entity RightEntity is already created in a different builder")
}
}
this.diff = builder
this.snapshot = builder
addToBuilder()
this.id = getEntityData().createEntityId()
// Process linked entities that are connected without a builder
processLinkedEntities(builder)
checkInitialization() // TODO uncomment and check failed tests
}
fun checkInitialization() {
val _diff = diff
if (!getEntityData().isEntitySourceInitialized()) {
error("Field WorkspaceEntity#entitySource should be initialized")
}
// Check initialization for list with ref type
if (_diff != null) {
if (_diff.extractOneToManyChildren<WorkspaceEntityBase>(CHILDREN_CONNECTION_ID, this) == null) {
error("Field CompositeBaseEntity#children should be initialized")
}
}
else {
if (this.entityLinks[EntityLink(true, CHILDREN_CONNECTION_ID)] == null) {
error("Field CompositeBaseEntity#children should be initialized")
}
}
}
override fun connectionIdList(): List<ConnectionId> {
return connections
}
// Relabeling code, move information from dataSource to this builder
override fun relabel(dataSource: WorkspaceEntity, parents: Set<WorkspaceEntity>?) {
dataSource as RightEntity
this.entitySource = dataSource.entitySource
if (parents != null) {
this.parentEntity = parents.filterIsInstance<CompositeBaseEntity>().singleOrNull()
this.parent = parents.filterIsInstance<HeadAbstractionEntity>().singleOrNull()
}
}
override var entitySource: EntitySource
get() = getEntityData().entitySource
set(value) {
checkModificationAllowed()
getEntityData().entitySource = value
changedProperty.add("entitySource")
}
override var parentEntity: CompositeBaseEntity?
get() {
val _diff = diff
return if (_diff != null) {
_diff.extractOneToAbstractManyParent(PARENTENTITY_CONNECTION_ID, this) ?: this.entityLinks[EntityLink(false,
PARENTENTITY_CONNECTION_ID)] as? CompositeBaseEntity
}
else {
this.entityLinks[EntityLink(false, PARENTENTITY_CONNECTION_ID)] as? CompositeBaseEntity
}
}
set(value) {
checkModificationAllowed()
val _diff = diff
if (_diff != null && value is ModifiableWorkspaceEntityBase<*> && value.diff == null) {
// Setting backref of the list
if (value is ModifiableWorkspaceEntityBase<*>) {
val data = (value.entityLinks[EntityLink(true, PARENTENTITY_CONNECTION_ID)] as? List<Any> ?: emptyList()) + this
value.entityLinks[EntityLink(true, PARENTENTITY_CONNECTION_ID)] = data
}
// else you're attaching a new entity to an existing entity that is not modifiable
_diff.addEntity(value)
}
if (_diff != null && (value !is ModifiableWorkspaceEntityBase<*> || value.diff != null)) {
_diff.updateOneToAbstractManyParentOfChild(PARENTENTITY_CONNECTION_ID, this, value)
}
else {
// Setting backref of the list
if (value is ModifiableWorkspaceEntityBase<*>) {
val data = (value.entityLinks[EntityLink(true, PARENTENTITY_CONNECTION_ID)] as? List<Any> ?: emptyList()) + this
value.entityLinks[EntityLink(true, PARENTENTITY_CONNECTION_ID)] = data
}
// else you're attaching a new entity to an existing entity that is not modifiable
this.entityLinks[EntityLink(false, PARENTENTITY_CONNECTION_ID)] = value
}
changedProperty.add("parentEntity")
}
override var children: List<BaseEntity>
get() {
val _diff = diff
return if (_diff != null) {
_diff.extractOneToAbstractManyChildren<BaseEntity>(CHILDREN_CONNECTION_ID, this)!!.toList() + (this.entityLinks[EntityLink(true,
CHILDREN_CONNECTION_ID)] as? List<BaseEntity>
?: emptyList())
}
else {
this.entityLinks[EntityLink(true, CHILDREN_CONNECTION_ID)] as List<BaseEntity> ?: emptyList()
}
}
set(value) {
checkModificationAllowed()
val _diff = diff
if (_diff != null) {
for (item_value in value) {
if (item_value is ModifiableWorkspaceEntityBase<*> && (item_value as? ModifiableWorkspaceEntityBase<*>)?.diff == null) {
_diff.addEntity(item_value)
}
}
_diff.updateOneToAbstractManyChildrenOfParent(CHILDREN_CONNECTION_ID, this, value.asSequence())
}
else {
for (item_value in value) {
if (item_value is ModifiableWorkspaceEntityBase<*>) {
item_value.entityLinks[EntityLink(false, CHILDREN_CONNECTION_ID)] = this
}
// else you're attaching a new entity to an existing entity that is not modifiable
}
this.entityLinks[EntityLink(true, CHILDREN_CONNECTION_ID)] = value
}
changedProperty.add("children")
}
override var parent: HeadAbstractionEntity?
get() {
val _diff = diff
return if (_diff != null) {
_diff.extractOneToAbstractOneParent(PARENT_CONNECTION_ID, this) ?: this.entityLinks[EntityLink(false,
PARENT_CONNECTION_ID)] as? HeadAbstractionEntity
}
else {
this.entityLinks[EntityLink(false, PARENT_CONNECTION_ID)] as? HeadAbstractionEntity
}
}
set(value) {
checkModificationAllowed()
val _diff = diff
if (_diff != null && value is ModifiableWorkspaceEntityBase<*> && value.diff == null) {
if (value is ModifiableWorkspaceEntityBase<*>) {
value.entityLinks[EntityLink(true, PARENT_CONNECTION_ID)] = this
}
// else you're attaching a new entity to an existing entity that is not modifiable
_diff.addEntity(value)
}
if (_diff != null && (value !is ModifiableWorkspaceEntityBase<*> || value.diff != null)) {
_diff.updateOneToAbstractOneParentOfChild(PARENT_CONNECTION_ID, this, value)
}
else {
if (value is ModifiableWorkspaceEntityBase<*>) {
value.entityLinks[EntityLink(true, PARENT_CONNECTION_ID)] = this
}
// else you're attaching a new entity to an existing entity that is not modifiable
this.entityLinks[EntityLink(false, PARENT_CONNECTION_ID)] = value
}
changedProperty.add("parent")
}
override fun getEntityData(): RightEntityData = result ?: super.getEntityData() as RightEntityData
override fun getEntityClass(): Class<RightEntity> = RightEntity::class.java
}
}
class RightEntityData : WorkspaceEntityData<RightEntity>() {
override fun wrapAsModifiable(diff: MutableEntityStorage): ModifiableWorkspaceEntity<RightEntity> {
val modifiable = RightEntityImpl.Builder(null)
modifiable.allowModifications {
modifiable.diff = diff
modifiable.snapshot = diff
modifiable.id = createEntityId()
modifiable.entitySource = this.entitySource
}
modifiable.changedProperty.clear()
return modifiable
}
override fun createEntity(snapshot: EntityStorage): RightEntity {
val entity = RightEntityImpl()
entity.entitySource = entitySource
entity.snapshot = snapshot
entity.id = createEntityId()
return entity
}
override fun getEntityInterface(): Class<out WorkspaceEntity> {
return RightEntity::class.java
}
override fun serialize(ser: EntityInformation.Serializer) {
}
override fun deserialize(de: EntityInformation.Deserializer) {
}
override fun createDetachedEntity(parents: List<WorkspaceEntity>): WorkspaceEntity {
return RightEntity(entitySource) {
this.parentEntity = parents.filterIsInstance<CompositeBaseEntity>().singleOrNull()
this.parent = parents.filterIsInstance<HeadAbstractionEntity>().singleOrNull()
}
}
override fun getRequiredParents(): List<Class<out WorkspaceEntity>> {
val res = mutableListOf<Class<out WorkspaceEntity>>()
return res
}
override fun equals(other: Any?): Boolean {
if (other == null) return false
if (this::class != other::class) return false
other as RightEntityData
if (this.entitySource != other.entitySource) return false
return true
}
override fun equalsIgnoringEntitySource(other: Any?): Boolean {
if (other == null) return false
if (this::class != other::class) return false
other as RightEntityData
return true
}
override fun hashCode(): Int {
var result = entitySource.hashCode()
return result
}
override fun hashCodeIgnoringEntitySource(): Int {
var result = javaClass.hashCode()
return result
}
override fun collectClassUsagesData(collector: UsedClassesCollector) {
collector.sameForAllEntities = true
}
}
| apache-2.0 | 8efe483bda9cfe0bd963d9cb36ffab0a | 39.990683 | 178 | 0.66202 | 5.513367 | false | false | false | false |
NativeScript/android-runtime | test-app/build-tools/android-metadata-generator/src/src/com/telerik/metadata/security/logging/console/MetadataFilterConsoleLogger.kt | 1 | 2449 | package com.telerik.metadata.security.logging.console
import com.telerik.metadata.security.filtering.MetadataFilterResult
import com.telerik.metadata.security.logging.MetadataFilterLogger
object MetadataFilterConsoleLogger : MetadataFilterLogger {
var isEnabled = false
override fun logAllowed(packageName: String, className: String, whitelistFilterResult: MetadataFilterResult, blacklistFilterResult: MetadataFilterResult) = logAction("Included", packageName, className, whitelistFilterResult, blacklistFilterResult)
override fun logDisallowed(packageName: String, className: String, whitelistFilterResult: MetadataFilterResult, blacklistFilterResult: MetadataFilterResult) = logAction("Blacklisted", packageName, className, whitelistFilterResult, blacklistFilterResult)
private fun logAction(action: String, packageName: String, className: String, whitelistFilterResult: MetadataFilterResult, blacklistFilterResult: MetadataFilterResult) {
if (isEnabled) {
val logBuilder = StringBuilder()
logBuilder
.append("verbose: ")
.append(action)
.append(" ")
.append(className)
.append(" from ")
.append(packageName)
val hasWhitelistPatternEntry = whitelistFilterResult.matchedPatternEntry.isPresent
val hasBlacklistPatternEntry = blacklistFilterResult.matchedPatternEntry.isPresent
if (hasWhitelistPatternEntry || hasBlacklistPatternEntry) {
logBuilder.append(" (")
var hasWrittenWhitelistingLog = false
if (hasWhitelistPatternEntry && whitelistFilterResult.isAllowed) {
logBuilder.append("enabled by ")
.append(whitelistFilterResult.matchedPatternEntry.get())
hasWrittenWhitelistingLog = true
}
if (hasBlacklistPatternEntry && !blacklistFilterResult.isAllowed) {
if (hasWrittenWhitelistingLog) {
logBuilder.append(", ")
}
logBuilder.append("disabled by ")
.append(blacklistFilterResult.matchedPatternEntry.get())
}
logBuilder.append(")")
}
val log = logBuilder.toString()
println(log)
}
}
} | apache-2.0 | a61fbb3a6e1a79ee270f98cfeb142df8 | 39.833333 | 257 | 0.641078 | 5.872902 | false | false | false | false |
mdaniel/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/editor/fixers/KotlinMissingWhenEntryBodyFixer.kt | 1 | 1444 | // 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.editor.fixers
import com.intellij.lang.SmartEnterProcessorWithFixers
import com.intellij.openapi.editor.Editor
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiErrorElement
import com.intellij.psi.util.PsiTreeUtil
import org.jetbrains.kotlin.idea.editor.KotlinSmartEnterHandler
import org.jetbrains.kotlin.psi.KtWhenEntry
class KotlinMissingWhenEntryBodyFixer : SmartEnterProcessorWithFixers.Fixer<KotlinSmartEnterHandler>() {
override fun apply(editor: Editor, processor: KotlinSmartEnterHandler, element: PsiElement) {
if (element !is KtWhenEntry || element.expression != null) return
val doc = editor.document
val arrow = element.arrow
if (arrow != null) {
doc.insertString(arrow.range.end, "{\n}")
} else {
val lastCondition = element.conditions.lastOrNull() ?: return
if (PsiTreeUtil.findChildOfType(lastCondition, PsiErrorElement::class.java) != null) return
val offset = lastCondition.range.end
val caretModel = editor.caretModel
if (doc.getLineNumber(caretModel.offset) == doc.getLineNumber(element.range.start)) caretModel.moveToOffset(offset)
doc.insertString(offset, "-> {\n}")
}
}
}
| apache-2.0 | 52b58d3ec4738a98fb1367aa91214342 | 48.793103 | 158 | 0.725762 | 4.658065 | false | false | false | false |
ingokegel/intellij-community | notebooks/visualization/src/org/jetbrains/plugins/notebooks/visualization/NotebookIntervalPointerImpl.kt | 1 | 5654 | package org.jetbrains.plugins.notebooks.visualization
import com.intellij.openapi.editor.Editor
import com.intellij.util.EventDispatcher
class NotebookIntervalPointerFactoryImplProvider : NotebookIntervalPointerFactoryProvider {
override fun create(editor: Editor): NotebookIntervalPointerFactory =
NotebookIntervalPointerFactoryImpl(NotebookCellLines.get(editor))
}
private class NotebookIntervalPointerImpl(var interval: NotebookCellLines.Interval?) : NotebookIntervalPointer {
override fun get(): NotebookCellLines.Interval? = interval
override fun toString(): String = "NotebookIntervalPointerImpl($interval)"
}
class NotebookIntervalPointerFactoryImpl(private val notebookCellLines: NotebookCellLines) : NotebookIntervalPointerFactory, NotebookCellLines.IntervalListener {
private val pointers = ArrayList<NotebookIntervalPointerImpl>()
private var mySavedChanges: Iterable<NotebookIntervalPointerFactory.Change>? = null
override val changeListeners: EventDispatcher<NotebookIntervalPointerFactory.ChangeListener> =
EventDispatcher.create(NotebookIntervalPointerFactory.ChangeListener::class.java)
init {
pointers.addAll(notebookCellLines.intervals.asSequence().map { NotebookIntervalPointerImpl(it) })
notebookCellLines.intervalListeners.addListener(this)
}
override fun create(interval: NotebookCellLines.Interval): NotebookIntervalPointer =
pointers[interval.ordinal].also {
require(it.interval == interval)
}
override fun <T> modifyingPointers(changes: Iterable<NotebookIntervalPointerFactory.Change>, modifyDocumentAction: () -> T): T {
try {
require(mySavedChanges == null) { "NotebookIntervalPointerFactory hints already added somewhere" }
mySavedChanges = changes
return modifyDocumentAction().also {
if (mySavedChanges != null) {
applyChanges()
}
}
}
finally {
mySavedChanges = null
}
}
override fun segmentChanged(e: NotebookCellLinesEvent) {
when {
!e.isIntervalsChanged() -> {
// content edited without affecting intervals values
onEdited((e.oldAffectedIntervals + e.newAffectedIntervals).distinct().sortedBy { it.ordinal })
}
e.oldIntervals.size == 1 && e.newIntervals.size == 1 && e.oldIntervals.first().type == e.newIntervals.first().type -> {
// only one interval changed size
pointers[e.newIntervals.first().ordinal].interval = e.newIntervals.first()
onEdited(e.newAffectedIntervals)
if (e.newIntervals.first() !in e.newAffectedIntervals) {
changeListeners.multicaster.onEdited(e.newIntervals.first().ordinal)
}
}
else -> {
for (old in e.oldIntervals.asReversed()) {
pointers[old.ordinal].interval = null
pointers.removeAt(old.ordinal)
// called in reversed order, so ordinals of previous cells remain actual
changeListeners.multicaster.onRemoved(old.ordinal)
}
e.newIntervals.firstOrNull()?.also { firstNew ->
pointers.addAll(firstNew.ordinal, e.newIntervals.map { NotebookIntervalPointerImpl(it) })
}
for (newInterval in e.newIntervals) {
changeListeners.multicaster.onInserted(newInterval.ordinal)
}
onEdited(e.newAffectedIntervals, excluded = e.newIntervals)
}
}
val invalidPointersStart =
e.newIntervals.firstOrNull()?.let { it.ordinal + e.newIntervals.size }
?: e.oldIntervals.firstOrNull()?.ordinal
?: pointers.size
updatePointersFrom(invalidPointersStart)
applyChanges()
}
private fun onEdited(intervals: List<NotebookCellLines.Interval>, excluded: List<NotebookCellLines.Interval> = emptyList()) {
if (intervals.isEmpty()) return
val overLast = intervals.last().ordinal + 1
val excludedRange = (excluded.firstOrNull()?.ordinal ?: overLast)..(excluded.lastOrNull()?.ordinal ?: overLast)
for (interval in intervals) {
if (interval.ordinal !in excludedRange) {
changeListeners.multicaster.onEdited(interval.ordinal)
}
}
}
private fun applyChanges() {
mySavedChanges?.forEach { hint ->
when (hint) {
is NotebookIntervalPointerFactory.Invalidate -> {
val ordinal = hint.ptr.get()?.ordinal
invalidate((hint.ptr as NotebookIntervalPointerImpl))
if (ordinal != null) {
changeListeners.multicaster.let { listener ->
listener.onRemoved(ordinal)
listener.onInserted(ordinal)
}
}
}
is NotebookIntervalPointerFactory.Reuse -> {
val oldPtr = hint.ptr as NotebookIntervalPointerImpl
pointers.getOrNull(hint.ordinalAfterChange)?.let { newPtr ->
if (oldPtr !== newPtr) {
val oldOrdinal = oldPtr.interval?.ordinal
invalidate(oldPtr)
oldPtr.interval = newPtr.interval
newPtr.interval = null
pointers[hint.ordinalAfterChange] = oldPtr
if (oldOrdinal != null && oldOrdinal != hint.ordinalAfterChange) {
changeListeners.multicaster.onMoved(oldOrdinal, hint.ordinalAfterChange)
}
}
}
}
}
}
mySavedChanges = null
}
private fun invalidate(ptr: NotebookIntervalPointerImpl) {
ptr.interval?.let { interval ->
pointers[interval.ordinal] = NotebookIntervalPointerImpl(interval)
ptr.interval = null
}
}
private fun updatePointersFrom(pos: Int) {
for (i in pos until pointers.size) {
pointers[i].interval = notebookCellLines.intervals[i]
}
}
} | apache-2.0 | 4809a17499ddf0970f5583b3644890b5 | 36.7 | 161 | 0.685356 | 4.861565 | false | false | false | false |
iPoli/iPoli-android | app/src/main/java/io/ipoli/android/store/membership/MembershipViewState.kt | 1 | 3998 | package io.ipoli.android.store.membership
import io.ipoli.android.common.AppState
import io.ipoli.android.common.BaseViewStateReducer
import io.ipoli.android.common.redux.Action
import io.ipoli.android.common.redux.BaseViewState
import io.ipoli.android.store.membership.MembershipViewState.StateType.*
/**
* Created by Polina Zhelyazkova <[email protected]>
* on 3/16/18.
*/
sealed class MembershipAction : Action {
data class Load(
val monthlyPrice: Price,
val quarterlyPrice: Price,
val yearlyPrice: Price,
val activeSku: String?
) : MembershipAction()
data class Loaded(
val monthlyPrice: String,
val yearlyPrice: String,
val quarterlyPrice: String,
val activeSku: String?
) : MembershipAction() {
override fun toMap() = mapOf(
"monthlyPrice" to monthlyPrice,
"yearlyPrice" to yearlyPrice,
"quarterlyPrice" to quarterlyPrice,
"activeSku" to activeSku
)
}
data class SelectPlan(val plan: MembershipPlan) : MembershipAction() {
override fun toMap() = mapOf("plan" to plan)
}
data class Subscribed(
val sku: String,
val purchaseTime: Long,
val purchaseToken: String
) :
MembershipAction() {
override fun toMap() = mapOf("plan" to sku, "purchaseTime" to purchaseTime)
}
}
object MembershipReducer : BaseViewStateReducer<MembershipViewState>() {
override val stateKey = key<MembershipViewState>()
override fun reduce(
state: AppState,
subState: MembershipViewState,
action: Action
): MembershipViewState {
return when (action) {
is MembershipAction.Loaded -> {
val currentPlan = MembershipPlan.values().firstOrNull { it.sku == action.activeSku }
subState.copy(
type = DATA_CHANGED,
currentPlan = currentPlan,
showCurrentPlan = currentPlan != null && currentPlan == subState.selectedPlan,
monthlyPlanPrice = action.monthlyPrice,
yearlyPlanPrice = action.yearlyPrice,
quarterlyPlanPrice = action.quarterlyPrice,
activeSku = action.activeSku
)
}
is MembershipAction.Subscribed -> {
val plan = MembershipPlan.values().first { it.sku == action.sku }
subState.copy(
type = SUBSCRIBED,
currentPlan = plan,
showCurrentPlan = plan == subState.selectedPlan,
activeSku = action.sku
)
}
is MembershipAction.SelectPlan -> {
subState.copy(
type = DATA_CHANGED,
selectedPlan = action.plan,
showCurrentPlan = action.plan == subState.currentPlan
)
}
else -> subState
}
}
override fun defaultState() = MembershipViewState(
type = LOADING,
selectedPlan = MembershipPlan.YEARLY,
currentPlan = null,
showCurrentPlan = false,
monthlyPlanPrice = "0.00",
quarterlyPlanPrice = "0.00",
yearlyPlanPrice = "0.00",
activeSku = null
)
}
data class Price(val amount: Long, val currency: String)
enum class MembershipPlan(val sku: String) {
MONTHLY("monthly_plan_70_percent"),
YEARLY("yearly_plan_70_percent"),
QUARTERLY("quarterly_plan_70_percent")
}
data class MembershipViewState(
val type: StateType,
val selectedPlan: MembershipPlan,
val currentPlan: MembershipPlan?,
val showCurrentPlan: Boolean,
val monthlyPlanPrice: String,
val quarterlyPlanPrice: String,
val yearlyPlanPrice: String,
val activeSku: String?
) : BaseViewState() {
enum class StateType {
LOADING,
DATA_CHANGED,
SUBSCRIBED
}
}
| gpl-3.0 | 40a7549a21e6f47ccefba1cdcc17f417 | 29.519084 | 100 | 0.596548 | 4.659674 | false | false | false | false |
GunoH/intellij-community | platform/platform-impl/src/com/intellij/featureStatistics/fusCollectors/WSLInstallationsCollector.kt | 7 | 1781 | // 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.featureStatistics.fusCollectors
import com.intellij.execution.wsl.WSLUtil
import com.intellij.execution.wsl.WslDistributionManager
import com.intellij.internal.statistic.beans.MetricEvent
import com.intellij.internal.statistic.eventLog.EventLogGroup
import com.intellij.internal.statistic.eventLog.events.EventFields
import com.intellij.internal.statistic.service.fus.collectors.ApplicationUsagesCollector
import com.intellij.openapi.diagnostic.logger
import java.io.IOException
import java.lang.IllegalStateException
class WSLInstallationsCollector : ApplicationUsagesCollector() {
companion object {
private val group = EventLogGroup("wsl.installations", 1)
private val installationCountEvent = group.registerEvent("count", EventFields.Int("version"), EventFields.Int("count"))
private val LOG = logger<WSLInstallationsCollector>()
}
override fun getGroup(): EventLogGroup {
return Companion.group
}
override fun getMetrics(): Set<MetricEvent> {
if (!WSLUtil.isSystemCompatible()) return emptySet()
val distributionsWithVersions = try {
WslDistributionManager.getInstance().loadInstalledDistributionsWithVersions()
}
catch(e: IOException) {
LOG.warn("Failed to load installed WSL distributions: " + e.message)
return emptySet()
}
catch (e: IllegalStateException) {
LOG.error(e)
return emptySet()
}
val installations = distributionsWithVersions.groupBy { it.version }
return installations.mapNotNullTo(HashSet()) { (version, distributions) ->
installationCountEvent.metric(version, distributions.size)
}
}
}
| apache-2.0 | 181c311ad144e77f5ae15e6b0ebedde6 | 38.577778 | 140 | 0.769231 | 4.699208 | false | false | false | false |
GunoH/intellij-community | plugins/search-everywhere-ml/src/com/intellij/ide/actions/searcheverywhere/ml/features/SearchEverywhereActionFeaturesProvider.kt | 7 | 10851 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.ide.actions.searcheverywhere.ml.features
import com.intellij.ide.actions.SearchEverywhereBaseAction
import com.intellij.ide.actions.searcheverywhere.ActionSearchEverywhereContributor
import com.intellij.ide.actions.searcheverywhere.TopHitSEContributor
import com.intellij.ide.actions.searcheverywhere.ml.features.SearchEverywhereGeneralActionFeaturesProvider.Companion.IS_ENABLED
import com.intellij.ide.util.gotoByName.GotoActionModel
import com.intellij.ide.util.gotoByName.GotoActionModel.ActionWrapper
import com.intellij.ide.util.gotoByName.MatchMode
import com.intellij.internal.statistic.eventLog.events.EventField
import com.intellij.internal.statistic.eventLog.events.EventFields
import com.intellij.internal.statistic.eventLog.events.EventPair
import com.intellij.internal.statistic.local.ActionGlobalUsageInfo
import com.intellij.internal.statistic.local.ActionsGlobalSummaryManager
import com.intellij.internal.statistic.local.ActionsLocalSummary
import com.intellij.internal.statistic.utils.getPluginInfo
import com.intellij.openapi.actionSystem.ActionManager
import com.intellij.openapi.actionSystem.AnAction
import com.intellij.openapi.actionSystem.ToggleAction
import com.intellij.openapi.components.service
import com.intellij.openapi.editor.actionSystem.EditorAction
import com.intellij.util.Time
internal class SearchEverywhereActionFeaturesProvider :
SearchEverywhereElementFeaturesProvider(ActionSearchEverywhereContributor::class.java, TopHitSEContributor::class.java) {
companion object {
internal val IS_ACTION_DATA_KEY = EventFields.Boolean("isAction")
internal val IS_TOGGLE_ACTION_DATA_KEY = EventFields.Boolean("isToggleAction")
internal val IS_EDITOR_ACTION = EventFields.Boolean("isEditorAction")
internal val IS_SEARCH_ACTION = EventFields.Boolean("isSearchAction")
internal val MATCH_MODE_KEY = EventFields.Enum<MatchMode>("matchMode")
internal val TEXT_LENGTH_KEY = EventFields.Int("textLength")
internal val IS_GROUP_KEY = EventFields.Boolean("isGroup")
internal val GROUP_LENGTH_KEY = EventFields.Int("groupLength")
internal val HAS_ICON_KEY = EventFields.Boolean("withIcon")
internal val WEIGHT_KEY = EventFields.Double("weight")
internal val PLUGIN_TYPE = EventFields.StringValidatedByEnum("pluginType", "plugin_type")
internal val PLUGIN_ID = EventFields.StringValidatedByCustomRule("pluginId", "plugin")
private val GLOBAL_STATISTICS_DEFAULT = GlobalStatisticsFields(ActionsGlobalSummaryManager.getDefaultStatisticsVersion())
private val GLOBAL_STATISTICS_UPDATED = GlobalStatisticsFields(ActionsGlobalSummaryManager.getUpdatedStatisticsVersion())
internal val USAGE = EventFields.Int("usage")
internal val USAGE_SE = EventFields.Int("usageSe")
internal val USAGE_TO_MAX = EventFields.Double("usageToMax")
internal val USAGE_TO_MAX_SE = EventFields.Double("usageToMaxSe")
internal val TIME_SINCE_LAST_USAGE = EventFields.Long("timeSinceLastUsage")
internal val TIME_SINCE_LAST_USAGE_SE = EventFields.Long("timeSinceLastUsageSe")
internal val WAS_USED_IN_LAST_MINUTE = EventFields.Boolean("wasUsedInLastMinute")
internal val WAS_USED_IN_LAST_MINUTE_SE = EventFields.Boolean("wasUsedInLastMinuteSe")
internal val WAS_USED_IN_LAST_HOUR = EventFields.Boolean("wasUsedInLastHour")
internal val WAS_USED_IN_LAST_HOUR_SE = EventFields.Boolean("wasUsedInLastHourSe")
internal val WAS_USED_IN_LAST_DAY = EventFields.Boolean("wasUsedInLastDay")
internal val WAS_USED_IN_LAST_DAY_SE = EventFields.Boolean("wasUsedInLastDaySe")
internal val WAS_USED_IN_LAST_MONTH = EventFields.Boolean("wasUsedInLastMonth")
internal val WAS_USED_IN_LAST_MONTH_SE = EventFields.Boolean("wasUsedInLastMonthSe")
}
override fun getFeaturesDeclarations(): List<EventField<*>> {
val fields = arrayListOf<EventField<*>>(
IS_ACTION_DATA_KEY, IS_TOGGLE_ACTION_DATA_KEY, IS_EDITOR_ACTION, IS_SEARCH_ACTION,
MATCH_MODE_KEY, TEXT_LENGTH_KEY, IS_GROUP_KEY, GROUP_LENGTH_KEY, HAS_ICON_KEY, WEIGHT_KEY,
PLUGIN_TYPE, PLUGIN_ID,
USAGE, USAGE_SE, USAGE_TO_MAX, USAGE_TO_MAX_SE,
TIME_SINCE_LAST_USAGE, TIME_SINCE_LAST_USAGE_SE,
WAS_USED_IN_LAST_MINUTE, WAS_USED_IN_LAST_MINUTE_SE,
WAS_USED_IN_LAST_HOUR, WAS_USED_IN_LAST_HOUR_SE,
WAS_USED_IN_LAST_DAY, WAS_USED_IN_LAST_DAY_SE,
WAS_USED_IN_LAST_MONTH, WAS_USED_IN_LAST_MONTH_SE,
)
fields.addAll(GLOBAL_STATISTICS_DEFAULT.getFieldsDeclaration() + GLOBAL_STATISTICS_UPDATED.getFieldsDeclaration())
return fields
}
override fun getElementFeatures(element: Any,
currentTime: Long,
searchQuery: String,
elementPriority: Int,
cache: FeaturesProviderCache?): List<EventPair<*>> {
val value = if (element is GotoActionModel.MatchedValue) element.value else element
val action = getAnAction(value) ?: return emptyList()
val data = arrayListOf<EventPair<*>>()
data.add(IS_ACTION_DATA_KEY.with(true))
if (value is ActionWrapper) {
data.add(MATCH_MODE_KEY.with(value.mode))
data.add(IS_GROUP_KEY.with(value.isGroupAction))
value.actionText?.let {
data.add(TEXT_LENGTH_KEY.with(withUpperBound(it.length)))
}
value.groupName?.let {
data.add(GROUP_LENGTH_KEY.with(withUpperBound(it.length)))
}
}
addIfTrue(data, IS_EDITOR_ACTION, action is EditorAction)
addIfTrue(data, IS_SEARCH_ACTION, action is SearchEverywhereBaseAction)
addIfTrue(data, IS_TOGGLE_ACTION_DATA_KEY, action is ToggleAction)
val presentation = if (value is ActionWrapper && value.hasPresentation()) value.presentation else action.templatePresentation
data.add(HAS_ICON_KEY.with(presentation.icon != null))
data.add(IS_ENABLED.with(presentation.isEnabled))
data.add(WEIGHT_KEY.with(presentation.weight))
data.addAll(getLocalUsageStatistics(action, currentTime))
val actionId = ActionManager.getInstance().getId(action) ?: action.javaClass.name
val globalSummary = service<ActionsGlobalSummaryManager>()
val actionStats = globalSummary.getActionStatistics(actionId)
val maxUsageCount = globalSummary.totalSummary.maxUsageCount
data.addAll(GLOBAL_STATISTICS_DEFAULT.getGlobalUsageStatistics(actionStats, maxUsageCount))
val updatedActionStats = globalSummary.getUpdatedActionStatistics(actionId)
val updatedMaxUsageCount = globalSummary.updatedTotalSummary.maxUsageCount
data.addAll(GLOBAL_STATISTICS_UPDATED.getGlobalUsageStatistics(updatedActionStats, updatedMaxUsageCount))
val pluginInfo = getPluginInfo(action.javaClass)
if (pluginInfo.isSafeToReport()) {
data.add(PLUGIN_TYPE.with(pluginInfo.type.name))
pluginInfo.id?.let { data.add(PLUGIN_ID.with(it)) }
}
return data
}
private fun getAnAction(value: Any): AnAction? {
if (value is ActionWrapper) {
return value.action
}
else if (value is AnAction) {
return value
}
return null
}
private fun getLocalUsageStatistics(action: AnAction,
currentTime: Long): List<EventPair<*>> {
val actionId = ActionManager.getInstance().getId(action) ?: action.javaClass.name
val localSummary = service<ActionsLocalSummary>()
val summary = localSummary.getActionStatsById(actionId) ?: return emptyList()
val totalStats = localSummary.getTotalStats()
val result = arrayListOf<EventPair<*>>()
addTimeAndUsageStatistics(result, summary.usageCount, totalStats.maxUsageCount, currentTime, summary.lastUsedTimestamp, false)
addTimeAndUsageStatistics(
result,
summary.usageFromSearchEverywhere, totalStats.maxUsageFromSearchEverywhere,
currentTime, summary.lastUsedFromSearchEverywhere,
true
)
return result
}
private fun addTimeAndUsageStatistics(data: MutableList<EventPair<*>>,
usage: Int, maxUsage: Int,
time: Long, lastUsedTime: Long,
isSe: Boolean) {
addUsageStatistics(data, usage, maxUsage, isSe)
addLastTimeUsedStatistics(data, time, lastUsedTime, isSe)
}
private fun addUsageStatistics(data: MutableList<EventPair<*>>, usage: Int, maxUsage: Int, isSe: Boolean) {
if (usage > 0) {
val usageEventId = if (isSe) USAGE_SE else USAGE
data.add(usageEventId.with(usage))
if (maxUsage != 0) {
val usageToMaxEventId = if (isSe) USAGE_TO_MAX_SE else USAGE_TO_MAX
data.add(usageToMaxEventId.with(roundDouble(usage.toDouble() / maxUsage)))
}
}
}
private fun addLastTimeUsedStatistics(data: MutableList<EventPair<*>>, time: Long, lastUsedTime: Long, isSe: Boolean) {
if (lastUsedTime > 0) {
val timeSinceLastUsage = time - lastUsedTime
val timeSinceLastUsageEvent = if (isSe) TIME_SINCE_LAST_USAGE_SE else TIME_SINCE_LAST_USAGE
data.add(timeSinceLastUsageEvent.with(timeSinceLastUsage))
addIfTrue(data, if (isSe) WAS_USED_IN_LAST_MINUTE_SE else WAS_USED_IN_LAST_MINUTE, timeSinceLastUsage <= Time.MINUTE)
addIfTrue(data, if (isSe) WAS_USED_IN_LAST_HOUR_SE else WAS_USED_IN_LAST_HOUR, timeSinceLastUsage <= Time.HOUR)
addIfTrue(data, if (isSe) WAS_USED_IN_LAST_DAY_SE else WAS_USED_IN_LAST_DAY, timeSinceLastUsage <= Time.DAY)
addIfTrue(data, if (isSe) WAS_USED_IN_LAST_MONTH_SE else WAS_USED_IN_LAST_MONTH, timeSinceLastUsage <= (4 * Time.WEEK.toLong()))
}
}
internal class GlobalStatisticsFields(version: Int) {
private val globalUsage = EventFields.Long("globalUsageV$version")
private val globalUsageToMax = EventFields.Double("globalUsageToMaxV$version")
private val usersRatio = EventFields.Double("usersRatioV$version")
private val usagesPerUserRatio = EventFields.Double("usagesPerUserRatioV$version")
fun getFieldsDeclaration(): List<EventField<*>> = arrayListOf(globalUsage, globalUsageToMax, usersRatio, usagesPerUserRatio)
fun getGlobalUsageStatistics(actionGlobalStatistics: ActionGlobalUsageInfo?, maxUsageCount: Long) : List<EventPair<*>> {
val result = arrayListOf<EventPair<*>>()
actionGlobalStatistics?.let {
result.add(globalUsage.with(it.usagesCount))
if (maxUsageCount != 0L) {
result.add(globalUsageToMax.with(roundDouble(it.usagesCount.toDouble() / maxUsageCount)))
}
result.add(usersRatio.with(roundDouble(it.usersRatio)))
result.add(usagesPerUserRatio.with(roundDouble(it.usagesPerUserRatio)))
}
return result
}
}
} | apache-2.0 | a950bae05dbec1b0800d3d32bb45f6a3 | 49.71028 | 158 | 0.736891 | 4.215618 | false | false | false | false |
GunoH/intellij-community | platform/platform-impl/src/com/intellij/idea/ZipFilePoolImpl.kt | 5 | 1579 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
@file:Suppress("ReplaceGetOrSet")
package com.intellij.idea
import com.google.common.util.concurrent.Striped
import com.intellij.util.lang.ImmutableZipFile
import com.intellij.util.lang.ZipFile
import com.intellij.util.lang.ZipFilePool
import org.jetbrains.annotations.ApiStatus
import java.io.InputStream
import java.nio.file.Path
import java.util.concurrent.ConcurrentHashMap
@ApiStatus.Internal
class ZipFilePoolImpl : ZipFilePool() {
private val pool = ConcurrentHashMap<Path, MyEntryResolver>(1024)
private val lock = Striped.lock(64)
override fun loadZipFile(file: Path): ZipFile {
val resolver = pool.get(file)
// doesn't make sense to use pool for requests from class loader (requested only once per class loader)
return resolver?.zipFile ?: ImmutableZipFile.load(file)
}
override fun load(file: Path): EntryResolver {
pool.get(file)?.let { return it }
val lock = lock.get(file)
lock.lock()
try {
return pool.computeIfAbsent(file) {
val zipFile = ImmutableZipFile.load(file)
MyEntryResolver(zipFile)
}
}
finally {
lock.unlock()
}
}
private class MyEntryResolver(@JvmField val zipFile: ZipFile) : EntryResolver {
override fun loadZipEntry(path: String): InputStream? {
return zipFile.getInputStream(if (path[0] == '/') path.substring(1) else path)
}
override fun toString() = zipFile.toString()
}
fun clear() {
pool.clear()
}
} | apache-2.0 | 0a18692e01d1b0f51a56f7c60d17770c | 29.384615 | 120 | 0.718809 | 4.028061 | false | false | false | false |
AsamK/TextSecure | qr/lib/src/main/java/org/signal/qr/ImageProxyLuminanceSource.kt | 1 | 1953 | package org.signal.qr
import android.graphics.ImageFormat
import androidx.camera.core.ImageProxy
import com.google.zxing.LuminanceSource
import java.nio.ByteBuffer
/**
* Luminance source that gets data via an [ImageProxy]. The main reason for this is because
* the Y-Plane provided by the camera framework can have a row stride (number of bytes that make up a row)
* that is different than the image width.
*
* An image width can be reported as 1080 but the row stride may be 1088. Thus when representing a row-major
* 2D array as a 1D array, the math can go sideways if width is used instead of row stride.
*/
class ImageProxyLuminanceSource(image: ImageProxy) : LuminanceSource(image.width, image.height) {
val yData: ByteArray
init {
require(image.format == ImageFormat.YUV_420_888) { "Invalid image format" }
yData = ByteArray(image.width * image.height)
val yBuffer: ByteBuffer = image.planes[0].buffer
yBuffer.position(0)
val yRowStride: Int = image.planes[0].rowStride
for (y in 0 until image.height) {
val yIndex: Int = y * yRowStride
yBuffer.position(yIndex)
yBuffer.get(yData, y * image.width, image.width)
}
}
override fun getRow(y: Int, row: ByteArray?): ByteArray {
require(y in 0 until height) { "Requested row is outside the image: $y" }
val toReturn: ByteArray = if (row == null || row.size < width) {
ByteArray(width)
} else {
row
}
val yIndex: Int = y * width
yData.copyInto(toReturn, 0, yIndex, yIndex + width)
return toReturn
}
override fun getMatrix(): ByteArray {
return yData
}
fun render(): IntArray {
val argbArray = IntArray(width * height)
var yValue: Int
yData.forEachIndexed { i, byte ->
yValue = (byte.toInt() and 0xff).coerceIn(0..255)
argbArray[i] = 255 shl 24 or (yValue and 255 shl 16) or (yValue and 255 shl 8) or (yValue and 255)
}
return argbArray
}
}
| gpl-3.0 | 732daf126b4f37a3b0ff2ec657c9efbb | 27.720588 | 108 | 0.683052 | 3.698864 | false | false | false | false |
jk1/intellij-community | plugins/settings-repository/src/autoSync.kt | 3 | 6020 | // 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 org.jetbrains.settingsRepository
import com.intellij.configurationStore.ComponentStoreImpl
import com.intellij.notification.Notification
import com.intellij.notification.Notifications
import com.intellij.notification.NotificationsAdapter
import com.intellij.openapi.application.ModalityState
import com.intellij.openapi.application.ex.ApplicationManagerEx
import com.intellij.openapi.application.impl.ApplicationImpl
import com.intellij.openapi.components.stateStore
import com.intellij.openapi.progress.ProcessCanceledException
import com.intellij.openapi.progress.ProgressIndicator
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.ShutDownTracker
import com.intellij.openapi.vcs.VcsBundle
import com.intellij.openapi.vcs.VcsNotifier
import com.intellij.openapi.vcs.ui.VcsBalloonProblemNotifier
import java.util.concurrent.Future
internal class AutoSyncManager(private val icsManager: IcsManager) {
private @Volatile var autoSyncFuture: Future<*>? = null
@Volatile var enabled = true
fun waitAutoSync(indicator: ProgressIndicator) {
val autoFuture = autoSyncFuture
if (autoFuture != null) {
if (autoFuture.isDone) {
autoSyncFuture = null
}
else if (autoSyncFuture != null) {
LOG.info("Wait for auto sync future")
indicator.text = "Wait for auto sync completion"
while (!autoFuture.isDone) {
if (indicator.isCanceled) {
return
}
Thread.sleep(5)
}
}
}
}
fun registerListeners(project: Project) {
project.messageBus.connect().subscribe(Notifications.TOPIC, object : NotificationsAdapter() {
override fun notify(notification: Notification) {
if (!icsManager.isActive) {
return
}
if (when {
notification.groupId == VcsBalloonProblemNotifier.NOTIFICATION_GROUP.displayId -> {
val message = notification.content
message.startsWith("VCS Update Finished") ||
message == VcsBundle.message("message.text.file.is.up.to.date") ||
message == VcsBundle.message("message.text.all.files.are.up.to.date")
}
notification.groupId == VcsNotifier.NOTIFICATION_GROUP_ID.displayId && notification.title == "Push successful" -> true
else -> false
}) {
autoSync()
}
}
})
}
fun autoSync(onAppExit: Boolean = false, force: Boolean = false) {
if (!enabled || !icsManager.isActive || (!force && !icsManager.settings.autoSync)) {
return
}
autoSyncFuture?.let {
if (!it.isDone) {
return
}
}
val app = ApplicationManagerEx.getApplicationEx() as ApplicationImpl
if (onAppExit) {
sync(app, onAppExit)
return
}
else if (app.isDisposeInProgress) {
// will be handled by applicationExiting listener
return
}
autoSyncFuture = app.executeOnPooledThread {
try {
// to ensure that repository will not be in uncompleted state and changes will be pushed
ShutDownTracker.getInstance().registerStopperThread(Thread.currentThread())
sync(app, onAppExit)
}
finally {
autoSyncFuture = null
ShutDownTracker.getInstance().unregisterStopperThread(Thread.currentThread())
}
}
}
private fun sync(app: ApplicationImpl, onAppExit: Boolean) {
catchAndLog {
icsManager.runInAutoCommitDisabledMode {
doSync(app, onAppExit)
}
}
}
private fun doSync(app: ApplicationImpl, onAppExit: Boolean) {
val repositoryManager = icsManager.repositoryManager
val hasUpstream = repositoryManager.hasUpstream()
if (hasUpstream && !repositoryManager.canCommit()) {
LOG.warn("Auto sync skipped: repository is not committable")
return
}
// on app exit fetch and push only if there are commits to push
if (onAppExit) {
// if no upstream - just update cloud schemes
if (hasUpstream && !repositoryManager.commit() && repositoryManager.getAheadCommitsCount() == 0 && icsManager.readOnlySourcesManager.repositories.isEmpty()) {
return
}
// use explicit progress task to sync on app exit to make it clear why app is not exited immediately
icsManager.syncManager.sync(SyncType.MERGE, onAppExit = true)
return
}
// update read-only sources at first (because contain scheme - to ensure that some scheme will exist when it will be set as current by some setting)
updateCloudSchemes(icsManager)
if (hasUpstream) {
val updater = repositoryManager.fetch()
// we merge in EDT non-modal to ensure that new settings will be properly applied
app.invokeAndWait({
catchAndLog {
val updateResult = updater.merge()
if (!onAppExit &&
!app.isDisposeInProgress &&
updateResult != null &&
updateStoragesFromStreamProvider(icsManager, app.stateStore as ComponentStoreImpl, updateResult,
app.messageBus)) {
// force to avoid saveAll & confirmation
app.exit(true, true, true)
}
}
}, ModalityState.NON_MODAL)
if (!updater.definitelySkipPush) {
repositoryManager.push()
}
}
}
}
inline internal fun catchAndLog(asWarning: Boolean = false, runnable: () -> Unit) {
try {
runnable()
}
catch (e: ProcessCanceledException) { }
catch (e: Throwable) {
if (asWarning || e is AuthenticationException || e is NoRemoteRepositoryException) {
LOG.warn(e)
}
else {
LOG.error(e)
}
}
} | apache-2.0 | d89ff1a3fe667aa477ea02f2aad3bfae | 33.803468 | 164 | 0.645017 | 5.004156 | false | false | false | false |
RayBa82/DVBViewerController | dvbViewerController/src/main/java/org/dvbviewer/controller/ui/fragments/TaskListFragment.kt | 1 | 6102 | /*
* Copyright © 2012 dvbviewer-controller 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 org.dvbviewer.controller.ui.fragments
import android.content.DialogInterface
import android.content.DialogInterface.OnClickListener
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ListView
import android.widget.TextView
import androidx.appcompat.app.AlertDialog
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import okhttp3.ResponseBody
import org.dvbviewer.controller.R
import org.dvbviewer.controller.data.api.ApiResponse
import org.dvbviewer.controller.data.api.ApiStatus
import org.dvbviewer.controller.data.task.TaskViewModel
import org.dvbviewer.controller.data.task.xml.Task
import org.dvbviewer.controller.data.task.xml.TaskList
import org.dvbviewer.controller.ui.base.BaseListFragment
import org.dvbviewer.controller.utils.ArrayListAdapter
import org.dvbviewer.controller.utils.CategoryAdapter
import org.dvbviewer.controller.utils.EVENT_TASK_EXECUTED
import org.dvbviewer.controller.utils.PARAM_NAME
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import java.text.MessageFormat
/**
* Used to display the list of DMS tasks
*/
class TaskListFragment : BaseListFragment(), OnClickListener {
lateinit var sAdapter: CategoryAdapter
private var selectedTask: Task? = null
private lateinit var mViewModel: TaskViewModel
/* (non-Javadoc)
* @see android.support.v4.app.Fragment#onCreate(android.os.Bundle)
*/
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setHasOptionsMenu(true)
}
/* (non-Javadoc)
* @see android.support.v4.app.Fragment#onActivityCreated(android.os.Bundle)
*/
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
sAdapter = CategoryAdapter(context)
mViewModel = ViewModelProvider(this).get(TaskViewModel::class.java)
val mediaObserver = Observer<ApiResponse<TaskList>> { response ->
when {
response?.status == ApiStatus.SUCCESS -> {
response.data?.groups?.forEach {
val adapter = TaskAdapter()
it.tasks?.forEach { task ->
adapter.addItem(task)
}
sAdapter.addSection(it.name, adapter)
}
listAdapter = sAdapter
}
response.status == ApiStatus.NOT_SUPPORTED -> setEmptyText(response.message)
response.status == ApiStatus.ERROR -> catchException(TaskListFragment::class.java.simpleName, response.e)
}
setListShown(true)
}
mViewModel.taskList.observe(this, mediaObserver)
}
/* (non-Javadoc)
* @see android.support.v4.app.ListFragment#onListItemClick(android.widget.ListView, android.view.View, int, long)
*/
override fun onListItemClick(l: ListView, v: View, position: Int, id: Long) {
if (context == null) {
return
}
selectedTask = sAdapter.getItem(position) as Task
val builder = AlertDialog.Builder(context!!)
val question = MessageFormat.format(resources.getString(R.string.task_execute_security_question), selectedTask?.name)
builder.setMessage(question).setPositiveButton("Yes", this).setTitle(R.string.dialog_confirmation_title).setNegativeButton("No", this).show()
}
inner class TaskAdapter internal constructor() : ArrayListAdapter<Task>() {
/*
* (non-Javadoc)
*
* @see android.widget.ArrayAdapter#getView(int, android.view.View,
* android.view.ViewGroup)
*/
override fun getView(position: Int, convertView: View?, parent: ViewGroup): View {
var convertView = convertView
if (convertView == null) {
convertView = LayoutInflater.from(context).inflate(R.layout.list_item_tasks, parent, false)
}
val title = convertView!!.findViewById<TextView>(android.R.id.title)
title.text = mItems[position].name
return convertView
}
}
/* (non-Javadoc)
* @see android.content.DialogInterface.OnClickListener#onClick(android.content.DialogInterface, int)
*/
override fun onClick(dialog: DialogInterface, which: Int) {
when (which) {
DialogInterface.BUTTON_POSITIVE -> {
val action = selectedTask?.action
val name = selectedTask?.name
val call = action?.let { getDmsInterface().executeTask(it) }
call?.enqueue(object : Callback<ResponseBody> {
override fun onResponse(call: Call<ResponseBody>, response: Response<ResponseBody>) {
val resMsg = getString(R.string.task_executed)
val msg = MessageFormat.format(resMsg, name)
sendMessage(msg)
val bundle = Bundle()
bundle.putString(PARAM_NAME, name)
logEvent(EVENT_TASK_EXECUTED, bundle)
}
override fun onFailure(call: Call<ResponseBody>, t: Throwable) {
sendMessage(R.string.error_common)
}
})
}
DialogInterface.BUTTON_NEGATIVE -> {
}
}// No button clicked
}
}
| apache-2.0 | 48dd9433db71645b7368c1f79f8fa528 | 38.875817 | 149 | 0.6594 | 4.725794 | false | false | false | false |
oldergod/android-architecture | app/src/main/java/com/example/android/architecture/blueprints/todoapp/tasks/TasksAdapter.kt | 1 | 2239 | package com.example.android.architecture.blueprints.todoapp.tasks
import android.support.v4.content.ContextCompat
import android.support.v4.view.ViewCompat
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.BaseAdapter
import android.widget.CheckBox
import android.widget.TextView
import com.example.android.architecture.blueprints.todoapp.R
import com.example.android.architecture.blueprints.todoapp.data.Task
import io.reactivex.Observable
import io.reactivex.subjects.PublishSubject
class TasksAdapter(tasks: List<Task>) : BaseAdapter() {
private val taskClickSubject = PublishSubject.create<Task>()
private val taskToggleSubject = PublishSubject.create<Task>()
private lateinit var tasks: List<Task>
val taskClickObservable: Observable<Task>
get() = taskClickSubject
val taskToggleObservable: Observable<Task>
get() = taskToggleSubject
init {
setList(tasks)
}
fun replaceData(tasks: List<Task>) {
setList(tasks)
notifyDataSetChanged()
}
private fun setList(tasks: List<Task>) {
this.tasks = tasks
}
override fun getCount(): Int = tasks.size
override fun getItem(position: Int): Task = tasks[position]
override fun getItemId(position: Int): Long = position.toLong()
override fun getView(position: Int, view: View?, viewGroup: ViewGroup): View {
val rowView: View = view
?: LayoutInflater.from(viewGroup.context).inflate(R.layout.task_item, viewGroup, false)
val task = getItem(position)
rowView.findViewById<TextView>(R.id.title).text = task.titleForList
val completeCB = rowView.findViewById<CheckBox>(R.id.complete)
// Active/completed task UI
completeCB.isChecked = task.completed
if (task.completed) {
ViewCompat.setBackground(
rowView,
ContextCompat.getDrawable(viewGroup.context, R.drawable.list_completed_touch_feedback))
} else {
ViewCompat.setBackground(
rowView,
ContextCompat.getDrawable(viewGroup.context, R.drawable.touch_feedback))
}
completeCB.setOnClickListener { taskToggleSubject.onNext(task) }
rowView.setOnClickListener { taskClickSubject.onNext(task) }
return rowView
}
}
| apache-2.0 | d82c7fcbd94c0cf0368372d79d940864 | 29.256757 | 97 | 0.745869 | 4.322394 | false | false | false | false |
mdanielwork/intellij-community | platform/script-debugger/protocol/protocol-model-generator/src/TypeMap.kt | 12 | 1695 | package org.jetbrains.protocolModelGenerator
import gnu.trove.THashMap
import java.util.*
/**
* Keeps track of all referenced types.
* A type may be used and resolved (generated or hard-coded).
*/
internal class TypeMap {
private val map = THashMap<Pair<String, String>, TypeData>()
var domainGeneratorMap: Map<String, DomainGenerator>? = null
private val typesToGenerate = ArrayDeque<StandaloneTypeBinding>()
fun resolve(domainName: String, typeName: String, direction: TypeData.Direction): BoxableType? {
val domainGenerator = domainGeneratorMap!!.get(domainName)
if (domainGenerator == null) {
val qName = "$domainName.$typeName";
if (qName == "IO.StreamHandle" ||
qName == "Security.SecurityState" ||
qName == "Security.CertificateId" ||
qName == "Emulation.ScreenOrientation" ||
qName == "Security.MixedContentType"
) {
return BoxableType.ANY_STRING // ignore
}
throw RuntimeException("Failed to find domain generator: $domainName for type $typeName")
}
return direction.get(getTypeData(domainName, typeName)).resolve(this, domainGenerator)
}
fun addTypeToGenerate(binding: StandaloneTypeBinding) {
typesToGenerate.offer(binding)
}
fun generateRequestedTypes() {
// size may grow during iteration
val createdTypes = HashSet<CharSequence>()
while (typesToGenerate.isNotEmpty()) {
val binding = typesToGenerate.poll()
if (createdTypes.add(binding.getJavaType().fullText)) {
binding.generate()
}
}
}
fun getTypeData(domainName: String, typeName: String) = map.getOrPut(Pair(domainName, typeName)) { TypeData(typeName) }
}
| apache-2.0 | da47239b1115fc3084de6179ff838019 | 32.9 | 121 | 0.693805 | 4.568733 | false | false | false | false |
google/glance-experimental-tools | appwidget-viewer/src/main/java/com/google/android/glance/tools/viewer/GlanceViewerActivity.kt | 1 | 5555 | /*
* 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.glance.tools.viewer
import android.appwidget.AppWidgetManager
import android.appwidget.AppWidgetProvider
import android.appwidget.AppWidgetProviderInfo
import android.os.Build
import android.os.Bundle
import android.widget.RemoteViews
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.annotation.CallSuper
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.runtime.MutableState
import androidx.compose.runtime.mutableStateOf
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.DpSize
import androidx.glance.appwidget.ExperimentalGlanceRemoteViewsApi
import androidx.glance.appwidget.GlanceAppWidget
import androidx.glance.appwidget.GlanceAppWidgetReceiver
import com.google.android.glance.appwidget.host.getTargetSize
import com.google.android.glance.appwidget.host.glance.compose
import com.google.android.glance.tools.viewer.ui.ViewerScreen
import com.google.android.glance.tools.viewer.ui.theme.ViewerTheme
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
/**
* Base class to display AppWidgets.
*/
abstract class AppWidgetViewerActivity : ComponentActivity() {
/**
* The list of [AppWidgetProvider] to display in the viewer
*/
abstract fun getProviders(): List<Class<out AppWidgetProvider>>
/**
* Provides the [RemoteViews] snapshot of the given [AppWidgetProviderInfo] for the given size
*
* @param - The [AppWidgetProviderInfo] containing the metadata of the appwidget
* @param - The available size to display the appwidget
*
* @return the [RemoteViews] instance to use for the viewer.
*/
abstract suspend fun getAppWidgetSnapshot(
info: AppWidgetProviderInfo,
size: DpSize
): RemoteViews
// Moving states outside of composition to ensure they are kept when Live Edits happen.
private lateinit var selectedProvider: MutableState<AppWidgetProviderInfo>
private lateinit var currentSize: MutableState<DpSize>
@CallSuper
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val widgetManager = AppWidgetManager.getInstance(this)
val providers = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
widgetManager.getInstalledProvidersForPackage(packageName, null)
} else {
widgetManager.installedProviders.filter { it.provider.packageName == packageName }
}.filter { info ->
getProviders().any { selectedProvider ->
selectedProvider.name == info.provider.className
}
}
selectedProvider = mutableStateOf(providers.first())
currentSize = mutableStateOf(selectedProvider.value.getTargetSize(this))
setContent {
ViewerTheme {
Surface(
modifier = Modifier.fillMaxSize(),
color = MaterialTheme.colorScheme.background
) {
ViewerScreen(
providers = providers,
selectedProvider = selectedProvider.value,
currentSize = currentSize.value,
snapshot = ::getAppWidgetSnapshot,
onResize = { currentSize.value = it },
onSelected = { selectedProvider.value = it }
)
}
}
}
}
}
/**
* Extend this activity to provide a set of GlanceAppWidget snapshots to display.
*/
@ExperimentalGlanceRemoteViewsApi
abstract class GlanceViewerActivity : AppWidgetViewerActivity() {
/**
* Provides an instance of [GlanceAppWidget] to display inside the viewer.
*
* @param receiver - The selected [GlanceAppWidgetReceiver] to display
*/
abstract suspend fun getGlanceSnapshot(receiver: Class<out GlanceAppWidgetReceiver>): GlanceSnapshot
/**
* Only override this method to directly provide [RemoteViews] instead of [GlanceAppWidget]
* instances.
*
* @see AppWidgetViewerActivity.getAppWidgetSnapshot
*/
@Suppress("UNCHECKED_CAST")
override suspend fun getAppWidgetSnapshot(
info: AppWidgetProviderInfo,
size: DpSize
): RemoteViews = withContext(Dispatchers.IO) {
val receiver = Class.forName(info.provider.className)
require(GlanceAppWidgetReceiver::class.java.isAssignableFrom(receiver)) {
"AppWidget is not a GlanceAppWidgetReceiver. Override this method to provide other implementations"
}
val receiverClass = receiver as Class<out GlanceAppWidgetReceiver>
val snapshot = getGlanceSnapshot(receiverClass)
snapshot.instance.compose(applicationContext, size, snapshot.state, info)
}
}
| apache-2.0 | 0b5866d4c4b1664649040b1ede8e56dc | 38.119718 | 111 | 0.708011 | 5.148285 | false | false | false | false |
dahlstrom-g/intellij-community | python/src/com/jetbrains/python/codeInsight/mlcompletion/prev2calls/PrevCallsModelsProviderService.kt | 12 | 2786 | // Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.jetbrains.python.codeInsight.mlcompletion.prev2calls
import com.completion.features.models.prevcalls.python.PrevCallsModel
import com.completion.features.models.prevcalls.python.PrevCallsModelsLoader
import com.google.common.cache.CacheBuilder
import com.google.common.cache.CacheLoader
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.components.Service
import com.intellij.openapi.components.service
import com.intellij.openapi.diagnostic.Logger
import com.intellij.util.ui.update.MergingUpdateQueue
import com.intellij.util.ui.update.Update
import com.jetbrains.python.PythonPluginDisposable
import java.util.concurrent.ExecutionException
@Service
class PrevCallsModelsProviderService {
internal class ModelNotFoundException: Exception()
private val logger = Logger.getInstance(PrevCallsModelsProviderService::class.java)
private val package2model = CacheBuilder.newBuilder()
.softValues()
.maximumSize(40)
.build(object: CacheLoader<String, PrevCallsModel>() {
override fun load(expression: String): PrevCallsModel {
val result = PrevCallsModelsLoader.getModelForExpression(expression)
if (result == null) throw ModelNotFoundException()
return result
}
})
private val modelsLoadingQueue = MergingUpdateQueue("ModelsLoadingQueue", 1000, true, null,
PythonPluginDisposable.getInstance(), null, false)
private fun createUpdate(identity: Any, runnable: () -> Unit) = object : Update(identity) {
override fun canEat(update: Update?) = this == update
override fun run() = runnable()
}
fun loadModelFor(qualifierName: String) {
val moduleName = qualifierName.substringBefore(".")
if (!haveModelForQualifier(moduleName)) return
val modelForPackage = package2model.getIfPresent(moduleName)
fun tryLoadModel() {
try {
package2model.get(moduleName)
} catch (ex: ExecutionException) {
if (ex.cause !is ModelNotFoundException) {
logger.error(ex)
}
}
}
if (modelForPackage == null) {
if (ApplicationManager.getApplication().isUnitTestMode) {
tryLoadModel()
}
else {
modelsLoadingQueue.queue(createUpdate(moduleName) { tryLoadModel() })
}
}
}
fun getModelFor(qualifierName: String) = package2model.getIfPresent(qualifierName)
fun haveModelForQualifier(qualifier: String) = PrevCallsModelsLoader.haveModule(qualifier.substringBefore("."))
companion object {
val instance: PrevCallsModelsProviderService
get() = service()
}
} | apache-2.0 | 850f98c15d364287ed8c0803d2754ce7 | 36.662162 | 140 | 0.732592 | 4.544861 | false | false | false | false |
dahlstrom-g/intellij-community | plugins/kotlin/idea/tests/testData/refactoring/rename/renameKotlinBaseMethod/before/RenameKotlinBaseMethod.kt | 14 | 278 | package testing.rename
interface A {
fun first() : Int
}
public open class B: A {
override fun first() = 1
}
class C: B() {
override fun first() = 2
}
fun usages() {
val b = B()
val a: A = b
val c = C()
a.first()
b.first()
c.first()
}
| apache-2.0 | 86efef869ab87e97050d9b7b861c3892 | 10.12 | 28 | 0.510791 | 2.926316 | false | false | false | false |
android/privacy-codelab | PhotoLog_start/src/main/java/com/example/photolog_start/HomeViewModel.kt | 1 | 2567 | /*
* Copyright (C) 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.photolog_start
import android.app.Application
import android.content.Context
import android.text.format.DateUtils
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.viewModelScope
import androidx.lifecycle.viewmodel.CreationExtras
import androidx.room.Room
import com.example.photolog_start.AppDatabase.Companion.DB_NAME
import kotlinx.coroutines.launch
class HomeViewModel(
application: Application,
private val photoSaver: PhotoSaverRepository
) : AndroidViewModel(application) {
private val context: Context
get() = getApplication()
private val db = Room.databaseBuilder(context, AppDatabase::class.java, DB_NAME).build()
data class UiState(val loading: Boolean = true, val logs: List<Log> = emptyList())
var uiState by mutableStateOf(UiState())
private set
fun formatDateTime(timeInMillis: Long): String {
return DateUtils.formatDateTime(context, timeInMillis, DateUtils.FORMAT_ABBREV_ALL)
}
fun loadLogs() {
viewModelScope.launch {
uiState = uiState.copy(
loading = false,
logs = db.logDao().getAllWithFiles(photoSaver.photoFolder)
)
}
}
fun delete(log: Log) {
viewModelScope.launch {
db.logDao().delete(log.toLogEntry())
loadLogs()
}
}
}
class HomeViewModelFactory : ViewModelProvider.Factory {
@Suppress("UNCHECKED_CAST")
override fun <T : ViewModel> create(modelClass: Class<T>, extras: CreationExtras): T {
val app =
extras[ViewModelProvider.AndroidViewModelFactory.APPLICATION_KEY] as PhotoLogApplication
return HomeViewModel(app, app.photoSaver) as T
}
} | apache-2.0 | 5b50d0081d508dcd750bd88156121725 | 32.350649 | 100 | 0.723413 | 4.535336 | false | false | false | false |
airbnb/epoxy | epoxy-paging3/src/main/java/com/airbnb/epoxy/paging3/PagedListEpoxyController.kt | 1 | 5446 | /*
* Copyright 2018 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.airbnb.epoxy.paging3
import android.annotation.SuppressLint
import android.os.Handler
import androidx.paging.PagedList
import androidx.recyclerview.widget.DiffUtil
import com.airbnb.epoxy.EpoxyController
import com.airbnb.epoxy.EpoxyModel
import com.airbnb.epoxy.EpoxyViewHolder
/**
* An [EpoxyController] that can work with a [PagedList].
*
* Internally, it caches the model for each item in the [PagedList]. You should override
* [buildItemModel] method to build the model for the given item. Since [PagedList] might include
* `null` items if placeholders are enabled, this method needs to handle `null` values in the list.
*
* By default, the model for each item is added to the model list. To change this behavior (to
* filter items or inject extra items), you can override [addModels] function and manually add built
* models.
*
* @param T The type of the items in the [PagedList].
*/
abstract class PagedListEpoxyController<T : Any>(
/**
* The handler to use for building models. By default this uses the main thread, but you can use
* [EpoxyAsyncUtil.getAsyncBackgroundHandler] to do model building in the background.
*
* The notify thread of your PagedList (from setNotifyExecutor in the PagedList Builder) must be
* the same as this thread. Otherwise Epoxy will crash.
*/
modelBuildingHandler: Handler = EpoxyController.defaultModelBuildingHandler,
/**
* The handler to use when calculating the diff between built model lists.
* By default this uses the main thread, but you can use
* [EpoxyAsyncUtil.getAsyncBackgroundHandler] to do diffing in the background.
*/
diffingHandler: Handler = EpoxyController.defaultDiffingHandler,
/**
* [PagedListEpoxyController] uses an [DiffUtil.ItemCallback] to detect changes between
* [PagedList]s. By default, it relies on simple object equality but you can provide a custom
* one if you don't use all fields in the object in your models.
*/
itemDiffCallback: DiffUtil.ItemCallback<T> = DEFAULT_ITEM_DIFF_CALLBACK as DiffUtil.ItemCallback<T>
) : EpoxyController(modelBuildingHandler, diffingHandler) {
// this is where we keep the already built models
val modelCache = PagedListModelCache(
modelBuilder = { pos, item ->
buildItemModel(pos, item)
},
rebuildCallback = {
requestModelBuild()
},
itemDiffCallback = itemDiffCallback,
modelBuildingHandler = modelBuildingHandler
)
final override fun buildModels() {
addModels(modelCache.getModels())
}
/**
* This function adds all built models to the adapter. You can override this method to add extra
* items into the model list or remove some.
*/
open fun addModels(models: List<EpoxyModel<*>>) {
super.add(models)
}
/**
* Builds the model for a given item. This must return a single model for each item. If you want
* to inject headers etc, you can override [addModels] function.
*
* If the `item` is `null`, you should provide the placeholder. If your [PagedList] is
* configured without placeholders, you don't need to handle the `null` case.
*/
abstract fun buildItemModel(currentPosition: Int, item: T?): EpoxyModel<*>
override fun onModelBound(
holder: EpoxyViewHolder,
boundModel: EpoxyModel<*>,
position: Int,
previouslyBoundModel: EpoxyModel<*>?
) {
// TODO the position may not be a good value if there are too many injected items.
modelCache.loadAround(position)
}
/**
* Submit a new paged list.
*
* A diff will be calculated between this list and the previous list so you may still get calls
* to [buildItemModel] with items from the previous list.
*/
fun submitList(newList: PagedList<T>?) {
modelCache.submitList(newList)
}
/**
* Requests a model build that will run for every model, including the ones created for the paged
* list.
*
* Clears the current model cache to make sure that happens.
*/
fun requestForcedModelBuild() {
modelCache.clearModels()
requestModelBuild()
}
companion object {
/**
* [PagedListEpoxyController] calculates a diff on top of the PagedList to check which
* models are invalidated.
* This is the default [DiffUtil.ItemCallback] which uses object equality.
*/
val DEFAULT_ITEM_DIFF_CALLBACK = object : DiffUtil.ItemCallback<Any>() {
override fun areItemsTheSame(oldItem: Any, newItem: Any) = oldItem == newItem
@SuppressLint("DiffUtilEquals")
override fun areContentsTheSame(oldItem: Any, newItem: Any) = oldItem == newItem
}
}
}
| apache-2.0 | 249cdc2cac3cd2a900fc6b0e9f7a35d7 | 38.463768 | 103 | 0.691333 | 4.591906 | false | false | false | false |
paplorinc/intellij-community | plugins/gradle/java/src/integrations/maven/codeInsight/completion/MavenDependenciesGradleCompletionContributor.kt | 2 | 6551 | // 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 org.jetbrains.plugins.gradle.integrations.maven.codeInsight.completion
import com.intellij.codeInsight.completion.*
import com.intellij.codeInsight.lookup.LookupElementBuilder
import com.intellij.icons.AllIcons
import com.intellij.patterns.PatternCondition
import com.intellij.patterns.PlatformPatterns.psiElement
import com.intellij.psi.util.PsiTreeUtil
import com.intellij.util.ProcessingContext
import org.jetbrains.idea.maven.indices.MavenArtifactSearcher
import org.jetbrains.idea.maven.indices.MavenProjectIndicesManager
import org.jetbrains.idea.maven.model.MavenId
import org.jetbrains.plugins.gradle.codeInsight.AbstractGradleCompletionContributor
import org.jetbrains.plugins.gradle.integrations.maven.MavenRepositoriesHolder
import org.jetbrains.plugins.groovy.lang.psi.api.statements.arguments.GrArgumentList
import org.jetbrains.plugins.groovy.lang.psi.api.statements.arguments.GrNamedArgument
import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.literals.GrLiteral
import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.path.GrMethodCallExpression
import org.jetbrains.plugins.groovy.lang.psi.api.util.GrNamedArgumentsOwner
/**
* @author Vladislav.Soroka
*/
class MavenDependenciesGradleCompletionContributor : AbstractGradleCompletionContributor() {
init {
// map-style notation:
// e.g.:
// compile group: 'com.google.code.guice', name: 'guice', version: '1.0'
// runtime([group:'junit', name:'junit-dep', version:'4.7'])
// compile(group:'junit', name:'junit-dep', version:'4.7')
extend(CompletionType.BASIC, IN_MAP_DEPENDENCY_NOTATION, object : CompletionProvider<CompletionParameters>() {
override fun addCompletions(params: CompletionParameters,
context: ProcessingContext,
result: CompletionResultSet) {
val parent = params.position.parent?.parent
if (parent !is GrNamedArgument || parent.parent !is GrNamedArgumentsOwner) {
return
}
result.stopHere()
if (GROUP_LABEL == parent.labelName) {
MavenRepositoriesHolder.getInstance(parent.project).checkNotIndexedRepositories()
val m = MavenProjectIndicesManager.getInstance(parent.project)
for (groupId in m.groupIds) {
result.addElement(LookupElementBuilder.create(groupId).withIcon(AllIcons.Nodes.PpLib))
}
}
else if (NAME_LABEL == parent.labelName) {
MavenRepositoriesHolder.getInstance(parent.project).checkNotIndexedRepositories()
val groupId = findNamedArgumentValue(parent.parent as GrNamedArgumentsOwner, GROUP_LABEL) ?: return
val m = MavenProjectIndicesManager.getInstance(parent.project)
for (artifactId in m.getArtifactIds(groupId)) {
result.addElement(LookupElementBuilder.create(artifactId).withIcon(AllIcons.Nodes.PpLib))
}
}
else if (VERSION_LABEL == parent.labelName) {
MavenRepositoriesHolder.getInstance(parent.project).checkNotIndexedRepositories()
val namedArgumentsOwner = parent.parent as GrNamedArgumentsOwner
val groupId = findNamedArgumentValue(namedArgumentsOwner, GROUP_LABEL) ?: return
val artifactId = findNamedArgumentValue(namedArgumentsOwner, NAME_LABEL) ?: return
val m = MavenProjectIndicesManager.getInstance(parent.project)
for (version in m.getVersions(groupId, artifactId)) {
result.addElement(LookupElementBuilder.create(version).withIcon(AllIcons.Nodes.PpLib))
}
}
}
})
// group:name:version notation
// e.g.:
// compile 'junit:junit:4.11'
// compile('junit:junit:4.11')
extend(CompletionType.BASIC, IN_METHOD_DEPENDENCY_NOTATION, object : CompletionProvider<CompletionParameters>() {
override fun addCompletions(params: CompletionParameters,
context: ProcessingContext,
result: CompletionResultSet) {
val parent = params.position.parent
if (parent !is GrLiteral || parent.parent !is GrArgumentList) return
result.stopHere()
MavenRepositoriesHolder.getInstance(parent.project).checkNotIndexedRepositories()
val searchText = CompletionUtil.findReferenceOrAlphanumericPrefix(params)
val searcher = MavenArtifactSearcher()
val searchResults = searcher.search(params.position.project, searchText, MAX_RESULT)
for (searchResult in searchResults) {
for (artifactInfo in searchResult.versions) {
val buf = StringBuilder()
MavenId.append(buf, artifactInfo.groupId)
MavenId.append(buf, artifactInfo.artifactId)
MavenId.append(buf, artifactInfo.version)
result.addElement(LookupElementBuilder.create(buf.toString()).withIcon(AllIcons.Nodes.PpLib))
}
}
}
})
}
companion object {
private const val GROUP_LABEL = "group"
private const val NAME_LABEL = "name"
private const val VERSION_LABEL = "version"
private const val DEPENDENCIES_SCRIPT_BLOCK = "dependencies"
private const val MAX_RESULT = 1000
private val DEPENDENCIES_CALL_PATTERN = psiElement()
.inside(true, psiElement(GrMethodCallExpression::class.java).with(
object : PatternCondition<GrMethodCallExpression>("withInvokedExpressionText") {
override fun accepts(expression: GrMethodCallExpression, context: ProcessingContext): Boolean {
if (checkExpression(expression)) return true
return checkExpression(PsiTreeUtil.getParentOfType(expression, GrMethodCallExpression::class.java))
}
private fun checkExpression(expression: GrMethodCallExpression?): Boolean {
if (expression == null) return false
val grExpression = expression.invokedExpression
return DEPENDENCIES_SCRIPT_BLOCK == grExpression.text
}
}))
private val IN_MAP_DEPENDENCY_NOTATION = psiElement()
.and(GRADLE_FILE_PATTERN)
.withParent(GrLiteral::class.java)
.withSuperParent(2, psiElement(GrNamedArgument::class.java))
.and(DEPENDENCIES_CALL_PATTERN)
private val IN_METHOD_DEPENDENCY_NOTATION = psiElement()
.and(GRADLE_FILE_PATTERN)
.and(DEPENDENCIES_CALL_PATTERN)
}
}
| apache-2.0 | ec14f490ebd9e972194a3db7daca0e62 | 47.525926 | 140 | 0.709968 | 4.849001 | false | false | false | false |
RuneSuite/client | api/src/main/java/org/runestar/client/api/game/Text.kt | 1 | 690 | package org.runestar.client.api.game
import java.lang.StringBuilder
const val BR_TAG = "<br>"
const val GT_TAG = "<gt>"
const val LT_TAG = "<lt>"
fun imageTag(index: Int) = "<img=$index>"
fun appendImageTag(index: Int, dst: StringBuilder) {
dst.append("<img=").append(index).append('>')
}
fun unescapeAngleBrackets(s: String): String {
return s.replace(GT_TAG, ">").replace(LT_TAG, "<")
}
fun escapeAngleBrackets(s: String): String {
return s.replace(">", GT_TAG).replace("<", LT_TAG)
}
fun unescapeSpaces(s: String): String {
return s.replace('\u00a0', ' ')
}
private val TAG_REGEX = "<.*?>".toRegex()
fun removeTags(s: String): String = s.replace(TAG_REGEX, "") | mit | 04f55d3c67c7e7396c14fc9e60bab802 | 21.290323 | 60 | 0.652174 | 3.053097 | false | false | false | false |
apollographql/apollo-android | apollo-api/src/commonMain/kotlin/com/apollographql/apollo3/api/http/internal/UrlEncode.kt | 1 | 569 | package com.apollographql.apollo3.api.http.internal
import kotlin.native.concurrent.SharedImmutable
@SharedImmutable
private val RESERVED_CHARS = "!#\$&'\"()*+,/:;=?@[]{}"
/**
* A very simple urlEncode
*/
internal fun String.urlEncode(
spaceToPlus: Boolean = false
): String = buildString {
[email protected] {
when {
it in RESERVED_CHARS -> append(it.percentEncode())
spaceToPlus && it == ' ' -> append('+')
else -> append(it)
}
}
}
private fun Char.percentEncode(): String {
return "%${code.toString(16)}".uppercase()
}
| mit | 1562749354cb35e0241c371ff80b8ff3 | 21.76 | 56 | 0.644991 | 3.694805 | false | false | false | false |
Atsky/haskell-idea-plugin | plugin/src/org/jetbrains/haskell/debugger/utils/UIUtils.kt | 1 | 1728 | package org.jetbrains.haskell.debugger.utils
import com.intellij.notification.Notifications
import com.intellij.notification.Notification
import com.intellij.notification.NotificationType
import javax.swing.JPanel
import javax.swing.JComponent
import org.jetbrains.haskell.util.gridBagConstraints
import java.awt.Insets
import javax.swing.JLabel
import org.jetbrains.haskell.util.setConstraints
import java.awt.GridBagConstraints
import javax.swing.Box
/**
* @author Habibullin Marat
*/
class UIUtils {
companion object {
fun addLabeledControl(panel: JPanel,
row: Int,
label: String,
component: JComponent,
isFill : Boolean = true) {
val base = gridBagConstraints { insets = Insets(2, 0, 2, 3) }
panel.add(JLabel(label), base.setConstraints {
anchor = GridBagConstraints.LINE_START
gridx = 0
gridy = row
})
panel.add(component, base.setConstraints {
gridx = 1
gridy = row
fill = if (isFill) GridBagConstraints.HORIZONTAL else GridBagConstraints.NONE
weightx = 1.0
})
panel.add(Box.createHorizontalStrut(1), base.setConstraints {
gridx = 2
gridy = row
weightx = 0.1
})
}
fun notifyCommandInProgress() {
val msg = "Some command is in progress, it must finish first"
Notifications.Bus.notify(Notification("", "Can't perform action", msg, NotificationType.WARNING))
}
}
} | apache-2.0 | a9d63a0c0f4fd8222691ec247709b686 | 34.285714 | 109 | 0.578704 | 5.158209 | false | false | false | false |
android/wear-os-samples | DataLayer/Wearable/src/main/java/com/example/android/wearable/datalayer/ClientDataViewModel.kt | 1 | 4796 | /*
* Copyright 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.android.wearable.datalayer
import android.app.Application
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import androidx.annotation.StringRes
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateListOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.viewModelScope
import com.google.android.gms.wearable.Asset
import com.google.android.gms.wearable.CapabilityClient
import com.google.android.gms.wearable.CapabilityInfo
import com.google.android.gms.wearable.DataClient
import com.google.android.gms.wearable.DataEvent
import com.google.android.gms.wearable.DataEventBuffer
import com.google.android.gms.wearable.DataMapItem
import com.google.android.gms.wearable.MessageClient
import com.google.android.gms.wearable.MessageEvent
import com.google.android.gms.wearable.Wearable
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.launch
import kotlinx.coroutines.tasks.await
import kotlinx.coroutines.withContext
class ClientDataViewModel(
application: Application
) :
AndroidViewModel(application),
DataClient.OnDataChangedListener,
MessageClient.OnMessageReceivedListener,
CapabilityClient.OnCapabilityChangedListener {
private val _events = mutableStateListOf<Event>()
/**
* The list of events from the clients.
*/
val events: List<Event> = _events
/**
* The currently received image (if any), available to display.
*/
var image by mutableStateOf<Bitmap?>(null)
private set
private var loadPhotoJob: Job = Job().apply { complete() }
override fun onDataChanged(dataEvents: DataEventBuffer) {
// Add all events to the event log
_events.addAll(
dataEvents.map { dataEvent ->
val title = when (dataEvent.type) {
DataEvent.TYPE_CHANGED -> R.string.data_item_changed
DataEvent.TYPE_DELETED -> R.string.data_item_deleted
else -> R.string.data_item_unknown
}
Event(
title = title,
text = dataEvent.dataItem.toString()
)
}
)
// Do additional work for specific events
dataEvents.forEach { dataEvent ->
when (dataEvent.type) {
DataEvent.TYPE_CHANGED -> {
when (dataEvent.dataItem.uri.path) {
DataLayerListenerService.IMAGE_PATH -> {
loadPhotoJob.cancel()
loadPhotoJob = viewModelScope.launch {
image = loadBitmap(
DataMapItem.fromDataItem(dataEvent.dataItem)
.dataMap
.getAsset(DataLayerListenerService.IMAGE_KEY)
)
}
}
}
}
}
}
}
override fun onMessageReceived(messageEvent: MessageEvent) {
_events.add(
Event(
title = R.string.message,
text = messageEvent.toString()
)
)
}
override fun onCapabilityChanged(capabilityInfo: CapabilityInfo) {
_events.add(
Event(
title = R.string.capability_changed,
text = capabilityInfo.toString()
)
)
}
private suspend fun loadBitmap(asset: Asset?): Bitmap? {
if (asset == null) return null
val response =
Wearable.getDataClient(getApplication<Application>()).getFdForAsset(asset).await()
return response.inputStream.use { inputStream ->
withContext(Dispatchers.IO) {
BitmapFactory.decodeStream(inputStream)
}
}
}
}
/**
* A data holder describing a client event.
*/
data class Event(
@StringRes val title: Int,
val text: String
)
| apache-2.0 | 1788b63d4992aae043aaf151f86a45c6 | 33.014184 | 94 | 0.629483 | 4.893878 | false | false | false | false |
allotria/intellij-community | python/python-psi-impl/src/com/jetbrains/python/inspections/PyTypedDictInspection.kt | 3 | 17848 | // Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.jetbrains.python.inspections
import com.intellij.codeInspection.LocalInspectionToolSession
import com.intellij.codeInspection.ProblemHighlightType
import com.intellij.codeInspection.ProblemsHolder
import com.intellij.openapi.util.Ref
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiElementVisitor
import com.intellij.psi.PsiNameIdentifierOwner
import com.jetbrains.python.PyNames
import com.jetbrains.python.PyPsiBundle
import com.jetbrains.python.codeInsight.typing.PyTypedDictTypeProvider
import com.jetbrains.python.codeInsight.typing.PyTypingTypeProvider
import com.jetbrains.python.documentation.PythonDocumentationProvider
import com.jetbrains.python.psi.*
import com.jetbrains.python.psi.impl.PyEvaluator
import com.jetbrains.python.psi.impl.PyPsiUtils
import com.jetbrains.python.psi.types.PyLiteralType
import com.jetbrains.python.psi.types.PyTypeChecker
import com.jetbrains.python.psi.types.PyTypeUtil
import com.jetbrains.python.psi.types.PyTypedDictType
import com.jetbrains.python.psi.types.PyTypedDictType.Companion.TYPED_DICT_FIELDS_PARAMETER
import com.jetbrains.python.psi.types.PyTypedDictType.Companion.TYPED_DICT_NAME_PARAMETER
import com.jetbrains.python.psi.types.PyTypedDictType.Companion.TYPED_DICT_TOTAL_PARAMETER
class PyTypedDictInspection : PyInspection() {
override fun buildVisitor(holder: ProblemsHolder,
isOnTheFly: Boolean,
session: LocalInspectionToolSession): PsiElementVisitor {
return Visitor(holder, session)
}
private class Visitor(holder: ProblemsHolder, session: LocalInspectionToolSession) : PyInspectionVisitor(holder, session) {
override fun visitPySubscriptionExpression(node: PySubscriptionExpression) {
val operandType = myTypeEvalContext.getType(node.operand)
if (operandType !is PyTypedDictType) return
val indexExpression = node.indexExpression
val indexExpressionValueOptions = getIndexExpressionValueOptions(indexExpression)
if (indexExpressionValueOptions.isNullOrEmpty()) {
val keyList = operandType.fields.keys.joinToString(transform = { "'$it'" })
registerProblem(indexExpression, PyPsiBundle.message("INSP.typeddict.typeddict.key.must.be.string.literal.expected.one", keyList))
return
}
val nonMatchingFields = indexExpressionValueOptions.filterNot { it in operandType.fields }
if (nonMatchingFields.isNotEmpty()) {
registerProblem(indexExpression, if (nonMatchingFields.size == 1)
PyPsiBundle.message("INSP.typeddict.typeddict.has.no.key", operandType.name, nonMatchingFields[0])
else {
val nonMatchingFieldList = nonMatchingFields.joinToString(transform = { "'$it'" })
PyPsiBundle.message("INSP.typeddict.typeddict.has.no.keys", operandType.name, nonMatchingFieldList)
})
}
}
override fun visitPyTargetExpression(node: PyTargetExpression) {
val value = node.findAssignedValue()
if (value is PyCallExpression && value.callee != null && PyTypedDictTypeProvider.isTypedDict(value.callee!!, myTypeEvalContext)) {
val typedDictName = value.getArgument(0, TYPED_DICT_NAME_PARAMETER, PyExpression::class.java)
if (typedDictName is PyStringLiteralExpression && node.name != typedDictName.stringValue) {
registerProblem(typedDictName, PyPsiBundle.message("INSP.typeddict.first.argument.has.to.match.variable.name"))
}
}
}
override fun visitPyArgumentList(node: PyArgumentList) {
if (node.parent is PyClass && PyTypedDictTypeProvider.isTypingTypedDictInheritor(node.parent as PyClass, myTypeEvalContext)) {
val arguments = node.arguments
for (argument in arguments) {
val type = myTypeEvalContext.getType(argument)
if (argument !is PyKeywordArgument
&& type !is PyTypedDictType
&& !PyTypedDictTypeProvider.isTypedDict(argument, myTypeEvalContext)) {
registerProblem(argument, PyPsiBundle.message("INSP.typeddict.typeddict.cannot.inherit.from.non.typeddict.base.class"))
}
if (argument is PyKeywordArgument && argument.keyword == TYPED_DICT_TOTAL_PARAMETER && argument.valueExpression != null) {
checkValidTotality(argument.valueExpression!!)
}
}
}
else if (node.callExpression != null) {
val callExpression = node.callExpression
val callee = callExpression!!.callee
if (callee != null && PyTypedDictTypeProvider.isTypedDict(callee, myTypeEvalContext)) {
val fields = callExpression.getArgument(1, TYPED_DICT_FIELDS_PARAMETER, PyExpression::class.java)
if (fields !is PyDictLiteralExpression) {
return
}
fields.elements.forEach {
if (it !is PyKeyValueExpression) return
checkValueIsAType(it.value, it.value?.text)
}
val totalityArgument = callExpression.getArgument(2, TYPED_DICT_TOTAL_PARAMETER, PyExpression::class.java)
if (totalityArgument != null) {
checkValidTotality(totalityArgument)
}
}
}
}
override fun visitPyClass(node: PyClass) {
if (!PyTypedDictTypeProvider.isTypingTypedDictInheritor(node, myTypeEvalContext)) return
if (node.metaClassExpression != null) {
registerProblem((node.metaClassExpression as PyExpression).parent,
PyPsiBundle.message("INSP.typeddict.specifying.metaclass.not.allowed.in.typeddict"))
}
val ancestorsFields = mutableMapOf<String, PyTypedDictType.FieldTypeAndTotality>()
val typedDictAncestors = node.getAncestorTypes(myTypeEvalContext).filterIsInstance<PyTypedDictType>()
typedDictAncestors.forEach { typedDict ->
typedDict.fields.forEach { field ->
val key = field.key
val value = field.value
if (key in ancestorsFields && !matchTypedDictFieldTypeAndTotality(ancestorsFields[key]!!, value)) {
registerProblem(node.superClassExpressionList,
PyPsiBundle.message("INSP.typeddict.cannot.overwrite.typeddict.field.while.merging", key))
}
else {
ancestorsFields[key] = value
}
}
}
val singleStatement = node.statementList.statements.singleOrNull()
if (singleStatement != null &&
singleStatement is PyExpressionStatement &&
singleStatement.expression is PyNoneLiteralExpression &&
(singleStatement.expression as PyNoneLiteralExpression).isEllipsis) {
registerProblem(tryGetNameIdentifier(singleStatement),
PyPsiBundle.message("INSP.typeddict.invalid.statement.in.typeddict.definition.expected.field.name.field.type"),
ProblemHighlightType.WEAK_WARNING)
return
}
node.processClassLevelDeclarations { element, _ ->
if (element !is PyTargetExpression) {
registerProblem(tryGetNameIdentifier(element),
PyPsiBundle.message("INSP.typeddict.invalid.statement.in.typeddict.definition.expected.field.name.field.type"),
ProblemHighlightType.WEAK_WARNING)
return@processClassLevelDeclarations true
}
if (element.hasAssignedValue()) {
registerProblem(element.findAssignedValue(),
PyPsiBundle.message("INSP.typeddict.right.hand.side.values.are.not.supported.in.typeddict"))
return@processClassLevelDeclarations true
}
if (element.name in ancestorsFields) {
registerProblem(element, PyPsiBundle.message("INSP.typeddict.cannot.overwrite.typeddict.field"))
return@processClassLevelDeclarations true
}
checkValueIsAType(element.annotation?.value, element.annotationValue)
true
}
}
override fun visitPyDelStatement(node: PyDelStatement) {
for (target in node.targets) {
for (expr in PyUtil.flattenedParensAndTuples(target)) {
if (expr !is PySubscriptionExpression) continue
val type = myTypeEvalContext.getType(expr.operand)
if (type is PyTypedDictType) {
val index = PyEvaluator.evaluate(expr.indexExpression, String::class.java)
if (index == null || index !in type.fields) continue
if (type.fields[index]!!.isRequired) {
registerProblem(expr.indexExpression, PyPsiBundle.message("INSP.typeddict.key.cannot.be.deleted", index, type.name))
}
}
}
}
}
override fun visitPyCallExpression(node: PyCallExpression) {
val callee = node.callee
if (callee !is PyReferenceExpression || callee.qualifier == null) return
val nodeType = myTypeEvalContext.getType(callee.qualifier!!)
if (nodeType !is PyTypedDictType) return
val arguments = node.arguments
if (PyNames.UPDATE == callee.name) {
inspectUpdateSequenceArgument(
if (arguments.size == 1 && arguments[0] is PySequenceExpression) (arguments[0] as PySequenceExpression).elements else arguments,
nodeType)
}
if (PyNames.CLEAR == callee.name || PyNames.POPITEM == callee.name) {
if (nodeType.fields.any { it.value.isRequired }) {
registerProblem(callee.nameElement?.psi, PyPsiBundle.message("INSP.typeddict.this.operation.might.break.typeddict.consistency"),
if (PyNames.CLEAR == callee.name) ProblemHighlightType.WARNING else ProblemHighlightType.WEAK_WARNING)
}
}
if (PyNames.POP == callee.name) {
val key = if (arguments.isNotEmpty()) PyEvaluator.evaluate(arguments[0], String::class.java) else null
if (key != null && key in nodeType.fields && nodeType.fields[key]!!.isRequired) {
registerProblem(callee.nameElement?.psi, PyPsiBundle.message("INSP.typeddict.key.cannot.be.deleted", key, nodeType.name))
}
}
if (PyNames.SETDEFAULT == callee.name) {
val key = if (arguments.isNotEmpty()) PyEvaluator.evaluate(arguments[0], String::class.java) else null
if (key != null && key in nodeType.fields && !nodeType.fields[key]!!.isRequired) {
if (node.arguments.size > 1) {
val valueType = myTypeEvalContext.getType(arguments[1])
if (!PyTypeChecker.match(nodeType.fields[key]!!.type, valueType, myTypeEvalContext)) {
val expectedTypeName = PythonDocumentationProvider.getTypeName(nodeType.fields[key]!!.type,
myTypeEvalContext)
val actualTypeName = PythonDocumentationProvider.getTypeName(valueType, myTypeEvalContext)
registerProblem(arguments[1],
PyPsiBundle.message("INSP.type.checker.expected.type.got.type.instead", expectedTypeName, actualTypeName))
}
}
}
}
if (PyTypingTypeProvider.resolveToQualifiedNames(callee, myTypeEvalContext).contains(PyTypingTypeProvider.MAPPING_GET)) {
val keyArgument = node.getArgument(0, "key", PyExpression::class.java) ?: return
val key = PyEvaluator.evaluate(keyArgument, String::class.java)
if (key == null) {
registerProblem(keyArgument, PyPsiBundle.message("INSP.typeddict.key.should.be.string"))
return
}
if (!nodeType.fields.containsKey(key)) {
registerProblem(keyArgument, PyPsiBundle.message("INSP.typeddict.typeddict.has.no.key", nodeType.name, key))
}
}
}
override fun visitPyAssignmentStatement(node: PyAssignmentStatement) {
val targetsToValuesMapping = node.targetsToValuesMapping
node.targets.forEach { target ->
if (target !is PySubscriptionExpression) return@forEach
val targetType = myTypeEvalContext.getType(target.operand)
if (targetType !is PyTypedDictType) return@forEach
val indexString = PyEvaluator.evaluate(target.indexExpression, String::class.java)
if (indexString == null) return@forEach
val expected = targetType.getElementType(indexString)
val actualExpressions = targetsToValuesMapping.filter { it.first == target }.map { it.second }
actualExpressions.forEach { actual ->
val actualType = myTypeEvalContext.getType(actual)
if (!PyTypeChecker.match(expected, actualType, myTypeEvalContext)) {
val expectedTypeName = PythonDocumentationProvider.getTypeName(expected, myTypeEvalContext)
val actualTypeName = PythonDocumentationProvider.getTypeName(actualType, myTypeEvalContext)
registerProblem(actual,
PyPsiBundle.message("INSP.type.checker.expected.type.got.type.instead", expectedTypeName, actualTypeName))
}
}
}
}
private fun getIndexExpressionValueOptions(indexExpression: PyExpression?): List<String>? {
if (indexExpression == null) return null
val indexExprValue = PyEvaluator.evaluate(indexExpression, String::class.java)
if (indexExprValue == null) {
val type = myTypeEvalContext.getType(indexExpression) ?: return null
val members = PyTypeUtil.toStream(type)
.map { if (it is PyLiteralType) PyEvaluator.evaluate(it.expression, String::class.java) else null }
.toList()
return if (members.contains(null)) null
else members
.filterNotNull()
}
else {
return listOf(indexExprValue)
}
}
/**
* Checks that [expression] with [strType] name is a type
*/
private fun checkValueIsAType(expression: PyExpression?, strType: String?) {
if (expression !is PyReferenceExpression && expression !is PySubscriptionExpression && expression !is PyNoneLiteralExpression || strType == null) {
registerProblem(expression, PyPsiBundle.message("INSP.typeddict.value.must.be.type"), ProblemHighlightType.WEAK_WARNING)
return
}
val type = Ref.deref(PyTypingTypeProvider.getStringBasedType(strType, expression, myTypeEvalContext))
if (type == null && !PyTypingTypeProvider.resolveToQualifiedNames(expression, myTypeEvalContext).any { qualifiedName ->
PyTypingTypeProvider.ANY == qualifiedName
}) {
registerProblem(expression, PyPsiBundle.message("INSP.typeddict.value.must.be.type"), ProblemHighlightType.WEAK_WARNING)
}
}
private fun tryGetNameIdentifier(element: PsiElement): PsiElement {
return if (element is PsiNameIdentifierOwner) element.nameIdentifier ?: element else element
}
private fun checkValidTotality(totalityValue: PyExpression) {
if (LanguageLevel.forElement(totalityValue.originalElement).isPy3K && totalityValue !is PyBoolLiteralExpression ||
!listOf(PyNames.TRUE, PyNames.FALSE).contains(totalityValue.text)) {
registerProblem(totalityValue, PyPsiBundle.message("INSP.typeddict.total.value.must.be.true.or.false"))
}
}
private fun matchTypedDictFieldTypeAndTotality(expected: PyTypedDictType.FieldTypeAndTotality,
actual: PyTypedDictType.FieldTypeAndTotality): Boolean {
return expected.isRequired == actual.isRequired &&
PyTypeChecker.match(expected.type, actual.type, myTypeEvalContext)
}
private fun inspectUpdateSequenceArgument(sequenceElements: Array<PyExpression>, typedDictType: PyTypedDictType) {
sequenceElements.forEach {
var key: PsiElement? = null
var keyAsString: String? = null
var value: PyExpression? = null
if (it is PyKeyValueExpression && it.key is PyStringLiteralExpression) {
key = it.key
keyAsString = (it.key as PyStringLiteralExpression).stringValue
value = it.value
}
else if (it is PyParenthesizedExpression) {
val expression = PyPsiUtils.flattenParens(it)
if (expression == null) return@forEach
if (expression is PyTupleExpression && expression.elements.size == 2 && expression.elements[0] is PyStringLiteralExpression) {
key = expression.elements[0]
keyAsString = (expression.elements[0] as PyStringLiteralExpression).stringValue
value = expression.elements[1]
}
}
else if (it is PyKeywordArgument && it.valueExpression != null) {
key = it.keywordNode?.psi
keyAsString = it.keyword
value = it.valueExpression
}
else return@forEach
val fields = typedDictType.fields
if (value == null) {
return@forEach
}
if (keyAsString == null) {
registerProblem(key, PyPsiBundle.message("INSP.typeddict.cannot.add.non.string.key.to.typeddict", typedDictType.name))
return@forEach
}
if (!fields.containsKey(keyAsString)) {
registerProblem(key, PyPsiBundle.message("INSP.typeddict.typeddict.cannot.have.key", typedDictType.name, keyAsString))
return@forEach
}
val valueType = myTypeEvalContext.getType(value)
if (!PyTypeChecker.match(fields[keyAsString]?.type, valueType, myTypeEvalContext)) {
val expectedTypeName = PythonDocumentationProvider.getTypeName(fields[keyAsString]!!.type, myTypeEvalContext)
val actualTypeName = PythonDocumentationProvider.getTypeName(valueType, myTypeEvalContext)
registerProblem(value, PyPsiBundle.message("INSP.type.checker.expected.type.got.type.instead", expectedTypeName, actualTypeName))
return@forEach
}
}
}
}
} | apache-2.0 | e82488736e8e48db8e1231273786ee83 | 48.580556 | 153 | 0.686071 | 4.941307 | false | false | false | false |
udevbe/westford | compositor/src/main/kotlin/org/westford/compositor/protocol/WlSubcompositor.kt | 3 | 4737 | /*
* Westford Wayland Compositor.
* Copyright (C) 2016 Erik De Rijcke
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.westford.compositor.protocol
import org.freedesktop.wayland.server.*
import org.freedesktop.wayland.shared.WlSubcompositorError
import org.westford.compositor.core.Subsurface
import org.westford.compositor.core.SubsurfaceFactory
import java.util.*
import javax.annotation.Nonnegative
import javax.inject.Inject
import javax.inject.Singleton
@Singleton class WlSubcompositor @Inject internal constructor(display: Display,
private val wlSubSurfaceFactory: WlSubsurfaceFactory,
private val subsurfaceFactory: SubsurfaceFactory) : Global<WlSubcompositorResource>(display,
WlSubcompositorResource::class.java,
WlSubcompositorRequests.VERSION), WlSubcompositorRequests, ProtocolObject<WlSubcompositorResource> {
override val resources: MutableSet<WlSubcompositorResource> = Collections.newSetFromMap(WeakHashMap<WlSubcompositorResource, Boolean>())
override fun destroy(resource: WlSubcompositorResource) = resource.destroy()
override fun getSubsurface(requester: WlSubcompositorResource,
id: Int,
wlSurfaceResource: WlSurfaceResource,
parentWlSurfaceResource: WlSurfaceResource) {
val wlSurface = wlSurfaceResource.implementation as WlSurface
val surface = wlSurface.surface
val role = surface.role
val hasRole = role != null
/*
* Check if the surface does not have a role or has an inactive subsurface role, both are ok. Otherwise we raise
* a protocol error.
*/
if (!hasRole || role is Subsurface && role.inert) {
val subsurface = this.subsurfaceFactory.create(parentWlSurfaceResource,
wlSurfaceResource)
surface.role = subsurface
if (!hasRole) {
}
val wlSubsurface = this.wlSubSurfaceFactory.create(subsurface)
val wlSubsurfaceResource = wlSubsurface.add(requester.client,
requester.version,
id)
wlSurfaceResource.register {
wlSubsurfaceResource.destroy()
}
}
else {
requester.client.getObject(Display.OBJECT_ID).postError(WlSubcompositorError.BAD_SURFACE.value,
String.format("Desired sub surface already has another role (%s)",
role?.javaClass?.simpleName))
}
}
override fun create(client: Client,
@Nonnegative version: Int,
id: Int): WlSubcompositorResource = WlSubcompositorResource(client,
version,
id,
this)
override fun onBindClient(client: Client,
version: Int,
id: Int): WlSubcompositorResource = WlSubcompositorResource(client,
version,
id,
this)
}
| agpl-3.0 | 1597d29a38a571870cd53d70ef49a116 | 50.48913 | 246 | 0.512983 | 6.410014 | false | false | false | false |
rodm/teamcity-gradle-init-scripts-plugin | server/src/main/kotlin/com/github/rodm/teamcity/gradle/scripts/server/health/MissingInitScriptsHealthReport.kt | 1 | 5405 | /*
* Copyright 2017 Rod MacKenzie.
*
* 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.rodm.teamcity.gradle.scripts.server.health
import com.github.rodm.teamcity.gradle.scripts.GradleInitScriptsPlugin.FEATURE_TYPE
import com.github.rodm.teamcity.gradle.scripts.GradleInitScriptsPlugin.INIT_SCRIPT_NAME
import com.github.rodm.teamcity.gradle.scripts.GradleInitScriptsPlugin.INIT_SCRIPT_NAME_PARAMETER
import com.github.rodm.teamcity.gradle.scripts.server.GradleScriptsManager
import jetbrains.buildServer.serverSide.BuildTypeTemplate
import jetbrains.buildServer.serverSide.SBuildType
import jetbrains.buildServer.serverSide.healthStatus.HealthStatusItem
import jetbrains.buildServer.serverSide.healthStatus.HealthStatusItemConsumer
import jetbrains.buildServer.serverSide.healthStatus.HealthStatusReport
import jetbrains.buildServer.serverSide.healthStatus.HealthStatusScope
import jetbrains.buildServer.serverSide.healthStatus.ItemCategory
import jetbrains.buildServer.serverSide.healthStatus.ItemSeverity.WARN
import jetbrains.buildServer.web.openapi.PagePlaces
import jetbrains.buildServer.web.openapi.PluginDescriptor
import jetbrains.buildServer.web.openapi.healthStatus.HealthStatusItemPageExtension
enum class StatusType {
BUILD_RUNNER, BUILD_FEATURE
}
class MissingInitScriptsHealthReport(private val scriptsManager: GradleScriptsManager,
pagePlaces: PagePlaces,
descriptor: PluginDescriptor) : HealthStatusReport()
{
private val TYPE = "MissingInitScriptsReport"
private val CATEGORY = ItemCategory("missing_init_scripts", "Missing Gradle init scripts", WARN)
init {
val pageExtension = HealthStatusItemPageExtension(TYPE, pagePlaces)
pageExtension.includeUrl = descriptor.getPluginResourcesPath("/health/missingInitScripts.jsp")
pageExtension.isVisibleOutsideAdminArea = true
pageExtension.addCssFile("/css/admin/buildTypeForm.css")
pageExtension.register()
}
override fun getType() = TYPE
override fun getDisplayName() = "Missing Gradle Init Scripts"
override fun getCategories() = listOf(CATEGORY)
override fun canReportItemsFor(scope: HealthStatusScope): Boolean {
return scope.isItemWithSeverityAccepted(CATEGORY.severity)
}
override fun report(scope: HealthStatusScope, resultConsumer: HealthStatusItemConsumer) {
val reportBuildType = { buildType: SBuildType, name: String?, statusType: StatusType ->
if (name != null) {
val scriptContents = scriptsManager.findScript(buildType.project, name)
if (scriptContents == null) {
val data = mapOf("buildType" to buildType, "scriptName" to name, "statusType" to statusType)
val identity = CATEGORY.id + "_" + statusType + "_" + buildType.buildTypeId
val statusItem = HealthStatusItem(identity, CATEGORY, data)
resultConsumer.consumeForBuildType(buildType, statusItem)
}
}
}
val reportBuildTemplate = { buildTemplate: BuildTypeTemplate, name: String?, statusType: StatusType ->
if (name != null) {
val scriptContents = scriptsManager.findScript(buildTemplate.project, name)
if (scriptContents == null) {
val data = mapOf("buildTemplate" to buildTemplate, "scriptName" to name, "statusType" to statusType)
val identity = CATEGORY.id + "_" + statusType + "_" + buildTemplate.id
val statusItem = HealthStatusItem(identity, CATEGORY, data)
resultConsumer.consumeForTemplate(buildTemplate, statusItem)
}
}
}
for (buildType in scope.buildTypes) {
buildType.buildRunners.forEach { runner ->
val scriptName = runner.parameters[INIT_SCRIPT_NAME_PARAMETER]
reportBuildType(buildType, scriptName, StatusType.BUILD_RUNNER)
}
buildType.getBuildFeaturesOfType(FEATURE_TYPE).forEach { feature ->
val scriptName = feature.parameters[INIT_SCRIPT_NAME]
reportBuildType(buildType, scriptName, StatusType.BUILD_FEATURE)
}
}
for (buildTemplate in scope.buildTypeTemplates) {
buildTemplate.buildRunners.forEach { runner ->
val scriptName = runner.parameters[INIT_SCRIPT_NAME_PARAMETER]
reportBuildTemplate(buildTemplate, scriptName, StatusType.BUILD_RUNNER)
}
buildTemplate.getBuildFeaturesOfType(FEATURE_TYPE).forEach { feature ->
val scriptName = feature.parameters[INIT_SCRIPT_NAME]
reportBuildTemplate(buildTemplate, scriptName, StatusType.BUILD_FEATURE)
}
}
}
}
| apache-2.0 | 9af74bf58b176072d5929f643ebf402f | 48.587156 | 120 | 0.700278 | 4.895833 | false | false | false | false |
faceofcat/Tesla-Core-Lib | src/main/kotlin/net/ndrei/teslacorelib/netsync/SimpleNBTMessage.kt | 1 | 2352 | package net.ndrei.teslacorelib.netsync
import io.netty.buffer.ByteBuf
import net.minecraft.nbt.NBTTagCompound
import net.minecraft.tileentity.TileEntity
import net.minecraft.util.math.BlockPos
import net.minecraftforge.fml.common.network.ByteBufUtils
import net.minecraftforge.fml.common.network.NetworkRegistry
import net.minecraftforge.fml.common.network.simpleimpl.IMessage
import net.ndrei.teslacorelib.TeslaCoreLib
/**
* Created by CF on 2017-06-28.
*/
class SimpleNBTMessage(pos: BlockPos?, dimension: Int?, compound: NBTTagCompound?) : IMessage {
var compound: NBTTagCompound? = null
private set
var pos: BlockPos? = null
private set
var dimension: Int? = null
private set
@Suppress("unused")
constructor() : this(null, null, null)
constructor(entity: TileEntity, compound: NBTTagCompound)
: this(entity.pos, entity.world.provider.dimension, compound)
init {
this.pos = pos
this.dimension = dimension
this.compound = compound
}
override fun fromBytes(buf: ByteBuf) {
val pos = ByteBufUtils.readTag(buf)
if (pos != null) {
this.pos = BlockPos(pos.getInteger("x"), pos.getInteger("y"), pos.getInteger("z"))
this.dimension = pos.getInteger("dim")
} else {
TeslaCoreLib.logger.warn("Network package received with missing BlockPos information.")
this.pos = BlockPos(0, 0, 0)
this.dimension = 0
}
this.compound = ByteBufUtils.readTag(buf) ?: NBTTagCompound()
}
override fun toBytes(buf: ByteBuf) {
val pos = NBTTagCompound()
if (this.pos != null) {
pos.setInteger("x", this.pos!!.x)
pos.setInteger("y", this.pos!!.y)
pos.setInteger("z", this.pos!!.z)
}
if (this.dimension != null) {
pos.setInteger("dim", this.dimension!!)
}
ByteBufUtils.writeTag(buf, pos)
if (this.compound != null) {
ByteBufUtils.writeTag(buf, this.compound)
}
}
val targetPoint: NetworkRegistry.TargetPoint?
get() = if ((this.dimension != null) && (this.pos != null))
NetworkRegistry.TargetPoint(this.dimension!!, this.pos!!.x.toDouble(), this.pos!!.y.toDouble(), this.pos!!.z.toDouble(), 64.0)
else null
}
| mit | c8ee21601ea8a5fdf7e23d084544cb9a | 33.588235 | 138 | 0.633078 | 4.126316 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.