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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
industrial-data-space/trusted-connector | example-route-builder/src/main/kotlin/de/fhg/aisec/ids/ExampleConnector.kt | 1 | 2230 | /*-
* ========================LICENSE_START=================================
* example-route-builder
* %%
* Copyright (C) 2021 Fraunhofer AISEC
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =========================LICENSE_END==================================
*/
package de.fhg.aisec.ids
import org.apache.camel.support.jsse.KeyManagersParameters
import org.apache.camel.support.jsse.KeyStoreParameters
import org.apache.camel.support.jsse.SSLContextParameters
import org.apache.camel.support.jsse.TrustManagersParameters
import org.springframework.boot.autoconfigure.SpringBootApplication
import org.springframework.boot.runApplication
import java.nio.file.FileSystems
@SpringBootApplication
open class ExampleConnector : TrustedConnector() {
companion object {
@JvmStatic
fun main(args: Array<String>) {
runApplication<ExampleConnector>(*args)
}
fun getSslContext(): SSLContextParameters {
return SSLContextParameters().apply {
certAlias = "1.0.1"
keyManagers = KeyManagersParameters().apply {
keyStore = KeyStoreParameters().apply {
resource = FileSystems.getDefault().getPath("etc", "consumer-keystore.p12").toFile().path
password = "password"
}
}
trustManagers = TrustManagersParameters().apply {
keyStore = KeyStoreParameters().apply {
resource = FileSystems.getDefault().getPath("etc", "truststore.p12").toFile().path
password = "password"
}
}
}
}
}
}
| apache-2.0 | 8437acf7bc4b63444aa3f22c6fca1ca1 | 38.122807 | 113 | 0.613004 | 5.022523 | false | false | false | false |
takuji31/Koreference | koreference-observable/src/main/java/jp/takuji31/koreference/observable/KoreferenceModelObservableExtensions.kt | 1 | 1454 | package jp.takuji31.koreference.observable
import android.content.SharedPreferences
import io.reactivex.Observable
import io.reactivex.Single
import jp.takuji31.koreference.KoreferenceModel
import kotlin.reflect.KProperty1
inline fun <reified T : KoreferenceModel, reified R> T.getValueAsSingle(property: KProperty1<T, R>): Single<R> {
getKoreferencePropertyKey(this, property)
return Single.fromCallable {
property.get(this)
}
}
inline fun <reified T : KoreferenceModel, reified R> T.observe(property: KProperty1<T, R>): Observable<R> {
val key = getKoreferencePropertyKey(this, property)
return Observable.create { emitter ->
val initialiValue = property.get(this)
val listener = SharedPreferences.OnSharedPreferenceChangeListener { _, changedKey ->
if (changedKey == key) {
emitter.onNext(property.get(this))
}
}
emitter.onNext(initialiValue)
sharedPreferences.registerOnSharedPreferenceChangeListener(listener)
emitter.setCancellable {
sharedPreferences.unregisterOnSharedPreferenceChangeListener(listener)
}
}
}
fun <T : KoreferenceModel, R> getKoreferencePropertyKey(receiver: T, property: KProperty1<T, R>): String {
return receiver.getSharedPreferencesKey(property.name) ?: throw IllegalArgumentException("${receiver::class.qualifiedName}.${property.name} is not Koreference delegate property")
}
| apache-2.0 | ed02003e27114aaf5d5fc746dba27e73 | 39.388889 | 182 | 0.730399 | 4.473846 | false | false | false | false |
zhengjiong/ZJ_KotlinStudy | src/main/kotlin/com/zj/example/kotlin/basicsknowledge/38.AnonymousInnerClassExample匿名内部类.kt | 1 | 2145 | package com.zj.example.kotlin.basicsknowledge
/**
*
* CreateTime: 17/9/22 08:52
* @author 郑炯
*/
fun main(vararg args: String) {
var view = View()
//匿名内部类必须使用object关键字
view.clickListener = object : OnClickListener {
override fun click(view: View) {
println("click")
}
}
view.clickListener?.click(view)
/**
* kotlin中的匿名内部类还可以实现一个接口同时还可以继承一个父类
*/
view.clickListener = object : AbsClass(), OnClickListener {
override fun test() {
}
override fun click(view: View) {
}
}
/**
* 对象表达式
* https://hltj.gitbooks.io/kotlin-reference-chinese/content/txt/object-declarations.html#对象表达式
*/
var listener: OnClickListener = object : OnClickListener {
override fun click(view: View) {
}
}
/**
* 如果我们只需要“一个对象而已”,并不需要特殊超类型,那么我们可以简单地写:
*/
var listener2 = object {
var x: Int = 1
var y: Int = 2
}
println(listener2.x)
println(listener2.y)
}
class View {
var clickListener: OnClickListener? = null
}
interface OnClickListener {
fun click(view: View)
}
abstract class AbsClass {
abstract fun test();
}
/**
* 请注意,匿名对象可以用作只在本地和私有作用域中声明的类型。如果你使用匿名对象作为公有函数的返回类
* 型或者用作公有属性的类型,那么该函数或属性的实际类型会是匿名对象声明的超类型,如果你没有声明任何
* 超类型,就会是 Any。在匿名对象中添加的成员将无法访问(比如pubFoo中的y)
*/
class AA{
// 私有函数,所以其返回类型是匿名对象类型
private fun foo() = object{
val x = 0
}
// 公有函数,所以其返回类型是 Any
fun pubFoo() = object {
val y = "y"
}
fun bar(){
val x1 = foo().x
//val x2 = pubFoo().y// 错误:未能解析的引用“y”
}
} | mit | 5201b68a419f2c1075f6aa01dd2bdfd4 | 15.865979 | 99 | 0.587156 | 3.090737 | false | false | false | false |
luhaoaimama1/AndroidZone | JavaTest_Zone/src/a_新手/TestListAddNull.kt | 2 | 1151 | package a_新手
/**
* Created by fuzhipeng on 2018/9/7.
*/
fun main(args: Array<String>) {
val arr1 = ArrayList<String?>()
val arr2 = ArrayList<String?>()
val arr3 = ArrayList<String?>()
val listCollection = ListCollection<String?>()
listCollection.list.add(arr1)
listCollection.list.add(arr2)
arr1.add("arg1_1")
arr1.add("arg1_2")
arr1.add("arg1_3")
arr2.add("arg2_1")
arr2.add("arg2_2")
arr2.add("arg3_1")
arr2.add("arg3_2")
arr2.add("arg3_3")
println(listCollection.count())
for (i in -1..8) {
println(listCollection.getItem(i))
}
}
class ListCollection<T> {
var list = ArrayList<ArrayList<T?>>()
fun count(): Int {
var tempCount = 0
list.forEach { tempCount += it.count() }
return tempCount
}
fun getItem(pos: Int): T? {
if (pos < 0) return null //小于0
var iterPos = 0
list.forEachIndexed { index, arrayList ->
arrayList.forEachIndexed { index2, t ->
if (iterPos == pos) return t
iterPos++
}
}
return null //超过
}
} | epl-1.0 | 815ea694af581637ce59427a022d028e | 21.8 | 51 | 0.552239 | 3.311047 | false | false | false | false |
LorittaBot/Loritta | discord/loritta-bot-common/src/main/kotlin/net/perfectdreams/loritta/morenitta/commands/vanilla/discord/AvatarCommand.kt | 1 | 3089 | package net.perfectdreams.loritta.morenitta.commands.vanilla.discord
import com.github.salomonbrys.kotson.nullString
import com.github.salomonbrys.kotson.obj
import net.perfectdreams.loritta.morenitta.commands.AbstractCommand
import net.perfectdreams.loritta.morenitta.commands.CommandContext
import net.perfectdreams.loritta.morenitta.utils.Constants
import net.dv8tion.jda.api.EmbedBuilder
import net.perfectdreams.loritta.common.commands.ArgumentType
import net.perfectdreams.loritta.common.commands.CommandArguments
import net.perfectdreams.loritta.common.commands.arguments
import net.perfectdreams.loritta.common.locale.BaseLocale
import net.perfectdreams.loritta.common.locale.LocaleKeyData
import net.perfectdreams.loritta.common.utils.Emotes
import net.perfectdreams.loritta.morenitta.utils.OutdatedCommandUtils
import java.util.*
import net.perfectdreams.loritta.morenitta.LorittaBot
class AvatarCommand(loritta: LorittaBot) : AbstractCommand(loritta, "avatar", category = net.perfectdreams.loritta.common.commands.CommandCategory.DISCORD) {
companion object {
const val LOCALE_PREFIX = "commands.command.avatar"
}
override fun getDescriptionKey() = LocaleKeyData("commands.command.avatar.description")
override fun getUsage(): CommandArguments {
return arguments {
argument(ArgumentType.USER) {
optional = true
}
}
}
override fun getExamplesKey() = LocaleKeyData("commands.command.avatar.examples")
override suspend fun run(context: CommandContext,locale: BaseLocale) {
OutdatedCommandUtils.sendOutdatedCommandMessage(context, locale, "user avatar")
var getAvatar = context.getUserAt(0)
if (getAvatar == null) {
getAvatar = context.userHandle
}
val embed = EmbedBuilder()
embed.setColor(Constants.DISCORD_BLURPLE) // Cor do embed (Cor padrão do Discord)
embed.setDescription("**${context.locale["$LOCALE_PREFIX.clickHere", "${getAvatar.effectiveAvatarUrl}?size=2048"]}**")
// Easter Egg: Pantufa
if (getAvatar.idLong == 390927821997998081L)
embed.appendDescription("\n*${context.locale["$LOCALE_PREFIX.pantufaCute"]}* ${Emotes.LORI_TEMMIE}")
// Easter Egg: Gabriela
if (getAvatar.idLong == 481901252007952385L)
embed.appendDescription("\n*${context.locale["$LOCALE_PREFIX.gabrielaCute"]}* ${Emotes.LORI_PAT}")
// Easter Egg: Pollux
if (getAvatar.idLong == 271394014358405121L || getAvatar.idLong == 354285599588483082L || getAvatar.idLong == 578913818961248256L)
embed.appendDescription("\n*${context.locale["$LOCALE_PREFIX.polluxCute"]}* ${Emotes.LORI_HEART}")
// Easter Egg: Loritta
if (getAvatar.id == loritta.config.loritta.discord.applicationId.toString()) {
val calendar = Calendar.getInstance(TimeZone.getTimeZone(Constants.LORITTA_TIMEZONE))
val currentDay = calendar.get(Calendar.DAY_OF_WEEK)
embed.appendDescription("\n*${context.locale["$LOCALE_PREFIX.lorittaCute"]}* ${Emotes.LORI_SMILE}")
}
embed.setTitle("\uD83D\uDDBC ${getAvatar.name}")
embed.setImage("${getAvatar.effectiveAvatarUrl}?size=2048")
context.sendMessage(context.getAsMention(true), embed.build())
}
} | agpl-3.0 | a843088bdf0be0d258ad6f2ff7ab36d6 | 41.315068 | 157 | 0.781412 | 3.821782 | false | false | false | false |
LorittaBot/Loritta | discord/loritta-bot-common/src/main/kotlin/net/perfectdreams/loritta/morenitta/platform/discord/utils/RateLimitChecker.kt | 1 | 3502 | package net.perfectdreams.loritta.morenitta.platform.discord.utils
import net.perfectdreams.loritta.morenitta.LorittaBot
import mu.KotlinLogging
import net.dv8tion.jda.api.JDA
import net.dv8tion.jda.internal.JDAImpl
import net.dv8tion.jda.internal.requests.RateLimiter
import net.dv8tion.jda.internal.requests.Requester
import net.dv8tion.jda.internal.requests.ratelimit.BotRateLimiter
import net.dv8tion.jda.internal.requests.ratelimit.IBucket
import java.util.concurrent.ConcurrentHashMap
class RateLimitChecker(val m: LorittaBot) {
companion object {
private val logger = KotlinLogging.logger {}
val requesterField by lazy {
val field = JDAImpl::class.java.getDeclaredField("requester")
field.isAccessible = true
field
}
val rateLimiterField by lazy {
val field = Requester::class.java.getDeclaredField("rateLimiter")
field.isAccessible = true
field
}
val bucketsField by lazy {
val field = BotRateLimiter::class.java.getDeclaredField("buckets")
field.isAccessible = true
field
}
fun getRateLimiter(jda: JDA): RateLimiter {
val requester = requesterField.get(jda) as Requester
val rateLimiter = rateLimiterField.get(requester) as RateLimiter
return rateLimiter
}
}
var lastRequestWipe = System.currentTimeMillis()
var lastConsoleWarn = System.currentTimeMillis()
fun getAllPendingRequests() = m.lorittaShards.shardManager.shards.flatMap {
val rateLimiter = getRateLimiter(it)
val buckets = bucketsField.get(rateLimiter) as ConcurrentHashMap<String, IBucket>
buckets.flatMap { it.value.requests }
}
fun cancelAllPendingRequests() {
getAllPendingRequests().map { it.cancel() }
}
fun checkIfRequestShouldBeIgnored(): Boolean {
if (!m.config.loritta.discord.requestLimiter.enabled)
return false
// https://i.imgur.com/crENfcG.png
// Um bot pode fazer 25k requests inválidos em 10 minutos
// O limite é 25k https://cdn.discordapp.com/attachments/409847691896422410/672573213284237312/unknown.png
// Para calcular, vamos fazer que seja (25k / número de clusters)
// Mas para a gente não ficar muito "em cima do muro", vamos colocar (20k / número de clusters)
//
// O certo era ser 20k, mas parece que o Discord é muito trigger happy com bans, então é melhor deixar um valor
// extremamente baixo porque ficar alguns minutos sem responder comandos é bem melhor do que ser banido por
// uma hora
val rateLimitHits = m.bucketedController?.getGlobalRateLimitHitsInTheLastMinute() ?: 0
val maxRequestsPer10Minutes = m.config.loritta.discord.requestLimiter.maxRequestsPer10Minutes
val shouldIgnore = rateLimitHits >= maxRequestsPer10Minutes
if (shouldIgnore) {
val diff2 = System.currentTimeMillis() - this.lastConsoleWarn
if (diff2 >= m.config.loritta.discord.requestLimiter.consoleWarnCooldown) {
logger.warn { "All received events are cancelled and ignored due to too many global ratelimited requests being sent! $rateLimitHits >= $maxRequestsPer10Minutes" }
this.lastConsoleWarn = System.currentTimeMillis()
}
val diff = System.currentTimeMillis() - lastRequestWipe
if (diff >= m.config.loritta.discord.requestLimiter.removePendingRequestsCooldown) {
logger.info { "Cancelling and removing outdated global rate limit hits..." }
m.bucketedController?.removeOutdatedGlobalRateLimitHits()
// Limpar todos os requests pendentes
cancelAllPendingRequests()
this.lastRequestWipe = System.currentTimeMillis()
}
}
return shouldIgnore
}
} | agpl-3.0 | a07dd56f0110a8205de4fa6b205e3101 | 36.170213 | 166 | 0.769825 | 3.623444 | false | false | false | false |
cketti/okhttp | okhttp-brotli/src/main/kotlin/okhttp3/brotli/BrotliInterceptor.kt | 1 | 2280 | /*
* Copyright (C) 2019 Square, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package okhttp3.brotli
import okhttp3.Interceptor
import okhttp3.Response
import okhttp3.ResponseBody.Companion.asResponseBody
import okhttp3.internal.http.promisesBody
import okio.GzipSource
import okio.buffer
import okio.source
import org.brotli.dec.BrotliInputStream
/**
* Transparent Brotli response support.
*
* Adds Accept-Encoding: br to request and checks (and strips) for Content-Encoding: br in
* responses. n.b. this replaces the transparent gzip compression in BridgeInterceptor.
*/
object BrotliInterceptor : Interceptor {
override fun intercept(chain: Interceptor.Chain): Response =
if (chain.request().header("Accept-Encoding") == null) {
val request = chain.request().newBuilder()
.header("Accept-Encoding", "br,gzip")
.build()
val response = chain.proceed(request)
uncompress(response)
} else {
chain.proceed(chain.request())
}
internal fun uncompress(response: Response): Response {
if (!response.promisesBody()) {
return response
}
val body = response.body ?: return response
val encoding = response.header("Content-Encoding") ?: return response
val decompressedSource = when {
encoding.equals("br", ignoreCase = true) ->
BrotliInputStream(body.source().inputStream()).source().buffer()
encoding.equals("gzip", ignoreCase = true) ->
GzipSource(body.source()).buffer()
else -> return response
}
return response.newBuilder()
.removeHeader("Content-Encoding")
.removeHeader("Content-Length")
.body(decompressedSource.asResponseBody(body.contentType(), -1))
.build()
}
}
| apache-2.0 | c3df69537124226aa3436eff2812b6fc | 32.529412 | 90 | 0.697368 | 4.261682 | false | false | false | false |
carlphilipp/chicago-commutes | android-app/src/main/kotlin/fr/cph/chicago/core/fragment/BikeFragment.kt | 1 | 4859 | /**
* Copyright 2021 Carl-Philipp Harmant
*
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*
* http://www.apache.org/licenses/LICENSE-2.0
*
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package fr.cph.chicago.core.fragment
import android.os.Bundle
import android.text.Editable
import android.text.TextWatcher
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import fr.cph.chicago.core.activity.MainActivity
import fr.cph.chicago.core.adapter.BikeAdapter
import fr.cph.chicago.core.model.BikeStation
import fr.cph.chicago.databinding.FragmentFilterListBinding
import fr.cph.chicago.redux.BikeStationAction
import fr.cph.chicago.redux.State
import fr.cph.chicago.redux.Status
import fr.cph.chicago.redux.store
import org.apache.commons.lang3.StringUtils
import org.rekotlin.StoreSubscriber
import timber.log.Timber
/**
* Bike Fragment
*
* @author Carl-Philipp Harmant
* @version 1
*/
class BikeFragment : RefreshFragment(), StoreSubscriber<State> {
companion object {
fun newInstance(sectionNumber: Int): BikeFragment {
return fragmentWithBundle(BikeFragment(), sectionNumber) as BikeFragment
}
}
private var _binding: FragmentFilterListBinding? = null
private val binding get() = _binding!!
private lateinit var bikeAdapter: BikeAdapter
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
_binding = FragmentFilterListBinding.inflate(inflater, container, false)
setUpSwipeRefreshLayout(binding.swipeRefreshLayout)
return binding.root
}
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
bikeAdapter = BikeAdapter()
binding.listView.adapter = bikeAdapter
(activity as MainActivity).toolBar.setOnMenuItemClickListener { startRefreshing(); true }
binding.error.retryButton.setOnClickListener { startRefreshing() }
}
override fun onResume() {
super.onResume()
store.subscribe(this)
if (store.state.bikeStations.isEmpty()) {
store.dispatch(BikeStationAction())
}
}
override fun onPause() {
super.onPause()
store.unsubscribe(this)
}
override fun newState(state: State) {
Timber.d("Bike stations new state")
when (state.bikeStationsStatus) {
Status.SUCCESS, Status.ADD_FAVORITES, Status.REMOVE_FAVORITES -> showSuccessLayout()
Status.FAILURE -> {
util.showSnackBar(swipeRefreshLayout, state.bikeStationsErrorMessage)
showSuccessLayout()
}
Status.FULL_FAILURE -> showFailureLayout()
else -> {
Timber.d("Unknown status on new state")
util.showSnackBar(swipeRefreshLayout, state.bikeStationsErrorMessage)
showFailureLayout()
}
}
updateData(state.bikeStations)
stopRefreshing()
}
private fun updateData(bikeStations: List<BikeStation>) {
bikeAdapter.updateBikeStations(bikeStations)
bikeAdapter.notifyDataSetChanged()
binding.filter.addTextChangedListener(object : TextWatcher {
private lateinit var bikeStationsLocal: List<BikeStation>
override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {
bikeStationsLocal = listOf()
}
override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {
bikeStationsLocal = bikeStations
.filter { station -> StringUtils.containsIgnoreCase(station.name, s.toString().trim { it <= ' ' }) }
}
override fun afterTextChanged(s: Editable) {
bikeAdapter.updateBikeStations(this.bikeStationsLocal)
bikeAdapter.notifyDataSetChanged()
}
})
}
private fun showSuccessLayout() {
binding.successLayout.visibility = View.VISIBLE
binding.error.failureLayout.visibility = View.GONE
}
private fun showFailureLayout() {
binding.successLayout.visibility = View.GONE
binding.error.failureLayout.visibility = View.VISIBLE
}
override fun startRefreshing() {
super.startRefreshing()
store.dispatch(BikeStationAction())
}
}
| apache-2.0 | a42cd290bf3cd988984268f58b493fa7 | 33.21831 | 120 | 0.683474 | 4.777778 | false | false | false | false |
ngageoint/mage-android | mage/src/main/java/mil/nga/giat/mage/geopackage/media/GeoPackageMediaActivity.kt | 1 | 2472 | package mil.nga.giat.mage.geopackage.media
import android.content.Context
import android.content.Intent
import android.os.Bundle
import androidx.activity.compose.setContent
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.FileProvider
import androidx.lifecycle.ViewModelProvider
import dagger.hilt.android.AndroidEntryPoint
import java.io.File
@AndroidEntryPoint
class GeoPackageMediaActivity : AppCompatActivity() {
private lateinit var viewModel: GeoPackageMediaViewModel
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
viewModel = ViewModelProvider(this).get(GeoPackageMediaViewModel::class.java)
val geoPackageName = intent.getStringExtra(GEOPACKAGE_NAME)
require(geoPackageName != null) { "GEOPACKAGE_NAME is required to launch GeoPackageMediaActivity" }
val mediaTable = intent.getStringExtra(GEOPACKAGE_MEDIA_TABLE)
require(mediaTable != null) { "GEOPACKAGE_MEDIA_TABLE is required to launch GeoPackageMediaActivity" }
val mediaId = intent.getLongExtra(GEOPACKAGE_MEDIA_ID, -1)
require(mediaId != -1L) { "GEOPACKAGE_MEDIA_ID is required to launch GeoPackageMediaActivity" }
viewModel.setMedia(geoPackageName, mediaTable, mediaId)
setContent {
GeoPackageMediaScreen(
liveData = viewModel.geoPackageMedia,
onOpen = { onOpen(it) },
onClose = { finish() }
)
}
}
private fun onOpen(media: GeoPackageMedia) {
val uri = FileProvider.getUriForFile(this, application.packageName + ".fileprovider", File(media.path))
val intent = Intent(Intent.ACTION_VIEW).apply {
type = contentResolver.getType(uri)
setDataAndType(uri,contentResolver.getType(uri));
flags = Intent.FLAG_GRANT_READ_URI_PERMISSION
}
startActivity(intent)
}
companion object {
private const val GEOPACKAGE_NAME = "GEOPACKAGE_NAME"
private const val GEOPACKAGE_MEDIA_TABLE = "GEOPACKAGE_MEDIA_TABLE"
private const val GEOPACKAGE_MEDIA_ID = "GEOPACKAGE_MEDIA_ID"
fun intent(context: Context, geoPackage: String, mediaTable: String, mediaId: Long): Intent {
return Intent(context, GeoPackageMediaActivity::class.java).apply {
putExtra(GEOPACKAGE_NAME, geoPackage)
putExtra(GEOPACKAGE_MEDIA_TABLE, mediaTable)
putExtra(GEOPACKAGE_MEDIA_ID, mediaId)
}
}
}
} | apache-2.0 | 93e851cfe0d44e87fef463e417b3ced6 | 35.910448 | 109 | 0.718042 | 4.336842 | false | false | false | false |
thermatk/FastHub-Libre | app/src/main/java/com/fastaccess/ui/modules/reviews/changes/ReviewChangesActivity.kt | 4 | 5821 | package com.fastaccess.ui.modules.reviews.changes
import android.content.Context
import android.os.Bundle
import android.support.v4.content.ContextCompat
import android.support.v7.widget.Toolbar
import android.view.View
import android.widget.Spinner
import butterknife.BindView
import com.evernote.android.state.State
import com.fastaccess.R
import com.fastaccess.data.dao.ReviewRequestModel
import com.fastaccess.helper.BundleConstant
import com.fastaccess.helper.Bundler
import com.fastaccess.helper.InputHelper
import com.fastaccess.ui.base.BaseDialogFragment
import com.fastaccess.ui.modules.editor.comment.CommentEditorFragment
/**
* Created by Kosh on 25 Jun 2017, 1:25 AM
*/
class ReviewChangesActivity : BaseDialogFragment<ReviewChangesMvp.View, ReviewChangesPresenter>(), ReviewChangesMvp.View {
@BindView(R.id.toolbar) lateinit var toolbar: Toolbar
@BindView(R.id.reviewMethod) lateinit var spinner: Spinner
@State var reviewRequest: ReviewRequestModel? = null
@State var repoId: String? = null
@State var owner: String? = null
@State var number: Long? = null
@State var isClosed: Boolean = false
@State var isAuthor: Boolean = false
private var subimssionCallback: ReviewChangesMvp.ReviewSubmissionCallback? = null
private val commentEditorFragment: CommentEditorFragment? by lazy {
childFragmentManager.findFragmentByTag("commentContainer") as CommentEditorFragment?
}
override fun onAttach(context: Context?) {
super.onAttach(context)
if (parentFragment is ReviewChangesMvp.ReviewSubmissionCallback) {
subimssionCallback = parentFragment as ReviewChangesMvp.ReviewSubmissionCallback
} else if (context is ReviewChangesMvp.ReviewSubmissionCallback) {
subimssionCallback = context
}
}
override fun onDetach() {
subimssionCallback = null
super.onDetach()
}
override fun providePresenter(): ReviewChangesPresenter = ReviewChangesPresenter()
override fun fragmentLayout(): Int = R.layout.add_review_dialog_layout
override fun onFragmentCreated(view: View, savedInstanceState: Bundle?) {
if (savedInstanceState == null) {
val fragment = CommentEditorFragment()
fragment.arguments = Bundler.start().put(BundleConstant.YES_NO_EXTRA, true).end()
childFragmentManager.beginTransaction()
.replace(R.id.commentContainer, fragment, "commentContainer")
.commit()
val bundle = arguments!!
reviewRequest = bundle.getParcelable(BundleConstant.EXTRA)
repoId = bundle.getString(BundleConstant.EXTRA_TWO)
owner = bundle.getString(BundleConstant.EXTRA_THREE)
number = bundle.getLong(BundleConstant.ID)
isClosed = bundle.getBoolean(BundleConstant.EXTRA_FIVE)
isAuthor = bundle.getBoolean(BundleConstant.EXTRA_FOUR)
}
toolbar.navigationIcon = ContextCompat.getDrawable(context!!, R.drawable.ic_clear)
toolbar.inflateMenu(R.menu.done_menu)
toolbar.setNavigationOnClickListener { dismiss() }
toolbar.setOnMenuItemClickListener {
if (it.itemId == R.id.submit) {
if (spinner.selectedItemPosition != 0 && commentEditorFragment?.getEditText()?.text.isNullOrEmpty()) {
commentEditorFragment?.getEditText()?.error = getString(R.string.required_field)
} else {
commentEditorFragment?.getEditText()?.error = null
presenter.onSubmit(reviewRequest!!, repoId!!, owner!!, number!!, InputHelper.toString(commentEditorFragment?.getEditText()?.text)
, spinner.selectedItem as String)
}
}
return@setOnMenuItemClickListener true
}
if (isAuthor || isClosed) {
spinner.setSelection(2, true)
spinner.isEnabled = false
}
}
override fun onSuccessfullySubmitted() {
hideProgress()
subimssionCallback?.onSuccessfullyReviewed()
dismiss()
}
override fun onErrorSubmitting() {
showErrorMessage(getString(R.string.network_error))
}
override fun showMessage(titleRes: Int, msgRes: Int) {
hideProgress()
super.showMessage(titleRes, msgRes)
}
override fun showMessage(titleRes: String, msgRes: String) {
hideProgress()
super.showMessage(titleRes, msgRes)
}
override fun showErrorMessage(msgRes: String) {
hideProgress()
super.showErrorMessage(msgRes)
}
override fun onSendActionClicked(text: String, bundle: Bundle?) {}
override fun onTagUser(username: String) {}
override fun onClearEditText() {
commentEditorFragment?.commentText?.setText("")
}
override fun getNamesToTag(): ArrayList<String>? {
return arrayListOf()
}
companion object {
fun startForResult(reviewChanges: ReviewRequestModel, repoId: String, owner: String, number: Long,
isAuthor: Boolean, isEnterprise: Boolean, isClosed: Boolean): ReviewChangesActivity {
val fragment = ReviewChangesActivity()
val bundle = Bundler.start()
.put(BundleConstant.EXTRA, reviewChanges)
.put(BundleConstant.EXTRA_TWO, repoId)
.put(BundleConstant.EXTRA_THREE, owner)
.put(BundleConstant.EXTRA_FOUR, isAuthor)
.put(BundleConstant.ID, number)
.put(BundleConstant.IS_ENTERPRISE, isEnterprise)
.put(BundleConstant.EXTRA_FIVE, isClosed)
.end()
fragment.arguments = bundle
return fragment
}
}
} | gpl-3.0 | 0685ed1791ea4dfb3b0c808b087c7210 | 37.556291 | 149 | 0.666209 | 5.022433 | false | false | false | false |
HughG/partial-order | partial-order-app/src/main/kotlin/org/tameter/partialorder/dag/Graph.kt | 1 | 6791 | package org.tameter.partialorder.dag
import org.tameter.kotlin.collections.MutableMapWithDefault
import org.tameter.kotlin.collections.MutableMultiSet
import org.tameter.kotlin.collections.mutableMultiSetOf
import org.tameter.kotlin.collections.withDefaultValue
import org.tameter.kotlin.delegates.setOnce
import org.tameter.partialorder.scoring.Scoring
import org.tameter.partialorder.util.cached
/**
* Copyright (c) 2016-2017 Hugh Greene ([email protected]).
*/
class Graph(override val id: String) : Scoring {
// --------------------------------------------------------------------------------
// <editor-fold desc="Properties">
private val _edges: MutableSet<Edge> = mutableSetOf()
val nodes: Collection<Node> get() = owner.nodes
val edges: Collection<Edge> get() = _edges
private val outgoing =
mutableMapOf<String, MutableSet<Edge>>().withDefaultValue({ mutableSetOf<Edge>() })
private val descendants =
mutableMapOf<String, MutableMultiSet<String>>().withDefaultValue({ mutableMultiSetOf<String>() })
private val ancestors =
mutableMapOf<String, MutableMultiSet<String>>().withDefaultValue({ mutableMultiSetOf<String>() })
val roots: Collection<Node>
get() {
// TODO 2016-04-03 HughG: Cache, or update it incrementally.
val result = mutableSetOf<Node>()
result.addAll(nodes)
edges.forEach { result.remove(it.to) }
// console.info("Roots are ${result.joinToString { it._id }}")
return result
}
// Map from a node to all the nodes which have a path to it.
private val cachedRanks = cached {
val ranks = mutableMapOf<Node, Int>()
for (it in nodes) {
ranks[it] = 0
}
console.log("Caching ranks for $id ...")
val edgesFromNode = edges.groupBy { it.from }
val nodesToProcess = mutableListOf<Node>().apply { addAll(roots) }
while (nodesToProcess.isNotEmpty()) {
val fromNode = nodesToProcess.removeAt(0)
edgesFromNode[fromNode]?.forEach { edge ->
val toNode = edge.to
ranks[toNode] = maxOf(ranks[toNode]!!, ranks[fromNode]!! + 1)
console.log("${ranks[toNode]} '${toNode.description}' <- '${fromNode.description}'")
nodesToProcess.add(toNode)
}
}
console.log("Caching ranks ... done")
ranks as Map<Node, Int>
}
val ranks by cachedRanks
val maxRank: Int?
get() {
return ranks.values.max()
}
// </editor-fold>
// --------------------------------------------------------------------------------
// <editor-fold desc="Scoring implementation">
override var owner: CompositeScoring by setOnce()
private set
override fun setOwner(owner: CompositeScoring) {
this.owner = owner
}
override fun nodeAdded(node: Node) {
cachedRanks.clear()
}
override fun score(node: Node): Int {
return ranks[node] ?: throw Exception("Cannot determine rank of node not in graph: ${node}")
}
// </editor-fold>
// --------------------------------------------------------------------------------
// <editor-fold desc="Methods">
// TODO 2016-04-02 HughG: When implementing removeNode, fail if there are connected edges.
fun addEdge(edge: Edge) {
if (edge.graphId != id) {
throw IllegalArgumentException("Graph mismatch adding $edge to $id")
}
val fromId = edge.fromId
val toId = edge.toId
if (hasPath(toId, fromId)) {
throw Exception("Cannot add edge because it would create a cycle: ${edge}")
}
if (!_edges.add(edge)) {
return
}
// Adding a new edge will change the set of which nodes are reachable from where.
outgoing[fromId].add(edge)
fun increment(relativeIds: MutableMultiSet<String>, relativeId: String, count: Int) {
relativeIds.add(relativeId, count)
}
adjustCountsForRelatives(toId, fromId, ancestors, ::increment)
adjustCountsForRelatives(fromId, toId, descendants, ::increment)
// TODO 2016-04-03 HughG: Instead of just deleting the cache, update it incrementally.
cachedRanks.clear()
owner.scoreChanged(id)
}
fun removeEdge(edge: Edge) {
if (edge.graphId != id) {
throw IllegalArgumentException("Graph mismatch removing $edge from $id")
}
if (!_edges.remove(edge)) {
return
}
val fromId = edge.fromId
val toId = edge.toId
// Removing an edge will change the set of which nodes are reachable from where.
outgoing[fromId].remove(edge)
fun decrement(relativeIds: MutableMultiSet<String>, relativeId: String, count: Int) {
relativeIds.remove(relativeId, count)
}
adjustCountsForRelatives(toId, fromId, ancestors, ::decrement)
adjustCountsForRelatives(fromId, toId, descendants, ::decrement)
// TODO 2016-04-03 HughG: Instead of just deleting the cache, update it incrementally.
cachedRanks.clear()
}
private fun adjustCountsForRelatives(
selfId: String,
otherId: String,
relatives: MutableMapWithDefault<String, MutableMultiSet<String>>,
adjust: (MutableMultiSet<String>, String, Int) -> Unit
) {
relatives[selfId].add(otherId)
val otherNodeRelativeIds = relatives[otherId]
for (otherNodeRelativeId in otherNodeRelativeIds) {
val existingPaths = otherNodeRelativeIds.count(otherNodeRelativeId)
adjust(otherNodeRelativeIds, otherNodeRelativeId, existingPaths)
}
}
fun hasPath(fromId: String, toId: String): Boolean =
(fromId == toId) || descendants[fromId].contains(toId)
fun hasPath(from: Node, to: Node): Boolean = hasPath(from._id, to._id)
// </editor-fold>
// --------------------------------------------------------------------------------
// <editor-fold desc="Edge extensions">
val Edge.from get() = nodeFromGraph("from", fromId)
val Edge.to get() = nodeFromGraph("to", toId)
private fun nodeFromGraph(nodeType: String, nodeId: String): Node {
return owner.findNodeById(nodeId) ?: throw Exception("No '${nodeType}' node ${nodeId}")
}
// </editor-fold>
// --------------------------------------------------------------------------------
// <editor-fold desc="Node extensions">
val Node.outgoing: Set<Edge> get() {
return [email protected][_id]
}
fun Node.hasEdgeTo(to: Node) = outgoing.any { it.to == to }
// </editor-fold>
} | mit | 78c7b1c0616d96a61d4f9d556dc1598b | 35.320856 | 109 | 0.587101 | 4.515293 | false | false | false | false |
mallowigi/a-file-icon-idea | common/src/main/java/com/mallowigi/icons/associations/Association.kt | 1 | 4060 | /*
* The MIT License (MIT)
*
* Copyright (c) 2015-2022 Elior "Mallowigi" Boukhobza
*
* 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.mallowigi.icons.associations
import com.intellij.serialization.PropertyMapping
import com.intellij.util.xmlb.annotations.Property
import com.mallowigi.models.FileInfo
import com.mallowigi.models.IconType
import com.thoughtworks.xstream.annotations.XStreamAsAttribute
import java.io.Serializable
/**
* Represents an Association
*
* @property enabled whether the association is used
* @property touched whether the association is touched by the user
* @property iconType the [IconType] of icon (file/folder/psi)
* @property name the name of the association
* @property icon the icon path
* @property priority association priority. Lowest priorities are used last.
* @property matcher How the association will be matched against (regex, type)
* @property isEmpty whether the association has empty fields
* @property iconColor the color of the icon
* @property folderIconColor the color of the folder icon
* @property folderColor the color of the folder
*/
abstract class Association @PropertyMapping() internal constructor() : Serializable, Comparable<Association> {
@field:Property
var enabled: Boolean = true
@field:Property
@XStreamAsAttribute
var touched: Boolean = false
@field:Property
@XStreamAsAttribute
var iconType: IconType = IconType.FILE
@field:Property
@XStreamAsAttribute
var name: String = ""
@field:Property
@XStreamAsAttribute
var icon: String = ""
@field:Property
@XStreamAsAttribute
var priority: Int = 100
@field:Property
@XStreamAsAttribute
var iconColor: String? = DEFAULT_COLOR
@field:Property
@XStreamAsAttribute
var folderColor: String? = DEFAULT_COLOR
@field:Property
@XStreamAsAttribute
var folderIconColor: String? = DEFAULT_COLOR
abstract var matcher: String
open val isEmpty: Boolean
get() = name.isEmpty() || icon.isEmpty()
/**
* Check whether the file matches the association
*
* @param file file information
* @return true if matches
*/
abstract fun matches(file: FileInfo): Boolean
/**
* Apply changes to the association
*
* @param other the other assoc to apply from
*/
open fun apply(other: Association) {
iconType = other.iconType
name = other.name
icon = other.icon
enabled = other.enabled
priority = other.priority
touched = other.touched
iconColor = other.iconColor
folderColor = other.folderColor
folderIconColor = other.folderIconColor
}
override fun toString(): String = "$name: $matcher ($priority)"
override fun compareTo(other: Association): Int = Comparator
.comparingInt(Association::priority)
.compare(this, other)
/** Check if matches icon name. */
fun matchesName(assocName: String): Boolean = name == assocName
companion object {
private const val serialVersionUID: Long = -1L
private const val DEFAULT_COLOR = "808080"
}
}
| mit | f1566d85c1df49b886682448ffee7238 | 30.968504 | 110 | 0.739163 | 4.408252 | false | false | false | false |
ReactiveCircus/FlowBinding | flowbinding-material/src/main/java/reactivecircus/flowbinding/material/TextInputLayoutIconClickedFlow.kt | 1 | 2674 | package reactivecircus.flowbinding.material
import android.view.View
import androidx.annotation.CheckResult
import com.google.android.material.textfield.TextInputLayout
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.channels.awaitClose
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.callbackFlow
import kotlinx.coroutines.flow.conflate
import reactivecircus.flowbinding.common.checkMainThread
/**
* Create a [Flow] of clicked events on the [TextInputLayout] instance's start icon.
*
* Note: Created flow keeps a strong reference to the [TextInputLayout] instance
* until the coroutine that launched the flow collector is cancelled.
*
* Example of usage:
*
* ```
* textInputLayout.startIconClicks()
* .onEach {
* // handle start icon clicked
* }
* .launchIn(uiScope)
* ```
*/
@CheckResult
@OptIn(ExperimentalCoroutinesApi::class)
public fun TextInputLayout.startIconClicks(): Flow<Unit> = callbackFlow {
checkMainThread()
val listener = View.OnClickListener {
trySend(Unit)
}
setStartIconOnClickListener(listener)
awaitClose { setStartIconOnClickListener(null) }
}.conflate()
/**
* Create a [Flow] of clicked events on the [TextInputLayout] instance's end icon.
*
* Note: Created flow keeps a strong reference to the [TextInputLayout] instance
* until the coroutine that launched the flow collector is cancelled.
*
* Example of usage:
*
* ```
* textInputLayout.endIconClicks()
* .onEach {
* // handle end icon clicked
* }
* .launchIn(uiScope)
* ```
*/
@CheckResult
@OptIn(ExperimentalCoroutinesApi::class)
public fun TextInputLayout.endIconClicks(): Flow<Unit> = callbackFlow {
checkMainThread()
val listener = View.OnClickListener {
trySend(Unit)
}
setEndIconOnClickListener(listener)
awaitClose { setEndIconOnClickListener(null) }
}.conflate()
/**
* Create a [Flow] of clicked events on the [TextInputLayout] instance's error icon.
*
* Note: Created flow keeps a strong reference to the [TextInputLayout] instance
* until the coroutine that launched the flow collector is cancelled.
*
* Example of usage:
*
* ```
* textInputLayout.errorIconClicks()
* .onEach {
* // handle error icon clicked
* }
* .launchIn(uiScope)
* ```
*/
@CheckResult
@OptIn(ExperimentalCoroutinesApi::class)
public fun TextInputLayout.errorIconClicks(): Flow<Unit> = callbackFlow {
checkMainThread()
val listener = View.OnClickListener {
trySend(Unit)
}
setErrorIconOnClickListener(listener)
awaitClose { setErrorIconOnClickListener(null) }
}.conflate()
| apache-2.0 | d9136c44d7b1ec76910147ae2d2c1f59 | 28.065217 | 84 | 0.722513 | 4.419835 | false | false | false | false |
robinverduijn/gradle | subprojects/kotlin-dsl/src/test/kotlin/org/gradle/kotlin/dsl/ProjectExtensionsTest.kt | 1 | 6177 | package org.gradle.kotlin.dsl
import com.nhaarman.mockito_kotlin.any
import com.nhaarman.mockito_kotlin.eq
import com.nhaarman.mockito_kotlin.doReturn
import com.nhaarman.mockito_kotlin.inOrder
import com.nhaarman.mockito_kotlin.mock
import com.nhaarman.mockito_kotlin.whenever
import org.gradle.api.Action
import org.gradle.api.NamedDomainObjectContainer
import org.gradle.api.NamedDomainObjectFactory
import org.gradle.api.Project
import org.gradle.api.UnknownDomainObjectException
import org.gradle.api.plugins.Convention
import org.gradle.api.plugins.JavaPluginConvention
import org.gradle.api.reflect.TypeOf
import org.junit.Assert.fail
import org.junit.Test
class ProjectExtensionsTest {
@Test
fun `can get generic project extension by type`() {
val project = mock<Project>()
val convention = mock<Convention>()
val extension = mock<NamedDomainObjectContainer<List<String>>>()
val extensionType = typeOf<NamedDomainObjectContainer<List<String>>>()
whenever(project.convention)
.thenReturn(convention)
whenever(convention.findByType(eq(extensionType)))
.thenReturn(extension)
project.the<NamedDomainObjectContainer<List<String>>>()
inOrder(convention) {
verify(convention).findByType(eq(extensionType))
verifyNoMoreInteractions()
}
}
@Test
fun `can configure generic project extension by type`() {
val project = mock<Project>()
val convention = mock<Convention>()
val extension = mock<NamedDomainObjectContainer<List<String>>>()
val extensionType = typeOf<NamedDomainObjectContainer<List<String>>>()
whenever(project.convention)
.thenReturn(convention)
whenever(convention.findByType(eq(extensionType)))
.thenReturn(extension)
project.configure<NamedDomainObjectContainer<List<String>>> {}
inOrder(convention) {
verify(convention).findByType(eq(extensionType))
verifyNoMoreInteractions()
}
}
@Test
fun `can get convention by type`() {
val project = mock<Project>()
val convention = mock<Convention>()
val javaConvention = mock<JavaPluginConvention>()
whenever(project.convention)
.thenReturn(convention)
whenever(convention.findPlugin(eq(JavaPluginConvention::class.java)))
.thenReturn(javaConvention)
project.the<JavaPluginConvention>()
inOrder(convention) {
verify(convention).findByType(any<TypeOf<JavaPluginConvention>>())
verify(convention).findPlugin(eq(JavaPluginConvention::class.java))
verifyNoMoreInteractions()
}
}
@Test
fun `can configure convention by type`() {
val project = mock<Project>()
val convention = mock<Convention>()
val javaConvention = mock<JavaPluginConvention>()
whenever(project.convention)
.thenReturn(convention)
whenever(convention.findByType(any<TypeOf<*>>()))
.thenReturn(null)
whenever(convention.findPlugin(eq(JavaPluginConvention::class.java)))
.thenReturn(javaConvention)
project.configure<JavaPluginConvention> {}
inOrder(convention) {
verify(convention).findByType(any<TypeOf<JavaPluginConvention>>())
verify(convention).findPlugin(eq(JavaPluginConvention::class.java))
verifyNoMoreInteractions()
}
}
@Test
fun `the() falls back to throwing getByType when not found`() {
val project = mock<Project>()
val convention = mock<Convention>()
val conventionType = typeOf<JavaPluginConvention>()
whenever(project.convention)
.thenReturn(convention)
whenever(convention.getByType(eq(conventionType)))
.thenThrow(UnknownDomainObjectException::class.java)
try {
project.the<JavaPluginConvention>()
fail("UnknownDomainObjectException not thrown")
} catch (ex: UnknownDomainObjectException) {
// expected
}
inOrder(convention) {
verify(convention).findByType(eq(conventionType))
verify(convention).findPlugin(eq(JavaPluginConvention::class.java))
verify(convention).getByType(eq(conventionType))
verifyNoMoreInteractions()
}
}
@Test
fun `configure() falls back to throwing configure when not found`() {
val project = mock<Project>()
val convention = mock<Convention>()
val conventionType = typeOf<JavaPluginConvention>()
whenever(project.convention)
.thenReturn(convention)
whenever(convention.configure(eq(conventionType), any<Action<JavaPluginConvention>>()))
.thenThrow(UnknownDomainObjectException::class.java)
try {
project.configure<JavaPluginConvention> {}
fail("UnknownDomainObjectException not thrown")
} catch (ex: UnknownDomainObjectException) {
// expected
}
inOrder(convention) {
verify(convention).findByType(eq(conventionType))
verify(convention).findPlugin(eq(JavaPluginConvention::class.java))
verify(convention).configure(eq(conventionType), any<Action<JavaPluginConvention>>())
verifyNoMoreInteractions()
}
}
@Test
fun container() {
val project = mock<Project> {
on { container(any<Class<String>>()) } doReturn mock<NamedDomainObjectContainer<String>>()
on { container(any<Class<String>>(), any<NamedDomainObjectFactory<String>>()) } doReturn mock<NamedDomainObjectContainer<String>>()
}
project.container<String>()
inOrder(project) {
verify(project).container(String::class.java)
verifyNoMoreInteractions()
}
project.container { "some" }
inOrder(project) {
verify(project).container(any<Class<String>>(), any<NamedDomainObjectFactory<String>>())
verifyNoMoreInteractions()
}
}
}
| apache-2.0 | c100b9926b0a30ee4db452338816a894 | 32.032086 | 143 | 0.655334 | 5.380662 | false | false | false | false |
square/leakcanary | shark/src/main/java/shark/HeapAnalyzer.kt | 2 | 27133 | /*
* Copyright (C) 2015 Square, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package shark
import shark.HeapAnalyzer.TrieNode.LeafNode
import shark.HeapAnalyzer.TrieNode.ParentNode
import shark.HeapObject.HeapClass
import shark.HeapObject.HeapInstance
import shark.HeapObject.HeapObjectArray
import shark.HeapObject.HeapPrimitiveArray
import shark.HprofHeapGraph.Companion.openHeapGraph
import shark.LeakTrace.GcRootType
import shark.LeakTraceObject.LeakingStatus
import shark.LeakTraceObject.LeakingStatus.LEAKING
import shark.LeakTraceObject.LeakingStatus.NOT_LEAKING
import shark.LeakTraceObject.LeakingStatus.UNKNOWN
import shark.LeakTraceObject.ObjectType.ARRAY
import shark.LeakTraceObject.ObjectType.CLASS
import shark.LeakTraceObject.ObjectType.INSTANCE
import shark.OnAnalysisProgressListener.Step.BUILDING_LEAK_TRACES
import shark.OnAnalysisProgressListener.Step.COMPUTING_NATIVE_RETAINED_SIZE
import shark.OnAnalysisProgressListener.Step.COMPUTING_RETAINED_SIZE
import shark.OnAnalysisProgressListener.Step.EXTRACTING_METADATA
import shark.OnAnalysisProgressListener.Step.FINDING_RETAINED_OBJECTS
import shark.OnAnalysisProgressListener.Step.INSPECTING_OBJECTS
import shark.OnAnalysisProgressListener.Step.PARSING_HEAP_DUMP
import shark.internal.AndroidNativeSizeMapper
import shark.internal.DominatorTree
import shark.internal.PathFinder
import shark.internal.PathFinder.PathFindingResults
import shark.internal.ReferencePathNode
import shark.internal.ReferencePathNode.ChildNode
import shark.internal.ReferencePathNode.RootNode
import shark.internal.ShallowSizeCalculator
import shark.internal.createSHA1Hash
import shark.internal.lastSegment
import java.io.File
import java.util.ArrayList
import java.util.concurrent.TimeUnit.NANOSECONDS
import shark.internal.AndroidReferenceReaders
import shark.internal.ApacheHarmonyInstanceRefReaders
import shark.internal.ChainingInstanceReferenceReader
import shark.internal.ClassReferenceReader
import shark.internal.DelegatingObjectReferenceReader
import shark.internal.FieldInstanceReferenceReader
import shark.internal.JavaLocalReferenceReader
import shark.internal.ObjectArrayReferenceReader
import shark.internal.OpenJdkInstanceRefReaders
import shark.internal.ReferenceLocationType
import shark.internal.ReferencePathNode.RootNode.LibraryLeakRootNode
import shark.internal.ReferenceReader
/**
* Analyzes heap dumps to look for leaks.
*/
class HeapAnalyzer constructor(
private val listener: OnAnalysisProgressListener
) {
private class FindLeakInput(
val graph: HeapGraph,
val referenceMatchers: List<ReferenceMatcher>,
val computeRetainedHeapSize: Boolean,
val objectInspectors: List<ObjectInspector>,
val referenceReader: ReferenceReader<HeapObject>
)
@Deprecated("Use the non deprecated analyze method instead")
fun analyze(
heapDumpFile: File,
leakingObjectFinder: LeakingObjectFinder,
referenceMatchers: List<ReferenceMatcher> = emptyList(),
computeRetainedHeapSize: Boolean = false,
objectInspectors: List<ObjectInspector> = emptyList(),
metadataExtractor: MetadataExtractor = MetadataExtractor.NO_OP,
proguardMapping: ProguardMapping? = null
): HeapAnalysis {
if (!heapDumpFile.exists()) {
val exception = IllegalArgumentException("File does not exist: $heapDumpFile")
return HeapAnalysisFailure(
heapDumpFile = heapDumpFile,
createdAtTimeMillis = System.currentTimeMillis(),
analysisDurationMillis = 0,
exception = HeapAnalysisException(exception)
)
}
listener.onAnalysisProgress(PARSING_HEAP_DUMP)
val sourceProvider = ConstantMemoryMetricsDualSourceProvider(FileSourceProvider(heapDumpFile))
return try {
sourceProvider.openHeapGraph(proguardMapping).use { graph ->
analyze(
heapDumpFile,
graph,
leakingObjectFinder,
referenceMatchers,
computeRetainedHeapSize,
objectInspectors,
metadataExtractor
).let { result ->
if (result is HeapAnalysisSuccess) {
val lruCacheStats = (graph as HprofHeapGraph).lruCacheStats()
val randomAccessStats =
"RandomAccess[" +
"bytes=${sourceProvider.randomAccessByteReads}," +
"reads=${sourceProvider.randomAccessReadCount}," +
"travel=${sourceProvider.randomAccessByteTravel}," +
"range=${sourceProvider.byteTravelRange}," +
"size=${heapDumpFile.length()}" +
"]"
val stats = "$lruCacheStats $randomAccessStats"
result.copy(metadata = result.metadata + ("Stats" to stats))
} else result
}
}
} catch (throwable: Throwable) {
HeapAnalysisFailure(
heapDumpFile = heapDumpFile,
createdAtTimeMillis = System.currentTimeMillis(),
analysisDurationMillis = 0,
exception = HeapAnalysisException(throwable)
)
}
}
/**
* Searches the heap dump for leaking instances and then computes the shortest strong reference
* path from those instances to the GC roots.
*/
fun analyze(
heapDumpFile: File,
graph: HeapGraph,
leakingObjectFinder: LeakingObjectFinder,
referenceMatchers: List<ReferenceMatcher> = emptyList(),
computeRetainedHeapSize: Boolean = false,
objectInspectors: List<ObjectInspector> = emptyList(),
metadataExtractor: MetadataExtractor = MetadataExtractor.NO_OP,
): HeapAnalysis {
val analysisStartNanoTime = System.nanoTime()
val referenceReader = DelegatingObjectReferenceReader(
classReferenceReader = ClassReferenceReader(graph, referenceMatchers),
instanceReferenceReader = ChainingInstanceReferenceReader(
listOf(
JavaLocalReferenceReader(graph, referenceMatchers),
)
+ OpenJdkInstanceRefReaders.values().mapNotNull { it.create(graph) }
+ ApacheHarmonyInstanceRefReaders.values().mapNotNull { it.create(graph) }
+ AndroidReferenceReaders.values().mapNotNull { it.create(graph) },
FieldInstanceReferenceReader(graph, referenceMatchers)
),
objectArrayReferenceReader = ObjectArrayReferenceReader()
)
return analyze(
heapDumpFile,
graph,
leakingObjectFinder,
referenceMatchers,
computeRetainedHeapSize,
objectInspectors,
metadataExtractor,
referenceReader
).run {
val updatedDurationMillis = since(analysisStartNanoTime)
when (this) {
is HeapAnalysisSuccess -> copy(analysisDurationMillis = updatedDurationMillis)
is HeapAnalysisFailure -> copy(analysisDurationMillis = updatedDurationMillis)
}
}
}
// TODO Callers should add to analysisStartNanoTime
// Input should be a builder or part of the object state probs?
// Maybe there's some sort of helper for setting up the right analysis?
// There's a part focused on finding leaks, and then we add to that.
// Maybe the result isn't even a leaktrace yet, but something with live object ids?
// Ideally the result contains only what this can return. No file, etc.
// File: used to create the graph + in result
// leakingObjectFinder: Helper object, shared
// computeRetainedHeapSize: boolean param for single analysis
// referenceMatchers: param?. though honestly not great.
// objectInspectors: Helper object.
// metadataExtractor: helper object, not needed for leak finding
// referenceReader: can't be helper object, needs graph => param something that can produce it from
// graph (and in the impl we give that thing the referenceMatchers)
@Suppress("LongParameterList")
internal fun analyze(
// TODO Kill this file
heapDumpFile: File,
graph: HeapGraph,
leakingObjectFinder: LeakingObjectFinder,
referenceMatchers: List<ReferenceMatcher>,
computeRetainedHeapSize: Boolean,
objectInspectors: List<ObjectInspector>,
metadataExtractor: MetadataExtractor,
referenceReader: ReferenceReader<HeapObject>
): HeapAnalysis {
val analysisStartNanoTime = System.nanoTime()
return try {
val helpers =
FindLeakInput(
graph, referenceMatchers, computeRetainedHeapSize, objectInspectors,
referenceReader
)
helpers.analyzeGraph(
metadataExtractor, leakingObjectFinder, heapDumpFile, analysisStartNanoTime
)
} catch (exception: Throwable) {
HeapAnalysisFailure(
heapDumpFile = heapDumpFile,
createdAtTimeMillis = System.currentTimeMillis(),
analysisDurationMillis = since(analysisStartNanoTime),
exception = HeapAnalysisException(exception)
)
}
}
private fun FindLeakInput.analyzeGraph(
metadataExtractor: MetadataExtractor,
leakingObjectFinder: LeakingObjectFinder,
heapDumpFile: File,
analysisStartNanoTime: Long
): HeapAnalysisSuccess {
listener.onAnalysisProgress(EXTRACTING_METADATA)
val metadata = metadataExtractor.extractMetadata(graph)
val retainedClearedWeakRefCount = KeyedWeakReferenceFinder.findKeyedWeakReferences(graph)
.count { it.isRetained && !it.hasReferent }
// This should rarely happens, as we generally remove all cleared weak refs right before a heap
// dump.
val metadataWithCount = if (retainedClearedWeakRefCount > 0) {
metadata + ("Count of retained yet cleared" to "$retainedClearedWeakRefCount KeyedWeakReference instances")
} else {
metadata
}
listener.onAnalysisProgress(FINDING_RETAINED_OBJECTS)
val leakingObjectIds = leakingObjectFinder.findLeakingObjectIds(graph)
val (applicationLeaks, libraryLeaks, unreachableObjects) = findLeaks(leakingObjectIds)
return HeapAnalysisSuccess(
heapDumpFile = heapDumpFile,
createdAtTimeMillis = System.currentTimeMillis(),
analysisDurationMillis = since(analysisStartNanoTime),
metadata = metadataWithCount,
applicationLeaks = applicationLeaks,
libraryLeaks = libraryLeaks,
unreachableObjects = unreachableObjects
)
}
private data class LeaksAndUnreachableObjects(
val applicationLeaks: List<ApplicationLeak>,
val libraryLeaks: List<LibraryLeak>,
val unreachableObjects: List<LeakTraceObject>
)
private fun FindLeakInput.findLeaks(leakingObjectIds: Set<Long>): LeaksAndUnreachableObjects {
val pathFinder = PathFinder(graph, listener, referenceReader, referenceMatchers)
val pathFindingResults =
pathFinder.findPathsFromGcRoots(leakingObjectIds, computeRetainedHeapSize)
val unreachableObjects = findUnreachableObjects(pathFindingResults, leakingObjectIds)
val shortestPaths =
deduplicateShortestPaths(pathFindingResults.pathsToLeakingObjects)
val inspectedObjectsByPath = inspectObjects(shortestPaths)
val retainedSizes =
if (pathFindingResults.dominatorTree != null) {
computeRetainedSizes(inspectedObjectsByPath, pathFindingResults.dominatorTree)
} else {
null
}
val (applicationLeaks, libraryLeaks) = buildLeakTraces(
shortestPaths, inspectedObjectsByPath, retainedSizes
)
return LeaksAndUnreachableObjects(applicationLeaks, libraryLeaks, unreachableObjects)
}
private fun FindLeakInput.findUnreachableObjects(
pathFindingResults: PathFindingResults,
leakingObjectIds: Set<Long>
): List<LeakTraceObject> {
val reachableLeakingObjectIds =
pathFindingResults.pathsToLeakingObjects.map { it.objectId }.toSet()
val unreachableLeakingObjectIds = leakingObjectIds - reachableLeakingObjectIds
val unreachableObjectReporters = unreachableLeakingObjectIds.map { objectId ->
ObjectReporter(heapObject = graph.findObjectById(objectId))
}
objectInspectors.forEach { inspector ->
unreachableObjectReporters.forEach { reporter ->
inspector.inspect(reporter)
}
}
val unreachableInspectedObjects = unreachableObjectReporters.map { reporter ->
val reason = resolveStatus(reporter, leakingWins = true).let { (status, reason) ->
when (status) {
LEAKING -> reason
UNKNOWN -> "This is a leaking object"
NOT_LEAKING -> "This is a leaking object. Conflicts with $reason"
}
}
InspectedObject(
reporter.heapObject, LEAKING, reason, reporter.labels
)
}
return buildLeakTraceObjects(unreachableInspectedObjects, null)
}
internal sealed class TrieNode {
abstract val objectId: Long
class ParentNode(override val objectId: Long) : TrieNode() {
val children = mutableMapOf<Long, TrieNode>()
override fun toString(): String {
return "ParentNode(objectId=$objectId, children=$children)"
}
}
class LeafNode(
override val objectId: Long,
val pathNode: ReferencePathNode
) : TrieNode()
}
private fun deduplicateShortestPaths(
inputPathResults: List<ReferencePathNode>
): List<ShortestPath> {
val rootTrieNode = ParentNode(0)
inputPathResults.forEach { pathNode ->
// Go through the linked list of nodes and build the reverse list of instances from
// root to leaking.
val path = mutableListOf<Long>()
var leakNode: ReferencePathNode = pathNode
while (leakNode is ChildNode) {
path.add(0, leakNode.objectId)
leakNode = leakNode.parent
}
path.add(0, leakNode.objectId)
updateTrie(pathNode, path, 0, rootTrieNode)
}
val outputPathResults = mutableListOf<ReferencePathNode>()
findResultsInTrie(rootTrieNode, outputPathResults)
if (outputPathResults.size != inputPathResults.size) {
SharkLog.d {
"Found ${inputPathResults.size} paths to retained objects," +
" down to ${outputPathResults.size} after removing duplicated paths"
}
} else {
SharkLog.d { "Found ${outputPathResults.size} paths to retained objects" }
}
return outputPathResults.map { retainedObjectNode ->
val shortestChildPath = mutableListOf<ChildNode>()
var node = retainedObjectNode
while (node is ChildNode) {
shortestChildPath.add(0, node)
node = node.parent
}
val rootNode = node as RootNode
ShortestPath(rootNode, shortestChildPath)
}
}
private fun updateTrie(
pathNode: ReferencePathNode,
path: List<Long>,
pathIndex: Int,
parentNode: ParentNode
) {
val objectId = path[pathIndex]
if (pathIndex == path.lastIndex) {
parentNode.children[objectId] = LeafNode(objectId, pathNode)
} else {
val childNode = parentNode.children[objectId] ?: run {
val newChildNode = ParentNode(objectId)
parentNode.children[objectId] = newChildNode
newChildNode
}
if (childNode is ParentNode) {
updateTrie(pathNode, path, pathIndex + 1, childNode)
}
}
}
private fun findResultsInTrie(
parentNode: ParentNode,
outputPathResults: MutableList<ReferencePathNode>
) {
parentNode.children.values.forEach { childNode ->
when (childNode) {
is ParentNode -> {
findResultsInTrie(childNode, outputPathResults)
}
is LeafNode -> {
outputPathResults += childNode.pathNode
}
}
}
}
internal class ShortestPath(
val root: RootNode,
val childPath: List<ChildNode>
) {
val childPathWithDetails = childPath.map { it to it.lazyDetailsResolver.resolve() }
fun asList() = listOf(root) + childPath
fun firstLibraryLeakMatcher(): LibraryLeakReferenceMatcher? {
if (root is LibraryLeakRootNode) {
return root.matcher
}
return childPathWithDetails.map { it.second.matchedLibraryLeak }.firstOrNull { it != null }
}
fun asNodesWithMatchers(): List<Pair<ReferencePathNode, LibraryLeakReferenceMatcher?>> {
val rootMatcher = if (root is LibraryLeakRootNode) {
root.matcher
} else null
val childPathWithMatchers =
childPathWithDetails.map { it.first to it.second.matchedLibraryLeak }
return listOf(root to rootMatcher) + childPathWithMatchers
}
}
private fun FindLeakInput.buildLeakTraces(
shortestPaths: List<ShortestPath>,
inspectedObjectsByPath: List<List<InspectedObject>>,
retainedSizes: Map<Long, Pair<Int, Int>>?
): Pair<List<ApplicationLeak>, List<LibraryLeak>> {
listener.onAnalysisProgress(BUILDING_LEAK_TRACES)
val applicationLeaksMap = mutableMapOf<String, MutableList<LeakTrace>>()
val libraryLeaksMap =
mutableMapOf<String, Pair<LibraryLeakReferenceMatcher, MutableList<LeakTrace>>>()
shortestPaths.forEachIndexed { pathIndex, shortestPath ->
val inspectedObjects = inspectedObjectsByPath[pathIndex]
val leakTraceObjects = buildLeakTraceObjects(inspectedObjects, retainedSizes)
val referencePath = buildReferencePath(shortestPath, leakTraceObjects)
val leakTrace = LeakTrace(
gcRootType = GcRootType.fromGcRoot(shortestPath.root.gcRoot),
referencePath = referencePath,
leakingObject = leakTraceObjects.last()
)
val firstLibraryLeakMatcher = shortestPath.firstLibraryLeakMatcher()
if (firstLibraryLeakMatcher != null) {
val signature: String = firstLibraryLeakMatcher.pattern.toString()
.createSHA1Hash()
libraryLeaksMap.getOrPut(signature) { firstLibraryLeakMatcher to mutableListOf() }
.second += leakTrace
} else {
applicationLeaksMap.getOrPut(leakTrace.signature) { mutableListOf() } += leakTrace
}
}
val applicationLeaks = applicationLeaksMap.map { (_, leakTraces) ->
ApplicationLeak(leakTraces)
}
val libraryLeaks = libraryLeaksMap.map { (_, pair) ->
val (matcher, leakTraces) = pair
LibraryLeak(leakTraces, matcher.pattern, matcher.description)
}
return applicationLeaks to libraryLeaks
}
private fun FindLeakInput.inspectObjects(shortestPaths: List<ShortestPath>): List<List<InspectedObject>> {
listener.onAnalysisProgress(INSPECTING_OBJECTS)
val leakReportersByPath = shortestPaths.map { path ->
val pathList = path.asNodesWithMatchers()
pathList
.mapIndexed { index, (node, _) ->
val reporter = ObjectReporter(heapObject = graph.findObjectById(node.objectId))
if (index + 1 < pathList.size) {
val (_, nextMatcher) = pathList[index + 1]
if (nextMatcher != null) {
reporter.labels += "Library leak match: ${nextMatcher.pattern}"
}
}
reporter
}
}
objectInspectors.forEach { inspector ->
leakReportersByPath.forEach { leakReporters ->
leakReporters.forEach { reporter ->
inspector.inspect(reporter)
}
}
}
return leakReportersByPath.map { leakReporters ->
computeLeakStatuses(leakReporters)
}
}
private fun FindLeakInput.computeRetainedSizes(
inspectedObjectsByPath: List<List<InspectedObject>>,
dominatorTree: DominatorTree
): Map<Long, Pair<Int, Int>> {
val nodeObjectIds = inspectedObjectsByPath.flatMap { inspectedObjects ->
inspectedObjects.filter { it.leakingStatus == UNKNOWN || it.leakingStatus == LEAKING }
.map { it.heapObject.objectId }
}.toSet()
listener.onAnalysisProgress(COMPUTING_NATIVE_RETAINED_SIZE)
val nativeSizeMapper = AndroidNativeSizeMapper(graph)
val nativeSizes = nativeSizeMapper.mapNativeSizes()
listener.onAnalysisProgress(COMPUTING_RETAINED_SIZE)
val shallowSizeCalculator = ShallowSizeCalculator(graph)
return dominatorTree.computeRetainedSizes(nodeObjectIds) { objectId ->
val nativeSize = nativeSizes[objectId] ?: 0
val shallowSize = shallowSizeCalculator.computeShallowSize(objectId)
nativeSize + shallowSize
}
}
private fun buildLeakTraceObjects(
inspectedObjects: List<InspectedObject>,
retainedSizes: Map<Long, Pair<Int, Int>>?
): List<LeakTraceObject> {
return inspectedObjects.map { inspectedObject ->
val heapObject = inspectedObject.heapObject
val className = recordClassName(heapObject)
val objectType = when (heapObject) {
is HeapClass -> CLASS
is HeapObjectArray, is HeapPrimitiveArray -> ARRAY
else -> INSTANCE
}
val retainedSizeAndObjectCount = retainedSizes?.get(inspectedObject.heapObject.objectId)
LeakTraceObject(
type = objectType,
className = className,
labels = inspectedObject.labels,
leakingStatus = inspectedObject.leakingStatus,
leakingStatusReason = inspectedObject.leakingStatusReason,
retainedHeapByteSize = retainedSizeAndObjectCount?.first,
retainedObjectCount = retainedSizeAndObjectCount?.second
)
}
}
private fun FindLeakInput.buildReferencePath(
shortestPath: ShortestPath,
leakTraceObjects: List<LeakTraceObject>
): List<LeakTraceReference> {
return shortestPath.childPathWithDetails.mapIndexed { index, (childNode, details) ->
LeakTraceReference(
originObject = leakTraceObjects[index],
referenceType = when (details.locationType) {
ReferenceLocationType.INSTANCE_FIELD -> LeakTraceReference.ReferenceType.INSTANCE_FIELD
ReferenceLocationType.STATIC_FIELD -> LeakTraceReference.ReferenceType.STATIC_FIELD
ReferenceLocationType.LOCAL -> LeakTraceReference.ReferenceType.LOCAL
ReferenceLocationType.ARRAY_ENTRY -> LeakTraceReference.ReferenceType.ARRAY_ENTRY
},
owningClassName = graph.findObjectById(details.locationClassObjectId).asClass!!.name,
referenceName = details.name
)
}
}
internal class InspectedObject(
val heapObject: HeapObject,
val leakingStatus: LeakingStatus,
val leakingStatusReason: String,
val labels: MutableSet<String>
)
private fun computeLeakStatuses(leakReporters: List<ObjectReporter>): List<InspectedObject> {
val lastElementIndex = leakReporters.size - 1
var lastNotLeakingElementIndex = -1
var firstLeakingElementIndex = lastElementIndex
val leakStatuses = ArrayList<Pair<LeakingStatus, String>>()
for ((index, reporter) in leakReporters.withIndex()) {
val resolvedStatusPair =
resolveStatus(reporter, leakingWins = index == lastElementIndex).let { statusPair ->
if (index == lastElementIndex) {
// The last element should always be leaking.
when (statusPair.first) {
LEAKING -> statusPair
UNKNOWN -> LEAKING to "This is the leaking object"
NOT_LEAKING -> LEAKING to "This is the leaking object. Conflicts with ${statusPair.second}"
}
} else statusPair
}
leakStatuses.add(resolvedStatusPair)
val (leakStatus, _) = resolvedStatusPair
if (leakStatus == NOT_LEAKING) {
lastNotLeakingElementIndex = index
// Reset firstLeakingElementIndex so that we never have
// firstLeakingElementIndex < lastNotLeakingElementIndex
firstLeakingElementIndex = lastElementIndex
} else if (leakStatus == LEAKING && firstLeakingElementIndex == lastElementIndex) {
firstLeakingElementIndex = index
}
}
val simpleClassNames = leakReporters.map { reporter ->
recordClassName(reporter.heapObject).lastSegment('.')
}
for (i in 0 until lastNotLeakingElementIndex) {
val (leakStatus, leakStatusReason) = leakStatuses[i]
val nextNotLeakingIndex = generateSequence(i + 1) { index ->
if (index < lastNotLeakingElementIndex) index + 1 else null
}.first { index ->
leakStatuses[index].first == NOT_LEAKING
}
// Element is forced to NOT_LEAKING
val nextNotLeakingName = simpleClassNames[nextNotLeakingIndex]
leakStatuses[i] = when (leakStatus) {
UNKNOWN -> NOT_LEAKING to "$nextNotLeakingName↓ is not leaking"
NOT_LEAKING -> NOT_LEAKING to "$nextNotLeakingName↓ is not leaking and $leakStatusReason"
LEAKING -> NOT_LEAKING to "$nextNotLeakingName↓ is not leaking. Conflicts with $leakStatusReason"
}
}
if (firstLeakingElementIndex < lastElementIndex - 1) {
// We already know the status of firstLeakingElementIndex and lastElementIndex
for (i in lastElementIndex - 1 downTo firstLeakingElementIndex + 1) {
val (leakStatus, leakStatusReason) = leakStatuses[i]
val previousLeakingIndex = generateSequence(i - 1) { index ->
if (index > firstLeakingElementIndex) index - 1 else null
}.first { index ->
leakStatuses[index].first == LEAKING
}
// Element is forced to LEAKING
val previousLeakingName = simpleClassNames[previousLeakingIndex]
leakStatuses[i] = when (leakStatus) {
UNKNOWN -> LEAKING to "$previousLeakingName↑ is leaking"
LEAKING -> LEAKING to "$previousLeakingName↑ is leaking and $leakStatusReason"
NOT_LEAKING -> throw IllegalStateException("Should never happen")
}
}
}
return leakReporters.mapIndexed { index, objectReporter ->
val (leakingStatus, leakingStatusReason) = leakStatuses[index]
InspectedObject(
objectReporter.heapObject, leakingStatus, leakingStatusReason, objectReporter.labels
)
}
}
private fun resolveStatus(
reporter: ObjectReporter,
leakingWins: Boolean
): Pair<LeakingStatus, String> {
var status = UNKNOWN
var reason = ""
if (reporter.notLeakingReasons.isNotEmpty()) {
status = NOT_LEAKING
reason = reporter.notLeakingReasons.joinToString(" and ")
}
val leakingReasons = reporter.leakingReasons
if (leakingReasons.isNotEmpty()) {
val winReasons = leakingReasons.joinToString(" and ")
// Conflict
if (status == NOT_LEAKING) {
if (leakingWins) {
status = LEAKING
reason = "$winReasons. Conflicts with $reason"
} else {
reason += ". Conflicts with $winReasons"
}
} else {
status = LEAKING
reason = winReasons
}
}
return status to reason
}
private fun recordClassName(
heap: HeapObject
): String {
return when (heap) {
is HeapClass -> heap.name
is HeapInstance -> heap.instanceClassName
is HeapObjectArray -> heap.arrayClassName
is HeapPrimitiveArray -> heap.arrayClassName
}
}
private fun since(analysisStartNanoTime: Long): Long {
return NANOSECONDS.toMillis(System.nanoTime() - analysisStartNanoTime)
}
}
| apache-2.0 | 45563380e4b81a26b0b4cd420de43ce0 | 36.359504 | 113 | 0.711499 | 4.798832 | false | false | false | false |
android/camera-samples | CameraXExtensions/app/src/main/java/com/example/android/cameraxextensions/adapter/CameraExtensionsSelectorAdapter.kt | 1 | 2927 | /*
* 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.example.android.cameraxextensions.adapter
import android.graphics.Color
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.ListAdapter
import androidx.recyclerview.widget.RecyclerView
import com.example.android.cameraxextensions.R
/**
* Adapter used to display CameraExtensionItems in a RecyclerView.
*/
class CameraExtensionsSelectorAdapter(private val onItemClick: (view: View) -> Unit) :
ListAdapter<CameraExtensionItem, CameraExtensionItemViewHolder>(ItemCallback()) {
override fun onCreateViewHolder(
parent: ViewGroup,
viewType: Int
): CameraExtensionItemViewHolder =
CameraExtensionItemViewHolder(
LayoutInflater.from(parent.context)
.inflate(R.layout.view_extension_type, parent, false) as TextView,
onItemClick
)
override fun onBindViewHolder(holder: CameraExtensionItemViewHolder, position: Int) {
holder.bind(getItem(position))
}
internal class ItemCallback : DiffUtil.ItemCallback<CameraExtensionItem>() {
override fun areItemsTheSame(
oldItem: CameraExtensionItem,
newItem: CameraExtensionItem
): Boolean = oldItem.extensionMode == newItem.extensionMode
override fun areContentsTheSame(
oldItem: CameraExtensionItem,
newItem: CameraExtensionItem
): Boolean = oldItem.selected == newItem.selected
}
}
class CameraExtensionItemViewHolder internal constructor(
private val extensionView: TextView,
private val onItemClick: (view: View) -> Unit
) :
RecyclerView.ViewHolder(extensionView) {
init {
extensionView.setOnClickListener { onItemClick(it) }
}
internal fun bind(extensionModel: CameraExtensionItem) {
extensionView.text = extensionModel.name
if (extensionModel.selected) {
extensionView.setBackgroundResource(R.drawable.pill_selected_background)
extensionView.setTextColor(Color.BLACK)
} else {
extensionView.setBackgroundResource(R.drawable.pill_unselected_background)
extensionView.setTextColor(Color.WHITE)
}
}
} | apache-2.0 | f5fc086e98816c7305c93764ca095ac2 | 34.707317 | 89 | 0.725658 | 4.886477 | false | false | false | false |
diyaakanakry/Diyaa | LogicCondition.kt | 1 | 179 |
fun main(args:Array<String>){
var n:Int= 9
println(n>=0 && n<10)
var n2:Int=55
println(n2==10 || n>100)
var IsMerried:Boolean=false
print(!IsMerried)
} | unlicense | 4055bf04fb51f324aad57d30c7d458e5 | 14 | 31 | 0.586592 | 2.671642 | false | false | false | false |
corenting/EDCompanion | app/src/main/java/fr/corenting/edcompanion/utils/CommanderUtils.kt | 1 | 2537 | package fr.corenting.edcompanion.utils
import android.content.Context
import fr.corenting.edcompanion.R
import fr.corenting.edcompanion.network.player.EDSMPlayer
import fr.corenting.edcompanion.network.player.FrontierPlayer
import fr.corenting.edcompanion.network.player.InaraPlayer
object CommanderUtils {
fun getCommanderName(context: Context): String {
val edsmPlayer = EDSMPlayer(context)
if (edsmPlayer.isUsable()) {
return SettingsUtils.getString(
context,
context.getString(R.string.settings_cmdr_edsm_username)
)
}
val inaraPlayer = InaraPlayer(context)
if (inaraPlayer.isUsable()) {
return inaraPlayer.getCommanderName()
}
return context.getString(R.string.commander)
}
fun hasFleetData(context: Context): Boolean {
val frontierPlayer = FrontierPlayer(context)
if (frontierPlayer.isUsable()) {
return true
}
return false
}
fun hasCreditsData(context: Context): Boolean {
val edsmPlayer = EDSMPlayer(context)
if (edsmPlayer.isUsable()) {
return true
}
val frontierPlayer = FrontierPlayer(context)
if (frontierPlayer.isUsable()) {
return true
}
return false
}
fun hasPositionData(context: Context): Boolean {
val edsmPlayer = EDSMPlayer(context)
if (edsmPlayer.isUsable()) {
return true
}
val frontierPlayer = FrontierPlayer(context)
if (frontierPlayer.isUsable()) {
return true
}
return false
}
fun hasCommanderInformations(context: Context): Boolean {
val edsmPlayer = EDSMPlayer(context)
val inaraPlayer = InaraPlayer(context)
val frontierPlayer = FrontierPlayer(context)
return edsmPlayer.isUsable() || inaraPlayer.isUsable() || frontierPlayer.isUsable()
}
fun setCachedCurrentCommanderPosition(context: Context, systemName: String) {
SettingsUtils.setString(
context,
context.getString(R.string.commander_position_cache_key),
systemName
)
}
fun getCachedCurrentCommanderPosition(context: Context): String? {
return SettingsUtils.getString(
context,
context.getString(R.string.commander_position_cache_key)
)
}
} | mit | 364fc4ba9af6d56cc98b342ba9e6c565 | 27.183908 | 91 | 0.610958 | 4.596014 | false | false | false | false |
mrebollob/LoteriadeNavidad | androidApp/src/main/java/com/mrebollob/loteria/android/presentation/home/HomeViewModel.kt | 1 | 1797 | package com.mrebollob.loteria.android.presentation.home
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.mrebollob.loteria.domain.entity.SortingMethod
import com.mrebollob.loteria.domain.repository.SettingsRepository
import com.mrebollob.loteria.domain.repository.TicketsRepository
import com.mrebollob.loteria.domain.usecase.GetDaysToLotteryDraw
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.stateIn
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch
class HomeViewModel(
private val getDaysToLotteryDraw: GetDaysToLotteryDraw,
private val ticketsRepository: TicketsRepository,
private val settingsRepository: SettingsRepository,
) : ViewModel() {
private val viewModelState = MutableStateFlow(HomeViewModelState())
val uiState = viewModelState
.map { it.toUiState() }
.stateIn(
viewModelScope,
SharingStarted.Eagerly,
viewModelState.value.toUiState()
)
fun refreshData() {
viewModelState.update { it.copy(isLoading = true) }
viewModelScope.launch {
val daysToLotteryDraw = getDaysToLotteryDraw.execute()
val tickets = ticketsRepository.getTickets().getOrElse { emptyList() }
val sortingMethod =
settingsRepository.getSortingMethod().getOrElse { SortingMethod.NAME }
viewModelState.update {
it.copy(
daysToLotteryDraw = daysToLotteryDraw,
sortingMethod = sortingMethod,
tickets = tickets,
isLoading = false
)
}
}
}
}
| apache-2.0 | da24cf7d15d859e938a8211d3817f4fb | 34.94 | 86 | 0.69616 | 5.178674 | false | false | false | false |
dkhmelenko/miband-android | miband-sdk-kotlin/src/main/java/com/khmelenko/lab/miband/model/Protocol.kt | 2 | 1017 | package com.khmelenko.lab.miband.model
/**
* Defines values for accessing data and controlling band
*
* @author Dmytro Khmelenko
*/
object Protocol {
val PAIR = byteArrayOf(2)
val VIBRATION_WITH_LED = byteArrayOf(1)
val VIBRATION_10_TIMES_WITH_LED = byteArrayOf(2)
val VIBRATION_WITHOUT_LED = byteArrayOf(4)
val STOP_VIBRATION = byteArrayOf(0)
val ENABLE_REALTIME_STEPS_NOTIFY = byteArrayOf(3, 1)
val DISABLE_REALTIME_STEPS_NOTIFY = byteArrayOf(3, 0)
val ENABLE_SENSOR_DATA_NOTIFY = byteArrayOf(18, 1)
val DISABLE_SENSOR_DATA_NOTIFY = byteArrayOf(18, 0)
val SET_COLOR_RED = byteArrayOf(14, 6, 1, 2, 1)
val SET_COLOR_BLUE = byteArrayOf(14, 0, 6, 6, 1)
val SET_COLOR_ORANGE = byteArrayOf(14, 6, 2, 0, 1)
val SET_COLOR_GREEN = byteArrayOf(14, 4, 5, 0, 1)
val START_HEART_RATE_SCAN = byteArrayOf(21, 2, 1)
val REBOOT = byteArrayOf(12)
val REMOTE_DISCONNECT = byteArrayOf(1)
val FACTORY_RESET = byteArrayOf(9)
val SELF_TEST = byteArrayOf(2)
}
| apache-2.0 | 7f913555434b5f8dd726b670626bb8f3 | 34.068966 | 57 | 0.684366 | 3.280645 | false | false | false | false |
Kotlin/dokka | plugins/base/src/main/kotlin/parsers/Parser.kt | 1 | 5318 | package org.jetbrains.dokka.base.parsers
import org.jetbrains.dokka.model.doc.*
import org.jetbrains.dokka.model.doc.Deprecated
import org.jetbrains.dokka.model.doc.Suppress
abstract class Parser {
abstract fun parseStringToDocNode(extractedString: String): DocTag
abstract fun preparse(text: String): String
open fun parse(text: String): DocumentationNode =
DocumentationNode(extractTagsToListOfPairs(preparse(text)).map { (tag, content) -> parseTagWithBody(tag, content) })
open fun parseTagWithBody(tagName: String, content: String): TagWrapper =
when (tagName) {
"description" -> Description(parseStringToDocNode(content))
"author" -> Author(parseStringToDocNode(content))
"version" -> Version(parseStringToDocNode(content))
"since" -> Since(parseStringToDocNode(content))
"see" -> See(
parseStringToDocNode(content.substringAfter(' ')),
content.substringBefore(' '),
null
)
"param" -> Param(
parseStringToDocNode(content.substringAfter(' ')),
content.substringBefore(' ')
)
"property" -> Property(
parseStringToDocNode(content.substringAfter(' ')),
content.substringBefore(' ')
)
"return" -> Return(parseStringToDocNode(content))
"constructor" -> Constructor(parseStringToDocNode(content))
"receiver" -> Receiver(parseStringToDocNode(content))
"throws", "exception" -> Throws(
parseStringToDocNode(content.substringAfter(' ')),
content.substringBefore(' '),
null
)
"deprecated" -> Deprecated(parseStringToDocNode(content))
"sample" -> Sample(
parseStringToDocNode(content.substringAfter(' ')),
content.substringBefore(' ')
)
"suppress" -> Suppress(parseStringToDocNode(content))
else -> CustomTagWrapper(parseStringToDocNode(content), tagName)
}
/**
* KDoc parser from Kotlin compiler relies on a comment asterisk
* So there is a mini parser here
* TODO: at least to adapt [org.jetbrains.kotlin.kdoc.lexer.KDocLexer] to analyze KDoc without the asterisks and use it here
*/
private fun extractTagsToListOfPairs(text: String): List<Pair<String, String>> =
"description $text"
.extractKDocSections()
.map { content ->
val contentWithEscapedAts = content.replace("\\@", "@")
val (tag, body) = contentWithEscapedAts.split(" ", limit = 2)
tag to body
}
/**
* Ignore a doc tag inside code spans and blocks
* @see org.jetbrains.kotlin.kdoc.psi.impl.KDocSection
*/
private fun CharSequence.extractKDocSections(delimiter: String = "\n@"): List<String> {
var countOfBackticks = 0
var countOfTildes = 0
var countOfBackticksInOpeningFence = 0
var countOfTildesInOpeningFence = 0
var isInCode = false
val result = mutableListOf<String>()
var rangeStart = 0
var rangeEnd = 0
var currentOffset = 0
while (currentOffset < length) {
when (get(currentOffset)) {
'`' -> {
countOfBackticks++
countOfTildes = 0
}
'~' -> {
countOfTildes++
countOfBackticks = 0
}
else -> {
if (isInCode) {
// The closing code fence must be at least as long as the opening fence
if(countOfBackticks >= countOfBackticksInOpeningFence
|| countOfTildes >= countOfTildesInOpeningFence)
isInCode = false
} else {
// as per CommonMark spec, there can be any number of backticks for a code span, not only one or three
if (countOfBackticks > 0) {
isInCode = true
countOfBackticksInOpeningFence = countOfBackticks
countOfTildesInOpeningFence = Int.MAX_VALUE
}
// tildes are only for a code block, not code span
if (countOfTildes >= 3) {
isInCode = true
countOfTildesInOpeningFence = countOfTildes
countOfBackticksInOpeningFence = Int.MAX_VALUE
}
}
countOfTildes = 0
countOfBackticks = 0
}
}
if (!isInCode && startsWith(delimiter, currentOffset)) {
result.add(substring(rangeStart, rangeEnd))
currentOffset += delimiter.length
rangeStart = currentOffset
rangeEnd = currentOffset
continue
}
++rangeEnd
++currentOffset
}
result.add(substring(rangeStart, rangeEnd))
return result
}
}
| apache-2.0 | a27659c391e570dbaead1fee960ff015 | 39.59542 | 128 | 0.539677 | 5.168124 | false | false | false | false |
tinypass/piano-sdk-for-android | composer/src/test/java/io/piano/android/composer/PrefsStorageTest.kt | 1 | 5634 | package io.piano.android.composer
import android.content.Context
import android.content.SharedPreferences
import com.nhaarman.mockitokotlin2.any
import com.nhaarman.mockitokotlin2.doNothing
import com.nhaarman.mockitokotlin2.doReturn
import com.nhaarman.mockitokotlin2.mock
import com.nhaarman.mockitokotlin2.spy
import com.nhaarman.mockitokotlin2.verify
import com.nhaarman.mockitokotlin2.whenever
import java.util.Date
import kotlin.test.Test
import kotlin.test.assertEquals
class PrefsStorageTest {
private val prefsEditor: SharedPreferences.Editor = mock {
on { putLong(any(), any()) } doReturn mock
on { putInt(any(), any()) } doReturn mock
on { putString(any(), any()) } doReturn mock
}
private val prefs: SharedPreferences = mock {
on { edit() } doReturn prefsEditor
}
private val context: Context = mock {
on { getSharedPreferences(any(), any()) } doReturn prefs
}
private val prefsStorage = spy(PrefsStorage(context))
@Test
fun getValueForKey() {
whenever(prefs.getString(KEY, null)).thenReturn(VALUE)
assertEquals(VALUE, prefsStorage.getValueForKey(KEY))
verify(prefs).getString(KEY, null)
}
@Test
fun setValueForKey() {
prefsStorage.setValueForKey(KEY, VALUE)
verify(prefsEditor).putString(KEY, VALUE)
}
@Test
fun getVisitId() {
doReturn(DUMMY_STRING).`when`(prefsStorage).getValueForKey(any())
assertEquals(DUMMY_STRING, prefsStorage.visitId)
verify(prefsStorage).getValueForKey(PrefsStorage.KEY_VISIT_ID)
}
@Test
fun setVisitId() {
doNothing().`when`(prefsStorage).setValueForKey(any(), any())
prefsStorage.visitId = DUMMY_STRING
verify(prefsStorage).setValueForKey(PrefsStorage.KEY_VISIT_ID, DUMMY_STRING)
}
@Test
fun getVisitTimestamp() {
whenever(prefs.getLong(PrefsStorage.KEY_VISIT_ID_TIMESTAMP, 0)).thenReturn(DUMMY_LONG)
assertEquals(DUMMY_LONG, prefsStorage.visitTimestamp)
verify(prefs).getLong(PrefsStorage.KEY_VISIT_ID_TIMESTAMP, 0)
}
@Test
fun setVisitDateByTimestamp() {
prefsStorage.setVisitDate(DUMMY_LONG)
verify(prefsEditor).putLong(PrefsStorage.KEY_VISIT_ID_TIMESTAMP, DUMMY_LONG)
}
@Test
fun setVisitDateByDate() {
doNothing().`when`(prefsStorage).setVisitDate(any<Long>())
val date: Date = mock() {
on { time } doReturn DUMMY_LONG
}
prefsStorage.setVisitDate(date)
verify(date).time
verify(prefsStorage).setVisitDate(DUMMY_LONG)
}
@Test
fun setVisitDateByNullDate() {
doNothing().`when`(prefsStorage).setVisitDate(any<Long>())
prefsStorage.setVisitDate(null)
verify(prefsStorage).setVisitDate(0)
}
@Test
fun getTpBrowserCookie() {
doReturn(DUMMY_STRING).`when`(prefsStorage).getValueForKey(any())
assertEquals(DUMMY_STRING, prefsStorage.tpBrowserCookie)
verify(prefsStorage).getValueForKey(PrefsStorage.KEY_TP_BROWSER_COOKIE)
}
@Test
fun setTpBrowserCookie() {
doNothing().`when`(prefsStorage).setValueForKey(any(), any())
prefsStorage.tpBrowserCookie = DUMMY_STRING
verify(prefsStorage).setValueForKey(PrefsStorage.KEY_TP_BROWSER_COOKIE, DUMMY_STRING)
}
@Test
fun getXbuilderBrowserCookie() {
doReturn(DUMMY_STRING).`when`(prefsStorage).getValueForKey(any())
assertEquals(DUMMY_STRING, prefsStorage.xbuilderBrowserCookie)
verify(prefsStorage).getValueForKey(PrefsStorage.KEY_XBUILDER_BROWSER_COOKIE)
}
@Test
fun setXbuilderBrowserCookie() {
doNothing().`when`(prefsStorage).setValueForKey(any(), any())
prefsStorage.xbuilderBrowserCookie = DUMMY_STRING
verify(prefsStorage).setValueForKey(PrefsStorage.KEY_XBUILDER_BROWSER_COOKIE, DUMMY_STRING)
}
@Test
fun getTpAccessCookie() {
doReturn(DUMMY_STRING).`when`(prefsStorage).getValueForKey(any())
assertEquals(DUMMY_STRING, prefsStorage.tpAccessCookie)
verify(prefsStorage).getValueForKey(PrefsStorage.KEY_TP_ACCESS_COOKIE)
}
@Test
fun setTpAccessCookie() {
doNothing().`when`(prefsStorage).setValueForKey(any(), any())
prefsStorage.tpAccessCookie = DUMMY_STRING
verify(prefsStorage).setValueForKey(PrefsStorage.KEY_TP_ACCESS_COOKIE, DUMMY_STRING)
}
@Test
fun getServerTimezoneOffset() {
whenever(prefs.getInt(PrefsStorage.KEY_TIMEZONE_OFFSET, 0)).thenReturn(DUMMY_INT)
assertEquals(DUMMY_INT, prefsStorage.serverTimezoneOffset)
verify(prefs).getInt(PrefsStorage.KEY_TIMEZONE_OFFSET, 0)
}
@Test
fun setServerTimezoneOffset() {
prefsStorage.serverTimezoneOffset = DUMMY_INT
verify(prefsEditor).putInt(PrefsStorage.KEY_TIMEZONE_OFFSET, DUMMY_INT)
}
@Test
fun getVisitTimeout() {
whenever(prefs.getLong(PrefsStorage.KEY_VISIT_TIMEOUT, PrefsStorage.VISIT_TIMEOUT_FALLBACK)).thenReturn(
DUMMY_LONG
)
assertEquals(DUMMY_LONG, prefsStorage.visitTimeout)
verify(prefs).getLong(PrefsStorage.KEY_VISIT_TIMEOUT, PrefsStorage.VISIT_TIMEOUT_FALLBACK)
}
@Test
fun setVisitTimeout() {
prefsStorage.visitTimeout = DUMMY_LONG
verify(prefsEditor).putLong(PrefsStorage.KEY_VISIT_TIMEOUT, DUMMY_LONG)
}
companion object {
const val KEY = "KEY"
const val VALUE = "VALUE"
const val DUMMY_STRING = "DUMMY"
const val DUMMY_INT = 1234
const val DUMMY_LONG = 1234L
}
}
| apache-2.0 | ac63664cd06fb12e4ae9069801c82fe2 | 33.145455 | 112 | 0.686191 | 4.313936 | false | true | false | false |
Sevran/DnDice | app/src/main/java/io/deuxsept/dndice/Model/Dice.kt | 1 | 1245 | package io.deuxsept.dndice.Model
import java.util.*
/**
* Created by Flo
* 09/08/2016.
*/
class Dice: IRollable {
override var results: MutableList<Int>
/**
* Type of dice (e.g. d20, d10, d4, d<n> where <n> is <dice_type>)
*/
var dice_type: Int
/**
* Amount of rolls to do (e.g. 2d10, 4d4, <n>d6 where <n> is <dice_rolls>)
*/
var dice_rolls: Int
constructor(dice_rolls: Int, dice_type: Int) {
this.dice_rolls = dice_rolls
this.dice_type = dice_type
this.results = mutableListOf()
}
override fun toString(): String {
return "${dice_rolls}d$dice_type"
}
override fun equals(other: Any?): Boolean {
return when(other) {
is Dice -> { this.dice_rolls == other.dice_rolls && this.dice_type == other.dice_type }
else -> { false }
}
}
override fun roll(): List<Int> {
val rng: Random = Random()
results.clear()
for (i in 0..Math.abs(dice_rolls) - 1) {
results.add((rng.nextInt(dice_type) + 1) * Integer.signum(dice_rolls))
}
return results
}
override fun results_as_string(): String {
return "[${results.joinToString(",")}]"
}
} | mit | e68757434f1792c02327674678e618ae | 22.961538 | 99 | 0.550201 | 3.293651 | false | false | false | false |
Kotlin/dokka | plugins/base/src/test/kotlin/locationProvider/AndroidExternalLocationProviderTest.kt | 1 | 3597 | package locationProvider
import org.jetbrains.dokka.base.resolvers.external.DefaultExternalLocationProvider
import org.jetbrains.dokka.base.resolvers.external.javadoc.AndroidExternalLocationProvider
import org.jetbrains.dokka.base.resolvers.shared.ExternalDocumentation
import org.jetbrains.dokka.base.resolvers.shared.PackageList
import org.jetbrains.dokka.base.resolvers.shared.RecognizedLinkFormat
import org.jetbrains.dokka.links.Callable
import org.jetbrains.dokka.links.DRI
import org.jetbrains.dokka.links.TypeConstructor
import org.jetbrains.dokka.plugability.DokkaContext
import org.jetbrains.dokka.base.testApi.testRunner.BaseAbstractTest
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.Test
import java.net.URL
class AndroidExternalLocationProviderTest : BaseAbstractTest() {
private val android = ExternalDocumentation(
URL("https://developer.android.com/reference/kotlin"),
PackageList(
RecognizedLinkFormat.DokkaHtml,
mapOf("" to setOf("android.content", "android.net")),
emptyMap(),
URL("file://not-used")
)
)
private val androidx = ExternalDocumentation(
URL("https://developer.android.com/reference/kotlin"),
PackageList(
RecognizedLinkFormat.DokkaHtml,
mapOf("" to setOf("androidx.appcompat.app")),
emptyMap(),
URL("file://not-used")
)
)
private val configuration = dokkaConfiguration {
sourceSets {
sourceSet {
sourceRoots = listOf("src/")
classpath += jvmStdlibPath!!
}
}
}
private fun getTestLocationProvider(
externalDocumentation: ExternalDocumentation,
context: DokkaContext? = null
): DefaultExternalLocationProvider {
val dokkaContext = context ?: DokkaContext.create(configuration, logger, emptyList())
return AndroidExternalLocationProvider(externalDocumentation, dokkaContext)
}
@Test
fun `#1230 anchor to a method from AndroidX`() {
val locationProvider = getTestLocationProvider(androidx)
val dri = DRI(
"androidx.appcompat.app",
"AppCompatActivity",
Callable("findViewById", null, listOf(TypeConstructor("kotlin.Int", emptyList())))
)
assertEquals(
"${androidx.documentationURL}/androidx/appcompat/app/AppCompatActivity.html#findviewbyid",
locationProvider.resolve(dri)
)
}
@Test
fun `anchor to a method from Android`() {
val locationProvider = getTestLocationProvider(android)
val dri = DRI(
"android.content",
"ContextWrapper",
Callable(
"checkCallingUriPermission",
null,
listOf(
TypeConstructor("android.net.Uri", emptyList()),
TypeConstructor("kotlin.Int", emptyList())
)
)
)
assertEquals(
"${android.documentationURL}/android/content/ContextWrapper.html#checkcallinguripermission",
locationProvider.resolve(dri)
)
}
@Test
fun `should return null for method not in list`() {
val locationProvider = getTestLocationProvider(android)
val dri = DRI(
"foo",
"Bar",
Callable(
"baz",
null,
emptyList()
)
)
assertEquals(null, locationProvider.resolve(dri))
}
}
| apache-2.0 | 89c0f94a9047ebbf219e70df4d24325e | 33.257143 | 104 | 0.632472 | 5.289706 | false | true | false | false |
alygin/intellij-rust | src/test/kotlin/org/rust/lang/core/psi/RsLiteralOffsetsTest.kt | 2 | 4170 | /*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.lang.core.psi
import com.intellij.psi.impl.source.tree.LeafPsiElement
import com.intellij.psi.tree.IElementType
import org.junit.Assert.assertEquals
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.runners.Parameterized
import org.rust.lang.core.psi.RsElementTypes.BYTE_LITERAL as BCH
import org.rust.lang.core.psi.RsElementTypes.CHAR_LITERAL as CHR
import org.rust.lang.core.psi.RsElementTypes.FLOAT_LITERAL as FLT
import org.rust.lang.core.psi.RsElementTypes.INTEGER_LITERAL as INT
import org.rust.lang.core.psi.RsElementTypes.RAW_BYTE_STRING_LITERAL as BRW
import org.rust.lang.core.psi.RsElementTypes.RAW_STRING_LITERAL as RAW
abstract class RsLiteralOffsetsTestCase(
private val type: IElementType,
private val text: String,
private val constructor: (IElementType, CharSequence) -> LiteralOffsets
) {
protected fun doTest() {
val offsets = constructor(type, text.replace("|", ""))
val expected = makeOffsets(text)
assertEquals(expected, offsets)
}
private fun makeOffsets(text: String): LiteralOffsets {
val parts = text.split('|')
assert(parts.size == 5)
val prefixEnd = parts[0].length
val openDelimEnd = prefixEnd + parts[1].length
val valueEnd = openDelimEnd + parts[2].length
val closeDelimEnd = valueEnd + parts[3].length
val suffixEnd = closeDelimEnd + parts[4].length
return LiteralOffsets.fromEndOffsets(prefixEnd, openDelimEnd, valueEnd, closeDelimEnd, suffixEnd)
}
}
@RunWith(Parameterized::class)
class RsNumericLiteralOffsetsTest(
type: IElementType,
text: String
) : RsLiteralOffsetsTestCase(type, text, { type, text -> offsetsForNumber(LeafPsiElement(type, text)) }) {
@Test
fun test() = doTest()
companion object {
@Parameterized.Parameters(name = "{index}: {1}")
@JvmStatic fun data(): Collection<Array<Any>> = listOf(
arrayOf(INT, "||123||i32"),
arrayOf(INT, "||0||u"),
arrayOf(INT, "||0||"),
arrayOf(FLT, "||-12||f32"),
arrayOf(FLT, "||-12.124||f32"),
arrayOf(FLT, "||1.0e10||"),
arrayOf(FLT, "||1.0e||"),
arrayOf(FLT, "||1.0e||e"),
arrayOf(INT, "||0xABC||"),
arrayOf(INT, "||0xABC||i64"),
arrayOf(FLT, "||2.||"),
arrayOf(INT, "||0x||"),
arrayOf(INT, "||1_______||"),
arrayOf(INT, "||1_______||i32")
)
}
}
@RunWith(Parameterized::class)
class RsStringLiteralOffsetsTest(type: IElementType, text: String) :
RsLiteralOffsetsTestCase(type, text, { type, text -> offsetsForText(LeafPsiElement(type, text)) }) {
@Test
fun test() = doTest()
companion object {
@Parameterized.Parameters(name = "{index}: {1}")
@JvmStatic fun data(): Collection<Array<Any>> = listOf(
arrayOf(CHR, "|'|a|'|suf"),
arrayOf(BCH, "b|'|a|'|"),
arrayOf(BCH, "b|'|a|'|suf"),
arrayOf(CHR, "|'|a||"),
arrayOf(CHR, "|'||'|"),
arrayOf(CHR, "|'|\\\\|'|"),
arrayOf(CHR, "|'|\\'||"),
arrayOf(CHR, "|'||'|a"),
arrayOf(CHR, "|'|\\\\|'|a"),
arrayOf(CHR, "|'|\\'a||"),
arrayOf(CHR, "|'|\\\\\\'a||")
)
}
}
@RunWith(Parameterized::class)
class RsRawStringLiteralOffsetsTest(type: IElementType, text: String) :
RsLiteralOffsetsTestCase(type, text, { type, text -> offsetsForText(LeafPsiElement(type, text)) }) {
@Test
fun test() = doTest()
companion object {
@Parameterized.Parameters(name = "{index}: {1}")
@JvmStatic fun data(): Collection<Array<Any>> = listOf(
arrayOf(RAW, "r|\"|a|\"|suf"),
arrayOf(BRW, "br|\"|a|\"|suf"),
arrayOf(RAW, "r|\"|a|\"|"),
arrayOf(RAW, "r|###\"|aaa||"),
arrayOf(RAW, "r|###\"|aaa\"##||"),
arrayOf(RAW, "r|###\"||\"###|"),
arrayOf(RAW, "r|###\"|a\"##a|\"###|s")
)
}
}
| mit | 017071b477afc9a08b79cce9c4488209 | 34.641026 | 106 | 0.582254 | 3.836247 | false | true | false | false |
herbeth1u/VNDB-Android | app/src/main/java/com/booboot/vndbandroid/ui/vnlist/VNHolder.kt | 1 | 3962 | package com.booboot.vndbandroid.ui.vnlist
import android.view.View
import androidx.core.content.ContextCompat
import androidx.core.view.isVisible
import androidx.recyclerview.widget.RecyclerView
import com.booboot.vndbandroid.R
import com.booboot.vndbandroid.extensions.showNsfwImage
import com.booboot.vndbandroid.model.vndb.Label
import com.booboot.vndbandroid.model.vndb.UserList
import com.booboot.vndbandroid.model.vndb.VN
import com.booboot.vndbandroid.model.vndbandroid.Vote
import com.booboot.vndbandroid.util.Utils
import com.google.android.flexbox.AlignItems
import com.google.android.flexbox.FlexboxLayoutManager
import com.google.android.flexbox.JustifyContent
import com.xwray.groupie.GroupAdapter
import com.xwray.groupie.kotlinandroidextensions.GroupieViewHolder
import com.xwray.groupie.kotlinandroidextensions.Item
import kotlinx.android.extensions.LayoutContainer
import kotlinx.android.synthetic.main.label_tag.*
import kotlinx.android.synthetic.main.nsfw_tag.*
import kotlinx.android.synthetic.main.vn_card.*
class VNHolder(override val containerView: View, private val onVnClicked: (View, VN) -> Unit) : RecyclerView.ViewHolder(containerView), LayoutContainer {
val adapter = GroupAdapter<GroupieViewHolder>()
init {
labels.adapter = adapter
labels.layoutManager = FlexboxLayoutManager(containerView.context).apply {
alignItems = AlignItems.CENTER
justifyContent = JustifyContent.CENTER
}
labels.suppressLayout(true)
}
fun bind(
vn: VN,
userList: UserList?,
showFullDate: Boolean,
showRank: Boolean,
showRating: Boolean,
showPopularity: Boolean,
showVoteCount: Boolean
) {
cardView.setOnClickListener { onVnClicked(containerView, vn) }
val titleText = StringBuilder()
val subtitleText = StringBuilder()
if (showRank)
titleText.append("#").append(adapterPosition + 1).append(containerView.context.getString(R.string.dash))
titleText.append(vn.title)
when {
showRating -> subtitleText.append(vn.rating).append(" (").append(Vote.getName(vn.rating)).append(")")
showPopularity -> subtitleText.append(vn.popularity).append("%")
showVoteCount -> subtitleText.append(vn.votecount).append(" votes")
else -> subtitleText.append(Utils.getDate(vn.released, showFullDate))
}
subtitleText.append(containerView.context.getString(R.string.bullet))
if (vn.length ?: 0 > 0)
subtitleText.append(vn.lengthFull())
else
subtitleText.append(Utils.getDate(vn.released, true))
image.transitionName = "slideshow" + vn.id
image.showNsfwImage(vn.image, vn.image_nsfw, nsfwTag)
title.text = titleText
subtitle.text = subtitleText
voteButton.isVisible = userList?.vote != null
voteButton.text = Vote.toShortString(userList?.vote)
voteButton.background = ContextCompat.getDrawable(containerView.context, Vote.getDrawableColor10(userList?.vote))
val showLabels = userList != null && userList.labelItems.isNotEmpty()
labels.isVisible = showLabels
noLabelText.isVisible = !showLabels
when {
userList == null -> noLabelText.setText(R.string.not_in_your_list)
userList.labelItems.isEmpty() -> noLabelText.setText(R.string.no_labels)
else -> adapter.update(userList.labelItems)
}
}
}
data class VNLabelItem(var label: Label) : Item() {
override fun bind(viewHolder: GroupieViewHolder, position: Int) {
viewHolder.apply {
tagText.text = label.label
tagText.setTextColor(label.textColor(containerView.context))
tagText.setBackgroundColor(label.backgroundColor(containerView.context))
}
}
override fun getId() = label.id
override fun getLayout() = R.layout.label_tag
} | gpl-3.0 | bfc671c22157eacf78c141df2ef64d65 | 39.438776 | 153 | 0.706714 | 4.446689 | false | false | false | false |
wuseal/JsonToKotlinClass | gradle-changelog-plugin-main/src/main/kotlin/org/jetbrains/changelog/ChangelogPluginExtension.kt | 1 | 3504 | package org.jetbrains.changelog
import groovy.lang.Closure
import org.gradle.api.model.ObjectFactory
import org.gradle.api.tasks.Internal
import org.gradle.api.tasks.Optional
import org.jetbrains.changelog.exceptions.VersionNotSpecifiedException
import java.io.File
import java.util.regex.Pattern
@Suppress("UnstableApiUsage")
open class ChangelogPluginExtension(objects: ObjectFactory, private val projectDir: File) {
@Optional
@Internal
private val groupsProperty = objects.listProperty(String::class.java).apply {
set(listOf("Added", "Changed", "Deprecated", "Removed", "Fixed", "Security"))
}
var groups: List<String>
get() = groupsProperty.getOrElse(emptyList())
set(value) = groupsProperty.set(value)
@Optional
@Internal
private val headerProperty = objects.property(Closure::class.java).apply {
set(closure { "[$version]" })
}
var header: Closure<*>
get() = headerProperty.get()
set(value) = headerProperty.set(value)
@Optional
@Internal
private val headerParserRegexProperty = objects.property(Regex::class.java)
var headerParserRegex: Any?
get() = headerParserRegexProperty.orNull
set(value) = headerParserRegexProperty.set(headerParserRegexHelper(value))
private fun <T> headerParserRegexHelper(t: T) = when (t) {
is Regex -> t
is String -> t.toRegex()
is Pattern -> t.toRegex()
else -> throw IllegalArgumentException("Unsupported type of $t. Expected value types: Regex, String, Pattern.")
}
@Optional
@Internal
private val itemPrefixProperty = objects.property(String::class.java).apply {
set("-")
}
var itemPrefix: String
get() = itemPrefixProperty.get()
set(value) = itemPrefixProperty.set(value)
@Optional
@Internal
private val keepUnreleasedSectionProperty = objects.property(Boolean::class.java).apply {
set(true)
}
var keepUnreleasedSection: Boolean
get() = keepUnreleasedSectionProperty.get()
set(value) = keepUnreleasedSectionProperty.set(value)
@Optional
@Internal
private val patchEmptyProperty = objects.property(Boolean::class.java).apply {
set(true)
}
var patchEmpty: Boolean
get() = patchEmptyProperty.get()
set(value) = patchEmptyProperty.set(value)
@Optional
@Internal
private val pathProperty = objects.property(String::class.java).apply {
set("$projectDir/CHANGELOG.md")
}
var path: String
get() = pathProperty.get()
set(value) = pathProperty.set(value)
@Internal
private val versionProperty = objects.property(String::class.java)
var version: String
get() = versionProperty.run {
if (isPresent) {
return get()
}
throw VersionNotSpecifiedException()
}
set(value) = versionProperty.set(value)
@Optional
@Internal
private val unreleasedTermProperty = objects.property(String::class.java).apply {
set("[Unreleased]")
}
var unreleasedTerm: String
get() = unreleasedTermProperty.get()
set(value) = unreleasedTermProperty.set(value)
fun getUnreleased() = get(unreleasedTerm)
fun get(version: String) = Changelog(this).get(version)
fun getLatest() = Changelog(this).getLatest()
fun getAll() = Changelog(this).getAll()
fun has(version: String) = Changelog(this).has(version)
}
| gpl-3.0 | 80e42b293168623814d92753f9927bb0 | 30.567568 | 119 | 0.666952 | 4.257594 | false | false | false | false |
mbuhot/eskotlin | src/main/kotlin/mbuhot/eskotlin/query/term/Prefix.kt | 1 | 939 | /*
* Copyright (c) 2016. Michael Buhot [email protected]
*/
package mbuhot.eskotlin.query.term
import mbuhot.eskotlin.query.QueryData
import mbuhot.eskotlin.query.initQuery
import org.elasticsearch.index.query.PrefixQueryBuilder
class PrefixBlock {
class PrefixData(
val name: String,
var prefix: String? = null) : QueryData()
infix fun String.to(prefix: String) = PrefixData(name = this, prefix = prefix)
@Deprecated(message = "Use invoke operator instead.", replaceWith = ReplaceWith("invoke(init)"))
infix fun String.to(init: PrefixData.() -> Unit) = this.invoke(init)
operator fun String.invoke(init: PrefixData.() -> Unit) = PrefixData(name = this).apply(init)
}
fun prefix(init: PrefixBlock.() -> PrefixBlock.PrefixData): PrefixQueryBuilder {
val params = PrefixBlock().init()
return PrefixQueryBuilder(params.name, params.prefix).apply {
initQuery(params)
}
} | mit | c5c5a4ef05d74c03ec0bc52a659e892a | 31.413793 | 100 | 0.702875 | 3.864198 | false | false | false | false |
http4k/http4k | http4k-server/undertow/src/main/kotlin/org/http4k/server/Http4kUndertowWebSocketCallback.kt | 1 | 2968 | package org.http4k.server
import io.undertow.server.HttpServerExchange
import io.undertow.websockets.WebSocketConnectionCallback
import io.undertow.websockets.core.AbstractReceiveListener
import io.undertow.websockets.core.BufferedBinaryMessage
import io.undertow.websockets.core.BufferedTextMessage
import io.undertow.websockets.core.WebSocketChannel
import io.undertow.websockets.core.WebSockets.sendBinary
import io.undertow.websockets.core.WebSockets.sendClose
import io.undertow.websockets.core.WebSockets.sendText
import io.undertow.websockets.spi.WebSocketHttpExchange
import org.http4k.core.Body
import org.http4k.core.Method.GET
import org.http4k.core.Request
import org.http4k.core.StreamBody
import org.http4k.websocket.PushPullAdaptingWebSocket
import org.http4k.websocket.WsHandler
import org.http4k.websocket.WsMessage
import org.http4k.websocket.WsStatus
import java.io.IOException
class Http4kWebSocketCallback(private val ws: WsHandler) : WebSocketConnectionCallback {
override fun onConnect(exchange: WebSocketHttpExchange, channel: WebSocketChannel) {
val upgradeRequest = exchange.asRequest()
val socket = object : PushPullAdaptingWebSocket(upgradeRequest) {
override fun send(message: WsMessage) =
if (message.body is StreamBody) sendBinary(message.body.payload, channel, null)
else sendText(message.bodyString(), channel, null)
override fun close(status: WsStatus) {
sendClose(status.code, status.description, channel, null)
}
}.apply(ws(upgradeRequest))
channel.addCloseTask {
socket.triggerClose(WsStatus(it.closeCode, it.closeReason ?: "unknown"))
}
channel.receiveSetter.set(object : AbstractReceiveListener() {
override fun onFullTextMessage(channel: WebSocketChannel, message: BufferedTextMessage) {
try {
socket.triggerMessage(WsMessage(Body(message.data)))
} catch (e: IOException) {
throw e
} catch (e: Exception) {
socket.triggerError(e)
throw e
}
}
override fun onFullBinaryMessage(channel: WebSocketChannel, message: BufferedBinaryMessage) =
message.data.resource.forEach { socket.triggerMessage(WsMessage(Body(it))) }
override fun onError(channel: WebSocketChannel, error: Throwable) = socket.triggerError(error)
})
channel.resumeReceives()
}
}
private fun WebSocketHttpExchange.asRequest() = Request(GET, requestURI)
.headers(requestHeaders.toList().flatMap { h -> h.second.map { h.first to it } })
fun requiresWebSocketUpgrade(): (HttpServerExchange) -> Boolean = {
(it.requestHeaders["Connection"]?.any { it.equals("upgrade", true) } ?: false) &&
(it.requestHeaders["Upgrade"]?.any { it.equals("websocket", true) } ?: false)
}
| apache-2.0 | cc72de747cfac26192bc1cf01f35b0a2 | 42.014493 | 106 | 0.702156 | 4.358297 | false | false | false | false |
facebookincubator/ktfmt | core/src/main/java/com/facebook/ktfmt/format/KotlinInput.kt | 1 | 8381 | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* 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.facebook.ktfmt.format
import com.google.common.collect.DiscreteDomain
import com.google.common.collect.ImmutableList
import com.google.common.collect.ImmutableMap
import com.google.common.collect.ImmutableRangeMap
import com.google.common.collect.Iterables.getLast
import com.google.common.collect.Range
import com.google.common.collect.RangeSet
import com.google.common.collect.TreeRangeSet
import com.google.googlejavaformat.Input
import com.google.googlejavaformat.Newlines
import com.google.googlejavaformat.java.FormatterException
import com.google.googlejavaformat.java.JavaOutput
import java.util.LinkedHashMap
import org.jetbrains.kotlin.com.intellij.openapi.util.text.StringUtil
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.psi.KtFile
// TODO: share the code with JavaInput instead of copy-pasting here.
/**
* KotlinInput is for Kotlin what JavaInput is for Java.
*
* <p>KotlinInput is duplicating most of JavaInput's code, but uses the Kotlin compiler as a lexer
* instead of Javac. This is required because some valid Kotlin programs are not valid Java
* programs, e.g., "a..b".
*
* <p>See javadoc for JavaInput.
*/
class KotlinInput(private val text: String, file: KtFile) : Input() {
private val tokens: ImmutableList<Token> // The Tokens for this input.
private val positionToColumnMap: ImmutableMap<Int, Int> // Map Tok position to column.
private val positionTokenMap: ImmutableRangeMap<Int, Token> // Map position to Token.
private var kN = 0 // The number of numbered toks (tokens or comments), excluding the EOF.
private val kToToken: Array<Token?>
init {
setLines(ImmutableList.copyOf(Newlines.lineIterator(text)))
val toks = buildToks(file, text)
positionToColumnMap = makePositionToColumnMap(toks)
tokens = buildTokens(toks)
val tokenLocations = ImmutableRangeMap.builder<Int, Token>()
for (token in tokens) {
val end = JavaOutput.endTok(token)
var upper = end.position
if (end.text.isNotEmpty()) {
upper += end.length() - 1
}
tokenLocations.put(Range.closed(JavaOutput.startTok(token).position, upper), token)
}
positionTokenMap = tokenLocations.build()
// adjust kN for EOF
kToToken = arrayOfNulls(kN + 1)
for (token in tokens) {
for (tok in token.toksBefore) {
if (tok.index < 0) {
continue
}
kToToken[tok.index] = token
}
kToToken[token.tok.index] = token
for (tok in token.toksAfter) {
if (tok.index < 0) {
continue
}
kToToken[tok.index] = token
}
}
}
@Throws(FormatterException::class)
fun characterRangesToTokenRanges(characterRanges: Collection<Range<Int>>): RangeSet<Int> {
val tokenRangeSet = TreeRangeSet.create<Int>()
for (characterRange0 in characterRanges) {
val characterRange = characterRange0.canonical(DiscreteDomain.integers())
tokenRangeSet.add(
characterRangeToTokenRange(
characterRange.lowerEndpoint(),
characterRange.upperEndpoint() - characterRange.lowerEndpoint()))
}
return tokenRangeSet
}
/**
* Convert from an offset and length flag pair to a token range.
*
* @param offset the `0`-based offset in characters
* @param length the length in characters
* @return the `0`-based [Range] of tokens
* @throws FormatterException
*/
@Throws(FormatterException::class)
internal fun characterRangeToTokenRange(offset: Int, length: Int): Range<Int> {
val requiredLength = offset + length
if (requiredLength > text.length) {
throw FormatterException(
String.format(
"error: invalid length %d, offset + length (%d) is outside the file",
length,
requiredLength))
}
val expandedLength =
when {
length < 0 -> return EMPTY_RANGE
length == 0 -> 1 // 0 stands for "format the line under the cursor"
else -> length
}
val enclosed =
getPositionTokenMap()
.subRangeMap(Range.closedOpen(offset, offset + expandedLength))
.asMapOfRanges()
.values
return if (enclosed.isEmpty()) {
EMPTY_RANGE
} else
Range.closedOpen(
enclosed.iterator().next().tok.index, getLast(enclosed).getTok().getIndex() + 1)
}
private fun makePositionToColumnMap(toks: List<KotlinTok>): ImmutableMap<Int, Int> {
val builder = LinkedHashMap<Int, Int>()
for (tok in toks) {
builder.put(tok.position, tok.column)
}
return ImmutableMap.copyOf(builder)
}
private fun buildToks(file: KtFile, fileText: String): ImmutableList<KotlinTok> {
val tokenizer = Tokenizer(fileText, file)
file.accept(tokenizer)
val toks = tokenizer.toks
toks.add(KotlinTok(tokenizer.index, "", "", fileText.length, 0, true, KtTokens.EOF))
kN = tokenizer.index
computeRanges(toks)
return ImmutableList.copyOf(toks)
}
private fun buildTokens(toks: List<KotlinTok>): ImmutableList<Token> {
val tokens = ImmutableList.builder<Token>()
var k = 0
val kN = toks.size
// Remaining non-tokens before the token go here.
var toksBefore: ImmutableList.Builder<KotlinTok> = ImmutableList.builder()
OUTERMOST@ while (k < kN) {
while (!toks[k].isToken) {
val tok = toks[k++]
toksBefore.add(tok)
if (isParamComment(tok)) {
while (toks[k].isNewline) {
// drop newlines after parameter comments
k++
}
}
}
val tok = toks[k++]
// Non-tokens starting on the same line go here too.
val toksAfter = ImmutableList.builder<KotlinTok>()
OUTER@ while (k < kN && !toks[k].isToken) {
// Don't attach inline comments to certain leading tokens, e.g. for `f(/*flag1=*/true).
//
// Attaching inline comments to the right token is hard, and this barely
// scratches the surface. But it's enough to do a better job with parameter
// name comments.
//
// TODO(cushon): find a better strategy.
if (toks[k].isSlashStarComment && (tok.text == "(" || tok.text == "<" || tok.text == "."))
break@OUTER
if (toks[k].isJavadocComment && tok.text == ";") break@OUTER
if (isParamComment(toks[k])) {
tokens.add(KotlinToken(toksBefore.build(), tok, toksAfter.build()))
toksBefore = ImmutableList.builder<KotlinTok>().add(toks[k++])
// drop newlines after parameter comments
while (toks[k].isNewline) {
k++
}
continue@OUTERMOST
}
val nonTokenAfter = toks[k++]
toksAfter.add(nonTokenAfter)
if (Newlines.containsBreaks(nonTokenAfter.text)) {
break
}
}
tokens.add(KotlinToken(toksBefore.build(), tok, toksAfter.build()))
toksBefore = ImmutableList.builder()
}
return tokens.build()
}
private fun isParamComment(tok: Tok): Boolean {
return tok.isSlashStarComment && tok.text.matches("/\\*[A-Za-z0-9\\s_\\-]+=\\s*\\*/".toRegex())
}
override fun getkN(): Int = kN
override fun getToken(k: Int): Token? = kToToken[k]
override fun getTokens(): ImmutableList<out Token> = tokens
override fun getPositionTokenMap(): ImmutableRangeMap<Int, out Token> = positionTokenMap
override fun getPositionToColumnMap(): ImmutableMap<Int, Int> = positionToColumnMap
override fun getText(): String = text
override fun getLineNumber(inputPosition: Int) =
StringUtil.offsetToLineColumn(text, inputPosition).line + 1
override fun getColumnNumber(inputPosition: Int) =
StringUtil.offsetToLineColumn(text, inputPosition).column
}
| apache-2.0 | a02197b2baa23a6d2bca4192ca7b417f | 35.281385 | 99 | 0.668417 | 4.0043 | false | false | false | false |
ut-iais/java-utils | src/main/java/ir/iais/utilities/javautils/ranges/DateTimeRangeSets.kt | 2 | 9998 | @file:Suppress("unused")
package ir.iais.utilities.javautils.ranges
import com.github.jonpeterson.kotlin.ranges.RangeSet
import ir.iais.utilities.javautils.IQ
import ir.iais.utilities.javautils.time.PersianDate
import java.io.Serializable
import java.time.Duration
import java.time.LocalDate
import java.time.LocalTime
import java.time.Period
import java.util.*
@JvmName("serializeDateRangeSet")
fun RangeSet<Date>.serializeForDB(): String = this.joinToString("|") { it.serializeForDB() }
@JvmName("serializeLocalDateRangeSet")
fun RangeSet<LocalDate>.serializeForDB(): String = this.joinToString("|") { it.serializeForDB() }
@JvmName("serializePersianDateRangeSet")
fun RangeSet<PersianDate>.serializeForDB(): String = this.joinToString("|") { it.serializeForDB() }
@JvmName("serializeLocalTimeRangeSet")
fun RangeSet<LocalTime>.serializeForDB(): String = this.joinToString("|") { it.serializeForDB() }
/**
* By default increment and decrement 1 day
*/
//class DateRangeSet @JvmOverloads constructor(
// ranges: List<ClosedRange<Date>> = emptyList(),
// private val step: Period = Period.ofDays(1)
//) : RangeSet<Date>(), Serializable {
//
// init {
// this += ranges
// }
//
// constructor(vararg ranges: ClosedRange<Date>) : this(ranges.asList())
//
// private constructor(rangeSet: DateRangeSet) : this(rangeSet.toList())
//
// override fun createRange(start: Date, endInclusive: Date): ClosedRange<Date> = DateRange(start, endInclusive)
//
// override fun incrementValue(value: Date): Date = value + 1.days
//
// override fun decrementValue(value: Date): Date = value - 1.days
//
// override fun clone(): RangeSet<Date> = DateRangeSet(this)
//
// override fun toString(): String = serializeForDB()
//// fun asDTO(): DateRangeSetDTO = DateRangeSetDTO(this)
//
// companion object {
// @JvmStatic
// fun of(serializedInDB: String?): DateRangeSet {
// val rangeSet = DateRangeSet()
// if (serializedInDB == null || serializedInDB.isBlank()) return rangeSet
// try {
// serializedInDB
// .split("|")
// .dropLastWhile { it.isEmpty() }
// .mapTo(rangeSet) { toDateRange(it) }
// return rangeSet
// } catch (e: Throwable) {
// throw IllegalArgumentException("Time range is invalid: $serializedInDB", e)
// }
// }
//
// private fun toDateRange(serializedDateRange: String): DateRange {
// val split = serializedDateRange.split(RANGE_SIGN).dropLastWhile { it.isEmpty() }
// return DateRange(toDate(split[0]), toDate(split[1]))
// }
//
// private fun toDate(serializedDateRange: String): Date =
// SimpleDateFormat(DEFAULT_DATE_FORMAT).parse(serializedDateRange)
//
// private fun toLocalTimeRange(serializedTimeRange: String): LocalTimeRange {
// val split = serializedTimeRange.split(RANGE_SIGN).dropLastWhile { it.isEmpty() }
// return LocalTimeRange(toLocalTime(split[0]), toLocalTime(split[1]))
// }
//
// private fun toLocalTime(serializedDayTime: String): LocalTime {
// val split = serializedDayTime.split(":").dropLastWhile { it.isEmpty() }
// return LocalTime.of(split[0].toInt(), split[1].toInt())
// }
// }
//}
/**
* By default increment and decrement 1 day
*/
class PersianDateRangeSet @JvmOverloads constructor(
ranges: List<ClosedRange<PersianDate>> = emptyList(),
private val step: Period = Period.ofDays(1)
) : RangeSet<PersianDate>(), Serializable {
init {
addAll(ranges)
}
constructor(vararg ranges: PersianDateRange) : this(ranges.asList())
private constructor(rangeSet: PersianDateRangeSet) : this(rangeSet.toList())
override fun createRange(start: PersianDate, endInclusive: PersianDate): PersianDateRange = PersianDateRange(start, endInclusive)
override fun incrementValue(value: PersianDate): PersianDate = value + step
override fun decrementValue(value: PersianDate): PersianDate = value - step
override fun clone(): RangeSet<PersianDate> = PersianDateRangeSet(this)
override fun toString(): String = this.serializeForDB()
companion object {
@JvmStatic
fun of(serializedInDB: String?): PersianDateRangeSet {
val rangeSet = PersianDateRangeSet()
if (serializedInDB == null || serializedInDB.isBlank()) return rangeSet
try {
serializedInDB
.split("|")
.dropLastWhile { it.isEmpty() }
.mapTo(rangeSet) { toPersianDateRange(it) }
return rangeSet
} catch (e: Throwable) {
throw IllegalArgumentException("Date range set is invalid: $serializedInDB", e)
}
}
private fun toPersianDateRange(serializedTimeRange: String): PersianDateRange {
val split = serializedTimeRange.split(RANGE_SIGN).dropLastWhile { it.isEmpty() }
return PersianDateRange(toPersianDate(split[0]), toPersianDate(split[1]))
}
private fun toPersianDate(serializedDayTime: String): PersianDate {
return PersianDate.parse(serializedDayTime)
// val split = serializedDayTime.split("-").dropLastWhile { it.isEmpty() }
// return PersianDate.of(split[0].toInt(), split[1].toInt(), split[2].toInt())
}
}
}
/**
* By default increment and decrement 1 day
*/
class LocalDateRangeSet @JvmOverloads constructor(
ranges: List<ClosedRange<LocalDate>> = emptyList(),
private val step: Period = Period.ofDays(1)
) : RangeSet<LocalDate>(), Serializable {
init {
addAll(ranges)
}
constructor(vararg ranges: LocalDateRange) : this(ranges.asList())
private constructor(rangeSet: LocalDateRangeSet) : this(rangeSet.toList())
override fun createRange(start: LocalDate, endInclusive: LocalDate): LocalDateRange = LocalDateRange(start, endInclusive)
override fun incrementValue(value: LocalDate): LocalDate = value + step
override fun decrementValue(value: LocalDate): LocalDate = value - step
override fun clone(): RangeSet<LocalDate> = LocalDateRangeSet(this)
override fun toString(): String = this.serializeForDB()
companion object {
@JvmStatic
fun of(serializedInDB: String?): LocalDateRangeSet {
val rangeSet = LocalDateRangeSet()
if (serializedInDB == null || serializedInDB.isBlank()) return rangeSet
try {
serializedInDB
.split("|")
.dropLastWhile { it.isEmpty() }
.mapTo(rangeSet) { toLocalDateRange(it) }
return rangeSet
} catch (e: Throwable) {
throw IllegalArgumentException("Date range set is invalid: $serializedInDB", e)
}
}
private fun toLocalDateRange(serializedTimeRange: String): LocalDateRange {
val split = serializedTimeRange.split(RANGE_SIGN).dropLastWhile { it.isEmpty() }
return LocalDateRange(toLocalDate(split[0]), toLocalDate(split[1]))
}
private fun toLocalDate(serializedDayTime: String): LocalDate {
return LocalDate.parse(serializedDayTime)
// val split = serializedDayTime.split("-").dropLastWhile { it.isEmpty() }
// return LocalDate.of(split[0].toInt(), split[1].toInt(), split[2].toInt())
}
}
}
/**
* By default increment and decrement 5 minutes
*/
//@JsonDeserialize(using = LocalTimeRangeSetDeserializer::class)
class LocalTimeRangeSet @JvmOverloads constructor(
ranges: List<ClosedRange<LocalTime>> = emptyList(),
private val step: Duration = Duration.ofMinutes(5)
) : RangeSet<LocalTime>(), Serializable, IQ {
init {
this += ranges
}
constructor(vararg ranges: ClosedRange<LocalTime>) : this(ranges.asList())
private constructor(rangeSet: LocalTimeRangeSet) : this(rangeSet.toList())
override fun createRange(start: LocalTime, endInclusive: LocalTime): LocalTimeRange = LocalTimeRange(start, endInclusive)
override fun incrementValue(value: LocalTime): LocalTime = value + step
override fun decrementValue(value: LocalTime): LocalTime = value - step
override fun clone(): RangeSet<LocalTime> = LocalTimeRangeSet(this)
override fun toString(): String = this.serializeForDB()
// fun asDTO(): LocalTimeRangeSetDTO = LocalTimeRangeSetDTO(this)
companion object {
@JvmStatic
fun of(serializedInDB: String?): LocalTimeRangeSet {
val rangeSet = LocalTimeRangeSet()
if (serializedInDB == null || serializedInDB.isBlank()) return rangeSet
try {
serializedInDB
.split("|")
.dropLastWhile { it.isEmpty() }
.mapTo(rangeSet) { toLocalTimeRange(it) }
return rangeSet
} catch (e: Throwable) {
throw IllegalArgumentException("Time range set is invalid: $serializedInDB", e)
}
}
private fun toLocalTimeRange(serializedTimeRange: String): LocalTimeRange {
val split = serializedTimeRange.split(RANGE_SIGN).dropLastWhile { it.isEmpty() }
return LocalTimeRange(toLocalTime(split[0]), toLocalTime(split[1]))
}
private fun toLocalTime(serializedDayTime: String): LocalTime {
return LocalTime.parse(serializedDayTime)
// val split = serializedDayTime.split(":").dropLastWhile { it.isEmpty() }
// return LocalTime.of(split[0].toInt(), split[1].toInt())
}
}
}
| gpl-3.0 | a684be2b7d0c472efaeeacc875ddcc7e | 38.207843 | 133 | 0.631326 | 4.588343 | false | false | false | false |
infinum/android_dbinspector | dbinspector/src/main/kotlin/com/infinum/dbinspector/data/Data.kt | 1 | 7280 | package com.infinum.dbinspector.data
import android.content.Context
import androidx.datastore.core.DataStoreFactory
import androidx.datastore.core.Serializer
import com.infinum.dbinspector.data.Data.Constants.Name.PROTO_FILENAME_HISTORY
import com.infinum.dbinspector.data.Data.Constants.Name.PROTO_FILENAME_SETTINGS
import com.infinum.dbinspector.data.models.local.proto.output.HistoryEntity
import com.infinum.dbinspector.data.models.local.proto.output.SettingsEntity
import com.infinum.dbinspector.data.sources.local.cursor.PragmaSource
import com.infinum.dbinspector.data.sources.local.cursor.RawQuerySource
import com.infinum.dbinspector.data.sources.local.cursor.SchemaSource
import com.infinum.dbinspector.data.sources.local.proto.history.HistoryDataStore
import com.infinum.dbinspector.data.sources.local.proto.history.HistorySerializer
import com.infinum.dbinspector.data.sources.local.proto.settings.SettingsDataStore
import com.infinum.dbinspector.data.sources.local.proto.settings.SettingsSerializer
import com.infinum.dbinspector.data.sources.memory.connection.AndroidConnectionSource
import com.infinum.dbinspector.data.sources.memory.distance.LevenshteinDistance
import com.infinum.dbinspector.data.sources.memory.pagination.CursorPaginator
import com.infinum.dbinspector.data.sources.memory.pagination.Paginator
import com.infinum.dbinspector.data.sources.raw.AndroidDatabasesSource
import com.infinum.dbinspector.extensions.dataStoreFile
import org.koin.core.module.Module
import org.koin.core.qualifier.StringQualifier
import org.koin.dsl.module
internal object Data {
object Constants {
object Limits {
const val PAGE_SIZE = 100
const val INITIAL_PAGE = 1
}
object Settings {
const val LINES_LIMIT_MAXIMUM = 100
}
object Name {
const val PROTO_FILENAME_SETTINGS = "settings-entity.pb"
const val PROTO_FILENAME_HISTORY = "history-entity.pb"
}
}
object Qualifiers {
object Name {
val DATASTORE_SETTINGS = StringQualifier("data.qualifiers.name.datastore.settings")
val DATASTORE_HISTORY = StringQualifier("data.qualifiers.name.datastore.history")
}
object Schema {
val TABLES = StringQualifier("data.qualifiers.tables")
val TABLE_BY_NAME = StringQualifier("data.qualifiers.table_by_name")
val DROP_TABLE_CONTENT = StringQualifier("data.qualifiers.drop_table_content")
val VIEWS = StringQualifier("data.qualifiers.views")
val VIEW_BY_NAME = StringQualifier("data.qualifiers.view_by_name")
val DROP_VIEW = StringQualifier("data.qualifiers.drop_view")
val TRIGGERS = StringQualifier("data.qualifiers.triggers")
val TRIGGER_BY_NAME = StringQualifier("data.qualifiers.trigger_by_name")
val DROP_TRIGGER = StringQualifier("data.qualifiers.drop_trigger")
val RAW_QUERY = StringQualifier("data.qualifiers.raw_query")
}
object Pragma {
val TABLE_INFO = StringQualifier("data.qualifiers.table_info")
val FOREIGN_KEYS = StringQualifier("data.qualifiers.foreign_keys")
val INDEXES = StringQualifier("data.qualifiers.indexes")
}
}
fun modules(): List<Module> =
listOf(
raw(),
memory(),
local()
)
private fun raw() = module {
single<Sources.Raw> { AndroidDatabasesSource() }
}
private fun memory() = module {
factory<Paginator>(qualifier = Qualifiers.Schema.TABLES) { CursorPaginator() }
factory<Paginator>(qualifier = Qualifiers.Schema.TABLE_BY_NAME) { CursorPaginator() }
factory<Paginator>(qualifier = Qualifiers.Schema.DROP_TABLE_CONTENT) { CursorPaginator() }
factory<Paginator>(qualifier = Qualifiers.Schema.VIEWS) { CursorPaginator() }
factory<Paginator>(qualifier = Qualifiers.Schema.VIEW_BY_NAME) { CursorPaginator() }
factory<Paginator>(qualifier = Qualifiers.Schema.DROP_VIEW) { CursorPaginator() }
factory<Paginator>(qualifier = Qualifiers.Schema.TRIGGERS) { CursorPaginator() }
factory<Paginator>(qualifier = Qualifiers.Schema.TRIGGER_BY_NAME) { CursorPaginator() }
factory<Paginator>(qualifier = Qualifiers.Schema.DROP_TRIGGER) { CursorPaginator() }
factory<Paginator>(qualifier = Qualifiers.Pragma.TABLE_INFO) { CursorPaginator() }
factory<Paginator>(qualifier = Qualifiers.Pragma.FOREIGN_KEYS) { CursorPaginator() }
factory<Paginator>(qualifier = Qualifiers.Pragma.INDEXES) { CursorPaginator() }
factory<Paginator>(qualifier = Qualifiers.Schema.RAW_QUERY) { CursorPaginator() }
single<Sources.Memory.Connection> { AndroidConnectionSource() }
single<Sources.Memory.Distance> { LevenshteinDistance() }
}
private fun local() = module {
single(qualifier = Qualifiers.Name.DATASTORE_SETTINGS) { PROTO_FILENAME_SETTINGS }
single(qualifier = Qualifiers.Name.DATASTORE_HISTORY) { PROTO_FILENAME_HISTORY }
single<Serializer<SettingsEntity>>(qualifier = Qualifiers.Name.DATASTORE_SETTINGS) { SettingsSerializer() }
single<Serializer<HistoryEntity>>(qualifier = Qualifiers.Name.DATASTORE_HISTORY) { HistorySerializer() }
single<Sources.Local.Settings> {
val context: Context = get()
SettingsDataStore(
DataStoreFactory.create(
get(qualifier = Qualifiers.Name.DATASTORE_SETTINGS)
) {
context.dataStoreFile(get(qualifier = Qualifiers.Name.DATASTORE_SETTINGS))
}
)
}
single<Sources.Local.History> {
val context: Context = get()
HistoryDataStore(
DataStoreFactory.create(
get(qualifier = Qualifiers.Name.DATASTORE_HISTORY)
) {
context.dataStoreFile(get(qualifier = Qualifiers.Name.DATASTORE_HISTORY))
}
)
}
factory<Sources.Local.Schema> {
SchemaSource(
get(qualifier = Qualifiers.Schema.TABLES),
get(qualifier = Qualifiers.Schema.TABLE_BY_NAME),
get(qualifier = Qualifiers.Schema.DROP_TABLE_CONTENT),
get(qualifier = Qualifiers.Schema.VIEWS),
get(qualifier = Qualifiers.Schema.VIEW_BY_NAME),
get(qualifier = Qualifiers.Schema.DROP_VIEW),
get(qualifier = Qualifiers.Schema.TRIGGERS),
get(qualifier = Qualifiers.Schema.TRIGGER_BY_NAME),
get(qualifier = Qualifiers.Schema.DROP_TRIGGER),
get()
)
}
factory<Sources.Local.Pragma> {
PragmaSource(
get(qualifier = Qualifiers.Pragma.TABLE_INFO),
get(qualifier = Qualifiers.Pragma.FOREIGN_KEYS),
get(qualifier = Qualifiers.Pragma.INDEXES),
get()
)
}
factory<Sources.Local.RawQuery> {
RawQuerySource(
get(qualifier = Qualifiers.Schema.RAW_QUERY),
get()
)
}
}
}
| apache-2.0 | bc8e0afe983b2df102b907261bba5d22 | 41.573099 | 115 | 0.662912 | 4.572864 | false | false | false | false |
ankidroid/Anki-Android | AnkiDroid/src/main/java/com/ichi2/anki/MetaDB.kt | 1 | 21123 | //noinspection MissingCopyrightHeader #8659
package com.ichi2.anki
import android.content.Context
import android.database.Cursor
import android.database.sqlite.SQLiteDatabase
import android.database.sqlite.SQLiteException
import com.ichi2.anki.model.WhiteboardPenColor
import com.ichi2.anki.model.WhiteboardPenColor.Companion.default
import com.ichi2.libanki.DeckId
import com.ichi2.libanki.Sound.SoundSide
import com.ichi2.utils.KotlinCleanup
import timber.log.Timber
import java.lang.Exception
import java.lang.IllegalStateException
import java.util.regex.Pattern
/**
* Used to store additional information besides what is stored in the deck itself.
*
*
* Currently it used to store:
*
* * The languages associated with questions and answers.
* * The state of the whiteboard.
* * The cached state of the widget.
*
*/
@KotlinCleanup("see about lateinit")
@KotlinCleanup("IDE lint")
object MetaDB {
/** The name of the file storing the meta-db. */
private const val DATABASE_NAME = "ankidroid.db"
/** The Database Version, increase if you want updates to happen on next upgrade. */
private const val DATABASE_VERSION = 6
// Possible values for the qa column of the languages table.
/** The language refers to the question. */
const val LANGUAGES_QA_QUESTION = 0
/** The language refers to the answer. */
const val LANGUAGES_QA_ANSWER = 1
/** The language does not refer to either the question or answer. */
const val LANGUAGES_QA_UNDEFINED = 2
/** The pattern used to remove quotes from file names. */
private val quotePattern = Pattern.compile("[\"']")
/** The database object used by the meta-db. */
private var mMetaDb: SQLiteDatabase? = null
/** Remove any pairs of quotes from the given text. */
private fun stripQuotes(textParam: String): String {
var text = textParam
val matcher = quotePattern.matcher(text)
text = matcher.replaceAll("")
return text
}
/** Open the meta-db */
@KotlinCleanup("scope function or lateinit db")
private fun openDB(context: Context) {
try {
mMetaDb = context.openOrCreateDatabase(DATABASE_NAME, 0, null).let {
if (it.needUpgrade(DATABASE_VERSION))
upgradeDB(it, DATABASE_VERSION)
else
it
}
Timber.v("Opening MetaDB")
} catch (e: Exception) {
Timber.e(e, "Error opening MetaDB ")
}
}
/** Creating any table that missing and upgrading necessary tables. */
private fun upgradeDB(metaDb: SQLiteDatabase, databaseVersion: Int): SQLiteDatabase {
Timber.i("MetaDB:: Upgrading Internal Database..")
// if (mMetaDb.getVersion() == 0) {
Timber.i("MetaDB:: Applying changes for version: 0")
if (metaDb.version < 4) {
metaDb.execSQL("DROP TABLE IF EXISTS languages;")
metaDb.execSQL("DROP TABLE IF EXISTS whiteboardState;")
}
// Create tables if not exist
metaDb.execSQL(
"CREATE TABLE IF NOT EXISTS languages (" + " _id INTEGER PRIMARY KEY AUTOINCREMENT, " +
"did INTEGER NOT NULL, ord INTEGER, " + "qa INTEGER, " + "language TEXT)"
)
metaDb.execSQL(
"CREATE TABLE IF NOT EXISTS smallWidgetStatus (" + "id INTEGER PRIMARY KEY AUTOINCREMENT, " +
"due INTEGER NOT NULL, eta INTEGER NOT NULL)"
)
updateWidgetStatus(metaDb)
updateWhiteboardState(metaDb)
metaDb.version = databaseVersion
Timber.i("MetaDB:: Upgrading Internal Database finished. New version: %d", databaseVersion)
return metaDb
}
private fun updateWhiteboardState(metaDb: SQLiteDatabase) {
val columnCount = DatabaseUtil.getTableColumnCount(metaDb, "whiteboardState")
if (columnCount <= 0) {
metaDb.execSQL(
"CREATE TABLE IF NOT EXISTS whiteboardState (_id INTEGER PRIMARY KEY AUTOINCREMENT, " +
"did INTEGER NOT NULL, state INTEGER, visible INTEGER, lightpencolor INTEGER, darkpencolor INTEGER)"
)
return
}
if (columnCount < 4) {
// Default to 1
metaDb.execSQL("ALTER TABLE whiteboardState ADD COLUMN visible INTEGER NOT NULL DEFAULT '1'")
Timber.i("Added 'visible' column to whiteboardState")
}
if (columnCount < 5) {
metaDb.execSQL("ALTER TABLE whiteboardState ADD COLUMN lightpencolor INTEGER DEFAULT NULL")
Timber.i("Added 'lightpencolor' column to whiteboardState")
metaDb.execSQL("ALTER TABLE whiteboardState ADD COLUMN darkpencolor INTEGER DEFAULT NULL")
Timber.i("Added 'darkpencolor' column to whiteboardState")
}
}
private fun updateWidgetStatus(metaDb: SQLiteDatabase) {
val columnCount = DatabaseUtil.getTableColumnCount(metaDb, "widgetStatus")
if (columnCount > 0) {
if (columnCount < 7) {
metaDb.execSQL("ALTER TABLE widgetStatus " + "ADD COLUMN eta INTEGER NOT NULL DEFAULT '0'")
metaDb.execSQL("ALTER TABLE widgetStatus " + "ADD COLUMN time INTEGER NOT NULL DEFAULT '0'")
}
} else {
metaDb.execSQL(
"CREATE TABLE IF NOT EXISTS widgetStatus (" + "deckId INTEGER NOT NULL PRIMARY KEY, " +
"deckName TEXT NOT NULL, " + "newCards INTEGER NOT NULL, " + "lrnCards INTEGER NOT NULL, " +
"dueCards INTEGER NOT NULL, " + "progress INTEGER NOT NULL, " + "eta INTEGER NOT NULL)"
)
}
}
/** Open the meta-db but only if it currently closed. */
private fun openDBIfClosed(context: Context) {
if (!isDBOpen()) {
openDB(context)
}
}
/** Close the meta-db. */
fun closeDB() {
if (isDBOpen()) {
mMetaDb!!.close()
mMetaDb = null
Timber.d("Closing MetaDB")
}
}
/** Reset the content of the meta-db, erasing all its content. */
fun resetDB(context: Context): Boolean {
openDBIfClosed(context)
try {
mMetaDb!!.run {
execSQL("DROP TABLE IF EXISTS languages;")
Timber.i("MetaDB:: Resetting all language assignment")
execSQL("DROP TABLE IF EXISTS whiteboardState;")
Timber.i("MetaDB:: Resetting whiteboard state")
execSQL("DROP TABLE IF EXISTS widgetStatus;")
Timber.i("MetaDB:: Resetting widget status")
execSQL("DROP TABLE IF EXISTS smallWidgetStatus;")
Timber.i("MetaDB:: Resetting small widget status")
execSQL("DROP TABLE IF EXISTS intentInformation;")
Timber.i("MetaDB:: Resetting intentInformation")
upgradeDB(this, DATABASE_VERSION)
}
return true
} catch (e: Exception) {
Timber.e(e, "Error resetting MetaDB ")
}
return false
}
/** Reset the language associations for all the decks and card models. */
fun resetLanguages(context: Context): Boolean {
openDBIfClosed(context)
try {
Timber.i("MetaDB:: Resetting all language assignments")
mMetaDb!!.run {
execSQL("DROP TABLE IF EXISTS languages;")
upgradeDB(this, DATABASE_VERSION)
}
return true
} catch (e: Exception) {
Timber.e(e, "Error resetting MetaDB ")
}
return false
}
/** Reset the widget status. */
fun resetWidget(context: Context): Boolean {
openDBIfClosed(context)
try {
Timber.i("MetaDB:: Resetting widget status")
mMetaDb!!.run {
execSQL("DROP TABLE IF EXISTS widgetStatus;")
execSQL("DROP TABLE IF EXISTS smallWidgetStatus;")
upgradeDB(this, DATABASE_VERSION)
}
return true
} catch (e: Exception) {
Timber.e(e, "Error resetting widgetStatus and smallWidgetStatus")
}
return false
}
/**
* Associates a language to a deck, model, and card model for a given type.
*
* @param qa the part of the card for which to store the association, [.LANGUAGES_QA_QUESTION],
* [.LANGUAGES_QA_ANSWER], or [.LANGUAGES_QA_UNDEFINED]
* @param language the language to associate, as a two-characters, lowercase string
*/
fun storeLanguage(context: Context, did: DeckId, ord: Int, qa: SoundSide, language: String) {
openDBIfClosed(context)
try {
if ("" == getLanguage(context, did, ord, qa)) {
mMetaDb!!.execSQL(
"INSERT INTO languages (did, ord, qa, language) " + " VALUES (?, ?, ?, ?);",
arrayOf<Any>(
did, ord, qa.int, language
)
)
Timber.v("Store language for deck %d", did)
} else {
mMetaDb!!.execSQL(
"UPDATE languages SET language = ? WHERE did = ? AND ord = ? AND qa = ?;",
arrayOf<Any>(
language, did, ord, qa.int
)
)
Timber.v("Update language for deck %d", did)
}
} catch (e: Exception) {
Timber.e(e, "Error storing language in MetaDB ")
}
}
/**
* Returns the language associated with the given deck, model and card model, for the given type.
*
* @param qa the part of the card for which to store the association, [.LANGUAGES_QA_QUESTION],
* [.LANGUAGES_QA_ANSWER], or [.LANGUAGES_QA_UNDEFINED] return the language associate with
* the type, as a two-characters, lowercase string, or the empty string if no association is defined
*/
fun getLanguage(context: Context, did: DeckId, ord: Int, qa: SoundSide): String {
openDBIfClosed(context)
var language = ""
val query = "SELECT language FROM languages WHERE did = ? AND ord = ? AND qa = ? LIMIT 1"
try {
mMetaDb!!.rawQuery(
query,
arrayOf(
java.lang.Long.toString(did),
Integer.toString(ord),
Integer.toString(qa.int)
)
).use { cur ->
Timber.v("getLanguage: %s", query)
if (cur.moveToNext()) {
language = cur.getString(0)
}
}
} catch (e: Exception) {
Timber.e(e, "Error fetching language ")
}
return language
}
/**
* Resets all the language associates for a given deck.
*
* @return whether an error occurred while resetting the language for the deck
*/
fun resetDeckLanguages(context: Context, did: DeckId): Boolean {
openDBIfClosed(context)
try {
mMetaDb!!.execSQL("DELETE FROM languages WHERE did = ?;", arrayOf(did))
Timber.i("MetaDB:: Resetting language assignment for deck %d", did)
return true
} catch (e: Exception) {
Timber.e(e, "Error resetting deck language")
}
return false
}
/**
* Returns the state of the whiteboard for the given deck.
*
* @return 1 if the whiteboard should be shown, 0 otherwise
*/
fun getWhiteboardState(context: Context, did: DeckId): Boolean {
openDBIfClosed(context)
try {
mMetaDb!!.rawQuery(
"SELECT state FROM whiteboardState WHERE did = ?",
arrayOf(java.lang.Long.toString(did))
).use { cur -> return DatabaseUtil.getScalarBoolean(cur) }
} catch (e: Exception) {
Timber.e(e, "Error retrieving whiteboard state from MetaDB ")
return false
}
}
/**
* Stores the state of the whiteboard for a given deck.
*
* @param did deck id to store whiteboard state for
* @param whiteboardState 1 if the whiteboard should be shown, 0 otherwise
*/
fun storeWhiteboardState(context: Context, did: DeckId, whiteboardState: Boolean) {
val state = if (whiteboardState) 1 else 0
openDBIfClosed(context)
try {
val metaDb = mMetaDb!!
metaDb.rawQuery(
"SELECT _id FROM whiteboardState WHERE did = ?",
arrayOf(java.lang.Long.toString(did))
).use { cur ->
if (cur.moveToNext()) {
metaDb.execSQL(
"UPDATE whiteboardState SET did = ?, state=? WHERE _id=?;",
arrayOf<Any>(did, state, cur.getString(0))
)
Timber.d("Store whiteboard state (%d) for deck %d", state, did)
} else {
metaDb.execSQL(
"INSERT INTO whiteboardState (did, state) VALUES (?, ?)",
arrayOf<Any>(did, state)
)
Timber.d("Store whiteboard state (%d) for deck %d", state, did)
}
}
} catch (e: Exception) {
Timber.e(e, "Error storing whiteboard state in MetaDB ")
}
}
/**
* Returns the state of the whiteboard for the given deck.
*
* @return 1 if the whiteboard should be shown, 0 otherwise
*/
fun getWhiteboardVisibility(context: Context, did: DeckId): Boolean {
openDBIfClosed(context)
try {
mMetaDb!!.rawQuery(
"SELECT visible FROM whiteboardState WHERE did = ?",
arrayOf(java.lang.Long.toString(did))
).use { cur -> return DatabaseUtil.getScalarBoolean(cur) }
} catch (e: Exception) {
Timber.e(e, "Error retrieving whiteboard state from MetaDB ")
return false
}
}
/**
* Stores the state of the whiteboard for a given deck.
*
* @param did deck id to store whiteboard state for
* @param isVisible 1 if the whiteboard should be shown, 0 otherwise
*/
fun storeWhiteboardVisibility(context: Context, did: DeckId, isVisible: Boolean) {
val isVisibleState = if (isVisible) 1 else 0
openDBIfClosed(context)
try {
val metaDb = mMetaDb!!
metaDb.rawQuery(
"SELECT _id FROM whiteboardState WHERE did = ?",
arrayOf(java.lang.Long.toString(did))
).use { cur ->
if (cur.moveToNext()) {
metaDb.execSQL(
"UPDATE whiteboardState SET did = ?, visible= ? WHERE _id=?;",
arrayOf<Any>(did, isVisibleState, cur.getString(0))
)
Timber.d("Store whiteboard visibility (%d) for deck %d", isVisibleState, did)
} else {
metaDb.execSQL(
"INSERT INTO whiteboardState (did, visible) VALUES (?, ?)",
arrayOf<Any>(did, isVisibleState)
)
Timber.d("Store whiteboard visibility (%d) for deck %d", isVisibleState, did)
}
}
} catch (e: Exception) {
Timber.e(e, "Error storing whiteboard visibility in MetaDB ")
}
}
/**
* Returns the pen color of the whiteboard for the given deck.
*/
fun getWhiteboardPenColor(context: Context, did: DeckId): WhiteboardPenColor {
openDBIfClosed(context)
try {
mMetaDb!!.rawQuery(
"SELECT lightpencolor, darkpencolor FROM whiteboardState WHERE did = ?",
arrayOf(java.lang.Long.toString(did))
).use { cur ->
cur.moveToFirst()
val light = DatabaseUtil.getInteger(cur, 0)
val dark = DatabaseUtil.getInteger(cur, 1)
return WhiteboardPenColor(light, dark)
}
} catch (e: Exception) {
Timber.e(e, "Error retrieving whiteboard pen color from MetaDB ")
return default
}
}
/**
* Stores the pen color of the whiteboard for a given deck.
*
* @param did deck id to store whiteboard state for
* @param isLight if dark mode is disabled
* @param value The new color code to store
*/
fun storeWhiteboardPenColor(context: Context, did: DeckId, isLight: Boolean, value: Int?) {
openDBIfClosed(context)
val columnName = if (isLight) "lightpencolor" else "darkpencolor"
try {
val metaDb = mMetaDb!!
metaDb.rawQuery(
"SELECT _id FROM whiteboardState WHERE did = ?",
arrayOf(java.lang.Long.toString(did))
).use { cur ->
if (cur.moveToNext()) {
metaDb.execSQL(
"UPDATE whiteboardState SET did = ?, " +
columnName + "= ? " +
" WHERE _id=?;",
arrayOf<Any?>(did, value, cur.getString(0))
)
} else {
val sql = "INSERT INTO whiteboardState (did, $columnName) VALUES (?, ?)"
metaDb.execSQL(sql, arrayOf<Any?>(did, value))
}
Timber.d("Store whiteboard %s (%d) for deck %d", columnName, value, did)
}
} catch (e: Exception) {
Timber.w(e, "Error storing whiteboard color in MetaDB")
}
}
/**
* Return the current status of the widget.
*
* @return [due, eta]
*/
fun getWidgetSmallStatus(context: Context): IntArray {
openDBIfClosed(context)
var cursor: Cursor? = null
try {
cursor = mMetaDb!!.query(
"smallWidgetStatus", arrayOf("due", "eta"),
null, null, null, null, null
)
if (cursor.moveToNext()) {
return intArrayOf(cursor.getInt(0), cursor.getInt(1))
}
} catch (e: SQLiteException) {
Timber.e(e, "Error while querying widgetStatus")
} finally {
if (cursor != null && !cursor.isClosed) {
cursor.close()
}
}
return intArrayOf(0, 0)
}
fun getNotificationStatus(context: Context): Int {
openDBIfClosed(context)
var cursor: Cursor? = null
val due = 0
try {
cursor =
mMetaDb!!.query("smallWidgetStatus", arrayOf("due"), null, null, null, null, null)
if (cursor.moveToFirst()) {
return cursor.getInt(0)
}
} catch (e: SQLiteException) {
Timber.e(e, "Error while querying widgetStatus")
} finally {
if (cursor != null && !cursor.isClosed) {
cursor.close()
}
}
return due
}
fun storeSmallWidgetStatus(context: Context, status: Pair<Int, Int>) {
openDBIfClosed(context)
try {
val metaDb = mMetaDb!!
metaDb.beginTransaction()
try {
// First clear all the existing content.
metaDb.execSQL("DELETE FROM smallWidgetStatus")
metaDb.execSQL(
"INSERT INTO smallWidgetStatus(due, eta) VALUES (?, ?)",
arrayOf<Any>(status.first, status.second)
)
metaDb.setTransactionSuccessful()
} finally {
metaDb.endTransaction()
}
} catch (e: IllegalStateException) {
Timber.e(e, "MetaDB.storeSmallWidgetStatus: failed")
} catch (e: SQLiteException) {
Timber.e(e, "MetaDB.storeSmallWidgetStatus: failed")
closeDB()
Timber.i("MetaDB:: Trying to reset Widget: %b", resetWidget(context))
}
}
fun close() {
mMetaDb?.run {
try {
close()
} catch (e: Exception) {
Timber.w(e, "Failed to close MetaDB")
}
}
}
private object DatabaseUtil {
fun getScalarBoolean(cur: Cursor): Boolean {
return if (cur.moveToNext()) {
cur.getInt(0) > 0
} else {
false
}
}
// API LEVEL
fun getTableColumnCount(metaDb: SQLiteDatabase, tableName: String): Int {
var c: Cursor? = null
return try {
c = metaDb.rawQuery("PRAGMA table_info($tableName)", null)
c.count
} finally {
c?.close()
}
}
fun getInteger(cur: Cursor, columnIndex: Int): Int? {
return if (cur.isNull(columnIndex)) null else cur.getInt(columnIndex)
}
}
private fun isDBOpen() = mMetaDb?.isOpen == true
}
| gpl-3.0 | 2b929ecc004055ea1599b0926ab1508e | 36.719643 | 120 | 0.550159 | 4.561218 | false | false | false | false |
mixitconf/mixit | src/main/kotlin/mixit/util/cache/AbstractCacheService.kt | 1 | 2280 | package mixit.util.cache
import com.github.benmanes.caffeine.cache.Cache
import com.github.benmanes.caffeine.cache.Caffeine
import kotlinx.coroutines.reactor.awaitSingle
import kotlinx.coroutines.reactor.awaitSingleOrNull
import reactor.cache.CacheMono
import reactor.core.publisher.Mono
import reactor.core.publisher.Signal
import java.time.Instant
import java.util.concurrent.TimeUnit
import java.util.concurrent.atomic.AtomicReference
interface Cached {
val id: String
}
enum class CacheZone { EVENT, BLOG, TALK, USER, TICKET }
/**
* All element exposed to user (event, talk, speaker) are put in a cache. For
* each entity we have a cache for the current year data (this cache is reloaded each hour or manually).
* For old data and the old editions, cache is populated on startup or manually refreshed if necessary
*/
abstract class CacheTemplate<T : Cached> {
abstract val cacheZone: CacheZone
val refreshInstant = AtomicReference<Instant?>()
val cache: Cache<String, List<T>> by lazy {
Caffeine
.newBuilder()
.expireAfterWrite(1, TimeUnit.DAYS)
.maximumSize(5_000)
.build()
}
/**
* Cache is initialized on startup
*/
fun initializeCache() {
refreshInstant.set(Instant.now())
findAll().block()
}
fun findOne(id: String): Mono<T> =
findAll().flatMap { elements -> Mono.justOrEmpty(elements.firstOrNull { it.id == id }) }
suspend fun coFindOne(id: String): T =
findOne(id).awaitSingle()
suspend fun coFindOneOrNull(id: String): T? =
findOne(id).awaitSingleOrNull()
fun findAll(loader: () -> Mono<List<T>>): Mono<List<T>> =
CacheMono
.lookup({ k -> Mono.justOrEmpty(cache.getIfPresent(k)).map { Signal.next(it) } }, "global")
.onCacheMissResume {
loader.invoke()
}
.andWriteWith { key, signal ->
Mono.fromRunnable {
cache.put(key, signal.get()!!)
}
}
fun isEmpty(): Boolean =
cache.asMap().entries.isEmpty()
abstract fun findAll(): Mono<List<T>>
fun invalidateCache() {
cache.invalidateAll()
refreshInstant.set(Instant.now())
}
}
| apache-2.0 | 26870000b0355d05b2fbe537a15c9220 | 28.61039 | 104 | 0.641228 | 4.261682 | false | false | false | false |
ankidroid/Anki-Android | AnkiDroid/src/androidTest/java/com/ichi2/ui/ActionBarOverflowTest.kt | 1 | 3167 | /*
* Copyright (c) 2020 David Allison <[email protected]>
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free Software
* Foundation; either version 3 of the License, or (at your option) any later
* version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
* PARTICULAR PURPOSE. See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.ichi2.ui
import android.content.Context
import android.view.MenuItem
import androidx.appcompat.view.menu.MenuBuilder
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.platform.app.InstrumentationRegistry
import org.hamcrest.MatcherAssert.assertThat
import org.hamcrest.Matchers.equalTo
import org.hamcrest.Matchers.notNullValue
import org.junit.Assert.fail
import org.junit.Test
import org.junit.runner.RunWith
import java.lang.reflect.InvocationTargetException
@RunWith(AndroidJUnit4::class)
class ActionBarOverflowTest {
@Test
fun hasValidActionBarReflectionMethod() {
assertThat(
"Ensures that there is a valid way to obtain a listener",
ActionBarOverflow.hasUsableMethod(), equalTo(true)
)
}
@Test
fun errorsAreBeingThrownCanary() {
try {
ActionBarOverflow.setupMethods(ActionBarOverflow::getPrivateMethodOnlyHandleExceptions)
} catch (e: Error) {
fail(
"""
See discussion on #5806
https://developer.android.com/distribute/best-practices/develop/restrictions-non-sdk-interfaces
Once this throws, errors are being thrown on a currently greylisted method
""".trimIndent()
)
}
}
@Test
fun testAndroidXMenuItem() {
val targetContext = InstrumentationRegistry.getInstrumentation().targetContext
val b = MenuBuilder(targetContext)
val i = b.add("Test")
val value = ActionBarOverflow.isActionButton(i)
assertThat(value, notNullValue())
}
@Test
@Throws(
ClassNotFoundException::class,
InstantiationException::class,
IllegalAccessException::class,
NoSuchMethodException::class,
InvocationTargetException::class
)
fun testAndroidMenuItem() {
val targetContext = InstrumentationRegistry.getInstrumentation().targetContext
val clazz = "com.android.internal.view.menu.MenuBuilder"
val c = Class.forName(clazz)
val constructor = c.getConstructor(Context::class.java)
val mmb = constructor.newInstance(targetContext)
val add = mmb.javaClass.getMethod("add", CharSequence::class.java)
add.isAccessible = true
val mi = add.invoke(mmb, "Add") as MenuItem
val value = ActionBarOverflow.isActionButton(mi)
assertThat(value, notNullValue())
}
}
| gpl-3.0 | 9d30bc91873a4cd89394125ab9593c11 | 32.691489 | 99 | 0.703505 | 4.636896 | false | true | false | false |
matkoniecz/StreetComplete | app/src/main/java/de/westnordost/streetcomplete/data/elementfilter/filters/HasTagGreaterOrEqualThan.kt | 2 | 273 | package de.westnordost.streetcomplete.data.elementfilter.filters
/** key >= value */
class HasTagGreaterOrEqualThan(key: String, value: Float): CompareTagValue(key, value) {
override val operator = ">="
override fun compareTo(tagValue: Float) = tagValue >= value
} | gpl-3.0 | 3f2f25f8e52cc546439b9e7df835211d | 38.142857 | 88 | 0.739927 | 4.333333 | false | false | false | false |
sabi0/intellij-community | platform/testGuiFramework/src/com/intellij/testGuiFramework/fixtures/extended/ExtendedJTreePathFixture.kt | 1 | 6029 | // Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.testGuiFramework.fixtures.extended
import com.intellij.openapi.externalSystem.service.execution.NotSupportedException
import com.intellij.testGuiFramework.driver.ExtendedJTreeDriver
import com.intellij.testGuiFramework.driver.ExtendedJTreePathFinder
import com.intellij.testGuiFramework.framework.Timeouts
import com.intellij.testGuiFramework.util.FinderPredicate
import com.intellij.testGuiFramework.impl.GuiRobotHolder
import com.intellij.testGuiFramework.impl.GuiTestUtilKt
import com.intellij.testGuiFramework.util.Predicate
import org.fest.swing.core.MouseButton
import org.fest.swing.core.MouseClickInfo
import org.fest.swing.core.Robot
import org.fest.swing.exception.LocationUnavailableException
import org.fest.swing.fixture.JTreeFixture
import javax.swing.JTree
import javax.swing.tree.TreePath
open class ExtendedJTreePathFixture(
val tree: JTree,
private val stringPath: List<String>,
private val predicate: FinderPredicate = Predicate.equality,
robot: Robot = GuiRobotHolder.robot,
private val myDriver: ExtendedJTreeDriver = ExtendedJTreeDriver(robot)
) : JTreeFixture(robot, tree) {
constructor(
tree: JTree,
path: TreePath,
predicate: FinderPredicate = Predicate.equality,
robot: Robot = GuiRobotHolder.robot,
driver: ExtendedJTreeDriver = ExtendedJTreeDriver(robot)
) :
this(tree, path.getPathStrings(), predicate, robot, driver)
init {
replaceDriverWith(myDriver)
}
private val cachePaths = mutableMapOf<List<String>, TreePath>()
protected val path: TreePath
get() {
return if (!cachePaths.containsKey(stringPath))
expandAndGetPathStepByStep(stringPath)
else
cachePaths.getValue(stringPath)
}
/**
* Create a new object of ExtendedJTreePathFixture for a new path
* It's supposed the new path in the same tree
* @param pathStrings full new path
* @throws LocationUnavailableException if path not found
* */
fun path(vararg pathStrings: String): ExtendedJTreePathFixture {
return ExtendedJTreePathFixture(tree, pathStrings.toList(), predicate, robot(), myDriver)
}
/**
* Create a new object of ExtendedJTreePathFixture for a path
* containing a specified [node]
* It's supposed the new path in the same tree
* @param node one node value somewhere whithin the same tree
* @throws LocationUnavailableException if node not found
* */
fun pathToNode(node: String): ExtendedJTreePathFixture{
val newPath = myDriver.findPathToNode(tree, node, predicate)
return ExtendedJTreePathFixture(tree, newPath, predicate, robot(), myDriver)
}
fun hasPath(): Boolean {
return try {
path
true
}
catch (e: Exception) {
false
}
}
fun clickPath(mouseClickInfo: MouseClickInfo): Unit =
myDriver.clickPath(tree, path, mouseClickInfo.button(), mouseClickInfo.times())
fun clickPath(): Unit = myDriver.clickPath(tree, path, MouseButton.LEFT_BUTTON, 1)
fun doubleClickPath(): Unit = myDriver.clickPath(tree, path, MouseButton.LEFT_BUTTON, 2)
fun rightClickPath(): Unit = myDriver.clickPath(tree, path, MouseButton.RIGHT_BUTTON, 1)
fun expandPath() {
myDriver.expandPath(tree, path)
}
protected fun expandAndGetPathStepByStep(stringPath: List<String>): TreePath {
fun <T> List<T>.list2tree() = map { subList(0, indexOf(it) + 1) }
if (!cachePaths.containsKey(stringPath)){
var partialPath: TreePath? = null
for (partialList in stringPath.list2tree()) {
GuiTestUtilKt.waitUntil(condition = "correct path to click is found", timeout = Timeouts.seconds02) {
try {
partialPath = ExtendedJTreePathFinder(tree)
.findMatchingPathByPredicate(predicate = predicate, pathStrings = *partialList.toTypedArray())
partialPath != null
}
catch (e: Exception) {
false
}
}
cachePaths[partialList] = partialPath!!
myDriver.expandPath(tree, cachePaths.getValue(partialList))
}
}
return cachePaths.getValue(stringPath)
}
fun collapsePath(): Unit = myDriver.collapsePath(tree, path)
////////////////////////////////////////////////////////////////
// Overridden functions
override fun clickPath(path: String): ExtendedJTreePathFixture {
val tree = this.path(path)
tree.clickPath()
return tree
}
override fun clickPath(path: String, mouseClickInfo: MouseClickInfo): JTreeFixture {
val tree = this.path(path)
tree.clickPath(mouseClickInfo)
return tree
}
override fun clickPath(path: String, button: MouseButton): ExtendedJTreePathFixture {
val tree = this.path(path)
when(button){
MouseButton.LEFT_BUTTON -> tree.clickPath()
MouseButton.MIDDLE_BUTTON -> throw NotSupportedException("Middle mouse click not supported")
MouseButton.RIGHT_BUTTON -> tree.rightClickPath()
}
return tree
}
override fun doubleClickPath(path: String): ExtendedJTreePathFixture {
val tree = this.path(path)
tree.doubleClickPath()
return tree
}
override fun rightClickPath(path: String): ExtendedJTreePathFixture {
val tree = this.path(path)
tree.rightClickPath()
return tree
}
override fun expandPath(path: String): ExtendedJTreePathFixture {
val tree = this.path(path)
tree.expandPath()
return tree
}
override fun collapsePath(path: String): ExtendedJTreePathFixture {
val tree = this.path(path)
tree.collapsePath()
return tree
}
}
/**
* Returns list of visible strings not including the first invisible item
*
* Note: code `this.path.joinToString()` always includes the first invisible item
* */
fun TreePath.getPathStrings(): List<String> {
val pathStrings = this.path.map { it.toString() }
return if (pathStrings.first().isEmpty()) pathStrings.drop(1) else pathStrings
}
| apache-2.0 | 0419f6982663c70df0f87a85ac3f884d | 32.870787 | 142 | 0.714712 | 4.353069 | false | true | false | false |
devmil/PaperLaunch | app/src/main/java/de/devmil/paperlaunch/view/utils/ColorUtils.kt | 1 | 2034 | /*
* Copyright 2015 Devmil Solutions
*
* 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 de.devmil.paperlaunch.view.utils
import android.graphics.Bitmap
import android.graphics.Color
import android.graphics.drawable.Drawable
import android.support.v7.graphics.Palette
import de.devmil.paperlaunch.utils.BitmapUtils
object ColorUtils {
fun getBackgroundColorFromImage(bitmap: Bitmap, defaultColor: Int): Int {
val p = Palette.from(bitmap).generate()
return getColorFromPalette(p, defaultColor)
}
fun getBackgroundColorFromImage(drawable: Drawable, defaultColor: Int): Int {
val bmpResult = BitmapUtils.drawableToBitmap(drawable)
if (bmpResult == null) {
return defaultColor
}
val p = Palette.from(bmpResult.bitmap).generate()
if (bmpResult.isNew) {
bmpResult.bitmap.recycle()
}
return getColorFromPalette(p, defaultColor)
}
private fun getColorFromPalette(palette: Palette, defaultColor: Int): Int {
var result = palette.getLightMutedColor(Color.BLACK)
if (result == Color.BLACK) {
result = palette.getLightVibrantColor(Color.BLACK)
}
if (result == Color.BLACK) {
result = palette.getMutedColor(Color.BLACK)
}
if (result == Color.BLACK) {
result = palette.getVibrantColor(Color.BLACK)
}
if (result == Color.BLACK) {
result = defaultColor
}
return result
}
}
| apache-2.0 | adf5575c9ac27dd3f2d3e9c3b4be2555 | 30.78125 | 81 | 0.674533 | 4.393089 | false | false | false | false |
sabi0/intellij-community | platform/build-scripts/icons/src/org/jetbrains/intellij/build/images/sync/reportUtils.kt | 1 | 4339 | // 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.intellij.build.images.sync
import org.apache.http.client.methods.HttpGet
import org.apache.http.client.methods.HttpPost
import org.apache.http.entity.StringEntity
import org.apache.http.impl.client.HttpClients
import org.apache.http.util.EntityUtils
import java.net.URLEncoder
import java.text.SimpleDateFormat
import java.util.*
import java.util.function.Consumer
internal fun report(
devIcons: Int, icons: Int, skipped: Int,
addedByDev: Collection<String>, removedByDev: Collection<String>,
modifiedByDev: Collection<String>, addedByDesigners: Collection<String>,
removedByDesigners: Collection<String>, modifiedByDesigners: Collection<String>,
consistent: Collection<String>, errorHandler: Consumer<String>, doNotify: Boolean
) {
log("Skipped $skipped dirs")
fun Collection<String>.logIcons() = if (size < 100) joinToString() else size.toString()
log("""
|dev repo:
| added: ${addedByDev.logIcons()}
| removed: ${removedByDev.logIcons()}
| modified: ${modifiedByDev.logIcons()}
|icons repo:
| added: ${addedByDesigners.logIcons()}
| removed: ${removedByDesigners.logIcons()}
| modified: ${modifiedByDesigners.logIcons()}
""".trimMargin())
val report = """
|$devIcons icons are found in dev repo:
| ${addedByDev.size} added
| ${removedByDev.size} removed
| ${modifiedByDev.size} modified
|$icons icons are found in icons repo:
| ${addedByDesigners.size} added
| ${removedByDesigners.size} removed
| ${modifiedByDesigners.size} modified
|${consistent.size} consistent icons in both repos
""".trimMargin()
log(report)
if (doNotify) {
val success = addedByDev.isEmpty() && removedByDev.isEmpty() && modifiedByDev.isEmpty()
sendNotification(success)
if (!success) errorHandler.accept(report)
}
}
private fun sendNotification(isSuccess: Boolean) {
if (BUILD_SERVER == null) {
log("TeamCity url is unknown: unable to query last build status and send Slack channel notification")
}
else {
callSafely {
if (isNotificationRequired(isSuccess)) {
notifySlackChannel(isSuccess)
}
}
}
}
private val BUILD_SERVER = System.getProperty("teamcity.serverUrl")
private val BUILD_CONF = System.getProperty("teamcity.buildType.id")
private val DATE_FORMAT = SimpleDateFormat("yyyyMMdd'T'HHmmsszzz")
private fun isNotificationRequired(isSuccess: Boolean) =
HttpClients.createDefault().use {
val request = "$BUILD_SERVER/guestAuth/app/rest/builds?locator=buildType:$BUILD_CONF,count:1"
if (isSuccess) {
val get = HttpGet(request)
val previousBuild = EntityUtils.toString(it.execute(get).entity, Charsets.UTF_8)
// notify on fail -> success
previousBuild.contains("status=\"FAILURE\"")
}
else {
val dayAgo = DATE_FORMAT.format(Calendar.getInstance().let {
it.add(Calendar.HOUR, -12)
it.time
})
val get = HttpGet("$request,sinceDate:${URLEncoder.encode(dayAgo, "UTF-8")}")
val previousBuild = EntityUtils.toString(it.execute(get).entity, Charsets.UTF_8)
// remind of failure once per day
previousBuild.contains("count=\"0\"")
}
}
private val CHANNEL_WEB_HOOK = System.getProperty("intellij.icons.slack.channel")
private val BUILD_ID = System.getProperty("teamcity.build.id")
private val INTELLIJ_ICONS_SYNC_RUN_CONF = System.getProperty("intellij.icons.sync.run.conf")
private fun notifySlackChannel(isSuccess: Boolean) {
HttpClients.createDefault().use {
val text = "*${System.getProperty("teamcity.buildConfName")}* " +
(if (isSuccess) ":white_check_mark:" else ":scream:") + "\n" +
(if (!isSuccess) "Use 'Icons processing/*$INTELLIJ_ICONS_SYNC_RUN_CONF*' IDEA Ultimate run configuration\n" else "") +
"<$BUILD_SERVER/viewLog.html?buildId=$BUILD_ID&buildTypeId=$BUILD_CONF|See build log>"
val post = HttpPost(CHANNEL_WEB_HOOK)
post.entity = StringEntity("""{ "text": "$text" }""", Charsets.UTF_8)
val response = EntityUtils.toString(it.execute(post).entity, Charsets.UTF_8)
if (response != "ok") throw IllegalStateException("$CHANNEL_WEB_HOOK responded with $response")
}
} | apache-2.0 | 61184241031632dbee65f5d167aafa97 | 40.333333 | 140 | 0.705232 | 3.887993 | false | false | false | false |
Ruben-Sten/TeXiFy-IDEA | src/nl/hannahsten/texifyidea/structure/latex/LatexLabelPresentation.kt | 1 | 1682 | package nl.hannahsten.texifyidea.structure.latex
import com.intellij.navigation.ItemPresentation
import com.intellij.openapi.fileEditor.FileDocumentManager
import nl.hannahsten.texifyidea.TexifyIcons
import nl.hannahsten.texifyidea.lang.alias.CommandManager
import nl.hannahsten.texifyidea.psi.LatexCommands
import nl.hannahsten.texifyidea.util.labels.getLabelDefinitionCommands
import nl.hannahsten.texifyidea.util.requiredParameter
/**
* @author Hannah Schellekens
*/
class LatexLabelPresentation(labelCommand: LatexCommands) : ItemPresentation {
private val locationString: String
private val presentableText: String
init {
val labelingCommands = getLabelDefinitionCommands()
if (!labelingCommands.contains(labelCommand.commandToken.text)) {
val token = labelCommand.commandToken.text
throw IllegalArgumentException("command '$token' is no \\label-command")
}
val position =
CommandManager.labelAliasesInfo.getOrDefault(labelCommand.commandToken.text, null)?.positions?.firstOrNull()
?: 0
presentableText = labelCommand.requiredParameter(position) ?: "no label found"
// Location string.
val manager = FileDocumentManager.getInstance()
val document = manager.getDocument(labelCommand.containingFile.virtualFile)
val line = document!!.getLineNumber(labelCommand.textOffset) + 1
this.locationString = labelCommand.containingFile.name + ":" + line
}
override fun getPresentableText() = presentableText
override fun getLocationString() = locationString
override fun getIcon(b: Boolean) = TexifyIcons.DOT_LABEL
}
| mit | aa67eb88d2631d37035ea98d816bb44f | 38.116279 | 120 | 0.747919 | 5.239875 | false | false | false | false |
Ruben-Sten/TeXiFy-IDEA | src/nl/hannahsten/texifyidea/run/latex/externaltool/ExternalToolRunConfiguration.kt | 1 | 3548 | package nl.hannahsten.texifyidea.run.latex.externaltool
import com.intellij.execution.Executor
import com.intellij.execution.configurations.*
import com.intellij.execution.runners.ExecutionEnvironment
import com.intellij.openapi.options.SettingsEditor
import com.intellij.openapi.project.Project
import com.intellij.openapi.vfs.LocalFileSystem
import com.intellij.openapi.vfs.VirtualFile
import nl.hannahsten.texifyidea.run.compiler.ExternalTool
import org.jdom.Element
import java.util.*
/**
* Run configuration for running an [nl.hannahsten.texifyidea.run.compiler.ExternalTool].
*/
class ExternalToolRunConfiguration(
project: Project,
factory: ConfigurationFactory,
name: String
) : RunConfigurationBase<ExternalToolCommandLineState>(project, factory, name), LocatableConfiguration {
companion object {
private const val PARENT_ELEMENT = "texify-external"
private const val PROGRAM = "program"
private const val MAIN_FILE = "main-file"
private const val WORK_DIR = "work-dir"
}
// The following variables are saved in the SettingsEditor
var program = ExternalTool.PYTHONTEX
var mainFile: VirtualFile? = null
var workingDirectory: VirtualFile? = null
override fun getState(executor: Executor, environment: ExecutionEnvironment): RunProfileState {
return ExternalToolCommandLineState(environment, mainFile, workingDirectory, this.program)
}
override fun getConfigurationEditor(): SettingsEditor<out RunConfiguration> = ExternalToolSettingsEditor(project)
override fun readExternal(element: Element) {
super<LocatableConfiguration>.readExternal(element)
val parent = element.getChild(PARENT_ELEMENT)
try {
val programText = parent.getChildText(PROGRAM)
if (!programText.isNullOrEmpty()) {
this.program = ExternalTool.valueOf(programText)
}
}
catch (ignored: NullPointerException) {}
val mainFilePath = try {
parent.getChildText(MAIN_FILE)
}
catch (e: NullPointerException) {
null
}
mainFile = if (!mainFilePath.isNullOrBlank()) {
LocalFileSystem.getInstance().findFileByPath(mainFilePath)
}
else {
null
}
val workDirPath = try {
parent.getChildText(WORK_DIR)
}
catch (e: NullPointerException) {
null
}
workingDirectory = if (!workDirPath.isNullOrBlank()) {
LocalFileSystem.getInstance().findFileByPath(workDirPath)
}
else {
null
}
}
override fun writeExternal(element: Element) {
super<LocatableConfiguration>.writeExternal(element)
val parent = element.getChild(PARENT_ELEMENT) ?: Element(PARENT_ELEMENT).apply { element.addContent(this) }
parent.removeContent()
parent.addContent(Element(PROGRAM).apply { text = [email protected] })
parent.addContent(Element(MAIN_FILE).apply { text = mainFile?.path ?: "" })
parent.addContent(Element(WORK_DIR).apply { text = workingDirectory?.path ?: "" })
}
override fun isGeneratedName() = name == suggestedName()
override fun suggestedName(): String {
val main = if (mainFile != null) mainFile?.nameWithoutExtension + " " else ""
return main + this.program.name.lowercase(Locale.getDefault())
}
fun setSuggestedName() {
name = suggestedName()
}
} | mit | e24cda317ff6199286ea23e83a043d40 | 33.456311 | 117 | 0.678974 | 5.032624 | false | true | false | false |
pagecloud/fitcloud-bot | src/main/kotlin/com/pagecloud/slack/Logging.kt | 1 | 1819 | package com.pagecloud.slack
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import kotlin.reflect.KClass
import kotlin.reflect.full.companionObject
// Return logger for Java class, if companion object fix the name
public fun <T: Any> logger(forClass: Class<T>): Logger {
return LoggerFactory.getLogger(unwrapCompanionClass(forClass).name)
}
// unwrap companion class to enclosing class given a Java Class
public fun <T: Any> unwrapCompanionClass(ofClass: Class<T>): Class<*> {
return if (ofClass.enclosingClass != null && ofClass.enclosingClass.kotlin.companionObject?.java == ofClass) {
ofClass.enclosingClass
} else {
ofClass
}
}
// unwrap companion class to enclosing class given a Kotlin Class
public fun <T: Any> unwrapCompanionClass(ofClass: KClass<T>): KClass<*> {
return unwrapCompanionClass(ofClass.java).kotlin
}
// Return logger for Kotlin class
public fun <T: Any> logger(forClass: KClass<T>): Logger {
return logger(forClass.java)
}
// return logger from extended class (or the enclosing class)
public fun <T: Any> T.logger(): Logger {
return logger(this.javaClass)
}
// return a lazy logger property delegate for enclosing class
public fun <R : Any> R.lazyLogger(): Lazy<Logger> {
return lazy { logger(this.javaClass) }
}
// return a logger property delegate for enclosing class
public fun <R : Any> R.injectLogger(): Lazy<Logger> {
return lazyOf(logger(this.javaClass))
}
// marker interface and related extension (remove extension for Any.logger() in favour of this)
interface Loggable {}
public fun Loggable.logger(): Logger = logger(this.javaClass)
// abstract base class to provide logging, intended for companion objects more than classes but works for either
public abstract class WithLogging: Loggable {
val log = logger()
} | unlicense | 7fa8b5983a472c57b7b2674f978f4161 | 32.703704 | 114 | 0.742166 | 4.015453 | false | false | false | false |
mopsalarm/Pr0 | app/src/main/java/com/pr0gramm/app/util/BrowserHelper.kt | 1 | 7174 | package com.pr0gramm.app.util
import android.content.Context
import android.content.Intent
import android.net.Uri
import androidx.browser.customtabs.CustomTabColorSchemeParams
import androidx.browser.customtabs.CustomTabsIntent
import androidx.browser.customtabs.CustomTabsService
import androidx.core.content.ContextCompat
import com.pr0gramm.app.Logger
import com.pr0gramm.app.R
import com.pr0gramm.app.Settings
import com.pr0gramm.app.api.pr0gramm.Api
import com.pr0gramm.app.services.ThemeHelper
import com.pr0gramm.app.services.Track
import com.pr0gramm.app.services.UserService
import com.pr0gramm.app.ui.base.BaseAppCompatActivity
import com.pr0gramm.app.ui.base.launchWhenStarted
import com.pr0gramm.app.ui.fragments.withBusyDialog
import com.pr0gramm.app.ui.showDialog
import com.pr0gramm.app.util.di.injector
import java.util.*
/**
*/
object BrowserHelper {
private val logger = Logger("BrowserHelper")
private const val CHROME_STABLE_PACKAGE = "com.android.chrome"
private const val CHROME_BETA_PACKAGE = "com.chrome.beta"
private const val CHROME_DEV_PACKAGE = "com.chrome.dev"
private const val CHROME_LOCAL_PACKAGE = "com.google.android.apps.chrome"
private val FIREFOX_URI = Uri.parse("https://play.google.com/store/apps/details?id=org.mozilla.klar&hl=en")
private val chromeTabPackageName by memorize<Context, String?> { context ->
try {
val activityIntent = Intent(Intent.ACTION_VIEW, Uri.parse("https://www.example.com"))
val pm = context.packageManager
val packagesSupportingCustomTabs = ArrayList<String>()
for (info in pm.queryIntentActivities(activityIntent, 0)) {
val serviceIntent = Intent()
serviceIntent.action = CustomTabsService.ACTION_CUSTOM_TABS_CONNECTION
serviceIntent.`package` = info.activityInfo.packageName
if (pm.resolveService(serviceIntent, 0) != null) {
packagesSupportingCustomTabs.add(info.activityInfo.packageName)
}
}
return@memorize when {
packagesSupportingCustomTabs.contains(CHROME_STABLE_PACKAGE) -> CHROME_STABLE_PACKAGE
packagesSupportingCustomTabs.contains(CHROME_BETA_PACKAGE) -> CHROME_BETA_PACKAGE
packagesSupportingCustomTabs.contains(CHROME_DEV_PACKAGE) -> CHROME_DEV_PACKAGE
packagesSupportingCustomTabs.contains(CHROME_LOCAL_PACKAGE) -> CHROME_LOCAL_PACKAGE
packagesSupportingCustomTabs.size == 1 -> packagesSupportingCustomTabs[0]
else -> null
}
} catch (err: Exception) {
null
}
}
private fun firefoxFocusPackage(context: Context): String? {
return listOf("org.mozilla.klar", "org.mozilla.focus").firstOrNull { packageName ->
val intent = Intent(Intent.ACTION_VIEW, Uri.parse("http://www.example.com"))
intent.`package` = packageName
context.packageManager.queryIntentActivities(intent, 0).size > 0
}
}
fun open(context: Context, url: String) {
if (context.injector.instance<Settings>().useIncognitoBrowser) {
openIncognito(context, url)
} else {
openCustomTab(context, Uri.parse(url))
}
}
/**
* Try to open the url in a firefox focus window.
* This one will never attempt to do session handover.
*/
fun openIncognito(context: Context, url: String) {
val uri = Uri.parse(url)
// if the firefox focus is installed, we'll open the page in this browser.
firefoxFocusPackage(context)?.let { packageName ->
val intent = Intent(Intent.ACTION_VIEW, uri)
intent.`package` = packageName
context.startActivity(intent)
Track.openBrowser("FirefoxFocus")
return
}
showDialog(context) {
content(R.string.hint_use_firefox_focus)
positive(R.string.play_store) {
it.dismiss()
openCustomTab(context, FIREFOX_URI)
Track.gotoFirefoxFocusWebsite()
}
negative(R.string.cancel) {
it.dismiss()
}
}
}
fun openCustomTab(context: Context, uri: Uri, handover: Boolean = true) {
val themedContext = AndroidUtility.activityFromContext(context) ?: context
fun open(block: (Uri) -> Unit) {
if (handover) {
runWithHandoverToken(context, uri) { uriWithHandoverToken ->
block(uriWithHandoverToken)
}
} else {
block(uri)
}
}
// get the chrome package to use
val packageName = chromeTabPackageName(context)
if (packageName == null) {
Track.openBrowser("External")
open { context.startActivity(Intent(Intent.ACTION_VIEW, it)) }
return
}
val customTabsIntent = CustomTabsIntent.Builder()
.setUrlBarHidingEnabled(true)
.setShareState(CustomTabsIntent.SHARE_STATE_DEFAULT)
.setDefaultColorSchemeParams(
CustomTabColorSchemeParams.Builder()
.setToolbarColor(ContextCompat.getColor(themedContext, ThemeHelper.theme.primaryColor))
.setSecondaryToolbarColor(ContextCompat.getColor(themedContext, ThemeHelper.theme.primaryColorDark))
.build()
)
.build()
customTabsIntent.intent.`package` = packageName
open { customTabsIntent.launchUrl(context, it) }
Track.openBrowser("CustomTabs")
}
private fun runWithHandoverToken(context: Context, uri: Uri, block: (Uri) -> Unit) {
// we need an activity to do the request and to show the 'busy dialog'
val activity = AndroidUtility.activityFromContext(context)
// we only want to do handover for pr0gramm urls
val externalUri = uri.host?.lowercase() != "pr0gramm.com"
// the user needs to be signed in for handover to make sense
val userService = context.injector.instance<UserService>()
val notAuthorized = !userService.isAuthorized
if (activity !is BaseAppCompatActivity || externalUri || notAuthorized) {
block(uri)
return
}
val api = context.injector.instance<Api>()
activity.launchWhenStarted {
block(try {
val response = withBusyDialog(activity) {
api.handoverToken(null)
}
Uri.parse("https://pr0gramm.com/api/user/handoverlogin").buildUpon()
.appendQueryParameter("path", (uri.path ?: "/") + "?" + (uri.query ?: ""))
.appendQueryParameter("token", response.token)
.build()
} catch (err: Exception) {
logger.warn(err) { "Error getting handover token" }
return@launchWhenStarted
})
}
}
} | mit | 28b3d8dd411b38feeadf81dafd81c34e | 37.164894 | 132 | 0.620574 | 4.604621 | false | false | false | false |
ykrank/S1-Next | app/src/main/java/me/ykrank/s1next/view/adapter/delegate/ThreadAdapterDelegate.kt | 1 | 2282 | package me.ykrank.s1next.view.adapter.delegate
import android.content.Context
import android.view.ViewGroup
import androidx.databinding.DataBindingUtil
import com.github.ykrank.androidtools.ui.adapter.simple.SimpleRecycleViewHolder
import me.ykrank.s1next.App
import me.ykrank.s1next.R
import me.ykrank.s1next.data.api.model.Thread
import me.ykrank.s1next.data.pref.ReadPreferencesManager
import me.ykrank.s1next.data.pref.ThemeManager
import me.ykrank.s1next.databinding.ItemThreadBinding
import me.ykrank.s1next.viewmodel.ThreadViewModel
import me.ykrank.s1next.viewmodel.UserViewModel
import javax.inject.Inject
class ThreadAdapterDelegate(context: Context, private val forumId: String) :
BaseAdapterDelegate<Thread, SimpleRecycleViewHolder<ItemThreadBinding>>(context, Thread::class.java) {
@Inject
internal lateinit var mUserViewModel: UserViewModel
@Inject
internal lateinit var mThemeManager: ThemeManager
@Inject
internal lateinit var mReadPreferencesManager: ReadPreferencesManager
init {
App.appComponent.inject(this)
}
public override fun onCreateViewHolder(parent: ViewGroup): androidx.recyclerview.widget.RecyclerView.ViewHolder {
val binding = DataBindingUtil.inflate<ItemThreadBinding>(mLayoutInflater, R.layout.item_thread,
parent, false)
// we do not use view model for ThemeManager
// because theme changes only when Activity recreated
binding.userViewModel = mUserViewModel
binding.themeManager = mThemeManager
binding.forumId = forumId
binding.model = ThreadViewModel()
val threadPadding = mReadPreferencesManager.threadPadding
if (threadPadding != null && threadPadding > 0) {
val paddingPx = threadPadding * parent.context.resources.displayMetrics.scaledDensity.toInt()
binding.tvThread.setPadding(binding.tvThread.paddingLeft, paddingPx, binding.tvThread.paddingLeft, paddingPx)
}
return SimpleRecycleViewHolder<ItemThreadBinding>(binding)
}
override fun onBindViewHolderData(t: Thread, position: Int, holder: SimpleRecycleViewHolder<ItemThreadBinding>, payloads: List<Any>) {
val binding = holder.binding
binding.model?.thread?.set(t)
}
}
| apache-2.0 | 427536f0d35857c05ad03d3f335fc531 | 39.035088 | 138 | 0.759422 | 4.564 | false | false | false | false |
asamm/locus-api | locus-api-android/src/main/java/locus/api/android/ActionFiles.kt | 1 | 6221 | package locus.api.android
import android.app.Activity
import android.content.ActivityNotFoundException
import android.content.Context
import android.content.Intent
import android.net.Uri
import locus.api.android.objects.LocusVersion
import locus.api.android.utils.LocusConst
import locus.api.android.utils.LocusUtils
import locus.api.utils.Logger
import java.io.File
@Suppress("unused")
object ActionFiles {
// tag for logger
private const val TAG = "ActionFiles"
//*************************************************
// SENDING FILE TO SYSTEM/LOCUS
//*************************************************
/**
* Generic call to the system. All applications that are capable of handling of certain file should
* be offered to user.
*
* @param ctx current context
* @param fileUri file we wants to share
*/
fun importFileSystem(ctx: Context, fileUri: Uri, type: String): Boolean {
// send Intent
ctx.startActivity(Intent(Intent.ACTION_VIEW).apply {
setDataAndType(fileUri, type)
addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
})
return true
}
/**
* Import GPX/KML files directly into Locus application.
*
* @param ctx current context
* @param lv instance of target Locus app
* @param fileUri file we wants to share
* @param callImport `true` to start import, otherwise content is just displayed on the map
* @return `false` if file don't exist or Locus is not installed
*/
@JvmOverloads
fun importFileLocus(ctx: Context, fileUri: Uri, type: String,
lv: LocusVersion? = LocusUtils.getActiveVersion(ctx),
callImport: Boolean = true): Boolean {
// check requirements
if (lv == null) {
Logger.logE(TAG, "importFileLocus(" + ctx + ", " + lv + ", " + fileUri + ", " + callImport + "), " +
"invalid input parameters. Import cannot be performed!")
return false
}
// send request
ctx.startActivity(Intent(Intent.ACTION_VIEW).apply {
setPackage(lv.packageName)
setDataAndType(fileUri, type)
addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
putExtra(LocusConst.INTENT_EXTRA_CALL_IMPORT, callImport)
})
return true
}
/**
* Get mime type for certain file. This method created simplified version of mime-type just
* based on file extension.
*
* @param file we work with
* @return generated mime-type
*/
fun getMimeType(file: File): String {
val name = file.name
val index = name.lastIndexOf(".")
return if (index == -1) {
"*/*"
} else "application/" + name.substring(index + 1)
}
//*************************************************
// FILE PICKER
//*************************************************
/**
* Allows to call activity for File pick. You can use Locus picker for this purpose, but
* check if Locus version 231 and above are installed **isLocusAvailable(context, 231)**!
*
* Call use generic `org.openintents.action.PICK_FILE` call, so not just Locus Map may respond
* on this intent.
*
* Since Android 4.4, write access to received content is disabled, so use this method for
* read-only access.
*
* For read-write access, use since Android 5 available `ACTION_OPEN_DOCUMENT_TREE` feature.
*
* @param activity starting activity that also receive result
* @param requestCode request code
* @param title title visible in header of picker
* @param filter optional file filter, list of supported endings
* @throws ActivityNotFoundException thrown in case of missing required Locus app
*/
@JvmOverloads
@Throws(ActivityNotFoundException::class)
fun actionPickFile(activity: Activity, requestCode: Int,
title: String? = null, filter: Array<String>? = null) {
intentPick("org.openintents.action.PICK_FILE",
activity, requestCode, title, filter)
}
/**
* Allows to call activity for Directory pick. You can use Locus picker for this purpose, but
* check if Locus version 231 and above are installed **isLocusAvailable(context, 231)**!
*
* Call use generic `org.openintents.action.PICK_DIRECTORY` call, so not just Locus Map may
* respond on this intent.
*
* Since Android 4.4, write access to received content is disabled, so use this method for
* read-only access.
*
* For read-write access, use since Android 5 available `ACTION_OPEN_DOCUMENT_TREE` feature.
*
* @param activity starting activity that also receive result
* @param requestCode request code
* @param title title visible in header of picker
* @throws ActivityNotFoundException thrown in case of missing required Locus app
*/
@JvmOverloads
@Throws(ActivityNotFoundException::class)
fun actionPickDir(activity: Activity, requestCode: Int, title: String? = null) {
intentPick("org.openintents.action.PICK_DIRECTORY",
activity, requestCode, title, null)
}
/**
* Execute pick of files/directories.
*
* @param action action to start
* @param act starting activity that also receive result
* @param requestCode request code
* @param title title visible in header of picker
* @param filter optional file filter, list of supported endings
* @throws ActivityNotFoundException thrown in case of missing required Locus app
*/
@Throws(ActivityNotFoundException::class)
private fun intentPick(action: String, act: Activity, requestCode: Int,
title: String?, filter: Array<String>?) {
// create intent
val intent = Intent(action)
if (title != null && title.isNotEmpty()) {
intent.putExtra("org.openintents.extra.TITLE", title)
}
if (filter != null && filter.isNotEmpty()) {
intent.putExtra("org.openintents.extra.FILTER", filter)
}
// execute request
act.startActivityForResult(intent, requestCode)
}
}
| mit | 0595072ec540b50504f76bc3e8947016 | 36.932927 | 112 | 0.627713 | 4.62872 | false | false | false | false |
misaochan/apps-android-commons | app/src/main/java/fr/free/nrw/commons/category/ContinuationClient.kt | 2 | 1400 | package fr.free.nrw.commons.category
import io.reactivex.Single
abstract class ContinuationClient<Network, Domain> {
private val continuationStore: MutableMap<String, Map<String, String>?> = mutableMapOf()
private val continuationExists: MutableMap<String, Boolean> = mutableMapOf()
private fun hasMorePagesFor(key: String) = continuationExists[key] ?: true
fun continuationRequest(
prefix: String,
name: String,
requestFunction: (Map<String, String>) -> Single<Network>
): Single<List<Domain>> {
val key = "$prefix$name"
return if (hasMorePagesFor(key)) {
responseMapper(requestFunction(continuationStore[key] ?: emptyMap()), key)
} else {
Single.just(emptyList())
}
}
abstract fun responseMapper(networkResult: Single<Network>, key: String?=null): Single<List<Domain>>
fun handleContinuationResponse(continuation:Map<String,String>?, key:String?){
if (key != null) {
continuationExists[key] =
continuation?.let { continuation ->
continuationStore[key] = continuation
true
} ?: false
}
}
protected fun resetContinuation(prefix: String, category: String) {
continuationExists.remove("$prefix$category")
continuationStore.remove("$prefix$category")
}
}
| apache-2.0 | fd87f7234ce1978ed0eecfec7dd2a89a | 33.146341 | 104 | 0.636429 | 4.682274 | false | false | false | false |
schaal/ocreader | app/src/main/java/email/schaal/ocreader/LoginFlowActivity.kt | 1 | 4037 | /*
* Copyright © 2020. Daniel Schaal <[email protected]>
*
* This file is part of ocreader.
*
* ocreader 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.
*
* ocreader 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 Foobar. If not, see <http://www.gnu.org/licenses/>.
*/
package email.schaal.ocreader
import android.app.Activity
import android.content.Intent
import android.net.Uri
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import androidx.activity.viewModels
import androidx.databinding.DataBindingUtil
import androidx.lifecycle.Observer
import androidx.lifecycle.lifecycleScope
import email.schaal.ocreader.api.API
import email.schaal.ocreader.databinding.LoginFlowActivityBinding
import email.schaal.ocreader.ui.loginflow.LoginFlowFragment
import email.schaal.ocreader.util.LoginError
import email.schaal.ocreader.util.buildBaseUrl
import email.schaal.ocreader.view.LoginViewModel
import kotlinx.coroutines.launch
import okhttp3.HttpUrl.Companion.toHttpUrlOrNull
class LoginFlowActivity : AppCompatActivity() {
private val loginViewModel: LoginViewModel by viewModels()
companion object {
const val EXTRA_URL = "email.schaal.ocreader.extra.url"
const val EXTRA_IMPROPERLY_CONFIGURED_CRON = "email.schaal.ocreader.extra.improperlyConfiguredCron"
const val EXTRA_MESSAGE = "email.schaal.ocreader.extra.message"
}
private lateinit var binding: LoginFlowActivityBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = DataBindingUtil.setContentView(this, R.layout.login_flow_activity)
setSupportActionBar(binding.toolbarLayout.toolbar)
supportActionBar?.title = getString(R.string.title_activity_login)
loginViewModel.credentialsLiveData.observe(this, Observer {
val server = it?.get("server")?.let { urlString ->
if(!urlString.endsWith("/")) "$urlString/" else urlString }?.toHttpUrlOrNull()
val user = it?.get("user")
val password = it?.get("password")
if (server != null && user != null && password != null) {
lifecycleScope.launch {
try {
API.login(this@LoginFlowActivity, server, user, password)?.let {status ->
setResult(Activity.RESULT_OK,
Intent(Intent.ACTION_VIEW, Uri.parse(server.buildBaseUrl("index.php/apps/news").toString()))
.putExtra(EXTRA_IMPROPERLY_CONFIGURED_CRON, status.isImproperlyConfiguredCron))
} ?: setResult(Activity.RESULT_CANCELED)
} catch(e: Exception) {
e.printStackTrace()
setResult(Activity.RESULT_CANCELED, Intent().apply {
putExtra(EXTRA_MESSAGE, LoginError.getError(this@LoginFlowActivity, e).message)
})
} finally {
finish()
}
}
} else {
setResult(Activity.RESULT_CANCELED, Intent().apply {
putExtra(EXTRA_MESSAGE, "Couldn't parse response from server")
})
}
})
if (savedInstanceState == null) {
supportFragmentManager.beginTransaction()
.replace(R.id.container, LoginFlowFragment.newInstance(intent.extras?.getString(EXTRA_URL)))
.commitNow()
}
}
}
| gpl-3.0 | af6717c8c746f186062973913243de9c | 42.869565 | 128 | 0.652874 | 4.833533 | false | false | false | false |
TeamAmaze/AmazeFileManager | app/src/main/java/com/amaze/filemanager/ui/dialogs/SftpConnectDialog.kt | 1 | 31215 | /*
* Copyright (C) 2014-2021 Arpit Khurana <[email protected]>, Vishal Nehra <[email protected]>,
* Emmanuel Messulam<[email protected]>, Raymond Lai <airwave209gt at gmail.com> and Contributors.
*
* This file is part of Amaze File Manager.
*
* Amaze File Manager is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.amaze.filemanager.ui.dialogs
import android.app.Activity
import android.app.AlertDialog
import android.app.Dialog
import android.content.Context
import android.content.DialogInterface
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.text.Editable
import android.text.TextUtils
import android.text.TextWatcher
import android.view.LayoutInflater
import android.view.View
import android.widget.AdapterView
import android.widget.ArrayAdapter
import androidx.activity.result.contract.ActivityResultContracts
import androidx.core.text.isDigitsOnly
import androidx.fragment.app.DialogFragment
import com.afollestad.materialdialogs.DialogAction
import com.afollestad.materialdialogs.MaterialDialog
import com.afollestad.materialdialogs.internal.MDButton
import com.amaze.filemanager.R
import com.amaze.filemanager.application.AppConfig
import com.amaze.filemanager.asynchronous.asynctasks.ftp.AbstractGetHostInfoTask
import com.amaze.filemanager.asynchronous.asynctasks.ftp.hostcert.FtpsGetHostCertificateTask
import com.amaze.filemanager.asynchronous.asynctasks.ssh.GetSshHostFingerprintTask
import com.amaze.filemanager.asynchronous.asynctasks.ssh.PemToKeyPairTask
import com.amaze.filemanager.database.UtilsHandler
import com.amaze.filemanager.database.models.OperationData
import com.amaze.filemanager.databinding.SftpDialogBinding
import com.amaze.filemanager.fileoperations.filesystem.OpenMode
import com.amaze.filemanager.filesystem.ftp.NetCopyClientConnectionPool
import com.amaze.filemanager.filesystem.ftp.NetCopyClientConnectionPool.FTPS_URI_PREFIX
import com.amaze.filemanager.filesystem.ftp.NetCopyClientConnectionPool.FTP_URI_PREFIX
import com.amaze.filemanager.filesystem.ftp.NetCopyClientConnectionPool.SSH_URI_PREFIX
import com.amaze.filemanager.filesystem.ftp.NetCopyClientUtils
import com.amaze.filemanager.ui.activities.MainActivity
import com.amaze.filemanager.ui.activities.superclasses.ThemedActivity
import com.amaze.filemanager.ui.icons.MimeTypes
import com.amaze.filemanager.ui.provider.UtilitiesProvider
import com.amaze.filemanager.utils.BookSorter
import com.amaze.filemanager.utils.DataUtils
import com.amaze.filemanager.utils.MinMaxInputFilter
import com.amaze.filemanager.utils.SimpleTextWatcher
import com.amaze.filemanager.utils.X509CertificateUtil.FINGERPRINT
import com.google.android.material.snackbar.Snackbar
import io.reactivex.Single
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import net.schmizz.sshj.common.SecurityUtils
import org.json.JSONObject
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import java.io.BufferedReader
import java.lang.ref.WeakReference
import java.security.KeyPair
import java.security.PublicKey
import java.util.*
import java.util.concurrent.Callable
/** SSH/SFTP connection setup dialog. */
class SftpConnectDialog : DialogFragment() {
companion object {
@JvmStatic
private val log: Logger = LoggerFactory.getLogger(SftpConnectDialog::class.java)
const val ARG_NAME = "name"
const val ARG_EDIT = "edit"
const val ARG_ADDRESS = "address"
const val ARG_PORT = "port"
const val ARG_PROTOCOL = "protocol"
const val ARG_USERNAME = "username"
const val ARG_PASSWORD = "password"
const val ARG_DEFAULT_PATH = "defaultPath"
const val ARG_HAS_PASSWORD = "hasPassword"
const val ARG_KEYPAIR_NAME = "keypairName"
private val VALID_PORT_RANGE = IntRange(1, 65535)
}
lateinit var ctx: WeakReference<Context>
private var selectedPem: Uri? = null
private var selectedParsedKeyPair: KeyPair? = null
private var selectedParsedKeyPairName: String? = null
private var oldPath: String? = null
lateinit var binding: SftpDialogBinding
@Suppress("ComplexMethod")
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
ctx = WeakReference(activity)
binding = SftpDialogBinding.inflate(LayoutInflater.from(context))
val utilsProvider: UtilitiesProvider = AppConfig.getInstance().utilsProvider
val edit = requireArguments().getBoolean(ARG_EDIT, false)
initForm(edit)
val accentColor = (activity as ThemedActivity).accent
// Use system provided action to get Uri to PEM.
binding.selectPemBTN.setOnClickListener {
val intent = Intent()
.setType(MimeTypes.ALL_MIME_TYPES)
.setAction(Intent.ACTION_GET_CONTENT)
activityResultHandlerForPemSelection.launch(intent)
}
// Define action for buttons
val dialogBuilder = MaterialDialog.Builder(ctx.get()!!)
.title(R.string.scp_connection)
.autoDismiss(false)
.customView(binding.root, true)
.theme(utilsProvider.appTheme.getMaterialDialogTheme(context))
.negativeText(R.string.cancel)
.positiveText(if (edit) R.string.update else R.string.create)
.positiveColor(accentColor)
.negativeColor(accentColor)
.neutralColor(accentColor)
.onPositive(handleOnPositiveButton(edit))
.onNegative { dialog: MaterialDialog, _: DialogAction? ->
dialog.dismiss()
}
// If we are editing connection settings, give new actions for neutral and negative buttons
if (edit) {
appendButtonListenersForEdit(dialogBuilder)
}
val dialog = dialogBuilder.build()
// Some validations to make sure the Create/Update button is clickable only when required
// setting values are given
val okBTN: MDButton = dialog.getActionButton(DialogAction.POSITIVE)
if (!edit) okBTN.isEnabled = false
val validator: TextWatcher = createValidator(edit, okBTN)
binding.ipET.addTextChangedListener(validator)
binding.portET.addTextChangedListener(validator)
binding.usernameET.addTextChangedListener(validator)
binding.passwordET.addTextChangedListener(validator)
return dialog
}
private fun initForm(edit: Boolean) = binding.run {
portET.apply {
filters = arrayOf(MinMaxInputFilter(VALID_PORT_RANGE))
// For convenience, so I don't need to press backspace all the time
onFocusChangeListener = View.OnFocusChangeListener { _: View?, hasFocus: Boolean ->
if (hasFocus) {
selectAll()
}
}
}
protocolDropDown.adapter = ArrayAdapter(
requireContext(),
android.R.layout.simple_spinner_dropdown_item,
requireContext().resources.getStringArray(R.array.ftpProtocols)
)
chkFtpAnonymous.setOnCheckedChangeListener { _, isChecked ->
usernameET.isEnabled = !isChecked
passwordET.isEnabled = !isChecked
if (isChecked) {
usernameET.setText("")
passwordET.setText("")
}
}
// If it's new connection setup, set some default values
// Otherwise, use given Bundle instance for filling in the blanks
if (!edit) {
connectionET.setText(R.string.scp_connection)
portET.setText(NetCopyClientConnectionPool.SSH_DEFAULT_PORT.toString())
protocolDropDown.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
override fun onItemSelected(
parent: AdapterView<*>?,
view: View?,
position: Int,
id: Long
) {
portET.setText(
when (position) {
1 -> NetCopyClientConnectionPool.FTP_DEFAULT_PORT.toString()
2 -> NetCopyClientConnectionPool.FTPS_DEFAULT_PORT.toString()
else -> NetCopyClientConnectionPool.SSH_DEFAULT_PORT.toString()
}
)
chkFtpAnonymous.visibility = when (position) {
0 -> View.GONE
else -> View.VISIBLE
}
if (position == 0) {
chkFtpAnonymous.isChecked = false
}
selectPemBTN.visibility = when (position) {
0 -> View.VISIBLE
else -> View.GONE
}
}
override fun onNothingSelected(parent: AdapterView<*>?) = Unit
}
} else {
protocolDropDown.setSelection(
when (requireArguments().getString(ARG_PROTOCOL)) {
FTP_URI_PREFIX -> 1
FTPS_URI_PREFIX -> 2
else -> 0
}
)
connectionET.setText(requireArguments().getString(ARG_NAME))
ipET.setText(requireArguments().getString(ARG_ADDRESS))
portET.setText(requireArguments().getInt(ARG_PORT).toString())
defaultPathET.setText(requireArguments().getString(ARG_DEFAULT_PATH))
usernameET.setText(requireArguments().getString(ARG_USERNAME))
if (requireArguments().getBoolean(ARG_HAS_PASSWORD)) {
passwordET.setHint(R.string.password_unchanged)
} else {
selectedParsedKeyPairName = requireArguments().getString(ARG_KEYPAIR_NAME)
selectPemBTN.text = selectedParsedKeyPairName
}
oldPath = NetCopyClientUtils.encryptFtpPathAsNecessary(
NetCopyClientUtils.deriveUriFrom(
requireArguments().getString(ARG_PROTOCOL)!!,
requireArguments().getString(ARG_ADDRESS)!!,
requireArguments().getInt(ARG_PORT),
requireArguments().getString(ARG_DEFAULT_PATH, ""),
requireArguments().getString(ARG_USERNAME)!!,
requireArguments().getString(ARG_PASSWORD),
selectedParsedKeyPair
)
)
}
}
private fun appendButtonListenersForEdit(
dialogBuilder: MaterialDialog.Builder
) {
createConnectionSettings().run {
dialogBuilder
.negativeText(R.string.delete)
.onNegative { dialog: MaterialDialog, _: DialogAction? ->
val path = NetCopyClientUtils.encryptFtpPathAsNecessary(
NetCopyClientUtils.deriveUriFrom(
getProtocolPrefixFromDropdownSelection(),
hostname,
port,
defaultPath,
username,
requireArguments().getString(ARG_PASSWORD, null),
selectedParsedKeyPair
)
)
val i = DataUtils.getInstance().containsServer(
arrayOf(connectionName, path)
)
if (i > -1) {
DataUtils.getInstance().removeServer(i)
AppConfig.getInstance()
.runInBackground {
AppConfig.getInstance().utilsHandler.removeFromDatabase(
OperationData(
UtilsHandler.Operation.SFTP,
path,
connectionName,
null,
null,
null
)
)
}
(activity as MainActivity).drawer.refreshDrawer()
}
dialog.dismiss()
}.neutralText(R.string.cancel)
.onNeutral { dialog: MaterialDialog, _: DialogAction? -> dialog.dismiss() }
}
}
private fun createValidator(edit: Boolean, okBTN: MDButton): SimpleTextWatcher {
return object : SimpleTextWatcher() {
override fun afterTextChanged(s: Editable) {
val portETValue = binding.portET.text.toString()
val port = if (portETValue.isDigitsOnly() && (portETValue.length in 1..5)) {
portETValue.toInt()
} else {
-1
}
val hasCredential: Boolean = if (edit) {
if (true == binding.passwordET.text?.isNotEmpty() ||
!TextUtils.isEmpty(requireArguments().getString(ARG_PASSWORD))
) {
true
} else {
true == selectedParsedKeyPairName?.isNotEmpty()
}
} else {
true == binding.passwordET.text?.isNotEmpty() || selectedParsedKeyPair != null
}
okBTN.isEnabled = (
true == binding.connectionET.text?.isNotEmpty() &&
true == binding.ipET.text?.isNotEmpty() &&
port in VALID_PORT_RANGE &&
true == binding.usernameET.text?.isNotEmpty() &&
hasCredential
) || (
binding.chkFtpAnonymous.isChecked &&
binding.protocolDropDown.selectedItemPosition > 0
)
}
}
}
private fun handleOnPositiveButton(edit: Boolean):
MaterialDialog.SingleButtonCallback =
MaterialDialog.SingleButtonCallback { _, _ ->
createConnectionSettings().run {
when (prefix) {
FTP_URI_PREFIX -> positiveButtonForFtp(this, edit)
else -> positiveButtonForSftp(this, edit)
}
}
}
private fun positiveButtonForFtp(connectionSettings: ConnectionSettings, edit: Boolean) {
connectionSettings.run {
authenticateAndSaveSetup(connectionSettings = connectionSettings, isEdit = edit)
}
}
/*
* for SSH and FTPS, get host's cert/public key fingerprint.
*/
private fun positiveButtonForSftp(connectionSettings: ConnectionSettings, edit: Boolean) {
connectionSettings.run {
// Get original SSH host key
AppConfig.getInstance().utilsHandler.getRemoteHostKey(
NetCopyClientUtils.deriveUriFrom(
prefix,
hostname,
port,
defaultPath,
username,
arguments?.getString(ARG_PASSWORD, null),
selectedParsedKeyPair
)
)?.let { sshHostKey ->
NetCopyClientConnectionPool.removeConnection(
this.toUriString()
) {
if (prefix == FTPS_URI_PREFIX) {
reconnectToFtpsServerToVerifyHostFingerprint(
this,
JSONObject(sshHostKey),
edit
)
} else {
reconnectToSshServerToVerifyHostFingerprint(this, sshHostKey, edit)
}
}
} ?: run {
if (prefix == FTPS_URI_PREFIX) {
firstConnectToFtpsServer(this, edit)
} else {
firstConnectToSftpServer(this, edit)
}
}
}
}
/*
* Used by firstConnectToFtpsServer() and firstConnectToSftpServer().
*/
private val createFirstConnectCallback:
(Boolean, ConnectionSettings, String, String, String, JSONObject?) -> Unit = {
edit,
connectionSettings,
hostAndPort,
hostKeyAlgorithm,
hostKeyFingerprint,
hostInfo ->
AlertDialog.Builder(ctx.get())
.setTitle(R.string.ssh_host_key_verification_prompt_title)
.setMessage(
getString(
R.string.ssh_host_key_verification_prompt,
hostAndPort,
hostKeyAlgorithm,
hostKeyFingerprint
)
).setCancelable(true)
.setPositiveButton(R.string.yes) {
dialog1: DialogInterface, _: Int ->
// This closes the host fingerprint verification dialog
dialog1.dismiss()
if (authenticateAndSaveSetup(
connectionSettings,
hostInfo?.toString() ?: hostKeyFingerprint,
edit
)
) {
dialog1.dismiss()
log.debug("Saved setup")
dismiss()
}
}.setNegativeButton(R.string.no) {
dialog1: DialogInterface, _: Int ->
dialog1.dismiss()
}.show()
}
private fun firstConnectToFtpsServer(
connectionSettings: ConnectionSettings,
edit: Boolean
) = connectionSettings.run {
connectToSecureServerInternal(
FtpsGetHostCertificateTask(
hostname,
port,
requireContext()
) { hostInfo ->
createFirstConnectCallback.invoke(
edit,
this,
StringBuilder(hostname).also {
if (port != NetCopyClientConnectionPool.FTPS_DEFAULT_PORT && port > 0) {
it.append(':').append(port)
}
}.toString(),
"SHA-256",
hostInfo.getString(FINGERPRINT),
hostInfo
)
}
)
}
private fun firstConnectToSftpServer(
connectionSettings: ConnectionSettings,
edit: Boolean
) = connectionSettings.run {
connectToSecureServerInternal(
GetSshHostFingerprintTask(
hostname,
port,
true
) { hostKey: PublicKey ->
createFirstConnectCallback.invoke(
edit,
this,
StringBuilder(hostname).also {
if (port != NetCopyClientConnectionPool.SSH_DEFAULT_PORT && port > 0) {
it.append(':').append(port)
}
}.toString(),
hostKey.algorithm,
SecurityUtils.getFingerprint(hostKey),
null
)
}
)
}
private val createReconnectSecureServerCallback:
(ConnectionSettings, String, String, () -> Boolean, Boolean) -> Unit = {
connectionSettings, oldHostIdentity, newHostIdentity, hostIdentityIsValid, edit ->
if (hostIdentityIsValid.invoke()) {
authenticateAndSaveSetup(
connectionSettings,
oldHostIdentity,
edit
)
} else {
AlertDialog.Builder(ctx.get())
.setTitle(
R.string.ssh_connect_failed_host_key_changed_title
).setMessage(
R.string.ssh_connect_failed_host_key_changed_prompt
).setPositiveButton(
R.string.update_host_key
) { _: DialogInterface?, _: Int ->
authenticateAndSaveSetup(
connectionSettings,
newHostIdentity,
edit
)
}.setNegativeButton(R.string.cancel_recommended) {
dialog1: DialogInterface, _: Int ->
dialog1.dismiss()
}.show()
}
}
private fun reconnectToSshServerToVerifyHostFingerprint(
connectionSettings: ConnectionSettings,
sshHostKey: String,
edit: Boolean
) {
connectionSettings.run {
connectToSecureServerInternal(
GetSshHostFingerprintTask(hostname, port, false) {
currentHostKey: PublicKey ->
SecurityUtils.getFingerprint(currentHostKey).let {
currentHostKeyFingerprint ->
createReconnectSecureServerCallback(
connectionSettings,
sshHostKey,
currentHostKeyFingerprint,
{ currentHostKeyFingerprint == sshHostKey },
edit
)
}
}
)
}
}
private fun reconnectToFtpsServerToVerifyHostFingerprint(
connectionSettings: ConnectionSettings,
ftpsHostInfo: JSONObject,
edit: Boolean
) {
connectionSettings.run {
connectToSecureServerInternal(
FtpsGetHostCertificateTask(
hostname,
port,
requireContext()
) { hostInfo: JSONObject ->
createReconnectSecureServerCallback(
connectionSettings,
ftpsHostInfo.toString(),
hostInfo.toString(),
{ ftpsHostInfo.getString(FINGERPRINT) == hostInfo.getString(FINGERPRINT) },
edit
)
}
)
}
}
private fun <V, T : Callable<V>> connectToSecureServerInternal(
task: AbstractGetHostInfoTask<V, T>
) {
Single.fromCallable(task.getTask())
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.doOnSubscribe { task.onPreExecute() }
.subscribe(task::onFinish, task::onError)
}
@Suppress("LabeledExpression")
private val activityResultHandlerForPemSelection = registerForActivityResult(
ActivityResultContracts.StartActivityForResult()
) {
if (Activity.RESULT_OK == it.resultCode) {
it.data?.data?.run {
selectedPem = this
runCatching {
requireContext().contentResolver.openInputStream(this)?.let {
selectedKeyContent ->
PemToKeyPairTask(selectedKeyContent) { result: KeyPair? ->
selectedParsedKeyPair = result
selectedParsedKeyPairName = this
.lastPathSegment!!
.substring(
this.lastPathSegment!!
.indexOf('/') + 1
)
val okBTN = (dialog as MaterialDialog)
.getActionButton(DialogAction.POSITIVE)
okBTN.isEnabled = okBTN.isEnabled || true
binding.selectPemBTN.text = selectedParsedKeyPairName
}.execute()
}
}.onFailure {
log.error("Error reading PEM key", it)
}
}
}
}
private fun authenticateAndSaveSetup(
connectionSettings: ConnectionSettings,
hostKeyFingerprint: String? = null,
isEdit: Boolean
): Boolean = connectionSettings.run {
val path = this.toUriString()
val encryptedPath = NetCopyClientUtils.encryptFtpPathAsNecessary(path)
return if (!isEdit) {
saveFtpConnectionAndLoadlist(
connectionSettings,
hostKeyFingerprint,
path,
encryptedPath,
selectedParsedKeyPairName,
selectedParsedKeyPair
)
} else {
updateFtpConnection(
connectionName,
hostKeyFingerprint,
encryptedPath
)
}
}
@Suppress("LongParameterList")
private fun saveFtpConnectionAndLoadlist(
connectionSettings: ConnectionSettings,
hostKeyFingerprint: String?,
path: String,
encryptedPath: String,
selectedParsedKeyPairName: String?,
selectedParsedKeyPair: KeyPair?
): Boolean {
connectionSettings.run {
return runCatching {
NetCopyClientConnectionPool.getConnection(
prefix,
hostname,
port,
hostKeyFingerprint,
username,
password,
selectedParsedKeyPair
)?.run {
if (DataUtils.getInstance().containsServer(path) == -1) {
DataUtils.getInstance().addServer(arrayOf(connectionName, path))
(activity as MainActivity).drawer.refreshDrawer()
AppConfig.getInstance().utilsHandler.saveToDatabase(
OperationData(
UtilsHandler.Operation.SFTP,
encryptedPath,
connectionName,
hostKeyFingerprint,
selectedParsedKeyPairName,
getPemContents()
)
)
val ma = (activity as MainActivity).currentMainFragment
ma?.loadlist(
path,
false,
if (prefix == SSH_URI_PREFIX) {
OpenMode.SFTP
} else {
OpenMode.FTP
},
false
)
dismiss()
} else {
Snackbar.make(
requireActivity().findViewById(R.id.content_frame),
getString(R.string.connection_exists),
Snackbar.LENGTH_SHORT
).show()
dismiss()
}
true
} ?: false
}.getOrElse {
log.warn("Problem getting connection and load file list", it)
false
}
}
}
private fun updateFtpConnection(
connectionName: String,
hostKeyFingerprint: String?,
encryptedPath: String
): Boolean {
DataUtils.getInstance().removeServer(DataUtils.getInstance().containsServer(oldPath))
DataUtils.getInstance().addServer(arrayOf(connectionName, encryptedPath))
Collections.sort(DataUtils.getInstance().servers, BookSorter())
(activity as MainActivity).drawer.refreshDrawer()
AppConfig.getInstance().runInBackground {
AppConfig.getInstance().utilsHandler.updateSsh(
connectionName,
requireArguments().getString(ARG_NAME)!!,
encryptedPath,
hostKeyFingerprint,
selectedParsedKeyPairName,
getPemContents()
)
}
dismiss()
return true
}
// Read the PEM content from InputStream to String.
private fun getPemContents(): String? = selectedPem?.run {
runCatching {
requireContext().contentResolver.openInputStream(this)
?.bufferedReader()
?.use(BufferedReader::readText)
}.getOrNull()
}
private fun getProtocolPrefixFromDropdownSelection(): String {
return when (binding.protocolDropDown.selectedItem.toString()) {
requireContext().getString(R.string.protocol_ftp) -> FTP_URI_PREFIX
requireContext().getString(R.string.protocol_ftps) -> FTPS_URI_PREFIX
else -> SSH_URI_PREFIX
}
}
private data class ConnectionSettings(
val prefix: String,
val connectionName: String,
val hostname: String,
val port: Int,
val defaultPath: String? = null,
val username: String,
val password: String? = null,
val selectedParsedKeyPairName: String? = null,
val selectedParsedKeyPair: KeyPair? = null
) {
fun toUriString() = NetCopyClientUtils.deriveUriFrom(
prefix,
hostname,
port,
defaultPath,
username,
password,
selectedParsedKeyPair
)
}
private fun createConnectionSettings() =
ConnectionSettings(
prefix = getProtocolPrefixFromDropdownSelection(),
connectionName = binding.connectionET.text.toString(),
hostname = binding.ipET.text.toString(),
port = binding.portET.text.toString().toInt(),
defaultPath = binding.defaultPathET.text.toString(),
username = binding.usernameET.text.toString(),
password = if (true == binding.passwordET.text?.isEmpty()) {
arguments?.getString(ARG_PASSWORD, null)
} else {
binding.passwordET.text.toString()
},
selectedParsedKeyPairName = this.selectedParsedKeyPairName,
selectedParsedKeyPair = selectedParsedKeyPair
)
}
| gpl-3.0 | d872c7253709c37424205de837713eb4 | 39.644531 | 107 | 0.54272 | 5.71494 | false | false | false | false |
cwoolner/flex-poker | src/main/kotlin/com/flexpoker/game/command/aggregate/GameState.kt | 1 | 4214 | package com.flexpoker.game.command.aggregate
import com.flexpoker.game.command.events.BlindsIncreasedEvent
import com.flexpoker.game.command.events.GameCreatedEvent
import com.flexpoker.game.command.events.GameEvent
import com.flexpoker.game.command.events.GameFinishedEvent
import com.flexpoker.game.command.events.GameJoinedEvent
import com.flexpoker.game.command.events.GameMovedToStartingStageEvent
import com.flexpoker.game.command.events.GameStartedEvent
import com.flexpoker.game.command.events.GameTablesCreatedAndPlayersAssociatedEvent
import com.flexpoker.game.command.events.NewHandIsClearedToStartEvent
import com.flexpoker.game.command.events.PlayerBustedGameEvent
import com.flexpoker.game.command.events.PlayerMovedToNewTableEvent
import com.flexpoker.game.command.events.TablePausedForBalancingEvent
import com.flexpoker.game.command.events.TableRemovedEvent
import com.flexpoker.game.command.events.TableResumedAfterBalancingEvent
import com.flexpoker.game.command.events.dto.BlindScheduleDTO
import com.flexpoker.game.query.dto.GameStage
import org.pcollections.HashTreePMap
import org.pcollections.HashTreePSet
import org.pcollections.PMap
import org.pcollections.PSet
import java.util.UUID
data class GameState(
val aggregateId: UUID,
val maxNumberOfPlayers: Int,
val numberOfPlayersPerTable: Int,
val stage: GameStage,
val blindScheduleDTO: BlindScheduleDTO,
val registeredPlayerIds: PSet<UUID> = HashTreePSet.empty(),
val tableIdToPlayerIdsMap: PMap<UUID, PSet<UUID>> = HashTreePMap.empty(),
val pausedTablesForBalancing: PSet<UUID> = HashTreePSet.empty()
)
fun applyEvents(events: List<GameEvent>): GameState {
return applyEvents(null, events)
}
fun applyEvents(state: GameState?, events: List<GameEvent>): GameState {
return events.fold(state, { acc, event -> applyEvent(acc, event) })!!
}
fun applyEvent(state: GameState?, event: GameEvent): GameState {
require(state != null || event is GameCreatedEvent)
return when(event) {
is GameCreatedEvent -> GameState(
event.aggregateId, event.numberOfPlayers, event.numberOfPlayersPerTable,
GameStage.REGISTERING, blindSchedule(event.numberOfMinutesBetweenBlindLevels)
)
is GameJoinedEvent -> state!!.copy(registeredPlayerIds = state.registeredPlayerIds.plus(event.playerId))
is GameMovedToStartingStageEvent -> state!!.copy(stage = GameStage.STARTING)
is GameStartedEvent -> state!!.copy(stage = GameStage.INPROGRESS)
is GameTablesCreatedAndPlayersAssociatedEvent ->
state!!.copy(tableIdToPlayerIdsMap = state.tableIdToPlayerIdsMap.plusAll(event.tableIdToPlayerIdsMap))
is GameFinishedEvent -> state!!.copy(stage = GameStage.FINISHED)
is NewHandIsClearedToStartEvent -> state!!
is BlindsIncreasedEvent -> incrementLevel(state!!)
is TableRemovedEvent ->
state!!.copy(
tableIdToPlayerIdsMap = state.tableIdToPlayerIdsMap.minus(event.tableId),
pausedTablesForBalancing = state.pausedTablesForBalancing.minus(event.tableId)
)
is TablePausedForBalancingEvent ->
state!!.copy(pausedTablesForBalancing = state.pausedTablesForBalancing.plus(event.tableId))
is TableResumedAfterBalancingEvent ->
state!!.copy(pausedTablesForBalancing = state.pausedTablesForBalancing.minus(event.tableId))
is PlayerMovedToNewTableEvent -> {
val fromPlayerIds = state!!.tableIdToPlayerIdsMap[event.fromTableId]!!.minus(event.playerId)
val toPlayerIds = state.tableIdToPlayerIdsMap[event.fromTableId]!!.plus(event.playerId)
state.copy(tableIdToPlayerIdsMap = state.tableIdToPlayerIdsMap
.plus(event.fromTableId, fromPlayerIds)
.plus(event.toTableId, toPlayerIds))
}
is PlayerBustedGameEvent -> {
val tableId = state!!.tableIdToPlayerIdsMap.entries.first { it.value.contains(event.playerId) }.key
val playerIds = state.tableIdToPlayerIdsMap[tableId]!!.minus(event.playerId)
state.copy(tableIdToPlayerIdsMap = state.tableIdToPlayerIdsMap.plus(tableId, playerIds))
}
}
} | gpl-2.0 | 09b83c237038f570eb70f7f5635cfd92 | 50.402439 | 114 | 0.755102 | 4.218218 | false | false | false | false |
bailuk/AAT | aat-gtk/src/main/kotlin/ch/bailu/aat_gtk/search/SearchModel.kt | 1 | 1338 | package ch.bailu.aat_gtk.search
import ch.bailu.aat_gtk.lib.json.JsonMap
import org.mapsforge.core.model.LatLong
class SearchModel {
private data class Result(val name: String, val latLong: LatLong)
private val result = ArrayList<Result>()
private val observers = ArrayList<(SearchModel)->Unit>()
fun observe(observer: (SearchModel) -> Unit) {
observers.add(observer)
observer(this)
}
fun updateSearchResult(json: JsonMap) {
parse(json)
observers.forEach { it(this) }
}
private fun parse(json: JsonMap) {
result.clear()
json.map("result") { it ->
var lat = 0.0
var lon = 0.0
var name = ""
it.string("lat") {
lat = it.toDouble()
}
it.string("lon") {
lon = it.toDouble()
}
it.string("display_name") {
name = it
}
result.add(Result(name, LatLong(lat, lon)))
}
}
fun withFirst(cb : (String, LatLong) -> Unit) {
val first = result.firstOrNull()
if (first is Result) {
cb(first.name, first.latLong)
}
}
fun forEach(cb: (String, LatLong) -> Unit) {
result.forEach {
cb(it.name, it.latLong)
}
}
}
| gpl-3.0 | 10f96a02cf7303997c75010bdc83c3c6 | 23.777778 | 69 | 0.520179 | 3.900875 | false | false | false | false |
nemerosa/ontrack | ontrack-extension-indicators/src/main/java/net/nemerosa/ontrack/extension/indicators/portfolio/PortfolioGlobalIndicatorsMigration.kt | 1 | 2172 | package net.nemerosa.ontrack.extension.indicators.portfolio
import net.nemerosa.ontrack.model.security.SecurityService
import net.nemerosa.ontrack.model.support.StartupService
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import org.springframework.stereotype.Component
/**
* Migration of the global indicators into a 'Migrated' indicator view.
*/
@Deprecated("Used for the transition period in V4. This class will be removed in V5.")
@Component
class PortfolioGlobalIndicatorsMigration(
private val indicatorPortfolioService: IndicatorPortfolioService,
private val indicatorViewService: IndicatorViewService,
private val securityService: SecurityService
) : StartupService {
private val logger: Logger = LoggerFactory.getLogger(PortfolioGlobalIndicatorsMigration::class.java)
override fun getName(): String = "Migration of global indicators to an indicator view"
override fun startupOrder(): Int = StartupService.JOB_REGISTRATION
override fun start() {
securityService.asAdmin {
// Gets the migrated view
val view = indicatorViewService.findIndicatorViewByName(DEFAULT_VIEW_NAME)
if (view == null) {
// Gets the global indicators
val formerCategories = indicatorPortfolioService.getPortfolioOfPortfolios().categories
if (formerCategories.isNotEmpty()) {
logger.info("""Migrating old global indicators to the "$DEFAULT_VIEW_NAME" indicator view.""")
indicatorViewService.saveIndicatorView(
IndicatorView(
id = "",
name = DEFAULT_VIEW_NAME,
categories = formerCategories
)
)
// Clears the global indicators
indicatorPortfolioService.savePortfolioOfPortfolios(
PortfolioGlobalIndicators(emptyList())
)
}
}
}
}
companion object {
private const val DEFAULT_VIEW_NAME = "Migrated from global indicators"
}
} | mit | 77bf8abe9cfca1bf432856164d6f13aa | 39.240741 | 114 | 0.644567 | 5.597938 | false | false | false | false |
LarsKrogJensen/graphql-kotlin | src/test/groovy/graphql/TypeReferenceSchema.kt | 1 | 1256 | package graphql
import graphql.GarfieldSchema.CatType
import graphql.GarfieldSchema.DogType
import graphql.GarfieldSchema.NamedType
import graphql.schema.*
val PetType = newUnionType {
name = "Pet"
types += objectRef(CatType.name)
types += objectRef(DogType.name)
typeResolver = typeResolverProxy()
}
val PersonInputType = newInputObject {
name ="Person_Input"
field {
name = "name"
type = GraphQLString
}
}
val PersonType = newObject {
name = "Person"
field<String> {
name = "name"
}
field<Any> {
name = "pet"
type = typeRef(PetType.name)
}
interfaces += interfaceRef(NamedType.name)
}
val exists = newField<Any>{
name = "exists"
type = GraphQLBoolean
argument {
name = "person"
type = inputRef("Person_Input")
}
}
val find = newField<Any>{
name = "find"
type = typeRef("Person")
argument {
name ="name"
type = GraphQLString
}
}
val PersonService = newObject {
name = "PersonService"
fields += exists
fields += find
}
val SchemaWithReferences = newSchema {
query = PersonService
additionalTypes = setOf(PersonType, PersonInputType, PetType, CatType, DogType, NamedType)
}
| mit | 7bf00f17f99c96b0c4374d6c6a71b097 | 19.590164 | 94 | 0.636146 | 3.771772 | false | false | false | false |
FFlorien/AmpachePlayer | app/src/debug/java/be/florien/anyflow/data/user/UserModule.kt | 1 | 1956 | package be.florien.anyflow.data.user
import android.content.Context
import android.media.AudioManager
import androidx.lifecycle.LiveData
import be.florien.anyflow.data.server.AmpacheConnection
import be.florien.anyflow.feature.alarms.AlarmsSynchronizer
import be.florien.anyflow.injection.UserScope
import be.florien.anyflow.player.ExoPlayerController
import be.florien.anyflow.player.FiltersManager
import be.florien.anyflow.player.PlayerController
import be.florien.anyflow.player.PlayingQueue
import com.google.android.exoplayer2.upstream.cache.Cache
import dagger.Module
import dagger.Provides
import okhttp3.OkHttpClient
import javax.inject.Named
/**
* Module for dependencies available only when a user is logged in.
*/
@Module
class UserModule {
@Provides
@UserScope
fun providePlayerController(context: Context, playingQueue: PlayingQueue, ampacheConnection: AmpacheConnection, filtersManager: FiltersManager, audioManager: AudioManager, alarmsSynchronizer: AlarmsSynchronizer, cache: Cache, okHttpClient: OkHttpClient): PlayerController = ExoPlayerController(playingQueue, ampacheConnection, filtersManager, audioManager, alarmsSynchronizer, context, cache, okHttpClient)
@Provides
@Named("Songs")
@UserScope
fun provideSongsPercentageUpdater(ampacheConnection: AmpacheConnection): LiveData<Int> = ampacheConnection.songsPercentageUpdater
@Provides
@Named("Artists")
@UserScope
fun provideArtistsPercentageUpdater(ampacheConnection: AmpacheConnection): LiveData<Int> = ampacheConnection.artistsPercentageUpdater
@Provides
@Named("Albums")
@UserScope
fun provideAlbumsPercentageUpdater(ampacheConnection: AmpacheConnection): LiveData<Int> = ampacheConnection.albumsPercentageUpdater
@Provides
@Named("Playlists")
@UserScope
fun providePlaylistsPercentageUpdater(ampacheConnection: AmpacheConnection): LiveData<Int> = ampacheConnection.playlistsPercentageUpdater
} | gpl-3.0 | ee9714ae4b062a0ca6f416a751d65b28 | 39.770833 | 410 | 0.820552 | 5.015385 | false | false | false | false |
nickbutcher/plaid | core/src/main/java/io/plaidapp/core/designernews/data/stories/StoriesRemoteDataSource.kt | 1 | 3564 | /*
* Copyright 2018 Google LLC.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.plaidapp.core.designernews.data.stories
import io.plaidapp.core.data.Result
import io.plaidapp.core.designernews.data.DesignerNewsSearchSourceItem
import io.plaidapp.core.designernews.data.api.DesignerNewsService
import io.plaidapp.core.designernews.data.stories.model.StoryResponse
import java.io.IOException
import retrofit2.Response
/**
* Data source class that handles work with Designer News API.
*/
class StoriesRemoteDataSource(private val service: DesignerNewsService) {
suspend fun loadStories(page: Int): Result<List<StoryResponse>> {
return try {
val response = service.getStories(page)
getResult(response = response, onError = {
Result.Error(
IOException("Error getting stories ${response.code()} ${response.message()}")
)
})
} catch (e: Exception) {
Result.Error(IOException("Error getting stories", e))
}
}
suspend fun search(query: String, page: Int): Result<List<StoryResponse>> {
val queryWithoutPrefix =
query.replace(DesignerNewsSearchSourceItem.DESIGNER_NEWS_QUERY_PREFIX, "")
return try {
val searchResults = service.search(queryWithoutPrefix, page)
val ids = searchResults.body()
if (searchResults.isSuccessful && !ids.isNullOrEmpty()) {
val commaSeparatedIds = ids.joinToString(",")
loadStories(commaSeparatedIds)
} else {
Result.Error(IOException("Error searching $queryWithoutPrefix"))
}
} catch (e: Exception) {
Result.Error(IOException("Error searching $queryWithoutPrefix", e))
}
}
private suspend fun loadStories(commaSeparatedIds: String): Result<List<StoryResponse>> {
return try {
val response = service.getStories(commaSeparatedIds)
getResult(response = response, onError = {
Result.Error(
IOException("Error getting stories ${response.code()} ${response.message()}")
)
})
} catch (e: Exception) {
Result.Error(IOException("Error getting stories", e))
}
}
private inline fun getResult(
response: Response<List<StoryResponse>>,
onError: () -> Result.Error
): Result<List<StoryResponse>> {
if (response.isSuccessful) {
val body = response.body()
if (body != null) {
return Result.Success(body)
}
}
return onError.invoke()
}
companion object {
@Volatile
private var INSTANCE: StoriesRemoteDataSource? = null
fun getInstance(service: DesignerNewsService): StoriesRemoteDataSource {
return INSTANCE ?: synchronized(this) {
INSTANCE ?: StoriesRemoteDataSource(service).also { INSTANCE = it }
}
}
}
}
| apache-2.0 | b28ddb9e1cce59c617033e77b04e3ba7 | 35.742268 | 97 | 0.631594 | 4.822733 | false | false | false | false |
almibe/library-weasel-ratpack | src/main/kotlin/org/libraryweasel/vertx/LibraryWeaselVertxManager.kt | 1 | 2158 | /* 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.libraryweasel.vertx
import io.vertx.core.Verticle
import io.vertx.core.Vertx
import io.vertx.core.logging.LoggerFactory
import org.libraryweasel.auth.api.AuthRouterInitializer
import org.libraryweasel.servo.Callback
import org.libraryweasel.servo.Callbacks
import org.libraryweasel.servo.Component
import org.libraryweasel.servo.Service
import org.libraryweasel.vertx.api.VertxUrl
import org.libraryweasel.web.api.WebRoute
@Component(VertxUrl::class)
@Callbacks(
Callback(WebRoute::class),
Callback(Verticle::class)
)
class LibraryWeaselVertxManager: VertxUrl {
val vertx: Vertx = Vertx.vertx()
val deploymentMap = mutableMapOf<Verticle, String>()
val logger = LoggerFactory.getLogger(LibraryWeaselVertxManager::class.java)
override val url: String = "http://localhost:5055/" //TODO this shouldn't be hard coded
@Service @Volatile
lateinit var authRouterInitializer: AuthRouterInitializer
fun start() {
WebServer.start(vertx, authRouterInitializer)
}
fun stop() {
vertx.close()
}
fun addVerticle(verticle: Verticle) {
vertx.deployVerticle(verticle) {
if (it.succeeded()) {
deploymentMap[verticle] = it.result()
} else {
logger.error("Could not load Verticle.", it.cause())
}
}
}
fun removeVerticle(verticle: Verticle) {
val deploymentId = deploymentMap[verticle]
if (deploymentId != null) {
vertx.undeploy(deploymentId) {
if (it.succeeded()) {
deploymentMap.remove(verticle)
} else {
logger.error("Could not remove Verticle.", it.cause())
}
}
}
}
fun addWebRoute(webRoute: WebRoute) {
WebServer.addWebRoute(webRoute)
}
fun removeWebRoute(webRoute: WebRoute) {
WebServer.removeWebRoute(webRoute)
}
}
| mpl-2.0 | 8ff38e54f26539673b950f255c37c989 | 29.828571 | 91 | 0.657553 | 4.190291 | false | false | false | false |
simia-tech/epd-kotlin | src/main/kotlin/com/anyaku/epd/Locker.kt | 1 | 12028 | package com.anyaku.epd
import com.anyaku.crypt.decrypt
import com.anyaku.crypt.encrypt
import com.anyaku.crypt.asymmetric.Key as AsymmetricKey
import com.anyaku.crypt.combined.decryptAny as combinedDecryptAny
import com.anyaku.crypt.combined.encryptAny as combinedEncryptAny
import com.anyaku.crypt.symmetric.Key as SymmetricKey
import com.anyaku.crypt.symmetric.decryptAny as symmetricDecryptAny
import com.anyaku.crypt.symmetric.encryptAny as symmetricEncryptAny
import com.anyaku.epd.structure.UnlockedDocument
import com.anyaku.epd.structure.LockedDocument
import com.anyaku.epd.structure.Factory
import com.anyaku.epd.structure.UnlockedSection
import com.anyaku.epd.structure.LockedSection
import com.anyaku.epd.structure.UnlockedSectionsMap
import com.anyaku.epd.structure.LockedSectionsMap
import com.anyaku.epd.structure.UnlockedKeysMap
import com.anyaku.epd.structure.LockedContactsMap
import com.anyaku.epd.structure.UnlockedContactsMap
import com.anyaku.epd.structure.UnlockedContact
import com.anyaku.epd.structure.UnlockedMapper
import com.anyaku.epd.structure.LockedContact
import com.anyaku.epd.structure.Sections
import com.anyaku.epd.structure.SignedLockedDocument
import com.anyaku.crypt.asymmetric.Key
import com.anyaku.crypt.PasswordEncryptedKey
import com.anyaku.crypt.Password
/**
* The Locker provides functions to lock a private key or a whole document. At the end of the locking process the
* [[Signer]] is used to add a signature to the locked document. After this last step, an instance of
* [[SignedLockedDocument]] is returned by the `lock` function.
*
* The revert the locking process `unlock` function for both - private keys and documents - are provided.
*
* For initialization, an instance of a [[PublicKeyResolver]] has to be provided. The Locker will use it during the
* locking, to resolve the public keys for the given contact ids.
*
* Locking example
* <pre>val generator = Generator()
* val locker = Locker()
* val password = generator.password("test123")
* val document = generator.document()
*
* val lockedPrivateKey = locker.lock(document.privateKey, password)
* val lockedDocument = locker.lock(document, lockedPrivateKey)</pre>
*
* Unlocking example (given the values from the previous example)
* <pre>val unlockedPrivateKey = locker.unlock(lockedPrivateKey, password)
* val unlockedDocument = locker.unlock(lockedDocument, unlockedPrivateKey)</pre>
*/
public class Locker(private val publicKeyResolver: PublicKeyResolver) {
class InvalidPasswordException: Exception("an invalid password was given")
/**
* Locks the given asymmetric key with the given password. The result is of type [[PasswordEncryptedKey]] and
* contains the encrypted key as well as a set of hash parameters, that is needed to generate the hash password
* again.
*/
fun lock(key: Key, password: Password): PasswordEncryptedKey =
encrypt(key, password)
/**
* Unlocks the given encrypted asymmetric key with the given password. The result is the decrypted asymmetric key.
* If an invalid password is provided, the function should throw an [[InvalidPasswordException]]. The successfuly
* decrypted key can be used to unlock an LockedDocument using the unlock function.
*/
fun unlock(encryptedKey: PasswordEncryptedKey, password: Password): Key {
try {
return decrypt(encryptedKey, password)
} catch (exception: javax.crypto.BadPaddingException) {
throw InvalidPasswordException()
}
}
/**
* Locks the given document using the key pair inside the given [[UnlockedDocument]]. Optionally, an encrypted
* private key can be provided. If so, it's stored inside the returned [[SignedLockedDocument]]. In this case,
* strong hash parameters (aka a high security level) should be used to hash the password that has been used to
* encrypt the private key. The generated [[SignedLockedDocument]] is usually exposed to the public and thereby
* accessible to possible attackers.
* If no encrypted private key is provided, the returned document won't include it and the private key has to be
* stored somewhere else. This could be - for example - a save area in the memory of the local device. In that case,
* the key-encryption might need a less stronger password, but the profile access might also be less protable.
*/
fun lock(
unlockedDocument: UnlockedDocument,
encryptedPrivateKey: PasswordEncryptedKey? = null
): SignedLockedDocument {
val unlockedMapper = unlockedDocument.factory.buildUnlockedMapper()
val lockedDocument = LockedDocument(
unlockedDocument.id,
unlockedDocument.publicKey,
encryptedPrivateKey,
unlockedDocument.factory)
lock(lockedDocument.contacts,
unlockedDocument.contacts,
unlockedMapper)
lock(lockedDocument.sections,
unlockedDocument.sections,
unlockedDocument.contacts.ownContact.keys,
unlockedMapper)
return signer.sign(lockedDocument, unlockedDocument.privateKey)
}
/**
* Unlocks the given document with the given private key. The function returns an [[UnlockedDocument]], which is
* equal to the [[UnlockedDocument]] that has been used to generate the given [[SignedLockedDocument]].
*/
fun unlock(lockedDocument: LockedDocument, privateKey: Key): UnlockedDocument {
val unlockedDocument =
UnlockedDocument(lockedDocument.id, lockedDocument.publicKey, privateKey, lockedDocument.factory)
unlock(unlockedDocument.contacts,
lockedDocument.contacts,
unlockedDocument.privateKey,
lockedDocument.factory)
unlock(unlockedDocument.sections,
lockedDocument.sections,
unlockedDocument.contacts,
lockedDocument.factory.buildUnlockedMapper())
return unlockedDocument
}
/*
* Locks the given sections with the given keys.
*/
private fun lock(
lockedSections: LockedSectionsMap,
unlockedSections: UnlockedSectionsMap,
keys: UnlockedKeysMap,
unlockedMapper: UnlockedMapper
) {
lockedSections.publicSection = unlockedSections.publicSection
for (entry in unlockedSections.entrySet())
if (!entry.value.isPublicSection)
lockedSections[ entry.key ] = lock(entry.value, keys[ entry.key ], unlockedMapper)
}
/*
* Unlocks the given sections with the given keys.
*/
private fun unlock(
unlockedSections: UnlockedSectionsMap,
lockedSections: LockedSectionsMap,
contacts: UnlockedContactsMap,
unlockedMapper: UnlockedMapper
) {
val keysMap = contacts.ownContact.keys
unlockedSections.publicSection = lockedSections.publicSection as UnlockedSection
unlockedSections.privateSection = unlock(
lockedSections.privateSection,
keysMap.privateSectionKey,
Sections.PRIVATE_SECTION_ID,
contacts,
unlockedMapper)
for (entry in lockedSections.entrySet())
unlockedSections[ entry.key ] =
unlock(entry.value, keysMap[ entry.key ], entry.key, contacts, unlockedMapper)
}
/*
* Locks the given contacts.
*/
private fun lock(
lockedContacts: LockedContactsMap,
unlockedContacts: UnlockedContactsMap,
unlockedMapper: UnlockedMapper
) {
val ownContactId = unlockedContacts.ownContactId
val ownContactPublicKey = unlockedContacts.ownContactPublicKey
for (entry in unlockedContacts.entrySet())
if (!entry.key.equals(ownContactId)) {
val publicKey = publicKeyResolver.resolve(entry.key)
if (publicKey != null)
lockedContacts[ entry.key ] =
lock(entry.value,
publicKey,
unlockedContacts.ownContact.keys.privateSectionKey,
unlockedMapper)
}
lockedContacts[ ownContactId ] = lock(unlockedContacts.ownContact, ownContactPublicKey, unlockedMapper)
}
/*
* Unlocks the given contacts.
*/
private fun unlock(
unlockedContacts: UnlockedContactsMap,
lockedContacts: LockedContactsMap,
privateKey: AsymmetricKey,
factory: Factory
) {
unlockedContacts.ownContact = unlock(lockedContacts.ownContact, privateKey, factory)
for (entry in lockedContacts.entrySet()) {
if (unlockedContacts.ownContactId.equals(entry.key))
continue
unlockedContacts[ entry.key ] = unlock(entry.value, unlockedContacts.ownContact.keys, factory)
}
}
/*
* Locks the given section with the given key.
*/
private fun lock(
unlockedSection: UnlockedSection,
key: SymmetricKey,
unlockedMapper: UnlockedMapper
): LockedSection =
LockedSection(symmetricEncryptAny(unlockedMapper.sectionToMap(unlockedSection), key))
/*
* Unlocks the given section with the given key.
*/
[ suppress("UNCHECKED_CAST") ]
private fun unlock(
lockedSection: LockedSection,
key: SymmetricKey,
id: String,
contacts: UnlockedContactsMap,
unlockedMapper: UnlockedMapper
): UnlockedSection =
unlockedMapper.sectionFromMap(
id,
symmetricDecryptAny(lockedSection.encrypted, key) as Map<String, Any?>,
contacts)
/*
* Locks the given contact.
*/
private fun lock(
unlockedContact: UnlockedContact,
publicKey: AsymmetricKey,
privateSectionKey: SymmetricKey,
unlockedMapper: UnlockedMapper
): LockedContact =
LockedContact(
combinedEncryptAny(unlockedMapper.keysToMap(unlockedContact.keys), publicKey),
symmetricEncryptAny(unlockedContact.sections, privateSectionKey))
/*
* Locks the given own contact.
*/
private fun lock(
unlockedContact: UnlockedContact,
publicKey: AsymmetricKey,
unlockedMapper: UnlockedMapper
): LockedContact =
LockedContact(
combinedEncryptAny(unlockedMapper.keysToMap(unlockedContact.keys), publicKey),
null)
/*
* Unlocks the given contact.
*/
[ suppress("UNCHECKED_CAST") ]
private fun unlock(
lockedContact: LockedContact,
keys: UnlockedKeysMap,
factory: Factory
): UnlockedContact {
val unlockedContact = UnlockedContact(factory)
val lockedSections = lockedContact.sections
if (lockedSections != null)
unlockedContact.sections =
symmetricDecryptAny(lockedSections, keys.privateSectionKey) as MutableCollection<String>
for (section in unlockedContact.sections)
unlockedContact.keys[section] = keys[section]
return unlockedContact
}
/*
* Unlocks the given contact.
*/
[ suppress("UNCHECKED_CAST") ]
private fun unlock(
lockedContact: LockedContact,
privateKey: AsymmetricKey,
factory: Factory
): UnlockedContact {
val unlockedContact = UnlockedContact(factory)
val unlockedMapper = factory.buildUnlockedMapper()
unlockedContact.keys.setAll(
unlockedMapper.keysFromMap(combinedDecryptAny(lockedContact.keys, privateKey) as Map<String, Any?>))
return unlockedContact
}
private val signer = Signer()
}
| lgpl-3.0 | 8b6383606e27ed6f64a6f66b16234865 | 37.925566 | 120 | 0.671184 | 4.93963 | false | false | false | false |
vanita5/twittnuker | twittnuker/src/main/kotlin/de/vanita5/twittnuker/fragment/status/MuteStatusUsersDialogFragment.kt | 1 | 2377 | /*
* Twittnuker - Twitter client for Android
*
* Copyright (C) 2013-2017 vanita5 <[email protected]>
*
* This program incorporates a modified version of Twidere.
* Copyright (C) 2012-2017 Mariotaku Lee <[email protected]>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package de.vanita5.twittnuker.fragment.status
import android.app.Dialog
import android.os.Bundle
import android.support.v7.app.AlertDialog
import org.mariotaku.kpreferences.get
import de.vanita5.twittnuker.R
import de.vanita5.twittnuker.constant.IntentConstants.EXTRA_STATUS
import de.vanita5.twittnuker.constant.nameFirstKey
import de.vanita5.twittnuker.extension.applyTheme
import de.vanita5.twittnuker.extension.model.referencedUsers
import de.vanita5.twittnuker.extension.onShow
import de.vanita5.twittnuker.fragment.BaseDialogFragment
import de.vanita5.twittnuker.fragment.CreateUserMuteDialogFragment
import de.vanita5.twittnuker.model.ParcelableStatus
class MuteStatusUsersDialogFragment : BaseDialogFragment() {
private val status: ParcelableStatus get() = arguments.getParcelable(EXTRA_STATUS)
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
val builder = AlertDialog.Builder(context)
val referencedUsers = status.referencedUsers
val nameFirst = preferences[nameFirstKey]
val displayNames = referencedUsers.map {
userColorNameManager.getDisplayName(it, nameFirst)
}.toTypedArray()
builder.setTitle(R.string.action_status_mute_users)
builder.setItems(displayNames) { _, which ->
CreateUserMuteDialogFragment.show(fragmentManager, referencedUsers[which])
}
val dialog = builder.create()
dialog.onShow { it.applyTheme() }
return dialog
}
} | gpl-3.0 | 52c774312fd55e1ba85325e2a34c8e93 | 39.305085 | 86 | 0.759361 | 4.410019 | false | false | false | false |
ToxicBakery/ViewPagerTransforms | app/src/main/java/com/ToxicBakery/viewpager/transforms/example/MainActivity.kt | 1 | 5960 | /*
* Copyright 2014 Toxic Bakery
*
* 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.ToxicBakery.viewpager.transforms.example
import android.os.Bundle
import android.support.v4.app.Fragment
import android.support.v4.app.FragmentManager
import android.support.v4.app.FragmentStatePagerAdapter
import android.support.v4.view.ViewPager
import android.support.v4.view.ViewPager.PageTransformer
import android.support.v7.app.AppCompatActivity
import android.support.v7.widget.AppCompatSpinner
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.AdapterView
import android.widget.ArrayAdapter
import android.widget.TextView
import com.ToxicBakery.viewpager.transforms.*
class MainActivity : AppCompatActivity() {
private var selectedClassIndex: Int = 0
private lateinit var pager: ViewPager
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
setSupportActionBar(findViewById(R.id.toolbar))
selectedClassIndex = savedInstanceState?.getInt(KEY_SELECTED_CLASS) ?: 0
pager = findViewById(R.id.container)
pager.adapter = PageAdapter(supportFragmentManager)
pager.currentItem = savedInstanceState?.getInt(KEY_SELECTED_PAGE) ?: 0
title = ""
findViewById<AppCompatSpinner>(R.id.spinner).apply {
adapter = ArrayAdapter(
applicationContext,
android.R.layout.simple_list_item_1,
android.R.id.text1,
TRANSFORM_CLASSES)
setSelection(selectedClassIndex)
onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
override fun onNothingSelected(parent: AdapterView<*>?) = Unit
override fun onItemSelected(
parent: AdapterView<*>,
view: View?,
position: Int,
id: Long) = selectPage(position)
}
}
}
public override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
outState.putInt(KEY_SELECTED_CLASS, selectedClassIndex)
outState.putInt(KEY_SELECTED_PAGE, pager.currentItem)
}
private fun selectPage(position: Int) {
selectedClassIndex = position
pager.setPageTransformer(true, TRANSFORM_CLASSES[position].clazz.newInstance())
}
class PlaceholderFragment : Fragment() {
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
val position = arguments!!.getInt(EXTRA_POSITION)
val textViewPosition = inflater.inflate(R.layout.fragment_main, container, false) as TextView
textViewPosition.text = position.toString()
textViewPosition.setBackgroundColor(COLORS[position - 1])
return textViewPosition
}
companion object {
private const val EXTRA_POSITION = "EXTRA_POSITION"
private val COLORS = intArrayOf(-0xcc4a1b, -0x559934, -0x663400, -0x44cd, -0xbbbc)
fun newInstance(position: Int) = PlaceholderFragment().apply {
arguments = Bundle().apply {
putInt(PlaceholderFragment.EXTRA_POSITION, position)
}
}
}
}
private class PageAdapter internal constructor(fragmentManager: FragmentManager) : FragmentStatePagerAdapter(fragmentManager) {
override fun getItem(position: Int): Fragment =
PlaceholderFragment.newInstance(position + 1)
override fun getCount(): Int {
return 5
}
}
class TransformerItem(
val clazz: Class<out PageTransformer>,
val title: String = clazz.simpleName
) {
override fun toString(): String = title
}
companion object {
private const val KEY_SELECTED_PAGE = "KEY_SELECTED_PAGE"
private const val KEY_SELECTED_CLASS = "KEY_SELECTED_CLASS"
private val TRANSFORM_CLASSES: List<TransformerItem> = listOf(
TransformerItem(DefaultTransformer::class.java),
TransformerItem(AccordionTransformer::class.java),
TransformerItem(BackgroundToForegroundTransformer::class.java),
TransformerItem(CubeInTransformer::class.java),
TransformerItem(CubeOutTransformer::class.java),
TransformerItem(DepthPageTransformer::class.java),
TransformerItem(FlipHorizontalTransformer::class.java),
TransformerItem(FlipVerticalTransformer::class.java),
TransformerItem(ForegroundToBackgroundTransformer::class.java),
TransformerItem(RotateDownTransformer::class.java),
TransformerItem(RotateUpTransformer::class.java),
TransformerItem(ScaleInOutTransformer::class.java),
TransformerItem(StackTransformer::class.java),
TransformerItem(TabletTransformer::class.java),
TransformerItem(ZoomInTransformer::class.java),
TransformerItem(ZoomOutSlideTransformer::class.java),
TransformerItem(ZoomOutTransformer::class.java),
TransformerItem(DrawerTransformer::class.java)
)
}
}
| apache-2.0 | a980c245cd5e93ac57df017094700b85 | 37.954248 | 131 | 0.668289 | 5.021061 | false | false | false | false |
chadrick-kwag/datalabeling_app | app/src/main/java/com/example/chadrick/datalabeling/Models/requestqueueSingleton.kt | 1 | 876 | package com.example.chadrick.datalabeling.Models
import android.content.Context
import com.android.volley.RequestQueue
import com.android.volley.toolbox.Volley
/**
* Created by chadrick on 17. 12. 15.
*/
class requestqueueSingleton(context: Context) {
// make sure that this context is application context
val mcontext = context
var req_queue = Volley.newRequestQueue(context)
companion object {
@Volatile private var INSTANCE: requestqueueSingleton? = null
fun getInstance(context: Context?): requestqueueSingleton? =
context?.let { INSTANCE ?: synchronized(this) {
INSTANCE ?: requestqueueSingleton(context).also { INSTANCE = it; INSTANCE}
} }
fun getInstance():requestqueueSingleton? = INSTANCE
fun getQueue():RequestQueue = INSTANCE!!.req_queue
}
} | mit | 3193fe63a76efbdbb6a8630fa24ad0d4 | 21.487179 | 94 | 0.676941 | 4.735135 | false | false | false | false |
codeka/wwmmo | client/src/main/kotlin/au/com/codeka/warworlds/client/game/empire/SettingsView.kt | 1 | 1311 | package au.com.codeka.warworlds.client.game.empire
import android.content.Context
import android.view.View
import android.widget.Button
import android.widget.ScrollView
import android.widget.TextView
import au.com.codeka.warworlds.client.App
import au.com.codeka.warworlds.client.R
import au.com.codeka.warworlds.client.concurrency.Threads
class SettingsView(context: Context?, private val callback: Callback) : ScrollView(context) {
interface Callback {
fun onPatreonConnectClick(completeCallback: PatreonConnectCompleteCallback)
}
interface PatreonConnectCompleteCallback {
fun onPatreonConnectComplete(msg: String?)
}
init {
View.inflate(context, R.layout.empire_settings, this)
val patreonBtn = findViewById<Button>(R.id.patreon_btn)
patreonBtn.setOnClickListener {
patreonBtn.isEnabled = false
callback.onPatreonConnectClick(
object : PatreonConnectCompleteCallback {
override fun onPatreonConnectComplete(msg: String?) {
App.taskRunner.runTask(Runnable {
patreonBtn.isEnabled = true
val msgView = findViewById<TextView>(R.id.patreon_complete)
msgView.visibility = View.VISIBLE
msgView.text = msg
}, Threads.UI)
}
}
)
}
}
}
| mit | 2766f7f5b2ba6fda1b4ebef608af5b3d | 31.775 | 93 | 0.707857 | 4.284314 | false | false | false | false |
afollestad/photo-affix | engine/src/main/java/com/afollestad/photoaffix/engine/subengines/DimensionsEngine.kt | 1 | 6468 | /**
* Designed and developed by Aidan Follestad (@afollestad)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.afollestad.photoaffix.engine.subengines
import com.afollestad.photoaffix.engine.bitmaps.BitmapIterator
import com.afollestad.photoaffix.prefs.ImageSpacingHorizontal
import com.afollestad.photoaffix.prefs.ImageSpacingVertical
import com.afollestad.photoaffix.prefs.ScalePriority
import com.afollestad.photoaffix.prefs.StackHorizontally
import com.afollestad.photoaffix.utilities.DpConverter
import com.afollestad.photoaffix.utilities.ext.toRoundedInt
import com.afollestad.rxkprefs.Pref
import javax.inject.Inject
/** @author Aidan Follestad (afollestad) */
interface DimensionsEngine {
fun calculateSize(bitmapIterator: BitmapIterator): SizingResult
}
class RealDimensionsEngine @Inject constructor(
private val dpConverter: DpConverter,
@StackHorizontally private val stackHorizontallyPref: Pref<Boolean>,
@ScalePriority private val scalePriorityPref: Pref<Boolean>,
@ImageSpacingVertical private val spacingVerticalPref: Pref<Int>,
@ImageSpacingHorizontal private val spacingHorizontalPref: Pref<Int>
) : DimensionsEngine {
override fun calculateSize(bitmapIterator: BitmapIterator): SizingResult {
return if (stackHorizontallyPref.get()) {
calculateHorizontalSize(bitmapIterator)
} else {
calculateVerticalSize(bitmapIterator)
}
}
private fun calculateHorizontalSize(bitmapIterator: BitmapIterator): SizingResult {
val spacingHorizontal = spacingHorizontalPref.get()
.dp()
// The width of the resulting image will be the largest width of the selected images
// The height of the resulting image will be the sum of all the selected images' heights
var maxHeight = -1
var minHeight = -1
// Traverse all selected images to find largest and smallest heights
bitmapIterator.reset()
try {
for (options in bitmapIterator) {
val size = Size.fromOptions(options)
if (maxHeight == -1) {
maxHeight = size.height
} else if (size.height > maxHeight) {
maxHeight = size.height
}
if (minHeight == -1) {
minHeight = size.height
} else if (size.height < minHeight) {
minHeight = size.height
}
}
} catch (e: Exception) {
bitmapIterator.reset()
return SizingResult(
error = Exception("Unable to process horizontal sizing", e)
)
}
// Traverse images again now that we know the min/max height, scale widths accordingly
bitmapIterator.reset()
var totalWidth = 0
val scalePriority = scalePriorityPref.get()
try {
for (options in bitmapIterator) {
val size = Size.fromOptions(options)
var w = size.width
var h = size.height
val ratio = w.toFloat() / h.toFloat()
if (scalePriority) {
// Scale to largest
if (h < maxHeight) {
h = maxHeight
w = (h.toFloat() * ratio).toRoundedInt()
}
} else if (h > minHeight) {
// Scale to smallest
h = minHeight
w = (h.toFloat() * ratio).toRoundedInt()
}
totalWidth += w
}
} catch (e: Exception) {
bitmapIterator.reset()
return SizingResult(
error = Exception("Unable to process horizontal sizing", e)
)
}
// Compensate for horizontal spacing
totalWidth += spacingHorizontal * (bitmapIterator.size() - 1)
val size = Size(
width = totalWidth,
height = if (scalePriority) maxHeight else minHeight
)
return SizingResult(size = size)
}
private fun calculateVerticalSize(bitmapIterator: BitmapIterator): SizingResult {
val spacingVertical = spacingVerticalPref.get()
.dp()
// The height of the resulting image will be the largest height of the selected images
// The width of the resulting image will be the sum of all the selected images' widths
var maxWidth = -1
var minWidth = -1
// Traverse all selected images and load min/max width, scale height accordingly
bitmapIterator.reset()
try {
for (options in bitmapIterator) {
val size = Size.fromOptions(options)
if (maxWidth == -1) {
maxWidth = size.width
} else if (size.width > maxWidth) {
maxWidth = size.width
}
if (minWidth == -1) {
minWidth = size.width
} else if (size.width < minWidth) {
minWidth = size.width
}
}
} catch (e: Exception) {
bitmapIterator.reset()
return SizingResult(
error = Exception("Unable to process vertical sizing", e)
)
}
// Traverse images again now that we know the min/max height, scale widths accordingly
bitmapIterator.reset()
var totalHeight = 0
val scalePriority = scalePriorityPref.get()
try {
for (options in bitmapIterator) {
val size = Size.fromOptions(options)
var w = size.width
var h = size.height
val ratio = h.toFloat() / w.toFloat()
if (scalePriority) {
// Scale to largest
if (w < maxWidth) {
w = maxWidth
h = (w.toFloat() * ratio).toRoundedInt()
}
} else if (w > minWidth) {
// Scale to smallest
w = minWidth
h = (w.toFloat() * ratio).toRoundedInt()
}
totalHeight += h
}
} catch (e: Exception) {
bitmapIterator.reset()
return SizingResult(
error = Exception("Unable to process vertical sizing", e)
)
}
// Compensate for spacing
totalHeight += spacingVertical * (bitmapIterator.size() - 1)
val size = Size(
width = if (scalePriority) maxWidth else minWidth,
height = totalHeight
)
return SizingResult(size = size)
}
private fun Int.dp() = dpConverter.toDp(this).toInt()
}
| apache-2.0 | 139be6ce474925e0aca8cbd0b519f300 | 30.246377 | 92 | 0.649505 | 4.448418 | false | false | false | false |
deeplearning4j/deeplearning4j | nd4j/samediff-import/samediff-import-onnx/src/main/kotlin/org/nd4j/samediff/frameworkimport/onnx/definitions/implementations/PRelu.kt | 1 | 2421 | /*
* ******************************************************************************
* *
* *
* * This program and the accompanying materials are made available under the
* * terms of the Apache License, Version 2.0 which is available at
* * https://www.apache.org/licenses/LICENSE-2.0.
* *
* * See the NOTICE file distributed with this work for additional
* * information regarding copyright ownership.
* * 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.
* *
* * SPDX-License-Identifier: Apache-2.0
* *****************************************************************************
*/
package org.nd4j.samediff.frameworkimport.onnx.definitions.implementations
import org.nd4j.autodiff.samediff.SDVariable
import org.nd4j.autodiff.samediff.SameDiff
import org.nd4j.autodiff.samediff.internal.SameDiffOp
import org.nd4j.samediff.frameworkimport.ImportGraph
import org.nd4j.samediff.frameworkimport.hooks.PreImportHook
import org.nd4j.samediff.frameworkimport.hooks.annotations.PreHookRule
import org.nd4j.samediff.frameworkimport.registry.OpMappingRegistry
import org.nd4j.shade.protobuf.GeneratedMessageV3
import org.nd4j.shade.protobuf.ProtocolMessageEnum
@PreHookRule(nodeNames = [],opNames = ["PRelu"],frameworkName = "onnx")
class PRelu: PreImportHook {
override fun doImport(
sd: SameDiff,
attributes: Map<String, Any>,
outputNames: List<String>,
op: SameDiffOp,
mappingRegistry: OpMappingRegistry<GeneratedMessageV3, GeneratedMessageV3, GeneratedMessageV3, GeneratedMessageV3, ProtocolMessageEnum, GeneratedMessageV3, GeneratedMessageV3>,
importGraph: ImportGraph<GeneratedMessageV3, GeneratedMessageV3, GeneratedMessageV3, GeneratedMessageV3, GeneratedMessageV3, GeneratedMessageV3, ProtocolMessageEnum>,
dynamicVariables: Map<String, GeneratedMessageV3>
): Map<String, List<SDVariable>> {
val inputVariable = sd.getVariable(op.inputsToOp[0])
val slope = sd.getVariable(op.inputsToOp[1])
val output = sd.nn().prelu(outputNames[0],inputVariable,slope,2,3)
return mapOf(output.name() to listOf(output))
}
} | apache-2.0 | 33562432632ec64a6bdbd2fee557e1db | 47.44 | 184 | 0.707146 | 4.323214 | false | false | false | false |
Undin/intellij-rust | src/main/kotlin/org/rust/cargo/project/model/impl/TestCargoProjectsServiceImpl.kt | 2 | 5755 | /*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.cargo.project.model.impl
import com.intellij.openapi.Disposable
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.Disposer
import com.intellij.openapi.vfs.VirtualFile
import org.jetbrains.annotations.TestOnly
import org.rust.cargo.CfgOptions
import org.rust.cargo.project.model.CargoProject
import org.rust.cargo.project.model.RustcInfo
import org.rust.cargo.project.workspace.CargoWorkspace
import org.rust.cargo.project.workspace.CargoWorkspace.Edition
import org.rust.cargo.project.workspace.FeatureDep
import org.rust.cargo.project.workspace.PackageFeature
import org.rust.lang.core.psi.rustPsiManager
import org.rust.openapiext.pathAsPath
import java.nio.file.Path
import java.util.concurrent.CompletableFuture
import java.util.concurrent.TimeUnit
class TestCargoProjectsServiceImpl(project: Project) : CargoProjectsServiceImpl(project) {
@TestOnly
fun createTestProject(rootDir: VirtualFile, ws: CargoWorkspace, rustcInfo: RustcInfo? = null) {
val manifest = rootDir.pathAsPath.resolve("Cargo.toml")
val testProject = CargoProjectImpl(
manifest, this, UserDisabledFeatures.EMPTY, ws, null, rustcInfo,
workspaceStatus = CargoProject.UpdateStatus.UpToDate,
rustcInfoStatus = if (rustcInfo != null) CargoProject.UpdateStatus.UpToDate else CargoProject.UpdateStatus.NeedsUpdate
)
testProject.setRootDir(rootDir)
modifyProjectsSync { CompletableFuture.completedFuture(listOf(testProject)) }
}
@TestOnly
fun setRustcInfo(rustcInfo: RustcInfo, parentDisposable: Disposable) {
val oldValues = mutableMapOf<Path, RustcInfo?>()
modifyProjectsSync { projects ->
projects.forEach { oldValues[it.manifest] = it.rustcInfo }
val updatedProjects = projects.map {
it.copy(rustcInfo = rustcInfo, rustcInfoStatus = CargoProject.UpdateStatus.UpToDate)
}
CompletableFuture.completedFuture(updatedProjects)
}
Disposer.register(parentDisposable) {
modifyProjectsSync { projects ->
val updatedProjects = projects.map {
it.copy(rustcInfo = oldValues[it.manifest], rustcInfoStatus = CargoProject.UpdateStatus.UpToDate)
}
CompletableFuture.completedFuture(updatedProjects)
}
}
}
@TestOnly
fun setEdition(edition: Edition, parentDisposable: Disposable) {
if (edition == DEFAULT_EDITION_FOR_TESTS) return
setEditionInner(edition)
Disposer.register(parentDisposable) {
setEditionInner(DEFAULT_EDITION_FOR_TESTS)
}
}
@TestOnly
fun withEdition(edition: Edition, action: () -> Unit) {
if (edition == DEFAULT_EDITION_FOR_TESTS) return action()
setEditionInner(edition)
try {
action()
} finally {
setEditionInner(DEFAULT_EDITION_FOR_TESTS)
}
}
private fun setEditionInner(edition: Edition) {
modifyProjectsSync { projects ->
val updatedProjects = projects.map { project ->
val ws = project.workspace?.withEdition(edition)
project.copy(rawWorkspace = ws)
}
CompletableFuture.completedFuture(updatedProjects)
}
project.rustPsiManager.incRustStructureModificationCount()
}
@TestOnly
fun setCfgOptions(cfgOptions: CfgOptions, parentDisposable: Disposable) {
setCfgOptionsInner(cfgOptions)
Disposer.register(parentDisposable) {
setCfgOptionsInner(CfgOptions.DEFAULT)
}
}
private fun setCfgOptionsInner(cfgOptions: CfgOptions) {
modifyProjectsSync { projects ->
val updatedProjects = projects.map { project ->
val ws = project.workspace?.withCfgOptions(cfgOptions)
project.copy(rawWorkspace = ws)
}
CompletableFuture.completedFuture(updatedProjects)
}
}
@TestOnly
fun setCargoFeatures(features: Map<PackageFeature, List<FeatureDep>>, parentDisposable: Disposable) {
setCargoFeaturesInner(features)
Disposer.register(parentDisposable) {
setCargoFeaturesInner(emptyMap())
}
}
private fun setCargoFeaturesInner(features: Map<PackageFeature, List<FeatureDep>>) {
modifyProjectsSync { projects ->
val updatedProjects = projects.map { project ->
val ws = project.workspace?.withCargoFeatures(features)
project.copy(rawWorkspace = ws, userDisabledFeatures = UserDisabledFeatures.EMPTY)
}
CompletableFuture.completedFuture(updatedProjects)
}
}
private fun modifyProjectsSync(f: (List<CargoProjectImpl>) -> CompletableFuture<List<CargoProjectImpl>>) {
modifyProjects(f).get(1, TimeUnit.MINUTES) ?: error("Timeout when refreshing a test Cargo project")
}
@TestOnly
fun discoverAndRefreshSync(): List<CargoProject> {
return discoverAndRefresh().get(1, TimeUnit.MINUTES)
?: error("Timeout when refreshing a test Cargo project")
}
@TestOnly
fun refreshAllProjectsSync(): List<CargoProject> {
return refreshAllProjects().get(1, TimeUnit.MINUTES)
?: error("Timeout when refreshing a test Cargo project")
}
}
@get:TestOnly
val DEFAULT_EDITION_FOR_TESTS: Edition
get() {
val edition = System.getenv("DEFAULT_EDITION_FOR_TESTS") ?: return Edition.EDITION_2021
return Edition.values().single { it.presentation == edition }
}
| mit | ac7644eb15349c1e59a3e26bb9982c1c | 36.37013 | 130 | 0.679409 | 4.795833 | false | true | false | false |
Undin/intellij-rust | src/main/kotlin/org/rust/cargo/project/workspace/CargoWorkspace.kt | 2 | 31149 | /*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.cargo.project.workspace
import com.intellij.openapi.util.UserDataHolderBase
import com.intellij.openapi.util.UserDataHolderEx
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.openapi.vfs.VirtualFileManager
import com.intellij.util.ThreeState
import org.jetbrains.annotations.TestOnly
import org.rust.cargo.CargoConfig
import org.rust.cargo.CfgOptions
import org.rust.cargo.project.model.CargoProjectsService
import org.rust.cargo.project.model.RustcInfo
import org.rust.cargo.project.model.impl.UserDisabledFeatures
import org.rust.cargo.project.workspace.PackageOrigin.*
import org.rust.cargo.util.AutoInjectedCrates.CORE
import org.rust.cargo.util.AutoInjectedCrates.STD
import org.rust.openapiext.CachedVirtualFile
import org.rust.openapiext.isUnitTestMode
import org.rust.stdext.applyWithSymlink
import org.rust.stdext.mapToSet
import java.nio.file.Path
import java.nio.file.Paths
import java.util.*
/**
* Rust project model represented roughly in the same way as in Cargo itself.
*
* [CargoProjectsService] manages workspaces.
*/
interface CargoWorkspace {
val manifestPath: Path
val contentRoot: Path get() = manifestPath.parent
val workspaceRoot: VirtualFile?
val cfgOptions: CfgOptions
val cargoConfig: CargoConfig
/**
* Flatten list of packages including workspace members, dependencies, transitive dependencies
* and stdlib. Use `packages.filter { it.origin == PackageOrigin.WORKSPACE }` to
* obtain workspace members.
*/
val packages: Collection<Package>
val featureGraph: FeatureGraph
fun findPackageById(id: PackageId): Package? = packages.find { it.id == id }
fun findPackageByName(name: String, isStd: ThreeState = ThreeState.UNSURE): Package? = packages.find {
if (it.name != name && it.normName != name) return@find false
when (isStd) {
ThreeState.YES -> it.origin == STDLIB
ThreeState.NO -> it.origin == WORKSPACE || it.origin == DEPENDENCY
ThreeState.UNSURE -> true
}
}
fun findTargetByCrateRoot(root: VirtualFile): Target?
fun isCrateRoot(root: VirtualFile) = findTargetByCrateRoot(root) != null
fun withStdlib(stdlib: StandardLibrary, cfgOptions: CfgOptions, rustcInfo: RustcInfo? = null): CargoWorkspace
fun withDisabledFeatures(userDisabledFeatures: UserDisabledFeatures): CargoWorkspace
val hasStandardLibrary: Boolean get() = packages.any { it.origin == STDLIB }
@TestOnly
fun withImplicitDependency(pkgToAdd: CargoWorkspaceData.Package): CargoWorkspace
@TestOnly
fun withEdition(edition: Edition): CargoWorkspace
@TestOnly
fun withCfgOptions(cfgOptions: CfgOptions): CargoWorkspace
@TestOnly
fun withCargoFeatures(features: Map<PackageFeature, List<FeatureDep>>): CargoWorkspace
/** See docs for [CargoProjectsService] */
interface Package : UserDataHolderEx {
val contentRoot: VirtualFile?
val rootDirectory: Path
val id: String
val name: String
val normName: String get() = name.replace('-', '_')
val version: String
val source: String?
val origin: PackageOrigin
val targets: Collection<Target>
val libTarget: Target? get() = targets.find { it.kind.isLib }
val customBuildTarget: Target? get() = targets.find { it.kind == TargetKind.CustomBuild }
val hasCustomBuildScript: Boolean get() = customBuildTarget != null
val dependencies: Collection<Dependency>
/**
* Cfg options from the package custom build script (`build.rs`). `null` if there isn't build script
* or the build script was not evaluated successfully or build script evaluation is disabled
*/
val cfgOptions: CfgOptions?
val features: Set<PackageFeature>
val workspace: CargoWorkspace
val edition: Edition
val env: Map<String, String>
val outDir: VirtualFile?
val featureState: Map<FeatureName, FeatureState>
val procMacroArtifact: CargoWorkspaceData.ProcMacroArtifact?
fun findDependency(normName: String): Target? =
if (this.normName == normName) libTarget else dependencies.find { it.name == normName }?.pkg?.libTarget
}
/** See docs for [CargoProjectsService] */
interface Target {
val name: String
// target name must be a valid Rust identifier, so normalize it by mapping `-` to `_`
// https://github.com/rust-lang/cargo/blob/ece4e963a3054cdd078a46449ef0270b88f74d45/src/cargo/core/manifest.rs#L299
val normName: String get() = name.replace('-', '_')
val kind: TargetKind
val crateRoot: VirtualFile?
val pkg: Package
val edition: Edition
val doctest: Boolean
/** See [org.rust.cargo.toolchain.impl.CargoMetadata.Target.required_features] */
val requiredFeatures: List<String>
/** Complete `cfg` options of the target. Combines compiler options, package options and target options */
val cfgOptions: CfgOptions
}
interface Dependency {
val pkg: Package
val name: String
val cargoFeatureDependencyPackageName: String
val depKinds: List<DepKindInfo>
/**
* Consider Cargo.toml:
* ```
* [dependencies.foo]
* version = "*"
* features = ["bar", "baz"]
* ```
* For dependency `foo`, features `bar` and `baz` are considered "required"
*/
val requiredFeatures: Set<String>
}
data class DepKindInfo(
val kind: DepKind,
val target: String? = null
)
enum class DepKind(val cargoName: String?) {
// For old Cargo versions prior to `1.41.0`
Unclassified(null),
Stdlib("stdlib?"),
// [dependencies]
Normal(null),
// [dev-dependencies]
Development("dev"),
// [build-dependencies]
Build("build")
}
sealed class TargetKind(val name: String) {
class Lib(val kinds: EnumSet<LibKind>) : TargetKind("lib") {
constructor(vararg kinds: LibKind) : this(EnumSet.copyOf(kinds.asList()))
}
object Bin : TargetKind("bin")
object Test : TargetKind("test")
object ExampleBin : TargetKind("example")
class ExampleLib(val kinds: EnumSet<LibKind>) : TargetKind("example")
object Bench : TargetKind("bench")
object CustomBuild : TargetKind("custom-build")
object Unknown : TargetKind("unknown")
val isLib: Boolean get() = this is Lib
val isBin: Boolean get() = this == Bin
val isExampleBin: Boolean get() = this == ExampleBin
val isCustomBuild: Boolean get() = this == CustomBuild
val isProcMacro: Boolean
get() = this is Lib && this.kinds.contains(LibKind.PROC_MACRO)
}
enum class LibKind {
LIB, DYLIB, STATICLIB, CDYLIB, RLIB, PROC_MACRO, UNKNOWN
}
enum class Edition(val presentation: String) {
EDITION_2015("2015"),
EDITION_2018("2018"),
EDITION_2021("2021");
companion object {
val DEFAULT: Edition = EDITION_2018
}
}
companion object {
fun deserialize(
manifestPath: Path,
data: CargoWorkspaceData,
cfgOptions: CfgOptions = CfgOptions.DEFAULT,
cargoConfig: CargoConfig = CargoConfig.DEFAULT,
): CargoWorkspace =
WorkspaceImpl.deserialize(manifestPath, data, cfgOptions, cargoConfig)
}
}
private class WorkspaceImpl(
override val manifestPath: Path,
val workspaceRootUrl: String?,
packagesData: Collection<CargoWorkspaceData.Package>,
override val cfgOptions: CfgOptions,
override val cargoConfig: CargoConfig,
val featuresState: Map<PackageRoot, Map<FeatureName, FeatureState>>
) : CargoWorkspace {
override val workspaceRoot: VirtualFile? by CachedVirtualFile(workspaceRootUrl)
override val packages: List<PackageImpl> = packagesData.map { pkg ->
PackageImpl(
this,
pkg.id,
pkg.contentRootUrl,
pkg.name,
pkg.version,
pkg.targets,
pkg.source,
pkg.origin,
pkg.edition,
pkg.cfgOptions,
pkg.features,
pkg.enabledFeatures,
pkg.env,
pkg.outDirUrl,
pkg.procMacroArtifact,
)
}
override val featureGraph: FeatureGraph by lazy(LazyThreadSafetyMode.PUBLICATION) {
val wrappedFeatures = hashMapOf<PackageFeature, List<PackageFeature>>()
for (pkg in packages) {
val pkgFeatures = pkg.rawFeatures
for (packageFeature in pkg.features) {
if (packageFeature in wrappedFeatures) continue
val deps = pkgFeatures[packageFeature.name] ?: continue
val wrappedDeps = deps.flatMap { featureDep ->
when {
featureDep.startsWith("dep:") -> emptyList()
featureDep in pkgFeatures -> listOf(PackageFeature(pkg, featureDep))
"/" in featureDep -> {
val (firstSegment, name) = featureDep.split('/', limit = 2)
val optional = firstSegment.endsWith("?")
val depName = firstSegment.removeSuffix("?")
val dep = pkg.dependencies.find { it.cargoFeatureDependencyPackageName == depName }
?: return@flatMap emptyList()
if (name in dep.pkg.rawFeatures) {
if (!optional && dep.isOptional) {
listOf(PackageFeature(pkg, dep.cargoFeatureDependencyPackageName), PackageFeature(dep.pkg, name))
} else {
listOf(PackageFeature(dep.pkg, name))
}
} else {
emptyList()
}
}
else -> emptyList()
}
}
wrappedFeatures[packageFeature] = wrappedDeps
}
}
FeatureGraph.buildFor(wrappedFeatures)
}
val targetByCrateRootUrl = packages.flatMap { it.targets }.associateBy { it.crateRootUrl }
override fun findTargetByCrateRoot(root: VirtualFile): CargoWorkspace.Target? =
root.applyWithSymlink { targetByCrateRootUrl[it.url] }
override fun withStdlib(stdlib: StandardLibrary, cfgOptions: CfgOptions, rustcInfo: RustcInfo?): CargoWorkspace {
// This is a bit trickier than it seems required.
// The problem is that workspace packages and targets have backlinks
// so we have to rebuild the whole workspace from scratch instead of
// *just* adding in the stdlib.
val (newPackagesData, @Suppress("NAME_SHADOWING") stdlib) = if (!stdlib.isPartOfCargoProject) {
Pair(
packages.map { it.asPackageData() } + stdlib.asPackageData(rustcInfo),
stdlib
)
} else {
// In the case of https://github.com/rust-lang/rust project, stdlib
// is already a part of the project, so no need to add extra packages.
val oldPackagesData = packages.map { it.asPackageData() }
val stdCratePackageRoots = stdlib.crates.mapToSet { it.contentRootUrl }
val (stdPackagesData, otherPackagesData) = oldPackagesData.partition { it.contentRootUrl in stdCratePackageRoots }
val stdPackagesByPackageRoot = stdPackagesData.associateBy { it.contentRootUrl }
val pkgIdMapping = stdlib.crates.associate {
it.id to (stdPackagesByPackageRoot[it.contentRootUrl]?.id ?: it.id)
}
val newStdlibCrates = stdlib.crates.map { it.copy(id = pkgIdMapping.getValue(it.id)) }
val newStdlibDependencies = stdlib.workspaceData.dependencies.map { (oldId, dependency) ->
val newDependencies = dependency.mapToSet { it.copy(id = pkgIdMapping.getValue(it.id)) }
pkgIdMapping.getValue(oldId) to newDependencies
}.toMap()
Pair(
otherPackagesData + stdPackagesData.map { it.copy(origin = STDLIB) },
stdlib.copy(
workspaceData = stdlib.workspaceData.copy(
packages = newStdlibCrates,
dependencies = newStdlibDependencies
)
)
)
}
val stdAll = stdlib.crates.associateBy { it.id }
val stdInternalDeps = stdlib.crates.filter { it.origin == STDLIB_DEPENDENCY }.mapToSet { it.id }
val result = WorkspaceImpl(
manifestPath,
workspaceRootUrl,
newPackagesData,
cfgOptions,
cargoConfig,
featuresState
)
run {
val oldIdToPackage = packages.associateBy { it.id }
val newIdToPackage = result.packages.associateBy { it.id }
val stdlibDependencies = result.packages.filter { it.origin == STDLIB }
.map { DependencyImpl(it, depKinds = listOf(CargoWorkspace.DepKindInfo(CargoWorkspace.DepKind.Stdlib))) }
newIdToPackage.forEach { (id, pkg) ->
val stdCrate = stdAll[id]
if (stdCrate == null) {
pkg.dependencies.addAll(oldIdToPackage[id]?.dependencies.orEmpty().mapNotNull { dep ->
val dependencyPackage = newIdToPackage[dep.pkg.id] ?: return@mapNotNull null
dep.withPackage(dependencyPackage)
})
val explicitDeps = pkg.dependencies.map { it.name }.toSet()
pkg.dependencies.addAll(stdlibDependencies.filter { it.name !in explicitDeps && it.pkg.id !in stdInternalDeps })
} else {
// `pkg` is a crate from stdlib
pkg.addDependencies(stdlib.workspaceData, newIdToPackage)
}
}
}
return result
}
private fun withDependenciesOf(other: WorkspaceImpl): CargoWorkspace {
val otherIdToPackage = other.packages.associateBy { it.id }
val thisIdToPackage = packages.associateBy { it.id }
thisIdToPackage.forEach { (id, pkg) ->
pkg.dependencies.addAll(otherIdToPackage[id]?.dependencies.orEmpty().mapNotNull { dep ->
val dependencyPackage = thisIdToPackage[dep.pkg.id] ?: return@mapNotNull null
dep.withPackage(dependencyPackage)
})
}
return this
}
override fun withDisabledFeatures(userDisabledFeatures: UserDisabledFeatures): CargoWorkspace {
val featuresState = inferFeatureState(userDisabledFeatures).associateByPackageRoot()
return WorkspaceImpl(
manifestPath,
workspaceRootUrl,
packages.map { it.asPackageData() },
cfgOptions,
cargoConfig,
featuresState
).withDependenciesOf(this)
}
/**
* Infers a state of each Cargo feature of each package in the workspace (including dependencies!).
*
* Initial state: all [DEPENDENCY] packages features are disabled, all [WORKSPACE] packages features are enabled,
* excluding [userDisabledFeatures] features.
* Then we enable [DEPENDENCY] packages features transitively based on the initial state and features dependencies
*/
private fun inferFeatureState(userDisabledFeatures: UserDisabledFeatures): Map<PackageFeature, FeatureState> {
// Calculate features that should be enabled in the workspace, all by default (if `userDisabledFeatures` is empty)
val workspaceFeatureState = featureGraph.apply(defaultState = FeatureState.Enabled) {
disableAll(userDisabledFeatures.getDisabledFeatures(packages))
}
return featureGraph.apply(defaultState = FeatureState.Disabled) {
for (pkg in packages) {
// Enable remained workspace features (transitively)
if (pkg.origin == WORKSPACE || pkg.origin == STDLIB) {
for (feature in pkg.features) {
if (workspaceFeatureState[feature] == FeatureState.Enabled) {
enable(feature)
}
}
}
// Also, enable features specified in dependencies configuration. Consider `Cargo.toml`:
// ```
// [dependency]
// foo = { version = "*", feature = ["bar", "baz"] }
// #^ enable these features
// ```
// Here features `bar` and `baz` in package `foo` should be enabled, but only if the
// package `foo` is not a workspace member. Otherwise its features are controlled by
// a user (and enabled by default)
for (dependency in pkg.dependencies) {
if (dependency.pkg.origin == WORKSPACE || dependency.pkg.origin == STDLIB) continue
if (dependency.areDefaultFeaturesEnabled) {
enable(PackageFeature(dependency.pkg, "default"))
}
enableAll(dependency.requiredFeatures.map { PackageFeature(dependency.pkg, it) })
}
}
}
}
/** A kind of test for [inferFeatureState]: check that our features inference works the same way as Cargo's */
private fun checkFeaturesInference() {
if (!isUnitTestMode) return
val enabledByCargo = packages.flatMap { pkg ->
pkg.cargoEnabledFeatures.map { PackageFeature(pkg, it) }
}
for ((feature, state) in inferFeatureState(UserDisabledFeatures.EMPTY)) {
when (feature.pkg.origin) {
STDLIB -> {
// All features of stdlib package should be considered as enabled by default.
// If `RsExperiments.FETCH_ACTUAL_STDLIB_METADATA` is enabled,
// the plugin invokes `cargo metadata` for `test` crate of stdlib to get actual info.
// And since stdlib packages are not a single workspace,
// `cargo` considers that all stdlib crates except test one are dependencies and
// as a result, enabled only features required by `test` package (i.e. `pkg.cargoEnabledFeatures` are not expected)
// It doesn't make sense to fix `pkg.cargoEnabledFeatures` so let's just adjust this check
if (!state.isEnabled) {
error("Feature `${feature.name}` in package `${feature.pkg.name}` should be ${!state}, but it is $state")
}
}
// `cargoEnabledFeatures` are not source of truth here when `RsExperiments.FETCH_ACTUAL_STDLIB_METADATA` is enabled
// because only `test` crate is considered as part of workspace where all features are enabled by default (see comment above).
// As a result, state of stdlib dependencies can differ from `cargoEnabledFeatures`.
// Skip check here for now
STDLIB_DEPENDENCY -> Unit
else -> {
if (feature in enabledByCargo != state.isEnabled) {
error("Feature `${feature.name}` in package `${feature.pkg.name}` should be ${!state}, but it is $state")
}
}
}
}
}
@TestOnly
override fun withImplicitDependency(pkgToAdd: CargoWorkspaceData.Package): CargoWorkspace {
val newPackagesData = packages.map { it.asPackageData() } + listOf(pkgToAdd)
val result = WorkspaceImpl(
manifestPath,
workspaceRootUrl,
newPackagesData,
cfgOptions,
cargoConfig,
featuresState
)
run {
@Suppress("DuplicatedCode")
val oldIdToPackage = packages.associateBy { it.id }
val newIdToPackage = result.packages.associateBy { it.id }
val stdlibDependencies = result.packages.filter { it.origin == STDLIB }
.map { DependencyImpl(it, depKinds = listOf(CargoWorkspace.DepKindInfo(CargoWorkspace.DepKind.Stdlib))) }
val pkgToAddDependency = DependencyImpl(
result.packages.find { it.id == pkgToAdd.id }!!,
depKinds = listOf(CargoWorkspace.DepKindInfo(CargoWorkspace.DepKind.Stdlib))
)
newIdToPackage.forEach { (id, pkg) ->
if (id == pkgToAdd.id) {
pkg.dependencies.addAll(stdlibDependencies)
} else {
pkg.dependencies.addAll(oldIdToPackage[id]?.dependencies.orEmpty().mapNotNull { dep ->
val dependencyPackage = newIdToPackage[dep.pkg.id] ?: return@mapNotNull null
dep.withPackage(dependencyPackage)
})
pkg.dependencies.add(pkgToAddDependency)
}
}
}
return result
}
@TestOnly
override fun withEdition(edition: CargoWorkspace.Edition): CargoWorkspace = WorkspaceImpl(
manifestPath,
workspaceRootUrl,
packages.map { pkg ->
val packageEdition = if (pkg.origin == STDLIB || pkg.origin == STDLIB_DEPENDENCY) pkg.edition else edition
pkg.asPackageData(packageEdition)
},
cfgOptions,
cargoConfig,
featuresState
).withDependenciesOf(this)
@TestOnly
override fun withCfgOptions(cfgOptions: CfgOptions): CargoWorkspace = WorkspaceImpl(
manifestPath,
workspaceRootUrl,
packages.map { it.asPackageData() },
cfgOptions,
cargoConfig,
featuresState
).withDependenciesOf(this)
@TestOnly
override fun withCargoFeatures(features: Map<PackageFeature, List<FeatureDep>>): CargoWorkspace {
val packageToFeatures = features.entries
.groupBy { it.key.pkg }
.mapValues { (_, v) -> v.associate { it.key.name to it.value } }
return WorkspaceImpl(
manifestPath,
workspaceRootUrl,
packages.map { it.asPackageData().copy(features = packageToFeatures[it].orEmpty(), enabledFeatures = packageToFeatures[it].orEmpty().keys) },
cfgOptions,
cargoConfig,
featuresState
).withDependenciesOf(this).withDisabledFeatures(UserDisabledFeatures.EMPTY)
}
override fun toString(): String {
val pkgs = packages.joinToString(separator = "") { " $it,\n" }
return "Workspace(packages=[\n$pkgs])"
}
companion object {
fun deserialize(
manifestPath: Path,
data: CargoWorkspaceData,
cfgOptions: CfgOptions,
cargoConfig: CargoConfig,
): WorkspaceImpl {
// Packages form mostly a DAG. "Why mostly?", you say.
// Well, a dev-dependency `X` of package `P` can depend on the `P` itself.
// This is ok, because cargo can compile `P` (without `X`, because dev-deps
// are used only for tests), then `X`, and then `P`s tests. So we need to
// handle cycles here.
val result = WorkspaceImpl(
manifestPath,
data.workspaceRootUrl,
data.packages,
cfgOptions,
cargoConfig,
emptyMap()
)
// Fill package dependencies
run {
val idToPackage = result.packages.associateBy { it.id }
idToPackage.forEach { (_, pkg) -> pkg.addDependencies(data, idToPackage) }
}
return result
}
}
}
private class PackageImpl(
override val workspace: WorkspaceImpl,
override val id: PackageId,
// Note: In tests, we use in-memory file system,
// so we can't use `Path` here.
val contentRootUrl: String,
override val name: String,
override val version: String,
targetsData: Collection<CargoWorkspaceData.Target>,
override val source: String?,
override var origin: PackageOrigin,
override val edition: CargoWorkspace.Edition,
override val cfgOptions: CfgOptions?,
/** See [org.rust.cargo.toolchain.impl.CargoMetadata.Package.features] */
val rawFeatures: Map<FeatureName, List<FeatureDep>>,
val cargoEnabledFeatures: Set<FeatureName>,
override val env: Map<String, String>,
val outDirUrl: String?,
override val procMacroArtifact: CargoWorkspaceData.ProcMacroArtifact?,
) : UserDataHolderBase(), CargoWorkspace.Package {
override val targets = targetsData.map {
TargetImpl(
this,
crateRootUrl = it.crateRootUrl,
name = it.name,
kind = it.kind,
edition = it.edition,
doctest = it.doctest,
requiredFeatures = it.requiredFeatures
)
}
override val contentRoot: VirtualFile? by CachedVirtualFile(contentRootUrl)
override val rootDirectory: Path
get() = Paths.get(VirtualFileManager.extractPath(contentRootUrl))
override val dependencies: MutableList<DependencyImpl> = ArrayList()
override val outDir: VirtualFile? by CachedVirtualFile(outDirUrl)
override val features: Set<PackageFeature> = rawFeatures.keys.mapToSet { PackageFeature(this, it) }
override val featureState: Map<FeatureName, FeatureState>
get() = workspace.featuresState[rootDirectory] ?: emptyMap()
override fun toString() = "Package(name='$name', contentRootUrl='$contentRootUrl', outDirUrl='$outDirUrl')"
}
private fun PackageImpl.addDependencies(workspaceData: CargoWorkspaceData, packagesMap: Map<PackageId, PackageImpl>) {
val pkgDeps = workspaceData.dependencies[id].orEmpty()
val pkgRawDeps = workspaceData.rawDependencies[id].orEmpty()
dependencies += pkgDeps.mapNotNull { dep ->
val dependencyPackage = packagesMap[dep.id] ?: return@mapNotNull null
val depTargetName = dependencyPackage.libTarget?.normName ?: dependencyPackage.normName
val depName = dep.name ?: depTargetName
val rename = if (depName != depTargetName) depName else null
// There can be multiple appropriate raw dependencies because a dependency can be mentioned
// in `Cargo.toml` in different sections, e.g. [dev-dependencies] and [build-dependencies]
val rawDeps = pkgRawDeps.filter { rawDep ->
rawDep.name == dependencyPackage.name && rawDep.rename?.replace('-', '_') == rename && dep.depKinds.any {
it.kind == CargoWorkspace.DepKind.Unclassified ||
it.target == rawDep.target && it.kind.cargoName == rawDep.kind
}
}
DependencyImpl(
dependencyPackage,
depName,
dep.depKinds,
rawDeps.any { it.optional },
rawDeps.any { it.uses_default_features },
rawDeps.flatMap { it.features }.toSet(),
rawDeps.firstOrNull()?.rename ?: dependencyPackage.name
)
}
}
private class TargetImpl(
override val pkg: PackageImpl,
val crateRootUrl: String,
override val name: String,
override val kind: CargoWorkspace.TargetKind,
override val edition: CargoWorkspace.Edition,
override val doctest: Boolean,
override val requiredFeatures: List<FeatureName>
) : CargoWorkspace.Target {
override val crateRoot: VirtualFile? by CachedVirtualFile(crateRootUrl)
override val cfgOptions: CfgOptions = pkg.workspace.cfgOptions + (pkg.cfgOptions ?: CfgOptions.EMPTY) +
// https://doc.rust-lang.org/reference/conditional-compilation.html#proc_macro
if (kind.isProcMacro) CfgOptions(emptyMap(), setOf("proc_macro")) else CfgOptions.EMPTY
override fun toString(): String = "Target(name='$name', kind=$kind, crateRootUrl='$crateRootUrl')"
}
private class DependencyImpl(
override val pkg: PackageImpl,
override val name: String = pkg.libTarget?.normName ?: pkg.normName,
override val depKinds: List<CargoWorkspace.DepKindInfo>,
val isOptional: Boolean = false,
val areDefaultFeaturesEnabled: Boolean = true,
override val requiredFeatures: Set<String> = emptySet(),
override val cargoFeatureDependencyPackageName: String = if (name == pkg.libTarget?.normName) pkg.name else name
) : CargoWorkspace.Dependency {
fun withPackage(newPkg: PackageImpl): DependencyImpl =
DependencyImpl(
newPkg,
name,
depKinds,
isOptional,
areDefaultFeaturesEnabled,
requiredFeatures,
cargoFeatureDependencyPackageName
)
override fun toString(): String = name
}
/**
* A way to add additional (indexable) source roots for a package.
* These hacks are needed for the stdlib that has a weird source structure.
*/
fun CargoWorkspace.Package.additionalRoots(): List<VirtualFile> {
return if (origin == STDLIB) {
when (name) {
STD -> listOfNotNull(contentRoot?.parent?.findFileByRelativePath("backtrace"))
CORE -> contentRoot?.parent?.let {
listOfNotNull(
it.findFileByRelativePath("stdarch/crates/core_arch"),
it.findFileByRelativePath("stdarch/crates/std_detect"),
it.findFileByRelativePath("portable-simd/crates/core_simd"),
it.findFileByRelativePath("portable-simd/crates/std_float"),
)
} ?: emptyList()
else -> emptyList()
}
} else {
emptyList()
}
}
private fun PackageImpl.asPackageData(edition: CargoWorkspace.Edition? = null): CargoWorkspaceData.Package =
CargoWorkspaceData.Package(
id = id,
contentRootUrl = contentRootUrl,
name = name,
version = version,
targets = targets.map {
CargoWorkspaceData.Target(
crateRootUrl = it.crateRootUrl,
name = it.name,
kind = it.kind,
edition = edition ?: it.edition,
doctest = it.doctest,
requiredFeatures = it.requiredFeatures
)
},
source = source,
origin = origin,
edition = edition ?: this.edition,
features = rawFeatures,
enabledFeatures = cargoEnabledFeatures,
cfgOptions = cfgOptions,
env = env,
outDirUrl = outDirUrl,
procMacroArtifact = procMacroArtifact
)
| mit | 359c1fdb6b45a53d8d4bd905194edf11 | 39.037275 | 153 | 0.61254 | 4.886884 | false | false | false | false |
google/dokka | core/testdata/format/typeAliases.kt | 3 | 290 |
class A
class B
class C<T>
typealias D = A
typealias E = D
typealias F = (A) -> B
typealias G = C<A>
typealias H<T> = C<T>
typealias I<T> = H<T>
typealias J = H<A>
typealias K = H<J>
typealias L = (K, B) -> J
/**
* Documented
*/
typealias M = A
@Deprecated("!!!")
typealias N = A | apache-2.0 | 912ee606bbe1fdbeab2473db46a22531 | 9.777778 | 25 | 0.586207 | 2.436975 | false | false | false | false |
androidx/androidx | slidingpanelayout/slidingpanelayout/src/androidTest/java/androidx/slidingpanelayout/widget/helpers/Espresso.kt | 3 | 2802 | /*
* 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.slidingpanelayout.widget.helpers
import android.view.View
import androidx.slidingpanelayout.widget.SlidingPaneLayout
import androidx.test.espresso.UiController
import androidx.test.espresso.ViewAction
import androidx.test.espresso.action.GeneralLocation
import androidx.test.espresso.action.GeneralSwipeAction
import androidx.test.espresso.action.Press
import androidx.test.espresso.action.Swipe
import androidx.test.espresso.action.ViewActions
import androidx.test.espresso.matcher.ViewMatchers
import org.hamcrest.Description
import org.hamcrest.Matcher
import org.hamcrest.TypeSafeMatcher
fun slideClose(): ViewAction? {
return ViewActions.actionWithAssertions(
GeneralSwipeAction(
Swipe.FAST,
GeneralLocation.CENTER_LEFT,
GeneralLocation.CENTER_RIGHT,
Press.FINGER
)
)
}
fun slideOpen(): ViewAction? {
return ViewActions.actionWithAssertions(
GeneralSwipeAction(
Swipe.FAST,
GeneralLocation.CENTER_RIGHT,
GeneralLocation.CENTER_LEFT,
Press.FINGER
)
)
}
fun openPane(): ViewAction {
return object : ViewAction {
override fun getConstraints(): Matcher<View> {
return ViewMatchers.isAssignableFrom(SlidingPaneLayout::class.java)
}
override fun getDescription(): String {
return "Open the list pane"
}
override fun perform(uiController: UiController?, view: View?) {
var slidingPaneLayout: SlidingPaneLayout? = view as? SlidingPaneLayout
if (uiController == null || slidingPaneLayout == null) return
uiController.loopMainThreadUntilIdle()
slidingPaneLayout.openPane()
uiController.loopMainThreadUntilIdle()
}
}
}
fun isTwoPane(): Matcher<View> {
return object : TypeSafeMatcher<View>() {
override fun describeTo(description: Description) {
description.appendText("SlidingPaneLayout should be in two-pane")
}
override fun matchesSafely(item: View?): Boolean {
return !(item as SlidingPaneLayout).isSlideable
}
}
} | apache-2.0 | b02a14a4384fc3a17297a8a03e421e43 | 31.976471 | 82 | 0.700214 | 4.806175 | false | true | false | false |
androidx/androidx | datastore/datastore-preferences/src/main/java/androidx/datastore/preferences/PreferenceDataStoreDelegate.kt | 3 | 4621 | /*
* Copyright 2020 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.datastore.preferences
import android.content.Context
import androidx.annotation.GuardedBy
import androidx.datastore.core.DataMigration
import androidx.datastore.core.DataStore
import androidx.datastore.core.handlers.ReplaceFileCorruptionHandler
import androidx.datastore.preferences.core.PreferenceDataStoreFactory
import androidx.datastore.preferences.core.Preferences
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob
import kotlin.properties.ReadOnlyProperty
import kotlin.reflect.KProperty
/**
* Creates a property delegate for a single process DataStore. This should only be called once
* in a file (at the top level), and all usages of the DataStore should use a reference the same
* Instance. The receiver type for the property delegate must be an instance of [Context].
*
* This should only be used from a single application in a single classloader in a single process.
*
* Example usage:
* ```
* val Context.myDataStore by preferencesDataStore("filename")
*
* class SomeClass(val context: Context) {
* suspend fun update() = context.myDataStore.edit {...}
* }
* ```
*
*
* @param name The name of the preferences. The preferences will be stored in a file in the
* "datastore/" subdirectory in the application context's files directory and is generated using
* [preferencesDataStoreFile].
* @param corruptionHandler The corruptionHandler is invoked if DataStore encounters a
* [androidx.datastore.core.CorruptionException] when attempting to read data. CorruptionExceptions
* are thrown by serializers when data can not be de-serialized.
* @param produceMigrations produce the migrations. The ApplicationContext is passed in to these
* callbacks as a parameter. DataMigrations are run before any access to data can occur. Each
* producer and migration may be run more than once whether or not it already succeeded
* (potentially because another migration failed or a write to disk failed.)
* @param scope The scope in which IO operations and transform functions will execute.
*
* @return a property delegate that manages a datastore as a singleton.
*/
@Suppress("MissingJvmstatic")
public fun preferencesDataStore(
name: String,
corruptionHandler: ReplaceFileCorruptionHandler<Preferences>? = null,
produceMigrations: (Context) -> List<DataMigration<Preferences>> = { listOf() },
scope: CoroutineScope = CoroutineScope(Dispatchers.IO + SupervisorJob())
): ReadOnlyProperty<Context, DataStore<Preferences>> {
return PreferenceDataStoreSingletonDelegate(name, corruptionHandler, produceMigrations, scope)
}
/**
* Delegate class to manage Preferences DataStore as a singleton.
*/
internal class PreferenceDataStoreSingletonDelegate internal constructor(
private val name: String,
private val corruptionHandler: ReplaceFileCorruptionHandler<Preferences>?,
private val produceMigrations: (Context) -> List<DataMigration<Preferences>>,
private val scope: CoroutineScope
) : ReadOnlyProperty<Context, DataStore<Preferences>> {
private val lock = Any()
@GuardedBy("lock")
@Volatile
private var INSTANCE: DataStore<Preferences>? = null
/**
* Gets the instance of the DataStore.
*
* @param thisRef must be an instance of [Context]
* @param property not used
*/
override fun getValue(thisRef: Context, property: KProperty<*>): DataStore<Preferences> {
return INSTANCE ?: synchronized(lock) {
if (INSTANCE == null) {
val applicationContext = thisRef.applicationContext
INSTANCE = PreferenceDataStoreFactory.create(
corruptionHandler = corruptionHandler,
migrations = produceMigrations(applicationContext),
scope = scope
) {
applicationContext.preferencesDataStoreFile(name)
}
}
INSTANCE!!
}
}
} | apache-2.0 | 9028b2d4b30ff4967ffd6d995fb0dee2 | 39.902655 | 99 | 0.737936 | 5.106077 | false | false | false | false |
DemonWav/StatCraft | src/main/kotlin/com/demonwav/statcraft/listeners/FishCaughtListener.kt | 1 | 2747 | /*
* StatCraft Bukkit Plugin
*
* Copyright (c) 2016 Kyle Wood (DemonWav)
* https://www.demonwav.com
*
* MIT License
*/
package com.demonwav.statcraft.listeners
import com.demonwav.statcraft.StatCraft
import com.demonwav.statcraft.damageValue
import com.demonwav.statcraft.magic.FishCode
import com.demonwav.statcraft.querydsl.QFishCaught
import org.bukkit.Material
import org.bukkit.entity.Item
import org.bukkit.event.EventHandler
import org.bukkit.event.EventPriority
import org.bukkit.event.Listener
import org.bukkit.event.player.PlayerFishEvent
class FishCaughtListener(private val plugin: StatCraft) : Listener {
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
fun onFishCatch(event: PlayerFishEvent) {
if (event.caught == null) {
return
}
val uuid = event.player.uniqueId
val worldName = event.player.world.name
val caught = event.caught
if (caught is Item) {
val itemId = caught.itemStack.typeId.toShort()
val damage = damageValue(itemId, caught.itemStack.data.data.toShort())
val code = when (caught.itemStack.type) {
Material.RAW_FISH ->
FishCode.FISH
Material.BOW,
Material.ENCHANTED_BOOK,
Material.NAME_TAG,
Material.SADDLE,
Material.WATER_LILY ->
FishCode.TREASURE
Material.BOWL,
Material.LEATHER,
Material.LEATHER_BOOTS,
Material.ROTTEN_FLESH,
Material.STICK,
Material.STRING,
Material.POTION,
Material.BONE,
Material.INK_SACK,
Material.TRIPWIRE_HOOK ->
FishCode.JUNK
Material.FISHING_ROD ->
if (caught.itemStack.enchantments.size == 0) {
FishCode.JUNK
} else {
FishCode.TREASURE
}
else ->
FishCode.JUNK
}
plugin.threadManager.schedule<QFishCaught>(
uuid, worldName,
{ f, clause, id, worldId ->
clause.columns(f.id, f.worldId, f.item, f.damage, f.amount)
.values(id, worldId, itemId, damage, code.code, 1).execute()
}, { f, clause, id, worldId ->
clause.where(f.id.eq(id), f.worldId.eq(worldId), f.item.eq(itemId), f.damage.eq(damage), f.type.eq(code.code))
.set(f.amount, f.amount.add(1)).execute()
}
)
}
}
}
| mit | f66a30297e9d628d44e353980c89140e | 31.317647 | 130 | 0.547142 | 4.40931 | false | false | false | false |
googlearchive/android-SliceViewer | app/src/main/java/com/example/android/sliceviewer/ui/ViewModelFactory.kt | 1 | 2441 | /*
* Copyright 2018 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.android.sliceviewer.ui
import android.annotation.SuppressLint
import android.content.Context
import androidx.annotation.VisibleForTesting
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import com.example.android.sliceviewer.domain.LocalUriDataSource
import com.example.android.sliceviewer.domain.UriDataSource
import com.example.android.sliceviewer.ui.list.SliceViewModel
import com.example.android.sliceviewer.ui.single.SingleSliceViewModel
class ViewModelFactory private constructor(
private val uriDataSource: UriDataSource
) : ViewModelProvider.NewInstanceFactory() {
@Suppress("UNCHECKED_CAST")
override fun <T : ViewModel> create(modelClass: Class<T>): T {
if (modelClass.isAssignableFrom(SliceViewModel::class.java)) {
return SliceViewModel(uriDataSource) as T
} else if (modelClass.isAssignableFrom(SingleSliceViewModel::class.java)) {
return SingleSliceViewModel(uriDataSource) as T
}
throw IllegalArgumentException("Unknown ViewModel class: " + modelClass.name)
}
companion object {
@SuppressLint("StaticFieldLeak")
@Volatile private var INSTANCE: ViewModelFactory? = null
fun getInstance(context: Context): ViewModelFactory? {
if (INSTANCE == null) {
synchronized(ViewModelFactory::class.java) {
if (INSTANCE == null) {
val sharedPrefs = context.getSharedPreferences(
LocalUriDataSource.SHARED_PREFS_NAME,
Context.MODE_PRIVATE
)
INSTANCE = ViewModelFactory(LocalUriDataSource(sharedPrefs))
}
}
}
return INSTANCE
}
}
} | apache-2.0 | 445b4e3b4e17f314b4365d02d9f9c2fb | 37.761905 | 85 | 0.680868 | 4.911469 | false | false | false | false |
mvosske/comlink | app/src/main/java/org/tnsfit/dragon/comlink/matrix/NotificationBuilder.kt | 1 | 4354 | package org.tnsfit.dragon.comlink.matrix
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.content.res.Resources
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.Point
import android.support.v4.app.NotificationCompat
import org.tnsfit.dragon.comlink.ComlinkActivity
import org.tnsfit.dragon.comlink.R
import org.tnsfit.dragon.comlink.misc.AppConstants
/**
* @author eric.neidhardt on 17.10.2016.
*/
object ServiceNotification {
val NOTIFICATION_ACTION_DISMISS = "NOTIFICATION_ACTION_DISMISS"
val filter: IntentFilter = IntentFilter().apply {
this.addAction(NOTIFICATION_ACTION_DISMISS)
}
fun buildNotificationServiceNotAlive(context: Context): NotificationCompat.Builder {
val openAppIntent = PendingIntent.getActivity(context,
AppConstants.INTENT_REQUEST_NOTIFICATION_OPEN, Intent(context, ComlinkActivity::class.java), 0)
val startServiceIntent = PendingIntent.getService(context,
AppConstants.INTENT_REQUEST_NOTIFICATION_RESTART_SERVICE, Intent(context, MatrixService::class.java), 0)
val builder = NotificationCompat.Builder(context)
.setContentTitle(context.getString(R.string.matrix_service_notification_title))
.setSmallIcon(R.drawable.ic_notification_matrix_on)
.setContentIntent(openAppIntent)
.setLargeIcon(this.getLargeIcon(context))
.addAction(0, context.getString(R.string.matrix_service_notification_action_restart), startServiceIntent)
val wearableExtender = NotificationCompat.WearableExtender()
.setHintHideIcon(true)
builder.extend(wearableExtender)
return builder
}
fun buildNotificationServiceAlive(context: Context): NotificationCompat.Builder {
val openAppIntent = PendingIntent.getActivity(context,
AppConstants.INTENT_REQUEST_NOTIFICATION_OPEN, Intent(context, ComlinkActivity::class.java), 0)
val deleteIntent = PendingIntent.getBroadcast(context,
AppConstants.INTENT_REQUEST_NOTIFICATION_DISMISS, Intent(NOTIFICATION_ACTION_DISMISS), 0)
val builder = NotificationCompat.Builder(context)
.setContentTitle(context.getString(R.string.matrix_service_notification_title))
.setDeleteIntent(deleteIntent)
.setSmallIcon(R.drawable.ic_notification_matrix_on)
.setContentIntent(openAppIntent)
.setLargeIcon(this.getLargeIcon(context))
.addAction(0, context.getString(R.string.matrix_service_notification_action_shutdown), deleteIntent)
val wearableExtender = NotificationCompat.WearableExtender()
.setHintHideIcon(true)
builder.extend(wearableExtender)
return builder
}
private fun getLargeIcon(context: Context): Bitmap {
val resources = context.resources
val requiredHeight = resources.getDimensionPixelSize(android.R.dimen.notification_large_icon_height)
val requiredWidth = resources.getDimensionPixelSize(android.R.dimen.notification_large_icon_width)
val size = getBitmapSize(resources, R.drawable.ic_notification_large)
val sampleSize = getSampleFactor(size.x, size.y, requiredWidth, requiredHeight)
return getBitmapFromAsset(context, R.drawable.ic_notification_large, sampleSize)
}
private fun getBitmapSize(resources: Resources, drawableId: Int): Point {
val options = BitmapFactory.Options()
options.inJustDecodeBounds = true
BitmapFactory.decodeResource(resources, drawableId, options)
val imageHeight = options.outHeight
val imageWidth = options.outWidth
return Point(imageWidth, imageHeight)
}
private fun getSampleFactor(width: Int, height: Int, requiredWidth: Int, requiredHeight: Int): Int {
var inSampleSize = 1
if (height > requiredHeight || width > requiredWidth) {
val halfHeight = height / 2
val halfWidth = width / 2
// Calculate the largest inSampleSize value that is a power of 2 and keeps both
// height and width larger than the requested height and width.
while ((halfHeight / inSampleSize) >= requiredHeight && (halfWidth / inSampleSize) >= requiredWidth)
inSampleSize *= 2
}
return inSampleSize
}
private fun getBitmapFromAsset(context: Context, drawableId: Int, scaleFactor: Int): Bitmap
{
val options = BitmapFactory.Options()
options.inSampleSize = scaleFactor
options.inJustDecodeBounds = false
return BitmapFactory.decodeResource(context.resources, drawableId, options)
}
} | gpl-3.0 | 1ab97936cc7b9dfaeb94592d40cfb4ee | 38.234234 | 109 | 0.791456 | 4.13093 | false | false | false | false |
kenrube/Fantlab-client | app/src/main/kotlin/ru/fantlab/android/ui/modules/edition/overview/EditionOverviewPresenter.kt | 2 | 4999 | package ru.fantlab.android.ui.modules.edition.overview
import android.os.Bundle
import io.reactivex.Single
import io.reactivex.functions.Consumer
import ru.fantlab.android.data.dao.model.*
import ru.fantlab.android.data.dao.response.BookcaseInclusionResponse
import ru.fantlab.android.data.dao.response.BookcaseItemIncludedResponse
import ru.fantlab.android.data.dao.response.EditionResponse
import ru.fantlab.android.helper.BundleConstant
import ru.fantlab.android.provider.rest.DataManager
import ru.fantlab.android.provider.rest.getBookcaseInclusionsPath
import ru.fantlab.android.provider.rest.getEditionPath
import ru.fantlab.android.provider.storage.DbProvider
import ru.fantlab.android.ui.base.mvp.presenter.BasePresenter
class EditionOverviewPresenter : BasePresenter<EditionOverviewMvp.View>(),
EditionOverviewMvp.Presenter {
private var editionId: Int = -1
override fun onFragmentCreated(bundle: Bundle) {
editionId = bundle.getInt(BundleConstant.EXTRA)
makeRestCall(
getEditionInternal(editionId).toObservable(),
Consumer { (edition, additionalImages) ->
sendToView { it.onInitViews(edition, additionalImages) }
}
)
getContent()
}
private fun getEditionInternal(editionId: Int) =
getEditionFromServer(editionId)
.onErrorResumeNext {
getEditionFromDb(editionId)
}
.onErrorResumeNext { ext -> Single.error(ext) }
.doOnError { err -> sendToView { it.onShowErrorView(err.message) } }
private fun getEditionFromServer(editionId: Int): Single<Pair<Edition, AdditionalImages?>> =
DataManager.getEdition(editionId, showAdditionalImages = true)
.map { getEdition(it) }
private fun getEditionFromDb(editionId: Int): Single<Pair<Edition, AdditionalImages?>> =
DbProvider.mainDatabase
.responseDao()
.get(getEditionPath(editionId, showAdditionalImages = true))
.map { it.response }
.map { EditionResponse.Deserializer().deserialize(it) }
.map { getEdition(it) }
private fun getEdition(response: EditionResponse): Pair<Edition, AdditionalImages?> =
response.edition to response.additionalImages
private fun getContent() {
makeRestCall(
getContentInternal().toObservable(),
Consumer { content -> sendToView { it.onSetContent(content) } }
)
}
private fun getContentInternal() =
getContentFromServer()
.onErrorResumeNext {
getContentFromDb()
}
private fun getContentFromServer(): Single<ArrayList<EditionContent>> =
DataManager.getEdition(editionId, true)
.map { getContent(it) }
private fun getContentFromDb(): Single<ArrayList<EditionContent>> =
DbProvider.mainDatabase
.responseDao()
.get(getEditionPath(editionId, true))
.map { it.response }
.map { EditionResponse.Deserializer().deserialize(it) }
.map { getContent(it) }
private fun getContent(response: EditionResponse): ArrayList<EditionContent> =
response.editionContent
fun getBookcases(bookcaseType: String, entityId: Int, force: Boolean) {
makeRestCall(
getBookcasesInternal(bookcaseType, entityId, force).toObservable(),
Consumer { bookcasesInclusions ->
sendToView {
val inclusions: ArrayList<BookcaseSelection> = ArrayList()
bookcasesInclusions!!.forEach { inclusions.add(BookcaseSelection(it, it.itemAdded == 1)) }
it.onSetBookcases(inclusions)
it.hideProgress()
}
}
)
}
private fun getBookcasesInternal(bookcaseType: String, entityId: Int, force: Boolean) =
getBookcasesFromServer(bookcaseType, entityId)
.onErrorResumeNext { throwable ->
if (!force) {
getBookcasesFromDb(bookcaseType, entityId)
} else {
throw throwable
}
}
private fun getBookcasesFromServer(bookcaseType: String, entityId: Int): Single<ArrayList<BookcaseInclusion>> =
DataManager.getBookcaseInclusions(bookcaseType, entityId)
.map { getBookcases(it) }
private fun getBookcasesFromDb(bookcaseType: String, entityId: Int): Single<ArrayList<BookcaseInclusion>> =
DbProvider.mainDatabase
.responseDao()
.get(getBookcaseInclusionsPath(bookcaseType, entityId))
.map { it.response }
.map { BookcaseInclusionResponse.Deserializer().deserialize(it) }
.map { getBookcases(it) }
private fun getBookcases(response: BookcaseInclusionResponse): ArrayList<BookcaseInclusion> {
val inclusions = ArrayList<BookcaseInclusion>()
response.items.forEach { inclusions.add(BookcaseInclusion(it.bookcaseId, it.bookcaseName, it.itemAdded, "edition")) }
return inclusions
}
fun includeItem(bookcaseId: Int, entityId: Int, include: Boolean) {
makeRestCall(
DataManager.includeItemToBookcase(bookcaseId, entityId, if (include) "add" else "delete").toObservable(),
Consumer { response ->
val result = BookcaseItemIncludedResponse.Parser().parse(response)
sendToView {
if (result == null) {
it.showErrorMessage(response)
} else {
it.onBookcaseSelectionUpdated(bookcaseId, include)
}
}
}
)
}
} | gpl-3.0 | f7b83200d785a1f2db1c2d342c367d6a | 34.211268 | 119 | 0.739348 | 4.034705 | false | false | false | false |
esofthead/mycollab | mycollab-dao/src/main/java/com/mycollab/db/query/DateParam.kt | 3 | 3950 | /**
* 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.db.query
import com.mycollab.common.i18n.QueryI18nEnum.*
import com.mycollab.core.MyCollabException
import com.mycollab.db.arguments.BetweenValuesSearchField
import com.mycollab.db.arguments.OneValueSearchField
import com.mycollab.db.arguments.SearchField
import java.lang.reflect.Array
import java.time.LocalDate
/**
* @author MyCollab Ltd.
* @since 4.0
*/
class DateParam(id: String, table: String, column: String) : ColumnParam(id, table, column) {
fun buildSearchField(prefixOper: String, compareOper: String, dateValue1: LocalDate, dateValue2: LocalDate): SearchField {
val compareValue = valueOf(compareOper)
return when (compareValue) {
BETWEEN -> buildDateValBetween(prefixOper, dateValue1, dateValue2)
NOT_BETWEEN -> buildDateValNotBetween(prefixOper, dateValue1, dateValue2)
else -> throw MyCollabException("Not support yet")
}
}
fun buildSearchField(prefixOper: String, compareOper: String, dateValue: LocalDate): SearchField {
val compareValue = valueOf(compareOper)
return when (compareValue) {
IS -> buildDateIsEqual(prefixOper, dateValue)
IS_NOT -> buildDateIsNotEqual(prefixOper, dateValue)
BEFORE -> buildDateIsLessThan(prefixOper, dateValue)
AFTER -> buildDateIsGreaterThan(prefixOper, dateValue)
else -> throw MyCollabException("Not support yet")
}
}
private fun buildDateValBetween(oper: String, value1: LocalDate, value2: LocalDate): BetweenValuesSearchField =
BetweenValuesSearchField(oper, "DATE($table.$column) BETWEEN", value1, value2)
private fun buildDateValNotBetween(oper: String, value1: LocalDate, value2: LocalDate): BetweenValuesSearchField =
BetweenValuesSearchField(oper, "DATE($table.$column) NOT BETWEEN", value1, value2)
private fun buildDateIsEqual(oper: String, value: LocalDate): OneValueSearchField =
OneValueSearchField(oper, "DATE($table.$column) = ", value)
private fun buildDateIsNotEqual(oper: String, value: LocalDate): OneValueSearchField =
OneValueSearchField(oper, "DATE($table.$column) <> ", value)
private fun buildDateIsGreaterThan(oper: String, value: LocalDate): OneValueSearchField =
OneValueSearchField(oper, "DATE($table.$column) >= ", value)
private fun buildDateIsLessThan(oper: String, value: LocalDate): OneValueSearchField =
OneValueSearchField(oper, "DATE($table.$column) <= ", value)
companion object {
@JvmField
val OPTIONS = arrayOf(IS, IS_NOT, BEFORE, AFTER, BETWEEN, NOT_BETWEEN)
@JvmStatic
fun inRangeDate(dateParam: DateParam, variableInjector: VariableInjector<*>): SearchField? {
val value = variableInjector.eval()
return if (value != null) {
if (value.javaClass.isArray) {
dateParam.buildSearchField(SearchField.AND, BETWEEN.name, Array.get(value, 0) as LocalDate, Array.get(value, 1) as LocalDate)
} else {
dateParam.buildSearchField(SearchField.AND, BETWEEN.name, value as LocalDate)
}
} else null
}
}
}
| agpl-3.0 | 3f890580e7e67ad7426ab91c76d8e0a3 | 43.875 | 145 | 0.694606 | 4.382908 | false | false | false | false |
y2k/JoyReactor | core/src/main/kotlin/y2k/joyreactor/services/LifeCycleService.kt | 1 | 1382 | package y2k.joyreactor.services
import java.util.*
import kotlin.reflect.KClass
/**
* Created by y2k on 2/3/16.
*/
class LifeCycleService(
private val broadcastService: BroadcastService) {
private val actions = ArrayList<Pair<Any?, () -> Unit>>()
private var isActivated = false
fun register(func: () -> Unit) {
actions.add(null to func)
}
inline fun <reified T : Any> register(noinline func: (T) -> Unit) {
return register(T::class, func)
}
fun <T : Any> register(token: KClass<out T>, func: (T) -> Unit) {
actions.add(null to { broadcastService.register(this, token.java, func) })
}
operator fun invoke(token: Any, func: () -> Unit) = scope(token, func)
fun scope(token: Any, func: () -> Unit) {
val old = actions.firstOrNull { it.first == token }
if (old != null) {
old.first?.let { broadcastService.unregisterToken(it) }
actions.remove(old)
}
val onActivated = {
broadcastService.register<Any>(this, token, { func() })
func()
}
actions.add(token to onActivated)
if (isActivated) onActivated()
}
fun activate() {
isActivated = true
actions.forEach { it.second() }
}
fun deactivate() {
broadcastService.unregister(this)
isActivated = false
}
} | gpl-2.0 | 284942d6f4a9a2ebb3fb3e018854a5fc | 25.09434 | 82 | 0.58466 | 3.903955 | false | false | false | false |
westnordost/StreetComplete | app/src/main/java/de/westnordost/streetcomplete/quests/opening_hours/model/Months.kt | 1 | 2339 | package de.westnordost.streetcomplete.quests.opening_hours.model
import java.text.DateFormatSymbols
class Months {
private val data = BooleanArray(MONTHS_COUNT)
val selection: BooleanArray get() = data.copyOf()
constructor()
constructor(selection: BooleanArray) {
var i = 0
while (i < selection.size && i < data.size) {
data[i] = selection[i]
++i
}
}
fun isSelectionEmpty() = data.all { !it }
override fun toString() = toStringUsing(OSM_ABBR_MONTHS, ",", "-")
fun toLocalizedString() = toStringUsing(getNames(), ", ", "–")
fun toStringUsing(names: Array<String>, separator: String, range: String): String {
return toCircularSections().joinToString(separator) { section ->
if (section.start == section.end) {
names[section.start]
} else {
names[section.start] + range + names[section.end]
}
}
}
fun toCircularSections(): List<CircularSection> {
val result = mutableListOf<CircularSection>()
var currentStart: Int? = null
for (i in 0 until MONTHS_COUNT) {
if (currentStart == null) {
if (data[i]) currentStart = i
} else {
if (!data[i]) {
result.add(CircularSection(currentStart, i - 1))
currentStart = null
}
}
}
if (currentStart != null) {
result.add(CircularSection(currentStart, MONTHS_COUNT-1))
}
return MONTHS_NUMBER_SYSTEM.merged(result)
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other !is Months) return false
return data.contentEquals(other.data)
}
override fun hashCode() = data.contentHashCode()
companion object {
const val MONTHS_COUNT = 12
val OSM_ABBR_MONTHS = arrayOf("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec")
val MONTHS_NUMBER_SYSTEM = NumberSystem(0, MONTHS_COUNT-1)
fun getNames(): Array<String> {
val symbols = DateFormatSymbols.getInstance()
val result = symbols.months.copyOf(MONTHS_COUNT)
return result.requireNoNulls()
}
}
} | gpl-3.0 | 6e4d5d62cc77b1a29855d6bfb4af2dc8 | 29.363636 | 121 | 0.564399 | 4.264599 | false | false | false | false |
Heiner1/AndroidAPS | wear/src/main/java/info/nightscout/androidaps/interaction/actions/TempTargetActivity.kt | 1 | 5709 | @file:Suppress("DEPRECATION")
package info.nightscout.androidaps.interaction.actions
import android.os.Bundle
import android.support.wearable.view.GridPagerAdapter
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import info.nightscout.androidaps.R
import info.nightscout.androidaps.events.EventWearToMobile
import info.nightscout.androidaps.interaction.utils.EditPlusMinusViewAdapter
import info.nightscout.androidaps.interaction.utils.PlusMinusEditText
import info.nightscout.shared.SafeParse
import info.nightscout.shared.weardata.EventData.ActionTempTargetPreCheck
import java.text.DecimalFormat
class TempTargetActivity : ViewSelectorActivity() {
var lowRange: PlusMinusEditText? = null
var highRange: PlusMinusEditText? = null
var time: PlusMinusEditText? = null
var isMGDL = false
var isSingleTarget = false
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setAdapter(MyGridViewPagerAdapter())
isMGDL = sp.getBoolean(R.string.key_units_mgdl, true)
isSingleTarget = sp.getBoolean(R.string.key_single_target, true)
}
override fun onPause() {
super.onPause()
finish()
}
private inner class MyGridViewPagerAdapter : GridPagerAdapter() {
override fun getColumnCount(arg0: Int): Int {
return if (isSingleTarget) 3 else 4
}
override fun getRowCount(): Int {
return 1
}
override fun instantiateItem(container: ViewGroup, row: Int, col: Int): View = when {
col == 0 -> {
val viewAdapter = EditPlusMinusViewAdapter.getViewAdapter(sp, applicationContext, container, false)
val view = viewAdapter.root
val initValue = SafeParse.stringToDouble(time?.editText?.text.toString(), 60.0)
time = PlusMinusEditText(viewAdapter, initValue, 0.0, 24 * 60.0, 5.0, DecimalFormat("0"), false, getString(R.string.action_duration))
container.addView(view)
view.requestFocus()
view
}
col == 1 -> {
val viewAdapter = EditPlusMinusViewAdapter.getViewAdapter(sp, applicationContext, container, false)
val view = viewAdapter.root
val title = if (isSingleTarget) getString(R.string.action_target) else getString(R.string.action_low)
if (isMGDL) {
var initValue = SafeParse.stringToDouble(lowRange?.editText?.text.toString(), 100.0)
lowRange = PlusMinusEditText(viewAdapter, initValue, 72.0, 180.0, 1.0, DecimalFormat("0"), false, title)
} else {
var initValue = SafeParse.stringToDouble(lowRange?.editText?.text.toString(), 5.5)
lowRange = PlusMinusEditText(viewAdapter, initValue, 4.0, 10.0, 0.1, DecimalFormat("#0.0"), false, title)
}
container.addView(view)
view
}
col == 2 && !isSingleTarget -> {
val viewAdapter = EditPlusMinusViewAdapter.getViewAdapter(sp, applicationContext, container, false)
val view = viewAdapter.root
if (isMGDL) {
var initValue = SafeParse.stringToDouble(highRange?.editText?.text.toString(), 100.0)
highRange = PlusMinusEditText(viewAdapter, initValue, 72.0, 180.0, 1.0, DecimalFormat("0"), false, getString(R.string.action_high))
} else {
var initValue = SafeParse.stringToDouble(highRange?.editText?.text.toString(), 5.5)
highRange = PlusMinusEditText(viewAdapter, initValue, 4.0, 10.0, 0.1, DecimalFormat("#0.0"), false, getString(R.string.action_high))
}
container.addView(view)
view
}
else -> {
val view = LayoutInflater.from(applicationContext).inflate(R.layout.action_confirm_ok, container, false)
val confirmButton = view.findViewById<ImageView>(R.id.confirmbutton)
confirmButton.setOnClickListener {
// check if it can happen that the fragment is never created that hold data?
// (you have to swipe past them anyways - but still)
val action = ActionTempTargetPreCheck(
ActionTempTargetPreCheck.TempTargetCommand.MANUAL,
isMGDL,
SafeParse.stringToInt(time?.editText?.text.toString()),
SafeParse.stringToDouble(lowRange?.editText?.text.toString()),
if (isSingleTarget) SafeParse.stringToDouble(lowRange?.editText?.text.toString()) else SafeParse.stringToDouble(highRange?.editText?.text.toString())
)
rxBus.send(EventWearToMobile(action))
showToast(this@TempTargetActivity, R.string.action_tempt_confirmation)
finishAffinity()
}
container.addView(view)
view
}
}
override fun destroyItem(container: ViewGroup, row: Int, col: Int, view: Any) {
// Handle this to get the data before the view is destroyed?
// Object should still be kept by this, just setup for re-init?
container.removeView(view as View)
}
override fun isViewFromObject(view: View, `object`: Any): Boolean {
return view === `object`
}
}
}
| agpl-3.0 | 7ccb46fbc950f0fe2bc84b5252f9a1d2 | 46.181818 | 173 | 0.612191 | 4.862862 | false | false | false | false |
szaboa/ShowTrackerMVP | app/src/main/java/com/cdev/showtracker/ui/category/CategoryFragment.kt | 1 | 3188 | package com.cdev.showtracker.ui.category
import android.os.Bundle
import android.support.v4.app.ActivityOptionsCompat
import android.support.v4.app.Fragment
import android.support.v4.view.ViewCompat
import android.view.LayoutInflater
import android.view.View
import android.view.View.GONE
import android.view.View.VISIBLE
import android.view.ViewGroup
import com.cdev.showtracker.BaseApplication
import com.cdev.showtracker.R
import com.cdev.showtracker.ui.details.DetailsActivity
import com.cdev.showtracker.model.Category
import com.cdev.showtracker.util.snack
import kotlinx.android.synthetic.main.fragment_category.*
import javax.inject.Inject
class CategoryFragment : Fragment(), CategoryContract.View {
@Inject
lateinit var presenter: CategoryPresenter
lateinit var transitionSourceView: View
companion object {
fun newInstance(): CategoryFragment {
return CategoryFragment()
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
DaggerCategoryComponent.builder()
.tvShowRepositoryComponent(BaseApplication.tvShowRepositoryComponent)
.categoryPresenterModule(CategoryPresenterModule()).build()
.inject(this)
}
override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View? {
return inflater?.inflate(R.layout.fragment_category, container, false)
}
override fun onResume() {
super.onResume()
presenter.attachView(this)
}
override fun onViewCreated(view: View?, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
presenter.loadCategories()
}
override fun showCategories(listOfCategories: List<Category>) {
for (category in listOfCategories) {
val categoryViewGroup: CategoryViewGroup = CategoryViewGroup(container.context)
categoryViewGroup.setData(category)
categoryViewGroup.setOnItemSelectionListener { view, tvShow ->
this.transitionSourceView = view
presenter.tvShowSelected(tvShow)
}
container.addView(categoryViewGroup)
}
}
override fun startTvShowDetailScreen(posterPath: String?, tvShowId: Int) {
val intent = DetailsActivity.createIntent(context, tvShowId, posterPath, ViewCompat.getTransitionName(transitionSourceView))
val options = ActivityOptionsCompat.makeSceneTransitionAnimation(activity, transitionSourceView, ViewCompat.getTransitionName(transitionSourceView))
startActivity(intent, options.toBundle())
}
override fun showEmptyState() {
rootView.snack(getString(R.string.error_something_went_wrong))
}
override fun showError(error: String?) {
rootView.snack(error ?: getString(R.string.error_something_went_wrong))
}
override fun showProgressBar() {
progressBar.visibility = VISIBLE
}
override fun hideProgressBar() {
progressBar.visibility = GONE
}
override fun onStop() {
super.onStop()
presenter.detachView()
}
}
| mit | e45f873a44b0650814d41e45608835a1 | 33.27957 | 156 | 0.716437 | 5.036335 | false | false | false | false |
realm/realm-java | realm/realm-library/src/androidTest/kotlin/io/realm/realmany/DynamicRealmAnyTests.kt | 1 | 13986 | /*
* Copyright 2020 Realm Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.realm.realmany
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.platform.app.InstrumentationRegistry
import io.realm.*
import org.bson.types.Decimal128
import org.bson.types.ObjectId
import org.junit.After
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import org.junit.rules.TemporaryFolder
import org.junit.runner.RunWith
import java.util.*
import kotlin.test.assertEquals
import kotlin.test.assertNotNull
import kotlin.test.assertTrue
@RunWith(AndroidJUnit4::class)
class DynamicRealmAnyTests {
@get:Rule
val configFactory = TestRealmConfigurationFactory()
@Rule
@JvmField
val folder = TemporaryFolder()
private lateinit var realm: DynamicRealm
init {
Realm.init(InstrumentationRegistry.getInstrumentation().targetContext)
}
@Before
fun setUp() {
realm = DynamicRealm.getInstance(configFactory.createConfiguration("RealmAny"))
realm.executeTransaction {
realm.schema
.create("RealmAnyObject")
.addField("myRealmAny", RealmAny::class.java)
realm.schema
.create("RealmAnyListObject")
.addRealmListField("aList", RealmAny::class.java)
realm.schema
.create("ObjectString")
.addField("aString", String::class.java, FieldAttribute.PRIMARY_KEY)
}
}
@After
fun tearDown() {
realm.close()
}
@Test
fun writeRead_primitive() {
realm.beginTransaction()
val anObject = realm.createObject("RealmAnyObject")
anObject.setRealmAny("myRealmAny", RealmAny.valueOf(Date(10)))
realm.commitTransaction()
val myRealmAny = anObject.getRealmAny("myRealmAny")
assertEquals(Date(10), myRealmAny.asDate())
assertEquals(RealmAny.valueOf(Date(10)), myRealmAny)
realm.close()
}
@Test
fun defaultNullValue() {
realm.beginTransaction()
val anObject = realm.createObject("RealmAnyObject")
realm.commitTransaction()
val myRealmAny = anObject.getRealmAny("myRealmAny")
assertNotNull(myRealmAny)
assertTrue(myRealmAny.isNull)
assertEquals(RealmAny.nullValue(), myRealmAny)
assertEquals(RealmAny.Type.NULL, myRealmAny.type)
}
@Test
fun setNullValue() {
realm.beginTransaction()
val anObject = realm.createObject("RealmAnyObject")
anObject.setRealmAny("myRealmAny", RealmAny.nullValue())
realm.commitTransaction()
val myRealmAny = anObject.getRealmAny("myRealmAny")
assertTrue(myRealmAny.isNull)
assertEquals(RealmAny.Type.NULL, myRealmAny.type)
}
@Test
fun writeRead_model() {
realm.beginTransaction()
val innerObject = realm.createObject("RealmAnyObject")
innerObject.setRealmAny("myRealmAny", RealmAny.valueOf(Date(10)))
val outerObject = realm.createObject("RealmAnyObject")
outerObject.setRealmAny("myRealmAny", RealmAny.valueOf(innerObject))
realm.commitTransaction()
val innerRealmAny = innerObject.getRealmAny("myRealmAny")
val outerRealmAny = outerObject.getRealmAny("myRealmAny")
assertEquals(Date(10), innerRealmAny.asDate())
assertEquals(DynamicRealmObject::class.java, outerRealmAny.valueClass)
val aRealmAny = outerRealmAny
.asRealmModel(DynamicRealmObject::class.java)
.getRealmAny("myRealmAny")
assertEquals(innerRealmAny.asDate(), aRealmAny.asDate())
}
@Test
fun managed_listsAllTypes() {
val aString = "a string"
val byteArray = byteArrayOf(0, 1, 0)
val date = Date()
val objectId = ObjectId()
val decimal128 = Decimal128(1)
val uuid = UUID.randomUUID()
realm.executeTransaction {
val allJavaTypes = it.createObject("RealmAnyListObject")
val realmAnyList = allJavaTypes.getList("aList", RealmAny::class.java)
val dynamicRealmObject = it.createObject("ObjectString", "dynamic")
realmAnyList.add(RealmAny.valueOf(true))
realmAnyList.add(RealmAny.valueOf(1.toByte()))
realmAnyList.add(RealmAny.valueOf(2.toShort()))
realmAnyList.add(RealmAny.valueOf(3.toInt()))
realmAnyList.add(RealmAny.valueOf(4.toLong()))
realmAnyList.add(RealmAny.valueOf(5.toFloat()))
realmAnyList.add(RealmAny.valueOf(6.toDouble()))
realmAnyList.add(RealmAny.valueOf(aString))
realmAnyList.add(RealmAny.valueOf(byteArray))
realmAnyList.add(RealmAny.valueOf(date))
realmAnyList.add(RealmAny.valueOf(objectId))
realmAnyList.add(RealmAny.valueOf(decimal128))
realmAnyList.add(RealmAny.valueOf(uuid))
realmAnyList.add(RealmAny.nullValue())
realmAnyList.add(null)
realmAnyList.add(RealmAny.valueOf(dynamicRealmObject))
}
val allJavaTypes = realm.where("RealmAnyListObject").findFirst()
val realmAnyList = allJavaTypes!!.getList("aList", RealmAny::class.java)
assertEquals(true, realmAnyList[0]!!.asBoolean())
assertEquals(1, realmAnyList[1]!!.asByte())
assertEquals(2, realmAnyList[2]!!.asShort())
assertEquals(3, realmAnyList[3]!!.asInteger())
assertEquals(4, realmAnyList[4]!!.asLong())
assertEquals(5.toFloat(), realmAnyList[5]!!.asFloat())
assertEquals(6.toDouble(), realmAnyList[6]!!.asDouble())
assertEquals(aString, realmAnyList[7]!!.asString())
assertTrue(Arrays.equals(byteArray, realmAnyList[8]!!.asBinary()))
assertEquals(date, realmAnyList[9]!!.asDate())
assertEquals(objectId, realmAnyList[10]!!.asObjectId())
assertEquals(decimal128, realmAnyList[11]!!.asDecimal128())
assertEquals(uuid, realmAnyList[12]!!.asUUID())
assertTrue(realmAnyList[13]!!.isNull)
assertTrue(realmAnyList[14]!!.isNull)
assertEquals("dynamic", realmAnyList[15]!!.asRealmModel(DynamicRealmObject::class.java).getString("aString"))
}
@Test
fun managed_listsInsertAllTypes() {
val aString = "a string"
val byteArray = byteArrayOf(0, 1, 0)
val date = Date()
val objectId = ObjectId()
val decimal128 = Decimal128(1)
val uuid = UUID.randomUUID()
realm.executeTransaction {
val allJavaTypes = it.createObject("RealmAnyListObject")
val realmAnyList = allJavaTypes.getList("aList", RealmAny::class.java)
val dynamicRealmObject = it.createObject("ObjectString", "dynamic")
realmAnyList.add(0, RealmAny.valueOf(true))
realmAnyList.add(0, RealmAny.valueOf(1.toByte()))
realmAnyList.add(0, RealmAny.valueOf(2.toShort()))
realmAnyList.add(0, RealmAny.valueOf(3.toInt()))
realmAnyList.add(0, RealmAny.valueOf(4.toLong()))
realmAnyList.add(0, RealmAny.valueOf(5.toFloat()))
realmAnyList.add(0, RealmAny.valueOf(6.toDouble()))
realmAnyList.add(0, RealmAny.valueOf(aString))
realmAnyList.add(0, RealmAny.valueOf(byteArray))
realmAnyList.add(0, RealmAny.valueOf(date))
realmAnyList.add(0, RealmAny.valueOf(objectId))
realmAnyList.add(0, RealmAny.valueOf(decimal128))
realmAnyList.add(0, RealmAny.valueOf(uuid))
realmAnyList.add(0, RealmAny.nullValue())
realmAnyList.add(0, null)
realmAnyList.add(0, RealmAny.valueOf(dynamicRealmObject))
}
val allJavaTypes = realm.where("RealmAnyListObject").findFirst()
val realmAnyList = allJavaTypes!!.getList("aList", RealmAny::class.java)
assertEquals(true, realmAnyList[15]!!.asBoolean())
assertEquals(1, realmAnyList[14]!!.asByte())
assertEquals(2, realmAnyList[13]!!.asShort())
assertEquals(3, realmAnyList[12]!!.asInteger())
assertEquals(4, realmAnyList[11]!!.asLong())
assertEquals(5.toFloat(), realmAnyList[10]!!.asFloat())
assertEquals(6.toDouble(), realmAnyList[9]!!.asDouble())
assertEquals(aString, realmAnyList[8]!!.asString())
assertTrue(Arrays.equals(byteArray, realmAnyList[7]!!.asBinary()))
assertEquals(date, realmAnyList[6]!!.asDate())
assertEquals(objectId, realmAnyList[5]!!.asObjectId())
assertEquals(decimal128, realmAnyList[4]!!.asDecimal128())
assertEquals(uuid, realmAnyList[3]!!.asUUID())
assertTrue(realmAnyList[2]!!.isNull)
assertTrue(realmAnyList[1]!!.isNull)
assertEquals("dynamic", realmAnyList[0]!!.asRealmModel(DynamicRealmObject::class.java).getString("aString"))
}
@Test
fun managed_listsSetAllTypes() {
val aString = "a string"
val byteArray = byteArrayOf(0, 1, 0)
val date = Date()
val objectId = ObjectId()
val decimal128 = Decimal128(1)
val uuid = UUID.randomUUID()
realm.executeTransaction {
val allJavaTypes = it.createObject("RealmAnyListObject")
val dynamicRealmObject = it.createObject("ObjectString", "dynamic")
val initialList = RealmList<RealmAny>()
initialList.addAll(arrayOfNulls(16))
allJavaTypes.setList("aList", initialList)
val realmAnyList = allJavaTypes.getList("aList", RealmAny::class.java)
realmAnyList[0] = RealmAny.valueOf(true)
realmAnyList[1] = RealmAny.valueOf(1.toByte())
realmAnyList[2] = RealmAny.valueOf(2.toShort())
realmAnyList[3] = RealmAny.valueOf(3.toInt())
realmAnyList[4] = RealmAny.valueOf(4.toLong())
realmAnyList[5] = RealmAny.valueOf(5.toFloat())
realmAnyList[6] = RealmAny.valueOf(6.toDouble())
realmAnyList[7] = RealmAny.valueOf(aString)
realmAnyList[8] = RealmAny.valueOf(byteArray)
realmAnyList[9] = RealmAny.valueOf(date)
realmAnyList[10] = RealmAny.valueOf(objectId)
realmAnyList[11] = RealmAny.valueOf(decimal128)
realmAnyList[12] = RealmAny.valueOf(uuid)
realmAnyList[13] = RealmAny.nullValue()
realmAnyList[14] = null
realmAnyList[15] = RealmAny.valueOf(dynamicRealmObject)
}
val allJavaTypes = realm.where("RealmAnyListObject").findFirst()
val realmAnyList = allJavaTypes!!.getList("aList", RealmAny::class.java)
assertEquals(true, realmAnyList[0]!!.asBoolean())
assertEquals(1, realmAnyList[1]!!.asByte())
assertEquals(2, realmAnyList[2]!!.asShort())
assertEquals(3, realmAnyList[3]!!.asInteger())
assertEquals(4, realmAnyList[4]!!.asLong())
assertEquals(5.toFloat(), realmAnyList[5]!!.asFloat())
assertEquals(6.toDouble(), realmAnyList[6]!!.asDouble())
assertEquals(aString, realmAnyList[7]!!.asString())
assertTrue(Arrays.equals(byteArray, realmAnyList[8]!!.asBinary()))
assertEquals(date, realmAnyList[9]!!.asDate())
assertEquals(objectId, realmAnyList[10]!!.asObjectId())
assertEquals(decimal128, realmAnyList[11]!!.asDecimal128())
assertEquals(uuid, realmAnyList[12]!!.asUUID())
assertTrue(realmAnyList[13]!!.isNull)
assertTrue(realmAnyList[14]!!.isNull)
assertEquals("dynamic", realmAnyList[15]!!.asRealmModel(DynamicRealmObject::class.java).getString("aString"))
}
@Test
fun managed_listsRemoveAllTypes() {
val aString = "a string"
val byteArray = byteArrayOf(0, 1, 0)
val date = Date()
val objectId = ObjectId()
val decimal128 = Decimal128(1)
val uuid = UUID.randomUUID()
realm.executeTransaction {
val allJavaTypes = it.createObject("RealmAnyListObject")
val dynamicRealmObject = it.createObject("ObjectString", "dynamic")
val realmAnyList = allJavaTypes.getList("aList", RealmAny::class.java)
realmAnyList.add(RealmAny.valueOf(true))
realmAnyList.add(RealmAny.valueOf(1.toByte()))
realmAnyList.add(RealmAny.valueOf(2.toShort()))
realmAnyList.add(RealmAny.valueOf(3.toInt()))
realmAnyList.add(RealmAny.valueOf(4.toLong()))
realmAnyList.add(RealmAny.valueOf(5.toFloat()))
realmAnyList.add(RealmAny.valueOf(6.toDouble()))
realmAnyList.add(RealmAny.valueOf(aString))
realmAnyList.add(RealmAny.valueOf(byteArray))
realmAnyList.add(RealmAny.valueOf(date))
realmAnyList.add(RealmAny.valueOf(objectId))
realmAnyList.add(RealmAny.valueOf(decimal128))
realmAnyList.add(RealmAny.valueOf(uuid))
realmAnyList.add(RealmAny.nullValue())
realmAnyList.add(null)
realmAnyList.add(RealmAny.valueOf(dynamicRealmObject))
}
realm.executeTransaction {
val allJavaTypes = realm.where("RealmAnyListObject").findFirst()
val realmAnyList = allJavaTypes!!.getList("aList", RealmAny::class.java)
for (i in 0..15)
realmAnyList.removeAt(0)
assertEquals(0, realmAnyList.size)
}
}
}
| apache-2.0 | f3d3b6992cd2bb0b6386c1652a9c145e | 38.176471 | 117 | 0.648649 | 4.527679 | false | false | false | false |
antoniolg/kontacts | app/src/main/java/com/antonioleiva/kontacts/DetailActivity.kt | 1 | 664 | package com.antonioleiva.kontacts
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import kotlinx.android.synthetic.main.activity_detail.*
class DetailActivity : AppCompatActivity() {
companion object {
val EXTRA_NAME = "extraName"
val EXTRA_IMAGE = "extraImage"
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_detail)
val name = intent.getStringExtra(EXTRA_NAME)
supportActionBar?.title = name
contactText.text = name
contactImage.loadUrl(intent.getStringExtra(EXTRA_IMAGE))
}
} | apache-2.0 | c9fef5d3a7e95254350102f9927ac60c | 26.708333 | 64 | 0.712349 | 4.547945 | false | false | false | false |
k9mail/k-9 | app/ui/base/src/main/java/com/fsck/k9/ui/base/KoinModule.kt | 2 | 516 | package com.fsck.k9.ui.base
import com.fsck.k9.ui.base.locale.SystemLocaleManager
import org.koin.core.qualifier.named
import org.koin.dsl.module
val uiBaseModule = module {
single {
ThemeManager(
context = get(),
themeProvider = get(),
generalSettingsManager = get(),
appCoroutineScope = get(named("AppCoroutineScope"))
)
}
single { AppLanguageManager(systemLocaleManager = get()) }
single { SystemLocaleManager(context = get()) }
}
| apache-2.0 | 655df82ae46036737e7b741b545f4a92 | 27.666667 | 63 | 0.647287 | 4.229508 | false | false | false | false |
PolymerLabs/arcs | javatests/arcs/showcase/inline/Writer.kt | 1 | 1508 | @file:Suppress("EXPERIMENTAL_FEATURE_WARNING")
package arcs.showcase.inline
import arcs.jvm.host.TargetHost
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.withContext
@OptIn(ExperimentalCoroutinesApi::class)
@TargetHost(arcs.android.integration.IntegrationHost::class)
class Writer0 : AbstractWriter0() {
private fun MyLevel0.toArcs() = Level0(name)
suspend fun write(item: MyLevel0) = withContext(handles.level0.dispatcher) {
handles.level0.store(item.toArcs())
}
}
@OptIn(ExperimentalCoroutinesApi::class)
@TargetHost(arcs.android.integration.IntegrationHost::class)
class Writer1 : AbstractWriter1() {
private fun MyLevel0.toArcs() = Level0(name)
private suspend fun MyLevel1.toArcs() = Level1(
name = name,
children = children.map { it.toArcs() }.toSet()
)
suspend fun write(item: MyLevel1) = withContext(handles.level1.dispatcher) {
handles.level1.store(item.toArcs())
}
}
@OptIn(ExperimentalCoroutinesApi::class)
@TargetHost(arcs.android.integration.IntegrationHost::class)
class Writer2 : AbstractWriter2() {
private fun MyLevel0.toArcs() = Level0(name)
private suspend fun MyLevel1.toArcs() = Level1(
name = name,
children = children.map { it.toArcs() }.toSet()
)
private suspend fun MyLevel2.toArcs() = Level2(
name = name,
children = children.map { it.toArcs() }.toSet()
)
suspend fun write(item: MyLevel2) = withContext(handles.level2.dispatcher) {
handles.level2.store(item.toArcs())
}
}
| bsd-3-clause | adcd402f4a4b5037cb2db67aa7941b95 | 28 | 78 | 0.738727 | 3.57346 | false | false | false | false |
Maccimo/intellij-community | plugins/git4idea/src/git4idea/search/GitSearchEverywhereContributor.kt | 2 | 8674 | // Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package git4idea.search
import com.intellij.icons.AllIcons
import com.intellij.ide.actions.searcheverywhere.*
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.actionSystem.CommonDataKeys
import com.intellij.openapi.components.service
import com.intellij.openapi.progress.ProgressIndicator
import com.intellij.openapi.project.DumbAware
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.NlsSafe
import com.intellij.openapi.util.registry.Registry
import com.intellij.openapi.vcs.ProjectLevelVcsManager
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.psi.codeStyle.NameUtil
import com.intellij.ui.render.IconCompCompPanel
import com.intellij.util.Processor
import com.intellij.util.text.Matcher
import com.intellij.util.ui.JBUI
import com.intellij.util.ui.UIUtil
import com.intellij.vcs.log.Hash
import com.intellij.vcs.log.VcsCommitMetadata
import com.intellij.vcs.log.VcsRef
import com.intellij.vcs.log.data.DataPack
import com.intellij.vcs.log.data.VcsLogData
import com.intellij.vcs.log.impl.VcsLogContentUtil
import com.intellij.vcs.log.impl.VcsProjectLog
import com.intellij.vcs.log.ui.render.LabelIcon
import com.intellij.vcs.log.util.VcsLogUtil
import com.intellij.vcs.log.util.containsAll
import com.intellij.vcs.log.visible.filters.VcsLogFilterObject
import git4idea.GitVcs
import git4idea.branch.GitBranchUtil
import git4idea.i18n.GitBundle
import git4idea.log.GitRefManager
import git4idea.repo.GitRepositoryManager
import git4idea.search.GitSearchEverywhereItemType.*
import java.awt.Component
import java.util.function.Function
import javax.swing.JLabel
import javax.swing.JList
import javax.swing.ListCellRenderer
internal class GitSearchEverywhereContributor(private val project: Project) : WeightedSearchEverywhereContributor<Any>, DumbAware {
private val filter = PersistentSearchEverywhereContributorFilter(
GitSearchEverywhereItemType.values().asList(),
project.service<GitSearchEverywhereFilterConfiguration>(),
Function { it.displayName },
Function { null }
)
override fun fetchWeightedElements(
pattern: String,
progressIndicator: ProgressIndicator,
consumer: Processor<in FoundItemDescriptor<Any>>
) {
if (!ProjectLevelVcsManager.getInstance(project).checkVcsIsActive(GitVcs.NAME)) return
val logManager = VcsProjectLog.getInstance(project).logManager ?: return
val dataManager = logManager.dataManager
val storage = dataManager.storage
val index = dataManager.index
val dataPack = awaitFullLogDataPack(dataManager, progressIndicator) ?: return
if (filter.isSelected(COMMIT_BY_HASH) && pattern.length >= 7 && VcsLogUtil.HASH_REGEX.matcher(pattern).matches()) {
storage.findCommitId {
progressIndicator.checkCanceled()
it.hash.asString().startsWith(pattern, true) && dataPack.containsAll(listOf(it), storage)
}?.let { commitId ->
val id = storage.getCommitIndex(commitId.hash, commitId.root)
dataManager.miniDetailsGetter.loadCommitsData(listOf(id), {
consumer.process(FoundItemDescriptor(it, COMMIT_BY_HASH.weight))
}, progressIndicator)
}
}
val matcher = NameUtil.buildMatcher("*$pattern")
.withCaseSensitivity(NameUtil.MatchingCaseSensitivity.NONE)
.typoTolerant()
.build()
dataPack.refsModel.stream().forEach {
progressIndicator.checkCanceled()
when (it.type) {
GitRefManager.LOCAL_BRANCH, GitRefManager.HEAD -> processRefOfType(it, LOCAL_BRANCH, matcher, consumer)
GitRefManager.REMOTE_BRANCH -> processRefOfType(it, REMOTE_BRANCH, matcher, consumer)
GitRefManager.TAG -> processRefOfType(it, TAG, matcher, consumer)
}
}
if (filter.isSelected(COMMIT_BY_MESSAGE) && Registry.`is`("git.search.everywhere.commit.by.message")) {
if (pattern.length < 3) return
val allRootsIndexed = GitRepositoryManager.getInstance(project).repositories.all { index.isIndexed(it.root) }
if (!allRootsIndexed) return
index.dataGetter?.filterMessages(VcsLogFilterObject.fromPattern(pattern)) { commitIdx ->
progressIndicator.checkCanceled()
dataManager.miniDetailsGetter.loadCommitsData(listOf(commitIdx), {
consumer.process(FoundItemDescriptor(it, COMMIT_BY_MESSAGE.weight))
}, progressIndicator)
}
}
}
private fun processRefOfType(ref: VcsRef, type: GitSearchEverywhereItemType,
matcher: Matcher, consumer: Processor<in FoundItemDescriptor<Any>>) {
if (!filter.isSelected(type)) return
if (matcher.matches(ref.name)) consumer.process(FoundItemDescriptor(ref, type.weight))
}
private fun awaitFullLogDataPack(dataManager: VcsLogData, indicator: ProgressIndicator): DataPack? {
if (!Registry.`is`("vcs.log.keep.up.to.date")) return null
var dataPack: DataPack
do {
indicator.checkCanceled()
dataPack = dataManager.dataPack
}
while (!dataPack.isFull && Thread.sleep(1000) == Unit)
return dataPack
}
private val renderer = object : ListCellRenderer<Any> {
private val panel = IconCompCompPanel(JLabel(), JLabel()).apply {
border = JBUI.Borders.empty(0, 8)
}
override fun getListCellRendererComponent(
list: JList<out Any>,
value: Any?, index: Int,
isSelected: Boolean, cellHasFocus: Boolean
): Component {
panel.reset()
panel.background = UIUtil.getListBackground(isSelected, cellHasFocus)
panel.setIcon(when (value) {
is VcsRef -> LabelIcon(panel.center, JBUI.scale(16), panel.background, listOf(value.type.backgroundColor))
else -> AllIcons.Vcs.CommitNode
})
panel.center.apply {
font = list.font
text = when (value) {
is VcsRef -> value.name
is VcsCommitMetadata -> value.subject
else -> null
}
foreground = UIUtil.getListForeground(isSelected, cellHasFocus)
}
panel.right.apply {
font = list.font
text = when (value) {
is VcsRef -> getTrackingRemoteBranchName(value)
is VcsCommitMetadata -> value.id.toShortString()
else -> null
}
foreground = if (!isSelected) UIUtil.getInactiveTextColor() else UIUtil.getListForeground(isSelected, cellHasFocus)
}
return panel
}
@NlsSafe
private fun getTrackingRemoteBranchName(vcsRef: VcsRef): String? {
if (vcsRef.type != GitRefManager.LOCAL_BRANCH) {
return null
}
val repository = GitRepositoryManager.getInstance(project).getRepositoryForRootQuick(vcsRef.root) ?: return null
return GitBranchUtil.getTrackInfo(repository, vcsRef.name)?.remoteBranch?.name
}
}
override fun getElementsRenderer(): ListCellRenderer<in Any> = renderer
override fun processSelectedItem(selected: Any, modifiers: Int, searchText: String): Boolean {
val hash: Hash?
val root: VirtualFile?
when (selected) {
is VcsRef -> {
hash = selected.commitHash
root = selected.root
}
is VcsCommitMetadata -> {
hash = selected.id
root = selected.root
}
else -> {
hash = null
root = null
}
}
if (hash != null && root != null) {
VcsLogContentUtil.runInMainLog(project) {
it.vcsLog.jumpToCommit(hash, root)
}
return true
}
return false
}
override fun getActions(onChanged: Runnable) = listOf(SearchEverywhereFiltersAction(filter, onChanged))
override fun getSearchProviderId() = "Vcs.Git"
override fun getGroupName() = GitBundle.message("search.everywhere.group.name")
override fun getFullGroupName() = GitBundle.message("search.everywhere.group.full.name")
// higher weight -> lower position
override fun getSortWeight() = 500
override fun showInFindResults() = false
override fun isShownInSeparateTab(): Boolean {
return ProjectLevelVcsManager.getInstance(project).checkVcsIsActive(GitVcs.NAME) &&
VcsProjectLog.getInstance(project).logManager != null
}
override fun getDataForItem(element: Any, dataId: String): Any? = null
companion object {
class Factory : SearchEverywhereContributorFactory<Any> {
override fun createContributor(initEvent: AnActionEvent): GitSearchEverywhereContributor {
val project = initEvent.getRequiredData(CommonDataKeys.PROJECT)
return GitSearchEverywhereContributor(project)
}
}
}
}
| apache-2.0 | c4fafed4d58419068a1e5351f0d863eb | 37.04386 | 140 | 0.719737 | 4.534239 | false | false | false | false |
Maccimo/intellij-community | platform/xdebugger-impl/src/com/intellij/xdebugger/impl/pinned/items/actions/XDebuggerPinToTopAction.kt | 2 | 3217 | // Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.xdebugger.impl.pinned.items.actions
import com.intellij.openapi.actionSystem.ActionManager
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.actionSystem.CommonDataKeys
import com.intellij.openapi.actionSystem.Presentation
import com.intellij.openapi.actionSystem.impl.SimpleDataContext
import com.intellij.xdebugger.XDebuggerBundle
import com.intellij.xdebugger.impl.XDebuggerUtilImpl
import com.intellij.xdebugger.impl.pinned.items.*
import com.intellij.xdebugger.impl.ui.tree.XDebuggerTree
import com.intellij.xdebugger.impl.ui.tree.actions.XDebuggerTreeActionBase
import com.intellij.xdebugger.impl.ui.tree.nodes.XValueNodeImpl
import icons.PlatformDebuggerImplIcons
import java.awt.event.MouseEvent
class XDebuggerPinToTopAction : XDebuggerTreeActionBase() {
companion object {
fun pinToTopField(event: MouseEvent?, node: XValueNodeImpl) {
ActionManager.getInstance().getAction("XDebugger.PinToTop").actionPerformed(
AnActionEvent.createFromInputEvent(
event,
XDebuggerPinToTopAction::class.java.name,
Presentation(),
SimpleDataContext.builder()
.add(XDebuggerTree.XDEBUGGER_TREE_KEY, node.tree)
.add(CommonDataKeys.PROJECT, node.tree.project)
.build()
)
)
}
}
override fun update(e: AnActionEvent) {
val node = getSelectedNode(e.dataContext)
val valueContainer = node?.valueContainer as? PinToTopMemberValue
val presentation = e.presentation
val project = e.project
if (valueContainer == null || project == null) {
presentation.isEnabledAndVisible = false
return
}
val pinToTopManager = XDebuggerPinToTopManager.getInstance(project)
if (!pinToTopManager.isPinToTopSupported(node)) {
presentation.isEnabledAndVisible = false
return
}
presentation.isVisible = true
presentation.isEnabled = node.canBePinned()
presentation.icon = if (pinToTopManager.isItemPinned(node)) PlatformDebuggerImplIcons.PinToTop.UnpinnedItem else PlatformDebuggerImplIcons.PinToTop.PinnedItem
presentation.text = if (pinToTopManager.isItemPinned(node)) XDebuggerBundle.message("xdebugger.unpin.action") else XDebuggerBundle.message("xdebugger.pin.to.top.action")
}
override fun perform(node: XValueNodeImpl?, nodeName: String, e: AnActionEvent) {
node ?: return
val project = e.project ?: return
if (!node.canBePinned())
return
val pinToTopManager = XDebuggerPinToTopManager.getInstance(project)
val pinInfo = node.getPinInfo()
?: return
if (node.isPinned(pinToTopManager)) {
pinToTopManager.removeItemInfo(pinInfo)
} else {
pinToTopManager.addItemInfo(pinInfo)
}
XDebuggerUtilImpl.rebuildTreeAndViews(node.tree)
}
} | apache-2.0 | 42be90a04f3475aacf6a332cbf492f7a | 39.734177 | 177 | 0.692571 | 4.83033 | false | false | false | false |
Maccimo/intellij-community | platform/diff-impl/src/com/intellij/diff/actions/impl/MutableDiffRequestChain.kt | 1 | 7367 | // Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.diff.actions.impl
import com.intellij.diff.DiffContext
import com.intellij.diff.DiffContextEx
import com.intellij.diff.DiffRequestFactory
import com.intellij.diff.chains.DiffRequestChain
import com.intellij.diff.chains.DiffRequestProducer
import com.intellij.diff.contents.DiffContent
import com.intellij.diff.contents.FileContent
import com.intellij.diff.requests.DiffRequest
import com.intellij.diff.requests.SimpleDiffRequest
import com.intellij.diff.tools.util.DiffDataKeys
import com.intellij.diff.util.DiffUserDataKeys
import com.intellij.diff.util.DiffUserDataKeys.ThreeSideDiffColors
import com.intellij.diff.util.Side
import com.intellij.diff.util.ThreeSide
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.actionSystem.DataContext
import com.intellij.openapi.actionSystem.DefaultActionGroup
import com.intellij.openapi.actionSystem.ex.ComboBoxAction
import com.intellij.openapi.diff.DiffBundle
import com.intellij.openapi.fileTypes.FileType
import com.intellij.openapi.progress.ProgressIndicator
import com.intellij.openapi.project.DumbAwareAction
import com.intellij.openapi.util.Key
import com.intellij.openapi.util.NlsActions
import com.intellij.openapi.util.UserDataHolder
import com.intellij.openapi.util.UserDataHolderBase
import javax.swing.JComponent
class MutableDiffRequestChain(
var content1: DiffContent,
var baseContent: DiffContent?,
var content2: DiffContent
) : UserDataHolderBase(), DiffRequestChain {
private val producer = MyDiffRequestProducer()
private val requestUserData: MutableMap<Key<*>, Any> = mutableMapOf()
var windowTitle: String? = null
var title1: String? = getTitleFor(content1)
var title2: String? = getTitleFor(content2)
var baseTitle: String? = baseContent?.let { getTitleFor(it) }
var baseColorMode: ThreeSideDiffColors = ThreeSideDiffColors.LEFT_TO_RIGHT
constructor(content1: DiffContent, content2: DiffContent) : this(content1, null, content2)
fun <T : Any> putRequestUserData(key: Key<T>, value: T) {
requestUserData.put(key, value)
}
override fun getRequests(): List<DiffRequestProducer> = listOf(producer)
override fun getIndex(): Int = 0
private inner class MyDiffRequestProducer : DiffRequestProducer {
override fun getName(): String {
return DiffBundle.message("diff.files.generic.request.title")
}
override fun getContentType(): FileType? = content1.contentType ?: content2.contentType
override fun process(context: UserDataHolder, indicator: ProgressIndicator): DiffRequest {
val request = if (baseContent != null) {
SimpleDiffRequest(windowTitle, content1, baseContent!!, content2, title1, baseTitle, title2).also {
putUserData(DiffUserDataKeys.THREESIDE_DIFF_COLORS_MODE, baseColorMode)
}
}
else {
SimpleDiffRequest(windowTitle, content1, content2, title1, title2)
}
request.putUserData(CHAIN_KEY, this@MutableDiffRequestChain)
requestUserData.forEach { key, value ->
@Suppress("UNCHECKED_CAST")
request.putUserData(key as Key<Any>, value)
}
return request
}
}
companion object {
private val CHAIN_KEY = Key.create<MutableDiffRequestChain>("Diff.MutableDiffRequestChain")
fun createHelper(context: DiffContext, request: DiffRequest): Helper? {
if (context !is DiffContextEx) return null
val chain = request.getUserData(CHAIN_KEY) ?: return null
return Helper(chain, context)
}
fun createHelper(dataContext: DataContext): Helper? {
val context = dataContext.getData(DiffDataKeys.DIFF_CONTEXT) ?: return null
val request = dataContext.getData(DiffDataKeys.DIFF_REQUEST) ?: return null
return createHelper(context, request)
}
}
data class Helper(val chain: MutableDiffRequestChain, val context: DiffContextEx) {
fun setContent(newContent: DiffContent, side: Side) {
setContent(newContent, getTitleFor(newContent), side)
}
fun setContent(newContent: DiffContent, side: ThreeSide) {
setContent(newContent, getTitleFor(newContent), side)
}
fun setContent(newContent: DiffContent, title: String?, side: Side) {
setContent(newContent, title, side.selectNotNull(ThreeSide.LEFT, ThreeSide.RIGHT))
}
fun setContent(newContent: DiffContent, title: String?, side: ThreeSide) {
when (side) {
ThreeSide.LEFT -> {
chain.content1 = newContent
chain.title1 = title
}
ThreeSide.RIGHT -> {
chain.content2 = newContent
chain.title2 = title
}
ThreeSide.BASE -> {
chain.baseContent = newContent
chain.baseTitle = title
}
}
}
fun fireRequestUpdated() {
chain.requestUserData.clear()
context.reloadDiffRequest()
}
}
}
internal class SwapDiffSidesAction : DumbAwareAction() {
override fun update(e: AnActionEvent) {
val helper = MutableDiffRequestChain.createHelper(e.dataContext)
if (helper == null) {
e.presentation.isEnabledAndVisible = false
return
}
e.presentation.isEnabledAndVisible = helper.chain.baseContent == null
}
override fun actionPerformed(e: AnActionEvent) {
val helper = MutableDiffRequestChain.createHelper(e.dataContext)!!
val oldContent1 = helper.chain.content1
val oldContent2 = helper.chain.content2
val oldTitle1 = helper.chain.title1
val oldTitle2 = helper.chain.title2
helper.setContent(oldContent1, oldTitle1, Side.RIGHT)
helper.setContent(oldContent2, oldTitle2, Side.LEFT)
helper.fireRequestUpdated()
}
}
internal class SwapThreeWayColorModeAction : ComboBoxAction() {
override fun update(e: AnActionEvent) {
val presentation = e.presentation
val helper = MutableDiffRequestChain.createHelper(e.dataContext)
if (helper != null) {
presentation.text = getText(helper.chain.baseColorMode)
presentation.isEnabledAndVisible = true && helper.chain.baseContent != null
}
else {
presentation.isEnabledAndVisible = false
}
}
override fun createPopupActionGroup(button: JComponent?): DefaultActionGroup {
return DefaultActionGroup(ThreeSideDiffColors.values().map { MyAction(getText(it), it) })
}
private fun getText(option: ThreeSideDiffColors): @NlsActions.ActionText String {
return when (option) {
ThreeSideDiffColors.MERGE_CONFLICT -> DiffBundle.message("option.three.side.color.policy.merge.conflict")
ThreeSideDiffColors.MERGE_RESULT -> DiffBundle.message("option.three.side.color.policy.merge.resolved")
ThreeSideDiffColors.LEFT_TO_RIGHT -> DiffBundle.message("option.three.side.color.policy.left.to.right")
}
}
private inner class MyAction(text: @NlsActions.ActionText String, val option: ThreeSideDiffColors) : DumbAwareAction(text) {
override fun actionPerformed(e: AnActionEvent) {
val helper = MutableDiffRequestChain.createHelper(e.dataContext) ?: return
helper.chain.baseColorMode = option
helper.fireRequestUpdated()
}
}
}
private fun getTitleFor(content: DiffContent) =
if (content is FileContent) DiffRequestFactory.getInstance().getContentTitle(content.file) else null
| apache-2.0 | affbbd7e1caf60d0b03c0f7dbf6e1243 | 36.586735 | 140 | 0.740871 | 4.421969 | false | false | false | false |
mdaniel/intellij-community | plugins/kotlin/jvm-debugger/test/test/org/jetbrains/kotlin/idea/debugger/test/AbstractBreakpointApplicabilityTest.kt | 1 | 2727 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.kotlin.idea.debugger.test
import com.intellij.psi.PsiFile
import com.intellij.testFramework.LightProjectDescriptor
import org.jetbrains.kotlin.idea.base.psi.getLineCount
import org.jetbrains.kotlin.idea.base.psi.getLineEndOffset
import org.jetbrains.kotlin.idea.base.psi.getLineStartOffset
import org.jetbrains.kotlin.idea.debugger.breakpoints.BreakpointChecker
import org.jetbrains.kotlin.idea.test.KotlinLightCodeInsightFixtureTestCase
import org.jetbrains.kotlin.idea.test.KotlinTestUtils
import org.jetbrains.kotlin.idea.test.KotlinWithJdkAndRuntimeLightProjectDescriptor
import org.jetbrains.kotlin.psi.KtFile
abstract class AbstractBreakpointApplicabilityTest : KotlinLightCodeInsightFixtureTestCase() {
private companion object {
private const val COMMENT = "///"
}
override fun getProjectDescriptor(): LightProjectDescriptor {
return KotlinWithJdkAndRuntimeLightProjectDescriptor.INSTANCE
}
protected fun doTest(unused: String) {
val ktFile = myFixture.configureByFile(fileName()) as KtFile
val actualContents = checkBreakpoints(ktFile, BreakpointChecker())
KotlinTestUtils.assertEqualsToFile(dataFile(), actualContents)
}
private fun checkBreakpoints(file: KtFile, checker: BreakpointChecker): String {
val lineCount = file.getLineCount()
return (0 until lineCount).joinToString("\n") { line -> checkLine(file, line, checker) }
}
private fun checkLine(file: KtFile, line: Int, checker: BreakpointChecker): String {
val lineText = file.getLine(line)
val expectedBreakpointTypes = lineText.substringAfterLast(COMMENT).trim().split(",").map { it.trim() }.toSortedSet()
val actualBreakpointTypes = checker.check(file, line).map { it.prefix }.distinct().toSortedSet()
return if (expectedBreakpointTypes != actualBreakpointTypes) {
val lineWithoutComments = lineText.substringBeforeLast(COMMENT).trimEnd()
if (actualBreakpointTypes.isNotEmpty()) {
"$lineWithoutComments $COMMENT " + actualBreakpointTypes.joinToString()
} else {
lineWithoutComments
}
} else {
lineText
}
}
private fun PsiFile.getLine(line: Int): String {
val start = getLineStartOffset(line, skipWhitespace = false) ?: error("Cannot find start for line $line")
val end = getLineEndOffset(line) ?: error("Cannot find end for line $line")
if (start >= end) {
return ""
}
return text.substring(start, end)
}
}
| apache-2.0 | 6ed195fe26e2e2d1a934742331f43aa1 | 42.285714 | 124 | 0.715805 | 4.931284 | false | true | false | false |
kelsos/mbrc | app/src/main/kotlin/com/kelsos/mbrc/constants/UserInputEventType.kt | 1 | 449 | package com.kelsos.mbrc.constants
object UserInputEventType {
const val StartConnection = "StartConnection"
const val SettingsChanged = "SettingsChanged"
const val ResetConnection = "ResetConnection"
const val CancelNotification = "CancelNotification"
const val StartDiscovery = "StartDiscovery"
const val KeyVolumeUp = "KeyVolumeUp"
const val KeyVolumeDown = "KeyVolumeDown"
const val TerminateConnection = "TerminateConnection"
}
| gpl-3.0 | 0ae62b60395fdabefd2f6e607f5dee7c | 36.416667 | 55 | 0.7951 | 4.445545 | false | false | false | false |
mdaniel/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/intentions/AddMissingDestructuringIntention.kt | 1 | 1784 | // 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.intentions
import com.intellij.openapi.editor.Editor
import org.jetbrains.kotlin.descriptors.ClassDescriptor
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.caches.resolve.analyze
import org.jetbrains.kotlin.idea.codeinsight.api.classic.intentions.SelfTargetingIntention
import org.jetbrains.kotlin.idea.inspections.IncompleteDestructuringQuickfix
import org.jetbrains.kotlin.psi.KtDestructuringDeclaration
class AddMissingDestructuringIntention : SelfTargetingIntention<KtDestructuringDeclaration>(
KtDestructuringDeclaration::class.java,
KotlinBundle.lazyMessage("add.missing.component")
) {
override fun isApplicableTo(element: KtDestructuringDeclaration, caretOffset: Int): Boolean {
val entriesCount = element.entries.size
val classDescriptor = element.classDescriptor() ?: return false
if (!classDescriptor.isData) return false
val primaryParameters = classDescriptor.primaryParameters() ?: return false
return primaryParameters.size > entriesCount
}
override fun applyTo(element: KtDestructuringDeclaration, editor: Editor?) {
IncompleteDestructuringQuickfix.addMissingEntries(element)
}
private fun KtDestructuringDeclaration.classDescriptor(): ClassDescriptor? {
val type = initializer?.let { it.analyze().getType(it) } ?: return null
return type.constructor.declarationDescriptor as? ClassDescriptor ?: return null
}
private fun ClassDescriptor.primaryParameters() = constructors.firstOrNull { it.isPrimary }?.valueParameters
} | apache-2.0 | d495b507e4ee35efc1650d9058ba6b4b | 47.243243 | 158 | 0.788677 | 5.216374 | false | false | false | false |
ingokegel/intellij-community | plugins/kotlin/gradle/gradle-tooling/src/org/jetbrains/kotlin/idea/gradleTooling/arguments/CompilerArgumentsCacheAwareImpl.kt | 1 | 1328 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.gradleTooling.arguments
import org.gradle.internal.impldep.org.apache.commons.lang.math.RandomUtils
import org.jetbrains.kotlin.idea.projectModel.CompilerArgumentsCacheAware
import kotlin.collections.HashMap
/**
* Abstract compiler arguments cache aware
*
* @constructor Create empty Abstract compiler arguments cache aware
*/
abstract class AbstractCompilerArgumentsCacheAware : CompilerArgumentsCacheAware {
abstract val cacheByValueMap: HashMap<Int, String>
override fun getCached(cacheId: Int): String? = cacheByValueMap[cacheId]
override fun distributeCacheIds(): Iterable<Int> = cacheByValueMap.keys
}
data class CompilerArgumentsCacheAwareImpl(
override val cacheOriginIdentifier: Long = RandomUtils.nextLong(),
override val cacheByValueMap: HashMap<Int, String> = hashMapOf(),
) : AbstractCompilerArgumentsCacheAware() {
constructor(cacheAware: CompilerArgumentsCacheAware) : this(
cacheOriginIdentifier = cacheAware.cacheOriginIdentifier,
cacheByValueMap = HashMap(cacheAware.distributeCacheIds().mapNotNull { id -> cacheAware.getCached(id)?.let { id to it } }.toMap())
)
}
| apache-2.0 | f709e6526c7040cb8dae5aae6d074fca | 46.428571 | 158 | 0.786145 | 4.776978 | false | false | false | false |
sys1yagi/longest-streak-android | app/src/main/java/com/sys1yagi/longeststreakandroid/db/Settings.kt | 1 | 1692 | package com.sys1yagi.longeststreakandroid.db
import com.github.gfx.android.orma.annotation.Column
import com.github.gfx.android.orma.annotation.PrimaryKey
import com.github.gfx.android.orma.annotation.Table
@Table
class Settings {
@PrimaryKey
var id: Long = 0
@Column
lateinit var name: String
@Column
lateinit var email: String
@Column
lateinit var zoneId: String
companion object {
fun alreadyInitialized(database: OrmaDatabase): Boolean {
return database.selectFromSettings().count() > 0
}
fun getRecord(database: OrmaDatabase): Settings {
if (!alreadyInitialized(database)) {
throw IllegalStateException("record not found")
}
return database.selectFromSettings().first()
}
fun getRecordAndAction(database: OrmaDatabase): Pair<Settings, (Settings) -> Settings> {
var settings: Settings?
var saveAction: (Settings) -> Settings
if (!alreadyInitialized(database)) {
settings = Settings()
saveAction = {
database.insertIntoSettings(it)
it
}
} else {
settings = getRecord(database)
saveAction = {
database.updateSettings()
.idEq(it.id)
.name(it.name)
.email(it.email)
.zoneId(it.zoneId)
.execute()
it
}
}
return Pair(settings, saveAction)
}
}
}
| mit | 627e407a22b1f4d5a1447de0f232f95e | 28.172414 | 96 | 0.525414 | 5.2875 | false | false | false | false |
florent37/Flutter-AssetsAudioPlayer | android/src/main/kotlin/com/github/florent37/assets_audio_player/notification/NotificationManager.kt | 1 | 1967 | package com.github.florent37.assets_audio_player.notification
import android.content.Context
import android.content.Intent
import com.github.florent37.assets_audio_player.AssetsAudioPlayerPlugin
class NotificationManager(private val context: Context) {
var closed = false
fun showNotification(playerId: String, audioMetas: AudioMetas, isPlaying: Boolean, notificationSettings: NotificationSettings, stop: Boolean, durationMs: Long) {
try {
if (closed)
return
if (stop) {
stopNotification()
} else {
context.startService(Intent(context, NotificationService::class.java).apply {
putExtra(NotificationService.EXTRA_NOTIFICATION_ACTION, NotificationAction.Show(
isPlaying = isPlaying,
audioMetas = audioMetas,
playerId = playerId,
notificationSettings = notificationSettings,
durationMs = durationMs
))
})
}
AssetsAudioPlayerPlugin.instance?.assetsAudioPlayer?.registerLastPlayerWithNotif(playerId)
} catch (t: Throwable) {
t.printStackTrace()
}
}
fun stopNotification() {
try {
context.startService(Intent(context, NotificationService::class.java).apply {
putExtra(NotificationService.EXTRA_NOTIFICATION_ACTION, NotificationAction.Hide(
))
})
} catch (t: Throwable) {
t.printStackTrace()
}
}
fun hideNotificationService(definitively: Boolean = false) {
try {
//if remainingNotif == 0, stop
context.stopService(Intent(context, NotificationService::class.java))
closed = definitively
} catch (t: Throwable) {
t.printStackTrace()
}
}
} | apache-2.0 | 179e9be0a577ecd939c6743444c9acc8 | 35.444444 | 165 | 0.583122 | 5.62 | false | false | false | false |
GunoH/intellij-community | platform/platform-impl/src/com/intellij/openapi/wm/impl/content/SingleContentSupplier.kt | 2 | 2909 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.openapi.wm.impl.content
import com.intellij.openapi.actionSystem.*
import com.intellij.openapi.util.Key
import com.intellij.ui.content.Content
import com.intellij.ui.tabs.JBTabs
import com.intellij.ui.tabs.TabInfo
import javax.swing.JComponent
import javax.swing.SwingUtilities
/**
* Describes tabs and toolbar for the [SingleContentLayout].
*/
interface SingleContentSupplier {
/**
* Tabs will be copied into toolwindow header and managed by [SingleContentLayout].
*/
fun getTabs() : JBTabs
/**
* Toolbar follows after the tabs.
*
* By default, current toolwindow content is used for [ActionToolbar.setTargetComponent].
* Toolbars can be adjusted in [init].
*/
fun getToolbarActions() : ActionGroup? {
return null
}
/**
* Actions after close action.
*/
fun getContentActions() : List<AnAction> {
return emptyList()
}
/**
* Defines if a tab from [getTabs] can be closed.
*/
fun isClosable(tab: TabInfo) : Boolean {
return false
}
fun close(tab: TabInfo) {
getTabs().removeTab(tab)
}
/**
* This method is called after a single view mode is activated.
*
* @param mainToolbar main toolbar that can be customized, e.g. [ActionToolbar.setTargetComponent]
* @param contentToolbar right sided toolbar with close action and others from [getContentActions]
*/
fun init(mainToolbar: ActionToolbar?, contentToolbar: ActionToolbar?) {
}
/**
* This method is called to customize wrappers after tabs are changed or new view is set.
*
* @param wrapper additional empty panel between toolbar and close action where something can be put
*/
fun customize(wrapper: JComponent?) {
}
/**
* This method is called after a single view mode was revoked.
*/
fun reset() {
}
fun getMainToolbarPlace(): String = ActionPlaces.TOOLWINDOW_TITLE
fun getContentToolbarPlace(): String = ActionPlaces.TOOLWINDOW_TITLE
fun addSubContent(tabInfo: TabInfo, content: Content) {
}
fun getSubContents(): Collection<Content> = emptyList()
companion object {
@JvmField
val KEY = DataKey.create<SingleContentSupplier>("SingleContentSupplier")
@JvmField
val DRAGGED_OUT_KEY: Key<Boolean> = Key.create("DraggedOutKey")
@JvmStatic
fun removeSubContentsOfContent(content: Content, rightNow: Boolean) {
val supplier = (content.component as? DataProvider)?.let(KEY::getData)
if (supplier != null) {
val removeSubContents = {
for (subContent in supplier.getSubContents()) {
subContent.manager?.removeContent(subContent, true)
}
}
if (rightNow) {
removeSubContents()
}
else SwingUtilities.invokeLater { removeSubContents() }
}
}
}
} | apache-2.0 | bfff1f2a1cae506483390462bd5e1b91 | 26.714286 | 120 | 0.690959 | 4.35479 | false | false | false | false |
GunoH/intellij-community | notebooks/visualization/src/org/jetbrains/plugins/notebooks/visualization/NotebookIntervalPointerImpl.kt | 2 | 13028 | package org.jetbrains.plugins.notebooks.visualization
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.command.undo.BasicUndoableAction
import com.intellij.openapi.command.undo.DocumentReference
import com.intellij.openapi.command.undo.DocumentReferenceManager
import com.intellij.openapi.command.undo.UndoManager
import com.intellij.openapi.diagnostic.thisLogger
import com.intellij.openapi.editor.Editor
import com.intellij.util.EventDispatcher
import org.jetbrains.annotations.TestOnly
import org.jetbrains.plugins.notebooks.visualization.NotebookIntervalPointersEvent.*
class NotebookIntervalPointerFactoryImplProvider : NotebookIntervalPointerFactoryProvider {
override fun create(editor: Editor): NotebookIntervalPointerFactory =
NotebookIntervalPointerFactoryImpl(NotebookCellLines.get(editor),
DocumentReferenceManager.getInstance().create(editor.document),
editor.project?.let(UndoManager::getInstance))
}
private class NotebookIntervalPointerImpl(var interval: NotebookCellLines.Interval?) : NotebookIntervalPointer {
override fun get(): NotebookCellLines.Interval? {
ApplicationManager.getApplication().assertReadAccessAllowed()
return interval
}
override fun toString(): String = "NotebookIntervalPointerImpl($interval)"
}
private typealias NotebookIntervalPointersEventChanges = ArrayList<Change>
private sealed interface ChangesContext
private data class DocumentChangedContext(var redoContext: RedoContext? = null) : ChangesContext
private data class UndoContext(val changes: List<Change>) : ChangesContext
private data class RedoContext(val changes: List<Change>) : ChangesContext
/**
* One unique NotebookIntervalPointer exists for each current interval. You can use NotebookIntervalPointer as map key.
* [NotebookIntervalPointerFactoryImpl] automatically supports undo/redo for [documentChanged] and [modifyPointers] calls.
*
* During undo or redo operations old intervals are restored.
* For example, you can save pointer anywhere, remove interval, undo removal and pointer instance will contain interval again.
* You can store interval-related data into WeakHashMap<NotebookIntervalPointer, Data> and this data will outlive undo/redo actions.
*/
class NotebookIntervalPointerFactoryImpl(private val notebookCellLines: NotebookCellLines,
private val documentReference: DocumentReference,
private val undoManager: UndoManager?) : NotebookIntervalPointerFactory, NotebookCellLines.IntervalListener {
private val pointers = ArrayList<NotebookIntervalPointerImpl>()
private var changesContext: ChangesContext? = 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 {
ApplicationManager.getApplication().assertReadAccessAllowed()
return pointers[interval.ordinal].also {
require(it.interval == interval)
}
}
override fun modifyPointers(changes: Iterable<NotebookIntervalPointerFactory.Change>) {
ApplicationManager.getApplication()?.assertWriteAccessAllowed()
val eventChanges = NotebookIntervalPointersEventChanges()
applyChanges(changes, eventChanges)
val pointerEvent = NotebookIntervalPointersEvent(eventChanges, cellLinesEvent = null, EventSource.ACTION)
undoManager?.undoableActionPerformed(object : BasicUndoableAction(documentReference) {
override fun undo() {
val invertedChanges = invertChanges(eventChanges)
updatePointersByChanges(invertedChanges)
changeListeners.multicaster.onUpdated(
NotebookIntervalPointersEvent(invertedChanges, cellLinesEvent = null, EventSource.UNDO_ACTION))
}
override fun redo() {
updatePointersByChanges(eventChanges)
changeListeners.multicaster.onUpdated(
NotebookIntervalPointersEvent(eventChanges, cellLinesEvent = null, EventSource.REDO_ACTION))
}
})
changeListeners.multicaster.onUpdated(pointerEvent)
}
override fun documentChanged(event: NotebookCellLinesEvent) {
try {
val pointersEvent = when (val context = changesContext) {
is DocumentChangedContext -> documentChangedByAction(event, context)
is UndoContext -> documentChangedByUndo(event, context)
is RedoContext -> documentChangedByRedo(event, context)
null -> documentChangedByAction(event, null) // changesContext is null if undo manager is unavailable
}
changeListeners.multicaster.onUpdated(pointersEvent)
}
catch (ex: Exception) {
thisLogger().error(ex)
// DS-3893 consume exception and log it, actions changing document should work as usual
}
finally {
changesContext = null
}
}
override fun beforeDocumentChange(event: NotebookCellLinesEventBeforeChange) {
if (undoManager == null || undoManager.isUndoOrRedoInProgress) return
val context = DocumentChangedContext()
try {
undoManager.undoableActionPerformed(object : BasicUndoableAction() {
override fun undo() {}
override fun redo() {
changesContext = context.redoContext
}
})
changesContext = context
} catch (ex: Exception) {
thisLogger().error(ex)
// DS-3893 consume exception, don't prevent document updating
}
}
private fun documentChangedByAction(event: NotebookCellLinesEvent,
documentChangedContext: DocumentChangedContext?): NotebookIntervalPointersEvent {
val eventChanges = NotebookIntervalPointersEventChanges()
updateChangedIntervals(event, eventChanges)
updateShiftedIntervals(event)
undoManager?.undoableActionPerformed(object : BasicUndoableAction(documentReference) {
override fun undo() {
changesContext = UndoContext(eventChanges)
}
override fun redo() {}
})
documentChangedContext?.let {
it.redoContext = RedoContext(eventChanges)
}
return NotebookIntervalPointersEvent(eventChanges, event, EventSource.ACTION)
}
private fun documentChangedByUndo(event: NotebookCellLinesEvent, context: UndoContext): NotebookIntervalPointersEvent {
val invertedChanges = invertChanges(context.changes)
updatePointersByChanges(invertedChanges)
updateShiftedIntervals(event)
return NotebookIntervalPointersEvent(invertedChanges, event, EventSource.UNDO_ACTION)
}
private fun documentChangedByRedo(event: NotebookCellLinesEvent, context: RedoContext): NotebookIntervalPointersEvent {
updatePointersByChanges(context.changes)
updateShiftedIntervals(event)
return NotebookIntervalPointersEvent(context.changes, event, EventSource.REDO_ACTION)
}
private fun updatePointersByChanges(changes: List<Change>) {
for (change in changes) {
when (change) {
is OnEdited -> (change.pointer as NotebookIntervalPointerImpl).interval = change.intervalAfter
is OnInserted -> {
for (p in change.subsequentPointers) {
(p.pointer as NotebookIntervalPointerImpl).interval = p.interval
}
pointers.addAll(change.ordinals.first, change.subsequentPointers.map { it.pointer as NotebookIntervalPointerImpl })
}
is OnRemoved -> {
for (p in change.subsequentPointers.asReversed()) {
pointers.removeAt(p.interval.ordinal)
(p.pointer as NotebookIntervalPointerImpl).interval = null
}
}
is OnSwapped -> {
trySwapPointers(null, NotebookIntervalPointerFactory.Swap(change.firstOrdinal, change.secondOrdinal))
}
}
}
}
private fun makeSnapshot(interval: NotebookCellLines.Interval) =
PointerSnapshot(pointers[interval.ordinal], interval)
private fun updateChangedIntervals(e: NotebookCellLinesEvent, eventChanges: NotebookIntervalPointersEventChanges) {
when {
!e.isIntervalsChanged() -> {
// content edited without affecting intervals values
for (editedInterval in LinkedHashSet(e.oldAffectedIntervals) + e.newAffectedIntervals) {
eventChanges.add(OnEdited(pointers[editedInterval.ordinal], editedInterval, editedInterval))
}
}
e.oldIntervals.size == 1 && e.newIntervals.size == 1 && e.oldIntervals.first().type == e.newIntervals.first().type -> {
// only one interval changed size
for (editedInterval in e.newAffectedIntervals) {
val ptr = pointers[editedInterval.ordinal]
eventChanges.add(OnEdited(ptr, ptr.interval!!, editedInterval))
}
if (e.newIntervals.first() !in e.newAffectedIntervals) {
val ptr = pointers[e.newIntervals.first().ordinal]
eventChanges.add(OnEdited(ptr, ptr.interval!!, e.newIntervals.first()))
}
pointers[e.newIntervals.first().ordinal].interval = e.newIntervals.first()
}
else -> {
if (e.oldIntervals.isNotEmpty()) {
eventChanges.add(OnRemoved(e.oldIntervals.map(::makeSnapshot)))
for (old in e.oldIntervals.asReversed()) {
pointers[old.ordinal].interval = null
pointers.removeAt(old.ordinal)
}
}
if (e.newIntervals.isNotEmpty()) {
pointers.addAll(e.newIntervals.first().ordinal, e.newIntervals.map { NotebookIntervalPointerImpl(it) })
eventChanges.add(OnInserted(e.newIntervals.map(::makeSnapshot)))
}
for (interval in e.newAffectedIntervals - e.newIntervals.toSet()) {
val ptr = pointers[interval.ordinal]
eventChanges.add(OnEdited(ptr, ptr.interval!!, interval))
}
}
}
}
private fun updateShiftedIntervals(event: NotebookCellLinesEvent) {
val invalidPointersStart =
event.newIntervals.firstOrNull()?.let { it.ordinal + event.newIntervals.size }
?: event.oldIntervals.firstOrNull()?.ordinal
?: pointers.size
for (i in invalidPointersStart until pointers.size) {
pointers[i].interval = notebookCellLines.intervals[i]
}
}
private fun applyChanges(changes: Iterable<NotebookIntervalPointerFactory.Change>, eventChanges: NotebookIntervalPointersEventChanges){
for (hint in changes) {
when (hint) {
is NotebookIntervalPointerFactory.Invalidate -> {
val ptr = create(hint.interval) as NotebookIntervalPointerImpl
invalidatePointer(eventChanges, ptr)
}
is NotebookIntervalPointerFactory.Swap ->
trySwapPointers(eventChanges, hint)
}
}
}
private fun invalidatePointer(eventChanges: NotebookIntervalPointersEventChanges,
ptr: NotebookIntervalPointerImpl) {
val interval = ptr.interval
if (interval == null) return
val newPtr = NotebookIntervalPointerImpl(interval)
pointers[interval.ordinal] = newPtr
ptr.interval = null
eventChanges.add(OnRemoved(listOf(PointerSnapshot(ptr, interval))))
eventChanges.add(OnInserted(listOf(PointerSnapshot(newPtr, interval))))
}
private fun trySwapPointers(eventChanges: NotebookIntervalPointersEventChanges?,
hint: NotebookIntervalPointerFactory.Swap) {
val firstPtr = pointers.getOrNull(hint.firstOrdinal)
val secondPtr = pointers.getOrNull(hint.secondOrdinal)
if (firstPtr == null || secondPtr == null) {
thisLogger().error("cannot swap invalid NotebookIntervalPointers: ${hint.firstOrdinal} and ${hint.secondOrdinal}")
return
}
if (hint.firstOrdinal == hint.secondOrdinal) return // nothing to do
val interval = firstPtr.interval!!
firstPtr.interval = secondPtr.interval
secondPtr.interval = interval
pointers[hint.firstOrdinal] = secondPtr
pointers[hint.secondOrdinal] = firstPtr
eventChanges?.add(OnSwapped(PointerSnapshot(firstPtr, firstPtr.interval!!),
PointerSnapshot(secondPtr, secondPtr.interval!!)))
}
private fun invertChanges(changes: List<Change>): List<Change> =
changes.asReversed().map(::invertChange)
private fun invertChange(change: Change): Change =
when (change) {
is OnEdited -> change.copy(intervalAfter = change.intervalBefore, intervalBefore = change.intervalAfter)
is OnInserted -> OnRemoved(change.subsequentPointers)
is OnRemoved -> OnInserted(change.subsequentPointers)
is OnSwapped -> OnSwapped(first = PointerSnapshot(change.first.pointer, change.second.interval),
second = PointerSnapshot(change.second.pointer, change.first.interval))
}
@TestOnly
fun pointersCount(): Int = pointers.size
}
| apache-2.0 | 92b240a6c50f2c8f55ee50dd475a4198 | 40.890675 | 150 | 0.72206 | 4.936718 | false | false | false | false |
tginsberg/advent-2016-kotlin | src/main/kotlin/com/ginsberg/advent2016/assembunny/AssembunnyInstruction.kt | 1 | 4102 | package com.ginsberg.advent2016.assembunny
sealed class AssembunnyInstruction() {
fun toIntOrNull(x: String): Int? =
try {
x.toInt()
} catch (e: NumberFormatException) {
null
}
fun toRegisterOrNull(r: String): Char? =
if (r[0] in setOf('a', 'b', 'c', 'd')) r[0]
else null
open fun isValid(): Boolean = true
abstract fun execute(state: AssembunnyState): AssembunnyState
abstract fun toggle(togglingInstruction: AssembunnyInstruction): AssembunnyInstruction
class Copy(val x: String, val y: String) : AssembunnyInstruction() {
override fun isValid(): Boolean =
(toRegisterOrNull(x) != null || toIntOrNull(x) != null) && toRegisterOrNull(y) != null
override fun execute(state: AssembunnyState): AssembunnyState {
val cpyVal = toRegisterOrNull(x)?.let { it -> state.registers[it] } ?: toIntOrNull(x)!!
val toReg = toRegisterOrNull(y)!!
return state.copy(registers = state.registers.plus(toReg to cpyVal)).pcDelta(1)
}
override fun toggle(togglingInstruction: AssembunnyInstruction): AssembunnyInstruction =
Jump(x, y)
}
class Inc(val x: String) : AssembunnyInstruction() {
override fun isValid(): Boolean =
toRegisterOrNull(x) != null
override fun execute(state: AssembunnyState): AssembunnyState {
val toReg = toRegisterOrNull(x)!!
return state.copy(registers = state.registers.plus(toReg to state.registers[toReg]!! + 1)).pcDelta(1)
}
override fun toggle(togglingInstruction: AssembunnyInstruction): AssembunnyInstruction =
Dec(x)
}
class Dec(val x: String) : AssembunnyInstruction() {
override fun isValid(): Boolean =
toRegisterOrNull(x) != null
override fun execute(state: AssembunnyState): AssembunnyState {
val toReg = toRegisterOrNull(x)!!
return state.copy(registers = state.registers.plus(toReg to state.registers[toReg]!! - 1)).pcDelta(1)
}
override fun toggle(togglingInstruction: AssembunnyInstruction): AssembunnyInstruction =
Inc(x)
}
class Jump(val x: String, val y: String) : AssembunnyInstruction() {
override fun execute(state: AssembunnyState): AssembunnyState {
val cmpVal = toRegisterOrNull(x)?.let { it -> state.registers[it] } ?: toIntOrNull(x)!!
val jmpVal = toRegisterOrNull(y)?.let { it -> state.registers[it] } ?: toIntOrNull(y)!!
return if (cmpVal == 0) state.pcDelta(1)
else state.pcDelta(jmpVal)
}
override fun toggle(togglingInstruction: AssembunnyInstruction): AssembunnyInstruction =
Copy(x, y)
}
class Toggle(val x: String) : AssembunnyInstruction() {
private var skippedSelfToggle = false
override fun execute(state: AssembunnyState): AssembunnyState {
val away = toRegisterOrNull(x)?.let { it -> state.registers[it] } ?: toIntOrNull(x)!!
val at = state.pc + away
val newInst = state.instructions.toMutableList()
if (at < newInst.size) {
newInst[at] = newInst[at].toggle(this)
return state.copy(newInst).pcDelta(1)
}
return state.pcDelta(1)
}
override fun toggle(togglingInstruction: AssembunnyInstruction): AssembunnyInstruction =
if (togglingInstruction == this) {
if (skippedSelfToggle) {
skippedSelfToggle = true
this
} else {
Inc(x)
}
} else {
Inc(x)
}
}
class Out(val x: String) : AssembunnyInstruction() {
override fun execute(state: AssembunnyState): AssembunnyState {
return state.copy(output = state.registers[x[0]]).pcDelta(1)
}
override fun toggle(togglingInstruction: AssembunnyInstruction): AssembunnyInstruction =
this
}
} | mit | f6a2ff31a9862ab1965285a2725d4d3b | 36.990741 | 113 | 0.603364 | 4.290795 | false | false | false | false |
GunoH/intellij-community | plugins/ide-features-trainer/src/training/actions/ChooseProgrammingLanguageForLearningAction.kt | 2 | 2699 | // 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 training.actions
import com.intellij.lang.Language
import com.intellij.openapi.actionSystem.*
import com.intellij.openapi.actionSystem.ex.ComboBoxAction
import com.intellij.openapi.util.NlsSafe
import com.intellij.ui.ExperimentalUI
import com.intellij.util.ui.JBUI
import com.intellij.util.ui.UIUtil
import training.lang.LangManager
import training.lang.LangSupport
import training.lang.LangSupportBean
import training.learn.LearnBundle
import training.ui.LearnToolWindow
import training.util.resetPrimaryLanguage
import javax.swing.JComponent
internal class ChooseProgrammingLanguageForLearningAction(private val learnToolWindow: LearnToolWindow) : ComboBoxAction() {
override fun getActionUpdateThread(): ActionUpdateThread {
return ActionUpdateThread.BGT
}
override fun createPopupActionGroup(button: JComponent, context: DataContext): DefaultActionGroup {
val allActionsGroup = DefaultActionGroup()
val supportedLanguagesExtensions = LangManager.getInstance().supportedLanguagesExtensions.sortedBy { it.language }
for (langSupportExt: LangSupportBean in supportedLanguagesExtensions) {
val languageId = langSupportExt.getLang()
val displayName = Language.findLanguageByID(languageId)?.displayName ?: continue
allActionsGroup.add(SelectLanguageAction(languageId, displayName))
}
return allActionsGroup
}
override fun update(e: AnActionEvent) {
val langSupport = LangManager.getInstance().getLangSupport()
if (langSupport != null) {
e.presentation.text = getDisplayName(langSupport)
}
e.presentation.description = LearnBundle.message("learn.choose.language.description.combo.box")
}
override fun createCustomComponent(presentation: Presentation, place: String): JComponent {
return super.createCustomComponent(presentation, place).also {
if (ExperimentalUI.isNewUI()) {
UIUtil.setBackgroundRecursively(it, JBUI.CurrentTheme.ToolWindow.background())
}
}
}
private inner class SelectLanguageAction(private val languageId: String, @NlsSafe displayName: String) : AnAction(displayName) {
override fun actionPerformed(e: AnActionEvent) {
val ep = LangManager.getInstance().supportedLanguagesExtensions.singleOrNull { it.language == languageId } ?: return
resetPrimaryLanguage(ep.getLang())
learnToolWindow.setModulesPanel()
}
}
}
@NlsSafe
private fun getDisplayName(language: LangSupport) =
Language.findLanguageByID(language.primaryLanguage)?.displayName ?: LearnBundle.message("unknown.language.name")
| apache-2.0 | a1be7ee0953abdcec06554fd69bbd109 | 41.171875 | 140 | 0.785476 | 4.925182 | false | false | false | false |
ftomassetti/kolasu | core/src/main/kotlin/com/strumenta/kolasu/parsing/ANTLRParseTreeUtils.kt | 1 | 4798 | package com.strumenta.kolasu.parsing
import com.strumenta.kolasu.model.*
import org.antlr.v4.runtime.*
import org.antlr.v4.runtime.tree.ErrorNode
import org.antlr.v4.runtime.tree.ParseTree
import org.antlr.v4.runtime.tree.TerminalNode
/**
* Navigate the parse tree performing the specified operations on the nodes, either real nodes or nodes
* representing errors.
*/
fun ParserRuleContext.processDescendantsAndErrors(
operationOnParserRuleContext: (ParserRuleContext) -> Unit,
operationOnError: (ErrorNode) -> Unit,
includingMe: Boolean = true
) {
if (includingMe) {
operationOnParserRuleContext(this)
}
if (this.children != null) {
this.children.filterIsInstance(ParserRuleContext::class.java).forEach {
it.processDescendantsAndErrors(operationOnParserRuleContext, operationOnError, includingMe = true)
}
this.children.filterIsInstance(ErrorNode::class.java).forEach {
operationOnError(it)
}
}
}
/**
* Get the original text associated to this non-terminal by querying the inputstream.
*/
fun ParserRuleContext.getOriginalText(): String {
val a: Int = this.start.startIndex
val b: Int = this.stop.stopIndex
val interval = org.antlr.v4.runtime.misc.Interval(a, b)
return this.start.inputStream.getText(interval)
}
/**
* Get the original text associated to this terminal by querying the inputstream.
*/
fun TerminalNode.getOriginalText(): String = this.symbol.getOriginalText()
/**
* Get the original text associated to this token by querying the inputstream.
*/
fun Token.getOriginalText(): String {
val a: Int = this.startIndex
val b: Int = this.stopIndex
val interval = org.antlr.v4.runtime.misc.Interval(a, b)
return this.inputStream.getText(interval)
}
/**
* Given the entire code, this returns the slice covered by this Node.
*/
fun Node.getText(code: String): String? = position?.text(code)
/**
* An Origin corresponding to a ParseTreeNode. This is used to indicate that an AST Node has been obtained
* by mapping an original ParseTreeNode.
*/
class ParseTreeOrigin(val parseTree: ParseTree, override var source: Source? = null) : Origin {
override val position: Position?
get() = parseTree.toPosition(source = source)
override val sourceText: String?
get() =
when (parseTree) {
is ParserRuleContext -> {
parseTree.getOriginalText()
}
is TerminalNode -> {
parseTree.text
}
else -> null
}
}
/**
* Set the origin of the AST node as a ParseTreeOrigin, providing the parseTree is not null.
* If the parseTree is null, no operation is performed.
*/
fun <T : Node> T.withParseTreeNode(parseTree: ParserRuleContext?): T {
if (parseTree != null) {
this.origin = ParseTreeOrigin(parseTree)
}
return this
}
val RuleContext.hasChildren: Boolean
get() = this.childCount > 0
val RuleContext.firstChild: ParseTree?
get() = if (hasChildren) this.getChild(0) else null
val RuleContext.lastChild: ParseTree?
get() = if (hasChildren) this.getChild(this.childCount - 1) else null
val Token.length
get() = if (this.type == Token.EOF) 0 else text.length
val Token.startPoint: Point
get() = Point(this.line, this.charPositionInLine)
val Token.endPoint: Point
get() = if (this.type == Token.EOF) startPoint else startPoint + this.text
val Token.position: Position
get() = Position(startPoint, endPoint)
/**
* Returns the position of the receiver parser rule context.
*/
val ParserRuleContext.position: Position
get() = Position(start.startPoint, stop.endPoint)
/**
* Returns the position of the receiver parser rule context.
* @param considerPosition if it's false, this method returns null.
*/
fun ParserRuleContext.toPosition(considerPosition: Boolean = true, source: Source? = null): Position? {
return if (considerPosition && start != null && stop != null) {
val position = position
if (source == null) position else Position(position.start, position.end, source)
} else null
}
fun TerminalNode.toPosition(considerPosition: Boolean = true, source: Source? = null): Position? =
this.symbol.toPosition(considerPosition, source)
fun Token.toPosition(considerPosition: Boolean = true, source: Source? = null): Position? =
if (considerPosition) Position(this.startPoint, this.endPoint, source) else null
fun ParseTree.toPosition(considerPosition: Boolean = true, source: Source? = null): Position? {
return when (this) {
is TerminalNode -> this.toPosition(considerPosition, source)
is ParserRuleContext -> this.toPosition(considerPosition, source)
else -> null
}
}
| apache-2.0 | 9a9d9ccac82da11d09b58c17ed4cc6c5 | 32.552448 | 110 | 0.694873 | 4.015063 | false | false | false | false |
AsamK/TextSecure | app/src/test/java/org/thoughtcrime/securesms/database/GroupTestUtil.kt | 1 | 9552 | package org.thoughtcrime.securesms.database
import com.google.protobuf.ByteString
import org.signal.libsignal.zkgroup.groups.GroupMasterKey
import org.signal.storageservice.protos.groups.AccessControl
import org.signal.storageservice.protos.groups.GroupChange
import org.signal.storageservice.protos.groups.Member
import org.signal.storageservice.protos.groups.local.DecryptedGroup
import org.signal.storageservice.protos.groups.local.DecryptedGroupChange
import org.signal.storageservice.protos.groups.local.DecryptedMember
import org.signal.storageservice.protos.groups.local.DecryptedPendingMember
import org.signal.storageservice.protos.groups.local.DecryptedRequestingMember
import org.signal.storageservice.protos.groups.local.DecryptedString
import org.signal.storageservice.protos.groups.local.DecryptedTimer
import org.signal.storageservice.protos.groups.local.EnabledState
import org.thoughtcrime.securesms.groups.GroupId
import org.thoughtcrime.securesms.recipients.RecipientId
import org.whispersystems.signalservice.api.groupsv2.DecryptedGroupHistoryEntry
import org.whispersystems.signalservice.api.groupsv2.GroupHistoryPage
import org.whispersystems.signalservice.api.groupsv2.GroupsV2Operations
import org.whispersystems.signalservice.api.push.DistributionId
import org.whispersystems.signalservice.api.push.ServiceId
import java.util.Optional
import java.util.UUID
fun DecryptedGroupChange.Builder.setNewDescription(description: String) {
newDescription = DecryptedString.newBuilder().setValue(description).build()
}
fun DecryptedGroupChange.Builder.setNewTitle(title: String) {
newTitle = DecryptedString.newBuilder().setValue(title).build()
}
class ChangeLog(private val revision: Int) {
var groupSnapshot: DecryptedGroup? = null
var groupChange: DecryptedGroupChange? = null
fun change(init: DecryptedGroupChange.Builder.() -> Unit) {
val builder = DecryptedGroupChange.newBuilder().setRevision(revision)
builder.init()
groupChange = builder.build()
}
fun fullSnapshot(
extendGroup: DecryptedGroup? = null,
title: String = extendGroup?.title ?: "",
avatar: String = extendGroup?.avatar ?: "",
description: String = extendGroup?.description ?: "",
accessControl: AccessControl = extendGroup?.accessControl ?: AccessControl.getDefaultInstance(),
members: List<DecryptedMember> = extendGroup?.membersList ?: emptyList(),
pendingMembers: List<DecryptedPendingMember> = extendGroup?.pendingMembersList ?: emptyList(),
requestingMembers: List<DecryptedRequestingMember> = extendGroup?.requestingMembersList ?: emptyList(),
inviteLinkPassword: ByteArray = extendGroup?.inviteLinkPassword?.toByteArray() ?: ByteArray(0),
disappearingMessageTimer: DecryptedTimer = extendGroup?.disappearingMessagesTimer ?: DecryptedTimer.getDefaultInstance()
) {
groupSnapshot = decryptedGroup(revision, title, avatar, description, accessControl, members, pendingMembers, requestingMembers, inviteLinkPassword, disappearingMessageTimer)
}
}
class ChangeSet {
private val changeSet: MutableList<ChangeLog> = mutableListOf()
fun changeLog(revision: Int, init: ChangeLog.() -> Unit) {
val entry = ChangeLog(revision)
entry.init()
changeSet += entry
}
fun toApiResponse(): GroupHistoryPage {
return GroupHistoryPage(changeSet.map { DecryptedGroupHistoryEntry(Optional.ofNullable(it.groupSnapshot), Optional.ofNullable(it.groupChange)) }, GroupHistoryPage.PagingData.NONE)
}
}
class GroupChangeData(private val revision: Int, private val groupOperations: GroupsV2Operations.GroupOperations) {
private val groupChangeBuilder: GroupChange.Builder = GroupChange.newBuilder()
private val actionsBuilder: GroupChange.Actions.Builder = GroupChange.Actions.newBuilder()
var changeEpoch: Int = GroupsV2Operations.HIGHEST_KNOWN_EPOCH
val groupChange: GroupChange
get() {
return groupChangeBuilder
.setChangeEpoch(changeEpoch)
.setActions(actionsBuilder.setRevision(revision).build().toByteString())
.build()
}
fun source(serviceId: ServiceId) {
actionsBuilder.sourceUuid = groupOperations.encryptUuid(serviceId.uuid())
}
fun deleteMember(serviceId: ServiceId) {
actionsBuilder.addDeleteMembers(GroupChange.Actions.DeleteMemberAction.newBuilder().setDeletedUserId(groupOperations.encryptUuid(serviceId.uuid())))
}
fun modifyRole(serviceId: ServiceId, role: Member.Role) {
actionsBuilder.addModifyMemberRoles(GroupChange.Actions.ModifyMemberRoleAction.newBuilder().setUserId(groupOperations.encryptUuid(serviceId.uuid())).setRole(role))
}
}
class GroupStateTestData(private val masterKey: GroupMasterKey, private val groupOperations: GroupsV2Operations.GroupOperations? = null) {
var localState: DecryptedGroup? = null
var groupRecord: Optional<GroupDatabase.GroupRecord> = Optional.empty()
var serverState: DecryptedGroup? = null
var changeSet: ChangeSet? = null
var groupChange: GroupChange? = null
var includeFirst: Boolean = false
var requestedRevision: Int = 0
fun localState(
active: Boolean = true,
revision: Int = 0,
title: String = "",
avatar: String = "",
description: String = "",
accessControl: AccessControl = AccessControl.getDefaultInstance(),
members: List<DecryptedMember> = emptyList(),
pendingMembers: List<DecryptedPendingMember> = emptyList(),
requestingMembers: List<DecryptedRequestingMember> = emptyList(),
inviteLinkPassword: ByteArray = ByteArray(0),
disappearingMessageTimer: DecryptedTimer = DecryptedTimer.getDefaultInstance(),
serviceId: String = ServiceId.from(UUID.randomUUID()).toString()
) {
localState = decryptedGroup(revision, title, avatar, description, accessControl, members, pendingMembers, requestingMembers, inviteLinkPassword, disappearingMessageTimer)
groupRecord = groupRecord(masterKey, localState!!, active = active, serviceId = serviceId)
}
fun serverState(
revision: Int,
extendGroup: DecryptedGroup? = null,
title: String = extendGroup?.title ?: "",
avatar: String = extendGroup?.avatar ?: "",
description: String = extendGroup?.description ?: "",
accessControl: AccessControl = extendGroup?.accessControl ?: AccessControl.getDefaultInstance(),
members: List<DecryptedMember> = extendGroup?.membersList ?: emptyList(),
pendingMembers: List<DecryptedPendingMember> = extendGroup?.pendingMembersList ?: emptyList(),
requestingMembers: List<DecryptedRequestingMember> = extendGroup?.requestingMembersList ?: emptyList(),
inviteLinkPassword: ByteArray = extendGroup?.inviteLinkPassword?.toByteArray() ?: ByteArray(0),
disappearingMessageTimer: DecryptedTimer = extendGroup?.disappearingMessagesTimer ?: DecryptedTimer.getDefaultInstance()
) {
serverState = decryptedGroup(revision, title, avatar, description, accessControl, members, pendingMembers, requestingMembers, inviteLinkPassword, disappearingMessageTimer)
}
fun changeSet(init: ChangeSet.() -> Unit) {
val changeSet = ChangeSet()
changeSet.init()
this.changeSet = changeSet
}
fun apiCallParameters(requestedRevision: Int, includeFirst: Boolean) {
this.requestedRevision = requestedRevision
this.includeFirst = includeFirst
}
fun groupChange(revision: Int, init: GroupChangeData.() -> Unit) {
val groupChangeData = GroupChangeData(revision, groupOperations!!)
groupChangeData.init()
this.groupChange = groupChangeData.groupChange
}
}
fun groupRecord(
masterKey: GroupMasterKey,
decryptedGroup: DecryptedGroup,
id: GroupId = GroupId.v2(masterKey),
recipientId: RecipientId = RecipientId.from(100),
members: String = "1",
unmigratedV1Members: String? = null,
avatarId: Long = 1,
avatarKey: ByteArray = ByteArray(0),
avatarContentType: String = "",
relay: String = "",
active: Boolean = true,
avatarDigest: ByteArray = ByteArray(0),
mms: Boolean = false,
distributionId: DistributionId? = null,
serviceId: String = ServiceId.from(UUID.randomUUID()).toString()
): Optional<GroupDatabase.GroupRecord> {
return Optional.of(
GroupDatabase.GroupRecord(
id,
recipientId,
decryptedGroup.title,
members,
unmigratedV1Members,
avatarId,
avatarKey,
avatarContentType,
relay,
active,
avatarDigest,
mms,
masterKey.serialize(),
decryptedGroup.revision,
decryptedGroup.toByteArray(),
distributionId,
serviceId
)
)
}
fun decryptedGroup(
revision: Int = 0,
title: String = "",
avatar: String = "",
description: String = "",
accessControl: AccessControl = AccessControl.getDefaultInstance(),
members: List<DecryptedMember> = emptyList(),
pendingMembers: List<DecryptedPendingMember> = emptyList(),
requestingMembers: List<DecryptedRequestingMember> = emptyList(),
inviteLinkPassword: ByteArray = ByteArray(0),
disappearingMessageTimer: DecryptedTimer = DecryptedTimer.getDefaultInstance()
): DecryptedGroup {
val builder = DecryptedGroup.newBuilder()
.setAccessControl(accessControl)
.setAvatar(avatar)
.setAvatarBytes(ByteString.EMPTY)
.setDescription(description)
.setDisappearingMessagesTimer(disappearingMessageTimer)
.setInviteLinkPassword(ByteString.copyFrom(inviteLinkPassword))
.setIsAnnouncementGroup(EnabledState.DISABLED)
.setTitle(title)
.setRevision(revision)
.addAllMembers(members)
.addAllPendingMembers(pendingMembers)
.addAllRequestingMembers(requestingMembers)
return builder.build()
}
| gpl-3.0 | 3f89082a266efceb802bd42ccf6aea18 | 40.530435 | 183 | 0.767797 | 4.4366 | false | false | false | false |
ktorio/ktor | ktor-io/jvm/src/io/ktor/utils/io/core/ByteBuffers.kt | 1 | 4038 | package io.ktor.utils.io.core
import io.ktor.utils.io.core.internal.*
import java.nio.*
import kotlin.contracts.*
/**
* Read at most `dst.remaining()` bytes to the specified [dst] byte buffer and change its position accordingly
* @return number of bytes copied
*/
public fun ByteReadPacket.readAvailable(dst: ByteBuffer): Int = readAsMuchAsPossible(dst, 0)
/**
* Read exactly `dst.remaining()` bytes to the specified [dst] byte buffer and change its position accordingly
* @return number of bytes copied
*/
public fun ByteReadPacket.readFully(dst: ByteBuffer): Int {
val rc = readAsMuchAsPossible(dst, 0)
if (dst.hasRemaining()) {
throw EOFException("Not enough data in packet to fill buffer: ${dst.remaining()} more bytes required")
}
return rc
}
private tailrec fun ByteReadPacket.readAsMuchAsPossible(bb: ByteBuffer, copied: Int): Int {
if (!bb.hasRemaining()) return copied
val current: ChunkBuffer = prepareRead(1) ?: return copied
val destinationCapacity = bb.remaining()
val available = current.readRemaining
return if (destinationCapacity >= available) {
current.readFully(bb, available)
releaseHead(current)
readAsMuchAsPossible(bb, copied + available)
} else {
current.readFully(bb, destinationCapacity)
headPosition = current.readPosition
copied + destinationCapacity
}
}
/**
* Write bytes directly to packet builder's segment. Generally shouldn't be used in user's code and useful for
* efficient integration.
*
* Invokes [block] lambda with one byte buffer. [block] lambda should change provided's position accordingly but
* shouldn't change any other pointers.
*
* @param size minimal number of bytes should be available in a buffer provided to the lambda. Should be as small as
* possible. If [size] is too large then the function may fail because the segments size is not guaranteed to be fixed
* and not guaranteed that it will be big enough to keep [size] bytes. However it is guaranteed that the segment size
* is at least 8 bytes long (long integer bytes length)
*/
@OptIn(ExperimentalContracts::class)
public inline fun BytePacketBuilder.writeDirect(size: Int, block: (ByteBuffer) -> Unit) {
contract {
callsInPlace(block, InvocationKind.EXACTLY_ONCE)
}
writeByteBufferDirect(size, block)
}
/**
* Write bytes directly to packet builder's segment. Generally shouldn't be used in user's code and useful for
* efficient integration.
*
* Invokes [block] lambda with one byte buffer. [block] lambda should change provided's position accordingly but
* shouldn't change any other pointers.
*
* @param size minimal number of bytes should be available in a buffer provided to the lambda. Should be as small as
* possible. If [size] is too large then the function may fail because the segments size is not guaranteed to be fixed
* and not guaranteed that it will be big enough to keep [size] bytes. However it is guaranteed that the segment size
* is at least 8 bytes long (long integer bytes length)
*/
@OptIn(ExperimentalContracts::class)
public inline fun BytePacketBuilder.writeByteBufferDirect(size: Int, block: (ByteBuffer) -> Unit): Int {
contract {
callsInPlace(block, InvocationKind.EXACTLY_ONCE)
}
return write(size) {
it.writeDirect(size, block)
}
}
@OptIn(ExperimentalContracts::class)
public inline fun ByteReadPacket.readDirect(size: Int, block: (ByteBuffer) -> Unit) {
contract {
callsInPlace(block, InvocationKind.EXACTLY_ONCE)
}
read(size) {
it.readDirect(block)
}
}
@OptIn(ExperimentalContracts::class)
@Deprecated("Use read {} instead.")
public inline fun Input.readDirect(size: Int, block: (ByteBuffer) -> Unit) {
contract {
callsInPlace(block, InvocationKind.EXACTLY_ONCE)
}
read(size) { view ->
view.readDirect {
block(it)
}
}
}
internal fun Buffer.hasArray(): Boolean = memory.buffer.let { it.hasArray() && !it.isReadOnly }
| apache-2.0 | 168f301c3b00f678106a286b59e83a8e | 34.734513 | 118 | 0.715948 | 4.286624 | false | false | false | false |
PtrTeixeira/cookbook-backend | cookbook/models/src/main/kotlin/RecipeEgg.kt | 2 | 975 | package com.github.ptrteixeira.cookbook.core
import com.fasterxml.jackson.annotation.JsonIgnoreProperties
/**
* Used for the egg pattern - that is, this is everything that a client would send to the application, at least
* initially. It contains all of the information that makes up a recipe, but it does _not_ contain an ID, as that isn't
* something that the client should necessarily need to pass along.
*
*/
@JsonIgnoreProperties(ignoreUnknown = true)
data class RecipeEgg (
val name: String = "",
val ingredients: List<String> = listOf(),
val instructions: String = "",
val summary: String = "",
val description: String = ""
) {
fun toRecipe(id: Int, user: User): Recipe {
return Recipe(
id = id,
userId = user.id,
name = name,
ingredients = ingredients,
instructions = instructions,
summary = summary,
description = description
)
}
}
| mit | 3e839dfed6db30f74049491ea5aa1518 | 31.5 | 119 | 0.641026 | 4.452055 | false | false | false | false |
inorichi/mangafeed | app/src/main/java/eu/kanade/tachiyomi/ui/base/presenter/NucleusConductorDelegate.kt | 3 | 1174 | package eu.kanade.tachiyomi.ui.base.presenter
import android.os.Bundle
import nucleus.factory.PresenterFactory
import nucleus.presenter.Presenter
class NucleusConductorDelegate<P : Presenter<*>>(private val factory: PresenterFactory<P>) {
var presenter: P? = null
get() {
if (field == null) {
field = factory.createPresenter()
field!!.create(bundle)
bundle = null
}
return field
}
private var bundle: Bundle? = null
fun onSaveInstanceState(): Bundle {
val bundle = Bundle()
// getPresenter(); // Workaround a crash related to saving instance state with child routers
presenter?.save(bundle)
return bundle
}
fun onRestoreInstanceState(presenterState: Bundle?) {
bundle = presenterState
}
@Suppress("UNCHECKED_CAST")
private fun <View> Presenter<View>.takeView(view: Any) = takeView(view as View)
fun onTakeView(view: Any) {
presenter?.takeView(view)
}
fun onDropView() {
presenter?.dropView()
}
fun onDestroy() {
presenter?.destroy()
}
}
| apache-2.0 | 046d9a06c42703bc0195e8f2e547dde4 | 24.521739 | 107 | 0.607325 | 4.733871 | false | false | false | false |
inorichi/mangafeed | app/src/main/java/eu/kanade/tachiyomi/data/track/komga/Komga.kt | 1 | 3848 | package eu.kanade.tachiyomi.data.track.komga
import android.content.Context
import android.graphics.Color
import androidx.annotation.StringRes
import eu.kanade.tachiyomi.R
import eu.kanade.tachiyomi.data.database.models.Manga
import eu.kanade.tachiyomi.data.database.models.Track
import eu.kanade.tachiyomi.data.track.EnhancedTrackService
import eu.kanade.tachiyomi.data.track.NoLoginTrackService
import eu.kanade.tachiyomi.data.track.TrackService
import eu.kanade.tachiyomi.data.track.model.TrackSearch
import eu.kanade.tachiyomi.source.Source
import okhttp3.Dns
import okhttp3.OkHttpClient
class Komga(private val context: Context, id: Int) : TrackService(id), EnhancedTrackService, NoLoginTrackService {
companion object {
const val UNREAD = 1
const val READING = 2
const val COMPLETED = 3
}
override val client: OkHttpClient =
networkService.client.newBuilder()
.dns(Dns.SYSTEM) // don't use DNS over HTTPS as it breaks IP addressing
.build()
val api by lazy { KomgaApi(client) }
@StringRes
override fun nameRes() = R.string.tracker_komga
override fun getLogo() = R.drawable.ic_tracker_komga
override fun getLogoColor() = Color.rgb(51, 37, 50)
override fun getStatusList() = listOf(UNREAD, READING, COMPLETED)
override fun getStatus(status: Int): String = with(context) {
when (status) {
UNREAD -> getString(R.string.unread)
READING -> getString(R.string.reading)
COMPLETED -> getString(R.string.completed)
else -> ""
}
}
override fun getReadingStatus(): Int = READING
override fun getRereadingStatus(): Int = -1
override fun getCompletionStatus(): Int = COMPLETED
override fun getScoreList(): List<String> = emptyList()
override fun displayScore(track: Track): String = ""
override suspend fun update(track: Track, didReadChapter: Boolean): Track {
if (track.status != COMPLETED) {
if (didReadChapter) {
if (track.last_chapter_read.toInt() == track.total_chapters && track.total_chapters > 0) {
track.status = COMPLETED
} else {
track.status = READING
}
}
}
return api.updateProgress(track)
}
override suspend fun bind(track: Track, hasReadChapters: Boolean): Track {
return track
}
override suspend fun search(query: String): List<TrackSearch> {
TODO("Not yet implemented: search")
}
override suspend fun refresh(track: Track): Track {
val remoteTrack = api.getTrackSearch(track.tracking_url)
track.copyPersonalFrom(remoteTrack)
track.total_chapters = remoteTrack.total_chapters
return track
}
override suspend fun login(username: String, password: String) {
saveCredentials("user", "pass")
}
// TrackService.isLogged works by checking that credentials are saved.
// By saving dummy, unused credentials, we can activate the tracker simply by login/logout
override fun loginNoop() {
saveCredentials("user", "pass")
}
override fun getAcceptedSources() = listOf("eu.kanade.tachiyomi.extension.all.komga.Komga")
override suspend fun match(manga: Manga): TrackSearch? =
try {
api.getTrackSearch(manga.url)
} catch (e: Exception) {
null
}
override fun isTrackFrom(track: Track, manga: Manga, source: Source?): Boolean =
track.tracking_url == manga.url && source?.let { accept(it) } == true
override fun migrateTrack(track: Track, manga: Manga, newSource: Source): Track? =
if (accept(newSource)) {
track.also { track.tracking_url = manga.url }
} else {
null
}
}
| apache-2.0 | 89669196ca73d4ccbcd8ad5f0dc0bfcc | 31.888889 | 114 | 0.655146 | 4.392694 | false | false | false | false |
code-disaster/lwjgl3 | modules/lwjgl/egl/src/templates/kotlin/egl/templates/KHR_stream.kt | 4 | 6368 | /*
* Copyright LWJGL. All rights reserved.
* License terms: https://www.lwjgl.org/license
*/
package egl.templates
import egl.*
import org.lwjgl.generator.*
val KHR_stream = "KHRStream".nativeClassEGL("KHR_stream", postfix = KHR) {
documentation =
"""
Native bindings to the $registryLink extension.
This extension defines a new object, the EGLStream, that can be used to efficiently transfer a sequence of image frames from one API to another. The
EGLStream has mechanisms that can help keep audio data synchronized to video data.
Each EGLStream is associated with a "producer" that generates image frames and inserts them into the EGLStream. The producer is responsible for
inserting each image frame into the EGLStream at the correct time so that the consumer can display the image frame for the appropriate period of time.
Each EGLStream is also associated with a "consumer" that retrieves image frames from the EGLStream. The consumer is responsible for noticing that an
image frame is available and displaying it (or otherwise consuming it). The consumer is also responsible for indicating the latency when that is
possible (the latency is the time that elapses between the time it is retrieved from the EGLStream until the time it is displayed to the user).
Some APIs are stream oriented (examples: OpenMAX IL, OpenMAX AL). These APIs may be connected directly to an EGLStream as a producer or consumer. Once
a stream oriented producer is "connected" to an EGLStream and "started" it may insert image frames into the EGLStream automatically with no further
interaction from the application. Likewise, once a stream oriented consumer is "connected" to an EGLStream and "started" it may retrieve image frames
from the EGLStream automatically with no further interaction from the application.
Some APIs are rendering oriented and require interaction with the application during the rendering of each frame (examples: OpenGL, OpenGL ES, OpenVG).
These APIs will not automatically insert or retrieve image frames into/from the EGLStream. Instead the application must take explicit action to cause a
rendering oriented producer to insert an image frame or to cause a rendering oriented consumer to retrieve an image frame.
The EGLStream conceptually operates as a mailbox. When the producer has a new image frame it empties the mailbox (discards the old contents) and
inserts the new image frame into the mailbox. The consumer retrieves the image frame from the mailbox and examines it. When the consumer is finished
examining the image frame it is either placed back in the mailbox (if the mailbox is empty) or discarded (if the mailbox is not empty).
Timing is mainly controlled by the producer. The consumer operated with a fixed latency that it indicates to the producer through the
EGL_CONSUMER_LATENCY_USEC_KHR attribute. The consumer is expected to notice when a new image frame is available in the EGLStream, retrieve it, and
display it to the user in the time indicated by EGL_CONSUMER_LATENCY_USEC_KHR. The producer controls when the image frame will be displayed by
inserting it into the stream at time T - EGL_CONSUMER_LATENCY_USEC_KHR where T is the time that the image frame is intended to appear to the user.
This extension does not cover the details of how a producer or a consumer works or is "connected" to an EGLStream. Different kinds of producers and
consumers work differently and are described in additional extension specifications.
"""
LongConstant(
"",
"NO_STREAM_KHR"..0L
)
IntConstant(
"",
"CONSUMER_LATENCY_USEC_KHR"..0x3210,
"PRODUCER_FRAME_KHR"..0x3212,
"CONSUMER_FRAME_KHR"..0x3213,
"STREAM_STATE_KHR"..0x3214,
"STREAM_STATE_CREATED_KHR"..0x3215,
"STREAM_STATE_CONNECTING_KHR"..0x3216,
"STREAM_STATE_EMPTY_KHR"..0x3217,
"STREAM_STATE_NEW_FRAME_AVAILABLE_KHR"..0x3218,
"STREAM_STATE_OLD_FRAME_AVAILABLE_KHR"..0x3219,
"STREAM_STATE_DISCONNECTED_KHR"..0x321A,
"BAD_STREAM_KHR"..0x321B,
"BAD_STATE_KHR"..0x321C
)
EGLStreamKHR(
"CreateStreamKHR",
"",
EGLDisplay("dpy", ""),
nullable..noneTerminated..EGLint.const.p("attrib_list", "")
)
EGLBoolean(
"DestroyStreamKHR",
"",
EGLDisplay("dpy", ""),
EGLStreamKHR("stream", "")
)
EGLBoolean(
"StreamAttribKHR",
"",
EGLDisplay("dpy", ""),
EGLStreamKHR("stream", ""),
EGLenum("attribute", ""),
EGLint("value", "")
)
EGLBoolean(
"QueryStreamKHR",
"",
EGLDisplay("dpy", ""),
EGLStreamKHR("stream", ""),
EGLenum("attribute", ""),
Check(1)..EGLint.p("value", "")
)
EGLBoolean(
"QueryStreamu64KHR",
"",
EGLDisplay("dpy", ""),
EGLStreamKHR("stream", ""),
EGLenum("attribute", ""),
Check(1)..EGLuint64KHR.p("value", "")
)
}
val KHR_stream_attrib = "KHRStreamAttrib".nativeClassEGL("KHR_stream_attrib", postfix = KHR) {
documentation = "See ${KHR_stream.link}."
EGLStreamKHR(
"CreateStreamAttribKHR",
"",
EGLDisplay("dpy", ""),
nullable..noneTerminated..EGLAttrib.const.p("attrib_list", "")
)
EGLBoolean(
"SetStreamAttribKHR",
"",
EGLDisplay("dpy", ""),
EGLStreamKHR("stream", ""),
EGLenum("attribute", ""),
EGLAttrib("value", "")
)
EGLBoolean(
"QueryStreamAttribKHR",
"",
EGLDisplay("dpy", ""),
EGLStreamKHR("stream", ""),
EGLenum("attribute", ""),
Check(1)..EGLAttrib.p("value", "")
)
EGLBoolean(
"StreamConsumerAcquireAttribKHR",
"",
EGLDisplay("dpy", ""),
EGLStreamKHR("stream", ""),
nullable..noneTerminated..EGLAttrib.const.p("attrib_list", "")
)
EGLBoolean(
"StreamConsumerReleaseAttribKHR",
"",
EGLDisplay("dpy", ""),
EGLStreamKHR("stream", ""),
nullable..noneTerminated..EGLAttrib.const.p("attrib_list", "")
)
} | bsd-3-clause | f60ab4c25b88208273df15e70369b511 | 37.6 | 159 | 0.65625 | 4.689249 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.