repo_name
stringlengths 7
81
| path
stringlengths 6
242
| copies
stringclasses 55
values | size
stringlengths 2
6
| content
stringlengths 55
737k
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 5.44
99.8
| line_max
int64 15
979
| alpha_frac
float64 0.3
0.91
| ratio
float64 2
9.93
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
toastkidjp/Yobidashi_kt | api/src/main/java/jp/toastkid/api/suggestion/SuggestionApi.kt | 1 | 2557 | /*
* Copyright (c) 2021 toastkidjp.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompany this distribution.
* The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html.
*/
package jp.toastkid.api.suggestion
import android.net.Uri
import jp.toastkid.api.lib.HttpClientFactory
import jp.toastkid.api.lib.MultiByteCharacterInspector
import okhttp3.Call
import okhttp3.Callback
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.Response
import timber.log.Timber
import java.io.IOException
import java.util.Locale
/**
* Suggest Web API response fetcher.
*
* @param httpClient HTTP client
* @param suggestionParser Response parser
* @param multiByteCharacterInspector Use for specifying language
*
* @author toastkidjp
*/
class SuggestionApi(
private val httpClient: OkHttpClient = HttpClientFactory().withTimeout(3L),
private val suggestionParser: SuggestionParser = SuggestionParser(),
private val multiByteCharacterInspector: MultiByteCharacterInspector = MultiByteCharacterInspector()
) {
/**
* Fetch Web API result asynchronously.
*
* @param query
* @param listCallback
*/
fun fetchAsync(query: String, listCallback: (List<String>) -> Unit) {
val request = Request.Builder()
.url(makeSuggestUrl(query))
.build()
httpClient.newCall(request).enqueue(object : Callback {
override fun onFailure(call: Call, e: IOException) = Timber.e(e)
@Throws(IOException::class)
override fun onResponse(call: Call, response: Response) {
val body = response.body?.string() ?: return
listCallback(suggestionParser(body))
}
})
}
/**
* Make suggest Web API requesting URL.
*
* @param query Query
* @return suggest Web API requesting URL
*/
private fun makeSuggestUrl(query: String): String {
return "$URL&hl=${findHl(query)}&q=${Uri.encode(query)}"
}
/**
* Find appropriate language.
*
* @param query
* @return language (ex: "ja", "en")
*/
private fun findHl(query: String): String =
if (multiByteCharacterInspector(query)) "ja" else Locale.getDefault().language
companion object {
/**
* Suggest Web API.
*/
private const val URL = "https://www.google.com/complete/search?&output=toolbar"
}
}
| epl-1.0 | db200f470c72df2339690f43b0016959 | 29.082353 | 104 | 0.666797 | 4.326565 | false | false | false | false |
quarkusio/quarkus | extensions/resteasy-reactive/quarkus-resteasy-reactive-kotlin/runtime/src/main/kotlin/org/jboss/resteasy/reactive/server/runtime/kotlin/AbstractSuspendedRequestFilter.kt | 1 | 1778 | package org.jboss.resteasy.reactive.server.runtime.kotlin
import io.smallrye.mutiny.Uni
import io.smallrye.mutiny.coroutines.asUni
import kotlinx.coroutines.async
import org.jboss.resteasy.reactive.server.core.ResteasyReactiveRequestContext
import org.jboss.resteasy.reactive.server.spi.ResteasyReactiveContainerRequestContext
import org.jboss.resteasy.reactive.server.spi.ResteasyReactiveContainerRequestFilter
/**
* Base class used by Quarkus to generate an implementation at build-time that calls
* a `suspend` method annotated with [org.jboss.resteasy.reactive.server.ServerRequestFilter](ServerRequestFilter)
*/
@Suppress("unused")
abstract class AbstractSuspendedRequestFilter : ResteasyReactiveContainerRequestFilter {
abstract suspend fun doFilter(containerRequestContext: ResteasyReactiveContainerRequestContext): Any
abstract fun handleResult(containerRequestContext: ResteasyReactiveContainerRequestContext, uniResult: Uni<*>)
private val originalTCCL: ClassLoader = Thread.currentThread().contextClassLoader
override fun filter(containerRequestContext: ResteasyReactiveContainerRequestContext) {
val (dispatcher, coroutineScope) = prepareExecution(containerRequestContext.serverRequestContext as ResteasyReactiveRequestContext)
val uni = coroutineScope.async(context = dispatcher) {
// ensure the proper CL is not lost in dev-mode
Thread.currentThread().contextClassLoader = originalTCCL
// the implementation gets the proper values from the context and invokes the user supplied method
doFilter(containerRequestContext)
}.asUni()
// the implementation should call the appropriate FilterUtil method
handleResult(containerRequestContext, uni)
}
}
| apache-2.0 | 7f9cb61da2f934110972e785ff96b46a | 47.054054 | 139 | 0.7964 | 5.051136 | false | false | false | false |
JanYoStudio/WhatAnime | app/src/main/java/pw/janyo/whatanime/repository/AnimationRepository.kt | 1 | 6154 | package pw.janyo.whatanime.repository
import android.util.Log
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import okhttp3.RequestBody.Companion.asRequestBody
import org.koin.core.component.KoinComponent
import org.koin.core.component.inject
import pw.janyo.whatanime.R
import pw.janyo.whatanime.api.AniListChineseApi
import pw.janyo.whatanime.api.SearchApi
import pw.janyo.whatanime.config.Configure
import pw.janyo.whatanime.config.DispatcherConfig
import pw.janyo.whatanime.constant.StringConstant.resString
import pw.janyo.whatanime.isOnline
import pw.janyo.whatanime.model.AniListChineseRequest
import pw.janyo.whatanime.model.AniListChineseRequestVar
import pw.janyo.whatanime.model.AnimationHistory
import pw.janyo.whatanime.model.ResourceException
import pw.janyo.whatanime.model.SearchAnimeResult
import pw.janyo.whatanime.model.SearchQuota
import pw.janyo.whatanime.model.searchAnimeResultAdapter
import pw.janyo.whatanime.repository.local.service.HistoryService
import pw.janyo.whatanime.trackEvent
import pw.janyo.whatanime.utils.md5
import java.io.File
import java.util.Calendar
class AnimationRepository : KoinComponent {
companion object {
private const val TAG = "AnimationRepository"
}
private val searchApi: SearchApi by inject()
private val aniListChineseApi: AniListChineseApi by inject()
private val historyService: HistoryService by inject()
private suspend fun checkNetwork() {
withContext(DispatcherConfig.CHECK_NETWORK) {
if (!isOnline()) {
throw ResourceException(R.string.hint_no_network)
}
}
}
private suspend fun queryAnimationByImageOnline(
file: File,
originPath: String,
cachePath: String,
mimeType: String,
): SearchAnimeResult {
val history = queryByFileMd5(file)
if (history != null) {
return history
}
checkNetwork()
trackEvent("search image")
val data = withContext(DispatcherConfig.NETWORK) {
val data = if (Configure.cutBorders) {
searchApi.search(file.asRequestBody(), mimeType)
} else {
searchApi.searchNoCut(file.asRequestBody(), mimeType)
}
if (data.error.isNotBlank()) {
Log.e(TAG, "http request failed, ${data.error}")
throw ResourceException(R.string.hint_search_error)
}
data
}
if (Configure.showChineseTitle) {
val aniListIdSet = data.result.map { it.aniList.id }.toSet()
val chineseTitleMap = HashMap<Long, String>()
aniListIdSet.forEach {
val request = AniListChineseRequest(AniListChineseRequestVar(it))
val info = aniListChineseApi.getAniListInfo(request)
chineseTitleMap[it] = info.data.media.title.chinese ?: ""
}
for (item in data.result) {
item.aniList.title.chinese = chineseTitleMap[item.aniList.id] ?: ""
}
}
saveHistory(originPath, cachePath, data)
return data
}
suspend fun showQuota(): SearchQuota {
checkNetwork()
return withContext(DispatcherConfig.NETWORK) {
searchApi.getMe()
}
}
suspend fun queryAnimationByImageLocal(
file: File,
originPath: String,
cachePath: String,
mimeType: String,
): SearchAnimeResult {
val animationHistory = withContext(Dispatchers.IO) {
historyService.queryHistoryByOriginPath(originPath)
} ?: return queryAnimationByImageOnline(file, originPath, cachePath, mimeType)
return searchAnimeResultAdapter.fromJson(animationHistory.result)!!
}
private suspend fun queryByFileMd5(file: File): SearchAnimeResult? {
val md5 = file.md5()
val animationHistory = withContext(Dispatchers.IO) {
//用现有的originPath字段来存储md5
historyService.queryHistoryByOriginPath(md5)
} ?: return null
return searchAnimeResultAdapter.fromJson(animationHistory.result)
}
suspend fun queryHistoryByOriginPath(originPath: String): AnimationHistory? =
withContext(Dispatchers.IO) {
historyService.queryHistoryByOriginPath(originPath)
}
suspend fun getByHistoryId(historyId: Int): SearchAnimeResult? {
val history = withContext(Dispatchers.IO) {
historyService.getById(historyId)
} ?: return null
return searchAnimeResultAdapter.fromJson(history.result)
}
private suspend fun saveHistory(
originPath: String,
cachePath: String,
searchAnimeResult: SearchAnimeResult
) {
val animationHistory = withContext(Dispatchers.Default) {
AnimationHistory().apply {
this.originPath = originPath
this.cachePath = cachePath
this.result = searchAnimeResultAdapter.toJson(searchAnimeResult)
this.time = Calendar.getInstance().timeInMillis
if (searchAnimeResult.result.isNotEmpty()) {
val result = searchAnimeResult.result[0]
this.title = result.aniList.title.native ?: ""
this.anilistId = result.aniList.id
this.episode = ""
this.similarity = result.similarity
} else {
this.title = R.string.hint_no_result.resString()
}
}
}
withContext(Dispatchers.IO) {
historyService.saveHistory(animationHistory)
}
}
suspend fun queryAllHistory(): List<AnimationHistory> = withContext(Dispatchers.IO) {
historyService.queryAllHistory()
}
suspend fun deleteHistory(historyId: Int) =
withContext(Dispatchers.IO) {
val animationHistory = historyService.getById(historyId)
historyService.delete(historyId)
animationHistory?.let {
File(it.cachePath).delete()
}
}
} | apache-2.0 | 37d8b7f95179a7a78b26746a3793b70d | 36.193939 | 89 | 0.651565 | 4.610068 | false | true | false | false |
alashow/music-android | modules/core-ui-media/src/main/java/tm/alashow/datmusic/ui/artists/ArtistColumn.kt | 1 | 3258 | /*
* Copyright (C) 2021, Alashov Berkeli
* All rights reserved.
*/
package tm.alashow.datmusic.ui.artists
import androidx.compose.foundation.Image
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.material.Text
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Person
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.vector.rememberVectorPainter
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
import coil.compose.rememberImagePainter
import com.google.accompanist.placeholder.material.placeholder
import com.google.accompanist.placeholder.material.shimmer
import com.google.firebase.analytics.FirebaseAnalytics
import tm.alashow.base.imageloading.ImageLoading
import tm.alashow.base.util.click
import tm.alashow.common.compose.LocalAnalytics
import tm.alashow.datmusic.domain.entities.Artist
import tm.alashow.ui.components.CoverImage
import tm.alashow.ui.components.shimmer
import tm.alashow.ui.theme.AppTheme
object ArtistsDefaults {
val imageSize = 70.dp
val nameWidth = 100.dp
}
@Composable
fun ArtistColumn(
artist: Artist,
imageSize: Dp = ArtistsDefaults.imageSize,
nameWidth: Dp = ArtistsDefaults.nameWidth,
isPlaceholder: Boolean = false,
analytics: FirebaseAnalytics = LocalAnalytics.current,
onClick: (Artist) -> Unit = {},
) {
val loadingModifier = Modifier.placeholder(
visible = isPlaceholder,
highlight = shimmer(),
)
Column(
verticalArrangement = Arrangement.spacedBy(AppTheme.specs.paddingSmall),
horizontalAlignment = Alignment.CenterHorizontally,
modifier = Modifier
.clickable {
analytics.click("artist", mapOf("id" to artist.id))
if (!isPlaceholder) onClick(artist)
}
.fillMaxWidth()
.padding(AppTheme.specs.paddingTiny)
) {
val image = rememberImagePainter(artist.photo(), builder = ImageLoading.defaultConfig)
CoverImage(
painter = image,
icon = rememberVectorPainter(Icons.Default.Person),
shape = CircleShape,
size = imageSize
) { modifier ->
Image(
painter = image,
contentDescription = null,
contentScale = ContentScale.Crop,
modifier = modifier.then(loadingModifier)
)
}
Text(
artist.name,
maxLines = 1,
overflow = TextOverflow.Ellipsis,
textAlign = TextAlign.Center,
modifier = Modifier
.width(nameWidth)
.then(loadingModifier)
)
}
}
| apache-2.0 | f51f8d891bd4142f23c89008083afb7f | 34.032258 | 94 | 0.708717 | 4.647646 | false | false | false | false |
rock3r/detekt | detekt-rules/src/test/kotlin/io/gitlab/arturbosch/detekt/rules/exceptions/ReturnFromFinallySpec.kt | 1 | 2973 | package io.gitlab.arturbosch.detekt.rules.exceptions
import io.gitlab.arturbosch.detekt.test.TestConfig
import io.gitlab.arturbosch.detekt.test.compileAndLint
import org.assertj.core.api.Assertions.assertThat
import org.spekframework.spek2.Spek
import org.spekframework.spek2.style.specification.describe
class ReturnFromFinallySpec : Spek({
val subject by memoized { ReturnFromFinally() }
describe("ReturnFromFinally rule") {
context("a finally block with a return statement") {
val code = """
fun x() {
try {
} finally {
return
}
}
"""
it("should report") {
val findings = subject.compileAndLint(code)
assertThat(findings).hasSize(1)
}
}
context("a finally block with no return statement") {
val code = """
fun x() {
try {
} finally {
}
}
"""
it("should not report") {
val findings = subject.compileAndLint(code)
assertThat(findings).isEmpty()
}
}
context("a finally block with a nested return statement") {
val code = """
fun x() {
try {
} finally {
if (1 == 1) {
return
}
}
}
"""
it("should report") {
val findings = subject.compileAndLint(code)
assertThat(findings).hasSize(1)
}
}
context("a finally block with a return in an inner function") {
val code = """
fun x() {
try {
} finally {
fun y() {
return
}
y()
}
}
"""
it("should not report") {
val findings = subject.compileAndLint(code)
assertThat(findings).isEmpty()
}
}
context("a finally block with a return as labelled expression") {
val code = """
fun x() {
try {
} finally {
label@{
return@label
}
}
}
"""
it("should report when ignoreLabeled is false") {
val findings = subject.compileAndLint(code)
assertThat(findings).hasSize(1)
}
it("should not report when ignoreLabeled is true") {
val config = TestConfig(mapOf(ReturnFromFinally.IGNORE_LABELED to "true"))
val findings = ReturnFromFinally(config).compileAndLint(code)
assertThat(findings).isEmpty()
}
}
}
})
| apache-2.0 | d811ec6687bf97f0a3830fd0c39f877d | 27.314286 | 90 | 0.443996 | 5.59887 | false | false | false | false |
airien/workbits | android-sunflower-master/app/src/main/java/no/politiet/soip/adapters/PlantDetailBindingAdapters.kt | 1 | 2455 | /*
* 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
*
* 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 no.politiet.soip.adapters
import android.text.SpannableStringBuilder
import android.text.method.LinkMovementMethod
import android.widget.ImageView
import android.widget.TextView
import androidx.core.text.HtmlCompat
import androidx.core.text.HtmlCompat.FROM_HTML_MODE_COMPACT
import androidx.core.text.bold
import androidx.core.text.italic
import androidx.databinding.BindingAdapter
import com.bumptech.glide.Glide
import com.bumptech.glide.load.resource.drawable.DrawableTransitionOptions
import com.google.android.material.floatingactionbutton.FloatingActionButton
import no.politiet.soip.R
@BindingAdapter("imageFromUrl")
fun bindImageFromUrl(view: ImageView, imageUrl: String?) {
if (!imageUrl.isNullOrEmpty()) {
Glide.with(view.context)
.load(imageUrl)
.transition(DrawableTransitionOptions.withCrossFade())
.into(view)
}
}
@BindingAdapter("isGone")
fun bindIsGone(view: FloatingActionButton, isGone: Boolean?) {
if (isGone == null || isGone) {
view.hide()
} else {
view.show()
}
}
@BindingAdapter("renderHtml")
fun bindRenderHtml(view: TextView, description: String?) {
if (description != null) {
view.text = HtmlCompat.fromHtml(description, FROM_HTML_MODE_COMPACT)
view.movementMethod = LinkMovementMethod.getInstance()
} else {
view.text = ""
}
}
@BindingAdapter("wateringText")
fun bindWateringText(textView: TextView, wateringInterval: Int) {
val resources = textView.context.resources
val quantityString = resources.getQuantityString(R.plurals.watering_needs_suffix,
wateringInterval, wateringInterval)
textView.text = SpannableStringBuilder()
.bold { append(resources.getString(R.string.watering_needs_prefix)) }
.append(" ")
.italic { append(quantityString) }
} | lgpl-3.0 | ae48c55b70263f496b53314fa4587a47 | 33.111111 | 85 | 0.731161 | 4.269565 | false | false | false | false |
ccomeaux/boardgamegeek4android | app/src/main/java/com/boardgamegeek/ui/GeekListItemsFragment.kt | 1 | 5246 | package com.boardgamegeek.ui
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.core.view.isVisible
import androidx.fragment.app.Fragment
import androidx.fragment.app.activityViewModels
import androidx.lifecycle.LifecycleCoroutineScope
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.RecyclerView
import com.boardgamegeek.R
import com.boardgamegeek.databinding.FragmentGeeklistItemsBinding
import com.boardgamegeek.databinding.RowGeeklistItemBinding
import com.boardgamegeek.entities.GeekListEntity
import com.boardgamegeek.entities.GeekListItemEntity
import com.boardgamegeek.entities.Status
import com.boardgamegeek.extensions.inflate
import com.boardgamegeek.extensions.loadThumbnail
import com.boardgamegeek.provider.BggContract
import com.boardgamegeek.ui.adapter.AutoUpdatableAdapter
import com.boardgamegeek.ui.viewmodel.GeekListViewModel
import kotlinx.coroutines.launch
import kotlin.properties.Delegates
class GeekListItemsFragment : Fragment() {
private var _binding: FragmentGeeklistItemsBinding? = null
private val binding get() = _binding!!
private val viewModel by activityViewModels<GeekListViewModel>()
private val adapter: GeekListRecyclerViewAdapter by lazy { GeekListRecyclerViewAdapter(lifecycleScope) }
@Suppress("RedundantNullableReturnType")
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
_binding = FragmentGeeklistItemsBinding.inflate(inflater, container, false)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
binding.recyclerView.setHasFixedSize(true)
binding.recyclerView.adapter = adapter
viewModel.geekList.observe(viewLifecycleOwner) {
it?.let { (status, data, message) ->
when (status) {
Status.REFRESHING -> binding.progressView.show()
Status.ERROR -> setError(message)
Status.SUCCESS -> {
val geekListItems = data?.items
if (geekListItems == null || geekListItems.isEmpty()) {
setError(getString(R.string.empty_geeklist))
binding.recyclerView.isVisible = false
} else {
adapter.geekList = data
adapter.geekListItems = geekListItems.orEmpty()
binding.recyclerView.isVisible = true
binding.progressView.hide()
}
}
}
}
}
}
override fun onDestroyView() {
super.onDestroyView()
_binding = null
}
private fun setError(message: String?) {
binding.emptyView.text = message
binding.emptyView.isVisible = true
binding.progressView.hide()
}
class GeekListRecyclerViewAdapter(val lifecycleScope: LifecycleCoroutineScope) :
RecyclerView.Adapter<GeekListRecyclerViewAdapter.GeekListItemViewHolder>(), AutoUpdatableAdapter {
var geekListItems: List<GeekListItemEntity> by Delegates.observable(emptyList()) { _, oldValue, newValue ->
autoNotify(oldValue, newValue) { old, new ->
old.objectId == new.objectId
}
}
var geekList: GeekListEntity? = null
init {
setHasStableIds(true)
}
override fun getItemCount(): Int = geekListItems.size
override fun getItemId(position: Int) = geekListItems.getOrNull(position)?.id ?: RecyclerView.NO_ID
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): GeekListItemViewHolder {
return GeekListItemViewHolder(parent.inflate(R.layout.row_geeklist_item))
}
override fun onBindViewHolder(holder: GeekListItemViewHolder, position: Int) {
holder.bind(geekListItems.getOrNull(position), position + 1)
}
inner class GeekListItemViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
val binding = RowGeeklistItemBinding.bind(itemView)
fun bind(entity: GeekListItemEntity?, order: Int) {
entity?.let { item ->
binding.orderView.text = order.toString()
lifecycleScope.launch {
binding.thumbnailView.loadThumbnail(item.imageId)
}
binding.itemNameView.text = item.objectName
binding.usernameView.text = item.username
binding.usernameView.isVisible = item.username != geekList?.username
geekList?.let { list ->
itemView.setOnClickListener {
if (item.objectId != BggContract.INVALID_ID) {
GeekListItemActivity.start(itemView.context, list, item, order)
}
}
}
}
}
}
}
}
| gpl-3.0 | bf8dd59cef851226c7fcebfbe0644144 | 40.307087 | 116 | 0.640297 | 5.331301 | false | false | false | false |
wzhxyz/ACManager | src/main/java/com/zzkun/controller/api/UserACApi.kt | 1 | 2451 | package com.zzkun.controller.api
import com.alibaba.fastjson.JSONObject
import com.zzkun.dao.ExtOjLinkRepo
import com.zzkun.model.OJType
import com.zzkun.service.ExtOjService
import com.zzkun.service.UserService
import com.zzkun.util.uhunt.UHuntAnalyser
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.web.bind.annotation.PathVariable
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RequestMethod
import org.springframework.web.bind.annotation.RestController
/**
* Created by kun on 2016/9/30.
*/
@RestController
@RequestMapping("/api/userac")
class UserACApi {
@Autowired lateinit var userService: UserService
@Autowired lateinit var extojService: ExtOjService
@Autowired lateinit var extojLinkRepo: ExtOjLinkRepo
@Autowired lateinit var uhuntAnalyser: UHuntAnalyser
@RequestMapping(value = "/{username}/list",
method = arrayOf(RequestMethod.GET))
fun list(@PathVariable username: String): String {
val user = userService.getUserByUsername(username)
val list = extojService.getUserAC(user)
val map = mutableMapOf<String, MutableList<String>>()
val set = mutableSetOf<String>()
val visited = mutableSetOf<String>()
list.forEach {
val oj = it.ojName.toString()
val id = it.ojPbId
if(!visited.contains(oj+id)){
visited.add(oj + id)
set.add(oj)
if(!map.contains(oj))
map[oj] = mutableListOf<String>()
map[oj]?.add(id)
}
}
val json = JSONObject(true)
json["ojs"] = set.toList()
json["ac"] = map as Map<String, Any>?
return json.toString()
}
@RequestMapping(value = "/url/{oj}/{pid}", method = arrayOf(RequestMethod.GET))
fun url(@PathVariable oj: String, @PathVariable pid: String): String {
val type = OJType.valueOf(oj)
val link = extojLinkRepo.findOne(type).problemLink
if(type == OJType.UVA) {
return String.format(link, uhuntAnalyser.numToPid(pid))
} else if(type == OJType.CodeForces || type == OJType.Gym) {
return String.format(link, pid.substring(0, pid.length-1), pid.substring(pid.length-1))
}
return String.format(link, pid)
}
} | gpl-3.0 | 9138399e6d004ef15f2ef317314b4cf4 | 36.936508 | 99 | 0.647491 | 3.966019 | false | false | false | false |
RainoBoy97/Faucet | src/main/kotlin/me/raino/faucet/api/region/Rectangle.kt | 1 | 432 | package me.raino.faucet.api.region
import com.flowpowered.math.vector.Vector2d
import com.flowpowered.math.vector.Vector3d
class Rectangle(val min: Vector2d, val max: Vector2d) : Region {
override fun contains(point: Vector3d): Boolean = contains(point.toVector2(true))
override fun contains(point: Vector2d): Boolean {
return point.x >= min.x && point.x <= max.x && point.y >= min.y && point.y <= max.y
}
} | mit | cdf56a64808cb163faafd4161818e65f | 29.928571 | 91 | 0.701389 | 3.24812 | false | false | false | false |
ratabb/Hishoot2i | template/src/main/java/template/factory/Version3Factory.kt | 1 | 1298 | package template.factory
import android.content.Context
import common.PathBuilder.stringTemplateApp
import common.ext.openAssetsFrom
import template.Template.Version3
import template.TemplateConstants.TEMPLATE_CFG
import template.model.ModelV3
import java.io.InputStream
internal class Version3Factory(
private val appContext: Context,
private val packageName: String,
private val installedDate: Long,
private val decodeModel: (InputStream) -> ModelV3
) : Factory<Version3> {
override fun newTemplate(): Version3 {
val model = appContext.openAssetsFrom(packageName, TEMPLATE_CFG).use { decodeModel(it) }
val frame = stringTemplateApp(packageName, model.frame)
return Version3(
id = packageName,
author = model.author,
name = model.name,
desc = model.desc ?: "Template V3",
frame = frame,
preview = model.preview?.let { stringTemplateApp(packageName, it) } ?: frame,
sizes = model.size,
coordinate = model.coordinate,
installedDate = installedDate,
shadow = model.shadow?.let { stringTemplateApp(packageName, it) },
glares = model.glares?.map { it.copy(name = stringTemplateApp(packageName, it.name)) }
)
}
}
| apache-2.0 | cbd05d5037ab3118e650a67c54abc7c0 | 37.176471 | 98 | 0.673344 | 4.460481 | false | false | false | false |
matiuri/Minesweeper | core/src/kotlin/mati/minesweeper/gui/GUIHelper.kt | 1 | 14229 | package mati.minesweeper.gui
import com.badlogic.gdx.Gdx
import com.badlogic.gdx.audio.Sound
import com.badlogic.gdx.graphics.Color
import com.badlogic.gdx.graphics.OrthographicCamera
import com.badlogic.gdx.graphics.Texture
import com.badlogic.gdx.graphics.g2d.BitmapFont
import com.badlogic.gdx.graphics.g2d.TextureRegion
import com.badlogic.gdx.scenes.scene2d.InputEvent
import com.badlogic.gdx.scenes.scene2d.InputListener
import com.badlogic.gdx.scenes.scene2d.Stage
import com.badlogic.gdx.scenes.scene2d.ui.*
import com.badlogic.gdx.scenes.scene2d.utils.TextureRegionDrawable
import mati.advancedgdx.utils.*
import mati.minesweeper.Game
import mati.minesweeper.Game.Static.game
import mati.minesweeper.board.Board
import mati.minesweeper.gui.Timer.TimerSerializer
import mati.minesweeper.input.CamButtonListener
import mati.minesweeper.io.BoardSerializer
import mati.minesweeper.io.CamSerializer
import mati.minesweeper.io.CamSerializer.Serializer
import mati.minesweeper.screens.GameS
object GUIHelper {
fun GUIBase(gui: Stage, board: Board): Image {
if (isAndroid()) {
androidButtons(board, gui)
}
val guiTop: Image = Image(createNPD(game.astManager["GUIt", Texture::class], 0, 0, 24, 24))
guiTop.setBounds(0f, gui.height - 64, gui.width, 64f)
guiTop.color = Color.BLUE
gui.addActor(guiTop)
guiTop.addListener(object : InputListener() {
override fun touchDown(event: InputEvent?, x: Float, y: Float, pointer: Int, button: Int): Boolean {
return true
}
})
val guiBottom: Image = Image(createNPD(game.astManager["GUIb", Texture::class], 0, 0, 24, 24))
guiBottom.setBounds(0f, 0f, gui.width, 32f)
guiBottom.color = Color(Color.DARK_GRAY.r, Color.DARK_GRAY.g, Color.DARK_GRAY.b, 0.5f)
gui.addActor(guiBottom)
guiBottom.addListener(object : InputListener() {
override fun touchDown(event: InputEvent?, x: Float, y: Float, pointer: Int, button: Int): Boolean {
return true
}
})
return guiBottom
}
private fun androidButtons(board: Board, gui: Stage) {
val guiLeft: Image = Image(createNPD(game.astManager["GUIl", Texture::class], 24, 24, 0, 0))
guiLeft.setBounds(0f, 0f, 64f, gui.height)
guiLeft.color = Color.GOLD
gui.addActor(guiLeft)
guiLeft.addListener(object : InputListener() {
override fun touchDown(event: InputEvent?, x: Float, y: Float, pointer: Int, button: Int): Boolean {
return true
}
})
val table: Table = Table()
gui.addActor(table)
table.setBounds(0f, 32f + 24f, 64f, gui.height - 32f - 64f - 2f * 24f)
val buttonNull: TextButton = createButton("Safe", game.astManager["AndroidF", BitmapFont::class],
createNPD(game.astManager["ButtonUp", Texture::class], 8),
createNPD(game.astManager["ButtonDown", Texture::class], 8),
createNPD(game.astManager["ButtonDown", Texture::class], 8))
buttonNull.color = Color.GRAY
buttonNull.addListener2 { e, a ->
board.mode = Board.AndroidMode.NULL
}
table.add(buttonNull).pad(5f)
table.row()
val buttonOpen: TextButton = createButton("Open", game.astManager["AndroidF", BitmapFont::class],
createNPD(game.astManager["ButtonUp", Texture::class], 8),
createNPD(game.astManager["ButtonDown", Texture::class], 8),
createNPD(game.astManager["ButtonDown", Texture::class], 8))
buttonOpen.color = Color.RED
buttonOpen.addListener2 { e, a ->
board.mode = Board.AndroidMode.OPEN
}
table.add(buttonOpen).pad(5f)
table.row()
val buttonFlag: TextButton = createButton("Flag", game.astManager["AndroidF", BitmapFont::class],
createNPD(game.astManager["ButtonUp", Texture::class], 8),
createNPD(game.astManager["ButtonDown", Texture::class], 8),
createNPD(game.astManager["ButtonDown", Texture::class], 8))
buttonFlag.color = Color.BLUE
buttonFlag.addListener2 { e, a ->
board.mode = Board.AndroidMode.FLAG
}
table.add(buttonFlag).pad(5f)
val group: ButtonGroup<TextButton> = ButtonGroup(buttonNull, buttonOpen, buttonFlag)
group.setMinCheckCount(1)
group.setMaxCheckCount(1)
group.setChecked(buttonNull.text.toString())
}
fun guiButtons(board: Board, gui: Stage, timer: Timer, cam: OrthographicCamera): Array<CamButtonListener> {
val table: Table = Table()
gui.addActor(table)
table.setBounds(24f, gui.height - 64, gui.width - 48, 64f)
val image: Image = Image(createNPD(game.astManager["Dialog", Texture::class], 5))
image.setBounds(0f, 0f, gui.width, gui.height)
image.color = Color.RED
val pause: TextButton = createButton("", game.astManager["GeneralW", BitmapFont::class],
TextureRegionDrawable(TextureRegion(game.astManager["PauseUp", Texture::class])),
TextureRegionDrawable(TextureRegion(game.astManager["PauseDown", Texture::class])))
val dialog: Dialog = Dialog("", Window.WindowStyle(game.astManager["GeneralW", BitmapFont::class],
Color.WHITE, createNPD(game.astManager["Dialog", Texture::class], 5)))
dialog.color = Color.ORANGE
val resume: TextButton = createButton("Continue", game.astManager["GeneralW", BitmapFont::class],
createNPD(game.astManager["ButtonUp", Texture::class], 8),
createNPD(game.astManager["ButtonDown", Texture::class], 8))
resume.color = Color.GREEN
resume.addListener1 { e, a ->
if (isDesktop())
Gdx.graphics.setCursor(game.cursors[1])
if (!board.first)
timer.start()
dialog.hide()
image.remove()
}
dialog.button(resume)
val save: TextButton = createButton("Save and Exit", game.astManager["GeneralW", BitmapFont::class],
createNPD(game.astManager["ButtonUp", Texture::class], 8),
createNPD(game.astManager["ButtonDown", Texture::class], 8))
save.color = Color.YELLOW
save.addListener1 { e, a ->
game.ioManager.save("board", board, BoardSerializer())
game.ioManager.save("timer", timer, TimerSerializer())
val camSer: CamSerializer = CamSerializer()
camSer.init(cam)
game.ioManager.save("camera", camSer, Serializer())
game.scrManager.change("Title")
}
dialog.button(save)
val exit: TextButton = createButton("Leave Game", game.astManager["GeneralW", BitmapFont::class],
createNPD(game.astManager["ButtonUp", Texture::class], 8),
createNPD(game.astManager["ButtonDown", Texture::class], 8))
exit.color = Color(0.5f, 0f, 0f, 1f)
var secure: Boolean = false
exit.addListener1 { e, a ->
if (!secure) {
secure = true
exit.color = Color.RED
val runnable: Runnable = Runnable {
val time: Long = System.nanoTime()
var timeSec: Double = time / 1000000000.0
var currentTime: Double = 0.0
while (currentTime < 5.0) {
val temp: Double = System.nanoTime() / 1000000000.0
currentTime += temp - timeSec
timeSec = temp
}
secure = false
exit.color = Color(0.5f, 0f, 0f, 1f)
}
Thread(runnable).start()
} else {
game.ioManager.delete("board").delete("timer").delete("camera")
secure = false
game.scrManager.change("Title")
dialog.hide()
}
}
dialog.button(exit)
pause.addListener1 { e, a ->
exit.color = Color(0.5f, 0f, 0f, 1f)
secure = false
if (isDesktop())
Gdx.graphics.setCursor(game.cursors[0])
timer.stop()
gui.addActor(image)
dialog.show(gui)
}
table.add(pause).pad(5f)
val left: TextButton = createButton("", game.astManager["GeneralW", BitmapFont::class],
TextureRegionDrawable(TextureRegion(game.astManager["CamLU", Texture::class])),
TextureRegionDrawable(TextureRegion(game.astManager["CamLD", Texture::class])))
val CBLL = CamButtonListener()
left.addListener(CBLL)
table.add(left).pad(5f)
val up: TextButton = createButton("", game.astManager["GeneralW", BitmapFont::class],
TextureRegionDrawable(TextureRegion(game.astManager["CamUU", Texture::class])),
TextureRegionDrawable(TextureRegion(game.astManager["CamUD", Texture::class])))
val CBLU = CamButtonListener()
up.addListener(CBLU)
table.add(up).pad(5f)
val down: TextButton = createButton("", game.astManager["GeneralW", BitmapFont::class],
TextureRegionDrawable(TextureRegion(game.astManager["CamDU", Texture::class])),
TextureRegionDrawable(TextureRegion(game.astManager["CamDD", Texture::class])))
val CBLD = CamButtonListener()
down.addListener(CBLD)
table.add(down).pad(5f)
val right: TextButton = createButton("", game.astManager["GeneralW", BitmapFont::class],
TextureRegionDrawable(TextureRegion(game.astManager["CamRU", Texture::class])),
TextureRegionDrawable(TextureRegion(game.astManager["CamRD", Texture::class])))
val CBLR = CamButtonListener()
right.addListener(CBLR)
table.add(right).pad(5f)
val zUp: TextButton = createButton("", game.astManager["GeneralW", BitmapFont::class],
TextureRegionDrawable(TextureRegion(game.astManager["CamPU", Texture::class])),
TextureRegionDrawable(TextureRegion(game.astManager["CamPD", Texture::class])))
zUp.addListener1 { e, a ->
cam.zoom -= 0.25f
cam.update()
}
table.add(zUp).pad(5f)
val zDn: TextButton = createButton("", game.astManager["GeneralW", BitmapFont::class],
TextureRegionDrawable(TextureRegion(game.astManager["CamMU", Texture::class])),
TextureRegionDrawable(TextureRegion(game.astManager["CamMD", Texture::class])))
zDn.addListener1 { e, a ->
cam.zoom += 0.25f
cam.update()
}
table.add(zDn).pad(5f)
val zCn: TextButton = createButton("", game.astManager["GeneralW", BitmapFont::class],
TextureRegionDrawable(TextureRegion(game.astManager["CamCU", Texture::class])),
TextureRegionDrawable(TextureRegion(game.astManager["CamCD", Texture::class])))
zCn.addListener1 { e, a ->
cam.zoom = 1f
cam.update()
}
table.add(zCn).pad(5f)
return arrayOf(CBLL, CBLU, CBLD, CBLR)
}
fun gameOverDialog(gui: Stage) {
game.astManager["ExplosionS", Sound::class].play(0.5f)
val dialog: Dialog = Dialog("", Window.WindowStyle(Game.game.astManager["GameOverF", BitmapFont::class],
Color.WHITE, createNPD(Game.game.astManager["Dialog", Texture::class], 5)))
dialog.color = Color.RED
dialog.text(createLabel("Game Over!", Game.game.astManager["GameOverF", BitmapFont::class]))
val retry: TextButton = createButton("Try Again", Game.game.astManager["GeneralW", BitmapFont::class],
createNPD(Game.game.astManager["ButtonUp", Texture::class], 8),
createNPD(Game.game.astManager["ButtonDown", Texture::class], 8))
retry.color = Color.GREEN
retry.addListener1 { e, a ->
(Game.game.scrManager["Game"] as GameS).newGame = true
Game.game.scrManager.change("New")
dialog.hide()
}
dialog.button(retry)
val menu: TextButton = createButton("Main Menu", Game.game.astManager["GeneralW", BitmapFont::class],
createNPD(Game.game.astManager["ButtonUp", Texture::class], 8),
createNPD(Game.game.astManager["ButtonDown", Texture::class], 8))
menu.color = Color.RED
menu.addListener1 { e, a ->
Game.game.scrManager.change("Title")
dialog.hide()
}
dialog.button(menu)
dialog.show(gui)
}
fun winDialog(gui: Stage) {
game.astManager["WinS", Sound::class].play(0.5f)
val dialog: Dialog = Dialog("", Window.WindowStyle(Game.game.astManager["WinF", BitmapFont::class],
Color.WHITE, createNPD(Game.game.astManager["Dialog", Texture::class], 5)))
dialog.color = Color.GREEN
dialog.text(createLabel("Congratulations!", Game.game.astManager["WinF", BitmapFont::class]))
val replay: TextButton = createButton("Play Again",
Game.game.astManager["GeneralW", BitmapFont::class],
createNPD(Game.game.astManager["ButtonUp", Texture::class], 8),
createNPD(Game.game.astManager["ButtonDown", Texture::class], 8))
replay.color = Color.GREEN
replay.addListener1 { e, a ->
(Game.game.scrManager["Game"] as GameS).newGame = true
Game.game.scrManager.change("New")
dialog.hide()
}
dialog.button(replay)
val menu: TextButton = createButton("Main Menu", Game.game.astManager["GeneralW", BitmapFont::class],
createNPD(Game.game.astManager["ButtonUp", Texture::class], 8),
createNPD(Game.game.astManager["ButtonDown", Texture::class], 8))
menu.color = Color.RED
menu.addListener1 { e, a ->
Game.game.scrManager.change("Title")
dialog.hide()
}
dialog.button(menu)
dialog.show(gui)
}
}
| gpl-2.0 | 03f2cb076c8081f582bf708118827bd2 | 43.465625 | 112 | 0.609178 | 4.272973 | false | false | false | false |
Flank/simple-flank | src/test/kotlin/DslCompatibility.kt | 1 | 5752 | import java.io.File
import org.junit.Test
import strikt.api.expectThat
import strikt.assertions.isNotNull
import strikt.gradle.testkit.isSuccess
import strikt.gradle.testkit.task
class DslCompatibility : GradleTest() {
@Test
fun kotlinCompatibility() {
projectFromResources("app")
File(testProjectDir.root, "build.gradle.kts")
.appendText(
"""
simpleFlank {
// Changing the credentials file, default: rootProject.file("ftl-credentials.json")
credentialsFile.set(file("some-credentials.json"))
// Making the tests cacheable
hermeticTests.set(true)
// if all modules have hermetic tests, add `simple-flank.hermeticTests=true` to your `gradle.properties`
// Choosing the devices manually
// default is NexusLowRes, and the minSdk from the project
devices.set(listOf(
io.github.flank.gradle.NexusLowRes(23),
io.github.flank.gradle.NexusLowRes(30, "es_ES", io.github.flank.gradle.Device.Orientation.landscape),
io.github.flank.gradle.Device("oriole", 31, "Google", "Pixel 6")
))
// Filtering tests
testTargets {
inClass("io.flank.sample.TestClass")
notInClass("io.flank.sample.NotATestClass", "io.flank.sample.NotATestClassEither")
small() // or medium() or large()
annotation("io.flank.test.InstrumentationTest")
notAnnotation("io.flank.test.Flaky")
inPackage("io.flank.sample")
notInPackage("io.flank.external")
testFile("/sdcard/tmp/testFile.txt")
notTestFile("/sdcard/tmp/notTestFile.txt")
regex("BarTest.*")
filter("com.android.foo.MyCustomFilter", "com.android.foo.AnotherCustomFilter")
runnerBuilder("com.android.foo.MyCustomBuilder", "com.android.foo.AnotherCustomBuilder")
}
// EnvironmentVariables
// default
environmentVariables.set(mapOf("clearPackageData" to "true", "something" to "1", "whatever" to "I don't know"))
// default extracted from credentials
projectId.set("my-GCP-project")
// Downloading files
directoriesToPull.set(listOf("/sdcard/"))
filesToDownload.set(listOf("a.txt","b.txt"))
keepFilePath.set(true)
// other options
testTimeout.set("15m")
recordVideo.set(true)
numFlakyTestAttempts.set(3)
failFast.set(true)
performanceMetrics.set(true)
}
""".trimIndent())
val build = gradleRunner("flankDoctorDebug", "--stacktrace").forwardOutput().build()
expectThat(build) { task(":flankDoctorDebug").isNotNull().isSuccess() }
}
@Test
fun groovyCompatibility() {
projectFromResources("library")
File(testProjectDir.root, "build.gradle")
.appendText(
"""
simpleFlank {
// Changing the credentials file, default: rootProject.file("ftl-credentials.json")
credentialsFile = file("some-credentials.json")
// Making the tests cacheable
hermeticTests = true
// if all modules have hermetic tests, add `simple-flank.hermeticTests=true` to your `gradle.properties`
// Choosing the devices manually
// default is NexusLowRes, and the minSdk from the project
devices = [
new io.github.flank.gradle.NexusLowRes(23),
new io.github.flank.gradle.NexusLowRes(30, "es_ES", io.github.flank.gradle.Device.Orientation.landscape),
new io.github.flank.gradle.Device("oriole", 31, "Google", "Pixel 6")
]
// Filtering tests
testTargets {
inClass("io.flank.sample.TestClass")
notInClass("io.flank.sample.NotATestClass", "io.flank.sample.NotATestClassEither")
small() // or medium() or large()
annotation("io.flank.test.InstrumentationTest")
notAnnotation("io.flank.test.Flaky")
inPackage("io.flank.sample")
notInPackage("io.flank.external")
testFile("/sdcard/tmp/testFile.txt")
notTestFile("/sdcard/tmp/notTestFile.txt")
regex("BarTest.*")
filter("com.android.foo.MyCustomFilter", "com.android.foo.AnotherCustomFilter")
runnerBuilder("com.android.foo.MyCustomBuilder", "com.android.foo.AnotherCustomBuilder")
}
// EnvironmentVariables
// default
environmentVariables = [
clearPackageData: "true",
something: "1",
whatever: "I don't know"
]
// default extracted from credentials
projectId = "my-GCP-project"
// Downloading files
directoriesToPull = ["/sdcard/"]
filesToDownload = ["a.txt","b.txt"]
keepFilePath = true
// other options
testTimeout = "15m"
recordVideo = true
numFlakyTestAttempts = 3
failFast = true
performanceMetrics = true
}
""".trimIndent())
val build = gradleRunner("flankDoctorDebug", "--stacktrace").forwardOutput().build()
expectThat(build) { task(":flankDoctorDebug").isNotNull().isSuccess() }
}
}
| apache-2.0 | 7e5d0663c2df0b8737ba7ca40c0ef418 | 36.109677 | 125 | 0.563282 | 4.801336 | false | true | false | false |
NextFaze/dev-fun | devfun-internal/src/main/java/com/nextfaze/devfun/internal/android/Fragments.kt | 1 | 3001 | package com.nextfaze.devfun.internal.android
import android.content.DialogInterface
import android.os.Bundle
import androidx.appcompat.app.AppCompatDialogFragment
import androidx.fragment.app.DialogFragment
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentActivity
import androidx.fragment.app.FragmentManager
import kotlin.reflect.KClass
abstract class BaseDialogFragment : AppCompatDialogFragment() {
companion object {
inline fun <reified T : DialogFragment> show(activity: FragmentActivity, obtain: () -> T) =
activity.obtain { obtain() }.apply { takeIf { !it.isAdded }?.show(activity.supportFragmentManager) }
inline fun <reified T : DialogFragment> showNow(activity: FragmentActivity, obtain: () -> T) =
activity.obtain { obtain() }.apply { takeIf { !it.isAdded }?.showNow(activity.supportFragmentManager) }
inline fun <reified T : DialogFragment> dismiss(activity: FragmentActivity) =
activity.supportFragmentManager.find<T>()?.dismiss() != null
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
retainInstance = true
}
override fun onDestroyView() {
dialog?.takeIf { retainInstance }?.setDismissMessage(null) // Fix http:///issuetracker.google.com/17423
super.onDestroyView()
}
private var dismissPerformed = false
private fun performDismiss() {
if (dismissPerformed) return
dismissPerformed = true
onPerformDismiss()
}
/**
* We will not get an onDismiss callback if a dialog fragment is opened on an activity that is then finished while the dialog is open.
* However we generally want to clean up if we are destroyed, so worst-case we perform the dismiss callback then if it hasn't already happened.
*
* We do this instead of (only using) onDestroy as the destroy callback can/will happen a few messenger loops after dismiss which can
* cause some annoying UI bugs.
*/
open fun onPerformDismiss() = Unit
override fun onDestroy() {
super.onDestroy()
performDismiss()
}
override fun onDismiss(dialog: DialogInterface) {
super.onDismiss(dialog)
performDismiss()
}
}
inline fun <reified T : Fragment> FragmentManager.find() = findFragmentByTag(T::class.defaultTag) as T?
inline fun <reified T : Fragment> FragmentManager.obtain(factory: () -> T) = find() ?: factory.invoke()
inline fun <reified T : Fragment> FragmentActivity.obtain(factory: () -> T) = supportFragmentManager.obtain(factory)
fun DialogFragment.show(fragmentManager: FragmentManager) = show(fragmentManager, defaultTag)
fun DialogFragment.showNow(fragmentManager: FragmentManager) = showNow(fragmentManager, defaultTag)
val Fragment.defaultTag: String get() = this::class.java.defaultTag
val KClass<out Fragment>.defaultTag: String get() = java.defaultTag
val Class<out Fragment>.defaultTag: String get() = name
| apache-2.0 | 9b905f69099b27fe2334cb8a44b62482 | 41.267606 | 147 | 0.722093 | 4.733438 | false | false | false | false |
AoEiuV020/PaNovel | api/src/main/java/cc/aoeiuv020/panovel/api/site/n2kzw.kt | 1 | 4703 | package cc.aoeiuv020.panovel.api.site
import cc.aoeiuv020.anull.notNull
import cc.aoeiuv020.atry.tryOrNul
import cc.aoeiuv020.base.jar.absHref
import cc.aoeiuv020.panovel.api.NovelChapter
import cc.aoeiuv020.panovel.api.base.DslJsoupNovelContext
import cc.aoeiuv020.panovel.api.firstThreeIntPattern
import cc.aoeiuv020.panovel.api.firstTwoIntPattern
import cc.aoeiuv020.regex.compilePattern
import cc.aoeiuv020.string.lastDivide
import org.jsoup.nodes.Element
/**
* Created by AoEiuV020 on 2018.06.08-18:47:21.
*/
class N2kzw : DslJsoupNovelContext() {init {
site {
name = "2k中文网"
baseUrl = "https://www.2kzw.cc"
logo = "https://www.2kzw.com/17mb/images/logo.png"
}
// 这网站所有名字都是/遮天(精校版)/官道无疆(校对版)/
val pickName = { e: Element ->
e.text().replace(compilePattern("\\(\\S+版\\)$").toRegex(), "")
}
search {
post {
url = "//m.2kzw.cc/search/"
data {
"searchkey" to it
"searchtype" to "all"
}
}
document {
items("body > table > tbody > tr") {
name("> td:nth-child(2) > div > a:nth-child(1)", block = pickName)
author("> td:nth-child(2) > div > p > span.mr15", block = pickString("作者:(\\S+)"))
}
}
}
// http://www.2kzw.com/5/5798/
bookIdRegex = firstTwoIntPattern
detailPageTemplate = "/%s/"
detail {
document {
novel {
name("div.w100 > h1", block = pickName)
author("div.w100 > div.w100 > span", block = pickString("作\\s*者:(\\S*)"))
}
update(
"div[class=dispc] > span",
format = "yyyy-MM-dd HH:mm:ss",
block = pickString("最后更新:(.*)")
)
// https://www.2kzw.com/images/14/14196.jpg
tryOrNul {
image = site.baseUrl + "/images/$it.jpg"
}
introduction("div.info-main-intro")
}
}
chapters {
document {
items("div.container.border3-2.mt8.mb20 > div > a")
lastUpdate(
"div[class=dispc] > span",
format = "yyyy-MM-dd HH:mm:ss",
block = pickString("最后更新:(.*)")
)
}.let { list ->
var cacheExtra: String? = null
list.map { novelChapter ->
var extra = novelChapter.extra
val nextIndex = cacheExtra?.let { previousExtra ->
if (novelChapter.extra.isEmpty() || previousExtra.startsWith(novelChapter.extra)) {
val pair = previousExtra.lastDivide(':')
extra = pair.first
val lastIndex = try {
pair.second.toInt()
} catch (e: Exception) {
0
}
lastIndex + 1
} else {
0
}
} ?: 0
NovelChapter(
novelChapter.name,
"${extra}:${nextIndex}".also { cacheExtra = it },
novelChapter.update
)
}
}
}
// https://www.2kzw.com/38/38424/30595033.html
bookIdWithChapterIdRegex = firstThreeIntPattern
contentPageTemplate = "/%s.html"
getNovelContentUrl { extra ->
// 判断兼容老数据,
if (!extra.contains(':')) {
return@getNovelContentUrl contentPageTemplate.notNull().format(extra)
}
contentPageTemplate.notNull().format(extra.lastDivide(':').first)
}
content {
// 判断兼容老数据,
if (!extra.contains(':')) {
// 有些小说第一行是章节名,但不是所有,所以不能删除第一行,
return@content document {
items("#article")
}
}
var index = extra.lastDivide(':').second.toInt()
var chapterUrl: String = getNovelContentUrl(extra)
while (index > 0) {
call = connect(chapterUrl)
chapterUrl = parse(connect(chapterUrl)).let { root ->
root.requireElement("#next_url").absHref()
}
index--
}
get {
url = chapterUrl
}
document {
items("#article")
}
}
cookieFilter {
removeAll {
// 删除cookie绕开搜索时间间隔限制,
it.name() == "ss_search_delay"
}
}
}
}
| gpl-3.0 | 90b4012cb9dd7f5eaef43266a66f1036 | 30.978723 | 103 | 0.487913 | 4.058506 | false | false | false | false |
dafi/photoshelf | tumblr-ui-draft/src/main/java/com/ternaryop/photoshelf/tumblr/ui/draft/fragment/DraftSortBottomMenuListener.kt | 1 | 2061 | package com.ternaryop.photoshelf.tumblr.ui.draft.fragment
import android.view.Menu
import android.view.MenuItem
import com.google.android.material.bottomsheet.BottomSheetDialogFragment
import com.ternaryop.photoshelf.fragment.BottomMenuListener
import com.ternaryop.photoshelf.tumblr.ui.core.adapter.photo.PhotoSortSwitcher
import com.ternaryop.photoshelf.tumblr.ui.draft.R
class DraftSortBottomMenuListener(
private val draftListFragment: DraftListFragment,
private val sortSwitcher: PhotoSortSwitcher
) : BottomMenuListener {
override val title: String
get() = draftListFragment.resources.getString(R.string.sort_by)
override val menuId: Int
get() = R.menu.draft_sort
private val uploadTimeId =
if (sortSwitcher.sortable.isAscending) R.id.sort_upload_time_date_oldest else R.id.sort_upload_time_date_newest
private val tagNameId =
if (sortSwitcher.sortable.isAscending) R.id.sort_tag_name_a_z else R.id.sort_tag_name_z_a
override fun setupMenu(menu: Menu, sheet: BottomSheetDialogFragment) {
when (sortSwitcher.sortable.sortId) {
PhotoSortSwitcher.TAG_NAME -> menu.findItem(tagNameId).isChecked = true
PhotoSortSwitcher.LAST_PUBLISHED_TAG -> menu.findItem(R.id.sort_published_tag).isChecked = true
PhotoSortSwitcher.UPLOAD_TIME -> menu.findItem(uploadTimeId).isChecked = true
}
}
override fun onItemSelected(item: MenuItem, sheet: BottomSheetDialogFragment) {
when (item.itemId) {
R.id.sort_tag_name_a_z -> draftListFragment.sortBy(PhotoSortSwitcher.TAG_NAME, true)
R.id.sort_tag_name_z_a -> draftListFragment.sortBy(PhotoSortSwitcher.TAG_NAME, false)
R.id.sort_published_tag -> draftListFragment.sortBy(PhotoSortSwitcher.LAST_PUBLISHED_TAG, true)
R.id.sort_upload_time_date_newest -> draftListFragment.sortBy(PhotoSortSwitcher.UPLOAD_TIME, false)
R.id.sort_upload_time_date_oldest -> draftListFragment.sortBy(PhotoSortSwitcher.UPLOAD_TIME, true)
}
}
}
| mit | 26a3269841577ed86203c4beac8e6dbd | 48.071429 | 119 | 0.735565 | 3.933206 | false | false | false | false |
cout970/ComputerMod | src/main/kotlin/com/cout970/computer/gui/components/ButtonComponent.kt | 1 | 2836 | package com.cout970.computer.gui.components
import com.cout970.computer.gui.*
import com.cout970.computer.util.resource
import com.cout970.computer.util.vector.Vec2d
import net.minecraft.util.ResourceLocation
/**
* Created by cout970 on 20/05/2016.
*/
class SimpleButton(ID: Int, pos: Vec2d, listener: IButtonListener?,
val uv: Vec2d
) : AbstractStateButtonComponent(ID, pos, Vec2d(16, 16), listener, null, resource("textures/gui/buttons.png")){
override fun getOffset(): Vec2d {
when(state){
ButtonState.HOVER -> return uv + Vec2d(0, 16)
ButtonState.DOWN -> return uv + Vec2d(0, 32)
else -> return uv
}
}
}
abstract class AbstractStateButtonComponent(ID: Int = 0, pos: Vec2d, size: Vec2d = Vec2d(16, 16),
listener: IButtonListener? = null, sound: ResourceLocation? = null,
texture: ResourceLocation) : AbstractButton(ID, pos, size, listener, sound, texture) {
var state: ButtonState = ButtonState.NORMAL
override fun drawFirstLayer(gui: IGui, mouse: Vec2d, partialTicks: Float) {
if(isInside(mouse, pos, size)){
if(isMouseButtonDown(MOUSE_BUTTON_LEFT)){
state = ButtonState.DOWN
}else {
state = ButtonState.HOVER
}
}else{
state = ButtonState.NORMAL
}
super.drawFirstLayer(gui, mouse, partialTicks)
}
}
open class AbstractButton(
val ID: Int,
var pos: Vec2d,
val size: Vec2d,
var listener: IButtonListener?,
var sound: ResourceLocation?,
var texture: ResourceLocation
) : IComponent {
override fun drawFirstLayer(gui: IGui, mouse: Vec2d, partialTicks: Float) {
gui.bindTexture(texture)
gui.drawTexturedModalRect(pos, size, getOffset())
}
override fun onMouseClick(gui: IGui, mouse: Vec2d, mouseButton: Int): Boolean {
if (isInside(mouse, pos, size)) {
var press: Boolean
if (listener != null) {
press = listener?.onPress(this, mouse, mouseButton) ?: false
} else {
press = true
}
if (press) {
playSound()
return true
}
}
return false
}
open fun getOffset(): Vec2d = Vec2d()
open fun playSound() = {}
}
interface IButtonListener {
fun onPress(button: AbstractButton, mouse: Vec2d, mouseButton: Int): Boolean;
}
enum class ButtonState(val parent: ButtonState?) {
NORMAL(null),
HOVER(NORMAL),
DOWN(HOVER),
DISABLED(null),
DISABLED_HOVER(DISABLED),
DISABLED_DOWN(DISABLED_HOVER),
ACTIVE(null),
ACTIVE_HOVER(ACTIVE),
ACTIVE_DOWN(ACTIVE_HOVER),
HIGHLIGHT(null);
} | gpl-3.0 | 50a8a144430a1cd5224892c1a4727c97 | 29.180851 | 120 | 0.59732 | 4.092352 | false | false | false | false |
mrmike/DiffUtil-sample | app/src/main/java/com/moczul/diffutilsample/MainActivity.kt | 1 | 1558 | package com.moczul.diffutilsample
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.view.Menu
import android.view.MenuItem
class MainActivity : AppCompatActivity() {
private val repository = ActorRepository()
private val actorAdapter = ActorAdapter(repository.actorsSortedByRating)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val recyclerView = findViewById<RecyclerView>(R.id.recycler_view)
recyclerView.apply {
layoutManager = LinearLayoutManager(this@MainActivity)
adapter = actorAdapter
}
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
menuInflater.inflate(R.menu.sort_menu, menu)
return super.onCreateOptionsMenu(menu)
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
return when (item.itemId) {
R.id.sort_by_name -> {
actorAdapter.swap(repository.actorsSortedByName)
true
}
R.id.sort_by_rating -> {
actorAdapter.swap(repository.actorsSortedByRating)
true
}
R.id.sort_by_birth -> {
actorAdapter.swap(repository.actorsSortedByYearOfBirth)
true
}
else -> super.onOptionsItemSelected(item)
}
}
} | apache-2.0 | 22421ca287f1f2a65506707be308f16b | 31.479167 | 76 | 0.654044 | 4.853583 | false | false | false | false |
material-components/material-components-android-motion-codelab | app/src/main/java/com/materialstudies/reply/ui/nav/BottomNavigationDrawerCallback.kt | 1 | 4747 | /*
* Copyright 2020 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.materialstudies.reply.ui.nav
import android.annotation.SuppressLint
import android.view.View
import androidx.coordinatorlayout.widget.CoordinatorLayout
import com.google.android.material.R
import com.google.android.material.bottomsheet.BottomSheetBehavior
import com.materialstudies.reply.util.normalize
import kotlin.math.max
/**
* A [BottomSheetBehavior.BottomSheetCallback] which helps break apart clients who would like to
* react to changed in either the bottom sheet's slide offset or state. Clients can dynamically
* add or remove [OnSlideAction]s or [OnStateChangedAction]s which will be run when the
* sheet's slideOffset or state are changed.
*
* This callback's behavior differs slightly in that the slideOffset passed to [OnSlideAction]s
* in [onSlide] is corrected to guarantee that the offset 0.0 <i>always</i> be exactly at the
* [BottomSheetBehavior.STATE_HALF_EXPANDED] state.
*/
class BottomNavigationDrawerCallback : BottomSheetBehavior.BottomSheetCallback() {
private val onSlideActions: MutableList<OnSlideAction> = mutableListOf()
private val onStateChangedActions: MutableList<OnStateChangedAction> = mutableListOf()
private var lastSlideOffset = -1.0F
private var halfExpandedSlideOffset = Float.MAX_VALUE
override fun onSlide(sheet: View, slideOffset: Float) {
if (halfExpandedSlideOffset == Float.MAX_VALUE)
calculateInitialHalfExpandedSlideOffset(sheet)
lastSlideOffset = slideOffset
// Correct for the fact that the slideOffset is not zero when half expanded
val trueOffset = if (slideOffset <= halfExpandedSlideOffset) {
slideOffset.normalize(-1F, halfExpandedSlideOffset, -1F, 0F)
} else {
slideOffset.normalize(halfExpandedSlideOffset, 1F, 0F, 1F)
}
onSlideActions.forEach { it.onSlide(sheet, trueOffset) }
}
override fun onStateChanged(sheet: View, newState: Int) {
if (newState == BottomSheetBehavior.STATE_HALF_EXPANDED) {
halfExpandedSlideOffset = lastSlideOffset
onSlide(sheet, lastSlideOffset)
}
onStateChangedActions.forEach { it.onStateChanged(sheet, newState) }
}
/**
* Calculate the onSlideOffset which will be given when the bottom sheet is in the
* [BottomSheetBehavior.STATE_HALF_EXPANDED] state.
*
* Recording the correct slide offset for the half expanded state happens in [onStateChanged].
* Since the first time the sheet is opened, we haven't yet received a call to [onStateChanged],
* this method is used to calculate the initial value manually so we can smoothly normalize
* slideOffset values received between -1 and 1.
*
* See:
* [BottomSheetBehavior.calculateCollapsedOffset]
* [BottomSheetBehavior.calculateHalfExpandedOffset]
* [BottomSheetBehavior.dispatchOnSlide]
*/
@SuppressLint("PrivateResource")
private fun calculateInitialHalfExpandedSlideOffset(sheet: View) {
val parent = sheet.parent as CoordinatorLayout
val behavior = BottomSheetBehavior.from(sheet)
val halfExpandedOffset = parent.height * (1 - behavior.halfExpandedRatio)
val peekHeightMin = parent.resources.getDimensionPixelSize(
R.dimen.design_bottom_sheet_peek_height_min
)
val peek = max(peekHeightMin, parent.height - parent.width * 9 / 16)
val collapsedOffset = max(
parent.height - peek,
max(0, parent.height - sheet.height)
)
halfExpandedSlideOffset =
(collapsedOffset - halfExpandedOffset) / (parent.height - collapsedOffset)
}
fun addOnSlideAction(action: OnSlideAction): Boolean {
return onSlideActions.add(action)
}
fun removeOnSlideAction(action: OnSlideAction): Boolean {
return onSlideActions.remove(action)
}
fun addOnStateChangedAction(action: OnStateChangedAction): Boolean {
return onStateChangedActions.add(action)
}
fun removeOnStateChangedAction(action: OnStateChangedAction): Boolean {
return onStateChangedActions.remove(action)
}
} | apache-2.0 | 8124166d3444f907e806c7a29970d936 | 39.931034 | 100 | 0.723404 | 4.613217 | false | false | false | false |
yuzumone/Raid | app/src/main/kotlin/net/yuzumone/raid/MainActivity.kt | 1 | 3112 | package net.yuzumone.raid
import android.content.Context
import android.databinding.DataBindingUtil
import android.net.ConnectivityManager
import android.os.Bundle
import android.support.v4.app.Fragment
import android.support.v4.app.FragmentManager
import android.support.v4.app.FragmentPagerAdapter
import android.support.v7.app.AppCompatActivity
import android.view.Menu
import android.view.MenuItem
import android.widget.Toast
import com.androidnetworking.AndroidNetworking
import com.google.firebase.analytics.FirebaseAnalytics
import net.yuzumone.raid.databinding.ActivityMainBinding
import net.yuzumone.raid.fragment.MoriokaRaidFragment
import net.yuzumone.raid.fragment.TakizawaRaidFragment
class MainActivity : AppCompatActivity() {
lateinit private var binding: ActivityMainBinding
lateinit private var analytics: FirebaseAnalytics
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = DataBindingUtil.setContentView(this, R.layout.activity_main)
analytics = FirebaseAnalytics.getInstance(this)
AndroidNetworking.initialize(applicationContext)
if (savedInstanceState == null) {
if (isDeviceOnline()) {
val adapter = ViewPagerAdapter(supportFragmentManager)
binding.pager.adapter = adapter
binding.tab.setupWithViewPager(binding.pager)
val morioka = MoriokaRaidFragment()
adapter.add(getString(R.string.morioka), morioka)
val takizawa = TakizawaRaidFragment()
adapter.add(getString(R.string.takizawa), takizawa)
} else {
Toast.makeText(this, getString(R.string.no_internet), Toast.LENGTH_SHORT).show()
}
}
}
override fun onCreateOptionsMenu(menu: Menu?): Boolean {
menuInflater.inflate(R.menu.menu_main, menu)
return true
}
override fun onOptionsItemSelected(item: MenuItem?): Boolean {
when (item?.itemId) {
R.id.menu_notification -> {
PrefActivity.createIntent(this)
}
}
return super.onOptionsItemSelected(item)
}
private fun isDeviceOnline(): Boolean {
val connMgr = getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
val networkInfo = connMgr.activeNetworkInfo
return networkInfo != null && networkInfo.isConnected
}
class ViewPagerAdapter(fm: FragmentManager) : FragmentPagerAdapter(fm) {
private val fragments = ArrayList<Fragment>()
private val titles = ArrayList<String>()
override fun getItem(position: Int): Fragment {
return fragments[position]
}
override fun getCount(): Int {
return fragments.size
}
override fun getPageTitle(position: Int): CharSequence {
return titles[position]
}
fun add(title: String, fragment: Fragment) {
fragments.add(fragment)
titles.add(title)
notifyDataSetChanged()
}
}
}
| apache-2.0 | 6b83725e6ddc4df3be47be85e5e20d1e | 34.363636 | 96 | 0.682198 | 4.931854 | false | false | false | false |
joffrey-bion/mc-mining-optimizer | src/main/kotlin/org/hildan/minecraft/mining/optimizer/patterns/tunnels/TunnelPattern.kt | 1 | 882 | package org.hildan.minecraft.mining.optimizer.patterns.tunnels
import org.hildan.minecraft.mining.optimizer.blocks.Sample
/**
* Defines how to dig a tunnel. It is based on a [TunnelSection] repeated horizontally and vertically.
*/
data class TunnelPattern(
val section: TunnelSection,
val hSpacing: Int,
val vSpacing: Int,
) {
fun digInto(sample: Sample, originX: Int, originY: Int, originZ: Int, length: Int, direction: Axis) =
section.digInto(sample, originX, originY, originZ, length, direction)
companion object {
val STANDARD_SHAFT = TunnelPattern(TunnelSection.DOUBLE_MAN_SIZED, 23, 2)
val BIG_SHAFT = TunnelPattern(TunnelSection.BIG_CORRIDOR, 23, 1)
val STANDARD_BRANCH_2SPACED = TunnelPattern(TunnelSection.MAN_SIZED, 2, -1)
val STANDARD_BRANCH_3SPACED = TunnelPattern(TunnelSection.MAN_SIZED, 3, -1)
}
}
| mit | c43dc874c5eca3efaf9005a7a2ffd51c | 39.090909 | 105 | 0.718821 | 3.445313 | false | false | false | false |
peervalhoegen/SudoQ | sudoq-app/sudoqapp/src/main/kotlin/de/sudoq/persistence/sudoku/CCBBE.kt | 2 | 1070 | package de.sudoq.persistence.sudoku
import de.sudoq.model.sudoku.complexity.Complexity
import de.sudoq.model.sudoku.complexity.ComplexityConstraint
import de.sudoq.persistence.XmlTree
import de.sudoq.persistence.Xmlable
import java.util.HashMap
class CCBBE(var specimen: MutableMap<Complexity?, ComplexityConstraint> = HashMap())
: Xmlable {
override fun toXmlTree(): XmlTree {
val representation = XmlTree(TITLE)
for (v in specimen.values) {
representation.addChild(ComplexityConstraintMapper.toBE(v).toXmlTree())
}
return representation
}
@Throws(IllegalArgumentException::class)
override fun fillFromXml(xmlTreeRepresentation: XmlTree) {
specimen = HashMap()
for (sub in xmlTreeRepresentation) {
val ccBE = ComplexityConstraintBE()
ccBE.fillFromXml(sub)
val cc = ComplexityConstraintMapper.fromBE(ccBE)
specimen[cc.complexity] = cc
}
}
companion object {
const val TITLE = "ComplexityConstraintBuilder"
}
} | gpl-3.0 | 7386dc07e3608116d0800b9981e29c2f | 30.5 | 84 | 0.690654 | 4.612069 | false | false | false | false |
Undin/intellij-rust | src/main/kotlin/org/rust/ide/intentions/ReplaceLineCommentWithBlockCommentIntention.kt | 3 | 2899 | /*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.ide.intentions
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiComment
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiWhiteSpace
import org.rust.lang.core.parser.RustParserDefinition.Companion.EOL_COMMENT
import org.rust.lang.core.psi.RsPsiFactory
import org.rust.lang.core.psi.ext.ancestorOrSelf
import org.rust.lang.core.psi.ext.elementType
import org.rust.lang.core.psi.ext.getNextNonWhitespaceSibling
import org.rust.lang.core.psi.ext.getPrevNonWhitespaceSibling
@Suppress("UnnecessaryVariable")
class ReplaceLineCommentWithBlockCommentIntention : RsElementBaseIntentionAction<PsiComment>() {
override fun getText(): String = familyName
override fun getFamilyName(): String = "Replace with block comment"
override fun findApplicableContext(project: Project, editor: Editor, element: PsiElement): PsiComment? {
val comment = element.ancestorOrSelf<PsiComment>()
?.takeIf { it.elementType == EOL_COMMENT }
?: return null
return generateSequence(comment) { it.prevComment }.last()
}
override fun invoke(project: Project, editor: Editor, ctx: PsiComment) {
val firstLineComment = ctx
val indent = (firstLineComment.prevSibling as? PsiWhiteSpace)
?.text
?.substringAfterLast('\n')
.orEmpty()
val lineComments = generateSequence(firstLineComment) { it.nextComment }.toList()
val blockCommentText = if (lineComments.size == 1) {
" ${firstLineComment.content} "
} else {
lineComments.joinToString(separator = "\n", prefix = "\n", postfix = "\n$indent") {
"$indent${it.content}"
}
}
for (lineComment in lineComments.drop(1)) {
val prevSibling = lineComment.prevSibling
if (prevSibling is PsiWhiteSpace) {
prevSibling.delete()
}
lineComment.delete()
}
val newBlockComment = RsPsiFactory(project).createBlockComment(blockCommentText)
firstLineComment.replace(newBlockComment)
}
private val PsiComment.content: String
get() = text
.drop(LINE_COMMENT_PREFIX_LEN)
.replace("/*", "/ *")
.replace("*/", "* /")
.trim()
private val PsiComment.prevComment: PsiComment?
get() = (getPrevNonWhitespaceSibling() as? PsiComment)?.takeIf { it.elementType == EOL_COMMENT }
private val PsiComment.nextComment: PsiComment?
get() = (getNextNonWhitespaceSibling() as? PsiComment)?.takeIf { it.elementType == EOL_COMMENT }
companion object {
const val LINE_COMMENT_PREFIX_LEN: Int = 2 // the length of `//`
}
}
| mit | 83aff93ebbf0296261d4525aa4e681a7 | 35.696203 | 108 | 0.666437 | 4.594295 | false | false | false | false |
Undin/intellij-rust | src/main/kotlin/org/rust/ide/typing/paste/RsConvertJsonToStructCopyPasteProcessor.kt | 2 | 15870 | /*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.ide.typing.paste
import com.intellij.codeInsight.editorActions.CopyPastePostProcessor
import com.intellij.codeInsight.editorActions.TextBlockTransferableData
import com.intellij.openapi.application.invokeLater
import com.intellij.openapi.application.runWriteAction
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.editor.RangeMarker
import com.intellij.openapi.options.advanced.AdvancedSettings
import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.DoNotAskOption
import com.intellij.openapi.ui.MessageDialogBuilder
import com.intellij.openapi.ui.Messages
import com.intellij.openapi.util.Ref
import com.intellij.psi.PsiDocumentManager
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiFile
import com.intellij.psi.SmartPsiElementPointer
import org.jetbrains.annotations.TestOnly
import org.rust.RsBundle
import org.rust.ide.inspections.lints.toCamelCase
import org.rust.ide.inspections.lints.toSnakeCase
import org.rust.ide.statistics.RsConvertJsonToStructUsagesCollector
import org.rust.ide.utils.import.RsImportHelper
import org.rust.ide.utils.template.newTemplateBuilder
import org.rust.lang.core.psi.*
import org.rust.lang.core.psi.ext.RsMod
import org.rust.lang.core.psi.ext.RsQualifiedNamedElement
import org.rust.lang.core.psi.ext.ancestorStrict
import org.rust.lang.core.psi.ext.containingCargoPackage
import org.rust.lang.core.resolve.knownItems
import org.rust.lang.core.resolve2.allScopeItemNames
import org.rust.openapiext.createSmartPointer
import org.rust.openapiext.isUnitTestMode
import org.rust.openapiext.runWriteCommandAction
import org.rust.openapiext.toPsiFile
import java.awt.datatransfer.DataFlavor
import java.awt.datatransfer.Transferable
class RsConvertJsonToStructCopyPasteProcessor : CopyPastePostProcessor<TextBlockTransferableData>() {
override fun collectTransferableData(
file: PsiFile,
editor: Editor,
startOffsets: IntArray,
endOffsets: IntArray
): List<TextBlockTransferableData> = emptyList()
override fun extractTransferableData(content: Transferable): List<TextBlockTransferableData> {
try {
if (content.isDataFlavorSupported(DataFlavor.stringFlavor)) {
val text = content.getTransferData(DataFlavor.stringFlavor) as String
return listOf(PotentialJsonTransferableData(text))
}
return emptyList()
} catch (e: Throwable) {
return emptyList()
}
}
override fun processTransferableData(
project: Project,
editor: Editor,
bounds: RangeMarker,
caretOffset: Int,
indented: Ref<in Boolean>,
values: List<TextBlockTransferableData>
) {
val file = editor.document.toPsiFile(project) as? RsFile ?: return
val data = values.getOrNull(0) as? PotentialJsonTransferableData ?: return
val text = data.text
val elementAtCaret = file.findElementAt(caretOffset)
if (elementAtCaret != null && elementAtCaret.parent !is RsMod) return
val structs = extractStructsFromJson(text) ?: return
RsConvertJsonToStructUsagesCollector.logJsonTextPasted()
if (!shouldConvertJson(project)) return
val factory = RsPsiFactory(project)
// The only time `elementAtCaret` could be null is if we are pasting into an empty file
val parentMod = elementAtCaret?.parent as? RsMod ?: file
val existingNames = parentMod.allScopeItemNames()
val nameMap = generateStructNames(structs, existingNames)
val psiDocumentManager = PsiDocumentManager.getInstance(project)
val insertedItems: MutableList<SmartPsiElementPointer<RsStructItem>> = mutableListOf()
val hasSerdeDependency = hasSerdeDependency(file)
runWriteAction {
// Delete original text
editor.document.deleteString(bounds.startOffset, bounds.endOffset)
psiDocumentManager.commitDocument(editor.document)
val element = file.findElementAt(caretOffset)
val parent = element?.parent ?: file
var anchor = element
for (struct in structs) {
val inserted = createAndInsertStruct(factory, anchor, parent, struct, nameMap, hasSerdeDependency) ?: continue
anchor = inserted
insertedItems.add(inserted.createSmartPointer())
}
}
if (insertedItems.isNotEmpty()) {
replacePlaceholders(editor, insertedItems, nameMap, file)
}
RsConvertJsonToStructUsagesCollector.logPastedJsonConverted()
}
}
private var CONVERT_JSON_SERDE_PRESENT: Boolean = false
@TestOnly
fun convertJsonWithSerdePresent(hasSerde: Boolean, action: () -> Unit) {
val original = CONVERT_JSON_SERDE_PRESENT
CONVERT_JSON_SERDE_PRESENT = hasSerde
try {
action()
} finally {
CONVERT_JSON_SERDE_PRESENT = original
}
}
private fun hasSerdeDependency(file: RsFile): Boolean {
if (isUnitTestMode && CONVERT_JSON_SERDE_PRESENT) {
return true
}
return file.containingCargoPackage?.dependencies?.any { it.name == "serde" } == true
}
enum class StoredPreference {
YES,
NO,
ASK_EVERY_TIME;
override fun toString(): String = when (this) {
YES -> "Yes"
NO -> "No"
ASK_EVERY_TIME -> "Ask every time"
}
}
private fun shouldConvertJson(project: Project): Boolean {
return if (isUnitTestMode) {
true
} else {
when (AdvancedSettings.getEnum("org.rust.convert.json.to.struct", StoredPreference::class.java)) {
StoredPreference.YES -> true
StoredPreference.NO -> false
StoredPreference.ASK_EVERY_TIME -> {
MessageDialogBuilder.yesNo(
title=RsBundle.message("copy.paste.convert.json.to.struct.dialog.title"),
message=RsBundle.message("copy.paste.convert.json.to.struct.dialog.text")
)
.yesText(Messages.getYesButton())
.noText(Messages.getNoButton())
.icon(Messages.getQuestionIcon())
.doNotAsk(object : DoNotAskOption.Adapter() {
override fun rememberChoice(isSelected: Boolean, exitCode: Int) {
if (isSelected) {
val value = when (exitCode) {
Messages.YES -> StoredPreference.YES
else -> StoredPreference.NO
}
AdvancedSettings.setEnum("org.rust.convert.json.to.struct", value)
// `exitCode != Messages.CANCEL` is always true since we don't override `shouldSaveOptionsOnCancel`
RsConvertJsonToStructUsagesCollector.logRememberChoiceResult(value == StoredPreference.YES)
}
}
})
.ask(project)
}
}
}
}
private fun generateStructNames(structs: List<Struct>, existingNames: Set<String>): Map<Struct, String> {
val map = mutableMapOf<Struct, String>()
if (structs.isEmpty()) return map
val assignedNames = existingNames.toMutableSet()
val assignName = { struct: Struct, name: String ->
val normalizedName = normalizeStructName(name)
val actualName = if (normalizedName in assignedNames) {
generateSequence(1) { it + 1 }
.map { "$normalizedName$it" }
.first { it !in assignedNames }
} else {
normalizedName
}
assignedNames.add(actualName)
map[struct] = actualName
}
assignName(structs.last(), "Root")
// Maps structs to fields under which they are embedded
val structEmbeddedFields = mutableMapOf<Struct, MutableSet<String>>()
val visitor = object: DataTypeVisitor() {
override fun visitStruct(dataType: DataType.StructRef) {
for ((field, type) in dataType.struct.fields) {
val innerType = type.unwrap()
if (innerType is DataType.StructRef) {
structEmbeddedFields.getOrPut(innerType.struct) { mutableSetOf() }.add(field)
}
}
super.visitStruct(dataType)
}
}
visitor.visit(DataType.StructRef(structs.last()))
for (struct in structs.reversed()) {
if (struct !in map) {
val fields = structEmbeddedFields[struct].orEmpty()
if (fields.size == 1) {
assignName(struct, fields.first())
} else {
assignName(struct, "Struct")
}
}
}
return map
}
/**
* Creates a PSI struct from the given Struct datatype description and inserts it after the given anchor.
*/
private fun createAndInsertStruct(
factory: RsPsiFactory,
anchor: PsiElement?,
parent: PsiElement,
struct: Struct,
nameMap: Map<Struct, String>,
hasSerdeDependency: Boolean
): RsStructItem? {
val structPsi = generateStruct(factory, struct, nameMap, hasSerdeDependency) ?: return null
val inserted = if (anchor == null) {
parent.add(structPsi)
} else {
parent.addAfter(structPsi, anchor)
} as RsStructItem
if (hasSerdeDependency) {
val knownItems = inserted.knownItems
val traits: List<RsQualifiedNamedElement> = listOfNotNull(
knownItems.findItem("serde::Serialize", isStd = false),
knownItems.findItem("serde::Deserialize", isStd = false)
)
for (trait in traits) {
RsImportHelper.importElement(inserted, trait)
}
}
return inserted
}
private fun StringBuilder.writeStructField(
field: String,
type: DataType,
structNameMap: Map<Struct, String>,
generatedFieldNames: MutableSet<String>,
hasSerdeDependency: Boolean
) {
val normalizedName = createFieldName(field, generatedFieldNames)
val serdeType = getSerdeType(type, structNameMap)
if (hasSerdeDependency && field != normalizedName) {
// Escape quotes
val rawField = field.replace("\"", "\\\"")
append("#[serde(rename = \"$rawField\")]\n")
}
append("pub $normalizedName: ${serdeType},\n")
generatedFieldNames.add(normalizedName)
}
private fun generateStruct(
factory: RsPsiFactory,
struct: Struct,
nameMap: Map<Struct, String>,
hasSerdeDependency: Boolean
): RsStructItem? {
val structString = buildString {
if (hasSerdeDependency) {
append("#[derive(Serialize, Deserialize)]\n")
}
append("struct ${nameMap[struct]} {\n")
val names = mutableSetOf<String>()
for ((field, type) in struct.fields) {
writeStructField(field, type, nameMap, names, hasSerdeDependency)
}
append("}")
}
return factory.tryCreateStruct(structString)
}
private val NON_IDENTIFIER_REGEX: Regex = Regex("[^a-zA-Z_0-9]")
private fun normalizeName(name: String, placeholder: String, caseConversion: (String) -> String): String {
var normalized = name.replace(NON_IDENTIFIER_REGEX, "_")
normalized = caseConversion(normalized)
if (normalized.getOrNull(0)?.isDigit() == true) {
normalized = "_$normalized"
}
if (normalized.all { it == '_' }) {
normalized += placeholder
}
return normalized.escapeIdentifierIfNeeded()
}
private fun normalizeFieldName(field: String): String {
return normalizeName(field, "field") { it.toSnakeCase(false) }
}
private fun normalizeStructName(struct: String): String {
return normalizeName(struct, "Struct") { it.toCamelCase() }
}
private fun createFieldName(field: String, generatedFieldNames: Set<String>): String {
val normalizedName = normalizeFieldName(field)
if (normalizedName !in generatedFieldNames) return normalizedName
return generateSequence(0) { it + 1 }
.map { "${normalizedName}_$it" }
.first { it !in generatedFieldNames }
}
private fun getSerdeType(type: DataType, nameMap: Map<Struct, String>): String {
return when (type) {
DataType.Boolean -> "bool"
DataType.String -> "String"
DataType.Integer -> "i64"
DataType.Float -> "f64"
is DataType.Nullable -> "Option<${getSerdeType(type.type, nameMap)}>"
is DataType.StructRef -> nameMap[type.struct] ?: "_"
is DataType.Array -> "Vec<${getSerdeType(type.type, nameMap)}>"
DataType.Unknown -> "_"
}
}
/**
* Replace generated struct names and _ types in the inserted structs.
*/
private fun replacePlaceholders(
editor: Editor,
insertedItems: List<SmartPsiElementPointer<RsStructItem>>,
nameMap: Map<Struct, String>,
file: RsFile
) {
invokeLater {
if (editor.isDisposed) return@invokeLater
editor.project?.runWriteCommandAction {
if (!file.isValid) return@runWriteCommandAction
val template = editor.newTemplateBuilder(file) ?: return@runWriteCommandAction
// Gather usages of structs in fields
val structNames = nameMap.values.toSet()
val visitor = StructFieldVisitor(structNames)
val items = insertedItems.mapNotNull { it.element }
items.forEach { it.accept(visitor) }
val nameUsages = visitor.usages
// Gather struct names, references to struct names and _ placeholders
for (item in items) {
val identifier = item.identifier
if (identifier != null) {
val variable = template.introduceVariable(identifier)
for (usage in nameUsages[identifier.text].orEmpty()) {
variable.replaceElementWithVariable(usage)
}
}
val underscoreVisitor = InferTypeVisitor()
item.accept(underscoreVisitor)
for (wildcard in underscoreVisitor.types) {
template.replaceElement(wildcard)
}
}
template.runInline()
}
}
}
/**
* Looks for underscore (`_`) types.
*/
private class InferTypeVisitor : RsRecursiveVisitor() {
private val _types: MutableSet<RsInferType> = linkedSetOf()
val types: Set<RsInferType> get() = _types
override fun visitInferType(o: RsInferType) {
_types.add(o)
super.visitInferType(o)
}
}
/**
* Looks for base paths that are contained in `nameMap`.
* Returns a mapping from name to a list of usages of that name.
*/
private class StructFieldVisitor(private val structNames: Set<String>) : RsRecursiveVisitor() {
private val _usages = linkedMapOf<String, MutableList<PsiElement>>()
val usages: Map<String, List<PsiElement>> get() = _usages
override fun visitPathType(o: RsPathType) {
val path = o.text
if (o.ancestorStrict<RsNamedFieldDecl>() != null && path in structNames) {
_usages.getOrPut(path) { mutableListOf() }.add(o)
}
super.visitPathType(o)
}
}
private class PotentialJsonTransferableData(val text: String) : TextBlockTransferableData {
override fun getFlavor(): DataFlavor = DATA_FLAVOR
override fun getOffsetCount(): Int = 0
override fun getOffsets(offsets: IntArray, index: Int): Int = index
override fun setOffsets(offsets: IntArray, index: Int): Int = index
companion object {
val DATA_FLAVOR: DataFlavor = DataFlavor(
RsConvertJsonToStructCopyPasteProcessor::class.java,
"class: RsConvertJsonToStructCopyPasteProcessor"
)
}
}
| mit | 48db9ec9f6b80ac3dbbbd2fea00567dc | 34.345212 | 131 | 0.648771 | 4.63493 | false | false | false | false |
Undin/intellij-rust | src/main/kotlin/org/rust/ide/inspections/RsLiftInspection.kt | 2 | 5315 | /*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.ide.inspections
import com.intellij.codeInspection.LocalQuickFix
import com.intellij.codeInspection.ProblemDescriptor
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiElement
import org.rust.lang.core.psi.*
import org.rust.lang.core.psi.ext.RsElement
import org.rust.lang.core.psi.ext.ancestorStrict
import org.rust.lang.core.psi.ext.arms
import org.rust.lang.core.psi.ext.hasSemicolon
import org.rust.openapiext.Testmark
class RsLiftInspection : RsLocalInspectionTool() {
override fun buildVisitor(holder: RsProblemsHolder, isOnTheFly: Boolean): RsVisitor {
return object : RsVisitor() {
override fun visitIfExpr(o: RsIfExpr) {
if (o.parent is RsElseBranch) return
checkExpr(o, o.`if`)
}
override fun visitMatchExpr(o: RsMatchExpr) {
checkExpr(o, o.match)
}
private fun checkExpr(e: RsExpr, keyword: PsiElement) {
if (e.hasFoldableReturns) {
holder.register(e, keyword)
}
}
}
}
override val isSyntaxOnly: Boolean = true
private fun RsProblemsHolder.register(expr: RsExpr, keyword: PsiElement) {
val keywordName = keyword.text
registerProblem(
expr,
keyword.textRangeInParent,
"Return can be lifted out of '$keywordName'",
LiftReturnOutFix(keywordName)
)
}
private class LiftReturnOutFix(private val keyword: String) : LocalQuickFix {
override fun getName(): String = "Lift return out of '$keyword'"
override fun getFamilyName(): String = "Lift return"
override fun applyFix(project: Project, descriptor: ProblemDescriptor) {
val expr = descriptor.psiElement as RsExpr
val foldableReturns = expr.getFoldableReturns() ?: return
val factory = RsPsiFactory(project)
for (foldableReturn in foldableReturns) {
foldableReturn.elementToReplace.replaceWithTailExpr(factory.createExpression(foldableReturn.expr.text))
}
val parent = expr.parent
if (parent !is RsRetExpr) {
(parent as? RsMatchArm)?.addCommaIfNeeded(factory)
expr.replace(factory.createRetExpr(expr.text))
} else {
Testmarks.InsideRetExpr.hit()
}
}
private fun RsMatchArm.addCommaIfNeeded(psiFactory: RsPsiFactory) {
if (comma != null) return
val arms = ancestorStrict<RsMatchExpr>()?.arms ?: return
val index = arms.indexOf(this)
if (index == -1 || index == arms.size - 1) return
add(psiFactory.createComma())
}
}
object Testmarks {
object InsideRetExpr : Testmark()
}
}
private fun RsElement.replaceWithTailExpr(expr: RsExpr) {
when (this) {
is RsExpr -> replace(expr)
is RsStmt -> {
val newStmt = RsPsiFactory(project).tryCreateExprStmtWithoutSemicolon("()")!!
newStmt.expr.replace(expr)
replace(newStmt)
}
}
}
private data class FoldableElement(val expr: RsExpr, val elementToReplace: RsElement)
private val RsExpr.hasFoldableReturns: Boolean get() = getFoldableReturns() != null
private fun RsExpr.getFoldableReturns(): List<FoldableElement>? {
val result = mutableListOf<FoldableElement>()
fun RsElement.collectFoldableReturns(): Boolean {
when (this) {
is RsRetExpr -> {
val expr = expr ?: return false
result += FoldableElement(expr, this)
}
is RsExprStmt -> {
if (hasSemicolon) {
val retExpr = expr as? RsRetExpr ?: return false
val expr = retExpr.expr ?: return false
result += FoldableElement(expr, this)
} else {
if (!expr.collectFoldableReturns()) return false
}
}
is RsBlock -> {
val lastChild = children.lastOrNull() as? RsElement ?: return false
if (!lastChild.collectFoldableReturns()) return false
}
is RsBlockExpr -> {
if (!block.collectFoldableReturns()) return false
}
is RsIfExpr -> {
if (block?.collectFoldableReturns() != true) return false
val elseIf = elseBranch?.ifExpr
if (elseIf != null) {
if (!elseIf.collectFoldableReturns()) return false
} else {
if (elseBranch?.block?.collectFoldableReturns() != true) return false
}
}
is RsMatchExpr -> {
val arms = matchBody?.matchArmList ?: return false
if (arms.isEmpty()) return false
for (arm in arms) {
if (arm.expr?.collectFoldableReturns() != true) return false
}
}
else -> return false
}
return true
}
return if (collectFoldableReturns()) result else null
}
| mit | 2585546aa49ce8d50ae1a91471e08dce | 34.912162 | 119 | 0.582502 | 4.907664 | false | false | false | false |
Senspark/ee-x | src/android/firebase_performance/src/main/java/com/ee/internal/FirebasePerformanceTrace.kt | 1 | 2772 | package com.ee.internal
import androidx.annotation.AnyThread
import com.ee.IMessageBridge
import com.google.firebase.perf.metrics.Trace
import kotlinx.serialization.Serializable
internal class FirebasePerformanceTrace(
private val _bridge: IMessageBridge,
private val _trace: Trace,
private val _traceName: String) {
companion object {
private const val kPrefix = "FirebasePerformance"
}
init {
registerHandlers()
}
fun destroy() {
deregisterHandlers()
}
private val kStart: String
@AnyThread get() = "${kPrefix}_start_$_traceName"
private val kStop: String
@AnyThread get() = "${kPrefix}_stop_$_traceName"
private val kIncrementMetric: String
@AnyThread get() = "${kPrefix}_incrementMetric_$_traceName"
private val kGetLongMetric: String
@AnyThread get() = "${kPrefix}_getLongMetric_$_traceName"
private val kPutMetric: String
@AnyThread get() = "${kPrefix}_putMetric_$_traceName"
@Serializable
private class IncrementMetricRequest(
val key: String,
val value: Long
)
@Serializable
private class PutMetricRequest(
val key: String,
val value: Long
)
@AnyThread
private fun registerHandlers() {
_bridge.registerHandler(kStart) {
start()
""
}
_bridge.registerHandler(kStop) {
stop()
""
}
_bridge.registerHandler(kIncrementMetric) { message ->
val request = deserialize<IncrementMetricRequest>(message)
incrementMetric(request.key, request.value)
""
}
_bridge.registerHandler(kPutMetric) { message ->
val request = deserialize<PutMetricRequest>(message)
putMetric(request.key, request.value)
""
}
_bridge.registerHandler(kGetLongMetric) { message ->
getLongMetric(message).toString()
}
}
@AnyThread
private fun deregisterHandlers() {
_bridge.deregisterHandler(kStart)
_bridge.deregisterHandler(kStop)
_bridge.deregisterHandler(kIncrementMetric)
_bridge.deregisterHandler(kPutMetric)
_bridge.deregisterHandler(kGetLongMetric)
}
@AnyThread
fun start() {
_trace.start()
}
@AnyThread
fun stop() {
_trace.stop()
}
@AnyThread
private fun incrementMetric(name: String, value: Long) {
_trace.incrementMetric(name, value)
}
@AnyThread
private fun putMetric(name: String, value: Long) {
_trace.putMetric(name, value)
}
@AnyThread
private fun getLongMetric(name: String): Long {
return _trace.getLongMetric(name)
}
} | mit | 1e6d14ac00aaa53c7418e1be8dfe17fc | 24.440367 | 70 | 0.618326 | 4.551724 | false | false | false | false |
foreverigor/TumCampusApp | app/src/main/java/de/tum/in/tumcampusapp/api/tumonline/interceptors/AddTokenInterceptor.kt | 1 | 1253 | package de.tum.`in`.tumcampusapp.api.tumonline.interceptors
import android.content.Context
import android.preference.PreferenceManager
import de.tum.`in`.tumcampusapp.utils.Const
import okhttp3.Interceptor
import okhttp3.Response
class AddTokenInterceptor(private val context: Context) : Interceptor {
private val accessToken: String?
get() = loadAccessTokenFromPreferences(context)
private fun loadAccessTokenFromPreferences(context: Context): String? {
return PreferenceManager
.getDefaultSharedPreferences(context)
.getString(Const.ACCESS_TOKEN, null)
}
override fun intercept(chain: Interceptor.Chain): Response {
val request = chain.request()
var url = request.url()
//Do not add any token for requesting a new token. This would result in a 404
if(url.encodedPath().contains("requestToken")) {
return chain.proceed(request);
}
accessToken?.let {
url = url
.newBuilder()
.addQueryParameter("pToken", it)
.build()
}
val modifiedRequest = request.newBuilder().url(url).build()
return chain.proceed(modifiedRequest)
}
} | gpl-3.0 | 047b0930105e6ae8f31cc9074db84bdf | 30.35 | 85 | 0.650439 | 4.992032 | false | false | false | false |
androidx/androidx | paging/integration-tests/testapp/src/main/java/androidx/paging/integration/testapp/v3/StateItemAdapter.kt | 3 | 2496 | /*
* 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.paging.integration.testapp.v3
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.ProgressBar
import android.widget.TextView
import androidx.paging.LoadState
import androidx.paging.LoadStateAdapter
import androidx.paging.integration.testapp.R
import androidx.recyclerview.widget.RecyclerView
class LoadStateViewHolder(
parent: ViewGroup,
retry: () -> Unit
) : RecyclerView.ViewHolder(inflate(parent)) {
private val progressBar: ProgressBar = itemView.findViewById(R.id.progress_bar)
private val errorMsg: TextView = itemView.findViewById(R.id.error_msg)
private val retry: Button = itemView.findViewById<Button>(R.id.retry_button)
.also { it.setOnClickListener { retry.invoke() } }
fun bind(loadState: LoadState) {
if (loadState is LoadState.Error) {
errorMsg.text = loadState.error.localizedMessage
}
progressBar.visibility = toVisibility(loadState is LoadState.Loading)
retry.visibility = toVisibility(loadState !is LoadState.Loading)
errorMsg.visibility = toVisibility(loadState !is LoadState.Loading)
}
private fun toVisibility(constraint: Boolean): Int = if (constraint) {
View.VISIBLE
} else {
View.GONE
}
companion object {
fun inflate(parent: ViewGroup): View =
LayoutInflater.from(parent.context)
.inflate(R.layout.load_state_item, parent, false)
}
}
class StateItemAdapter(
private val retry: () -> Unit
) : LoadStateAdapter<LoadStateViewHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, loadState: LoadState) =
LoadStateViewHolder(parent, retry)
override fun onBindViewHolder(holder: LoadStateViewHolder, loadState: LoadState) =
holder.bind(loadState)
} | apache-2.0 | b10671fa7d6e8e3c552e803d6815c044 | 34.671429 | 86 | 0.728365 | 4.473118 | false | false | false | false |
google/playhvz | Android/ghvzApp/app/src/main/java/com/app/playhvz/firebase/operations/GameDatabaseOperations.kt | 1 | 12322 | /*
* Copyright 2020 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.app.playhvz.firebase.operations
import android.content.SharedPreferences
import android.util.Log
import com.app.playhvz.app.debug.DebugFlags
import com.app.playhvz.common.globals.SharedPreferencesConstants
import com.app.playhvz.firebase.classmodels.Game
import com.app.playhvz.firebase.classmodels.Stat
import com.app.playhvz.firebase.classmodels.Stat.Companion.FIELD__CURRENT_HUMAN_COUNT
import com.app.playhvz.firebase.classmodels.Stat.Companion.FIELD__CURRENT_ZOMBIE_COUNT
import com.app.playhvz.firebase.classmodels.Stat.Companion.FIELD__OVER_TIME_INFECTION_COUNT
import com.app.playhvz.firebase.classmodels.Stat.Companion.FIELD__OVER_TIME_TIMESTAMP
import com.app.playhvz.firebase.classmodels.Stat.Companion.FIELD__STARTER_ZOMBIE_COUNT
import com.app.playhvz.firebase.classmodels.Stat.Companion.FIELD__STATS_OVER_TIME
import com.app.playhvz.firebase.constants.GamePath.Companion.GAMES_COLLECTION
import com.app.playhvz.firebase.constants.GamePath.Companion.GAME_FIELD__CREATOR_ID
import com.app.playhvz.firebase.constants.PlayerPath
import com.app.playhvz.firebase.constants.UniversalConstants.Companion.UNIVERSAL_FIELD__USER_ID
import com.app.playhvz.firebase.firebaseprovider.FirebaseProvider
import com.app.playhvz.firebase.utils.FirebaseDatabaseUtil
import com.app.playhvz.screens.rules_faq.CollapsibleListFragment
import com.google.android.gms.tasks.OnSuccessListener
import com.google.firebase.firestore.Query
import com.google.firebase.firestore.QuerySnapshot
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import org.json.JSONArray
class GameDatabaseOperations {
companion object {
private val TAG = GameDatabaseOperations::class.qualifiedName
/** Check if game exists and tries to add player to game if so. */
suspend fun asyncCheckGameExistsAndPlayerCanJoin(
name: String,
successListener: () -> Unit,
failureListener: () -> Unit
) = withContext(Dispatchers.Default) {
val data = hashMapOf(
"name" to name
)
FirebaseProvider.getFirebaseFunctions()
.getHttpsCallable("checkGameExists")
.call(data)
.continueWith { task ->
if (!task.isSuccessful) {
Log.e(TAG, "Game $name isn't valid for the user to join.")
failureListener.invoke()
return@continueWith
}
successListener.invoke()
}
}
/** Check if game exists and tries to add player to game if so. */
suspend fun asyncTryToJoinGame(
gameName: String,
playerName: String,
successListener: (gameId: String) -> Unit,
failureListener: () -> Unit
) = withContext(Dispatchers.Default) {
val data = hashMapOf(
"gameName" to gameName,
"playerName" to playerName
)
FirebaseProvider.getFirebaseFunctions()
.getHttpsCallable("joinGame")
.call(data)
.continueWith { task ->
if (!task.isSuccessful) {
failureListener.invoke()
return@continueWith
}
// gameId is returned.
val result = task.result?.data as String
successListener.invoke(result)
}
}
/** Calls the firebase endpoint for creating a game or handling errors if the game exists. */
suspend fun asyncTryToCreateGame(
gameDraft: Game,
successListener: OnSuccessListener<String>,
failureListener: () -> Unit
) = withContext(Dispatchers.Default) {
val data = hashMapOf(
"name" to gameDraft.name,
"startTime" to gameDraft.startTime,
"endTime" to gameDraft.endTime
)
FirebaseProvider.getFirebaseFunctions()
.getHttpsCallable("createGame")
.call(data)
.continueWith { task ->
if (!task.isSuccessful) {
Log.e(TAG, "Failed to create game ${gameDraft.name} " + task.exception)
failureListener.invoke()
return@continueWith
}
val result = task.result?.data as String
successListener.onSuccess(result)
}
}
/** Check if game name already exists. */
suspend fun asyncDeleteGame(gameId: String, successListener: () -> Unit) =
withContext(Dispatchers.Default) {
if (!DebugFlags.isDevEnvironment && !DebugFlags.isTestingEnvironment) {
// Only allow deleting from the dev & test environments
return@withContext
}
val data = hashMapOf(
"gameId" to gameId
)
FirebaseProvider.getFirebaseFunctions()
.getHttpsCallable("deleteGame")
.call(data)
.continueWith { task ->
if (!task.isSuccessful) {
Log.e(TAG, "Failed to delete game, " + task.exception)
return@continueWith
}
successListener.invoke()
}
}
/** Updates the game object except for rules & faq. */
suspend fun asyncUpdateGame(
gameDraft: Game,
successListener: () -> Unit,
failureListener: () -> Unit
) = withContext(Dispatchers.Default) {
if (gameDraft.id == null) {
return@withContext
}
val data = hashMapOf(
"gameId" to gameDraft.id,
"adminOnCallPlayerId" to gameDraft.adminOnCallPlayerId,
"startTime" to gameDraft.startTime,
"endTime" to gameDraft.endTime
)
FirebaseProvider.getFirebaseFunctions()
.getHttpsCallable("updateGame")
.call(data)
.continueWith { task ->
if (!task.isSuccessful) {
Log.e(TAG, "Failed to update game, " + task.exception)
return@continueWith
}
successListener.invoke()
}
}
/** Updates the game object. */
suspend fun asyncUpdateRulesOrFaq(
type: CollapsibleListFragment.CollapsibleFragmentType,
gameDraft: Game,
successListener: () -> Unit,
failureListener: () -> Unit
) = withContext(Dispatchers.Default) {
if (gameDraft.id == null) {
return@withContext
}
lateinit var field: String
lateinit var value: List<Game.CollapsibleSection>
if (type == CollapsibleListFragment.CollapsibleFragmentType.RULES) {
field = Game.FIELD__RULES
value = gameDraft.rules
} else {
field = Game.FIELD__FAQ
value = gameDraft.faq
}
GAMES_COLLECTION.document(gameDraft.id!!).update(field, value).addOnSuccessListener {
successListener.invoke()
}.addOnFailureListener {
Log.e(TAG, "Failed to update game: " + it)
failureListener.invoke()
}
}
/** Check if game exists and tries to add player to game if so. */
suspend fun asyncGetGameStats(
gameId: String,
successListener: (stats: Stat) -> Unit,
failureListener: () -> Unit
) = withContext(Dispatchers.Default) {
val data = hashMapOf(
"gameId" to gameId
)
FirebaseProvider.getFirebaseFunctions()
.getHttpsCallable("getGameStats")
.call(data)
.continueWith { task ->
if (!task.isSuccessful) {
failureListener.invoke()
return@continueWith
}
// Game Stat object is returned.
if (task.result != null) {
val stat = Stat()
try {
val resultMap = task.result!!.data as Map<*, *>
stat.currentHumanCount = resultMap[FIELD__CURRENT_HUMAN_COUNT] as Int
stat.currentZombieCount = resultMap[FIELD__CURRENT_ZOMBIE_COUNT] as Int
stat.starterZombieCount = resultMap[FIELD__STARTER_ZOMBIE_COUNT] as Int
val asHashMapArray = resultMap[FIELD__STATS_OVER_TIME] as ArrayList<HashMap<String, Any>>
val asStatTypeArray: MutableList<Stat.StatOverTime> = mutableListOf()
for (item in asHashMapArray) {
val statType = Stat.StatOverTime()
statType.interval = item[FIELD__OVER_TIME_TIMESTAMP] as Long
statType.infectionCount = item[FIELD__OVER_TIME_INFECTION_COUNT] as Int
asStatTypeArray.add(statType)
}
stat.statsOverTime = asStatTypeArray
} finally {
successListener.invoke(stat)
}
}
}
}
/** Returns a Query listing all Games created by the current user. */
fun getGameByCreatorQuery(): Query {
return GAMES_COLLECTION.whereEqualTo(
GAME_FIELD__CREATOR_ID,
FirebaseProvider.getFirebaseAuth().uid
)
}
/** Returns a Query listing all Games in which the current user is a player. */
fun getGameByPlayerQuery(): Query {
return PlayerPath.PLAYERS_QUERY.whereEqualTo(
UNIVERSAL_FIELD__USER_ID,
FirebaseProvider.getFirebaseAuth().uid
)
}
/** Returns the user's playerId for the given Games. */
suspend fun getPlayerIdForGame(
gameId: String,
editor: SharedPreferences.Editor,
successListener: () -> Unit
) =
withContext(Dispatchers.Default) {
val playerQuery = PlayerPath.PLAYERS_COLLECTION(gameId).whereEqualTo(
UNIVERSAL_FIELD__USER_ID,
FirebaseProvider.getFirebaseAuth().uid
)
val onSuccess: OnSuccessListener<QuerySnapshot> =
OnSuccessListener { querySnapshot ->
updatePlayerIdPref(querySnapshot, editor)
successListener.invoke()
}
FirebaseDatabaseUtil.optimizedGet(playerQuery, onSuccess)
}
private fun updatePlayerIdPref(
querySnapshot: QuerySnapshot?,
editor: SharedPreferences.Editor
) {
var playerId: String? = null
if (querySnapshot != null && !querySnapshot.isEmpty && querySnapshot.documents.size == 1) {
playerId = querySnapshot.documents[0].id
}
editor.putString(SharedPreferencesConstants.CURRENT_PLAYER_ID, playerId)
editor.apply()
}
}
} | apache-2.0 | a722b06d462edeb7c325f75a01d3518d | 41.493103 | 117 | 0.556565 | 5.34577 | false | false | false | false |
klazuka/intellij-elm | src/main/kotlin/org/elm/ide/intentions/PipelineIntention.kt | 1 | 6653 | package org.elm.ide.intentions
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiComment
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiWhiteSpace
import com.intellij.util.DocumentUtil
import org.elm.lang.core.psi.*
import org.elm.lang.core.psi.elements.ElmAnonymousFunctionExpr
import org.elm.lang.core.psi.elements.ElmBinOpExpr
import org.elm.lang.core.psi.elements.ElmFunctionCallExpr
import org.elm.lang.core.psi.elements.ElmParenthesizedExpr
import org.elm.lang.core.psi.elements.Pipeline.RightPipeline
import org.elm.lang.core.withoutExtraParens
import org.elm.lang.core.withoutParens
import org.elm.openapiext.runWriteCommandAction
/**
* An intention action that transforms a series of function applications into a pipeline.
*/
class PipelineIntention : ElmAtCaretIntentionActionBase<PipelineIntention.Context>() {
sealed class Context {
data class NoPipes(val functionCall: ElmFunctionCallExpr) : Context()
data class HasRightPipes(val pipelineExpression: RightPipeline) : Context()
}
override fun getText() = "Use pipeline of |>"
override fun getFamilyName() = text
override fun findApplicableContext(project: Project, editor: Editor, element: PsiElement): Context? {
// find nearest ancestor (or self) that is
// 1) a function call with at least one argument, or
// 2) a pipeline that isn't fully piped (first part of the pipe has at least one argument)
element.ancestors.forEach {
when (it) {
is ElmFunctionCallExpr -> {
if (it.arguments.count() > 0 && !it.isPartOfAPipeline) {
return Context.NoPipes(it)
}
}
is ElmBinOpExpr -> {
it.asPipeline().let { pipe ->
if (pipe is RightPipeline && pipe.isNotFullyPiped) {
return Context.HasRightPipes(pipe)
}
}
}
}
}
return null
}
override fun invoke(project: Project, editor: Editor, context: Context) {
project.runWriteCommandAction {
val psiFactory = ElmPsiFactory(project)
when (context) {
is Context.NoPipes -> {
val call = context.functionCall
val indent = call.indentStyle.oneLevelOfIndentation
val existingIndent = DocumentUtil.getIndent(editor.document, call.startOffset).toString()
val splitApplications = splitArgAndFunctionApplications(call)
val rewrittenWithPipes = psiFactory.createPipeChain(existingIndent, indent, splitApplications)
replaceUnwrapped(call, rewrittenWithPipes)
}
is Context.HasRightPipes -> {
val pipe = context.pipelineExpression
val existingIndent = DocumentUtil.getIndent(editor.document, pipe.pipeline.startOffset).toString()
val indent = pipe.pipeline.indentStyle.oneLevelOfIndentation
val firstSegment = pipe.segments().first()
val segments = pipe.segments().drop(1).flatMap {
it.comments.plus(it.expressionParts.joinToString(separator = " ") { it.text })
}
val splitApplications = splitArgAndFunctionApplications(
pipe.pipeline.parts.filterIsInstance<ElmFunctionCallExpr>().first()
)
val valueAndApplications = splitApplications + firstSegment.comments
val rewrittenFullyPiped = psiFactory.createPipeChain(existingIndent, indent, valueAndApplications + segments)
replaceUnwrapped(pipe.pipeline, rewrittenFullyPiped)
}
}
}
}
}
private fun replaceUnwrapped(expression: ElmPsiElement, parenExpr: ElmParenthesizedExpr) {
val comments = parenExpr.directChildren.filterIsInstance<PsiComment>()
val unwrapped = when {
needsParensInParent(expression) || comments.count() > 0 ->
parenExpr.withoutExtraParens
else ->
parenExpr.withoutParens
}
expression.replace(unwrapped)
}
private fun needsParensInParent(element: ElmPsiElement): Boolean =
element.parent is ElmBinOpExpr
private fun splitArgAndFunctionApplications(call: ElmFunctionCallExpr, associatedComments: List<PsiComment> = emptyList()): List<Any> {
val args = call.arguments
return when (args.count()) {
0 -> {
listOf(associatedComments, call.comments.toList(), call.target.text)
}
else -> {
val functionCallString = sequenceOf(call.target)
.plus(args.take(args.count() - 1))
.joinToString(separator = " ") { it.text }
val commentsForLastArg = args
.last()
.prevSiblings
.toList()
.takeWhile { it is PsiWhiteSpace || it is PsiComment }
.filterIsInstance<PsiComment>()
processArgument(args.last(), commentsForLastArg)
.plus(associatedComments)
.plus(call.comments.filter { it !in commentsForLastArg })
.plus(functionCallString)
}
}
}
private fun processArgument(argument: ElmAtomTag, commentsForLastArg: List<PsiComment>): List<Any> {
val arg = argument.withoutParens
return when {
arg is ElmFunctionCallExpr -> {
splitArgAndFunctionApplications(arg, commentsForLastArg)
}
arg.children.size != 1 -> {
listOf(addParensIfNeeded(arg), commentsForLastArg)
}
else -> {
commentsForLastArg + addParensIfNeeded(arg)
}
}
}
private fun addParensIfNeeded(element: ElmPsiElement): String =
when {
needsParens(element) -> "(" + element.text + ")"
else -> element.text
}
private fun needsParens(element: ElmPsiElement): Boolean =
when (element) {
is ElmFunctionCallExpr,
is ElmBinOpExpr,
is ElmAnonymousFunctionExpr -> true
else -> false
}
private val ElmFunctionCallExpr.comments: Sequence<PsiComment>
get() =
directChildren.filterIsInstance<PsiComment>()
private val ElmFunctionCallExpr.isPartOfAPipeline: Boolean
get() =
(parent as? ElmBinOpExpr)?.asPipeline() is RightPipeline | mit | fd7b4b184dc42285ab95d69a5cd0d96d | 40.074074 | 135 | 0.620021 | 4.942793 | false | false | false | false |
outlying/card-check | domain/src/main/kotlin/com/antyzero/cardcheck/storage/FileStorage.kt | 1 | 3121 | package com.antyzero.cardcheck.storage
import com.antyzero.cardcheck.card.Card
import com.antyzero.cardcheck.card.mpk.MpkCard
import com.google.gson.*
import java.io.File
import java.io.OutputStreamWriter
import java.lang.reflect.Type
import java.util.*
class FileStorage(
private val fileName: String = "storage",
private val filePath: File = File.createTempFile(fileName, "txt")) : PersistentStorage {
private val cardsSet: MutableSet<Card> = mutableSetOf()
private val gson: Gson = GsonBuilder()
.registerTypeHierarchyAdapter(CardList::class.java, Deser())
.create()
init {
filePath.apply {
if (!exists()) {
createNewFile()
} else {
val result = filePath.readLines().joinToString("\n")
if (!result.isNullOrEmpty()) {
cardsSet.addAll(gson.fromJson(result, CardList::class.java))
saveSetState()
}
}
}
}
override fun addCard(card: Card) {
cardsSet.add(card)
saveSetState()
}
override fun removeCard(card: Card) {
cardsSet.remove(card)
saveSetState()
}
override fun getCards(): List<Card> {
return cardsSet.toList()
}
override fun delete() {
filePath.apply {
if (exists()) {
delete()
createNewFile()
}
}
cardsSet.clear()
}
private fun saveSetState() {
val cardSaveList: MutableSet<CardMeta> = mutableSetOf()
cardsSet.forEach { cardSaveList.add(wrapWithMeta(it)) }
val json = gson.toJson(cardSaveList)
filePath.apply {
if (exists()) {
delete()
}
}.let {
OutputStreamWriter(it.outputStream()).use { it.write(json) }
}
}
private fun wrapWithMeta(card: Card): CardMeta {
return CardMeta(card.javaClass.canonicalName, card)
}
}
class CardList() : ArrayList<Card>() {
}
data class CardMeta(
val cardType: String,
val card: Card) {
}
private class Deser() : JsonDeserializer<CardList> {
override fun deserialize(json: JsonElement?, typeOfT: Type?, context: JsonDeserializationContext?): CardList {
val cardList = CardList()
val gson = Gson()
if (json is JsonArray) {
json.forEach {
if (it is JsonObject) {
val classCannonical = it.get("cardType").asString
val cardElement = it.getAsJsonObject("card")
val card = gson.fromJson(cardElement, when (classCannonical) {
"com.antyzero.cardcheck.card.mpk.MpkCard.Kkm" -> MpkCard.Kkm::class.java
"com.antyzero.cardcheck.card.mpk.MpkCard.Student" -> MpkCard.Student::class.java
else -> throw IllegalArgumentException("Unsupported type")
})
cardList.add(card)
}
}
}
return cardList
}
} | gpl-3.0 | bdf8db76f7cc3a0dc644b72bba4e7b2a | 25.913793 | 114 | 0.557834 | 4.536337 | false | false | false | false |
robohorse/RoboPOJOGenerator | generator/src/main/kotlin/com/robohorse/robopojogenerator/utils/ProcessingModelResolver.kt | 1 | 632 | package com.robohorse.robopojogenerator.utils
import com.robohorse.robopojogenerator.properties.JsonModel
import com.robohorse.robopojogenerator.models.GenerationModel
import org.json.JSONArray
import org.json.JSONObject
internal class ProcessingModelResolver {
fun resolveJsonModel(model: GenerationModel): JsonModel =
try {
JsonModel.JsonItem(jsonObject = JSONObject(model.content), key = model.rootClassName)
} catch (e: Exception) {
JsonModel.JsonItemArray(
jsonObject = JSONArray(model.content),
key = model.rootClassName
)
}
}
| mit | 92ad2b959cff47c11da2cd27b17ef035 | 32.263158 | 97 | 0.699367 | 4.787879 | false | false | false | false |
0x1bad1d3a/Kaku | app/src/main/java/ca/fuwafuwa/kaku/Windows/HistoryWindow.kt | 2 | 8638 | package ca.fuwafuwa.kaku.Windows
import android.content.Context
import android.graphics.Color
import android.opengl.Visibility
import android.util.TypedValue
import android.view.Gravity
import android.view.MotionEvent
import android.view.View
import android.view.ViewGroup.LayoutParams.*
import android.widget.HorizontalScrollView
import android.widget.LinearLayout
import android.widget.TextView
import ca.fuwafuwa.kaku.DB_JMDICT_NAME
import ca.fuwafuwa.kaku.Database.JmDictDatabase.Models.EntryOptimized
import ca.fuwafuwa.kaku.LangUtils
import ca.fuwafuwa.kaku.R
import ca.fuwafuwa.kaku.Search.JmSearchResult
import ca.fuwafuwa.kaku.Windows.Data.ISquareChar
import ca.fuwafuwa.kaku.Windows.Enums.LayoutPosition
import ca.fuwafuwa.kaku.dpToPx
class HistoryWindow(context: Context,
windowCoordinator: WindowCoordinator) : Window(context, windowCoordinator, R.layout.window_history)
{
private data class PastKanji(
val kanji: String,
val results: List<JmSearchResult>)
{
var timesSeen: Int = 0
}
private val container = window.findViewById<LinearLayout>(R.id.history_window_container)
private val childKanji = container.findViewById<LinearLayout>(R.id.history_window_kanji)
private val childResults = container.findViewById<LinearLayout>(R.id.history_window_results)
private val changeLayoutButton = window.findViewById<TextView>(R.id.history_window_layout_button)
private val maxShownHistory = 40
private val normalHeight = dpToPx(context, 45)
private val pastKanjiView = window.findViewById<LinearLayout>(R.id.past_kanji)!!
private val pastKanjiScrollView = window.findViewById<HorizontalScrollView>(R.id.past_kanji_scroll_view)!!
private val pastDictResults = window.findViewById<TextView>(R.id.history_dict_result)!!
private var pastKanjis = mutableListOf<PastKanji>()
private var isOnTop = true
init
{
changeLayoutButton.setOnClickListener {
isOnTop = !isOnTop
relayoutWindow(if (isOnTop) LayoutPosition.TOP else LayoutPosition.BOTTOM)
}
val tv = createTextView(0)
tv.text = "Lookup History"
pastKanjiView.addView(tv)
}
override fun onTouch(e: MotionEvent?): Boolean
{
childResults.layoutParams.height = 0
childKanji.visibility = View.VISIBLE
params.height = normalHeight
windowManager.updateViewLayout(window, params)
return true
}
override fun onScroll(e1: MotionEvent?, e2: MotionEvent?, distanceX: Float, distanceY: Float): Boolean
{
return false
}
override fun onResize(e: MotionEvent?): Boolean
{
return false
}
override fun show()
{
params.width = MATCH_PARENT
params.height = normalHeight
super.show()
}
/**
* HistoryWindow does not need to reInit layout as its getDefaultParams() are all relative. Re-initing will cause bugs.
*/
override fun reInit(options: Window.ReinitOptions)
{
options.reinitViewLayout = false
super.reInit(options)
}
fun addResult(squareChar: ISquareChar, results: List<JmSearchResult>)
{
if (!squareChar.userTouched)
{
return
}
val word = results.first().entry.kanji
if (pastKanjis.any { k -> k.kanji == word })
{
pastKanjis.first { k -> k.kanji == word }.timesSeen++
}
else
{
pastKanjis.add(PastKanji(word, results))
if (pastKanjiView.childCount < maxShownHistory)
{
pastKanjiView.addView(createTextView(pastKanjis.size))
}
}
recalculateViews()
}
@Synchronized private fun relayoutWindow(pos: LayoutPosition)
{
params.height = normalHeight
val marginSize = dpToPx(context, 5)
container.removeAllViews()
if (pos == LayoutPosition.TOP)
{
val childResultsParams = childResults.layoutParams as LinearLayout.LayoutParams
childResultsParams.setMargins(marginSize, marginSize, marginSize, 0)
childResultsParams.height = 0
childResults.layoutParams = childResultsParams
val childKanjiParams = childKanji.layoutParams as LinearLayout.LayoutParams
childKanjiParams.setMargins(marginSize, marginSize, marginSize, 0)
childKanji.layoutParams = childKanjiParams
changeLayoutButton.text = "▼"
container.addView(childKanji)
container.addView(childResults)
container.gravity = Gravity.TOP
params.y = 0
}
else if (pos == LayoutPosition.BOTTOM)
{
val childResultsParams = childResults.layoutParams as LinearLayout.LayoutParams
childResultsParams.setMargins(marginSize, 0, marginSize, marginSize)
childResultsParams.height = 0
childResults.layoutParams = childResultsParams
val childKanjiParams = childKanji.layoutParams as LinearLayout.LayoutParams
childKanjiParams.setMargins(marginSize, 0, marginSize, marginSize)
childKanji.layoutParams = childKanjiParams
changeLayoutButton.text = "▲"
container.addView(childResults)
container.addView(childKanji)
container.gravity = Gravity.BOTTOM
params.y = viewHeight - normalHeight
}
windowManager.updateViewLayout(window, params)
}
private fun recalculateViews()
{
pastKanjis.sortByDescending { k -> k.timesSeen }
pastKanjis = pastKanjis.take(100).toMutableList()
for (i in 0 until pastKanjis.size)
{
if (i >= pastKanjiView.childCount)
{
break
}
(pastKanjiView.getChildAt(i) as TextView).text = pastKanjis[i].kanji
}
pastKanjiScrollView.scrollTo(0, 0)
}
private fun createTextView(index: Int) : TextView
{
val tv = TextView(context)
val padding = dpToPx(context, 5)
tv.setTextColor(Color.BLACK)
tv.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 15.toFloat())
if (index == 0)
{
tv.setPadding(padding * 2, padding, padding, padding)
}
else if (index == maxShownHistory - 1)
{
tv.setPadding(padding, padding, padding * 2, padding)
}
else
{
tv.setPadding(padding, padding, padding, padding)
}
tv.setOnClickListener { v ->
childKanji.visibility = View.GONE
childKanji.requestLayout()
showEntry(pastKanjiView.indexOfChild(v))
}
return tv
}
private fun showEntry(index: Int)
{
childResults.layoutParams.height = WRAP_CONTENT
params.height = MATCH_PARENT
windowManager.updateViewLayout(window, params)
if (index < pastKanjis.size)
{
displayResults(pastKanjis[index].results)
}
}
private fun displayResults(jmResults: List<JmSearchResult>)
{
val sb = StringBuilder()
for ((entry, _) in jmResults)
{
sb.append(entry.kanji)
if (!entry.readings.isEmpty())
{
if (DB_JMDICT_NAME == entry.dictionary)
{
sb.append(" (")
} else
{
sb.append(" ")
}
sb.append(entry.readings)
if (DB_JMDICT_NAME == entry.dictionary) sb.append(")")
}
sb.append("\n")
sb.append(getMeaning(entry))
sb.append("\n\n")
}
if (sb.length > 2)
{
sb.setLength(sb.length - 2)
}
pastDictResults.setText(sb.toString())
}
private fun getMeaning(entry: EntryOptimized): String
{
val meanings = entry.meanings.split("\ufffc".toRegex()).toTypedArray()
val pos = entry.pos.split("\ufffc".toRegex()).toTypedArray()
val sb = StringBuilder()
for (i in meanings.indices)
{
if (i != 0)
{
sb.append(" ")
}
sb.append(LangUtils.ConvertIntToCircledNum(i + 1))
sb.append(" ")
if (DB_JMDICT_NAME == entry.dictionary && !pos[i].isEmpty())
{
sb.append(String.format("(%s) ", pos[i]))
}
sb.append(meanings[i])
}
return sb.toString()
}
} | bsd-3-clause | e7ae83d824650ab2ee4ea0e6c9d102f8 | 28.982639 | 123 | 0.612578 | 4.452811 | false | false | false | false |
vimeo/stag-java | stag-library/src/test/java/verification/Utils.kt | 1 | 1788 | @file:JvmName("Utils")
package verification
import com.google.gson.JsonArray
import com.google.gson.JsonObject
import org.assertj.core.api.Assertions.assertThat
import org.assertj.core.api.Assertions.assertThatThrownBy
import java.util.*
inline fun <reified T : Any> assertThatClassIsNotInstantiable() {
assertThatThrownBy {
T::class.java.getDeclaredConstructor().apply {
assertThat(isAccessible).isFalse()
isAccessible = true
}.newInstance()
}.hasCauseInstanceOf(UnsupportedOperationException::class.java)
}
fun <K, V> assertMapsEqual(map1: Map<K, V>, map2: Map<K, V>) {
for ((key, value) in map1) {
assertThat(value).isEqualTo(map2[key])
}
for ((key, value) in map2) {
assertThat(value).isEqualTo(map1[key])
}
}
fun createStringDummyList() = ArrayList<String>().apply {
add("abc")
add("abc1")
add("abc2")
add("abc3")
add("abc4")
add("abc5")
}
fun createStringDummyMap() = HashMap<String, String>().apply {
this["abc"] = "0"
this["abc1"] = "1"
this["abc2"] = "2"
this["abc3"] = "3"
this["abc4"] = "4"
this["abc5"] = "5"
}
fun createIntegerDummyList() = ArrayList<Int>().apply {
add(1)
add(2)
add(3)
add(4)
add(5)
add(6)
}
fun createIntegerDummyMap() = HashMap<Int, Int>().apply {
this[1] = 11
this[2] = 22
this[3] = 33
this[4] = 44
this[5] = 55
this[6] = 66
}
fun createDummyJsonObject() = JsonObject().apply {
addProperty("key", "value")
addProperty("key1", "value1")
addProperty("key2", "value2")
addProperty("key3", "value3")
addProperty("key4", "value4")
}
fun createDummyJsonArray() = JsonArray().apply {
add("item1")
add("item2")
add("item3")
add("item4")
}
| mit | bc4ba32959156fda7b8218fec97bff82 | 21.632911 | 67 | 0.614653 | 3.317254 | false | false | false | false |
westnordost/StreetComplete | app/src/main/java/de/westnordost/streetcomplete/data/osm/osmquest/OsmQuestController.kt | 1 | 12793 | package de.westnordost.streetcomplete.data.osm.osmquest
import de.westnordost.osmapi.map.data.BoundingBox
import de.westnordost.osmapi.map.data.Element
import de.westnordost.streetcomplete.ApplicationConstants
import de.westnordost.streetcomplete.data.osm.changes.StringMapChanges
import de.westnordost.streetcomplete.data.osm.elementgeometry.ElementGeometry
import de.westnordost.streetcomplete.data.osm.elementgeometry.ElementGeometryDao
import de.westnordost.streetcomplete.data.osm.elementgeometry.ElementGeometryEntry
import de.westnordost.streetcomplete.data.osm.mapdata.ElementKey
import de.westnordost.streetcomplete.data.quest.QuestStatus
import java.util.concurrent.CopyOnWriteArrayList
import javax.inject.Inject
import javax.inject.Singleton
/** Controller for managing OsmQuests. Takes care of persisting OsmQuest objects along with their
* referenced geometry and notifying listeners about changes */
@Singleton class OsmQuestController @Inject internal constructor(
private val dao: OsmQuestDao,
private val geometryDao: ElementGeometryDao
){
/* Must be a singleton because there is a listener that should respond to a change in the
* database table */
interface QuestStatusListener {
/** the status of a quest was changed */
fun onChanged(quest: OsmQuest, previousStatus: QuestStatus)
/** a quest was removed */
fun onRemoved(questId: Long, previousStatus: QuestStatus)
/** various note quests were updated */
fun onUpdated(added: Collection<OsmQuest>, updated: Collection<OsmQuest>, deleted: Collection<Long>)
}
private val questStatusListeners: MutableList<QuestStatusListener> = CopyOnWriteArrayList()
/* ---------------------------------- Modify single quests ---------------------------------- */
/** Return the previously answered quest to the initial unanswered state */
fun undo(quest: OsmQuest) {
val status = quest.status
quest.status = QuestStatus.NEW
quest.changes = null
quest.changesSource = null
dao.update(quest)
onChanged(quest, status)
}
/** Mark the previously successfully uploaded quest as reverted */
fun revert(quest: OsmQuest) {
val status = quest.status
dao.delete(quest.id!!)
onRemoved(quest.id!!, status)
}
/** Mark the quest as answered by the user with the given answer */
fun answer(quest: OsmQuest, changes: StringMapChanges, source: String) {
val status = quest.status
quest.changes = changes
quest.changesSource = source
quest.status = QuestStatus.ANSWERED
dao.update(quest)
onChanged(quest, status)
}
/** Mark the quest as hidden by user interaction */
fun hide(quest: OsmQuest) {
val status = quest.status
quest.status = QuestStatus.HIDDEN
dao.update(quest)
onChanged(quest, status)
}
/** Mark that the upload of the quest was successful */
fun success(quest: OsmQuest) {
val status = quest.status
quest.status = QuestStatus.CLOSED
dao.update(quest)
onChanged(quest, status)
}
/** Mark that the quest failed because either the changes could not be applied or there was an
* unsolvable conflict during upload (deletes the quest) */
fun fail(quest: OsmQuest) {
val status = quest.status
/* #812 conflicting quests may not reside in the database, otherwise they would
wrongfully be candidates for an undo - even though nothing was changed */
dao.delete(quest.id!!)
onRemoved(quest.id!!, status)
}
/* ------------------------------------------------------------------------------------------ */
/** Replace all quests of the given types in the given bounding box with the given quests,
* including their geometry. Called on download of a quest type for a bounding box. */
fun replaceInBBox(quests: Iterable<OsmQuest>, bbox: BoundingBox, questTypes: List<String>): UpdateResult {
require(questTypes.isNotEmpty()) { "questTypes must not be empty if not null" }
/* All quests in the given bounding box and of the given types should be replaced by the
* input list. So, there may be 1. new quests that are added and 2. there may be previous
* quests that have been there before but now not anymore, these need to be removed. */
val previousQuests = mutableMapOf<OsmElementQuestType<*>, MutableMap<ElementKey, Long>>()
for (quest in dao.getAll(bounds = bbox, questTypes = questTypes)) {
val previousQuestIdsByElement = previousQuests.getOrPut(quest.osmElementQuestType, { mutableMapOf() })
previousQuestIdsByElement[ElementKey(quest.elementType, quest.elementId)] = quest.id!!
}
val addedQuests = mutableListOf<OsmQuest>()
for (quest in quests) {
val previousQuestIdsByElement = previousQuests[quest.osmElementQuestType]
val e = ElementKey(quest.elementType, quest.elementId)
if (previousQuestIdsByElement != null && previousQuestIdsByElement.containsKey(e)) {
previousQuestIdsByElement.remove(e)
} else {
addedQuests.add(quest)
}
}
val obsoleteQuestIds = previousQuests.values.flatMap { it.values }
val deletedCount = removeObsolete(obsoleteQuestIds)
geometryDao.putAll(quests.map { ElementGeometryEntry(it.elementType, it.elementId, it.geometry) })
val addedCount = dao.addAll(addedQuests)
/* Only send quests to listener that were really added, i.e. have an ID. How could quests
* not be added at this point? If they exist in the DB but outside the bounding box,
* so usually either if the geometry has been moved in the meantime, or, some quests
* also extend the bbox in which they download the quests, like the housenumber quest */
val reallyAddedQuests = addedQuests.filter { it.id != null }
onUpdated(added = reallyAddedQuests, deleted = obsoleteQuestIds)
return UpdateResult(added = addedCount, deleted = deletedCount)
}
/** Add new unanswered quests and remove others for the given element, including their linked
* geometry. Called when an OSM element is updated, so the quests that reference that element
* need to be updated as well. */
fun updateForElement(
added: List<OsmQuest>,
removedIds: List<Long>,
updatedGeometry: ElementGeometry,
elementType: Element.Type,
elementId: Long
): UpdateResult {
geometryDao.put(ElementGeometryEntry(elementType, elementId, updatedGeometry))
val deletedCount = removeObsolete(removedIds)
val addedCount = dao.addAll(added)
onUpdated(added = added.filter { it.id != null }, deleted = removedIds)
return UpdateResult(added = addedCount, deleted = deletedCount)
}
/** Remove obsolete quests, including their linked geometry */
private fun removeObsolete(questIds: Collection<Long>): Int {
if (questIds.isNotEmpty()) {
val result = dao.deleteAllIds(questIds)
if (result > 0) {
geometryDao.deleteUnreferenced()
}
return result
}
return 0
}
/** Remove all unsolved quests that reference the given element. Used for when a quest blocker
* (=a note) or similar has been added for that element position. */
fun deleteAllUnsolvedForElement(elementType: Element.Type, elementId: Long): Int {
val deletedQuestIds = dao.getAllIds(
statusIn = listOf(QuestStatus.NEW),
element = ElementKey(elementType, elementId)
)
val result = dao.deleteAllIds(deletedQuestIds)
geometryDao.deleteUnreferenced()
onUpdated(deleted = deletedQuestIds)
return result
}
/** Remove all quests that reference the given element. Used for when that element has been
* deleted, so all quests referencing this element should to. */
fun deleteAllForElement(elementType: Element.Type, elementId: Long): Int {
val deletedQuestIds = dao.getAllIds(element = ElementKey(elementType, elementId))
val result = dao.deleteAllIds(deletedQuestIds)
geometryDao.delete(elementType, elementId)
onUpdated(deleted = deletedQuestIds)
return result
}
/** Un-hides all previously hidden quests by user interaction */
fun unhideAll(): Int {
val hiddenQuests = dao.getAll(statusIn = listOf(QuestStatus.HIDDEN))
hiddenQuests.forEach { it.status = QuestStatus.NEW }
val result = dao.updateAll(hiddenQuests)
onUpdated(updated = hiddenQuests)
return result
}
/** Delete old closed and reverted quests and old unsolved and hidden quests */
fun cleanUp(): Int {
// remove old uploaded quests. These were kept only for the undo/history function
val oldUploadedQuestsTimestamp = System.currentTimeMillis() - ApplicationConstants.MAX_QUEST_UNDO_HISTORY_AGE
var deleted = dao.deleteAll(
statusIn = listOf(QuestStatus.CLOSED),
changedBefore = oldUploadedQuestsTimestamp
)
// remove old unsolved and hidden quests. To let the quest cache not get too big and to
// ensure that the probability of merge conflicts remains low
val oldUnsolvedQuestsTimestamp = System.currentTimeMillis() - ApplicationConstants.DELETE_UNSOLVED_QUESTS_AFTER
deleted += dao.deleteAll(
statusIn = listOf(QuestStatus.NEW, QuestStatus.HIDDEN),
changedBefore = oldUnsolvedQuestsTimestamp
)
if (deleted > 0) geometryDao.deleteUnreferenced()
onUpdated()
return deleted
}
/* ---------------------------------------- Getters ----------------------------------------- */
/** Get the quest types of all unsolved quests for the given element */
fun getAllUnsolvedQuestTypesForElement(elementType: Element.Type, elementId: Long): List<OsmElementQuestType<*>> {
return dao.getAll(
statusIn = listOf(QuestStatus.NEW),
element = ElementKey(elementType, elementId)
).map { it.osmElementQuestType }
}
/** Get count of all unanswered quests in given bounding box */
fun getAllVisibleInBBoxCount(bbox: BoundingBox) : Int {
return dao.getCount(
statusIn = listOf(QuestStatus.NEW),
bounds = bbox
)
}
/** Get all unanswered quests in given bounding box of given types */
fun getAllVisibleInBBox(bbox: BoundingBox, questTypes: Collection<String>): List<OsmQuest> {
if (questTypes.isEmpty()) return listOf()
return dao.getAll(
statusIn = listOf(QuestStatus.NEW),
bounds = bbox,
questTypes = questTypes
)
}
/** Get single quest by id */
fun get(id: Long): OsmQuest? = dao.get(id)
/** Get the last undoable quest (includes answered, hidden and uploaded) */
fun getLastUndoable(): OsmQuest? = dao.getLastSolved()
/** Get all undoable quests count */
fun getAllUndoableCount(): Int = dao.getCount(statusIn = listOf(
QuestStatus.ANSWERED, QuestStatus.CLOSED, QuestStatus.HIDDEN
))
/** Get all answered quests */
fun getAllAnswered(): List<OsmQuest> = dao.getAll(statusIn = listOf(QuestStatus.ANSWERED))
/** Get all answered quests count */
fun getAllAnsweredCount(): Int = dao.getCount(statusIn = listOf(QuestStatus.ANSWERED))
/** Get all quests for the given type */
fun getAllForElement(elementType: Element.Type, elementId: Long): List<OsmQuest> =
dao.getAll(element = ElementKey(elementType, elementId))
/* ------------------------------------ Listeners ------------------------------------------- */
fun addQuestStatusListener(listener: QuestStatusListener) {
questStatusListeners.add(listener)
}
fun removeQuestStatusListener(listener: QuestStatusListener) {
questStatusListeners.remove(listener)
}
private fun onChanged(quest: OsmQuest, previousStatus: QuestStatus) {
questStatusListeners.forEach { it.onChanged(quest, previousStatus) }
}
private fun onRemoved(id: Long, previousStatus: QuestStatus) {
questStatusListeners.forEach { it.onRemoved(id, previousStatus) }
}
private fun onUpdated(
added: Collection<OsmQuest> = listOf(),
updated: Collection<OsmQuest> = listOf(),
deleted: Collection<Long> = listOf()
) {
questStatusListeners.forEach { it.onUpdated(added, updated, deleted) }
}
data class UpdateResult(val added: Int, val deleted: Int)
}
| gpl-3.0 | 5af0f7a72420ca8db55836f6ab611914 | 42.513605 | 119 | 0.663801 | 4.895905 | false | false | false | false |
HabitRPG/habitica-android | Habitica/src/main/java/com/habitrpg/android/habitica/ui/viewmodels/NotificationsViewModel.kt | 1 | 16423 | package com.habitrpg.android.habitica.ui.viewmodels
import android.os.Bundle
import androidx.core.os.bundleOf
import androidx.lifecycle.viewModelScope
import com.habitrpg.android.habitica.R
import com.habitrpg.android.habitica.components.UserComponent
import com.habitrpg.android.habitica.data.SocialRepository
import com.habitrpg.android.habitica.helpers.MainNavigationController
import com.habitrpg.android.habitica.helpers.NotificationsManager
import com.habitrpg.android.habitica.helpers.ExceptionHandler
import com.habitrpg.android.habitica.models.social.UserParty
import com.habitrpg.android.habitica.models.user.User
import com.habitrpg.common.habitica.models.Notification
import com.habitrpg.common.habitica.models.notifications.GroupTaskRequiresApprovalData
import com.habitrpg.common.habitica.models.notifications.GuildInvitationData
import com.habitrpg.common.habitica.models.notifications.GuildInvite
import com.habitrpg.common.habitica.models.notifications.NewChatMessageData
import com.habitrpg.common.habitica.models.notifications.NewStuffData
import com.habitrpg.common.habitica.models.notifications.PartyInvitationData
import com.habitrpg.common.habitica.models.notifications.PartyInvite
import com.habitrpg.common.habitica.models.notifications.QuestInvitationData
import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers
import io.reactivex.rxjava3.core.BackpressureStrategy
import io.reactivex.rxjava3.core.Flowable
import io.reactivex.rxjava3.functions.BiFunction
import io.reactivex.rxjava3.subjects.BehaviorSubject
import kotlinx.coroutines.launch
import javax.inject.Inject
open class NotificationsViewModel : BaseViewModel() {
@Inject
lateinit var notificationsManager: NotificationsManager
@Inject
lateinit var socialRepository: SocialRepository
private val supportedNotificationTypes = listOf(
Notification.Type.NEW_STUFF.type,
Notification.Type.NEW_CHAT_MESSAGE.type,
Notification.Type.NEW_MYSTERY_ITEMS.type,
Notification.Type.GROUP_TASK_NEEDS_WORK.type,
Notification.Type.GROUP_TASK_APPROVED.type,
Notification.Type.UNALLOCATED_STATS_POINTS.type
)
private val actionableNotificationTypes = listOf(
Notification.Type.GUILD_INVITATION.type,
Notification.Type.PARTY_INVITATION.type,
Notification.Type.QUEST_INVITATION.type
)
private var party: UserParty? = null
private val customNotifications: BehaviorSubject<List<Notification>> = BehaviorSubject.create()
override fun inject(component: UserComponent) {
component.inject(this)
}
init {
customNotifications.onNext(emptyList())
userViewModel.user.observeForever {
if (it == null) return@observeForever
party = it.party
val notifications = convertInvitationsToNotifications(it)
if (it.flags?.newStuff == true) {
val notification = Notification()
notification.id = "custom-new-stuff-notification"
notification.type = Notification.Type.NEW_STUFF.type
val data = NewStuffData()
notification.data = data
notifications.add(notification)
}
customNotifications.onNext(notifications)
}
}
fun getNotifications(): Flowable<List<Notification>> {
val serverNotifications = notificationsManager.getNotifications()
.map { filterSupportedTypes(it) }
return Flowable.combineLatest(
serverNotifications,
customNotifications.toFlowable(BackpressureStrategy.LATEST),
BiFunction {
serverNotificationsList, customNotificationsList ->
if (serverNotificationsList.firstOrNull { notification -> notification.type == Notification.Type.NEW_STUFF.type } != null) {
return@BiFunction serverNotificationsList + customNotificationsList.filter { notification -> notification.type != Notification.Type.NEW_STUFF.type }
}
return@BiFunction serverNotificationsList + customNotificationsList
}
)
.map { it.sortedBy { notification -> notification.priority } }
.observeOn(AndroidSchedulers.mainThread())
}
fun getNotificationCount(): Flowable<Int> {
return getNotifications()
.map { it.count() }
.distinctUntilChanged()
}
fun allNotificationsSeen(): Flowable<Boolean> {
return getNotifications()
.map { it.all { notification -> notification.seen != false } }
.distinctUntilChanged()
}
fun getHasPartyNotification(): Flowable<Boolean> {
return getNotifications()
.map {
it.find { notification ->
val data = notification.data as? NewChatMessageData
isPartyMessage(data)
} != null
}
.distinctUntilChanged()
}
suspend fun refreshNotifications(): User? {
return userRepository.retrieveUser(withTasks = false, forced = true)
}
private fun filterSupportedTypes(notifications: List<Notification>): List<Notification> {
return notifications.filter { supportedNotificationTypes.contains(it.type) }
}
private fun convertInvitationsToNotifications(user: User): MutableList<Notification> {
val notifications = mutableListOf<Notification>()
notifications.addAll(
user.invitations?.parties?.map {
val notification = Notification()
notification.id = "custom-party-invitation-" + it.id
notification.type = Notification.Type.PARTY_INVITATION.type
val data = PartyInvitationData()
data.invitation = PartyInvite()
data.invitation?.id = it.id
data.invitation?.name = it.name
data.invitation?.inviter = it.inviter
notification.data = data
notification
} ?: emptyList()
)
notifications.addAll(
user.invitations?.guilds?.map {
val notification = Notification()
notification.id = "custom-guild-invitation-" + it.id
notification.type = Notification.Type.GUILD_INVITATION.type
val data = GuildInvitationData()
data.invitation = GuildInvite()
data.invitation?.id = it.id
data.invitation?.name = it.name
data.invitation?.inviter = it.inviter
data.invitation?.publicGuild = it.publicGuild
notification.data = data
notification
} ?: emptyList()
)
val quest = user.party?.quest
if (quest != null && quest.RSVPNeeded) {
val notification = Notification()
notification.id = "custom-quest-invitation-" + user.party?.id
notification.type = Notification.Type.QUEST_INVITATION.type
val data = QuestInvitationData()
data.questKey = quest.key
notification.data = data
notifications.add(notification)
}
return notifications
}
fun isPartyMessage(data: NewChatMessageData?): Boolean {
if (party?.isValid != true || data?.group?.id == null) {
return false
}
return party?.id == data.group?.id
}
/**
* Is the given notification an "artificial" custom notification (created by this class)
* instead of one of the ones coming from server.
*/
private fun isCustomNotification(notification: Notification): Boolean {
return notification.id.startsWith("custom-")
}
private fun isCustomNewStuffNotification(notification: Notification) =
notification.id == "custom-new-stuff-notification"
fun dismissNotification(notification: Notification) {
if (isCustomNotification(notification)) {
if (isCustomNewStuffNotification(notification)) {
customNotifications.onNext(
customNotifications.value?.filterNot { it.id == notification.id } ?: listOf()
)
}
return
}
disposable.add(
userRepository.readNotification(notification.id)
.subscribe({}, ExceptionHandler.rx())
)
}
fun dismissAllNotifications(notifications: List<Notification>) {
val dismissableIds = notifications
.filter { !isCustomNotification(it) }
.filter { !actionableNotificationTypes.contains(it.type) }
.map { it.id }
val customNewStuffNotification = notifications
.firstOrNull { isCustomNewStuffNotification(it) }
if (customNewStuffNotification != null) {
dismissNotification(customNewStuffNotification)
}
if (dismissableIds.isEmpty()) {
return
}
val notificationIds = HashMap<String, List<String>>()
notificationIds["notificationIds"] = dismissableIds
disposable.add(
userRepository.readNotifications(notificationIds)
.subscribe({}, ExceptionHandler.rx())
)
}
fun markNotificationsAsSeen(notifications: List<Notification>) {
val unseenIds = notifications
.filter { !isCustomNotification(it) }
.filter { it.seen == false }
.map { it.id }
if (unseenIds.isEmpty()) {
return
}
val notificationIds = HashMap<String, List<String>>()
notificationIds["notificationIds"] = unseenIds
disposable.add(
userRepository.seeNotifications(notificationIds)
.subscribe({}, ExceptionHandler.rx())
)
}
private fun findNotification(id: String): Notification? {
return notificationsManager.getNotification(id) ?: customNotifications.value?.find { it.id == id }
}
fun click(notificationId: String, navController: MainNavigationController) {
val notification = findNotification(notificationId) ?: return
dismissNotification(notification)
when (notification.type) {
Notification.Type.NEW_STUFF.type -> navController.navigate(R.id.newsFragment)
Notification.Type.NEW_CHAT_MESSAGE.type -> clickNewChatMessage(notification, navController)
Notification.Type.GUILD_INVITATION.type -> clickGroupInvitation(notification, navController)
Notification.Type.PARTY_INVITATION.type -> clickGroupInvitation(notification, navController)
Notification.Type.QUEST_INVITATION.type -> navController.navigate(R.id.partyFragment)
Notification.Type.NEW_MYSTERY_ITEMS.type -> navController.navigate(R.id.itemsFragment, bundleOf(Pair("itemType", "special")))
Notification.Type.UNALLOCATED_STATS_POINTS.type -> navController.navigate(R.id.statsFragment)
// Group tasks should go to Group tasks view if that is added to this app at some point
Notification.Type.GROUP_TASK_APPROVED.type -> navController.navigate(R.id.tasksFragment)
Notification.Type.GROUP_TASK_NEEDS_WORK.type -> navController.navigate(R.id.tasksFragment)
}
}
private fun clickNewChatMessage(
notification: Notification,
navController: MainNavigationController
) {
val data = notification.data as? NewChatMessageData
if (isPartyMessage(data)) {
val bundle = Bundle()
bundle.putString("groupID", data?.group?.id)
navController.navigate(R.id.partyFragment, bundle)
} else {
val bundle = Bundle()
bundle.putString("groupID", data?.group?.id)
bundle.putBoolean("isMember", true) // safe to assume user is member since they got the notification
bundle.putInt("tabToOpen", 1)
navController.navigate(R.id.guildFragment, bundle)
}
}
private fun clickGroupInvitation(
notification: Notification,
navController: MainNavigationController
) {
when (notification.type) {
Notification.Type.GUILD_INVITATION.type -> {
val bundle = Bundle()
val data = notification.data as? GuildInvitationData
bundle.putString("groupID", data?.invitation?.id)
bundle.putBoolean("isMember", true) // safe to assume user is member since they got the notification
navController.navigate(R.id.guildFragment, bundle)
}
Notification.Type.PARTY_INVITATION.type -> {
navController.navigate(R.id.partyFragment)
}
}
}
fun accept(notificationId: String) {
val notification = findNotification(notificationId) ?: return
when (notification.type) {
Notification.Type.GUILD_INVITATION.type -> {
val data = notification.data as? GuildInvitationData
acceptGroupInvitation(data?.invitation?.id)
}
Notification.Type.PARTY_INVITATION.type -> {
val data = notification.data as? PartyInvitationData
acceptGroupInvitation(data?.invitation?.id)
}
Notification.Type.QUEST_INVITATION.type -> acceptQuestInvitation()
Notification.Type.GROUP_TASK_REQUIRES_APPROVAL.type -> acceptTaskApproval(notification)
}
if (isCustomNotification(notification)) {
viewModelScope.launch(ExceptionHandler.coroutine()) {
userRepository.retrieveUser()
}
} else {
dismissNotification(notification)
}
}
fun reject(notificationId: String) {
val notification = findNotification(notificationId) ?: return
when (notification.type) {
Notification.Type.GUILD_INVITATION.type -> {
val data = notification.data as? GuildInvitationData
rejectGroupInvite(data?.invitation?.id)
}
Notification.Type.PARTY_INVITATION.type -> {
val data = notification.data as? PartyInvitationData
rejectGroupInvite(data?.invitation?.id)
}
Notification.Type.QUEST_INVITATION.type -> rejectQuestInvitation()
Notification.Type.GROUP_TASK_REQUIRES_APPROVAL.type -> rejectTaskApproval(notification)
}
if (!isCustomNotification(notification)) {
dismissNotification(notification)
}
}
private fun acceptGroupInvitation(groupId: String?) {
groupId?.let {
viewModelScope.launch(ExceptionHandler.coroutine()) {
socialRepository.joinGroup(it)
refreshUser()
}
}
}
fun rejectGroupInvite(groupId: String?) {
groupId?.let {
disposable.add(
socialRepository.rejectGroupInvite(it)
.subscribe(
{
refreshUser()
},
ExceptionHandler.rx()
)
)
}
}
private fun acceptQuestInvitation() {
party?.id?.let {
disposable.add(
socialRepository.acceptQuest(null, it)
.subscribe(
{
refreshUser()
},
ExceptionHandler.rx()
)
)
}
}
private fun rejectQuestInvitation() {
party?.id?.let {
disposable.add(
socialRepository.rejectQuest(null, it)
.subscribe(
{
refreshUser()
},
ExceptionHandler.rx()
)
)
}
}
private fun refreshUser() {
viewModelScope.launch(ExceptionHandler.coroutine()) {
refreshNotifications()
}
}
private fun acceptTaskApproval(notification: Notification) {
notification.data as? GroupTaskRequiresApprovalData
}
private fun rejectTaskApproval(notification: Notification) {
notification.data as? GroupTaskRequiresApprovalData
}
}
| gpl-3.0 | 7bb59e187d867eee3838c426dd8b7add | 37.825059 | 168 | 0.627108 | 5.3063 | false | false | false | false |
austinv11/KotBot-IV | Core/src/main/kotlin/com/austinv11/kotbot/core/api/commands/Command.kt | 1 | 928 | package com.austinv11.kotbot.core.api.commands
import com.austinv11.kotbot.core.util.ModuleDependentObject
abstract class Command(val description: String,
val aliases: Array<String> = arrayOf(),
val requiredLevel: PermissionLevel = PermissionLevel.BASIC,
val nameOverride: String? = null) : ModuleDependentObject {
val name: String
get() {
if (nameOverride.isNullOrEmpty()) {
return this::class.simpleName!!.replace("Command", "").toLowerCase()
} else {
return nameOverride!!
}
}
fun doesCommandMatch(input: String): Boolean = (aliases+name).firstOrNull { it.equals(input, true) } != null
override fun clean() {
CommandRegistry.commands.remove(this)
}
override fun inject() {
CommandRegistry.commands.add(this)
}
}
| gpl-3.0 | 541eb902ee34b692a3bf9342a792a3b2 | 32.142857 | 112 | 0.591595 | 4.71066 | false | false | false | false |
campos20/tnoodle | webscrambles/src/main/kotlin/org/worldcubeassociation/tnoodle/server/webscrambles/wcif/model/Gender.kt | 1 | 806 | package org.worldcubeassociation.tnoodle.server.webscrambles.wcif.model
import org.worldcubeassociation.tnoodle.server.serial.SingletonStringEncoder
import org.worldcubeassociation.tnoodle.server.webscrambles.exceptions.BadWcifParameterException
enum class Gender(val wcaString: String) {
MALE("m"),
FEMALE("f"),
OTHER("o");
companion object : SingletonStringEncoder<Gender>("Gender") {
fun fromWCAString(wcaString: String) = values().find { it.wcaString == wcaString }
override fun encodeInstance(instance: Gender) = instance.wcaString
override fun makeInstance(deserialized: String) = fromWCAString(deserialized)
?: BadWcifParameterException.error("Unknown WCIF spec Gender: '$deserialized'. Valid types: ${values().map { it.wcaString }}")
}
}
| gpl-3.0 | 9094debb982456e8f1a666df1ef99200 | 43.777778 | 138 | 0.743176 | 4.356757 | false | false | false | false |
westnordost/osmagent | app/src/main/java/de/westnordost/streetcomplete/quests/opening_hours/model/OpeningMonths.kt | 1 | 1741 | package de.westnordost.streetcomplete.quests.opening_hours.model
import java.text.DateFormatSymbols
import java.util.*
class OpeningMonths(var months: CircularSection, var weekdaysClusters: List<List<OpeningWeekdays>>){
private val isWholeYear: Boolean
get() {
val aYear = NumberSystem(0, OpeningMonths.MAX_MONTH_INDEX)
return aYear.complemented(listOf(months)).isEmpty()
}
override fun toString(): String {
// the US locale is important here as this is the OSM format for dates
val monthsSymbols = DateFormatSymbols.getInstance(Locale.US).shortMonths
val months = if(isWholeYear) "" else months.toStringUsing(monthsSymbols, "-") + ": "
return weekdaysClusters.joinToString("; ") { weekdaysCluster ->
weekdaysCluster.joinToString(", ") { openingWeekdays ->
val weekdays = openingWeekdays.weekdays.toString()
val times = openingWeekdays.timeRanges.joinToString(",")
months + weekdays + " " + times
}
}
}
fun containsSelfIntersectingOpeningWeekdays(): Boolean {
for (weekdaysCluster in weekdaysClusters) {
for (openingWeekdays in weekdaysCluster) {
if (openingWeekdays.isSelfIntersecting()) return true
}
}
return false
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other !is OpeningMonths) return false
return months == other.months && weekdaysClusters == other.weekdaysClusters
}
override fun hashCode() = 31 * months.hashCode() + weekdaysClusters.hashCode()
companion object {
val MAX_MONTH_INDEX = 11
}
}
| gpl-3.0 | 0889cbaec0c30e17630246ab8f78406d | 34.530612 | 100 | 0.641585 | 4.876751 | false | false | false | false |
GLodi/GitNav | app/src/main/java/giuliolodi/gitnav/ui/issuelist/IssueClosedFragment.kt | 1 | 6282 | /*
* Copyright 2017 GLodi
*
* 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 giuliolodi.gitnav.ui.issuelist
import android.os.Bundle
import android.support.v7.widget.DefaultItemAnimator
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import com.yqritc.recyclerviewflexibledivider.HorizontalDividerItemDecoration
import es.dmoral.toasty.Toasty
import giuliolodi.gitnav.R
import giuliolodi.gitnav.ui.adapters.IssueAdapter
import giuliolodi.gitnav.ui.base.BaseFragment
import giuliolodi.gitnav.ui.issue.IssueActivity
import giuliolodi.gitnav.ui.user.UserActivity
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import kotlinx.android.synthetic.main.issue_list_closed.*
import org.eclipse.egit.github.core.Issue
import javax.inject.Inject
/**
* Created by giulio on 02/09/2017.
*/
class IssueClosedFragment : BaseFragment(), IssueClosedContract.View {
@Inject lateinit var mPresenter: IssueClosedContract.Presenter<IssueClosedContract.View>
private var mOwner: String? = null
private var mName: String? = null
companion object {
fun newInstance(owner: String, name: String): IssueClosedFragment {
val issueClosedFragment: IssueClosedFragment = IssueClosedFragment()
val bundle: Bundle = Bundle()
bundle.putString("owner", owner)
bundle.putString("name", name)
issueClosedFragment.arguments = bundle
return issueClosedFragment
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
retainInstance = true
getActivityComponent()?.inject(this)
mOwner = arguments.getString("owner")
mName = arguments.getString("name")
}
override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View? {
return inflater?.inflate(R.layout.issue_list_closed, container, false)
}
override fun initLayout(view: View?, savedInstanceState: Bundle?) {
mPresenter.onAttach(this)
val llm = LinearLayoutManager(context)
llm.orientation = LinearLayoutManager.VERTICAL
issue_list_closed_rv.layoutManager = llm
issue_list_closed_rv.addItemDecoration(HorizontalDividerItemDecoration.Builder(context).showLastDivider().build())
issue_list_closed_rv.itemAnimator = DefaultItemAnimator()
issue_list_closed_rv.adapter = IssueAdapter()
(issue_list_closed_rv.adapter as IssueAdapter).getUserClick()
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe { username -> mPresenter.onUserClick(username) }
(issue_list_closed_rv.adapter as IssueAdapter).getIssueClick()
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe { issueNumber -> mPresenter.onIssueClick(issueNumber) }
val mScrollListenerStarred = object : RecyclerView.OnScrollListener() {
override fun onScrolled(recyclerView: RecyclerView?, dx: Int, dy: Int) {
val visibleItemCount = (issue_list_closed_rv.layoutManager as LinearLayoutManager).childCount
val totalItemCount = (issue_list_closed_rv.layoutManager as LinearLayoutManager).itemCount
val pastVisibleItems = (issue_list_closed_rv.layoutManager as LinearLayoutManager).findFirstVisibleItemPosition()
if (pastVisibleItems + visibleItemCount >= totalItemCount) {
mPresenter.onLastItemVisible(isNetworkAvailable(), dy)
}
}
}
issue_list_closed_rv.setOnScrollListener(mScrollListenerStarred)
mPresenter.subscribe(isNetworkAvailable(), mOwner, mName)
}
override fun showClosedIssues(issueList: List<Issue>) {
(issue_list_closed_rv.adapter as IssueAdapter).addIssueList(issueList)
}
override fun showLoading() {
issue_list_closed_progressbar.visibility = View.VISIBLE
}
override fun hideLoading() {
issue_list_closed_progressbar.visibility = View.GONE
}
override fun showListLoading() {
(issue_list_closed_rv.adapter as IssueAdapter).addLoading()
}
override fun hideListLoading() {
(issue_list_closed_rv.adapter as IssueAdapter).hideLoading()
}
override fun showNoClosedIssues() {
issue_list_closed_noissues.visibility = View.VISIBLE
}
override fun hideNoClosedIssues() {
issue_list_closed_noissues.visibility = View.GONE
}
override fun showError(error: String) {
Toasty.error(context, error, Toast.LENGTH_LONG).show()
}
override fun showNoConnectionError() {
Toasty.warning(context, getString(R.string.network_error), Toast.LENGTH_LONG).show()
}
override fun intentToUserActivity(username: String) {
startActivity(UserActivity.getIntent(context).putExtra("username", username))
activity.overridePendingTransition(0,0)
}
override fun intentToIssueActivity(issueNumber: Int) {
startActivity(IssueActivity.getIntent(context)
.putExtra("owner", mOwner)
.putExtra("name", mName)
.putExtra("issueNumber", issueNumber))
activity.overridePendingTransition(0,0)
}
override fun onDestroyView() {
mPresenter.onDetachView()
super.onDestroyView()
}
override fun onDestroy() {
mPresenter.onDetach()
super.onDestroy()
}
} | apache-2.0 | f62994cd462fbf2942519cf2df31dd0c | 36.39881 | 129 | 0.701687 | 4.744713 | false | false | false | false |
NerdNumber9/TachiyomiEH | app/src/main/java/eu/kanade/tachiyomi/source/online/english/Pururin.kt | 1 | 4519 | package eu.kanade.tachiyomi.source.online.english
import android.net.Uri
import eu.kanade.tachiyomi.network.asObservableSuccess
import eu.kanade.tachiyomi.source.model.FilterList
import eu.kanade.tachiyomi.source.model.MangasPage
import eu.kanade.tachiyomi.source.model.SManga
import eu.kanade.tachiyomi.source.online.HttpSource
import eu.kanade.tachiyomi.source.online.LewdSource
import eu.kanade.tachiyomi.source.online.UrlImportableSource
import eu.kanade.tachiyomi.util.asJsoup
import exh.metadata.metadata.PururinSearchMetadata
import exh.metadata.metadata.base.RaisedTag
import exh.source.DelegatedHttpSource
import exh.util.dropBlank
import exh.util.trimAll
import exh.util.urlImportFetchSearchManga
import org.jsoup.nodes.Document
import rx.Observable
class Pururin(delegate: HttpSource) : DelegatedHttpSource(delegate),
LewdSource<PururinSearchMetadata, Document>, UrlImportableSource {
/**
* An ISO 639-1 compliant language code (two letters in lower case).
*/
override val lang = "en"
/**
* The class of the metadata used by this source
*/
override val metaClass = PururinSearchMetadata::class
//Support direct URL importing
override fun fetchSearchManga(page: Int, query: String, filters: FilterList): Observable<MangasPage> {
val trimmedIdQuery = query.trim().removePrefix("id:")
val newQuery = if(trimmedIdQuery.toIntOrNull() ?: -1 >= 0) {
"$baseUrl/gallery/$trimmedIdQuery/-"
} else query
return urlImportFetchSearchManga(newQuery) {
super.fetchSearchManga(page, query, filters)
}
}
override fun fetchMangaDetails(manga: SManga): Observable<SManga> {
return client.newCall(mangaDetailsRequest(manga))
.asObservableSuccess()
.flatMap {
parseToManga(manga, it.asJsoup())
.andThen(Observable.just(manga))
}
}
override fun parseIntoMetadata(metadata: PururinSearchMetadata, input: Document) {
val selfLink = input.select("[itemprop=name]").last().parent()
val parsedSelfLink = Uri.parse(selfLink.attr("href")).pathSegments
with(metadata) {
prId = parsedSelfLink[parsedSelfLink.lastIndex - 1].toIntOrNull()
prShortLink = parsedSelfLink.last()
val contentWrapper = input.selectFirst(".content-wrapper")
title = contentWrapper.selectFirst(".title h1").text()
altTitle = contentWrapper.selectFirst(".alt-title").text()
thumbnailUrl = "https:" + input.selectFirst(".cover-wrapper v-lazy-image").attr("src")
tags.clear()
contentWrapper.select(".table-gallery-info > tbody > tr").forEach { ele ->
val key = ele.child(0).text().toLowerCase()
val value = ele.child(1)
when(key) {
"pages" -> {
val split = value.text().split("(").trimAll().dropBlank()
pages = split.first().toIntOrNull()
fileSize = split.last().removeSuffix(")").trim()
}
"ratings" -> {
ratingCount = value.selectFirst("[itemprop=ratingCount]").attr("content").toIntOrNull()
averageRating = value.selectFirst("[itemprop=ratingValue]").attr("content").toDoubleOrNull()
}
"uploader" -> {
uploaderDisp = value.text()
uploader = Uri.parse(value.child(0).attr("href")).lastPathSegment
}
else -> {
value.select("a").forEach { link ->
val searchUrl = Uri.parse(link.attr("href"))
tags += RaisedTag(
searchUrl.pathSegments[searchUrl.pathSegments.lastIndex - 2],
searchUrl.lastPathSegment!!.substringBefore("."),
PururinSearchMetadata.TAG_TYPE_DEFAULT
)
}
}
}
}
}
}
override val matchingHosts = listOf(
"pururin.io",
"www.pururin.io"
)
override fun mapUrlToMangaUrl(uri: Uri): String? {
return "${PururinSearchMetadata.BASE_URL}/gallery/${uri.pathSegments[1]}/${uri.lastPathSegment}"
}
} | apache-2.0 | 20e955a6ed3e078502cd34d9570b76d0 | 40.46789 | 116 | 0.589954 | 4.792153 | false | false | false | false |
GKZX-HN/MyGithub | app/src/main/java/com/gkzxhn/mygithub/utils/LogUtil.kt | 1 | 3309 | package com.gkzxhn.mygithub.utils
import android.util.Log
/**
* Created by Xuezhi on 2017/12/14.
*/
object LogUtil {
//可以全局控制是否打印log日志
private val isPrintLog = true
private val LOG_MAXLENGTH = 2000
fun v(msg: String) {
v("LogUtil", msg)
}
fun v(tagName: String, msg: String) {
if (isPrintLog) {
val strLength = msg.length
var start = 0
var end = LOG_MAXLENGTH
for (i in 0..99) {
if (strLength > end) {
Log.v(tagName + i, msg.substring(start, end))
start = end
end = end + LOG_MAXLENGTH
} else {
Log.v(tagName + i, msg.substring(start, strLength))
break
}
}
}
}
fun d(msg: String) {
d("LogUtil", msg)
}
fun d(tagName: String, msg: String) {
if (isPrintLog) {
val strLength = msg.length
var start = 0
var end = LOG_MAXLENGTH
for (i in 0..99) {
if (strLength > end) {
Log.d(tagName + i, msg.substring(start, end))
start = end
end = end + LOG_MAXLENGTH
} else {
Log.d(tagName + i, msg.substring(start, strLength))
break
}
}
}
}
fun i(msg: String) {
i("LogUtil", msg)
}
fun i(tagName: String, msg: String) {
if (isPrintLog) {
val strLength = msg.length
var start = 0
var end = LOG_MAXLENGTH
for (i in 0..99) {
if (strLength > end) {
Log.i(tagName + i, msg.substring(start, end))
start = end
end = end + LOG_MAXLENGTH
} else {
Log.i(tagName + i, msg.substring(start, strLength))
break
}
}
}
}
fun w(msg: String) {
w("LogUtil", msg)
}
fun w(tagName: String, msg: String) {
if (isPrintLog) {
val strLength = msg.length
var start = 0
var end = LOG_MAXLENGTH
for (i in 0..99) {
if (strLength > end) {
Log.w(tagName + i, msg.substring(start, end))
start = end
end = end + LOG_MAXLENGTH
} else {
Log.w(tagName + i, msg.substring(start, strLength))
break
}
}
}
}
fun e(msg: String) {
e("LogUtil", msg)
}
fun e(tagName: String, msg: String) {
if (isPrintLog) {
val strLength = msg.length
var start = 0
var end = LOG_MAXLENGTH
for (i in 0..99) {
if (strLength > end) {
Log.e(tagName + i, msg.substring(start, end))
start = end
end = end + LOG_MAXLENGTH
} else {
Log.e(tagName + i, msg.substring(start, strLength))
break
}
}
}
}
} | gpl-3.0 | a50e32c4185d25fa5c1f970532db836c | 24.874016 | 71 | 0.408524 | 4.249677 | false | false | false | false |
da1z/intellij-community | python/src/com/jetbrains/python/sdk/add/PySdkPathChoosingComboBox.kt | 1 | 2274 | /*
* Copyright 2000-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.jetbrains.python.sdk.add
import com.intellij.openapi.fileChooser.FileChooser
import com.intellij.openapi.projectRoots.Sdk
import com.intellij.openapi.ui.ComponentWithBrowseButton
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.ui.ComboboxSpeedSearch
import com.jetbrains.python.sdk.PyDetectedSdk
import com.jetbrains.python.sdk.PySdkListCellRenderer
import com.jetbrains.python.sdk.PythonSdkType
import javax.swing.JComboBox
/**
* @author vlan
*/
class PySdkPathChoosingComboBox(sdks: List<Sdk>, suggestedFile: VirtualFile?) :
ComponentWithBrowseButton<JComboBox<Sdk>>(JComboBox(sdks.toTypedArray()), null) {
init {
childComponent.apply {
renderer = PySdkListCellRenderer(null)
ComboboxSpeedSearch(this)
}
addActionListener {
val pythonSdkType = PythonSdkType.getInstance()
val descriptor = pythonSdkType.homeChooserDescriptor.apply {
isForcedToUseIdeaFileChooser = true
}
FileChooser.chooseFiles(descriptor, null, suggestedFile) {
val virtualFile = it.firstOrNull() ?: return@chooseFiles
val path = virtualFile.path
if (!pythonSdkType.isValidSdkHome(path)) return@chooseFiles
childComponent.selectedItem =
items.find { it.homePath == path } ?: PyDetectedSdk(path).apply {
childComponent.insertItemAt(this, 0)
}
}
}
}
var selectedSdk: Sdk?
get() = childComponent.selectedItem as? Sdk?
set(value) {
if (value in items) {
childComponent.selectedItem = value
}
}
val items: List<Sdk>
get() = (0 until childComponent.itemCount).map { childComponent.getItemAt(it) }
} | apache-2.0 | bd39998ded76f65190473b1de2b5bad2 | 33.469697 | 83 | 0.724714 | 4.406977 | false | false | false | false |
CarlosEsco/tachiyomi | app/src/main/java/eu/kanade/data/QueryPagingSource.kt | 1 | 2414 | package eu.kanade.data
import androidx.paging.PagingSource
import androidx.paging.PagingState
import com.squareup.sqldelight.Query
import eu.kanade.tachiyomi.Database
import kotlin.properties.Delegates
class QueryPagingSource<RowType : Any>(
val handler: DatabaseHandler,
val countQuery: Database.() -> Query<Long>,
val queryProvider: Database.(Long, Long) -> Query<RowType>,
) : PagingSource<Long, RowType>(), Query.Listener {
override val jumpingSupported: Boolean = true
private var currentQuery: Query<RowType>? by Delegates.observable(null) { _, old, new ->
old?.removeListener(this)
new?.addListener(this)
}
init {
registerInvalidatedCallback {
currentQuery?.removeListener(this)
currentQuery = null
}
}
override suspend fun load(params: LoadParams<Long>): LoadResult<Long, RowType> {
try {
val key = params.key ?: 0L
val loadSize = params.loadSize
val count = handler.awaitOne { countQuery() }
val (offset, limit) = when (params) {
is LoadParams.Prepend -> key - loadSize to loadSize.toLong()
else -> key to loadSize.toLong()
}
val data = handler.awaitList {
queryProvider(limit, offset)
.also { currentQuery = it }
}
val (prevKey, nextKey) = when (params) {
is LoadParams.Append -> { offset - loadSize to offset + loadSize }
else -> { offset to offset + loadSize }
}
return LoadResult.Page(
data = data,
prevKey = if (offset <= 0L || prevKey < 0L) null else prevKey,
nextKey = if (offset + loadSize >= count) null else nextKey,
itemsBefore = maxOf(0L, offset).toInt(),
itemsAfter = maxOf(0L, count - (offset + loadSize)).toInt(),
)
} catch (e: Exception) {
return LoadResult.Error(throwable = e)
}
}
override fun getRefreshKey(state: PagingState<Long, RowType>): Long? {
return state.anchorPosition?.let { anchorPosition ->
val anchorPage = state.closestPageToPosition(anchorPosition)
anchorPage?.prevKey ?: anchorPage?.nextKey
}
}
override fun queryResultsChanged() {
invalidate()
}
}
| apache-2.0 | ef33b2d734008532cf17a543758ac6cc | 32.527778 | 92 | 0.58575 | 4.837675 | false | false | false | false |
square/wire | wire-library/wire-schema/src/commonMain/kotlin/com/squareup/wire/schema/MessageType.kt | 1 | 10128 | /*
* 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 com.squareup.wire.schema
import com.squareup.wire.Syntax
import com.squareup.wire.schema.Extend.Companion.fromElements
import com.squareup.wire.schema.Extend.Companion.toElements
import com.squareup.wire.schema.Extensions.Companion.fromElements
import com.squareup.wire.schema.Extensions.Companion.toElements
import com.squareup.wire.schema.Field.Companion.fromElements
import com.squareup.wire.schema.Field.Companion.retainAll
import com.squareup.wire.schema.Field.Companion.retainLinked
import com.squareup.wire.schema.Field.Companion.toElements
import com.squareup.wire.schema.OneOf.Companion.fromElements
import com.squareup.wire.schema.OneOf.Companion.toElements
import com.squareup.wire.schema.Options.Companion.MESSAGE_OPTIONS
import com.squareup.wire.schema.Reserved.Companion.fromElements
import com.squareup.wire.schema.Reserved.Companion.toElements
import com.squareup.wire.schema.internal.parser.MessageElement
import kotlin.jvm.JvmName
import kotlin.jvm.JvmStatic
data class MessageType(
override val type: ProtoType,
override val location: Location,
override val documentation: String,
override val name: String,
val declaredFields: List<Field>,
val extensionFields: MutableList<Field>,
val oneOfs: List<OneOf>,
override val nestedTypes: List<Type>,
override val nestedExtendList: List<Extend>,
val extensionsList: List<Extensions>,
private val reserveds: List<Reserved>,
override val options: Options,
override val syntax: Syntax
) : Type() {
private var deprecated: Any? = null
val isDeprecated: Boolean
get() = "true" == deprecated
@get:JvmName("fields")
val fields get() = declaredFields + extensionFields
val requiredFields: List<Field>
get() = fieldsAndOneOfFields.filter { it.isRequired }
val fieldsAndOneOfFields: List<Field>
get() = declaredFields + extensionFields + oneOfs.flatMap { it.fields }
/** Returns the field named [name], or null if this type has no such field. */
fun field(name: String): Field? {
for (field in declaredFields) {
if (field.name == name) {
return field
}
}
for (oneOf in oneOfs) {
for (field in oneOf.fields) {
if (field.name == name) {
return field
}
}
}
return null
}
/**
* Returns the field with the qualified name [qualifiedName], or null if this type has no
* such field.
*/
fun extensionField(qualifiedName: String): Field? =
extensionFields.firstOrNull { it.qualifiedName == qualifiedName }
/** Returns the field tagged [tag], or null if this type has no such field. */
fun field(tag: Int): Field? {
for (field in declaredFields) {
if (field.tag == tag) {
return field
}
}
for (field in extensionFields) {
if (field.tag == tag) {
return field
}
}
return null
}
fun extensionFieldsMap(): Map<String, Field> {
// TODO(jwilson): simplify this to just resolve field values directly.
val extensionsForType = mutableMapOf<String, Field>()
for (field in extensionFields) {
extensionsForType[field.qualifiedName] = field
}
return extensionsForType
}
fun addExtensionFields(fields: List<Field>) {
extensionFields.addAll(fields)
}
override fun linkMembers(linker: Linker) {
val linker = linker.withContext(this)
for (field in declaredFields) {
field.link(linker)
}
for (oneOf in oneOfs) {
oneOf.link(linker)
}
}
override fun linkOptions(linker: Linker, syntaxRules: SyntaxRules, validate: Boolean) {
val linker = linker.withContext(this)
for (nestedType in nestedTypes) {
nestedType.linkOptions(linker, syntaxRules, validate)
}
for (field in declaredFields) {
field.linkOptions(linker, syntaxRules, validate)
}
for (oneOf in oneOfs) {
oneOf.linkOptions(linker, syntaxRules, validate)
}
options.link(linker, location, validate)
deprecated = options.get(DEPRECATED)
}
override fun validate(linker: Linker, syntaxRules: SyntaxRules) {
val linker = linker.withContext(this)
linker.validateFields(fieldsAndOneOfFields, reserveds, syntaxRules)
linker.validateEnumConstantNameUniqueness(nestedTypes)
for (field in fieldsAndOneOfFields) {
field.validate(linker, syntaxRules)
}
for (nestedType in nestedTypes) {
nestedType.validate(linker, syntaxRules)
}
for (extensions in extensionsList) {
extensions.validate(linker)
}
}
override fun retainAll(
schema: Schema,
markSet: MarkSet
): Type? {
val retainedNestedTypes = nestedTypes.mapNotNull { it.retainAll(schema, markSet) }
val retainedNestedExtends = nestedExtendList.mapNotNull { it.retainAll(schema, markSet) }
if (!markSet.contains(type) && !Options.GOOGLE_PROTOBUF_OPTION_TYPES.contains(type)) {
return when {
// This type is not retained, and none of its nested types are retained, prune it.
retainedNestedTypes.isEmpty() && retainedNestedExtends.isEmpty() -> null
// This type is not retained but retained nested types, replace it with an enclosing type.
else -> EnclosingType(location, type, name, documentation, retainedNestedTypes, retainedNestedExtends, syntax)
}
}
val retainedOneOfs = oneOfs.mapNotNull { it.retainAll(schema, markSet, type) }
val result = MessageType(
type = type,
location = location,
documentation = documentation,
name = name,
declaredFields = retainAll(schema, markSet, type, declaredFields),
extensionFields = retainAll(schema, markSet, type, extensionFields).toMutableList(),
oneOfs = retainedOneOfs,
nestedTypes = retainedNestedTypes,
nestedExtendList = retainedNestedExtends,
extensionsList = extensionsList,
reserveds = reserveds,
options = options.retainAll(schema, markSet),
syntax = syntax
)
result.deprecated = deprecated
return result
}
override fun retainLinked(linkedTypes: Set<ProtoType>, linkedFields: Set<Field>): Type? {
val retainedNestedTypes = nestedTypes.mapNotNull { it.retainLinked(linkedTypes, linkedFields) }
val retainedNestedExtends = nestedExtendList.mapNotNull { it.retainLinked(linkedFields) }
if (!linkedTypes.contains(type)) {
return when {
// This type is not retained, and none of its nested types are retained, prune it.
retainedNestedTypes.isEmpty() && retainedNestedExtends.isEmpty() -> null
// This type is not retained but retained nested types, replace it with an enclosing type.
else -> EnclosingType(location, type, name, documentation, retainedNestedTypes, retainedNestedExtends, syntax)
}
}
// We're retaining this type. Retain its fields and oneofs.
val retainedOneOfs = oneOfs.mapNotNull { it.retainLinked() }
return MessageType(
type = type,
location = location,
documentation = documentation,
name = name,
declaredFields = retainLinked(declaredFields),
extensionFields = retainLinked(extensionFields).toMutableList(),
oneOfs = retainedOneOfs,
nestedTypes = retainedNestedTypes,
nestedExtendList = retainedNestedExtends,
extensionsList = emptyList(),
reserveds = emptyList(),
options = options.retainLinked(),
syntax = syntax
)
}
fun toElement(): MessageElement {
return MessageElement(
location = location,
name = name,
documentation = documentation,
nestedTypes = toElements(nestedTypes),
extendDeclarations = toElements(nestedExtendList),
options = options.elements,
reserveds = toElements(reserveds),
fields = toElements(declaredFields),
oneOfs = toElements(oneOfs),
extensions = toElements(extensionsList),
groups = emptyList()
)
}
companion object {
internal val DEPRECATED = ProtoMember.get(MESSAGE_OPTIONS, "deprecated")
@JvmStatic fun fromElement(
namespaces: List<String>,
protoType: ProtoType,
messageElement: MessageElement,
syntax: Syntax
): MessageType {
check(messageElement.groups.isEmpty()) {
"${messageElement.groups[0].location}: 'group' is not supported"
}
// Namespaces for all child elements include this message's name.
val childNamespaces = when{
namespaces.isEmpty() -> listOf("", messageElement.name) // first element must be package name
else -> namespaces.plus(messageElement.name)
}
val nestedTypes =
messageElement.nestedTypes.map { get(childNamespaces, protoType.nestedType(it.name), it, syntax) }
val nestedExtends = fromElements(childNamespaces, messageElement.extendDeclarations)
return MessageType(
type = protoType,
location = messageElement.location,
documentation = messageElement.documentation,
name = messageElement.name,
declaredFields =
fromElements(childNamespaces, messageElement.fields, extension = false, oneOf = false),
extensionFields = mutableListOf(), // Extension fields are populated during linking.
oneOfs = fromElements(childNamespaces, messageElement.oneOfs),
nestedTypes = nestedTypes,
nestedExtendList = nestedExtends,
extensionsList = fromElements(messageElement.extensions),
reserveds = fromElements(messageElement.reserveds),
options = Options(MESSAGE_OPTIONS, messageElement.options),
syntax = syntax
)
}
}
}
| apache-2.0 | 762c4ec125bc62477d9554043ee8e8f3 | 34.914894 | 118 | 0.702903 | 4.380623 | false | false | false | false |
TeamMeanMachine/meanlib | src/main/kotlin/org/team2471/frc/lib/motion/following/SwerveDrive.kt | 1 | 18326 | package org.team2471.frc.lib.motion.following
import com.team254.lib.util.Interpolable
import com.team254.lib.util.InterpolatingDouble
import com.team254.lib.util.InterpolatingTreeMap
import edu.wpi.first.networktables.NetworkTableInstance
import edu.wpi.first.wpilibj.Timer
import org.team2471.frc.lib.coroutines.delay
import org.team2471.frc.lib.coroutines.periodic
import org.team2471.frc.lib.math.Vector2
import org.team2471.frc.lib.motion_profiling.Path2D
import org.team2471.frc.lib.motion_profiling.following.SwerveParameters
import org.team2471.frc.lib.units.*
import kotlin.math.*
private val poseHistory = InterpolatingTreeMap<InterpolatingDouble, SwerveDrive.Pose>(75)
private var prevPosition = Vector2(0.0, 0.0)
private var prevPathPosition = Vector2(0.0, 0.0)
private var prevTime = 0.0
private var prevPathHeading = 0.0.radians
private val MAXHEADINGSPEED_DEGREES_PER_SECOND = 600.0
private val MAXTRANSLATIONSPEED_FEET_PER_SECOND = 15.0
private var prevHeadingError = 0.0.degrees
interface SwerveDrive {
val parameters: SwerveParameters
var heading: Angle
val headingRate: AngularVelocity
var position: Vector2
var velocity: Vector2
var robotPivot: Vector2 // location of rotational pivot in robot coordinates
var headingSetpoint: Angle
val modules: Array<Module>
fun startFollowing() = Unit
fun stopFollowing() = Unit
interface Module {
// module fixed parameters
val modulePosition: Vector2 // coordinates of module in robot coordinates
val angleOffset: Angle
// encoder interface
val angle: Angle
val speed: Double
val currDistance: Double
var prevDistance: Double
// motor interface
var angleSetpoint: Angle
fun setDrivePower(power: Double)
fun stop()
fun zeroEncoder()
fun driveWithDistance(angle: Angle, distance: Length)
}
companion object {
var prevTranslationInput = Vector2(0.0,0.0)
var prevTurn = 0.0
}
data class Pose(val position: Vector2, val heading: Angle) : Interpolable<Pose> {
override fun interpolate(other: Pose, x: Double): Pose = when {
x <= 0.0 -> this
x >= 1.0 -> other
else -> Pose(position.interpolate(other.position, x), (other.heading - heading) * x + heading)
}
}
}
val SwerveDrive.pose: SwerveDrive.Pose
get() = SwerveDrive.Pose(position, heading)
fun SwerveDrive.lookupPose(time: Double): SwerveDrive.Pose = poseHistory.getInterpolated(InterpolatingDouble(time))
fun SwerveDrive.stop() {
for (module in modules) {
module.stop()
}
}
fun SwerveDrive.zeroEncoders() {
for (module in modules) {
module.zeroEncoder()
}
position = Vector2(0.0, 0.0)
}
fun SwerveDrive.drive(
translation: Vector2,
turn: Double,
fieldCentric: Boolean = true,
teleopClosedLoopHeading: Boolean = false,
softTranslation: Vector2 = Vector2(0.0, 0.0),
softTurn: Double = 0.0,
maxChangeInOneFrame: Double = 0.0)
{
recordOdometry()
var requestedTranslation = translation
if (fieldCentric) {
requestedTranslation = requestedTranslation.rotateDegrees(heading.asDegrees)
}
requestedTranslation += softTranslation
var requestedTurn = turn + softTurn
if (requestedTranslation.length > 0.01 && requestedTurn.absoluteValue < 0.01) {
if (teleopClosedLoopHeading) { // closed loop on heading position
// heading error
val headingError = (headingSetpoint - heading).wrap()
//println("Heading Error: $headingError.")
// heading d
val deltaHeadingError = headingError - prevHeadingError
prevHeadingError = headingError
requestedTurn = headingError.asDegrees * parameters.kpHeading * 0.60 + deltaHeadingError.asDegrees * parameters.kdHeading
} else if (parameters.gyroRateCorrection > 0.0) { // closed loop on heading velocity
requestedTurn += (requestedTurn * MAXHEADINGSPEED_DEGREES_PER_SECOND - headingRate.changePerSecond.asDegrees) * parameters.gyroRateCorrection
}
} else {
headingSetpoint = heading
}
if (requestedTranslation.x == 0.0 && requestedTranslation.y == 0.0 && requestedTurn == 0.0) {
return stop()
}
val requestedLocalGoals = Array(modules.size) { Vector2(0.0, 0.0) }
for (i in modules.indices) {
requestedLocalGoals[i] = requestedTranslation + (modules[i].modulePosition - robotPivot).perpendicular().normalize() * requestedTurn
}
val speeds = Array(modules.size) { 0.0 }
// the beginning of Bryce's idea of how to drive more smoothly, but maintain responsiveness
// directional and rotational interpolation from robot state towards joystick request
if (maxChangeInOneFrame > 0.0) {
val normalizedRobotDirection = velocity.rotateDegrees(heading.asDegrees) / MAXTRANSLATIONSPEED_FEET_PER_SECOND
val translateDelta = requestedTranslation - normalizedRobotDirection
val length1 = min(translateDelta.length, maxChangeInOneFrame)
val interpolatedTranslation = normalizedRobotDirection + translateDelta.normalize() * length1
val normalizedTurnRate = headingRate.changePerSecond.asDegrees / MAXHEADINGSPEED_DEGREES_PER_SECOND
val turnDelta = requestedTurn - normalizedTurnRate
val length2 = min(turnDelta.absoluteValue, maxChangeInOneFrame)
val interpolatedTurn = normalizedTurnRate + turnDelta.sign * length2
for (i in modules.indices) {
val interpolatedLocalGoal = interpolatedTranslation + (modules[i].modulePosition - robotPivot).perpendicular().normalize() * interpolatedTurn
if (i==0) {
print("ilg=$interpolatedLocalGoal")
}
if (interpolatedLocalGoal.length>0.001) {
val bHat = interpolatedLocalGoal.normalize()
val projectedLocalGoal = bHat * requestedLocalGoals[i].dot(bHat)
if (i==0) {
print(" plg=$projectedLocalGoal")
}
val angleAndSpeed = modules[i].calculateAngleAndSpeed(projectedLocalGoal)
if (angleAndSpeed.status) {
modules[i].angleSetpoint = angleAndSpeed.angle
speeds[i] = angleAndSpeed.power
if (i==0) {
print(" aas=$angleAndSpeed")
}
} else {
speeds[i] = 0.0
}
} else {
speeds[i] = 0.0
}
println()
}
}
else {
for (i in modules.indices) {
val angleAndSpeed = modules[i].calculateAngleAndSpeed(requestedLocalGoals[i])
if (angleAndSpeed.status) {
modules[i].angleSetpoint = angleAndSpeed.angle
speeds[i] = angleAndSpeed.power
} else {
speeds[i] = 0.0
}
}
}
val maxSpeed = speeds.maxByOrNull(Math::abs)!!
if (maxSpeed > 1.0) {
for (i in speeds.indices) {
speeds[i] /= maxSpeed
}
}
for (i in modules.indices) {
//print("${modules[i].currDistance} ")
modules[i].setDrivePower(speeds[i])
}
//println()
}
data class AnglePowerAndStatus(val angle: Angle, val power: Double, val status: Boolean)
private fun SwerveDrive.Module.calculateAngleAndSpeed(localGoal : Vector2) : AnglePowerAndStatus {
var angle = 0.0.degrees
var power = localGoal.length
var status = false
if ( power.absoluteValue < 0.01 ) {
// var temp = localGoal.angle.radians
// println("setPoint=$temp")
status = false
}
else {
angle = localGoal.angle.radians
val angleError = (angle - this.angle).wrap()
if (Math.abs(angleError.asRadians) > Math.PI / 2.0) {
angle -= Math.PI.radians
power = -power
}
power *= Math.abs(angleError.cos())
status = true
}
return AnglePowerAndStatus(angle, power, status)
}
suspend fun SwerveDrive.Module.steerToAngle(angle: Angle, tolerance: Angle = 2.degrees) {
try {
periodic(watchOverrun = false) {
angleSetpoint = angle
val error = (angle - [email protected]).wrap()
if (error.asRadians.absoluteValue < tolerance.asRadians) stop()
}
delay(0.2)
} finally {
stop()
}
}
fun SwerveDrive.Module.recordOdometry(heading: Angle): Vector2 {
val angleInFieldSpace = heading + angle
val deltaDistance = currDistance - prevDistance
prevDistance = currDistance
return Vector2(
deltaDistance * sin(angleInFieldSpace.asRadians),
deltaDistance * cos(angleInFieldSpace.asRadians)
)
}
fun SwerveDrive.recordOdometry() {
var translation = Vector2(0.0, 0.0)
val translations: Array<Vector2> = Array(modules.size) { Vector2(0.0, 0.0) }
for (i in 0 until modules.size) {
translations[i] = modules[i].recordOdometry(heading)
}
for (i in 0 until modules.size) {
translation += translations[i]
}
translation /= modules.size.toDouble()
position += translation
val time = Timer.getFPGATimestamp()
val deltaTime = time - prevTime
velocity = (position - prevPosition) / deltaTime
poseHistory[InterpolatingDouble(time)] = pose
prevTime = time
prevPosition = position
// println("Position: $position")
}
fun SwerveDrive.resetOdometry() {
for (module in modules) {
module.prevDistance = 0.0
}
zeroEncoders()
position = Vector2(0.0, 0.0)
}
fun SwerveDrive.resetHeading() {
heading = ((0.0).degrees)
}
suspend fun SwerveDrive.driveAlongPath(
path: Path2D,
resetOdometry: Boolean = false,
extraTime: Double = 0.0,
inResetGyro: Boolean? = null,
earlyExit: () -> Boolean = {false}
) {
var resetGyro : Boolean = false
println("Driving along path ${path.name}, duration: ${path.durationWithSpeed}, travel direction: ${path.robotDirection}, mirrored: ${path.isMirrored}")
if (inResetGyro == null) {
// default to resetOdometry for backward compatibility
resetGyro = resetOdometry
} else {
resetGyro = inResetGyro
}
if (resetGyro) {
println("Heading = $heading")
resetHeading()
heading = path.headingCurve.getValue(0.0).degrees
if(parameters.alignRobotToPath) {
heading += path.getTangent(0.0).angle.degrees
println("path tangent = ${path.getTangent(0.0).angle.degrees}")
}
println("After Reset Heading = $heading")
}
if (resetOdometry) {
println("Position = $position")
resetOdometry()
// set to the numbers required for the start of the path
position = path.getPosition(0.0)
println("After Reset Position = $position")
}
var prevTime = 0.0
val timer = Timer()
timer.start()
prevPathPosition = path.getPosition(0.0)
prevPathHeading = path.getAbsoluteHeadingDegreesAt(0.0, parameters.alignRobotToPath).degrees
var prevPositionError = Vector2(0.0, 0.0)
prevHeadingError = 0.0.degrees
val table = NetworkTableInstance.getDefault().getTable("driveTable")
val outputEntry = table.getEntry("Output")
periodic {
val t = timer.get()
val dt = t - prevTime
// position error
val pathPosition = path.getPosition(t)
val positionError = pathPosition - position
//println("time=$t pathPosition=$pathPosition position=$position positionError=$positionError")
// position feed forward
val pathVelocity = (pathPosition - prevPathPosition) / dt
prevPathPosition = pathPosition
// position d
val deltaPositionError = positionError - prevPositionError
prevPositionError = positionError
val translationControlField =
pathVelocity * parameters.kPositionFeedForward + positionError * parameters.kpPosition + deltaPositionError * parameters.kdPosition
// heading error
val robotHeading = heading
val pathHeading = path.getAbsoluteHeadingDegreesAt(t, parameters.alignRobotToPath).degrees
val headingError = (pathHeading - robotHeading).wrap()
//println("Heading Error: $headingError. Hi. %%%%%%%%%%%%%%%%%%%%%%%%%%")
// heading feed forward
val headingVelocity = (pathHeading.asDegrees - prevPathHeading.asDegrees) / dt
prevPathHeading = pathHeading
// heading d
val deltaHeadingError = headingError - prevHeadingError
prevHeadingError = headingError
val turnControl = headingVelocity * parameters.kHeadingFeedForward + headingError.asDegrees * parameters.kpHeading + deltaHeadingError.asDegrees * parameters.kdHeading
outputEntry.setDouble(translationControlField.length.coerceAtMost(1.5))
// print("stuff maybe happening")
// send it
drive(translationControlField, turnControl, true)
// are we done yet?
if (t >= path.durationWithSpeed + extraTime || earlyExit())
stop()
prevTime = t
// println("Time=$t Path Position=$pathPosition Position=$position")
// println("DT$dt Path Velocity = $pathVelocity Velocity = $velocity")
}
// shut it down
drive(Vector2(0.0, 0.0), 0.0, true)
}
suspend fun SwerveDrive.driveAlongPathWithStrafe(
path: Path2D,
resetOdometry: Boolean = false,
extraTime: Double = 0.0,
strafeAlpha: (time: Double) -> Double,
getStrafe: () -> Double,
earlyExit: () -> Boolean
) {
println("Driving along path ${path.name}, duration: ${path.durationWithSpeed}, travel direction: ${path.robotDirection}, mirrored: ${path.isMirrored}")
if (resetOdometry) {
println("Position = $position Heading = $heading")
resetOdometry()
resetHeading()
// set to the numbers required for the start of the path
position = path.getPosition(0.0)
heading = path.getTangent(0.0).angle.degrees + path.headingCurve.getValue(0.0).degrees
println("After Reset Position = $position Heading = $heading")
}
var prevTime = 0.0
val timer = Timer()
timer.start()
prevPathPosition = path.getPosition(0.0)
prevPathHeading = path.getAbsoluteHeadingDegreesAt(0.0, parameters.alignRobotToPath).degrees
periodic {
val t = timer.get()
val dt = t - prevTime
// position error
val pathPosition = path.getPosition(t)
val positionError = pathPosition - position
//println("pathPosition=$pathPosition position=$position positionError=$positionError")
// position feed forward
val pathVelocity = (pathPosition - prevPathPosition) / dt
prevPathPosition = pathPosition
val translationControlField =
pathVelocity * parameters.kPositionFeedForward + positionError * parameters.kpPosition
// heading error
val robotHeading = heading
val pathHeading = path.getAbsoluteHeadingDegreesAt(t, parameters.alignRobotToPath).degrees
val headingError = (pathHeading - robotHeading).wrap()
// heading feed forward
val headingVelocity = (pathHeading.asDegrees - prevPathHeading.asDegrees) / dt
prevPathHeading = pathHeading
var turnControl =
headingVelocity * parameters.kHeadingFeedForward + headingError.asDegrees * parameters.kpHeading
val heading = (heading + (headingRate * parameters.gyroRateCorrection).changePerSecond).wrap()
var translationControlRobot = translationControlField.rotateDegrees(heading.asDegrees)
val alpha = strafeAlpha(t)
if (alpha > 0.0) {
translationControlRobot.x = translationControlRobot.x * (1.0 - alpha) + getStrafe() * alpha
turnControl = 0.0
}
// send it
drive(translationControlRobot, turnControl, false)
// are we done yet?
if (t >= path.durationWithSpeed + extraTime)
stop()
if (earlyExit()) {
stop()
}
prevTime = t
// println("Time=$t Path Position=$pathPosition Position=$position")
// println("DT$dt Path Velocity = $pathVelocity Velocity = $velocity")
}
// shut it down
drive(Vector2(0.0, 0.0), 0.0, true)
}
suspend fun SwerveDrive.tuneDrivePositionController(controller: org.team2471.frc.lib.input.XboxController) {
var prevX = 0.0
var prevY = 0.0
var prevTime = 0.0
var prevPositionError = Vector2(0.0, 0.0)
var prevHeadingError = 0.0.degrees
val timer = Timer().apply { start() }
var angleErrorAccum = 0.0.degrees
try {
resetOdometry()
resetHeading()
periodic {
val t = timer.get()
val dt = t - prevTime
val x = controller.leftThumbstickX
val y = controller.leftThumbstickY
val turn = 75.0*controller.rightThumbstickX
// position error
val pathPosition = Vector2(x, y)
val positionError = pathPosition - position
// position d
val deltaPositionError = positionError - prevPositionError
prevPositionError = positionError
val translationControlField = positionError * parameters.kpPosition + deltaPositionError * parameters.kdPosition
// heading error
val robotHeading = heading.asDegrees
val pathHeading = turn.degrees
val headingError = (pathHeading - robotHeading.degrees).wrap()
// println("Heading Error: $headingError. Hi.")
// heading d
val deltaHeadingError = headingError - prevHeadingError
prevHeadingError = headingError
val turnControl = headingError.asDegrees * parameters.kpHeading + deltaHeadingError.asDegrees * parameters.kdHeading
println("Error ${headingError.asDegrees}, setpoint ${pathHeading}, current pos $robotHeading")
drive(translationControlField, turnControl, true)
prevTime = t
}
} finally {
stop()
}
} | unlicense | fa14017de925ced756bce7cfb1ac482c | 32.938889 | 175 | 0.645586 | 4.131199 | false | false | false | false |
lcmatrix/betting-game | src/main/kotlin/de/bettinggame/domain/Location.kt | 1 | 1708 | package de.bettinggame.domain
import org.springframework.data.repository.CrudRepository
import javax.persistence.*
import javax.validation.constraints.NotNull
/**
* Location class.
*/
@Entity
class Location(identifier: String,
/**
* Short unique key.
*/
@NotNull
@Column(name = "short_key")
val key: String,
/**
* Name of the arena.
*/
@NotNull
@Embedded
@AttributeOverrides(
AttributeOverride(name = "de", column = Column(name = "name_de")),
AttributeOverride(name = "en", column = Column(name = "name_en"))
)
val name: Multilingual,
/**
* City of the arena.
*/
@NotNull
@Embedded
@AttributeOverrides(
AttributeOverride(name = "de", column = Column(name = "city_de")),
AttributeOverride(name = "en", column = Column(name = "city_en"))
)
val city: Multilingual,
/**
* Country of the arena.
*/
@NotNull
@Embedded
@AttributeOverrides(
AttributeOverride(name = "de", column = Column(name = "country_de")),
AttributeOverride(name = "en", column = Column(name = "country_en"))
)
val country: Multilingual
) : AbstractIdentifiableEntity(identifier)
interface LocationRepository : CrudRepository<Location, Int>
| apache-2.0 | f5da7fa5fdbf03170b18b9db199444b9 | 31.226415 | 92 | 0.471897 | 5.422222 | false | false | false | false |
Andreyv1989/KotlinLessons | src/iv_properties/_33_LazyProperty.kt | 1 | 691 | package iv_properties
import util.TODO
class LazyProperty(val initializer: () -> Int) {
val lazy: Int
get() = lazyValue!!
private val lazyValue: Int? = null
get() {
if (field == null) field = initializer()
return field
}
}
fun todoTask33(): Nothing = TODO(
"""
Task 33.
Add a custom getter to make the 'lazy' val really lazy.
It should be initialized by the invocation of 'initializer()'
at the moment of the first access.
You can add as many additional properties as you need.
Do not use delegated properties!
""",
references = { LazyProperty({ 42 }).lazy }
)
| mit | dec50de5bd5421c1ca4a4d6309668684 | 23.678571 | 69 | 0.583213 | 4.546053 | false | false | false | false |
pyamsoft/pydroid | ui/src/main/java/com/pyamsoft/pydroid/ui/internal/app/ComposeTheme.kt | 1 | 1818 | /*
* Copyright 2022 Peter Kenji Yamanaka
*
* 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.pyamsoft.pydroid.ui.internal.app
import android.app.Activity
import androidx.compose.runtime.Composable
import com.pyamsoft.pydroid.ui.app.ComposeThemeProvider
import com.pyamsoft.pydroid.ui.app.invoke
import com.pyamsoft.pydroid.ui.theme.Theming
import com.pyamsoft.pydroid.ui.theme.asThemeProvider
/** Alias for a theme type */
internal fun interface ComposeTheme {
/** Renders content() with the provided compose theme */
@Composable
fun Render(
activity: Activity,
content: @Composable () -> Unit,
)
}
/** Convenience method for rendering a theme provider */
@Composable
internal operator fun ComposeTheme.invoke(
activity: Activity,
content: @Composable () -> Unit,
) {
val self = this
self.Render(activity, content)
}
/** Generates a ComposeTheme */
internal class ComposeThemeFactory(
private val theming: Theming,
private val themeProvider: ComposeThemeProvider,
) : ComposeTheme {
@Composable
override fun Render(activity: Activity, content: @Composable () -> Unit) {
val provider = activity.asThemeProvider(theming)
themeProvider(
activity = activity,
themeProvider = provider,
content = content,
)
}
}
| apache-2.0 | 91d8118b93c3c1377a6b4bd9cc29c766 | 28.322581 | 76 | 0.729923 | 4.218097 | false | false | false | false |
wordpress-mobile/WordPress-Android | WordPress/src/main/java/org/wordpress/android/ui/mysite/cards/quicklinksribbon/QuickLinkRibbonItemAdapter.kt | 1 | 2006 | package org.wordpress.android.ui.mysite.cards.quicklinksribbon
import android.view.ViewGroup
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.DiffUtil.Callback
import androidx.recyclerview.widget.RecyclerView.Adapter
import org.wordpress.android.ui.mysite.MySiteCardAndItem.Card.QuickLinkRibbon.QuickLinkRibbonItem
class QuickLinkRibbonItemAdapter : Adapter<QuickLinkRibbonItemViewHolder>() {
private val items = mutableListOf<QuickLinkRibbonItem>()
override fun onCreateViewHolder(
parent: ViewGroup,
viewType: Int
): QuickLinkRibbonItemViewHolder {
return QuickLinkRibbonItemViewHolder(parent)
}
override fun getItemCount(): Int = items.size
override fun onBindViewHolder(holder: QuickLinkRibbonItemViewHolder, position: Int) {
holder.onBind(items[position])
}
fun update(newItems: List<QuickLinkRibbonItem>) {
val diffResult = DiffUtil.calculateDiff(InterestDiffUtil(items, newItems))
items.clear()
items.addAll(newItems)
diffResult.dispatchUpdatesTo(this)
}
class InterestDiffUtil(
private val oldList: List<QuickLinkRibbonItem>,
private val newList: List<QuickLinkRibbonItem>
) : Callback() {
override fun areItemsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean {
val newItem = newList[newItemPosition]
val oldItem = oldList[oldItemPosition]
return (oldItem == newItem)
}
override fun getOldListSize(): Int = oldList.size
override fun getNewListSize(): Int = newList.size
override fun areContentsTheSame(
oldItemPosition: Int,
newItemPosition: Int
): Boolean {
return if (oldList[oldItemPosition].showFocusPoint || newList[newItemPosition].showFocusPoint) {
false
} else {
oldList[oldItemPosition] == newList[newItemPosition]
}
}
}
}
| gpl-2.0 | 17093276494eb7de89ace5e5bf6dffcc | 34.192982 | 108 | 0.691924 | 5.196891 | false | false | false | false |
wordpress-mobile/WordPress-Android | WordPress/src/main/java/org/wordpress/android/ui/prefs/language/LocalePickerViewModel.kt | 1 | 5737 | package org.wordpress.android.ui.prefs.language
import androidx.lifecycle.LiveData
import androidx.lifecycle.MediatorLiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.Transformations
import androidx.lifecycle.ViewModel
import androidx.lifecycle.distinctUntilChanged
import org.wordpress.android.R.array
import org.wordpress.android.ui.prefs.language.LocalePickerListItem.ClickAction
import org.wordpress.android.ui.prefs.language.LocalePickerListItem.LocaleRow
import org.wordpress.android.util.LocaleProvider
import org.wordpress.android.util.merge
import org.wordpress.android.viewmodel.ResourceProvider
import org.wordpress.android.viewmodel.SingleLiveEvent
import javax.inject.Inject
class LocalePickerViewModel @Inject constructor(
private val resourceProvider: ResourceProvider,
private val localeProvider: LocaleProvider
) : ViewModel() {
private val cachedLocales = mutableListOf<LocalePickerListItem>()
private val _expandBottomSheet = SingleLiveEvent<Unit>()
val expandBottomSheet: LiveData<Unit> = _expandBottomSheet
private val _hideKeyboard = SingleLiveEvent<Unit>()
val hideKeyboard: LiveData<Unit> = _hideKeyboard
private val _clearSearchField = SingleLiveEvent<Unit>()
val clearSearchField: LiveData<Unit> = _clearSearchField
private val _dismissBottomSheet = SingleLiveEvent<Unit>()
val dismissBottomSheet: LiveData<Unit> = _dismissBottomSheet
private val _isEmptyViewVisible = SingleLiveEvent<Boolean>()
private val _suggestedLocale = MutableLiveData<CurrentLocale>()
private val _selectedLocale = SingleLiveEvent<String>()
val selectedLocale = _selectedLocale
private val _loadedLocales = MutableLiveData<List<LocalePickerListItem>>()
private val searchInput = MutableLiveData<String>()
private val _filteredLocales: LiveData<List<LocalePickerListItem>> =
Transformations.switchMap(searchInput) { term ->
filterLocales(term)
}
private val locales = MediatorLiveData<List<LocalePickerListItem>>().apply {
addSource(_loadedLocales) {
value = it
}
addSource(_filteredLocales) {
value = it
}
}.distinctUntilChanged()
val uiState: LiveData<LocalePickerUiState> = merge(
locales,
_suggestedLocale,
_isEmptyViewVisible
) { locales, suggestedLocale, emptyViewVisible ->
LocalePickerUiState(
locales,
suggestedLocale,
emptyViewVisible ?: false
)
}
private var started = false
fun start() {
if (started) {
return
}
started = true
loadLocales()
}
fun onSearchQueryChanged(query: CharSequence?) {
if (query.isNullOrBlank()) {
clearSearch()
} else {
searchInput.value = query.toString()
}
}
fun onCurrentLocaleSelected() {
val localeCode = _suggestedLocale.value?.localeCode
localeCode?.let {
clickItem(localeCode)
}
}
fun onListScrolled() {
_hideKeyboard.call()
}
fun onSearchFieldFocused() {
_expandBottomSheet.call()
}
fun onClearSearchFieldButtonClicked() {
clearSearch()
_hideKeyboard.call()
_clearSearchField.call()
}
private fun clickItem(localeCode: String) {
_selectedLocale.postValue(localeCode)
_dismissBottomSheet.asyncCall()
}
private fun clearSearch() {
_isEmptyViewVisible.value = false
_loadedLocales.postValue(cachedLocales)
}
private fun filterLocales(query: String): LiveData<List<LocalePickerListItem>> {
val filteredLocales = MutableLiveData<List<LocalePickerListItem>>()
cachedLocales.filter { locale ->
when (locale) {
is LocaleRow -> {
query.isBlank() or locale.label.contains(query, true) or locale.localizedLabel.contains(
query,
true
)
}
}
}.also {
_isEmptyViewVisible.value = it.isEmpty()
filteredLocales.value = it
}
return filteredLocales
}
private fun loadLocales() {
val appLocale = localeProvider.getAppLocale()
val displayLabel = localeProvider.getAppLanguageDisplayString()
_suggestedLocale.postValue(CurrentLocale(displayLabel, appLocale.toString()))
val availableLocales = resourceProvider.getStringArray(array.available_languages).distinct()
val availableLocalesData = localeProvider.createSortedLocalizedLanguageDisplayStrings(
availableLocales.toTypedArray(),
appLocale
) ?: return
val sortedEntries = availableLocalesData.first
val sortedValues = availableLocalesData.second
val sortedLocalizedEntries = availableLocalesData.third
for (i in availableLocalesData.first.indices) {
cachedLocales.add(
LocaleRow(
sortedEntries[i],
sortedLocalizedEntries[i],
sortedValues[i],
ClickAction(sortedValues[i], this::clickItem)
)
)
}
_loadedLocales.postValue(cachedLocales)
}
data class CurrentLocale(
val label: String,
val localeCode: String
)
data class LocalePickerUiState(
val listData: List<LocalePickerListItem>?,
val currentLocale: CurrentLocale?,
val isEmptyViewVisible: Boolean
)
}
| gpl-2.0 | ea86a85a3df5a288b0a2947e335fd4fb | 30.521978 | 108 | 0.648248 | 5.268136 | false | false | false | false |
LittleLightCz/SheepsGoHome | android/src/com/tumblr/svetylk0/sheepsgohome/android/libgdxbridge/GoogleLeaderboardBridge.kt | 1 | 4362 | package com.tumblr.svetylk0.sheepsgohome.android.libgdxbridge
import android.app.Activity
import android.os.Bundle
import com.google.android.gms.common.api.GoogleApiClient
import com.google.android.gms.common.api.GoogleApiClient.ConnectionCallbacks
import com.google.android.gms.common.api.PendingResult
import com.google.android.gms.games.Games
import com.google.android.gms.games.leaderboard.LeaderboardVariant
import com.google.android.gms.games.leaderboard.Leaderboards.LoadPlayerScoreResult
import com.google.android.gms.games.leaderboard.Leaderboards.LoadScoresResult
import com.sheepsgohome.google.GoogleLeaderboard
import com.sheepsgohome.google.leaderboard.GoogleConnectionCallback
import com.sheepsgohome.leaderboard.LeaderBoardResult
import com.sheepsgohome.leaderboard.LeaderBoardRow
import com.sheepsgohome.shared.GameData
class GoogleLeaderboardBridge(activity: Activity) : GoogleLeaderboard, ConnectionCallbacks {
companion object {
val REQUEST_RESOLVE_CONNECTION_ISSUE = 0
}
private val CLASSIC_MODE_LEADERBOARD_ID = "CgkIzpjQtpcDEAIQAQ"
private var callback: GoogleConnectionCallback? = null
private var pendingResult: PendingResult<LoadScoresResult>? = null
private val client = GoogleApiClient.Builder(activity)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener { result ->
if (result.hasResolution()) {
result.startResolutionForResult(activity, REQUEST_RESOLVE_CONNECTION_ISSUE)
} else {
callback?.onConnectionFailure()
}
}
.addApi(Games.API)
.addScope(Games.SCOPE_GAMES)
.build()
override val isConnected: Boolean
get() = client.isConnected
override fun connect() {
client.connect()
}
override fun cancelPendingResult() {
pendingResult?.cancel()
}
override fun registerConnectionCallback(callback: GoogleConnectionCallback) {
this.callback = callback
}
fun onActivityResult(requestCode: Int, resultCode: Int) {
when(requestCode) {
REQUEST_RESOLVE_CONNECTION_ISSUE -> {
when(resultCode) {
Activity.RESULT_OK -> {
//reconnect
client.connect()
}
else -> onConnectionSuspended(resultCode)
}
}
}
}
override fun onConnected(bundle: Bundle?) {
callback?.onConnected()
}
override fun onConnectionSuspended(code: Int) {
callback?.onConnectionFailure()
}
override fun fetchLeaderboardData(onResultAction: (LeaderBoardResult) -> Unit) {
//Submit score first
Games.Leaderboards.submitScoreImmediate(
client,
CLASSIC_MODE_LEADERBOARD_ID,
GameData.LEVEL.toLong(),
""
).setResultCallback {
//load my own score/leaderboard rank
Games.Leaderboards.loadCurrentPlayerLeaderboardScore(client,
CLASSIC_MODE_LEADERBOARD_ID,
LeaderboardVariant.TIME_SPAN_ALL_TIME,
LeaderboardVariant.COLLECTION_PUBLIC
).setResultCallback { myGoogleResult: LoadPlayerScoreResult? ->
//then fetch the leaderboard page
pendingResult = Games.Leaderboards.loadPlayerCenteredScores(
client,
CLASSIC_MODE_LEADERBOARD_ID,
LeaderboardVariant.TIME_SPAN_ALL_TIME,
LeaderboardVariant.COLLECTION_PUBLIC,
25,
true
).apply {
setResultCallback { scoresResult ->
val scores = scoresResult.scores.map {
score -> LeaderBoardRow(score.rank, score.scoreHolderDisplayName, score.rawScore)
}
val myResult = myGoogleResult?.score?.let {
LeaderBoardRow(it.rank, it.scoreHolderDisplayName, it.rawScore)
}
onResultAction(LeaderBoardResult(myResult, scores))
}
}
}
}
}
} | gpl-3.0 | d1f3b32dcab5ba06e3415978a5c6a522 | 35.358333 | 109 | 0.610271 | 5.217703 | false | false | false | false |
mdaniel/intellij-community | platform/build-scripts/groovy/org/jetbrains/intellij/build/impl/BuildContextImpl.kt | 1 | 14822 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
@file:Suppress("ReplaceJavaStaticMethodWithKotlinAnalog")
package org.jetbrains.intellij.build.impl
import com.intellij.openapi.util.io.FileUtilRt
import com.intellij.openapi.util.text.Strings
import io.opentelemetry.api.common.AttributeKey
import io.opentelemetry.api.common.Attributes
import io.opentelemetry.api.trace.Span
import kotlinx.collections.immutable.persistentListOf
import kotlinx.collections.immutable.toImmutableList
import org.jetbrains.intellij.build.*
import org.jetbrains.intellij.build.dependencies.BuildDependenciesCommunityRoot
import org.jetbrains.jps.model.JpsModel
import org.jetbrains.jps.model.JpsProject
import org.jetbrains.jps.model.java.JavaModuleSourceRootTypes
import org.jetbrains.jps.model.java.JavaResourceRootProperties
import org.jetbrains.jps.model.java.JavaSourceRootProperties
import org.jetbrains.jps.model.module.JpsModule
import org.jetbrains.jps.model.module.JpsModuleSourceRoot
import org.jetbrains.jps.util.JpsPathUtil
import java.nio.file.Files
import java.nio.file.Path
import java.util.concurrent.ConcurrentLinkedQueue
class BuildContextImpl private constructor(private val compilationContext: CompilationContextImpl,
override val productProperties: ProductProperties,
override val windowsDistributionCustomizer: WindowsDistributionCustomizer?,
override val linuxDistributionCustomizer: LinuxDistributionCustomizer?,
override val macDistributionCustomizer: MacDistributionCustomizer?,
override val proprietaryBuildTools: ProprietaryBuildTools = ProprietaryBuildTools.DUMMY,
private val distFiles: ConcurrentLinkedQueue<Map.Entry<Path, String>>) : BuildContext {
override val fullBuildNumber: String
get() = "${applicationInfo.productCode}-$buildNumber"
override val systemSelector: String
get() = productProperties.getSystemSelector(applicationInfo, buildNumber)
override val buildNumber: String = options.buildNumber ?: readSnapshotBuildNumber(paths.communityHomeDir)
override val xBootClassPathJarNames: List<String>
get() = productProperties.xBootClassPathJarNames
override var bootClassPathJarNames = persistentListOf("util.jar", "util_rt.jar")
override val applicationInfo: ApplicationInfoProperties = ApplicationInfoPropertiesImpl(project, productProperties, options).patch(this)
private var builtinModulesData: BuiltinModulesFileData? = null
init {
@Suppress("DEPRECATION")
if (productProperties.productCode == null) {
productProperties.productCode = applicationInfo.productCode
}
check(!systemSelector.contains(' ')) {
"System selector must not contain spaces: $systemSelector"
}
options.buildStepsToSkip.addAll(productProperties.incompatibleBuildSteps)
if (!options.buildStepsToSkip.isEmpty()) {
Span.current().addEvent("build steps to be skipped", Attributes.of(
AttributeKey.stringArrayKey("stepsToSkip"), options.buildStepsToSkip.toImmutableList()
))
}
configureProjectorPlugin(productProperties)
}
companion object {
@JvmStatic
@JvmOverloads
fun createContext(communityHome: BuildDependenciesCommunityRoot,
projectHome: Path,
productProperties: ProductProperties,
proprietaryBuildTools: ProprietaryBuildTools = ProprietaryBuildTools.DUMMY,
options: BuildOptions = BuildOptions()): BuildContextImpl {
val projectHomeAsString = FileUtilRt.toSystemIndependentName(projectHome.toString())
val windowsDistributionCustomizer = productProperties.createWindowsCustomizer(projectHomeAsString)
val linuxDistributionCustomizer = productProperties.createLinuxCustomizer(projectHomeAsString)
val macDistributionCustomizer = productProperties.createMacCustomizer(projectHomeAsString)
val compilationContext = CompilationContextImpl.create(
communityHome = communityHome,
projectHome = projectHome,
buildOutputRootEvaluator = createBuildOutputRootEvaluator(projectHome, productProperties, options),
options = options
)
return BuildContextImpl(compilationContext = compilationContext,
productProperties = productProperties,
windowsDistributionCustomizer = windowsDistributionCustomizer,
linuxDistributionCustomizer = linuxDistributionCustomizer,
macDistributionCustomizer = macDistributionCustomizer,
proprietaryBuildTools = proprietaryBuildTools,
distFiles = ConcurrentLinkedQueue())
}
}
override var builtinModule: BuiltinModulesFileData?
get() {
if (options.buildStepsToSkip.contains(BuildOptions.PROVIDED_MODULES_LIST_STEP)) {
return null
}
return builtinModulesData ?: throw IllegalStateException("builtinModulesData is not set. " +
"Make sure `BuildTasksImpl.buildProvidedModuleList` was called before")
}
set(value) {
check(builtinModulesData == null) { "builtinModulesData was already set" }
builtinModulesData = value
}
override fun addDistFile(file: Map.Entry<Path, String>) {
messages.debug("$file requested to be added to app resources")
distFiles.add(file)
}
override fun getDistFiles(): Collection<Map.Entry<Path, String>> {
return java.util.List.copyOf(distFiles)
}
override fun findApplicationInfoModule(): JpsModule {
return findRequiredModule(productProperties.applicationInfoModule)
}
override val options: BuildOptions
get() = compilationContext.options
@Suppress("SSBasedInspection")
override val messages: BuildMessages
get() = compilationContext.messages
override val dependenciesProperties: DependenciesProperties
get() = compilationContext.dependenciesProperties
override val paths: BuildPaths
get() = compilationContext.paths
override val bundledRuntime: BundledRuntime
get() = compilationContext.bundledRuntime
override val project: JpsProject
get() = compilationContext.project
override val projectModel: JpsModel
get() = compilationContext.projectModel
override val compilationData: JpsCompilationData
get() = compilationContext.compilationData
override val stableJavaExecutable: Path
get() = compilationContext.stableJavaExecutable
override val stableJdkHome: Path
get() = compilationContext.stableJdkHome
override val projectOutputDirectory: Path
get() = compilationContext.projectOutputDirectory
override fun findRequiredModule(name: String): JpsModule {
return compilationContext.findRequiredModule(name)
}
override fun findModule(name: String): JpsModule? {
return compilationContext.findModule(name)
}
override fun getOldModuleName(newName: String): String? {
return compilationContext.getOldModuleName(newName)
}
override fun getModuleOutputDir(module: JpsModule): Path {
return compilationContext.getModuleOutputDir(module)
}
override fun getModuleTestsOutputPath(module: JpsModule): String {
return compilationContext.getModuleTestsOutputPath(module)
}
override fun getModuleRuntimeClasspath(module: JpsModule, forTests: Boolean): List<String> {
return compilationContext.getModuleRuntimeClasspath(module, forTests)
}
override fun notifyArtifactBuilt(artifactPath: Path) {
compilationContext.notifyArtifactWasBuilt(artifactPath)
}
override fun notifyArtifactWasBuilt(artifactPath: Path) {
compilationContext.notifyArtifactWasBuilt(artifactPath)
}
override fun findFileInModuleSources(moduleName: String, relativePath: String): Path? {
for (info in getSourceRootsWithPrefixes(findRequiredModule(moduleName))) {
if (relativePath.startsWith(info.second)) {
val result = info.first.resolve(Strings.trimStart(Strings.trimStart(relativePath, info.second), "/"))
if (Files.exists(result)) {
return result
}
}
}
return null
}
override fun signFiles(files: List<Path>, options: Map<String, String>) {
if (proprietaryBuildTools.signTool == null) {
Span.current().addEvent("files won't be signed", Attributes.of(
AttributeKey.stringArrayKey("files"), files.map(Path::toString),
AttributeKey.stringKey("reason"), "sign tool isn't defined")
)
}
else {
proprietaryBuildTools.signTool.signFiles(files, this, options)
}
}
override fun executeStep(stepMessage: String, stepId: String, step: Runnable): Boolean {
if (options.buildStepsToSkip.contains(stepId)) {
Span.current().addEvent("skip step", Attributes.of(AttributeKey.stringKey("name"), stepMessage))
}
else {
messages.block(stepMessage, step::run)
}
return true
}
override fun shouldBuildDistributions(): Boolean {
return options.targetOs.lowercase() != BuildOptions.OS_NONE
}
override fun shouldBuildDistributionForOS(os: OsFamily, arch: JvmArchitecture): Boolean {
return shouldBuildDistributions()
&& listOf(BuildOptions.OS_ALL, os.osId).contains(options.targetOs.lowercase())
&& (options.targetArch == null || options.targetArch == arch)
}
override fun createCopyForProduct(productProperties: ProductProperties, projectHomeForCustomizers: Path): BuildContext {
val projectHomeForCustomizersAsString = FileUtilRt.toSystemIndependentName(projectHomeForCustomizers.toString())
/**
* FIXME compiled classes are assumed to be already fetched in the FIXME from [CompilationContextImpl.prepareForBuild], please change them together
*/
val options = BuildOptions()
options.useCompiledClassesFromProjectOutput = true
val compilationContextCopy = compilationContext.createCopy(
messages = messages,
options = options,
buildOutputRootEvaluator = createBuildOutputRootEvaluator(paths.projectHome, productProperties, options)
)
val copy = BuildContextImpl(
compilationContext = compilationContextCopy,
productProperties = productProperties,
windowsDistributionCustomizer = productProperties.createWindowsCustomizer(projectHomeForCustomizersAsString),
linuxDistributionCustomizer = productProperties.createLinuxCustomizer(projectHomeForCustomizersAsString),
macDistributionCustomizer = productProperties.createMacCustomizer(projectHomeForCustomizersAsString),
proprietaryBuildTools = proprietaryBuildTools,
distFiles = ConcurrentLinkedQueue()
)
@Suppress("DEPRECATION") val productCode = productProperties.productCode
copy.paths.artifactDir = paths.artifactDir.resolve(productCode!!)
copy.paths.artifacts = "${paths.artifacts}/$productCode"
copy.compilationContext.prepareForBuild()
return copy
}
override fun includeBreakGenLibraries() = isJavaSupportedInProduct
private val isJavaSupportedInProduct: Boolean
get() = productProperties.productLayout.bundledPluginModules.contains("intellij.java.plugin")
override fun patchInspectScript(path: Path) {
//todo[nik] use placeholder in inspect.sh/inspect.bat file instead
Files.writeString(path, Files.readString(path).replace(" inspect ", " ${productProperties.inspectCommandName} "))
}
override fun getAdditionalJvmArguments(os: OsFamily): List<String> {
val jvmArgs: MutableList<String> = ArrayList()
val classLoader = productProperties.classLoader
if (classLoader != null) {
jvmArgs.add("-Djava.system.class.loader=$classLoader")
if (classLoader == "com.intellij.util.lang.PathClassLoader") {
jvmArgs.add("-Didea.strict.classpath=true")
}
}
jvmArgs.add("-Didea.vendor.name=" + applicationInfo.shortCompanyName)
jvmArgs.add("-Didea.paths.selector=$systemSelector")
if (productProperties.platformPrefix != null) {
jvmArgs.add("-Didea.platform.prefix=${productProperties.platformPrefix}")
}
jvmArgs.addAll(productProperties.additionalIdeJvmArguments)
if (productProperties.useSplash) {
@Suppress("SpellCheckingInspection")
jvmArgs.add("-Dsplash=true")
}
jvmArgs.addAll(getCommandLineArgumentsForOpenPackages(this, os))
return jvmArgs
}
}
private fun createBuildOutputRootEvaluator(projectHome: Path,
productProperties: ProductProperties,
buildOptions: BuildOptions): (JpsProject) -> Path {
return { project ->
val appInfo = ApplicationInfoPropertiesImpl(project = project,
productProperties = productProperties,
buildOptions = buildOptions)
projectHome.resolve("out/${productProperties.getOutputDirectoryName(appInfo)}")
}
}
private fun getSourceRootsWithPrefixes(module: JpsModule): Sequence<Pair<Path, String>> {
return module.sourceRoots.asSequence()
.filter { root: JpsModuleSourceRoot ->
JavaModuleSourceRootTypes.PRODUCTION.contains(root.rootType)
}
.map { moduleSourceRoot: JpsModuleSourceRoot ->
var prefix: String
val properties = moduleSourceRoot.properties
prefix = if (properties is JavaSourceRootProperties) {
properties.packagePrefix.replace(".", "/")
}
else {
(properties as JavaResourceRootProperties).relativeOutputPath
}
if (!prefix.endsWith("/")) {
prefix += "/"
}
Pair(Path.of(JpsPathUtil.urlToPath(moduleSourceRoot.url)), prefix.trimStart('/'))
}
}
private const val projectorPlugin = "intellij.cwm.plugin.projector"
private const val projectorJar = "plugins/cwm-plugin-projector/lib/projector/projector.jar"
private fun configureProjectorPlugin(properties: ProductProperties) {
// configure only if versionCheckerConfig is not empty -
// otherwise will be an error because versionCheckerConfig expected to contain a default version (e.g. "" to "11")
if (properties.versionCheckerConfig.isNotEmpty() &&
properties.productLayout.bundledPluginModules.contains(projectorPlugin) &&
!properties.versionCheckerConfig.containsKey(projectorJar)) {
properties.versionCheckerConfig = properties.versionCheckerConfig.put(projectorJar, "17")
}
}
private fun readSnapshotBuildNumber(communityHome: BuildDependenciesCommunityRoot): String {
return Files.readString(communityHome.communityRoot.resolve("build.txt")).trim { it <= ' ' }
}
| apache-2.0 | dce4d164c5c7ea5483cb229d584dc6af | 43.644578 | 151 | 0.730131 | 5.627183 | false | false | false | false |
mdaniel/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/AddArrayOfTypeFix.kt | 1 | 1622 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.quickfix
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import org.jetbrains.kotlin.builtins.KotlinBuiltIns
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.codeinsight.api.classic.quickfixes.KotlinQuickFixAction
import org.jetbrains.kotlin.psi.KtExpression
import org.jetbrains.kotlin.psi.KtFile
import org.jetbrains.kotlin.psi.KtPsiFactory
import org.jetbrains.kotlin.psi.createExpressionByPattern
import org.jetbrains.kotlin.renderer.DescriptorRenderer
import org.jetbrains.kotlin.types.KotlinType
import java.util.*
class AddArrayOfTypeFix(expression: KtExpression, expectedType: KotlinType) : KotlinQuickFixAction<KtExpression>(expression) {
private val prefix = if (KotlinBuiltIns.isArray(expectedType)) {
"arrayOf"
} else {
val typeName = DescriptorRenderer.SHORT_NAMES_IN_TYPES.renderType(expectedType)
"${typeName.decapitalize(Locale.US)}Of"
}
override fun getText() = KotlinBundle.message("fix.add.array.of.type.text", prefix)
override fun getFamilyName() = KotlinBundle.message("fix.add.array.of.type.family")
override fun invoke(project: Project, editor: Editor?, file: KtFile) {
val element = element ?: return
val arrayOfExpression = KtPsiFactory(project).createExpressionByPattern("$0($1)", prefix, element)
element.replace(arrayOfExpression)
}
}
| apache-2.0 | 82b8fc185e3a6c46a934070db135bcd9 | 44.055556 | 158 | 0.778052 | 4.383784 | false | false | false | false |
mdaniel/intellij-community | platform/workspaceModel/codegen/src/com/intellij/workspaceModel/codegen/writer/apiCode.kt | 1 | 4348 | // 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.workspaceModel.codegen
import com.intellij.workspaceModel.codegen.SKIPPED_TYPES
import com.intellij.workspaceModel.codegen.classes.*
import com.intellij.workspaceModel.storage.*
import com.intellij.workspaceModel.codegen.fields.javaType
import org.jetbrains.deft.Type
import com.intellij.workspaceModel.codegen.fields.referencedField
import com.intellij.workspaceModel.codegen.fields.wsCode
import com.intellij.workspaceModel.codegen.deft.model.DefType
import com.intellij.workspaceModel.codegen.deft.model.WsEntityInterface
import com.intellij.workspaceModel.codegen.utils.fqn
import com.intellij.workspaceModel.codegen.utils.lines
import com.intellij.workspaceModel.codegen.deft.Field
import com.intellij.workspaceModel.codegen.fields.builderApi
fun DefType.generatedApiCode(indent: String = " ", isEmptyGenBlock: Boolean): String = lines(indent) {
if (isEmptyGenBlock) line("//region generated code") else result.append("//region generated code\n")
line("//@formatter:off")
line("@${GeneratedCodeApiVersion::class.fqn}(${CodeGeneratorVersions.API_VERSION})")
val abstractSupertype = if (base?.abstract == true) base else null
val header = when {
abstract && abstractSupertype != null -> {
"interface Builder<T: $javaFullName>: $javaFullName, ${abstractSupertype.name}.Builder<T>, ${
ModifiableWorkspaceEntity::class.fqn
}<T>, ObjBuilder<T>"
}
abstractSupertype != null -> {
"interface Builder: $javaFullName, ${abstractSupertype.name}.Builder<$javaFullName>, ${
ModifiableWorkspaceEntity::class.fqn
}<$javaFullName>, ObjBuilder<$javaFullName>"
}
abstract -> "interface Builder<T: $javaFullName>: $javaFullName, ${ModifiableWorkspaceEntity::class.fqn}<T>, ObjBuilder<T>"
else -> "interface Builder: $javaFullName, ${ModifiableWorkspaceEntity::class.fqn}<$javaFullName>, ObjBuilder<$javaFullName>"
}
section(header) {
list(structure.allFields.noPersistentId()) {
if (def.kind is WsEntityInterface) wsBuilderApi else builderApi
}
}
line()
val builderGeneric = if (abstract) "<$javaFullName>" else ""
val companionObjectHeader = buildString {
append("companion object: ${Type::class.fqn}<$javaFullName, Builder$builderGeneric>(")
val base = base
if (base != null && base.name !in SKIPPED_TYPES)
append(base.javaFullName)
append(")")
}
val mandatoryFields = structure.allFields.noRefs().noOptional().noPersistentId().noDefaultValue()
if (!mandatoryFields.isEmpty()) {
val fields = (mandatoryFields.noEntitySource() + mandatoryFields.first { it.name == "entitySource" }).joinToString { "${it.name}: ${it.type.javaType}" }
section(companionObjectHeader) {
section("operator fun invoke($fields, init: (Builder$builderGeneric.() -> Unit)? = null): $javaFullName") {
line("val builder = builder()")
list(mandatoryFields) {
"builder.$name = $name"
}
line("init?.invoke(builder)")
line("return builder")
}
}
} else {
section(companionObjectHeader) {
section("operator fun invoke(init: (Builder$builderGeneric.() -> Unit)? = null): $javaFullName") {
line("val builder = builder()")
line("init?.invoke(builder)")
line("return builder")
}
}
}
line("//@formatter:on")
lineNoNl("//endregion")
}
fun DefType.generatedExtensionCode(indent: String = " "): String {
val extFields = module.extFields.filter { it.owner is DefType &&
(this === it.owner || (it.owner.def.formExternalModule && it.referencedField.owner === this)) }
if (extFields.isEmpty() && abstract) return ""
return lines(indent) {
line("//region generated code")
if (!abstract) {
line("fun ${MutableEntityStorage::class.fqn}.modifyEntity(entity: $name, modification: $name.Builder.() -> Unit) = modifyEntity($name.Builder::class.java, entity, modification)")
}
if (extFields.isNotEmpty()) {
extFields.sortedWith(compareBy({it.owner.name}, {it.name})).forEach { line(it.wsCode) }
}
lineNoNl("//endregion")
}
}
val Field<*, *>.wsBuilderApi: String
get() = "override var $javaName: ${type.javaType}"
| apache-2.0 | 3b6b38be2415b5cc89e2cd6f1fabd7ff | 43.367347 | 184 | 0.694572 | 4.217265 | false | false | false | false |
WhisperSystems/Signal-Android | app/src/main/java/org/thoughtcrime/securesms/avatar/AvatarRenderer.kt | 1 | 5439 | package org.thoughtcrime.securesms.avatar
import android.content.Context
import android.graphics.Bitmap
import android.graphics.Canvas
import android.graphics.Typeface
import android.graphics.drawable.Drawable
import android.net.Uri
import androidx.appcompat.content.res.AppCompatResources
import com.airbnb.lottie.SimpleColorFilter
import org.signal.core.util.concurrent.SignalExecutors
import org.thoughtcrime.securesms.mediasend.Media
import org.thoughtcrime.securesms.mms.PartAuthority
import org.thoughtcrime.securesms.profiles.AvatarHelper
import org.thoughtcrime.securesms.providers.BlobProvider
import org.thoughtcrime.securesms.util.MediaUtil
import org.whispersystems.libsignal.util.guava.Optional
import java.io.ByteArrayInputStream
import java.io.ByteArrayOutputStream
import java.io.IOException
import javax.annotation.meta.Exhaustive
/**
* Renders Avatar objects into Media objects. This can involve creating a Bitmap, depending on the
* type of Avatar passed to `renderAvatar`
*/
object AvatarRenderer {
val DIMENSIONS = AvatarHelper.AVATAR_DIMENSIONS
fun getTypeface(context: Context): Typeface {
return Typeface.createFromAsset(context.assets, "fonts/Inter-Medium.otf")
}
fun renderAvatar(context: Context, avatar: Avatar, onAvatarRendered: (Media) -> Unit, onRenderFailed: (Throwable?) -> Unit) {
@Exhaustive
when (avatar) {
is Avatar.Resource -> renderResource(context, avatar, onAvatarRendered, onRenderFailed)
is Avatar.Vector -> renderVector(context, avatar, onAvatarRendered, onRenderFailed)
is Avatar.Photo -> renderPhoto(context, avatar, onAvatarRendered)
is Avatar.Text -> renderText(context, avatar, onAvatarRendered, onRenderFailed)
}
}
@JvmStatic
fun createTextDrawable(
context: Context,
avatar: Avatar.Text,
inverted: Boolean = false,
size: Int = DIMENSIONS,
): Drawable {
return TextAvatarDrawable(context, avatar, inverted, size)
}
private fun renderVector(context: Context, avatar: Avatar.Vector, onAvatarRendered: (Media) -> Unit, onRenderFailed: (Throwable?) -> Unit) {
renderInBackground(context, onAvatarRendered, onRenderFailed) { canvas ->
val drawableResourceId = Avatars.getDrawableResource(avatar.key) ?: return@renderInBackground Result.failure(Exception("Drawable resource for key ${avatar.key} does not exist."))
val vector: Drawable = requireNotNull(AppCompatResources.getDrawable(context, drawableResourceId))
vector.setBounds(0, 0, DIMENSIONS, DIMENSIONS)
canvas.drawColor(avatar.color.backgroundColor)
vector.draw(canvas)
Result.success(Unit)
}
}
private fun renderText(context: Context, avatar: Avatar.Text, onAvatarRendered: (Media) -> Unit, onRenderFailed: (Throwable?) -> Unit) {
renderInBackground(context, onAvatarRendered, onRenderFailed) { canvas ->
val textDrawable = createTextDrawable(context, avatar)
canvas.drawColor(avatar.color.backgroundColor)
textDrawable.draw(canvas)
Result.success(Unit)
}
}
private fun renderPhoto(context: Context, avatar: Avatar.Photo, onAvatarRendered: (Media) -> Unit) {
SignalExecutors.BOUNDED.execute {
val blob = BlobProvider.getInstance()
.forData(AvatarPickerStorage.read(context, PartAuthority.getAvatarPickerFilename(avatar.uri)), avatar.size)
.createForSingleSessionOnDisk(context)
onAvatarRendered(createMedia(blob, avatar.size))
}
}
private fun renderResource(context: Context, avatar: Avatar.Resource, onAvatarRendered: (Media) -> Unit, onRenderFailed: (Throwable?) -> Unit) {
renderInBackground(context, onAvatarRendered, onRenderFailed) { canvas ->
val resource: Drawable = requireNotNull(AppCompatResources.getDrawable(context, avatar.resourceId))
resource.colorFilter = SimpleColorFilter(avatar.color.foregroundColor)
val padding = (DIMENSIONS * 0.2).toInt()
resource.setBounds(0 + padding, 0 + padding, DIMENSIONS - padding, DIMENSIONS - padding)
canvas.drawColor(avatar.color.backgroundColor)
resource.draw(canvas)
Result.success(Unit)
}
}
private fun renderInBackground(context: Context, onAvatarRendered: (Media) -> Unit, onRenderFailed: (Throwable?) -> Unit, drawAvatar: (Canvas) -> Result<Unit>) {
SignalExecutors.BOUNDED.execute {
val canvasBitmap = Bitmap.createBitmap(DIMENSIONS, DIMENSIONS, Bitmap.Config.ARGB_8888)
val canvas = Canvas(canvasBitmap)
val drawResult = drawAvatar(canvas)
if (drawResult.isFailure) {
canvasBitmap.recycle()
onRenderFailed(drawResult.exceptionOrNull())
}
val outStream = ByteArrayOutputStream()
val compressed = canvasBitmap.compress(Bitmap.CompressFormat.JPEG, 80, outStream)
canvasBitmap.recycle()
if (!compressed) {
onRenderFailed(IOException("Failed to compress bitmap"))
return@execute
}
val bytes = outStream.toByteArray()
val inStream = ByteArrayInputStream(bytes)
val uri = BlobProvider.getInstance().forData(inStream, bytes.size.toLong()).createForSingleSessionOnDisk(context)
onAvatarRendered(createMedia(uri, bytes.size.toLong()))
}
}
private fun createMedia(uri: Uri, size: Long): Media {
return Media(uri, MediaUtil.IMAGE_JPEG, System.currentTimeMillis(), DIMENSIONS, DIMENSIONS, size, 0, false, false, Optional.absent(), Optional.absent(), Optional.absent())
}
}
| gpl-3.0 | 03d533c173649066642e9dc1e94dc58d | 40.204545 | 184 | 0.745541 | 4.396928 | false | false | false | false |
GunoH/intellij-community | plugins/grazie/src/main/kotlin/com/intellij/grazie/ide/ui/search/GrazieSearchableOptionContributor.kt | 8 | 2225 | // Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.grazie.ide.ui.search
import com.intellij.grazie.GraziePlugin
import com.intellij.grazie.ide.ui.components.dsl.msg
import com.intellij.grazie.ide.ui.grammar.tabs.rules.component.allRules
import com.intellij.grazie.jlanguage.Lang
import com.intellij.grazie.text.TextExtractor
import com.intellij.ide.ui.search.SearchableOptionContributor
import com.intellij.ide.ui.search.SearchableOptionProcessor
import com.intellij.openapi.options.OptionsBundle
private class GrazieSearchableOptionContributor : SearchableOptionContributor() {
private val proofreadId = "proofread"
private val proofreadName = OptionsBundle.message("configurable.group.proofread.settings.display.name")
private val grammarId = "reference.settingsdialog.project.grazie"
private val grammarName = GraziePlugin.settingsPageName
private fun SearchableOptionProcessor.addProofreadOptions(text: String, path: String? = null, hit: String? = text) {
addOptions(text, path, hit, proofreadId, proofreadName, false)
}
private fun SearchableOptionProcessor.addGrammarOptions(text: String, path: String? = null, hit: String? = text) {
addOptions(text, path, hit, grammarId, grammarName, false)
}
override fun processOptions(processor: SearchableOptionProcessor) {
for (lang in Lang.values()) {
processor.addProofreadOptions("${lang.displayName} ${lang.nativeName}", hit = msg("grazie.settings.proofreading.languages.text"))
}
for (language in TextExtractor.getSupportedLanguages()) {
processor.addGrammarOptions(language.displayName, hit = msg("grazie.settings.grammar.scope.file-types.text"))
}
processor.addGrammarOptions("grazie", null, null)
val categories = HashSet<String>()
for (rule in allRules().values.flatten()) {
processor.addGrammarOptions(rule.presentableName, hit = msg("grazie.settings.grammar.scope.rules.text"))
for (cat in rule.categories) {
if (categories.add(cat)) {
processor.addGrammarOptions(cat, hit = msg("grazie.settings.grammar.scope.rules.text"))
}
}
}
}
}
| apache-2.0 | 24f238b9d76e5e1f59a97c18e51a08a3 | 46.340426 | 140 | 0.759551 | 4.075092 | false | false | false | false |
hellenxu/TipsProject | Custom/app/src/main/java/six/ca/custom/json/FavAdapter.kt | 1 | 3874 | package six.ca.custom.json
import com.squareup.moshi.*
import java.lang.reflect.Array
import java.lang.reflect.Array.getLength
import kotlin.collections.ArrayList
/**
* @author hellenxu
* @date 2019-10-07
* Copyright 2019 Six. All rights reserved.
*/
class FavAdapter constructor(private val moshi: Moshi) : JsonAdapter<Any>() {
override fun fromJson(reader: JsonReader): kotlin.Array<FavResponse> {
val list = arrayListOf<FavResponse>()
when (reader.peek()) {
JsonReader.Token.BEGIN_OBJECT -> {
val obj = readObject(reader, FavResponse::class.java) as FavResponse
list.add(obj)
}
JsonReader.Token.BEGIN_ARRAY -> {
list.addAll(readArray(reader, FavResponse::class.java))
}
else -> {
}
}
return list.toTypedArray()
}
private fun <T> readArray(reader: JsonReader, clzz: Class<*>): List<T> {
val list = ArrayList<T>()
reader.beginArray()
while (reader.hasNext()) {
readObject(reader, clzz)?.let {
list.add(it as T)
}
}
reader.endArray()
return list
}
private fun <T> readObject(reader: JsonReader, clzz: Class<T>): T? {
return when (clzz) {
PhoneInfo::class.java -> moshi.adapter<T>(clzz).fromJson(reader)
else -> {
readFavNumList(reader) as T
}
}
}
private fun readFavNumList(reader: JsonReader): FavResponse {
reader.beginObject()
var serviceCd = ""
var featureCd = ""
var setSizeNum = ""
var effectiveDt = ""
var lastUpdateDt = ""
val currentList = ArrayList<PhoneInfo>()
val futureList = ArrayList<PhoneInfo>()
while (reader.hasNext()) {
val name = reader.nextName()
if ("serviceCd".equals(name, true)) {
serviceCd = reader.nextString()
}
if ("featureCd".equals(name, true)) {
featureCd = reader.nextString()
}
if ("setSizeNum".equals(name, true)) {
setSizeNum = reader.nextString()
}
if ("effectiveDt".equals(name, true)) {
effectiveDt = reader.nextString()
}
if ("lastUpdateDt".equals(name, true)) {
lastUpdateDt = reader.nextString()
}
if ("currentList".equals(name, true)) {
currentList.addAll(readList(reader))
}
if ("futureList".equals(name, true)) {
futureList.addAll(readList(reader))
}
}
reader.endObject()
return FavResponse(
serviceCd,
featureCd,
setSizeNum,
effectiveDt,
lastUpdateDt,
currentList,
futureList
)
}
private fun readList(reader: JsonReader): List<PhoneInfo> {
val list = arrayListOf<PhoneInfo>()
when (reader.peek()) {
JsonReader.Token.BEGIN_OBJECT -> {
val obj = readObject(reader, PhoneInfo::class.java) as PhoneInfo
list.add(obj)
}
JsonReader.Token.BEGIN_ARRAY -> {
list.addAll(readArray(reader, PhoneInfo::class.java))
}
else -> {
}
}
return list
}
override fun toJson(writer: JsonWriter, value: Any?) {
val result = StringBuilder()
val adapter = moshi.adapter<FavResponse>(FavResponse::class.java)
writer.beginArray()
val size = getLength(value)
for (i in 0 until size) {
result.append(adapter.toJson(writer, Array.get(value, i) as FavResponse))
}
writer.endArray()
}
} | apache-2.0 | 0b3c0ee58bd4b3bb84b5d381564e35ce | 29.03876 | 85 | 0.530459 | 4.515152 | false | false | false | false |
GunoH/intellij-community | plugins/full-line/python/src/org/jetbrains/completion/full/line/python/formatters/ParameterListFormatter.kt | 2 | 2218 | package org.jetbrains.completion.full.line.python.formatters
import com.intellij.openapi.util.text.StringUtil
import com.intellij.psi.PsiElement
import com.intellij.util.containers.ContainerUtil
import com.jetbrains.python.psi.PyNamedParameter
import com.jetbrains.python.psi.PyParameterList
import com.jetbrains.python.psi.PyStringLiteralCoreUtil
import com.jetbrains.python.psi.types.PyCallableParameter
import com.jetbrains.python.psi.types.PyCallableParameterImpl
import org.jetbrains.completion.full.line.language.ElementFormatter
class ParameterListFormatter : ElementFormatter {
override fun condition(element: PsiElement): Boolean = element is PyParameterList
override fun filter(element: PsiElement): Boolean? = element is PyParameterList
override fun format(element: PsiElement): String {
element as PyParameterList
return if (element.text.isNotEmpty()) {
val closing = if (element.text.last() == ')') ")" else ""
val params = ContainerUtil.map(element.parameters, PyCallableParameterImpl::psi)
"(" + formatParameter(params) + closing
}
else {
""
}
}
private fun formatParameter(params: List<PyCallableParameter>): String {
return params.joinToString(separator = ", ") {
if (it.hasDefaultValue()) {
it.getPresentableText(false) + ((it.parameter as PyNamedParameter).annotation?.text ?: "") +
includeDefaultValue(it.defaultValueText!!)
}
else {
if (it.parameter is PyNamedParameter) {
it.getPresentableText(true) + ((it.parameter as PyNamedParameter).annotation?.text ?: "")
}
else {
"*"
}
}
}
}
private fun includeDefaultValue(defaultValue: String): String {
val sb = StringBuilder()
val quotes = PyStringLiteralCoreUtil.getQuotes(defaultValue)
sb.append("=")
if (quotes != null) {
val value: String = defaultValue.substring(quotes.getFirst().length, defaultValue.length - quotes.getSecond().length)
sb.append(quotes.getFirst())
StringUtil.escapeStringCharacters(value.length, value, sb)
sb.append(quotes.getSecond())
}
else {
sb.append(defaultValue)
}
return sb.toString()
}
}
| apache-2.0 | a569ff91da08eb7a510f791e74d05926 | 33.65625 | 123 | 0.706041 | 4.545082 | false | false | false | false |
GunoH/intellij-community | java/java-impl/src/com/intellij/codeInsight/daemon/impl/JavaReferencesCodeVisionProvider.kt | 3 | 1476 | // 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 com.intellij.codeInsight.daemon.impl
import com.intellij.codeInsight.codeVision.CodeVisionRelativeOrdering
import com.intellij.codeInsight.hints.codeVision.ReferencesCodeVisionProvider
import com.intellij.java.JavaBundle
import com.intellij.lang.java.JavaLanguage
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiFile
import com.intellij.psi.PsiMember
import com.intellij.psi.PsiTypeParameter
class JavaReferencesCodeVisionProvider : ReferencesCodeVisionProvider() {
companion object{
const val ID = "java.references"
}
override fun acceptsFile(file: PsiFile): Boolean = file.language == JavaLanguage.INSTANCE
override fun acceptsElement(element: PsiElement): Boolean = element is PsiMember && element !is PsiTypeParameter
override fun getHint(element: PsiElement, file: PsiFile): String? = JavaTelescope.usagesHint(element as PsiMember, file)
override fun logClickToFUS(element: PsiElement) {
JavaCodeVisionUsageCollector.USAGES_CLICKED_EVENT_ID.log(element.project)
}
override val name: String
get() = JavaBundle.message("settings.inlay.java.usages")
override val relativeOrderings: List<CodeVisionRelativeOrdering>
get() = listOf(CodeVisionRelativeOrdering.CodeVisionRelativeOrderingBefore("java.inheritors"))
override val id: String
get() = ID
} | apache-2.0 | 8819bd82250cb2cf06429bfaec9e1679 | 42.441176 | 158 | 0.802846 | 4.626959 | false | false | false | false |
klutter/klutter | netflix-graph/src/main/kotlin/uy/klutter/graph/netflix/internal/Building.kt | 1 | 11463 | package uy.klutter.graph.netflix.internal
import com.netflix.nfgraph.build.NFBuildGraph
import com.netflix.nfgraph.spec.NFGraphSpec
import com.netflix.nfgraph.spec.NFNodeSpec
import com.netflix.nfgraph.spec.NFPropertySpec
import uy.klutter.graph.netflix.*
import java.io.DataOutputStream
import java.io.OutputStream
class CompiledGraphSchema<N : Enum<N>, R : Enum<R>>(val schema: GraphSchemaBuilder<N, R>) {
internal val nodeTypes: Set<N> = schema.nodeTypes
internal val relationTypes: Set<R> = schema.relationTypes
internal val nodeTypeEnum: Class<N> = schema.nodeTypeEnum
internal val relationTypeEnum: Class<R> = schema.relationTypeEnum
// when have a relationship of a->R->b and a->R->c need to change to a->R.b->b and a->R.c->c but later find both if someone asks for R again during querying
// ok, take the schema, render out both the NFGraphSpec and also our version of this that we can serialize
// Ours includes:
// outbound relationships for a given node type
// relationship groups that disambiguate any collisions
// relationship mirrors that automatically apply the reverse relationship when the opposite is added
internal val relationshipGroups: MutableMap<RelationshipPairKey<N, R>, MutableSet<RelationshipTrippleKey<N, R>>> = hashMapOf()
internal val relationshipMirrors = hashMapOf<RelationshipTrippleKey<N, R>, RelationshipTrippleKey<N, R>>()
internal val graphSpec = NFGraphSpec()
init {
val relationshipFlags = hashMapOf<RelationshipTrippleKey<N, R>, Int>()
fun createRelation(fromNode: N, relationship: R, toNode: N, relationOptions: GraphRelationOptions, @Suppress("UNUSED_PARAMETER") modelScope: String? = null): RelationshipTrippleKey<N, R> {
val trippleKey = RelationshipTrippleKey(fromNode, relationship, toNode)
val oldFlags = relationshipFlags.get(trippleKey)
if (oldFlags != null && oldFlags != relationOptions.flags) {
throw RuntimeException("Repeated definition of a relationship must have the same flags: ${trippleKey} with old ${oldFlags} new ${relationOptions.flags}")
}
val pairKey = RelationshipPairKey(fromNode, relationship)
val relationGroup = relationshipGroups.getOrPut(pairKey, { hashSetOf() })
relationGroup.add(trippleKey)
relationshipFlags.put(trippleKey, relationOptions.flags)
return trippleKey
}
schema.relations.forEach { r ->
val modelScope = if (r.scopeAs == RelationScope.GLOBAL) null else r.modelScopeName
val forward = createRelation(r.fromNode, r.forwardRelation, r.toNode, r.forwardFlags, modelScope)
if (r.backwardRelation != null) {
val backward = createRelation(r.toNode, r.backwardRelation!!, r.fromNode, r.backwardFlags, modelScope)
val oldForwardMirror = relationshipMirrors.get(forward)
val oldBackwardMirror = relationshipMirrors.get(backward)
if (oldForwardMirror != null && oldBackwardMirror != null && oldForwardMirror != backward && oldBackwardMirror != forward) {
throw RuntimeException("Repeated definition of a relationship mirrors must have the same mirror relationships: ${forward} and ${backward} have differing mirrors ${oldBackwardMirror} and ${oldForwardMirror}")
}
relationshipMirrors.put(forward, backward)
relationshipMirrors.put(backward, forward)
}
}
val relationshipGroupsPerNodeType = relationshipGroups.keys.groupBy { it.fromNode }
nodeTypes.forEach { node ->
val nodeRelationGroups = relationshipGroupsPerNodeType.get(node) ?: listOf()
val propSpecs = arrayListOf<NFPropertySpec>()
if (nodeRelationGroups.isNotEmpty()) {
nodeRelationGroups.forEach { pairKey ->
val groupMembers = relationshipGroups.getOrElse(pairKey, { hashSetOf() })
if (groupMembers.isNotEmpty()) {
val fullyQualify = groupMembers.size > 1
groupMembers.forEach { trippleKey ->
val relateName = if (fullyQualify) "${trippleKey.relationship.name}.${trippleKey.toNode.name}" else trippleKey.relationship.name
propSpecs.add(NFPropertySpec(relateName, trippleKey.toNode.name, relationshipFlags.get(trippleKey) ?: 0))
}
}
}
graphSpec.addNodeSpec(NFNodeSpec(node.name, *(propSpecs.toTypedArray())))
}
}
}
}
class GraphBuilderTempStep1<N : Enum<N>, R : Enum<R>>(val fromNodeWithOrd: NodeAndOrd<N>, val completr: (NodeAndOrd<N>, R, NodeAndOrd<N>)->Unit) {
fun edge(relation: R): GraphBuilderTempStep2<N,R> {
return GraphBuilderTempStep2<N, R>(fromNodeWithOrd, relation, completr)
}
}
class GraphBuilderTempStep2<N : Enum<N>, R : Enum<R>>(val fromNodeWithOrd: NodeAndOrd<N>, val relation: R, val completr: (NodeAndOrd<N>,R,NodeAndOrd<N>)->Unit) {
fun to(toNodeWithOrd: NodeAndOrd<N>): Unit {
completr(fromNodeWithOrd, relation, toNodeWithOrd)
}
}
class GraphBuilder<N : Enum<N>, R : Enum<R>>(val schema: CompiledGraphSchema<N, R>) : GraphOrdinalContainer<N>(false) {
private val graphBuilder = NFBuildGraph(schema.graphSpec)
fun connect(fromNodeWithOrd: NodeAndOrd<N>): GraphBuilderTempStep1<N,R> {
return GraphBuilderTempStep1<N,R>(fromNodeWithOrd, { f,r,t -> connect(f,r,t) })
}
fun connect(fromNodeWithId: NodeAndId<N>, relation: R, toNodeWithId: NodeAndId<N>) {
connect(fromNodeWithId.toNord(), relation, toNodeWithId.toNord())
}
fun connect(fromNodeWithOrd: NodeAndOrd<N>, relation: R, toNodeWithOrd: NodeAndOrd<N>) {
val forward = connectInternal(fromNodeWithOrd, relation, toNodeWithOrd)
val mirrorRelation = schema.relationshipMirrors.get(forward)
if (mirrorRelation != null) {
connectInternal(toNodeWithOrd, mirrorRelation.relationship, fromNodeWithOrd)
}
}
// TODO: support new methods getNodes(), getOrCreateNote(), addConnection(node, spec, ...) which are more efficient
// also addConnectionModel returning int can be used to speed things up
// also getPropertySpec returning NFPropertySpec can be used in the new add methods
// ... see: https://github.com/Netflix/netflix-graph/commit/2f297cf584bb83361d8ca7f1ecdfe84f11731031
// this may not be in release yet, could be 1.6 or later, have to check...
private fun connectInternal(fromNodeWithOrd: NodeAndOrd<N>, relation: R, toNodeWithOrd: NodeAndOrd<N>): RelationshipTrippleKey<N,R> {
val pairKey = RelationshipPairKey(fromNodeWithOrd.nodeType, relation)
val trippleKey = RelationshipTrippleKey(fromNodeWithOrd.nodeType, relation, toNodeWithOrd.nodeType)
val nodeRelations = schema.relationshipGroups.getOrElse(pairKey, { setOf<RelationshipTrippleKey<N,R>>() })
if (nodeRelations.isNotEmpty()) {
val fullyQualify = nodeRelations.size > 1
val matchingRelation = nodeRelations.filter { it == trippleKey }.firstOrNull()
if (matchingRelation != null) {
val relateName = if (fullyQualify) "${trippleKey.relationship.name}.${trippleKey.toNode.name}" else trippleKey.relationship.name
graphBuilder.addConnection(matchingRelation.fromNode.name, fromNodeWithOrd.ord, relateName, toNodeWithOrd.ord)
return trippleKey
} else {
throw RuntimeException("No relationship for ${trippleKey} exists, cannot connect these nodes!")
}
} else {
throw RuntimeException("No relationship for ${pairKey} exists, cannot connect it to anything!")
}
}
fun serialize(output: OutputStream) {
DataOutputStream(output).use { dataStream ->
// Header:
// "**KOTLIN-NFGRAPH**"
// version as number
// Partial Schema: (only unidirectional relations, no mirrors)
// "**SCHEMA**"
// number of nodeType
// [foreach nodeType]
// - name of nodeType
// number of relation groups
// [foreach relation group]
// - nodeType name
// - relation name
// - number of targets
// [foreach target]
// - target nodeType name
// number of mirrors
// [foreach mirror]
// - forward nodeType name
// - forward relation name
// - forward target nodeType name
// - backward nodeType name
// - backward relation name
// - backward target nodeType name
//
// Ordinals:
// "**ORDINALS**"
// number of ordinal maps
// [foreach ordinal map]
// - name of nodeType
// - count N of ordinals
// - 0..N of ordinals
//
// Graph:
// "**GRAPH**"
// compressed graph serialized
// Header
dataStream.writeUTF(GRAPH_MARKERS_HEADER)
dataStream.writeInt(1)
// Partial Schema:
dataStream.writeUTF(GRAPH_MARKERS_SCHEMA_HEADER)
val values = schema.nodeTypes
dataStream.writeInt(values.size)
values.forEach { nodeType ->
dataStream.writeUTF(nodeType.name)
}
val groups = schema.relationshipGroups
dataStream.writeInt(groups.size)
groups.entries.forEach { groupEntry ->
dataStream.writeUTF(groupEntry.key.fromNode.name)
dataStream.writeUTF(groupEntry.key.relationship.name)
dataStream.writeInt(groupEntry.value.size)
groupEntry.value.forEach { target ->
dataStream.writeUTF(target.toNode.name)
}
}
val mirrors = schema.relationshipMirrors
dataStream.writeInt(mirrors.size)
mirrors.entries.forEach { mirrorEntry ->
dataStream.writeUTF(mirrorEntry.key.fromNode.name)
dataStream.writeUTF(mirrorEntry.key.relationship.name)
dataStream.writeUTF(mirrorEntry.key.toNode.name)
dataStream.writeUTF(mirrorEntry.value.fromNode.name)
dataStream.writeUTF(mirrorEntry.value.relationship.name)
dataStream.writeUTF(mirrorEntry.value.toNode.name)
}
// Ordinals:
dataStream.writeUTF(GRAPH_MARKERS_ORDINAL_HEADER)
dataStream.writeInt(ordinalsByType.size)
ordinalsByType.forEach { entry ->
dataStream.writeUTF(entry.key.name)
dataStream.writeInt(entry.value.size())
entry.value.asSequence().forEach { ordValue ->
dataStream.writeUTF(ordValue)
}
}
// Graph:
dataStream.writeUTF(GRAPH_MARKERS_GRAPH_HEADER)
val compressed = graphBuilder.compress()
compressed.writeTo(dataStream)
}
}
}
| mit | 5ef5bad8ffd5d82d65ff8a08bce99c8b | 47.987179 | 227 | 0.627323 | 4.484742 | false | false | false | false |
code-disaster/lwjgl3 | modules/lwjgl/glfw/src/templates/kotlin/glfw/templates/GLFWNativeWGL.kt | 4 | 3304 | /*
* Copyright LWJGL. All rights reserved.
* License terms: https://www.lwjgl.org/license
*/
package glfw.templates
import org.lwjgl.generator.*
import glfw.*
import core.windows.*
val GLFWNativeWGL = "GLFWNativeWGL".nativeClass(Module.GLFW, nativeSubPath = "windows", prefix = "GLFW", binding = GLFW_BINDING_DELEGATE) {
javaImport(
"javax.annotation.*",
"org.lwjgl.opengl.GL",
"static org.lwjgl.system.MemoryUtil.*"
)
documentation = "Native bindings to the GLFW library's WGL native access functions."
HGLRC(
"GetWGLContext",
"""
Returns the {@code HGLRC} of the specified window.
The {@code HDC} associated with the window can be queried with the
${url("https://docs.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-getdc", "GetDC")} function.
${code("""
HDC dc = GetDC(glfwGetWin32Window(window));""")}
This DC is private and does not need to be released.
Note: This function may be called from any thread. Access is not synchronized.
""",
GLFWwindow.p("window", "the GLFW window"),
returnDoc =
"""
the {@code HGLRC} of the specified window, or #NULL if an error occurred.
Possible errors include #NO_WINDOW_CONTEXT and #NOT_INITIALIZED.
""",
since = "version 3.0"
)
customMethod("""
/**
* Calls {@link #setPath(String)} with the path of the specified {@link SharedLibrary}.
*
* <p>Example usage: ${code("GLFWNativeWGL.setPath(GL.getFunctionProvider());")}</p>
*
* @param sharedLibrary a {@code FunctionProvider} instance that will be cast to {@code SharedLibrary}
*/
public static void setPath(FunctionProvider sharedLibrary) {
if (!(sharedLibrary instanceof SharedLibrary)) {
apiLog("GLFW OpenGL path override not set: Function provider is not a shared library.");
return;
}
String path = ((SharedLibrary)sharedLibrary).getPath();
if (path == null) {
apiLog("GLFW OpenGL path override not set: Could not resolve the shared library path.");
return;
}
setPath(path);
}
/**
* Overrides the OpenGL shared library that GLFW loads internally.
*
* <p>This is useful when there's a mismatch between the shared libraries loaded by LWJGL and GLFW.</p>
*
* <p>This method must be called before GLFW initializes OpenGL. The override is available only in the default GLFW build bundled with LWJGL. Using the
* override with a custom GLFW build will produce a warning in {@code DEBUG} mode (but not an error).</p>
*
* @param path the OpenGL shared library path, or {@code null} to remove the override.
*/
public static void setPath(@Nullable String path) {
long override = GLFW.getLibrary().getFunctionAddress("_glfw_opengl_library");
if (override == NULL) {
apiLog("GLFW OpenGL path override not set: Could not resolve override symbol.");
return;
}
long a = memGetAddress(override);
if (a != NULL) {
nmemFree(a);
}
memPutAddress(override, path == null ? NULL : memAddress(memUTF16(path)));
}""")
} | bsd-3-clause | 5cdc2f00638c28154ad6ee81a2813267 | 35.318681 | 155 | 0.624697 | 4.464865 | false | false | false | false |
dbrant/apps-android-wikipedia | app/src/main/java/org/wikipedia/util/StringUtil.kt | 1 | 5929 | package org.wikipedia.util
import android.text.Spanned
import android.widget.EditText
import android.widget.TextView
import androidx.annotation.IntRange
import androidx.core.text.parseAsHtml
import androidx.core.text.toSpanned
import com.google.gson.Gson
import okio.ByteString.Companion.encodeUtf8
import org.json.JSONArray
import java.text.Collator
import java.text.Normalizer
object StringUtil {
private const val CSV_DELIMITER = ","
@JvmStatic
fun listToCsv(list: List<String?>): String {
return list.joinToString(CSV_DELIMITER)
}
@JvmStatic
fun csvToList(csv: String): List<String> {
return delimiterStringToList(csv, CSV_DELIMITER)
}
@JvmStatic
fun delimiterStringToList(delimitedString: String,
delimiter: String): List<String> {
return delimitedString.split(delimiter).filter { it.isNotBlank() }
}
@JvmStatic
fun md5string(s: String): String {
return s.encodeUtf8().md5().hex()
}
@JvmStatic
fun strip(str: CharSequence?): CharSequence {
// TODO: remove this function once Kotlin conversion of consumers is complete.
return if (str.isNullOrEmpty()) "" else str.trim()
}
@JvmStatic
fun intToHexStr(i: Int): String {
return String.format("x%08x", i)
}
@JvmStatic
fun addUnderscores(text: String?): String {
return text.orEmpty().replace(" ", "_")
}
@JvmStatic
fun removeUnderscores(text: String?): String {
return text.orEmpty().replace("_", " ")
}
@JvmStatic
fun removeSectionAnchor(text: String?): String {
text.orEmpty().let {
return if (it.contains("#")) it.substring(0, it.indexOf("#")) else it
}
}
@JvmStatic
fun removeNamespace(text: String): String {
return if (text.length > text.indexOf(":")) {
text.substring(text.indexOf(":") + 1)
} else {
text
}
}
@JvmStatic
fun removeHTMLTags(text: String?): String {
return fromHtml(text).toString()
}
@JvmStatic
fun removeStyleTags(text: String): String {
return text.replace("<style.*?</style>".toRegex(), "")
}
@JvmStatic
fun removeCiteMarkup(text: String): String {
return text.replace("<cite.*?>".toRegex(), "").replace("</cite>".toRegex(), "")
}
@JvmStatic
fun sanitizeAbuseFilterCode(code: String): String {
return code.replace("[⧼⧽]".toRegex(), "")
}
@JvmStatic
fun normalizedEquals(str1: String?, str2: String?): Boolean {
return if (str1 == null || str2 == null) {
str1 == null && str2 == null
} else (Normalizer.normalize(str1, Normalizer.Form.NFC)
== Normalizer.normalize(str2, Normalizer.Form.NFC))
}
@JvmStatic
fun fromHtml(source: String?): Spanned {
var sourceStr = source ?: return "".toSpanned()
if ("<" !in sourceStr && "&" !in sourceStr) {
// If the string doesn't contain any hints of HTML entities, then skip the expensive
// processing that fromHtml() performs.
return sourceStr.toSpanned()
}
sourceStr = sourceStr.replace("‎".toRegex(), "\u200E")
.replace("‏".toRegex(), "\u200F")
.replace("&".toRegex(), "&")
return sourceStr.parseAsHtml()
}
@JvmStatic
fun highlightEditText(editText: EditText, parentText: String, highlightText: String) {
val words = highlightText.split("\\s+".toRegex()).toTypedArray()
var pos = 0
for (word in words) {
pos = parentText.indexOf(word, pos)
if (pos == -1) {
break
}
}
if (pos == -1) {
pos = parentText.indexOf(words[words.size - 1])
}
if (pos >= 0) {
// TODO: Programmatic selection doesn't seem to work with RTL content...
editText.setSelection(pos, pos + words[words.size - 1].length)
editText.performLongClick()
}
}
@JvmStatic
fun boldenKeywordText(textView: TextView, parentText: String, searchQuery: String?) {
var parentTextStr = parentText
val startIndex = indexOf(parentTextStr, searchQuery)
if (startIndex >= 0) {
parentTextStr = (parentTextStr.substring(0, startIndex) + "<strong>" +
parentTextStr.substring(startIndex, startIndex + searchQuery!!.length) + "</strong>" +
parentTextStr.substring(startIndex + searchQuery.length))
textView.text = fromHtml(parentTextStr)
} else {
textView.text = parentTextStr
}
}
// case insensitive indexOf, also more lenient with similar chars, like chars with accents
private fun indexOf(original: String, search: String?): Int {
if (!search.isNullOrEmpty()) {
val collator = Collator.getInstance()
collator.strength = Collator.PRIMARY
for (i in 0..original.length - search.length) {
if (collator.equals(search, original.substring(i, i + search.length))) {
return i
}
}
}
return -1
}
@JvmStatic
fun getBase26String(@IntRange(from = 1) number: Int): String {
var num = number
val base = 26
var str = ""
while (--num >= 0) {
str = ('A' + num % base) + str
num /= base
}
return str
}
@JvmStatic
fun listToJsonArrayString(list: List<String>): String {
return JSONArray(list).toString()
}
@JvmStatic
fun stringToListMapToJSONString(map: Map<String, List<Int>>): String {
return Gson().toJson(map)
}
@JvmStatic
fun listToJSONString(list: List<Int>): String {
return Gson().toJson(list)
}
}
| apache-2.0 | e06992d0eaba14bd2515af1eb95a2739 | 29.859375 | 106 | 0.585485 | 4.438202 | false | false | false | false |
dhis2/dhis2-android-sdk | core/src/main/java/org/hisp/dhis/android/core/arch/helpers/DateUtils.kt | 1 | 3772 | /*
* Copyright (c) 2004-2022, University of Oslo
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* Neither the name of the HISP project nor the names of its contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.hisp.dhis.android.core.arch.helpers
import java.util.*
import org.hisp.dhis.android.core.arch.dateformat.internal.SafeDateFormat
import org.hisp.dhis.android.core.period.Period
import org.hisp.dhis.android.core.period.PeriodType
import org.hisp.dhis.android.core.period.internal.CalendarProviderFactory
object DateUtils {
@JvmField
val DATE_FORMAT = SafeDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS")
@JvmField
val SPACE_DATE_FORMAT = SafeDateFormat("yyyy-MM-dd HH:mm:ss.SSS")
@JvmField
val SIMPLE_DATE_FORMAT = SafeDateFormat("yyyy-MM-dd")
@JvmStatic
@Suppress("MagicNumber")
fun dateWithOffset(date: Date, periods: Int, periodType: PeriodType): Date {
val calendar = CalendarProviderFactory.calendarProvider.calendar.clone() as Calendar
calendar.time = date
when (periodType) {
PeriodType.Daily -> calendar.add(Calendar.DATE, periods)
PeriodType.Weekly,
PeriodType.WeeklySaturday,
PeriodType.WeeklySunday,
PeriodType.WeeklyThursday,
PeriodType.WeeklyWednesday -> calendar.add(Calendar.WEEK_OF_YEAR, periods)
PeriodType.BiWeekly -> calendar.add(Calendar.WEEK_OF_YEAR, 2 * periods)
PeriodType.Monthly -> calendar.add(Calendar.MONTH, periods)
PeriodType.BiMonthly -> calendar.add(Calendar.MONTH, 2 * periods)
PeriodType.Quarterly -> calendar.add(Calendar.MONTH, 3 * periods)
PeriodType.SixMonthly,
PeriodType.SixMonthlyApril,
PeriodType.SixMonthlyNov -> calendar.add(Calendar.MONTH, 6 * periods)
PeriodType.Yearly,
PeriodType.FinancialApril,
PeriodType.FinancialJuly,
PeriodType.FinancialOct,
PeriodType.FinancialNov -> calendar.add(Calendar.YEAR, periods)
}
return calendar.time
}
@JvmStatic
fun getStartDate(periods: List<Period>): Date? {
return periods.mapNotNull { it.startDate() }.minByOrNull { it.time }
}
@JvmStatic
fun getEndDate(periods: List<Period>): Date? {
return periods.mapNotNull { it.endDate() }.maxByOrNull { it.time }
}
}
| bsd-3-clause | 5730478cf62b09af32ff351ee135b6da | 42.356322 | 92 | 0.711559 | 4.296128 | false | false | false | false |
mdanielwork/intellij-community | platform/testGuiFramework/src/com/intellij/testGuiFramework/fixtures/CheckBoxFixture.kt | 8 | 1127 | // 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
import com.intellij.testGuiFramework.driver.CheckBoxDriver
import com.intellij.testGuiFramework.impl.findComponent
import org.fest.swing.core.Robot
import org.fest.swing.driver.AbstractButtonDriver
import java.awt.Container
import javax.swing.JCheckBox
/**
* @author Sergey Karashevich
*/
class CheckBoxFixture(robot: Robot, target: JCheckBox) : org.fest.swing.fixture.JCheckBoxFixture(robot, target) {
var isSelected: Boolean
get() = target().isSelected
set(value: Boolean) {
target().isSelected = value
}
override fun createDriver(robot: Robot): AbstractButtonDriver = CheckBoxDriver(robot)
companion object {
fun findByText(text: String, root: Container?, robot: Robot): CheckBoxFixture {
val jCheckBox = robot.findComponent(root, JCheckBox::class.java) {
it.text != null && it.text.toLowerCase() == text.toLowerCase()
}
return CheckBoxFixture(robot, jCheckBox)
}
}
}
| apache-2.0 | 54e5d2da2ad610956cb3d2853e6660f5 | 33.151515 | 140 | 0.74268 | 4.174074 | false | true | false | false |
iSoron/uhabits | uhabits-android/src/main/java/org/isoron/uhabits/activities/common/dialogs/WeekdayPickerDialog.kt | 1 | 3246 | /*
* Copyright (C) 2016-2021 Álinson Santos Xavier <[email protected]>
*
* This file is part of Loop Habit Tracker.
*
* Loop Habit Tracker 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.
*
* Loop Habit Tracker 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 org.isoron.uhabits.activities.common.dialogs
import android.app.Dialog
import android.content.DialogInterface
import android.content.DialogInterface.OnMultiChoiceClickListener
import android.os.Bundle
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatDialogFragment
import org.isoron.uhabits.R
import org.isoron.uhabits.core.models.WeekdayList
import org.isoron.uhabits.core.utils.DateUtils
import java.util.Calendar
/**
* Dialog that allows the user to pick one or more days of the week.
*/
class WeekdayPickerDialog :
AppCompatDialogFragment(),
OnMultiChoiceClickListener,
DialogInterface.OnClickListener {
private var selectedDays: BooleanArray? = null
private var listener: OnWeekdaysPickedListener? = null
override fun onClick(dialog: DialogInterface, which: Int, isChecked: Boolean) {
selectedDays!![which] = isChecked
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
if (savedInstanceState != null) {
selectedDays = savedInstanceState.getBooleanArray(KEY_SELECTED_DAYS)
}
}
override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
outState.putBooleanArray(KEY_SELECTED_DAYS, selectedDays)
}
override fun onClick(dialog: DialogInterface, which: Int) {
if (listener != null) listener!!.onWeekdaysSet(WeekdayList(selectedDays))
}
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
val builder = AlertDialog.Builder(
requireActivity()
)
builder
.setTitle(R.string.select_weekdays)
.setMultiChoiceItems(
DateUtils.getLongWeekdayNames(Calendar.SATURDAY),
selectedDays,
this
)
.setPositiveButton(android.R.string.yes, this)
.setNegativeButton(
android.R.string.cancel
) { _: DialogInterface?, _: Int -> dismiss() }
return builder.create()
}
fun setListener(listener: OnWeekdaysPickedListener?) {
this.listener = listener
}
fun setSelectedDays(days: WeekdayList) {
selectedDays = days.toArray()
}
fun interface OnWeekdaysPickedListener {
fun onWeekdaysSet(days: WeekdayList)
}
companion object {
private const val KEY_SELECTED_DAYS = "selectedDays"
}
}
| gpl-3.0 | 3fe94997374da6e4cffc911863d1b28f | 33.157895 | 83 | 0.699846 | 4.786136 | false | false | false | false |
dkandalov/katas | kotlin/src/katas/kotlin/leetcode/word_ladder_2/WordLadderTests.kt | 1 | 2252 | package katas.kotlin.leetcode.word_ladder_2
import datsok.*
import org.junit.*
/**
* https://leetcode.com/problems/word-ladder-ii/
*
* Given two words (beginWord and endWord), and a dictionary's word list,
* find all shortest transformation sequence(s) from beginWord to endWord, such that:
* - Only one letter can be changed at a time
* - Each transformed word must exist in the word list. Note that beginWord is not a transformed word.
*
* Note:
* - Return an empty list if there is no such transformation sequence.
* - All words have the same length.
* - All words contain only lowercase alphabetic characters.
* - You may assume no duplicates in the word list.
* - You may assume beginWord and endWord are non-empty and are not the same.
*/
class WordLadderTests {
@Test fun `some examples`() {
findLadders(beginWord = "hit", endWord = "cog", wordList = emptyList()) shouldEqual emptySet()
findLadders(
beginWord = "hit",
endWord = "cog",
wordList = listOf("hot", "dot", "dog", "lot", "log")
) shouldEqual emptySet()
findLadders(
beginWord = "hit",
endWord = "cog",
wordList = listOf("hot", "dot", "dog", "lot", "log", "cog")
) shouldEqual setOf(
listOf("hit", "hot", "dot", "dog", "cog"),
listOf("hit", "hot", "lot", "log", "cog")
)
}
}
private typealias Solution = List<String>
private fun findLadders(beginWord: String, endWord: String, wordList: List<String>): Set<Solution> {
val ladders = findAllLadders(beginWord, endWord, wordList)
val minSize = ladders.minByOrNull { it: Solution -> it.size }?.size ?: return emptySet()
return ladders.filterTo(HashSet()) { it.size == minSize }
}
private fun findAllLadders(beginWord: String, endWord: String, wordList: List<String>): Set<Solution> {
if (beginWord == endWord) return setOf(listOf(endWord))
val nextWords = wordList.filter { it.diff(beginWord) == 1 }
return nextWords
.flatMap { findLadders(it, endWord, wordList - it) }
.mapTo(HashSet()) { listOf(beginWord) + it }
}
private fun String.diff(that: String) =
zip(that).sumBy { if (it.first != it.second) 1 else 0 }
| unlicense | aee1bd8e14a58fd7c752e5a48c3dad40 | 36.533333 | 103 | 0.641652 | 3.626409 | false | false | false | false |
JesusM/FingerprintManager | kfingerprintmanager/src/main/kotlin/com/jesusm/kfingerprintmanager/base/FingerprintAssetsManager.kt | 1 | 4483 | package com.jesusm.kfingerprintmanager.base
import android.content.Context
import android.support.annotation.StringRes
import android.support.v4.hardware.fingerprint.FingerprintManagerCompat
import android.util.Log
import com.jesusm.kfingerprintmanager.KFingerprintManager
import com.jesusm.kfingerprintmanager.base.hardware.FingerprintHardware
import com.jesusm.kfingerprintmanager.base.keystore.KeyStoreManager
import com.jesusm.kfingerprintmanager.base.model.FingerprintErrorState
import java.security.NoSuchAlgorithmException
import javax.crypto.Cipher
import javax.crypto.NoSuchPaddingException
class FingerprintAssetsManager(val context: Context, val keyStoreAlias: String,
val fingerprintHardware: FingerprintHardware = FingerprintHardware(context),
val keyStoreManager: KeyStoreManager = KeyStoreManager(context)) {
private var cipher: Cipher? = null
var errorState: FingerprintErrorState? = null
fun initSecureDependencies(callback: KFingerprintManager.InitialisationCallback) {
initSecureDependenciesForDecryption(callback, null)
}
fun initSecureDependenciesForDecryption(callback: KFingerprintManager.InitialisationCallback,
IVs: ByteArray?) {
initSecureDependenciesWithIVs(callback, IVs)
}
private fun initSecureDependenciesWithIVs(callback: KFingerprintManager.InitialisationCallback,
IVs: ByteArray?) {
if (!isFingerprintAuthAvailable()) {
handleError(callback, FingerprintErrorState.FINGERPRINT_NOT_AVAILABLE)
return
}
if (!keyStoreManager.isFingerprintEnrolled()) {
handleError(callback, FingerprintErrorState.FINGERPRINT_NOT_ENROLLED)
return
}
try {
if (IVs == null) {
cipher = keyStoreManager.initDefaultCipher(keyStoreAlias)
} else {
cipher = keyStoreManager.initCipherForDecryption(keyStoreAlias, IVs)
}
} catch (e: KeyStoreManager.NewFingerprintEnrolledException) {
handleError(callback, FingerprintErrorState.NEW_FINGERPRINT_ENROLLED)
return
} catch (e: NoSuchPaddingException) {
handleError(callback, FingerprintErrorState.FINGERPRINT_INITIALISATION_ERROR)
return
} catch (e: NoSuchAlgorithmException) {
handleError(callback, FingerprintErrorState.FINGERPRINT_INITIALISATION_ERROR)
return
} catch (e: KeyStoreManager.InitialisationException) {
handleError(callback, FingerprintErrorState.FINGERPRINT_INITIALISATION_ERROR)
return
}
val isCipherAvailable = cipher != null
if (isCipherAvailable) {
callback.onInitialisationSuccessfullyCompleted()
} else {
handleError(callback, FingerprintErrorState.FINGERPRINT_INITIALISATION_ERROR)
}
}
private fun handleError(callback: KFingerprintManager.InitialisationCallback,
errorState: FingerprintErrorState) {
this.errorState = errorState
logError(errorState.errorMessage)
when (errorState) {
FingerprintErrorState.FINGERPRINT_NOT_AVAILABLE -> callback.onFingerprintNotAvailable()
FingerprintErrorState.FINGERPRINT_INITIALISATION_ERROR -> callback.onErrorFingerprintNotInitialised()
FingerprintErrorState.LOCK_SCREEN_RESET_OR_DISABLED, FingerprintErrorState.FINGERPRINT_NOT_ENROLLED -> callback.onErrorFingerprintNotEnrolled()
else -> callback.onErrorFingerprintNotInitialised()
}
}
private fun isFingerprintAuthAvailable(): Boolean = fingerprintHardware.isFingerprintAuthAvailable()
fun createKey(invalidatedByBiometricEnrollment: Boolean) {
try {
keyStoreManager.createKey(keyStoreAlias, invalidatedByBiometricEnrollment)
} catch (e: KeyStoreManager.InitialisationException) {
logError(e.message)
}
}
private fun logError(@StringRes message: Int) {
if (message != -1) {
logError(context.getString(message))
}
}
private fun logError(message: String?) {
Log.e(javaClass.simpleName, message)
}
fun getCryptoObject(): FingerprintManagerCompat.CryptoObject {
return FingerprintManagerCompat.CryptoObject(cipher)
}
} | mit | 42dc093610f0e1f7dbb95904a0634c53 | 40.906542 | 155 | 0.695516 | 5.420798 | false | false | false | false |
tateisu/SubwayTooter | colorpicker/src/main/java/com/jrummyapps/android/colorpicker/ColorPickerDialog.kt | 1 | 27593 | /*
* Copyright (C) 2017 JRummy Apps 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.jrummyapps.android.colorpicker
import android.annotation.SuppressLint
import android.app.Activity
import android.app.Dialog
import android.content.Context
import android.content.DialogInterface
import android.graphics.Color
import android.graphics.PorterDuff
import android.os.Bundle
import android.text.Editable
import android.text.InputFilter
import android.text.InputFilter.LengthFilter
import android.text.TextWatcher
import android.util.TypedValue
import android.view.MotionEvent
import android.view.View
import android.view.View.OnTouchListener
import android.view.ViewGroup.MarginLayoutParams
import android.view.WindowManager
import android.view.inputmethod.InputMethodManager
import android.widget.*
import android.widget.SeekBar.OnSeekBarChangeListener
import androidx.annotation.ColorInt
import androidx.annotation.IntDef
import androidx.annotation.StringRes
import androidx.appcompat.app.AlertDialog
import androidx.core.graphics.ColorUtils
import androidx.fragment.app.DialogFragment
import androidx.fragment.app.FragmentActivity
import com.jrummyapps.android.colorpicker.ColorPickerView.OnColorChangedListener
import java.util.*
import kotlin.math.roundToInt
/**
*
* A dialog to pick a color.
*
*
* The [activity][Activity] that shows this dialog should implement [ColorPickerDialogListener]
*
*
* Example usage:
*
* <pre>
* ColorPickerDialog.newBuilder().show(activity);
</pre> *
*/
class ColorPickerDialog :
DialogFragment(),
OnTouchListener,
OnColorChangedListener,
TextWatcher {
companion object {
private const val ARG_ID = "id"
private const val ARG_TYPE = "dialogType"
private const val ARG_COLOR = "color"
private const val ARG_ALPHA = "alpha"
private const val ARG_PRESETS = "presets"
private const val ARG_ALLOW_PRESETS = "allowPresets"
private const val ARG_ALLOW_CUSTOM = "allowCustom"
private const val ARG_DIALOG_TITLE = "dialogTitle"
private const val ARG_SHOW_COLOR_SHADES = "showColorShades"
private const val ARG_COLOR_SHAPE = "colorShape"
const val TYPE_CUSTOM = 0
const val TYPE_PRESETS = 1
const val ALPHA_THRESHOLD = 165
/**
* Material design colors used as the default color presets
*/
@JvmField
val MATERIAL_COLORS = intArrayOf(
-0xbbcca, // RED 500
-0x16e19d, // PINK 500
-0xd36d, // LIGHT PINK 500
-0x63d850, // PURPLE 500
-0x98c549, // DEEP PURPLE 500
-0xc0ae4b, // INDIGO 500
-0xde690d, // BLUE 500
-0xfc560c, // LIGHT BLUE 500
-0xff432c, // CYAN 500
-0xff6978, // TEAL 500
-0xb350b0, // GREEN 500
-0x743cb6, // LIGHT GREEN 500
-0x3223c7, // LIME 500
-0x14c5, // YELLOW 500
-0x3ef9, // AMBER 500
-0x6800, // ORANGE 500
-0x86aab8, // BROWN 500
-0x9f8275, // BLUE GREY 500
-0x616162
)
/**
* Create a new Builder for creating a [ColorPickerDialog] instance
*
* @return The [builder][Builder] to create the [ColorPickerDialog].
*/
@JvmStatic
fun newBuilder(): Builder {
return Builder()
}
fun unshiftIfNotExists(array: IntArray, value: Int): IntArray {
if (array.any { it == value }) {
return array
}
val newArray = IntArray(array.size + 1)
newArray[0] = value
System.arraycopy(array, 0, newArray, 1, newArray.size - 1)
return newArray
}
fun pushIfNotExists(array: IntArray, value: Int): IntArray {
if (array.any { it == value }) {
return array
}
val newArray = IntArray(array.size + 1)
newArray[newArray.size - 1] = value
System.arraycopy(array, 0, newArray, 0, newArray.size - 1)
return newArray
}
}
@Retention(AnnotationRetention.SOURCE)
@IntDef(TYPE_CUSTOM, TYPE_PRESETS)
annotation class DialogType
var colorPickerDialogListener: ColorPickerDialogListener? = null
var presets: IntArray = MATERIAL_COLORS
private var rootView: FrameLayout? = null
@ColorInt
var color = 0
private var dialogType = 0
var dialogId = 0
var showColorShades = false
private var colorShape = 0
// -- PRESETS --------------------------
internal var adapter: ColorPaletteAdapter? = null
private var shadesLayout: LinearLayout? = null
private var transparencySeekBar: SeekBar? = null
private var transparencyPercText: TextView? = null
// -- CUSTOM ---------------------------
var colorPicker: ColorPickerView? = null
private var newColorPanel: ColorPanelView? = null
private var hexEditText: EditText? = null
private var showAlphaSlider = false
private var fromEditText = false
private val selectedItemPosition: Int
get() = presets.indexOf(color)
override fun onAttach(context: Context) {
super.onAttach(context)
if (colorPickerDialogListener == null && context is ColorPickerDialogListener) {
colorPickerDialogListener = context
}
}
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
val args = arguments ?: error("onCreateDialog: args is null")
val activity = activity ?: error("onCreateDialog: activity is null")
dialogId = args.getInt(ARG_ID)
showAlphaSlider = args.getBoolean(ARG_ALPHA)
showColorShades = args.getBoolean(ARG_SHOW_COLOR_SHADES)
colorShape = args.getInt(ARG_COLOR_SHAPE)
if (savedInstanceState == null) {
color = args.getInt(ARG_COLOR)
dialogType = args.getInt(ARG_TYPE)
} else {
color = savedInstanceState.getInt(ARG_COLOR)
dialogType = savedInstanceState.getInt(ARG_TYPE)
}
val rootView = FrameLayout(activity).also { this.rootView = it }
when (dialogType) {
TYPE_CUSTOM -> rootView.addView(createPickerView())
TYPE_PRESETS -> rootView.addView(createPresetsView())
}
val builder = AlertDialog.Builder(activity)
.setView(rootView)
.setPositiveButton(R.string.cpv_select) { _, _ ->
colorPickerDialogListener?.onColorSelected(dialogId, color)
}
val dialogTitleStringRes = args.getInt(ARG_DIALOG_TITLE)
if (dialogTitleStringRes != 0) {
builder.setTitle(dialogTitleStringRes)
}
val neutralButtonStringRes: Int
neutralButtonStringRes =
if (dialogType == TYPE_CUSTOM && args.getBoolean(ARG_ALLOW_PRESETS)) {
R.string.cpv_presets
} else if (dialogType == TYPE_PRESETS && args.getBoolean(ARG_ALLOW_CUSTOM)) {
R.string.cpv_custom
} else {
0
}
if (neutralButtonStringRes != 0) {
builder.setNeutralButton(neutralButtonStringRes, null)
}
return builder.create()
}
override fun onStart() {
super.onStart()
val dialog = dialog as AlertDialog
// http://stackoverflow.com/a/16972670/1048340
dialog.window?.clearFlags(
WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE or
WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM
)
dialog.window?.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE)
// Do not dismiss the dialog when clicking the neutral button.
val neutralButton = dialog.getButton(AlertDialog.BUTTON_NEUTRAL)
neutralButton?.setOnClickListener { v: View ->
rootView!!.removeAllViews()
when (dialogType) {
TYPE_CUSTOM -> {
dialogType = TYPE_PRESETS
(v as Button).setText(R.string.cpv_custom)
rootView!!.addView(createPresetsView())
}
TYPE_PRESETS -> {
dialogType = TYPE_CUSTOM
(v as Button).setText(R.string.cpv_presets)
rootView!!.addView(createPickerView())
}
}
}
}
override fun onDismiss(dialog: DialogInterface) {
super.onDismiss(dialog)
colorPickerDialogListener!!.onDialogDismissed(dialogId)
}
override fun onSaveInstanceState(outState: Bundle) {
outState.putInt(ARG_COLOR, color)
outState.putInt(ARG_TYPE, dialogType)
super.onSaveInstanceState(outState)
}
// region Custom Picker
private fun createPickerView(): View {
val args = arguments ?: throw RuntimeException("createPickerView: args is null")
val activity = activity ?: throw RuntimeException("createPickerView: activity is null")
val contentView = View.inflate(getActivity(), R.layout.cpv_dialog_color_picker, null)
colorPicker = contentView.findViewById(R.id.cpv_color_picker_view)
val oldColorPanel: ColorPanelView = contentView.findViewById(R.id.cpv_color_panel_old)
newColorPanel = contentView.findViewById(R.id.cpv_color_panel_new)
val arrowRight = contentView.findViewById<ImageView>(R.id.cpv_arrow_right)
hexEditText = contentView.findViewById(R.id.cpv_hex)
try {
val value = TypedValue()
val typedArray = activity.obtainStyledAttributes(
value.data, intArrayOf(android.R.attr.textColorPrimary)
)
val arrowColor = typedArray.getColor(0, Color.BLACK)
typedArray.recycle()
arrowRight.setColorFilter(arrowColor)
} catch (ignored: Exception) {
}
oldColorPanel.color = args.getInt(ARG_COLOR)
val c = color
colorPicker?.apply {
setAlphaSliderVisible(showAlphaSlider)
setColor(c, true)
onColorChangedListener = this@ColorPickerDialog
}
newColorPanel?.apply {
color = c
setOnClickListener {
if (color == c) {
colorPickerDialogListener?.onColorSelected(dialogId, color)
dismiss()
}
}
}
hexEditText?.apply {
setHex(color)
addTextChangedListener(this@ColorPickerDialog)
setOnFocusChangeListener { _, hasFocus ->
if (hasFocus) showSoftInput(true)
}
if (!showAlphaSlider) {
filters = arrayOf<InputFilter>(LengthFilter(6))
}
}
contentView.setOnTouchListener(this)
return contentView
}
private fun View?.showSoftInput(show: Boolean) {
this ?: return
val imm = (activity?.getSystemService(Context.INPUT_METHOD_SERVICE) as? InputMethodManager)
?: return
if (show) {
imm.showSoftInput(this, InputMethodManager.SHOW_IMPLICIT)
} else {
imm.hideSoftInputFromWindow(this.windowToken, 0)
}
}
@SuppressLint("ClickableViewAccessibility")
override fun onTouch(v: View, event: MotionEvent): Boolean {
val hexEditText = this.hexEditText
if (hexEditText?.hasFocus() == true && v !== hexEditText) {
hexEditText.clearFocus()
hexEditText.showSoftInput(false)
hexEditText.clearFocus()
return true
}
return false
}
override fun onColorChanged(newColor: Int) {
color = newColor
newColorPanel!!.color = newColor
if (!fromEditText) {
setHex(newColor)
val hexEditText = this.hexEditText
if (hexEditText?.hasFocus() == true) {
hexEditText.showSoftInput(false)
hexEditText.clearFocus()
}
}
fromEditText = false
}
override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {}
override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {}
override fun afterTextChanged(s: Editable) {
if (hexEditText!!.isFocused) {
try {
val color = parseColorString(s.toString())
if (color != colorPicker!!.color) {
fromEditText = true
colorPicker!!.setColor(color, true)
}
} catch (ex: NumberFormatException) {
// nothing to do
}
}
}
private fun setHex(color: Int) {
if (showAlphaSlider) {
hexEditText!!.setText(String.format("%08X", color))
} else {
hexEditText!!.setText(String.format("%06X", 0xFFFFFF and color))
}
}
// -- endregion --
// region Presets Picker
private fun createPresetsView(): View {
val contentView = View.inflate(activity, R.layout.cpv_dialog_presets, null)
shadesLayout = contentView.findViewById(R.id.shades_layout)
transparencySeekBar = contentView.findViewById(R.id.transparency_seekbar)
transparencyPercText = contentView.findViewById(R.id.transparency_text)
val gridView = contentView.findViewById<GridView>(R.id.gridView)
loadPresets()
if (showColorShades) {
createColorShades(color)
} else {
shadesLayout?.visibility = View.GONE
contentView.findViewById<View>(R.id.shades_divider).visibility = View.GONE
}
adapter = ColorPaletteAdapter(presets, selectedItemPosition, colorShape){
when(it){
color -> {
colorPickerDialogListener?.onColorSelected(dialogId, color)
dismiss()
}
else ->{
color = it
if (showColorShades) {
createColorShades(color)
}
}
}
}
gridView.adapter = adapter
if (showAlphaSlider) {
setupTransparency()
} else {
contentView.findViewById<View>(R.id.transparency_layout).visibility = View.GONE
contentView.findViewById<View>(R.id.transparency_title).visibility = View.GONE
}
return contentView
}
private fun loadPresets() {
presets = arguments?.getIntArray(ARG_PRESETS) ?: MATERIAL_COLORS
presets = presets.copyOf()
val isMaterialColors = presets.contentEquals(MATERIAL_COLORS)
val alpha = Color.alpha(color)
// don't update the original array when modifying alpha
if (alpha != 255) {
// add alpha to the presets
for (i in presets.indices) {
val color = presets[i]
val red = Color.red(color)
val green = Color.green(color)
val blue = Color.blue(color)
presets[i] = Color.argb(alpha, red, green, blue)
}
}
presets = unshiftIfNotExists(presets, color)
if (isMaterialColors && presets.size == 19) {
// Add black to have a total of 20 colors if the current color is in the material color palette
presets = pushIfNotExists(presets, Color.argb(alpha, 0, 0, 0))
}
}
private fun createColorShades(@ColorInt color: Int) {
val colorShades = getColorShades(color)
if (shadesLayout!!.childCount != 0) {
for (i in 0 until shadesLayout!!.childCount) {
val layout = shadesLayout!!.getChildAt(i) as FrameLayout
val cpv: ColorPanelView = layout.findViewById(R.id.cpv_color_panel_view)
val iv = layout.findViewById<ImageView>(R.id.cpv_color_image_view)
cpv.color = colorShades[i]
cpv.tag = false
iv.setImageDrawable(null)
}
return
}
val horizontalPadding = resources
.getDimensionPixelSize(R.dimen.cpv_item_horizontal_padding)
for (colorShade in colorShades) {
var layoutResId: Int
layoutResId = if (colorShape == ColorShape.SQUARE) {
R.layout.cpv_color_item_square
} else {
R.layout.cpv_color_item_circle
}
val view = View.inflate(activity, layoutResId, null)
val colorPanelView: ColorPanelView = view.findViewById(R.id.cpv_color_panel_view)
val params = colorPanelView
.layoutParams as MarginLayoutParams
params.rightMargin = horizontalPadding
params.leftMargin = params.rightMargin
colorPanelView.layoutParams = params
colorPanelView.color = colorShade
shadesLayout!!.addView(view)
colorPanelView.post {
// The color is black when rotating the dialog. This is a dirty fix. WTF!?
colorPanelView.color = colorShade
}
colorPanelView.setOnClickListener { v: View ->
if (v.tag is Boolean && v.tag as Boolean) {
colorPickerDialogListener!!.onColorSelected(
dialogId,
[email protected]
)
dismiss()
return@setOnClickListener // already selected
}
[email protected] = colorPanelView.color
adapter!!.selectNone()
for (i in 0 until shadesLayout!!.childCount) {
val layout = shadesLayout!!.getChildAt(i) as FrameLayout
val cpv: ColorPanelView = layout.findViewById(R.id.cpv_color_panel_view)
val iv = layout.findViewById<ImageView>(R.id.cpv_color_image_view)
iv.setImageResource(if (cpv === v) R.drawable.cpv_preset_checked else 0)
if (cpv === v && ColorUtils.calculateLuminance(cpv.color) >= 0.65 ||
Color.alpha(cpv.color) <= ALPHA_THRESHOLD
) {
iv.setColorFilter(Color.BLACK, PorterDuff.Mode.SRC_IN)
} else {
iv.colorFilter = null
}
cpv.tag = cpv === v
}
}
colorPanelView.setOnLongClickListener {
colorPanelView.showHint()
true
}
}
}
private fun shadeColor(@ColorInt color: Int, percent: Double): Int {
val hex = String.format("#%06X", 0xFFFFFF and color)
val f = hex.substring(1).toLong(16)
val t = (if (percent < 0) 0 else 255).toDouble()
val p = if (percent < 0) percent * -1 else percent
val R = f shr 16
val G = f shr 8 and 0x00FF
val B = f and 0x0000FF
return Color.argb(
Color.alpha(color),
((t - R) * p).roundToInt() + R.toInt(),
((t - G) * p).roundToInt() + G.toInt(),
((t - B) * p).roundToInt() + B.toInt(),
)
}
private fun getColorShades(@ColorInt color: Int): IntArray {
return intArrayOf(
shadeColor(color, 0.9),
shadeColor(color, 0.7),
shadeColor(color, 0.5),
shadeColor(color, 0.333),
shadeColor(color, 0.166),
shadeColor(color, -0.125),
shadeColor(color, -0.25),
shadeColor(color, -0.375),
shadeColor(color, -0.5),
shadeColor(color, -0.675),
shadeColor(color, -0.7),
shadeColor(color, -0.775)
)
}
private fun setupTransparency() {
val transparency = 255 - Color.alpha(color)
val percentage = (transparency.toDouble() * 100 / 255).toInt()
transparencyPercText?.text =
String.format(Locale.ENGLISH, "%d%%", percentage)
transparencySeekBar?.apply {
max = 255
progress = transparency
this.setOnSeekBarChangeListener(object : OnSeekBarChangeListener {
override fun onStartTrackingTouch(seekBar: SeekBar) {}
override fun onStopTrackingTouch(seekBar: SeekBar) {}
override fun onProgressChanged(seekBar: SeekBar, progress: Int, fromUser: Boolean) {
handleTransparencyChanged(progress)
}
})
}
}
private fun handleTransparencyChanged(transparency: Int) {
val percentage = (transparency.toDouble() * 100 / 255).toInt()
val alpha = 255 - transparency
transparencyPercText?.text =
String.format(Locale.ENGLISH, "%d%%", percentage)
// update color:
val red = Color.red(color)
val green = Color.green(color)
val blue = Color.blue(color)
color = Color.argb(alpha, red, green, blue)
// update items in GridView:
adapter?.apply {
for (i in colors.indices) {
val color = colors[i]
colors[i] = Color.argb(
alpha,
Color.red(color),
Color.green(color),
Color.blue(color)
)
}
notifyDataSetChanged()
}
// update shades:
shadesLayout?.apply {
for (i in 0 until childCount) {
val layout = getChildAt(i) as FrameLayout
val cpv: ColorPanelView = layout.findViewById(R.id.cpv_color_panel_view)
val iv = layout.findViewById<ImageView>(R.id.cpv_color_image_view)
if (layout.tag == null) {
// save the original border color
layout.tag = cpv.borderColor
}
var color = cpv.color
color = Color.argb(
alpha,
Color.red(color),
Color.green(color),
Color.blue(color)
)
if (alpha <= ALPHA_THRESHOLD) {
cpv.borderColor = color or -0x1000000
} else {
cpv.borderColor = layout.tag as Int
}
if (cpv.tag != null && cpv.tag as Boolean) {
// The alpha changed on the selected shaded color. Update the checkmark color filter.
if (alpha <= ALPHA_THRESHOLD) {
iv.setColorFilter(Color.BLACK, PorterDuff.Mode.SRC_IN)
} else {
if (ColorUtils.calculateLuminance(color) >= 0.65) {
iv.setColorFilter(Color.BLACK, PorterDuff.Mode.SRC_IN)
} else {
iv.setColorFilter(Color.WHITE, PorterDuff.Mode.SRC_IN)
}
}
}
cpv.color = color
}
}
}
@Suppress("MemberVisibilityCanBePrivate")
class Builder(
// dialog title string resource id.
@StringRes
var dialogTitle: Int = R.string.cpv_default_title,
// which dialog view to show.
// Either [ColorPickerDialog.TYPE_CUSTOM] or [ColorPickerDialog.TYPE_PRESETS].
var dialogType: Int = TYPE_PRESETS,
// the colors used for the presets.
var presets: IntArray = MATERIAL_COLORS,
// the original color.
@ColorInt
var color: Int = Color.BLACK,
// the dialog id used for callbacks.
var dialogId: Int = 0,
// the alpha slider
// true to show the alpha slider.
// Currently only supported with the ColorPickerView.
var showAlphaSlider: Boolean = false,
// Show/Hide a neutral button to select preset colors.
// false to disable showing the presets button.
var allowPresets: Boolean = true,
// Show/Hide the neutral button to select a custom color.
// false to disable showing the custom button.
var allowCustom: Boolean = true,
// Show/Hide the color shades in the presets picker
// false to hide the color shades.
var showColorShades: Boolean = true,
// the shape of the color panel view.
// Either [ColorShape.CIRCLE] or [ColorShape.SQUARE].
var colorShape: Int = ColorShape.CIRCLE,
) {
fun setDialogTitle(@StringRes dialogTitle: Int): Builder {
this.dialogTitle = dialogTitle
return this
}
fun setDialogType(@DialogType dialogType: Int): Builder {
this.dialogType = dialogType
return this
}
fun setPresets(presets: IntArray): Builder {
this.presets = presets
return this
}
fun setColor(color: Int): Builder {
this.color = color
return this
}
fun setDialogId(dialogId: Int): Builder {
this.dialogId = dialogId
return this
}
fun setShowAlphaSlider(showAlphaSlider: Boolean): Builder {
this.showAlphaSlider = showAlphaSlider
return this
}
fun setAllowPresets(allowPresets: Boolean): Builder {
this.allowPresets = allowPresets
return this
}
fun setAllowCustom(allowCustom: Boolean): Builder {
this.allowCustom = allowCustom
return this
}
fun setShowColorShades(showColorShades: Boolean): Builder {
this.showColorShades = showColorShades
return this
}
fun setColorShape(colorShape: Int): Builder {
this.colorShape = colorShape
return this
}
/**
* Create the [ColorPickerDialog] instance.
*/
fun create(): ColorPickerDialog {
val dialog = ColorPickerDialog()
val args = Bundle()
args.putInt(ARG_ID, dialogId)
args.putInt(ARG_TYPE, dialogType)
args.putInt(ARG_COLOR, color)
args.putIntArray(ARG_PRESETS, presets)
args.putBoolean(ARG_ALPHA, showAlphaSlider)
args.putBoolean(ARG_ALLOW_CUSTOM, allowCustom)
args.putBoolean(ARG_ALLOW_PRESETS, allowPresets)
args.putInt(ARG_DIALOG_TITLE, dialogTitle)
args.putBoolean(ARG_SHOW_COLOR_SHADES, showColorShades)
args.putInt(ARG_COLOR_SHAPE, colorShape)
dialog.arguments = args
return dialog
}
/**
* Create and show the [ColorPickerDialog] created with this builder.
*/
fun show(activity: FragmentActivity) {
create().show(activity.supportFragmentManager, "color-picker-dialog")
}
}
}
| apache-2.0 | 726da8fe1fe1868d21184d860a182f7f | 35.306579 | 107 | 0.577103 | 4.729688 | false | false | false | false |
Killian-LeClainche/Java-Base-Application-Engine | src/polaris/okapi/options/Settings.kt | 1 | 11488 | package polaris.okapi.options
import org.joml.Vector2d
import org.lwjgl.glfw.*
import org.lwjgl.glfw.GLFW.*
import org.lwjgl.stb.STBImage.stbi_failure_reason
import org.lwjgl.stb.STBImage.stbi_load
import org.lwjgl.system.MemoryStack.stackPush
import polaris.okapi.SCALE_TO_HEIGHT
import polaris.okapi.SCALE_TO_WIDTH
import java.io.File
import java.io.FileInputStream
import java.io.FileOutputStream
import java.util.*
import kotlin.collections.ArrayList
/**
* Created by Killian Le Clainche on 12/10/2017.
*/
class Settings {
var window: Long = 0L
val keyboardMapping = HashMap<Int, Key>()
val mouseMapping = HashMap<Int, Key>()
val mouse: Vector2d = Vector2d(0.0)
val mouseDelta: Vector2d = Vector2d(0.0)
val scrollDelta: Vector2d = Vector2d(0.0)
private val textInput: StringBuilder = StringBuilder()
val inputText: String
get() = textInput.toString()
/**
* @return
*/
var monitor: Monitor? = null
private set
get() {
if(field == null)
field = getMonitor(glfwGetPrimaryMonitor())
return field
}
/**
* @return
*/
var windowMode: WindowMode = WindowMode.WINDOWED
set(value) {
if(field != value) {
field = value
updateWindow = true
}
}
var updateWindow: Boolean = false
private set
get() {
val shouldUpdate = field
field = false
return shouldUpdate
}
var windowPosX: Int = -1
get() {
if (field == -1 && monitor != null) field = (monitor!!.videoMode.width() - windowWidth) / 2
return field
}
var windowPosY: Int = -1
get() {
if (field == -1 && monitor != null) field = (monitor!!.videoMode.height() - windowHeight) / 2
return field
}
var windowWidth: Int = -1
get() {
if(field == -1 && monitor != null) field = monitor!!.videoMode.width() / 2
return field
}
var windowHeight: Int = -1
get() {
if(field == -1 && monitor != null) field = monitor!!.videoMode.height() / 2
return field
}
var windowMaximized: Boolean = false
var enableVsync: Boolean = true
var alcRefreshRate: Int = 60
var alcSync: Boolean = false
var settings: MutableMap<String, Setting> = HashMap()
var controllers: MutableMap<Int, Controller> = HashMap()
var title: String = ""
operator fun get(property : String): Setting? {
return settings[property]
}
operator fun set(property : String, value : Setting) {
if(value is Key) {
if(value.key in GLFW_MOUSE_BUTTON_1..GLFW_MOUSE_BUTTON_LAST)
mouseMapping.put(value.key, value)
else
keyboardMapping.put(value.key, value)
}
if(value is Controller) {
controllers.put(value.id, value)
}
settings[property] = value
}
operator fun set(property : String, value : String) {
settings[property] = StringSetting(value)
}
operator fun set(property : String, value : Int) {
settings[property] = IntSetting(value)
}
operator fun set(property : String, value : Double) {
settings[property] = DoubleSetting(value)
}
fun load() {
(GLFW_MOUSE_BUTTON_1..GLFW_MOUSE_BUTTON_LAST)
.filterNot { mouseMapping.containsKey(it) }
.forEach { mouseMapping.put(it, Key(it)) }
val settingsFile = File("settings.prop")
if(!settingsFile.createNewFile()) {
val properties = Properties()
properties.load(FileInputStream(settingsFile))
properties.forEach {
val value = it.value.toString()
when (it.key) {
"enableVsync" -> if(enableVsync) enableVsync = value.toBoolean()
"alcRefreshRate" -> if(alcRefreshRate == 60) alcRefreshRate = value.toInt()
"alcSync" -> if(!alcSync) alcSync = value.toBoolean()
"monitor" -> settings["monitor"] = LongSetting(value.toLong())
"windowMode" -> if(!updateWindow) windowMode = WindowMode.valueOf(value.toInt())
"windowPosX" -> windowPosX = value.toInt()
"windowPosY" -> windowPosY = value.toInt()
"windowWidth" -> windowWidth = value.toInt()
"windowHeight" -> windowHeight = value.toInt()
"windowMaximized" -> windowMaximized = value.toBoolean()
settings.containsKey(it.key) -> settings[it.key as String]!!.load(value)
}
}
}
}
fun save() {
val properties = Properties()
properties["enableVsync"] = enableVsync.toString()
properties["alcRefreshRate"] = alcRefreshRate.toString()
properties["alcSync"] = alcSync.toString()
if(monitor != null)
properties["monitor"] = "${monitor!!.instance}"
properties["windowMode"] = WindowMode.valueOf(windowMode).toString()
properties["windowPosX"] = windowPosX.toString()
properties["windowPosY"] = windowPosY.toString()
properties["windowWidth"] = windowWidth.toString()
properties["windowHeight"] = windowHeight.toString()
properties["windowMaximized"] = windowMaximized.toString()
settings.filterNot { properties.containsKey(it.key) }
.forEach { properties[it.key] = it.value.save() }
settings.forEach {
if(!properties.containsKey(it.key)) {
properties[it.key] = it.value.save()
}
}
val settingsFile = File("settings.prop")
settingsFile.createNewFile()
val settingsIO = FileOutputStream(settingsFile)
properties.store(settingsIO, "Current settings for, it is not recommended to alter the values here")
settingsIO.close()
}
fun init(instance: Long) {
window = instance
if(enableVsync)
glfwSwapInterval(1)
else
glfwSwapInterval(0)
stackPush().use({ stack ->
val width = stack.callocInt(1)
val height = stack.callocInt(1)
glfwGetFramebufferSize(window, width, height)
windowWidth = width[0]
windowHeight = height[0]
})
monitor = getMonitor(glfwGetPrimaryMonitor())
if(settings["icon"] != null) {
val icon = GLFWImage.malloc(1)
stackPush().use {
val w = it.mallocInt(1)
val h = it.mallocInt(1)
val comp = it.mallocInt(1)
val image = stbi_load((settings["icon"] as StringSetting).value, w, h, comp, 4)
if(image === null) {
System.err.println("Could not load icon!")
System.err.println(stbi_failure_reason())
}
else {
icon[0].set(w[0], h[0], image)
}
}
glfwSetWindowIcon(window, icon)
}
glfwSetFramebufferSizeCallback(window, GLFWFramebufferSizeCallback.create { _, _, _ ->
stackPush().use({ stack ->
val width = stack.callocInt(1)
val height = stack.callocInt(1)
glfwGetWindowSize(window, width, height)
windowWidth = width[0]
windowHeight = height[0]
})
})
glfwSetWindowPosCallback(window, GLFWWindowPosCallback.create { _, _posX, _posY ->
windowPosX = _posX
windowPosY = _posY
})
glfwSetWindowMaximizeCallback(window, GLFWWindowMaximizeCallback.create { _, _maximized ->
windowMaximized = _maximized
if(!_maximized) {
val width = monitor!!.videoMode.width()
val height = monitor!!.videoMode.height()
windowWidth = width / 2
windowHeight = height / 2
windowPosX = monitor!!.posX + width / 4
windowPosY = monitor!!.posY + height / 4
glfwSetWindowSize(window, windowWidth, windowHeight)
glfwSetWindowPos(window, windowPosX, windowPosY)
}
})
glfwSetCursorPosCallback(window, GLFWCursorPosCallback.create { _, xpos, ypos ->
val xposAdjusted = (xpos/ windowWidth) * SCALE_TO_WIDTH
val yposAdjusted = (ypos / windowHeight) * SCALE_TO_HEIGHT
mouseDelta.set(mouse.sub(xposAdjusted, yposAdjusted))
mouse.set(xposAdjusted, yposAdjusted)
})
glfwSetMouseButtonCallback(window, GLFWMouseButtonCallback.create { _, button, action, _ ->
if(button != -1) {
val mouseKey = mouseMapping[button]
if (action == GLFW_PRESS)
mouseKey?.press()
else if (action == GLFW_RELEASE)
mouseKey?.release()
}
})
glfwSetScrollCallback(window, GLFWScrollCallback.create { _, xoffset, yoffset -> scrollDelta.add(xoffset, yoffset) })
glfwSetKeyCallback(window, GLFWKeyCallback.create { _, key, _, action, _ ->
if (key != -1) {
val keyboardKey = keyboardMapping[key]
if (action == GLFW_PRESS)
keyboardKey?.press()
else if (action == GLFW_RELEASE)
keyboardKey?.release()
}
})
glfwSetCharCallback(window, GLFWCharCallback.create { _, codepoint -> textInput.append(codepoint.toChar()) })
}
fun update() {
textInput.setLength(0)
mouseDelta.set(0.0)
scrollDelta.set(0.0)
for(i in controllers.values) {
i.update();
}
for(i in settings.values) {
(i as? Key)?.update()
}
}
fun poll() {
}
fun setCursorMode(windowInstance: Long, mode: Int) {
glfwSetInputMode(windowInstance, GLFW_CURSOR, mode)
}
companion object {
private var staticInitialized = false
private var monitorList: MutableList<Monitor> = ArrayList()
fun init() {
if(staticInitialized) return
staticInitialized = true
glfwSetMonitorCallback(GLFWMonitorCallback.create { monitor, event ->
if (event == GLFW_CONNECTED) {
val monitorObject = createMonitor(monitor)
if(monitorObject != null)
monitorList.add(monitorObject)
}
else
monitorList = monitorList.filterNot { it.instance == monitor }.toMutableList()
})
val buffer = glfwGetMonitors()
if(buffer != null)
(0 until buffer.capacity()).forEach {
val monitorObject = createMonitor(buffer.get(it))
if(monitorObject != null)
monitorList.add(monitorObject)
}
}
fun hasMonitors() : Boolean = monitorList.isNotEmpty()
fun getMonitor(index: Int) : Monitor = monitorList[index]
fun getMonitor(instance: Long): Monitor? = monitorList.singleOrNull { it.instance == instance }
}
}
| gpl-2.0 | 872e5b398b33e7c228236412da0302c8 | 29.88172 | 125 | 0.553795 | 4.573248 | false | false | false | false |
tateisu/SubwayTooter | app/src/main/java/jp/juggler/subwaytooter/api/ApiPath.kt | 1 | 2919 | package jp.juggler.subwaytooter.api
object ApiPath {
const val READ_LIMIT = 80 // API側の上限が80です。ただし指定しても40しか返ってこないことが多い
// ステータスのリストを返すAPI
const val PATH_DIRECT_MESSAGES = "/api/v1/timelines/direct?limit=$READ_LIMIT"
const val PATH_DIRECT_MESSAGES2 = "/api/v1/conversations?limit=$READ_LIMIT"
const val PATH_FAVOURITES = "/api/v1/favourites?limit=$READ_LIMIT"
const val PATH_BOOKMARKS = "/api/v1/bookmarks?limit=$READ_LIMIT"
const val PATH_REACTIONS = "/api/v1/emoji_reactions?limit=$READ_LIMIT"
// アカウントのリストを返すAPI
const val PATH_ACCOUNT_FOLLOWING =
"/api/v1/accounts/%s/following?limit=$READ_LIMIT" // 1:account_id
const val PATH_ACCOUNT_FOLLOWERS =
"/api/v1/accounts/%s/followers?limit=$READ_LIMIT" // 1:account_id
const val PATH_MUTES = "/api/v1/mutes?limit=$READ_LIMIT"
const val PATH_BLOCKS = "/api/v1/blocks?limit=$READ_LIMIT"
const val PATH_FOLLOW_REQUESTS = "/api/v1/follow_requests?limit=$READ_LIMIT"
const val PATH_FOLLOW_SUGGESTION = "/api/v1/suggestions?limit=$READ_LIMIT"
const val PATH_FOLLOW_SUGGESTION2 = "/api/v2/suggestions?limit=$READ_LIMIT"
const val PATH_ENDORSEMENT = "/api/v1/endorsements?limit=$READ_LIMIT"
const val PATH_PROFILE_DIRECTORY = "/api/v1/directory?limit=$READ_LIMIT"
const val PATH_BOOSTED_BY =
"/api/v1/statuses/%s/reblogged_by?limit=$READ_LIMIT" // 1:status_id
const val PATH_FAVOURITED_BY =
"/api/v1/statuses/%s/favourited_by?limit=$READ_LIMIT" // 1:status_id
const val PATH_LIST_MEMBER = "/api/v1/lists/%s/accounts?limit=$READ_LIMIT"
// 他のリストを返すAPI
const val PATH_REPORTS = "/api/v1/reports?limit=$READ_LIMIT"
const val PATH_NOTIFICATIONS = "/api/v1/notifications?limit=$READ_LIMIT"
const val PATH_DOMAIN_BLOCK = "/api/v1/domain_blocks?limit=$READ_LIMIT"
const val PATH_LIST_LIST = "/api/v1/lists?limit=$READ_LIMIT"
const val PATH_SCHEDULED_STATUSES = "/api/v1/scheduled_statuses?limit=$READ_LIMIT"
// リストではなくオブジェクトを返すAPI
const val PATH_STATUSES = "/api/v1/statuses/%s" // 1:status_id
const val PATH_FILTERS = "/api/v1/filters"
const val PATH_MISSKEY_PROFILE_FOLLOWING = "/api/users/following"
const val PATH_MISSKEY_PROFILE_FOLLOWERS = "/api/users/followers"
const val PATH_MISSKEY_PROFILE_STATUSES = "/api/users/notes"
const val PATH_MISSKEY_MUTES = "/api/mute/list"
const val PATH_MISSKEY_BLOCKS = "/api/blocking/list"
const val PATH_MISSKEY_FOLLOW_REQUESTS = "/api/following/requests/list"
const val PATH_MISSKEY_FOLLOW_SUGGESTION = "/api/users/recommendation"
const val PATH_MISSKEY_FAVORITES = "/api/i/favorites"
const val PATH_M544_REACTIONS = "/api/i/reactions"
}
| apache-2.0 | f9d17fd4ae0c9c0f69ba5489bde52d61 | 46.508772 | 86 | 0.689331 | 3.185484 | false | false | false | false |
awsdocs/aws-doc-sdk-examples | kotlin/services/iam/src/main/kotlin/com/kotlin/iam/DeletePolicy.kt | 1 | 1620 | // snippet-sourcedescription:[DeletePolicy.kt demonstrates how to delete a fixed policy with a provided policy name.]
// snippet-keyword:[AWS SDK for Kotlin]
// snippet-service:[Identity and Access Management (IAM)]
/*
Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
SPDX-License-Identifier: Apache-2.0
*/
package com.kotlin.iam
// snippet-start:[iam.kotlin.delete_policy.import]
import aws.sdk.kotlin.services.iam.IamClient
import aws.sdk.kotlin.services.iam.model.DeletePolicyRequest
import kotlin.system.exitProcess
// snippet-end:[iam.kotlin.delete_policy.import]
/**
Before running this Kotlin code example, set up your development environment,
including your credentials.
For more information, see the following documentation topic:
https://docs.aws.amazon.com/sdk-for-kotlin/latest/developer-guide/setup.html
*/
suspend fun main(args: Array<String>) {
val usage = """
Usage:
<policyARN>
Where:
policyARN - A policy ARN value to delete.
"""
if (args.size != 1) {
println(usage)
exitProcess(0)
}
val policyARN = args[0]
deleteIAMPolicy(policyARN)
}
// snippet-start:[iam.kotlin.delete_policy.main]
suspend fun deleteIAMPolicy(policyARNVal: String?) {
val request = DeletePolicyRequest {
policyArn = policyARNVal
}
IamClient { region = "AWS_GLOBAL" }.use { iamClient ->
iamClient.deletePolicy(request)
println("Successfully deleted $policyARNVal")
}
}
// snippet-end:[iam.kotlin.delete_policy.main]
| apache-2.0 | 0c04138781f06356619d00bab587c036 | 26.928571 | 117 | 0.678395 | 3.847981 | false | false | false | false |
zbeboy/ISY | src/main/java/top/zbeboy/isy/web/vo/data/schoolroom/SchoolroomVo.kt | 1 | 442 | package top.zbeboy.isy.web.vo.data.schoolroom
import javax.validation.constraints.Min
import javax.validation.constraints.NotNull
import javax.validation.constraints.Size
/**
* Created by zbeboy 2017-12-08 .
**/
open class SchoolroomVo {
var schoolroomId: Int? = null
@NotNull
@Size(max = 10)
var buildingCode: String? = null
var schoolroomIsDel: Byte? = null
@NotNull
@Min(1)
var buildingId: Int? = null
} | mit | 2be77e271f10f33c3fbb72c56bcdcab5 | 22.315789 | 45 | 0.705882 | 3.536 | false | false | false | false |
esafirm/android-playground | app/src/main/java/com/esafirm/androidplayground/ui/XfermodeController.kt | 1 | 2013 | package com.esafirm.androidplayground.ui
import android.graphics.*
import android.graphics.drawable.BitmapDrawable
import android.os.Bundle
import android.view.View
import android.view.ViewTreeObserver
import android.widget.ImageView
import com.esafirm.androidplayground.R
import com.esafirm.androidplayground.libs.Logger
import com.esafirm.conductorextra.butterknife.BinderController
class XfermodeController : BinderController() {
init {
Logger.clear()
}
override fun getLayoutResId(): Int = R.layout.controller_xfermode
override fun onViewBound(bindingResult: View, savedState: Bundle?) {
bindingResult.viewTreeObserver.addOnPreDrawListener(object : ViewTreeObserver.OnPreDrawListener {
override fun onPreDraw(): Boolean {
bindingResult.viewTreeObserver.removeOnPreDrawListener(this)
val bg = Bitmap.createBitmap(bindingResult.width, bindingResult.height, Bitmap.Config.ARGB_8888)
val icon = BitmapFactory.decodeResource(applicationContext?.resources, R.drawable.ic_copyright).let {
Bitmap.createScaledBitmap(it, 400, 400, true)
}
val rectPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
color = Color.parseColor("#88000000")
}
val iconPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
color = Color.BLACK
xfermode = PorterDuffXfermode(PorterDuff.Mode.DST_OUT)
}
Canvas(bg).apply {
drawRect(0f, 0f, bindingResult.width.toFloat(), bindingResult.height.toFloat(), rectPaint)
drawBitmap(icon, bindingResult.width.toFloat() / 2, bindingResult.height.toFloat() / 2, iconPaint)
}
with(bindingResult.findViewById<ImageView>(R.id.imageview)) {
background = BitmapDrawable(bg)
}
return false
}
})
}
}
| mit | 43eb7c8e9424dc5bcd0ccd9d1f6312ae | 36.981132 | 118 | 0.639344 | 5.161538 | false | false | false | false |
google/intellij-community | python/src/com/jetbrains/python/newProject/NewProjectWizardDirectoryGeneratorAdapter.kt | 5 | 2811 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.jetbrains.python.newProject
import com.intellij.ide.util.projectWizard.AbstractNewProjectStep
import com.intellij.ide.util.projectWizard.ProjectSettingsStepBase
import com.intellij.ide.util.projectWizard.WizardContext
import com.intellij.ide.wizard.GeneratorNewProjectWizard
import com.intellij.ide.wizard.NewProjectWizardStepPanel
import com.intellij.openapi.module.Module
import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.VerticalFlowLayout
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.platform.DirectoryProjectGeneratorBase
import com.intellij.platform.GeneratorPeerImpl
import com.intellij.platform.ProjectGeneratorPeer
import javax.swing.Icon
import javax.swing.JButton
import javax.swing.JComponent
import javax.swing.JPanel
/**
* A base adapter class to turn a [GeneratorNewProjectWizard] into a
* [com.intellij.platform.DirectoryProjectGenerator] and register as an extension point.
*
* @see NewProjectWizardProjectSettingsStep
*/
open class NewProjectWizardDirectoryGeneratorAdapter<T>(val wizard: GeneratorNewProjectWizard) : DirectoryProjectGeneratorBase<T>() {
internal lateinit var panel: NewProjectWizardStepPanel
@Suppress("DialogTitleCapitalization")
override fun getName(): String = wizard.name
override fun getLogo(): Icon = wizard.icon
override fun generateProject(project: Project, baseDir: VirtualFile, settings: T, module: Module) {
panel.step.setupProject(project)
}
override fun createPeer(): ProjectGeneratorPeer<T> {
val context = WizardContext(null) {}
return object : GeneratorPeerImpl<T>() {
override fun getComponent(): JComponent {
panel = NewProjectWizardStepPanel(wizard.createStep(context))
return panel.component
}
}
}
}
/**
* A wizard-enabled project settings step that you should use for your [projectGenerator] in your
* [AbstractNewProjectStep.Customization.createProjectSpecificSettingsStep] to provide the project wizard UI and actions.
*/
class NewProjectWizardProjectSettingsStep<T>(val projectGenerator: NewProjectWizardDirectoryGeneratorAdapter<T>)
: ProjectSettingsStepBase<T>(projectGenerator, null) {
init {
myCallback = AbstractNewProjectStep.AbstractCallback()
}
override fun createAndFillContentPanel(): JPanel =
JPanel(VerticalFlowLayout()).apply {
add(peer.component)
}
override fun registerValidators() {}
override fun getProjectLocation(): String =
projectGenerator.panel.step.context.projectFileDirectory
override fun getActionButton(): JButton =
super.getActionButton().apply {
addActionListener {
projectGenerator.panel.apply()
}
}
} | apache-2.0 | 82de722dd85918780327a07d6ec4646c | 36 | 133 | 0.786909 | 4.72437 | false | false | false | false |
google/intellij-community | platform/vcs-impl/src/com/intellij/codeInsight/hints/VcsCodeVisionProvider.kt | 2 | 11513 | // 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.codeInsight.hints
import com.intellij.codeInsight.codeVision.*
import com.intellij.codeInsight.codeVision.CodeVisionState.Companion.READY_EMPTY
import com.intellij.codeInsight.codeVision.ui.model.ClickableTextCodeVisionEntry
import com.intellij.codeInsight.hints.Result.Companion.SUCCESS_EMPTY
import com.intellij.icons.AllIcons
import com.intellij.lang.Language
import com.intellij.openapi.Disposable
import com.intellij.openapi.actionSystem.ActionManager
import com.intellij.openapi.actionSystem.ActionPlaces
import com.intellij.openapi.actionSystem.ex.ActionUtil
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.application.runReadAction
import com.intellij.openapi.components.service
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.editor.ex.util.EditorUtil
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.Disposer
import com.intellij.openapi.util.Key
import com.intellij.openapi.util.TextRange
import com.intellij.openapi.vcs.AbstractVcs
import com.intellij.openapi.vcs.ProjectLevelVcsManager
import com.intellij.openapi.vcs.VcsBundle
import com.intellij.openapi.vcs.actions.ShortNameType
import com.intellij.openapi.vcs.annotate.AnnotationsPreloader
import com.intellij.openapi.vcs.annotate.FileAnnotation
import com.intellij.openapi.vcs.annotate.LineAnnotationAspect
import com.intellij.openapi.vcs.annotate.LineAnnotationAspectAdapter
import com.intellij.openapi.vcs.impl.UpToDateLineNumberProviderImpl
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.psi.*
import com.intellij.util.text.nullize
import com.intellij.vcs.CacheableAnnotationProvider
import java.awt.event.MouseEvent
import java.lang.Integer.min
import javax.swing.JComponent
class VcsCodeVisionProvider : CodeVisionProvider<Unit> {
companion object {
const val id: String = "vcs.code.vision"
}
override fun isAvailableFor(project: Project): Boolean {
return VcsCodeVisionLanguageContext.providersExtensionPoint.hasAnyExtensions()
}
override fun precomputeOnUiThread(editor: Editor) {
}
override fun preparePreview(editor: Editor, file: PsiFile) {
addPreviewInfo(editor)
}
override fun computeCodeVision(editor: Editor, uiData: Unit): CodeVisionState {
return runReadAction {
val project = editor.project ?: return@runReadAction READY_EMPTY
val document = editor.document
val file = PsiDocumentManager.getInstance(project).getPsiFile(document) ?: return@runReadAction CodeVisionState.NotReady
val language = file.language
if (!hasSupportedVcs(project, file, editor)) return@runReadAction READY_EMPTY
val aspectResult = getAspect(file, editor)
if (aspectResult.isSuccess.not()) return@runReadAction CodeVisionState.NotReady
val aspect = aspectResult.result ?: return@runReadAction READY_EMPTY
val lenses = ArrayList<Pair<TextRange, CodeVisionEntry>>()
val visionLanguageContext = VcsCodeVisionLanguageContext.providersExtensionPoint.forLanguage(language)
?: return@runReadAction READY_EMPTY
val traverser = SyntaxTraverser.psiTraverser(file)
for (element in traverser.preOrderDfsTraversal()) {
if (visionLanguageContext.isAccepted(element)) {
val textRange = InlayHintsUtils.getTextRangeWithoutLeadingCommentsAndWhitespaces(element)
val length = editor.document.textLength
val adjustedRange = TextRange(min(textRange.startOffset, length), min(textRange.endOffset, length))
val codeAuthorInfo = PREVIEW_INFO_KEY.get(editor) ?: getCodeAuthorInfo(element.project, adjustedRange, editor, aspect)
val text = codeAuthorInfo.getText()
val icon = if (codeAuthorInfo.mainAuthor != null) AllIcons.Vcs.Author else null
val clickHandler = CodeAuthorClickHandler(element, language)
val entry = ClickableTextCodeVisionEntry(text, id, onClick = clickHandler, icon, text, text, emptyList())
entry.showInMorePopup = false
lenses.add(adjustedRange to entry)
}
}
return@runReadAction CodeVisionState.Ready(lenses)
}
}
private fun hasSupportedVcs(project: Project, file: PsiFile, editor: Editor) : Boolean {
if (hasPreviewInfo(editor)) {
return true
}
val vcs = ProjectLevelVcsManager.getInstance(project).getVcsFor(file.virtualFile) ?: return false
return "Git" == vcs.name
}
override fun getPlaceholderCollector(editor: Editor, psiFile: PsiFile?): CodeVisionPlaceholderCollector? {
if (psiFile == null) return null
val language = psiFile.language
val project = editor.project ?: return null
val visionLanguageContext = VcsCodeVisionLanguageContext.providersExtensionPoint.forLanguage(language) ?: return null
val virtualFile = psiFile.virtualFile
if (virtualFile == null) return null
val vcs = ProjectLevelVcsManager.getInstance(project).getVcsFor(virtualFile) ?: return null
if ("Git" != vcs.name) {
return null
}
if (vcs.annotationProvider !is CacheableAnnotationProvider) return null
return object : BypassBasedPlaceholderCollector {
override fun collectPlaceholders(element: PsiElement, editor: Editor): List<TextRange> {
val ranges = ArrayList<TextRange>()
if (visionLanguageContext.isAccepted(element)) {
ranges.add(InlayHintsUtils.getTextRangeWithoutLeadingCommentsAndWhitespaces(element))
}
return ranges
}
}
}
override val name: String
get() = VcsBundle.message("label.code.author.inlay.hints")
override val relativeOrderings: List<CodeVisionRelativeOrdering>
get() = emptyList()
override val defaultAnchor: CodeVisionAnchorKind
get() = CodeVisionAnchorKind.Default
override val id: String
get() = Companion.id
}
// implemented not as inplace lambda to avoid capturing project/editor
private class CodeAuthorClickHandler(element: PsiElement, private val language: Language) : (MouseEvent?, Editor) -> Unit {
private val elementPointer = SmartPointerManager.createPointer(element)
override fun invoke(event: MouseEvent?, editor: Editor) {
event ?: return
val component = event.component as? JComponent ?: return
invokeAnnotateAction(event, component)
val element = elementPointer.element ?: return
val visionLanguageContext = VcsCodeVisionLanguageContext.providersExtensionPoint.forLanguage(language)
visionLanguageContext.handleClick(event, editor, element)
}
}
private fun invokeAnnotateAction(event: MouseEvent, contextComponent: JComponent) {
val action = ActionManager.getInstance().getAction("Annotate")
ActionUtil.invokeAction(action, contextComponent, ActionPlaces.EDITOR_INLAY, event, null)
}
private fun getCodeAuthorInfo(project: Project, range: TextRange, editor: Editor, authorAspect: LineAnnotationAspect): VcsCodeAuthorInfo {
val startLine = editor.document.getLineNumber(range.startOffset)
val endLine = editor.document.getLineNumber(range.endOffset)
val provider = UpToDateLineNumberProviderImpl(editor.document, project)
val authorsFrequency = (startLine..endLine)
.map { provider.getLineNumber(it) }
.mapNotNull { authorAspect.getValue(it).nullize() }
.groupingBy { it }
.eachCount()
val maxFrequency = authorsFrequency.maxOfOrNull { it.value } ?: return VcsCodeAuthorInfo.NEW_CODE
return VcsCodeAuthorInfo(
mainAuthor = authorsFrequency.filterValues { it == maxFrequency }.minOf { it.key },
otherAuthorsCount = authorsFrequency.size - 1,
isModified = provider.isRangeChanged(startLine, endLine + 1)
)
}
private fun getAspect(file: PsiFile, editor: Editor): Result<LineAnnotationAspect?> {
if (hasPreviewInfo(editor)) return Result.Success(LineAnnotationAspectAdapter.NULL_ASPECT)
val virtualFile = file.virtualFile ?: return SUCCESS_EMPTY
val annotationResult = getAnnotation(file.project, virtualFile, editor)
if (annotationResult.isSuccess.not()) return Result.Failure()
return Result.Success(annotationResult.result?.aspects?.find { it.id == LineAnnotationAspect.AUTHOR })
}
private val VCS_CODE_AUTHOR_ANNOTATION = Key.create<FileAnnotation>("Vcs.CodeAuthor.Annotation")
private fun getAnnotation(project: Project, file: VirtualFile, editor: Editor): Result<FileAnnotation?> {
editor.getUserData(VCS_CODE_AUTHOR_ANNOTATION)?.let { return Result.Success(it) }
val vcs = ProjectLevelVcsManager.getInstance(project).getVcsFor(file) ?: return SUCCESS_EMPTY
val provider = vcs.annotationProvider as? CacheableAnnotationProvider ?: return SUCCESS_EMPTY
val isFileInVcs = AbstractVcs.fileInVcsByFileStatus(project, file)
if (!isFileInVcs) return SUCCESS_EMPTY
val annotation = provider.getFromCache(file) ?: return Result.Failure()
val annotationDisposable = Disposable {
unregisterAnnotation(annotation)
annotation.dispose()
}
annotation.setCloser {
editor.putUserData(VCS_CODE_AUTHOR_ANNOTATION, null)
Disposer.dispose(annotationDisposable)
project.service<AnnotationsPreloader>().schedulePreloading(file)
}
annotation.setReloader { annotation.close() }
editor.putUserData(VCS_CODE_AUTHOR_ANNOTATION, annotation)
registerAnnotation(annotation)
ApplicationManager.getApplication().invokeLater {
EditorUtil.disposeWithEditor(editor, annotationDisposable)
}
return Result.Success(annotation)
}
private fun registerAnnotation(annotation: FileAnnotation) =
ProjectLevelVcsManager.getInstance(annotation.project).annotationLocalChangesListener.registerAnnotation(annotation)
private fun unregisterAnnotation(annotation: FileAnnotation) =
ProjectLevelVcsManager.getInstance(annotation.project).annotationLocalChangesListener.unregisterAnnotation(annotation)
private val VcsCodeAuthorInfo.isMultiAuthor: Boolean get() = otherAuthorsCount > 0
private fun VcsCodeAuthorInfo.getText(): String {
val mainAuthorText = ShortNameType.shorten(mainAuthor, ShortNameType.NONE)
return when {
mainAuthorText == null -> VcsBundle.message("label.new.code")
isMultiAuthor && isModified -> VcsBundle.message("label.multi.author.modified.code", mainAuthorText, otherAuthorsCount)
isMultiAuthor && !isModified -> VcsBundle.message("label.multi.author.not.modified.code", mainAuthorText, otherAuthorsCount)
!isMultiAuthor && isModified -> VcsBundle.message("label.single.author.modified.code", mainAuthorText)
else -> mainAuthorText
}
}
private sealed class Result<out T>(val isSuccess: Boolean, val result: T?) {
companion object {
private var mySuccess: Success<Nothing?>? = null
val SUCCESS_EMPTY : Success<Nothing?>
get() {
// initializing lazily to avoid deadlock. Not a problem to access it from different threads (safe race)
val mySuccessVal = mySuccess
if (mySuccessVal != null) {
return mySuccessVal
}
val success = Success(null)
mySuccess = success
return success
}
}
class Success<T>(result: T) : Result<T>(true, result)
class Failure<T> : Result<T>(false, null)
}
private val PREVIEW_INFO_KEY = Key.create<VcsCodeAuthorInfo>("preview.author.info")
private fun addPreviewInfo(editor: Editor) {
editor.putUserData(PREVIEW_INFO_KEY, VcsCodeAuthorInfo("John Smith", 2, false))
}
private fun hasPreviewInfo(editor: Editor) = PREVIEW_INFO_KEY.get(editor) != null | apache-2.0 | df180d121914f707f240464a0404a490 | 42.946565 | 138 | 0.767393 | 4.52555 | false | false | false | false |
google/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/actions/internal/CheckComponentsUsageSearchAction.kt | 2 | 5885 | // 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.actions.internal
import com.intellij.openapi.actionSystem.ActionUpdateThread
import com.intellij.openapi.actionSystem.AnAction
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.actionSystem.CommonDataKeys
import com.intellij.openapi.progress.EmptyProgressIndicator
import com.intellij.openapi.progress.ProgressManager
import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.Messages
import com.intellij.openapi.util.NlsSafe
import com.intellij.openapi.vfs.VfsUtilCore
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.openapi.vfs.VirtualFileVisitor
import com.intellij.psi.PsiManager
import com.intellij.psi.search.searches.ReferencesSearch
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.search.usagesSearch.ExpressionsOfTypeProcessor
import org.jetbrains.kotlin.idea.util.application.isApplicationInternalMode
import org.jetbrains.kotlin.idea.util.application.runReadAction
import org.jetbrains.kotlin.psi.KtClass
import org.jetbrains.kotlin.psi.KtFile
import javax.swing.SwingUtilities
class CheckComponentsUsageSearchAction : AnAction() {
override fun actionPerformed(e: AnActionEvent) {
val project = CommonDataKeys.PROJECT.getData(e.dataContext) ?: return
val selectedKotlinFiles = selectedKotlinFiles(e).toList()
ProgressManager.getInstance().runProcessWithProgressSynchronously(
{
runReadAction { process(selectedKotlinFiles, project) }
},
KotlinBundle.message("checking.data.classes"),
true,
project
)
}
private fun process(files: Collection<KtFile>, project: Project) {
val dataClasses = files.asSequence()
.flatMap { it.declarations.asSequence() }
.filterIsInstance<KtClass>()
.filter { it.isData() }
.toList()
val progressIndicator = ProgressManager.getInstance().progressIndicator
for ((i, dataClass) in dataClasses.withIndex()) {
progressIndicator?.text = KotlinBundle.message("checking.data.class.0.of.1", i + 1, dataClasses.size)
@NlsSafe val fqName = dataClass.fqName?.asString() ?: ""
progressIndicator?.text2 = fqName
val parameter = dataClass.primaryConstructor?.valueParameters?.firstOrNull()
if (parameter != null) {
try {
var smartRefsCount = 0
var goldRefsCount = 0
ProgressManager.getInstance().runProcess(
{
ExpressionsOfTypeProcessor.mode =
ExpressionsOfTypeProcessor.Mode.ALWAYS_SMART
smartRefsCount = ReferencesSearch.search(parameter).findAll().size
ExpressionsOfTypeProcessor.mode =
ExpressionsOfTypeProcessor.Mode.ALWAYS_PLAIN
goldRefsCount = ReferencesSearch.search(parameter).findAll().size
}, EmptyProgressIndicator()
)
if (smartRefsCount != goldRefsCount) {
SwingUtilities.invokeLater {
Messages.showInfoMessage(
project,
KotlinBundle.message(
"difference.found.for.data.class.0.found.1.2",
dataClass.fqName?.asString().toString(),
smartRefsCount,
goldRefsCount
),
KotlinBundle.message("title.error")
)
}
return
}
} finally {
ExpressionsOfTypeProcessor.mode = ExpressionsOfTypeProcessor.Mode.PLAIN_WHEN_NEEDED
}
}
progressIndicator?.fraction = (i + 1) / dataClasses.size.toDouble()
}
SwingUtilities.invokeLater {
Messages.showInfoMessage(
project,
KotlinBundle.message("analyzed.0.classes.no.difference.found", dataClasses.size),
KotlinBundle.message("title.success")
)
}
}
override fun getActionUpdateThread() = ActionUpdateThread.BGT
override fun update(e: AnActionEvent) {
e.presentation.isEnabledAndVisible = isApplicationInternalMode()
}
private fun selectedKotlinFiles(e: AnActionEvent): Sequence<KtFile> {
val virtualFiles = e.getData(CommonDataKeys.VIRTUAL_FILE_ARRAY) ?: return sequenceOf()
val project = CommonDataKeys.PROJECT.getData(e.dataContext) ?: return sequenceOf()
return allKotlinFiles(virtualFiles, project)
}
private fun allKotlinFiles(filesOrDirs: Array<VirtualFile>, project: Project): Sequence<KtFile> {
val manager = PsiManager.getInstance(project)
return allFiles(filesOrDirs)
.asSequence()
.mapNotNull { manager.findFile(it) as? KtFile }
}
private fun allFiles(filesOrDirs: Array<VirtualFile>): Collection<VirtualFile> {
val result = ArrayList<VirtualFile>()
for (file in filesOrDirs) {
VfsUtilCore.visitChildrenRecursively(file, object : VirtualFileVisitor<Unit>() {
override fun visitFile(file: VirtualFile): Boolean {
result.add(file)
return true
}
})
}
return result
}
}
| apache-2.0 | ca7103e6069cbf82e0e094b1a6685ed2 | 41.956204 | 158 | 0.615973 | 5.636973 | false | false | false | false |
allotria/intellij-community | plugins/git4idea/src/git4idea/update/GitUpdateSession.kt | 2 | 4587 | // 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 git4idea.update
import com.intellij.dvcs.DvcsUtil.getShortNames
import com.intellij.dvcs.DvcsUtil.getShortRepositoryName
import com.intellij.notification.Notification
import com.intellij.notification.NotificationAction
import com.intellij.notification.NotificationType
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.NlsContexts
import com.intellij.openapi.vcs.VcsException
import com.intellij.openapi.vcs.VcsNotifier
import com.intellij.openapi.vcs.update.UpdateSession
import com.intellij.util.containers.MultiMap
import git4idea.i18n.GitBundle
import git4idea.repo.GitRepository
import java.util.function.Supplier
/**
* Ranges are null if update didn't start yet, in which case there are no new commits to display,
* and the error notification is shown from the GitUpdateProcess itself.
*/
class GitUpdateSession(private val project: Project,
private val notificationData: GitUpdateInfoAsLog.NotificationData?,
private val result: Boolean,
private val skippedRoots: Map<GitRepository, String>) : UpdateSession {
override fun getExceptions(): List<VcsException> {
return emptyList()
}
override fun onRefreshFilesCompleted() {}
override fun isCanceled(): Boolean {
return !result
}
override fun getAdditionalNotificationContent(): String? {
if (skippedRoots.isEmpty()) return null
if (skippedRoots.size == 1) {
val repo = skippedRoots.keys.first()
return GitBundle.message("git.update.repo.was.skipped", getShortRepositoryName(repo), skippedRoots[repo])
}
val prefix = GitBundle.message("git.update.skipped.repositories", skippedRoots.size) + " <br/>" // NON-NLS
val grouped = groupByReasons(skippedRoots)
if (grouped.keySet().size == 1) {
val reason = grouped.keySet().first()
return prefix + getShortNames(grouped.get(reason)) + " (" + reason + ")"
}
return prefix + grouped.keySet().joinToString("<br/>") { reason -> getShortNames(grouped.get(reason)) + " (" + reason + ")" } // NON-NLS
}
private fun groupByReasons(skippedRoots: Map<GitRepository, String>): MultiMap<String, GitRepository> {
val result = MultiMap.create<String, GitRepository>()
skippedRoots.forEach { (file, s) -> result.putValue(s, file) }
return result
}
override fun showNotification() {
if (notificationData != null) {
val notification = prepareNotification(notificationData.updatedFilesCount, notificationData.receivedCommitsCount,
notificationData.filteredCommitsCount)
notification.addAction(NotificationAction.createSimple(Supplier { GitBundle.message("action.NotificationAction.GitUpdateSession.text.view.commits") },
notificationData.viewCommitAction))
VcsNotifier.getInstance(project).notify(notification)
}
}
private fun prepareNotification(updatedFilesNumber: Int, updatedCommitsNumber: Int, filteredCommitsNumber: Int?): Notification {
val title: String
var content: String?
val type: NotificationType
val mainMessage = getTitleForUpdateNotification(updatedFilesNumber, updatedCommitsNumber)
if (isCanceled) {
title = GitBundle.message("git.update.project.partially.updated.title")
content = mainMessage
type = NotificationType.WARNING
}
else {
title = mainMessage
content = getBodyForUpdateNotification(filteredCommitsNumber)
type = NotificationType.INFORMATION
}
val additionalContent = additionalNotificationContent
if (additionalContent != null) {
if (content.isNotEmpty()) {
content += "<br/>" // NON-NLS
}
content += additionalContent
}
return VcsNotifier.STANDARD_NOTIFICATION.createNotification(title, content, type, null)
}
}
@NlsContexts.NotificationTitle
fun getTitleForUpdateNotification(updatedFilesNumber: Int, updatedCommitsNumber: Int): String =
GitBundle.message("git.update.files.updated.in.commits", updatedFilesNumber, updatedCommitsNumber)
@NlsContexts.NotificationContent
fun getBodyForUpdateNotification(filteredCommitsNumber: Int?): String {
return when (filteredCommitsNumber) {
null -> ""
0 -> GitBundle.message("git.update.no.commits.matching.filters")
else -> GitBundle.message("git.update.commits.matching.filters", filteredCommitsNumber)
}
}
| apache-2.0 | 765cf60e09f5b996204282582627a3b3 | 40.324324 | 156 | 0.725311 | 4.833509 | false | false | false | false |
allotria/intellij-community | plugins/gradle/java/src/service/debugger/GradleJvmDebuggerBackend.kt | 3 | 4126 | // Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.plugins.gradle.service.debugger
import com.intellij.execution.RunManager.Companion.getInstance
import com.intellij.execution.RunnerAndConfigurationSettings
import com.intellij.execution.remote.RemoteConfiguration
import com.intellij.execution.remote.RemoteConfigurationType
import com.intellij.openapi.externalSystem.debugger.DebuggerBackendExtension
import com.intellij.openapi.externalSystem.debugger.DebuggerBackendExtension.RUNTIME_MODULE_DIR_KEY
import com.intellij.openapi.externalSystem.rt.execution.ForkedDebuggerHelper
import com.intellij.openapi.project.Project
class GradleJvmDebuggerBackend : DebuggerBackendExtension {
override fun id() = "Gradle JVM"
override fun debugConfigurationSettings(project: Project,
processName: String,
processParameters: String): RunnerAndConfigurationSettings {
val runSettings = getInstance(project).createConfiguration(processName, RemoteConfigurationType::class.java)
val description = splitParameters(processParameters)
val configuration = runSettings.configuration as RemoteConfiguration
configuration.HOST = "localhost"
configuration.PORT = description[ForkedDebuggerHelper.DEBUG_SERVER_PORT_KEY]
configuration.USE_SOCKET_TRANSPORT = true
configuration.SERVER_MODE = true
configuration.putUserData(RUNTIME_MODULE_DIR_KEY, description[ForkedDebuggerHelper.RUNTIME_MODULE_DIR_KEY])
return runSettings
}
override fun initializationCode(dispatchPort: String, parameters: String) =
//language=Gradle
"""
import com.intellij.openapi.externalSystem.rt.execution.ForkedDebuggerHelper
def getCurrentProject() {
def currentPath = gradle.startParameter.currentDir.path
def currentProject = rootProject.allprojects
.find { it.projectDir.path == currentPath }
return currentProject == null ? project : currentProject
}
def findAllTaskPathsInStartParameters() {
def currentProject = getCurrentProject()
logger.debug("Current project: ${'$'}{currentProject}")
def startTaskNames = gradle.startParameter.taskNames
if (startTaskNames.isEmpty()) {
startTaskNames = currentProject.defaultTasks
}
logger.debug("Start Tasks Names: ${'$'}{startTaskNames}")
def allTaskContainers = currentProject.allprojects.collect { it.tasks }
return startTaskNames.findResults { taskName ->
allTaskContainers.findResult { it.findByPath(taskName)?.path }
?: allTaskContainers.findResult { it.find { it.name.startsWith(taskName) || it.path.startsWith(taskName) }?.path }
}
}
gradle.taskGraph.whenReady { taskGraph ->
def debugAllIsEnabled = Boolean.valueOf(System.properties["idea.gradle.debug.all"])
def taskPathsList = debugAllIsEnabled ? [] : findAllTaskPathsInStartParameters()
logger.debug("idea.gradle.debug.all is ${'$'}{debugAllIsEnabled}")
logger.debug("Task paths: ${'$'}{taskPathsList}")
taskGraph.allTasks.each { Task task ->
if (task instanceof org.gradle.api.tasks.testing.Test) {
task.maxParallelForks = 1
task.forkEvery = 0
}
if (task instanceof JavaForkOptions && (debugAllIsEnabled || taskPathsList.contains(task.path))) {
def moduleDir = task.project.projectDir.path
task.doFirst {
def debugPort = ForkedDebuggerHelper.setupDebugger('${id()}', task.path, '$parameters', moduleDir)
def jvmArgs = task.jvmArgs.findAll{!it?.startsWith('-agentlib:jdwp') && !it?.startsWith('-Xrunjdwp')}
jvmArgs << ForkedDebuggerHelper.JVM_DEBUG_SETUP_PREFIX + ForkedDebuggerHelper.addrFromProperty +':' + debugPort
task.jvmArgs = jvmArgs
}
task.doLast {
ForkedDebuggerHelper.signalizeFinish('${id()}', task.path)
}
}
}
}
""".trimIndent().split("\n")
} | apache-2.0 | f31cbf28f38a0f8b9ef11c906021c4d3 | 48.130952 | 140 | 0.709646 | 4.758939 | false | true | false | false |
googlecodelabs/android-sleep | complete/src/main/java/com/android/example/sleepcodelab/receiver/SleepReceiver.kt | 1 | 3944 | /*
* Copyright (C) 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 com.android.example.sleepcodelab.receiver
import android.app.PendingIntent
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.util.Log
import com.android.example.sleepcodelab.MainApplication
import com.android.example.sleepcodelab.data.SleepRepository
import com.android.example.sleepcodelab.data.db.SleepClassifyEventEntity
import com.android.example.sleepcodelab.data.db.SleepSegmentEventEntity
import com.google.android.gms.location.SleepClassifyEvent
import com.google.android.gms.location.SleepSegmentEvent
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.MainScope
import kotlinx.coroutines.launch
/**
* Saves Sleep Events to Database.
*/
class SleepReceiver : BroadcastReceiver() {
// Used to launch coroutines (non-blocking way to insert data).
private val scope: CoroutineScope = MainScope()
override fun onReceive(context: Context, intent: Intent) {
Log.d(TAG, "onReceive(): $intent")
val repository: SleepRepository = (context.applicationContext as MainApplication).repository
// TODO: Extract sleep information from PendingIntent.
if (SleepSegmentEvent.hasEvents(intent)) {
val sleepSegmentEvents: List<SleepSegmentEvent> =
SleepSegmentEvent.extractEvents(intent)
Log.d(TAG, "SleepSegmentEvent List: $sleepSegmentEvents")
addSleepSegmentEventsToDatabase(repository, sleepSegmentEvents)
} else if (SleepClassifyEvent.hasEvents(intent)) {
val sleepClassifyEvents: List<SleepClassifyEvent> =
SleepClassifyEvent.extractEvents(intent)
Log.d(TAG, "SleepClassifyEvent List: $sleepClassifyEvents")
addSleepClassifyEventsToDatabase(repository, sleepClassifyEvents)
}
}
private fun addSleepSegmentEventsToDatabase(
repository: SleepRepository,
sleepSegmentEvents: List<SleepSegmentEvent>
) {
if (sleepSegmentEvents.isNotEmpty()) {
scope.launch {
val convertedToEntityVersion: List<SleepSegmentEventEntity> =
sleepSegmentEvents.map {
SleepSegmentEventEntity.from(it)
}
repository.insertSleepSegments(convertedToEntityVersion)
}
}
}
private fun addSleepClassifyEventsToDatabase(
repository: SleepRepository,
sleepClassifyEvents: List<SleepClassifyEvent>
) {
if (sleepClassifyEvents.isNotEmpty()) {
scope.launch {
val convertedToEntityVersion: List<SleepClassifyEventEntity> =
sleepClassifyEvents.map {
SleepClassifyEventEntity.from(it)
}
repository.insertSleepClassifyEvents(convertedToEntityVersion)
}
}
}
companion object {
const val TAG = "SleepReceiver"
fun createSleepReceiverPendingIntent(context: Context): PendingIntent {
val sleepIntent = Intent(context, SleepReceiver::class.java)
return PendingIntent.getBroadcast(
context,
0,
sleepIntent,
PendingIntent.FLAG_CANCEL_CURRENT
)
}
}
}
| apache-2.0 | 4e9442853bb0fd2c5e056885c48dd013 | 37.666667 | 100 | 0.686105 | 5.203166 | false | false | false | false |
trevjonez/ktor_playground | src/main/kotlin/com/trevjonez/ktor_playground/people/PersonEntity.kt | 1 | 1339 | package com.trevjonez.ktor_playground.people
import com.trevjonez.ktor_playground.Validator
import io.requery.Column
import io.requery.Entity
import io.requery.Key
import java.time.ZonedDateTime
import java.util.UUID
@Entity
data class PersonEntity(
@get:Key
@get:Column(nullable = false, unique = true)
override val id: UUID,
@get:Column(nullable = false)
override val createdOn: ZonedDateTime,
@get:Column(nullable = false)
override val updatedOn: ZonedDateTime,
@get:Column(nullable = true)
override val deletedOn: ZonedDateTime?,
@get:Column(nullable = false)
override val age: Int,
@get:Column(nullable = false)
override val name: String
) : ValidatedPerson {
companion object PostValidator : Validator.Post<Person, PersonEntity> {
override fun validate(input: Person): PersonEntity {
val now = ZonedDateTime.now()
return with(input) {
PersonEntity(id ?: UUID.randomUUID(),
createdOn ?: now,
now,
deletedOn,
age ?: throw NullPointerException("age"),
name ?: throw NullPointerException("name"))
}
}
}
} | apache-2.0 | 0c1b7ad14e4c187aebee27ad479df2b8 | 28.777778 | 75 | 0.584018 | 4.851449 | false | false | false | false |
leafclick/intellij-community | plugins/github/test/org/jetbrains/plugins/github/test/GithubGitRepoTest.kt | 1 | 2618 | // Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.plugins.github.test
import com.intellij.openapi.components.service
import com.intellij.openapi.vcs.VcsException
import com.intellij.openapi.vfs.VirtualFile
import git4idea.commands.GitHttpAuthService
import git4idea.commands.GitHttpAuthenticator
import git4idea.config.GitConfigUtil
import git4idea.repo.GitRepository
import git4idea.test.GitHttpAuthTestService
import git4idea.test.git
import org.jetbrains.plugins.github.util.GithubGitHelper
import org.jetbrains.plugins.github.util.GithubUtil
abstract class GithubGitRepoTest : GithubTest() {
protected lateinit var gitHelper: GithubGitHelper
protected lateinit var repository: GitRepository
@Throws(Exception::class)
override fun setUp() {
super.setUp()
gitHelper = service()
}
override fun setCurrentAccount(accountData: AccountData?) {
super.setCurrentAccount(accountData)
val gitHttpAuthService = service<GitHttpAuthService>() as GitHttpAuthTestService
if (accountData == null) {
gitHttpAuthService.cleanup()
return
}
gitHttpAuthService.register(object : GitHttpAuthenticator {
override fun askPassword(url: String) = GithubUtil.GIT_AUTH_PASSWORD_SUBSTITUTE
override fun askUsername(url: String) = accountData.token
override fun saveAuthData() {}
override fun forgetPassword() {}
override fun wasCancelled() = false
override fun wasRequested(): Boolean = true
})
}
protected fun findGitRepo() {
repository = repositoryManager.getRepositoryForFile(projectRoot)!!
}
// workaround: user on test server got "" as username, so git can't generate default identity
protected fun setGitIdentity(root: VirtualFile) {
try {
GitConfigUtil.setValue(myProject, root, "user.name", "Github Test")
GitConfigUtil.setValue(myProject, root, "user.email", "[email protected]")
}
catch (e: VcsException) {
e.printStackTrace()
}
}
protected fun checkGitExists() {
assertNotNull("Git repository does not exist", repository)
}
protected fun checkRemoteConfigured() {
assertNotNull(repository)
assertTrue("GitHub remote is not configured", GithubGitHelper.getInstance().hasAccessibleRemotes(repository))
}
protected fun checkLastCommitPushed() {
assertNotNull(repository)
val hash = repository.git("log -1 --pretty=%h")
val ans = repository.git("branch --contains $hash -a")
assertTrue(ans.contains("remotes/origin"))
}
} | apache-2.0 | 96aecce2fc73c79698ec8cdbbe9f8ac3 | 33.012987 | 140 | 0.747899 | 4.537262 | false | true | false | false |
benoitletondor/EasyBudget | Android/EasyBudget/app/src/main/java/com/benoitletondor/easybudgetapp/helper/MutableLiveFlow.kt | 1 | 1735 | /*
* Copyright 2022 Benoit LETONDOR
*
* 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.benoitletondor.easybudgetapp.helper
import kotlinx.coroutines.flow.*
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
/**
* A flow that emits only when it has a subscriber
*/
class MutableLiveFlow<T> : Flow<T>, FlowCollector<T> {
private val wrapped = MutableSharedFlow<T>(extraBufferCapacity = 8) // Store up to 8 events while LifeCycle is not Started before blocking sender
private val buffer = mutableListOf<T>()
private val mutex = Mutex()
override suspend fun collect(collector: FlowCollector<T>) {
wrapped
.onSubscription {
mutex.withLock {
if (buffer.isNotEmpty()) {
emitAll(buffer.asFlow())
buffer.clear()
}
}
}
.collect(collector)
}
override suspend fun emit(value: T) {
mutex.withLock {
if (wrapped.subscriptionCount.value <= 0) {
buffer.add(value)
} else {
wrapped.emit(value)
}
}
}
} | apache-2.0 | 5043821772f73e49cd6f78426466b73f | 32.384615 | 149 | 0.621326 | 4.589947 | false | false | false | false |
code-helix/slatekit | src/lib/kotlin/slatekit-utils/src/main/kotlin/slatekit/utils/templates/TemplateParser.kt | 1 | 4649 | /**
* <slate_header>
* url: www.slatekit.com
* git: www.github.com/code-helix/slatekit
* org: www.codehelix.co
* author: Kishore Reddy
* copyright: 2016 CodeHelix Solutions Inc.
* license: refer to website and/or github
* about: A tool-kit, utility library and server-backend
* mantra: Simplicity above all else
* </slate_header>
*/
package slatekit.utils.templates
import slatekit.common.lex.LexState
import slatekit.common.utils.Loops
import slatekit.results.Failure
import slatekit.results.Success
import slatekit.results.Try
/**
* Parses a text template that can contain variables/substitutions.
* e.g. An email template such as :
*
* "Hi @{user.name}, Welcome to @{startup.name}, please click @{verifyUrl} to verify your email."
*
* Is parsed into individual Template parts
* 1. "Hi" -> text
* 2. "user.name" -> substitution
* 3. ", Welcome to " -> text
* 4. "startup.name" -> substitution
* 5. ", please click" -> text
* 6. "verifyUrl" -> substitution
* 7. " to verify your email" -> text
*
* @param text
*/
class TemplateParser(val text: String) {
private val state = LexState(text)
fun parse(): Try<List<TemplatePart>> {
val subs = mutableListOf<TemplatePart>()
val result =
try {
var lastText: String = ""
var lastPos = state.pos
while (state.pos < state.END) {
val c = state.text[state.pos]
val hasMore = state.pos + 1 < state.END
val n = if (hasMore) state.text[state.pos + 1] else ' '
state.count = state.count + 1
// CASE 1: substitution
if (c == '@' && hasMore && n == '{') {
if (!lastText.isNullOrEmpty()) {
val sub = TemplatePart(lastText, TemplateConstants.TypeText, lastPos, state.pos - lastPos)
subs.add(sub)
}
val sub = readSub()
subs.add(sub)
// reset
lastText = ""
lastPos = state.pos
}
// CASE 2: Keep reading until sub
else {
lastText += c
state.pos += 1
}
}
// Last part was text ?!
if (!lastText.isNullOrEmpty()) {
val sub = TemplatePart(lastText, TemplateConstants.TypeText, lastPos, state.pos - lastPos)
subs.add(sub)
}
// Success!
Success(subs.toList())
} catch (ex: Exception) {
val line = state.line
val text = "Error occurred at : line : $line, char : ${state.pos}" + ex.message
val err = Exception(text, ex)
Failure(err, msg = text)
}
return result
}
/**
* reads a substitution inside of @{}
* expects that pos/current char = @ and next char = {
*
* @return
*/
fun readSub(): TemplatePart {
advanceAndExpect('{')
val c = advance()
val start = state.pos
val end = start
// 1. edge case ${}
return if (c == '}') {
advance()
TemplatePart("", 0, start, end)
} else {
// 2. read sub
Loops.doUntil {
if (state.pos < state.END) {
val curr = state.text[state.pos]
if (curr == '}') {
false
} else if ((state.pos + 1 < state.END)) {
state.pos += 1
true
} else {
false
}
} else {
false
}
}
val text = state.substringInclusive(start)
val sub = TemplatePart(text, TemplateConstants.TypeSub, start, state.pos)
state.pos += 1
sub
}
}
fun advanceAndExpect(expected: Char): Char {
val ch = advance()
require(ch == expected) { "Expected $expected but found $ch" }
return ch
}
fun advance(): Char {
state.pos += 1
return state.text[state.pos]
}
}
| apache-2.0 | 168b93148661ab4cd496dcdf38b58f66 | 30.842466 | 122 | 0.45128 | 4.7294 | false | false | false | false |
android/xAnd11 | core/src/main/java/com/monksanctum/xand11/core/fonts/FontProtocol.kt | 1 | 9403 | // 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 org.monksanctum.xand11.fonts
import org.monksanctum.xand11.comm.*
import org.monksanctum.xand11.core.Font
import org.monksanctum.xand11.core.Platform
import org.monksanctum.xand11.core.Platform.Companion.intToHexString
import org.monksanctum.xand11.core.Rect
import org.monksanctum.xand11.core.Throws
import org.monksanctum.xand11.errors.GContextError
import org.monksanctum.xand11.errors.XError
import org.monksanctum.xand11.core.Font.FontProperty
import org.monksanctum.xand11.fonts.FontManager.Companion.DEBUG
import org.monksanctum.xand11.graphics.GraphicsManager
class FontProtocol(private val mFontManager: FontManager, private val mGraphicsManager: GraphicsManager) : Dispatcher.PacketHandler {
override val opCodes: ByteArray
get() = HANDLED_OPS
@Throws(XError::class)
override fun handleRequest(client: Client, reader: PacketReader, writer: PacketWriter) {
when (reader.majorOpCode) {
Request.OPEN_FONT.code -> handleOpenFont(reader)
Request.CLOSE_FONT.code -> handleCloseFont(reader)
Request.QUERY_FONT.code -> handleQueryFont(reader, writer)
Request.LIST_FONTS.code -> handleListFonts(reader, writer)
Request.LIST_FONTS_WITH_INFO.code -> handleListFontsWithInfo(client, reader, writer)
Request.QUERY_TEXT_EXTENTS.code -> handleQueryTextExtents(reader, writer)
Request.GET_FONT_PATH.code -> handleGetFontPath(reader, writer)
}
}
private fun handleGetFontPath(reader: PacketReader, writer: PacketWriter) {
writer.writeCard16(0) // 0 Font paths
writer.writePadding(22)
}
private fun handleListFontsWithInfo(client: Client, reader: PacketReader, writer: PacketWriter) {
val max = reader.readCard16()
val n = reader.readCard16()
val pattern = reader.readPaddedString(n)
val fonts = mFontManager.getFontsMatching(pattern, max)
val N = fonts.size
for (i in 0 until N) {
val pWriter = PacketWriter(client.clientListener.writer)
val font = fonts[i]
val name = font.toString()
pWriter.minorOpCode = name.length.toByte()
writeFont(pWriter, font, N - i)
pWriter.writePaddedString(name)
pWriter.copyToReader().also { r ->
logInfo("FontProtocol", r)
r.close()
}
client.clientListener.sendPacket(Event.REPLY, pWriter)
}
writer.writePadding(52)
}
private fun handleListFonts(reader: PacketReader, writer: PacketWriter) {
val max = reader.readCard16()
val n = reader.readCard16()
val pattern = reader.readPaddedString(n)
val fonts = mFontManager.getFontsMatching(pattern, max)
val N = fonts.size
writer.writeCard16(N)
writer.writePadding(22)
val builder = StringBuilder()
for (i in 0 until N) {
val fontName = fonts[i].toString()
builder.append(fontName.length.toByte().toChar())
builder.append(fontName)
}
writer.writePaddedString(builder.toString())
}
private fun handleOpenFont(reader: PacketReader) {
val fid = reader.readCard32()
val length = reader.readCard16()
reader.readPadding(2)
val name = reader.readPaddedString(length)
mFontManager.openFont(fid, name)
}
private fun handleCloseFont(reader: PacketReader) {
val fid = reader.readCard32()
mFontManager.closeFont(fid)
}
private fun handleQueryFont(reader: PacketReader, writer: PacketWriter) {
val fid = reader.readCard32()
val font = mFontManager.getFont(fid)
if (font != null) {
writeFont(writer, font, font.chars.size)
writeChars(writer, font)
writer.copyToReader().also { r ->
logInfo("FontManager", r)
r.close()
}
} else {
Platform.logd("FontManager", "Sending empty font " + intToHexString(fid))
writer.writePadding(28)
}
}
@Throws(GContextError::class)
private fun handleQueryTextExtents(reader: PacketReader, writer: PacketWriter) {
val odd = reader.minorOpCode.toInt() != 0
val fid = reader.readCard32()
var font: Font? = mFontManager.getFont(fid)
if (font == null) {
font = mFontManager.getFont(mGraphicsManager.getGc(fid).font)
}
val length = reader.remaining / 2 - if (odd) 1 else 0
val s = reader.readString16(length)
val bounds = Rect()
val width = font!!.measureText(s).toInt()
font.paintGetTextBounds(s, 0, s.length, bounds)
writer.writeCard16(font.maxBounds.ascent)
writer.writeCard16(font.maxBounds.descent)
writer.writeCard16((-bounds.top).toShort().toInt())
writer.writeCard16(bounds.bottom.toShort().toInt())
writer.writeCard32(width)
writer.writeCard32(bounds.left)
writer.writeCard32(bounds.right)
writer.writePadding(4)
}
private fun writeFont(writer: PacketWriter, font: Font, sizeField: Int) {
writeChar(writer, font.minBounds)
writer.writePadding(4)
writeChar(writer, font.maxBounds)
writer.writePadding(4)
writer.writeCard16(font.minCharOrByte2.toInt())
writer.writeCard16(font.maxCharOrByte2.toInt())
writer.writeCard16(font.defaultChar.toInt())
val size = font.fontProperties.size
writer.writeCard16(size)
writer.writeByte(if (font.isRtl) Font.RIGHT_TO_LEFT else Font.LEFT_TO_RIGHT)
writer.writeByte(font.minByte1)
writer.writeByte(font.maxByte1)
writer.writeByte((if (font.allCharsExist) 1 else 0).toByte())
writer.writeCard16(font.fontAscent)
writer.writeCard16(font.fontDescent)
writer.writeCard32(sizeField)
for (i in 0 until size) {
writeProperty(writer, font.fontProperties[i])
}
}
private fun writeChars(writer: PacketWriter, font: Font) {
val chars = font.chars
val N = chars.size
for (i in 0 until N) {
writeChar(writer, chars[i])
}
}
private fun writeProperty(writer: PacketWriter, property: FontProperty) {
writer.writeCard32(property.name)
writer.writeCard32(property.value)
}
private fun writeChar(writer: PacketWriter, charInfo: Font.CharInfo) {
writer.writeCard16(charInfo.leftSideBearing)
writer.writeCard16(charInfo.rightSideBearing)
writer.writeCard16(charInfo.characterWidth)
writer.writeCard16(charInfo.ascent)
writer.writeCard16(charInfo.descent)
writer.writeCard16(charInfo.attributes)
}
companion object {
private val HANDLED_OPS = byteArrayOf(Request.OPEN_FONT.code,
Request.QUERY_FONT.code,
Request.CLOSE_FONT.code,
Request.LIST_FONTS.code,
Request.LIST_FONTS_WITH_INFO.code,
Request.QUERY_TEXT_EXTENTS.code,
Request.GET_FONT_PATH.code)
fun logInfo(tag: String, r: PacketReader) {
if (!DEBUG) return
Platform.logd(tag, "minBounds")
logChar(tag, r)
Platform.logd(tag, "")
Platform.logd(tag, "maxBounds")
logChar(tag, r)
Platform.logd(tag, "")
Platform.logd(tag, "minChar=" + r.readCard16() + " maxChar=" + r.readCard16())
Platform.logd(tag, "defaultChar=" + r.readCard16())
val numProps = r.readCard16()
Platform.logd(tag, "")
Platform.logd(tag, "isRtl:" + (r.readByte() == Font.RIGHT_TO_LEFT))
Platform.logd(tag, "minByte=" + r.readByte() + " maxByte=" + r.readByte())
Platform.logd(tag, "allChars:" + (r.readByte().toInt() != 0))
Platform.logd(tag, "ascent=" + r.readCard16() + " descent=" + r.readCard16())
Platform.logd(tag, "")
Platform.logd(tag, "Remaining hint: " + r.readCard32())
for (i in 0 until numProps) {
Platform.logd(tag, "Prop: " + r.readCard32() + " " + r.readCard32())
}
Platform.logd(tag, "Name: " + r.readPaddedString(r.minorOpCode.toInt()))
}
private fun logChar(tag: String, r: PacketReader) {
Platform.logd(tag, "leftSideBearing=" + r.readCard16()
+ " rightSideBearing=" + r.readCard16())
Platform.logd(tag, "width=" + r.readCard16())
Platform.logd(tag, "ascent=" + r.readCard16() + " descent=" + r.readCard16())
Platform.logd(tag, "attributes=" + r.readCard16())
r.readPadding(4)
}
}
}
| apache-2.0 | 19308c4f0060787f3985f4987d501201 | 38.508403 | 133 | 0.631501 | 3.939254 | false | false | false | false |
smmribeiro/intellij-community | platform/lang-impl/src/com/intellij/codeInsight/navigation/impl/doc.kt | 4 | 1032 | // Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.codeInsight.navigation.impl
import com.intellij.codeInsight.navigation.CtrlMouseDocInfo
import com.intellij.codeInsight.navigation.SingleTargetElementInfo
import com.intellij.model.Symbol
import com.intellij.model.documentation.impl.getSymbolDocumentation
import com.intellij.model.psi.PsiSymbolService
import com.intellij.psi.PsiElement
internal fun docInfo(symbol: Symbol, elementAtPointer: PsiElement): CtrlMouseDocInfo {
return fromPsi(symbol, elementAtPointer)
?: CtrlMouseDocInfo(getSymbolDocumentation(symbol), null, null)
}
private fun fromPsi(symbol: Symbol, elementAtPointer: PsiElement): CtrlMouseDocInfo? {
val psi = PsiSymbolService.getInstance().extractElementFromSymbol(symbol) ?: return null
val info = SingleTargetElementInfo.generateInfo(psi, elementAtPointer, true)
return info.takeUnless {
it === CtrlMouseDocInfo.EMPTY
}
}
| apache-2.0 | a842f5c51f6546e077492fbef7ed659d | 45.909091 | 140 | 0.811047 | 4.282158 | false | false | false | false |
smmribeiro/intellij-community | uast/uast-common/src/org/jetbrains/uast/baseElements/UIdentifier.kt | 2 | 1605 | /*
* Copyright 2000-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.uast
import com.intellij.psi.PsiElement
import org.jetbrains.annotations.ApiStatus
import org.jetbrains.uast.internal.log
open class UIdentifier(
override val sourcePsi: PsiElement?,
override val uastParent: UElement?
) : UElement {
/**
* Returns the identifier name.
*/
open val name: String
get() = sourcePsi?.text ?: "<error>"
override fun asLogString(): String = log("Identifier ($name)")
@Suppress("OverridingDeprecatedMember")
@get:ApiStatus.ScheduledForRemoval(inVersion = "2022.1")
@get:Deprecated("see the base property description")
@Deprecated("see the base property description", ReplaceWith("sourcePsi"))
override val psi: PsiElement?
get() = sourcePsi
override val javaPsi: PsiElement?
get() = null
}
open class LazyParentUIdentifier(psi: PsiElement?, private val givenParent: UElement?) : UIdentifier(psi, givenParent) {
override val uastParent: UElement? by lazy { givenParent ?: sourcePsi?.parent?.toUElement() }
} | apache-2.0 | 6077c75c78c3033dc1abc65d3b4e2f91 | 31.12 | 120 | 0.736449 | 4.326146 | false | false | false | false |
smmribeiro/intellij-community | plugins/github/src/org/jetbrains/plugins/github/ui/cloneDialog/GHECloneDialogExtension.kt | 3 | 4468 | // 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 org.jetbrains.plugins.github.ui.cloneDialog
import com.intellij.openapi.Disposable
import com.intellij.openapi.application.ModalityState
import com.intellij.openapi.components.service
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.Disposer
import com.intellij.openapi.vcs.ui.cloneDialog.VcsCloneDialogExtensionComponent
import com.intellij.ui.components.JBLabel
import com.intellij.util.ui.JBEmptyBorder
import com.intellij.util.ui.JBFont
import com.intellij.util.ui.JBUI.Panels.simplePanel
import com.intellij.util.ui.UIUtil.ComponentStyle
import com.intellij.util.ui.UIUtil.getRegularPanelInsets
import com.intellij.util.ui.cloneDialog.AccountMenuItem
import com.intellij.util.ui.components.BorderLayoutPanel
import org.jetbrains.plugins.github.api.GithubApiRequestExecutorManager
import org.jetbrains.plugins.github.authentication.GithubAuthenticationManager
import org.jetbrains.plugins.github.authentication.accounts.GHAccountManager
import org.jetbrains.plugins.github.authentication.accounts.GithubAccount
import org.jetbrains.plugins.github.authentication.accounts.GithubAccountInformationProvider
import org.jetbrains.plugins.github.authentication.accounts.isGHAccount
import org.jetbrains.plugins.github.i18n.GithubBundle.message
import org.jetbrains.plugins.github.util.CachingGHUserAvatarLoader
import org.jetbrains.plugins.github.util.GithubUtil
import javax.swing.JComponent
private val GithubAccount.isGHEAccount: Boolean get() = !isGHAccount
private fun getGHEAccounts(): Collection<GithubAccount> =
GithubAuthenticationManager.getInstance().getAccounts().filter { it.isGHEAccount }
class GHECloneDialogExtension : BaseCloneDialogExtension() {
override fun getName(): String = GithubUtil.ENTERPRISE_SERVICE_DISPLAY_NAME
override fun getAccounts(): Collection<GithubAccount> = getGHEAccounts()
override fun createMainComponent(project: Project, modalityState: ModalityState): VcsCloneDialogExtensionComponent =
GHECloneDialogExtensionComponent(project)
}
private class GHECloneDialogExtensionComponent(project: Project) : GHCloneDialogExtensionComponentBase(
project,
GithubAuthenticationManager.getInstance(),
GithubApiRequestExecutorManager.getInstance(),
GithubAccountInformationProvider.getInstance(),
CachingGHUserAvatarLoader.getInstance()
) {
init {
service<GHAccountManager>().addListener(this, this)
setup()
}
override fun getAccounts(): Collection<GithubAccount> = getGHEAccounts()
override fun onAccountListChanged(old: Collection<GithubAccount>, new: Collection<GithubAccount>) {
super.onAccountListChanged(old.filter { it.isGHEAccount }, new.filter { it.isGHEAccount })
}
override fun onAccountCredentialsChanged(account: GithubAccount) {
if (account.isGHEAccount) super.onAccountCredentialsChanged(account)
}
override fun createLoginPanel(account: GithubAccount?, cancelHandler: () -> Unit): JComponent =
GHECloneDialogLoginPanel(account).apply {
Disposer.register(this@GHECloneDialogExtensionComponent, this)
loginPanel.isCancelVisible = getAccounts().isNotEmpty()
loginPanel.setCancelHandler(cancelHandler)
}
override fun createAccountMenuLoginActions(account: GithubAccount?): Collection<AccountMenuItem.Action> =
listOf(createLoginAction(account))
private fun createLoginAction(account: GithubAccount?): AccountMenuItem.Action {
val isExistingAccount = account != null
return AccountMenuItem.Action(
message("login.to.github.enterprise.action"),
{ switchToLogin(account) },
showSeparatorAbove = !isExistingAccount
)
}
}
private class GHECloneDialogLoginPanel(account: GithubAccount?) : BorderLayoutPanel(), Disposable {
private val titlePanel =
simplePanel().apply {
val title = JBLabel(message("login.to.github.enterprise"), ComponentStyle.LARGE).apply { font = JBFont.label().biggerOn(5.0f) }
addToLeft(title)
}
val loginPanel = CloneDialogLoginPanel(account).apply {
Disposer.register(this@GHECloneDialogLoginPanel, this)
if (account == null) setServer("", true)
setTokenUi()
}
init {
addToTop(titlePanel.apply { border = JBEmptyBorder(getRegularPanelInsets().apply { bottom = 0 }) })
addToCenter(loginPanel)
}
override fun dispose() = loginPanel.cancelLogin()
} | apache-2.0 | 3afb189867f0d4c6e92431f7a144d689 | 41.160377 | 140 | 0.800806 | 4.77861 | false | false | false | false |
smmribeiro/intellij-community | java/debugger/impl/src/com/intellij/debugger/memory/agent/parsers/Parsers.kt | 12 | 9833 | // 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.debugger.memory.agent.parsers
import com.intellij.debugger.engine.ReferringObject
import com.intellij.debugger.memory.agent.*
import com.intellij.openapi.util.Pair
import com.sun.jdi.*
import java.util.*
import kotlin.collections.ArrayList
object StringParser : ResultParser<String> {
override fun parse(value: Value): String {
if (value is StringReference) {
return value.value()
}
throw UnexpectedValueFormatException("String value is expected")
}
}
object BooleanParser : ResultParser<Boolean> {
override fun parse(value: Value): Boolean {
if (value is BooleanValue) {
return value.value()
}
throw UnexpectedValueFormatException("Boolean value is expected")
}
}
object LongValueParser : ResultParser<Long> {
override fun parse(value: Value): Long {
if (value is PrimitiveValue) {
return value.longValue()
}
throw UnexpectedValueFormatException("Primitive value is expected")
}
}
object ObjectReferencesParser : ResultParser<List<ObjectReference>> {
override fun parse(value: Value): List<ObjectReference> {
if (value is ArrayReference) {
val result = ArrayList<ObjectReference>()
for (item in value.values) {
if (item !is ObjectReference) break
result.add(item)
}
if (result.size != value.length()) {
throw UnexpectedValueFormatException(
"All values should be object references but some of them are not")
}
return result
}
throw UnexpectedValueFormatException("Array with object references expected")
}
}
object ObjectsReferencesInfoParser : ResultParser<ReferringObjectsInfo> {
override fun parse(value: Value): ReferringObjectsInfo {
if (value !is ArrayReference) throw UnexpectedValueFormatException("Array of arrays is expected")
if (value.length() != 3) throw UnexpectedValueFormatException(
"Array must represent 3 values: objects, backward references and weak/soft reachability flags")
val objects = ObjectReferencesParser.parse(value.getValue(0))
val weakSoftReachable = BooleanArrayParser.parse(value.getValue(2))
val backwardReferences = parseLinksInfos(objects, weakSoftReachable, value.getValue(1))
return ReferringObjectsInfo(objects, backwardReferences)
}
private fun parseLinksInfos(
objects: List<ObjectReference>,
weakSoftReachable: List<Boolean>,
value: Value): List<List<ReferringObject>> {
if (value !is ArrayReference) throw UnexpectedValueFormatException("Array of arrays is expected")
val result = ArrayList<List<ReferringObject>>()
for (linksInfo in value.values) {
if (linksInfo !is ArrayReference) throw UnexpectedValueFormatException("Object references information should be represented by array")
val indices = IntArrayParser.parse(linksInfo.getValue(0))
val kinds = IntArrayParser.parse(linksInfo.getValue(1))
val infos = linksInfo.getValue(2) as? ArrayReference ?:
throw UnexpectedValueFormatException("Object references information should be represented by array")
val distinctIndices = mutableSetOf<Int>()
val referenceInfos = LinkedList<ReferringObject>()
val rootReferenceKinds = mutableListOf<MemoryAgentReferenceKind>()
for ((i, index) in indices.withIndex()) {
if (index == -1) {
rootReferenceKinds.add(MemoryAgentReferenceKind.valueOf(kinds[i]))
} else if (!distinctIndices.contains(index)) {
distinctIndices.add(index)
referenceInfos.add(
MemoryAgentReferringObjectCreator.createReferringObject(
objects[index],
MemoryAgentReferenceKind.valueOf(kinds[i]),
weakSoftReachable[index],
infos.getValue(i)
)
)
}
}
if (rootReferenceKinds.isNotEmpty()) {
referenceInfos.add(0, CompoundRootReferringObject(rootReferenceKinds.toTypedArray()))
}
result.add(referenceInfos)
}
return result
}
}
object IntArrayParser : ResultParser<List<Int>> {
override fun parse(value: Value): List<Int> {
if (value !is ArrayReference) throw UnexpectedValueFormatException("Array expected")
val items = value.values
if (items.isEmpty()) return emptyList()
if (items[0] !is IntegerValue) throw UnexpectedValueFormatException("array elements should be integers")
return items.map { it as IntegerValue }.map(IntegerValue::value)
}
}
object LongArrayParser : ResultParser<List<Long>> {
override fun parse(value: Value): List<Long> {
if (value !is ArrayReference) throw UnexpectedValueFormatException("Array expected")
return value.values.map(LongValueParser::parse)
}
}
object ShallowAndRetainedSizeParser : ResultParser<Pair<List<Long>, List<Long>>> {
override fun parse(value: Value): Pair<List<Long>, List<Long>> {
if (value !is ArrayReference) throw UnexpectedValueFormatException("Array expected")
if (value.length() < 2) throw UnexpectedValueFormatException("Two arrays expected")
return Pair(
LongArrayParser.parse(value.getValue(0)),
LongArrayParser.parse(value.getValue(1))
)
}
}
object SizeAndHeldObjectsParser : ResultParser<Pair<Array<Long>, Array<ObjectReference>>> {
override fun parse(value: Value): Pair<Array<Long>, Array<ObjectReference>> {
if (value !is ArrayReference) throw UnexpectedValueFormatException("Array expected")
if (value.length() < 2) throw UnexpectedValueFormatException("array of longs and array of objects expected")
return Pair(
LongArrayParser.parse(value.getValue(0)).toTypedArray(),
ObjectReferencesParser.parse(value.getValue(1)).toTypedArray()
)
}
}
object ErrorCodeParser : ResultParser<Pair<MemoryAgentActionResult.ErrorCode, Value>> {
override fun parse(value: Value): Pair<MemoryAgentActionResult.ErrorCode, Value> {
if (value !is ArrayReference) throw UnexpectedValueFormatException("Array expected")
return Pair(
MemoryAgentActionResult.ErrorCode.valueOf(
IntArrayParser.parse(value.getValue(0))[0]
),
value.getValue(1)
)
}
}
object BooleanArrayParser : ResultParser<List<Boolean>> {
override fun parse(value: Value): List<Boolean> {
if (value !is ArrayReference) throw UnexpectedValueFormatException("Array expected")
return value.values.map(BooleanParser::parse)
}
}
object StringArrayParser : ResultParser<List<String?>> {
override fun parse(value: Value): List<String?> {
if (value !is ArrayReference) throw UnexpectedValueFormatException("Array expected")
return value.values.map { it?.let { StringParser.parse(it) } }
}
}
object MemoryAgentReferringObjectCreator {
fun createRootReferringObject(
kind: MemoryAgentReferenceKind,
value: Value?): GCRootReferringObject {
return if (value == null) GCRootReferringObject(kind) else
when (kind) {
MemoryAgentReferenceKind.STACK_LOCAL -> {
if (value !is ArrayReference) return GCRootReferringObject(kind)
val methodName = StringArrayParser.parse(value.getValue(1))[0] ?: return GCRootReferringObject(kind)
val longs = LongArrayParser.parse(value.getValue(0))
StackLocalReferringObject(kind, methodName, longs[0], longs[1])
}
MemoryAgentReferenceKind.JNI_LOCAL -> {
if (value !is ArrayReference) return GCRootReferringObject(kind)
val longs = LongArrayParser.parse(value.getValue(0))
JNILocalReferringObject(kind, longs[0], longs[1])
}
else -> GCRootReferringObject(kind)
}
}
fun createReferringObject(
referrer: ObjectReference,
kind: MemoryAgentReferenceKind,
isWeakSoftReachable: Boolean,
value: Value?): MemoryAgentReferringObject {
return if (value == null) MemoryAgentKindReferringObject(referrer, isWeakSoftReachable, kind) else
when (kind) {
MemoryAgentReferenceKind.FIELD,
MemoryAgentReferenceKind.STATIC_FIELD -> {
val field = getFieldByJVMTIFieldIndex(referrer, IntArrayParser.parse(value)[0]) ?:
return MemoryAgentKindReferringObject(referrer, isWeakSoftReachable, kind)
MemoryAgentFieldReferringObject(referrer, isWeakSoftReachable, field)
}
MemoryAgentReferenceKind.CONSTANT_POOL ->
MemoryAgentConstantPoolReferringObject(referrer, IntArrayParser.parse(value)[0])
MemoryAgentReferenceKind.ARRAY_ELEMENT ->
MemoryAgentArrayReferringObject(referrer as ArrayReference, isWeakSoftReachable, IntArrayParser.parse(value)[0])
MemoryAgentReferenceKind.TRUNCATE ->
MemoryAgentTruncatedReferringObject(referrer, isWeakSoftReachable, IntArrayParser.parse(value)[0])
else -> MemoryAgentKindReferringObject(referrer, isWeakSoftReachable, kind)
}
}
/***
* For a detailed algorithm description see
* https://docs.oracle.com/javase/8/docs/platform/jvmti/jvmti.html#jvmtiHeapReferenceInfoField
*/
private fun getFieldByJVMTIFieldIndex(reference: ObjectReference, index: Int): Field? {
if (index < 0) {
return null
}
val allFields = reference.referenceType().allFields()
val it: ListIterator<Field> = allFields.listIterator(allFields.size)
var currIndex = index
var declaringType: ReferenceType? = null
while (it.hasPrevious()) {
val field = it.previous()
if (field.declaringType() != declaringType) {
declaringType = field.declaringType()
val fields = declaringType.fields()
if (currIndex < fields.size) {
return fields[currIndex]
}
currIndex -= fields.size
}
}
return null
}
}
| apache-2.0 | 2e0945572be9d735e21fd464cdf0d955 | 37.712598 | 140 | 0.711787 | 4.352811 | false | false | false | false |
devjn/GithubSearch | ios/src/main/kotlin/com/github/devjn/githubsearch/db/SQLiteDatabaseHelper.kt | 1 | 3044 | package com.github.devjn.githubsearch.db
import apple.foundation.c.Foundation
import apple.foundation.enums.NSSearchPathDirectory
import apple.foundation.enums.NSSearchPathDomainMask
import com.github.devjn.githubsearch.database.ISQLiteDatabase
import com.github.devjn.githubsearch.database.ISQLiteDatabaseHelper
import com.github.devjn.githubsearch.model.db.DataSource
import com.github.devjn.githubsearch.model.entities.UserEntity
import com.github.devjn.githubsearch.utils.Utils
import org.moe.natj.general.ptr.Ptr
import org.moe.natj.general.ptr.VoidPtr
import org.moe.natj.general.ptr.impl.PtrFactory
import org.sqlite.c.Globals
import java.io.File
import java.io.IOException
import java.io.InputStream
class SQLiteDatabaseHelper() : ISQLiteDatabaseHelper {
private var connectionHandle: VoidPtr? = null
init {
try {
init()
} catch (e: Exception) {
connectionHandle = null
}
}
@Throws(IOException::class)
private fun init() {
// Get path to database
val docPath = documentsPath
if (docPath == null) {
System.err.println("Failed to load app's document path")
return
}
val file = File(docPath, DataSource.DATABASE_NAME)
// Check existence
val isNew = !file.exists()
// Open database
@SuppressWarnings("unchecked")
val dbHandleRef = PtrFactory.newPointerPtr(Void::class.java, 2, 1, true, false) as Ptr<VoidPtr>
if (Globals.sqlite3_open(file.canonicalPath, dbHandleRef) != 0) {
throw IOException("Failed to open/create database file")
}
connectionHandle = dbHandleRef.get()
// Initialize
if (isNew) {
onCreate(writableDatabase)
} else {
// onUpdate(getWritableDatabase());
}
}
private fun onCreate(sqLiteDatabase: ISQLiteDatabase) {
Utils.executeSQLStatement(sqLiteDatabase, Utils.createTableSQL(DataSource.Tables.BOOKMARKS,
UserEntity.fields))
}
@SuppressWarnings("unused")
private fun onUpdate(sqLiteDatabase: ISQLiteDatabase) {
Utils.executeSQLStatement(sqLiteDatabase, Utils.dropTableIfExistsSQL(DataSource.Tables.BOOKMARKS))
onCreate(sqLiteDatabase)
}
private val documentsPath: String?
get() {
val paths = Foundation.NSSearchPathForDirectoriesInDomains(
NSSearchPathDirectory.DocumentDirectory,
NSSearchPathDomainMask.UserDomainMask, true)
return paths.firstObject()
}
override val writableDatabase: ISQLiteDatabase
get() = SQLiteDatabase(connectionHandle)
override fun close() {
if (connectionHandle != null) {
Globals.sqlite3_close(connectionHandle)
connectionHandle = null
}
}
override val defaultDatabaseContents: InputStream?
get() = null
} | apache-2.0 | d45803517d77e7728b0ba3f3d3e39005 | 30.752688 | 106 | 0.65276 | 4.476471 | false | false | false | false |
fabmax/kool | kool-core/src/jsMain/kotlin/de/fabmax/kool/platform/webgl/TextureLoader.kt | 1 | 5719 | package de.fabmax.kool.platform.webgl
import de.fabmax.kool.JsImpl.gl
import de.fabmax.kool.pipeline.*
import de.fabmax.kool.platform.*
import de.fabmax.kool.platform.WebGL2RenderingContext.Companion.TEXTURE_3D
import de.fabmax.kool.util.Float32BufferImpl
import de.fabmax.kool.util.Uint16BufferImpl
import de.fabmax.kool.util.Uint8BufferImpl
import org.khronos.webgl.ArrayBufferView
import org.khronos.webgl.WebGLRenderingContext
import org.khronos.webgl.WebGLRenderingContext.Companion.NONE
import org.khronos.webgl.WebGLRenderingContext.Companion.RGBA
import org.khronos.webgl.WebGLRenderingContext.Companion.TEXTURE_2D
import org.khronos.webgl.WebGLRenderingContext.Companion.TEXTURE_CUBE_MAP
import org.khronos.webgl.WebGLRenderingContext.Companion.TEXTURE_CUBE_MAP_NEGATIVE_X
import org.khronos.webgl.WebGLRenderingContext.Companion.TEXTURE_CUBE_MAP_NEGATIVE_Y
import org.khronos.webgl.WebGLRenderingContext.Companion.TEXTURE_CUBE_MAP_NEGATIVE_Z
import org.khronos.webgl.WebGLRenderingContext.Companion.TEXTURE_CUBE_MAP_POSITIVE_X
import org.khronos.webgl.WebGLRenderingContext.Companion.TEXTURE_CUBE_MAP_POSITIVE_Y
import org.khronos.webgl.WebGLRenderingContext.Companion.TEXTURE_CUBE_MAP_POSITIVE_Z
import org.khronos.webgl.WebGLRenderingContext.Companion.UNPACK_COLORSPACE_CONVERSION_WEBGL
import org.khronos.webgl.WebGLRenderingContext.Companion.UNSIGNED_BYTE
import kotlin.math.floor
import kotlin.math.log2
import kotlin.math.max
object TextureLoader {
fun loadTexture1d(ctx: JsContext, props: TextureProps, img: TextureData) : LoadedTextureWebGl {
// 1d texture internally uses a 2d texture
val tex = LoadedTextureWebGl(ctx, TEXTURE_2D, gl.createTexture(), img.estimateTexSize())
tex.setSize(img.width, 1, 1)
tex.applySamplerProps(props)
texImage2d(gl, TEXTURE_2D, img)
if (props.mipMapping) {
gl.generateMipmap(TEXTURE_2D)
}
return tex
}
fun loadTexture2d(ctx: JsContext, props: TextureProps, img: TextureData) : LoadedTextureWebGl {
val gl = ctx.gl
val tex = LoadedTextureWebGl(ctx, TEXTURE_2D, gl.createTexture(), img.estimateTexSize())
tex.setSize(img.width, img.height, 1)
tex.applySamplerProps(props)
texImage2d(gl, TEXTURE_2D, img)
if (props.mipMapping) {
gl.generateMipmap(TEXTURE_2D)
}
return tex
}
fun loadTexture3d(ctx: JsContext, props: TextureProps, img: TextureData) : LoadedTextureWebGl {
val tex = LoadedTextureWebGl(ctx, TEXTURE_3D, gl.createTexture(), img.estimateTexSize())
tex.setSize(img.width, img.height, img.depth)
tex.applySamplerProps(props)
when (img) {
is TextureData3d -> {
gl.texImage3D(TEXTURE_3D, 0, img.format.glInternalFormat, img.width, img.height, img.depth, 0, img.format.glFormat, img.format.glType, img.arrayBufferView)
}
is ImageAtlasTextureData -> {
gl.texStorage3D(TEXTURE_3D, 1, img.format.glInternalFormat, img.width, img.height, img.depth)
for (z in 0 until img.depth) {
gl.texSubImage3D(TEXTURE_3D, 0, 0, 0, z, img.width, img.height, 1, img.format.glFormat, img.format.glType, img.data[z])
}
}
}
if (props.mipMapping) {
gl.generateMipmap(TEXTURE_3D)
}
return tex
}
fun loadTextureCube(ctx: JsContext, props: TextureProps, img: TextureDataCube) : LoadedTextureWebGl {
val gl = ctx.gl
val tex = LoadedTextureWebGl(ctx, TEXTURE_CUBE_MAP, gl.createTexture(), img.estimateTexSize())
tex.setSize(img.width, img.height, 1)
tex.applySamplerProps(props)
texImage2d(gl, TEXTURE_CUBE_MAP_POSITIVE_X, img.right)
texImage2d(gl, TEXTURE_CUBE_MAP_NEGATIVE_X, img.left)
texImage2d(gl, TEXTURE_CUBE_MAP_POSITIVE_Y, img.up)
texImage2d(gl, TEXTURE_CUBE_MAP_NEGATIVE_Y, img.down)
texImage2d(gl, TEXTURE_CUBE_MAP_POSITIVE_Z, img.back)
texImage2d(gl, TEXTURE_CUBE_MAP_NEGATIVE_Z, img.front)
if (props.mipMapping) {
gl.generateMipmap(TEXTURE_CUBE_MAP)
}
return tex
}
private fun texImage2d(gl: WebGLRenderingContext, target: Int, data: TextureData) {
gl.pixelStorei(UNPACK_COLORSPACE_CONVERSION_WEBGL, NONE)
when (data) {
is TextureData1d -> {
gl.texImage2D(target, 0, data.format.glInternalFormat, data.width, 1, 0, data.format.glFormat, data.format.glType, data.arrayBufferView)
}
is TextureData2d -> {
gl.texImage2D(target, 0, data.format.glInternalFormat, data.width, data.height, 0, data.format.glFormat, data.format.glType, data.arrayBufferView)
}
is ImageTextureData -> {
gl.texImage2D(target, 0, RGBA, RGBA, UNSIGNED_BYTE, data.data)
}
else -> {
throw IllegalArgumentException("Invalid TextureData type for texImage2d: $data")
}
}
}
private fun TextureData.estimateTexSize(): Int {
val layers = if (this is TextureDataCube) 6 else 1
val mipLevels = floor(log2(max(width, height).toDouble())).toInt() + 1
return Texture.estimatedTexSize(width, height, layers, mipLevels, format.pxSize)
}
private val TextureData.arrayBufferView: ArrayBufferView
get() = when (val bufData = data) {
is Uint8BufferImpl -> bufData.buffer
is Uint16BufferImpl -> bufData.buffer
is Float32BufferImpl -> bufData.buffer
else -> throw IllegalArgumentException("Unsupported buffer type")
}
} | apache-2.0 | de484702086d82cba46ee7c3710df17f | 44.396825 | 171 | 0.684735 | 3.723307 | false | false | false | false |
JetBrains/xodus | entity-store/src/main/kotlin/jetbrains/exodus/entitystore/PersistentEntityStoreRefactorings.kt | 1 | 53014 | /**
* Copyright 2010 - 2022 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
@file:Suppress("NAME_SHADOWING")
package jetbrains.exodus.entitystore
import jetbrains.exodus.*
import jetbrains.exodus.bindings.*
import jetbrains.exodus.core.dataStructures.IntArrayList
import jetbrains.exodus.core.dataStructures.LongArrayList
import jetbrains.exodus.core.dataStructures.hash.*
import jetbrains.exodus.core.dataStructures.persistent.PersistentLong23TreeSet
import jetbrains.exodus.core.dataStructures.persistent.PersistentLongSet
import jetbrains.exodus.entitystore.PersistentEntityStoreImpl.*
import jetbrains.exodus.entitystore.iterate.EntityIterableBase
import jetbrains.exodus.entitystore.tables.*
import jetbrains.exodus.env.*
import jetbrains.exodus.env.StoreConfig.USE_EXISTING
import jetbrains.exodus.env.StoreConfig.WITHOUT_DUPLICATES_WITH_PREFIXING
import jetbrains.exodus.kotlin.notNull
import jetbrains.exodus.log.CompressedUnsignedLongByteIterable
import jetbrains.exodus.util.ByteArraySizedInputStream
import mu.KLogging
import java.util.*
import kotlin.experimental.xor
class PersistentEntityStoreRefactorings(private val store: PersistentEntityStoreImpl) {
fun refactorDeleteRedundantBlobs() {
val blobVault = store.blobVault
if (blobVault is FileSystemBlobVaultOld) {
logInfo("Deleting redundant blobs...")
val nextBlobHandle = store.computeInReadonlyTransaction { tx ->
val txn = tx as PersistentStoreTransaction
blobVault.nextHandle(txn.environmentTransaction)
}
for (i in 0..9999) {
val item = blobVault.getBlob(nextBlobHandle + i)
if (item.exists()) {
if (blobVault.delete(item.handle)) {
logInfo("Deleted $item")
} else {
logger.error("Failed to delete $item")
}
}
}
}
}
fun refactorCreateNullPropertyIndices() {
store.executeInReadonlyTransaction { txn ->
txn as PersistentStoreTransaction
var cursorValueToDelete: ArrayByteIterable? = null
var propTypeToDelete: ComparableValueType? = null
for (entityType in store.getEntityTypes(txn)) {
logInfo("Refactoring creating null-value property indices for [$entityType]")
val entityTypeId = store.getEntityTypeId(txn, entityType, false)
val props = store.getPropertiesTable(txn, entityTypeId)
val aFieldIds = IntArrayList()
val aLocalIds = LongArrayList()
val dFieldIds = IntArrayList()
val dLocalIds = LongArrayList()
fun dumpAdded() {
if (!aFieldIds.isEmpty) {
store.environment.executeInExclusiveTransaction { txn ->
val allPropsIndex = props.allPropsIndex
for (i in 0 until aFieldIds.size()) {
allPropsIndex.put(txn, aFieldIds[i], aLocalIds[i])
}
}
aFieldIds.clear()
aLocalIds.clear()
}
}
fun dumpDeleted() {
if (!dFieldIds.isEmpty) {
store.executeInExclusiveTransaction { txn ->
txn as PersistentStoreTransaction
for (i in 0 until dFieldIds.size()) {
props.delete(
txn, dLocalIds[i], cursorValueToDelete.notNull, dFieldIds[i], propTypeToDelete.notNull
)
}
}
dFieldIds.clear()
dLocalIds.clear()
}
}
store.getPrimaryPropertyIndexCursor(txn, entityTypeId).use { cursor ->
while (cursor.next) {
val propKey = PropertyKey.entryToPropertyKey(cursor.key)
val cursorValue = ArrayByteIterable(cursor.value)
val propValue = store.propertyTypes.entryToPropertyValue(cursorValue)
val data = propValue.data
val fieldId = propKey.propertyId
val localId = propKey.entityLocalId
if (data !is Boolean || data == true) {
aFieldIds.add(fieldId)
aLocalIds.add(localId)
if (aFieldIds.size() == 1000) {
dumpAdded()
}
} else {
dFieldIds.add(fieldId)
dLocalIds.add(localId)
cursorValueToDelete = cursorValue
propTypeToDelete = propValue.type
if (dFieldIds.size() == 1000) {
dumpDeleted()
}
}
}
}
dumpAdded()
dumpDeleted()
}
}
}
fun refactorCreateNullBlobIndices() {
safeExecuteRefactoringForEachEntityType("Refactoring creating null-value blob indices") { entityType, txn ->
val entityTypeId = store.getEntityTypeId(txn, entityType, false)
val blobs = store.getBlobsTable(txn, entityTypeId)
val allBlobsIndex = blobs.allBlobsIndex
val envTxn = txn.environmentTransaction
blobs.primaryIndex.openCursor(envTxn).use { cursor ->
while (cursor.next) {
val propertyKey = PropertyKey.entryToPropertyKey(cursor.key)
allBlobsIndex.put(envTxn, propertyKey.propertyId, propertyKey.entityLocalId)
}
}
}
}
fun refactorBlobFileLengths() {
val blobVault = store.blobVault
if (blobVault is DiskBasedBlobVault) {
val diskVault = blobVault as DiskBasedBlobVault
safeExecuteRefactoringForEachEntityType("Refactoring blob lengths table") { entityType, txn ->
val entityTypeId = store.getEntityTypeId(txn, entityType, false)
val blobs = store.getBlobsTable(txn, entityTypeId)
val envTxn = txn.environmentTransaction
blobs.primaryIndex.openCursor(envTxn).use { cursor ->
while (cursor.next) {
val blobHandle = LongBinding.compressedEntryToLong(cursor.value)
if (!isEmptyOrInPlaceBlobHandle(blobHandle)) {
store.setBlobFileLength(txn, blobHandle,
diskVault.getBlobLocation(blobHandle).length())
}
}
}
}
}
}
fun refactorCreateNullLinkIndices() {
store.executeInReadonlyTransaction { txn ->
txn as PersistentStoreTransaction
for (entityType in store.getEntityTypes(txn)) {
logInfo("Refactoring creating null-value link indices for [$entityType]")
safeExecuteRefactoringForEntityType(entityType,
object : StoreTransactionalExecutable {
override fun execute(tx: StoreTransaction) {
val txn = tx as PersistentStoreTransaction
val entityTypeId = store.getEntityTypeId(txn, entityType, false)
var links = store.getLinksTable(txn, entityTypeId)
var allLinksIndex = links.allLinksIndex
val envTxn = txn.environmentTransaction
if (allLinksIndex.getStore().count(envTxn) > 0) {
logger.warn("Refactoring creating null-value link indices looped for [$entityType]")
envTxn.environment.truncateStore(allLinksIndex.getStore().name, envTxn)
store.linksTables.remove(entityTypeId)
links = store.getLinksTable(txn, entityTypeId)
allLinksIndex = links.allLinksIndex
}
val readonlySnapshot = envTxn.readonlySnapshot
try {
val cursor = links.getSecondIndexCursor(readonlySnapshot)
val total = links.getSecondaryCount(readonlySnapshot)
var done: Long = 0
var prevLinkId = -1
val idSet = PersistentLong23TreeSet().beginWrite()
val format = "done %4.1f%% for $entityType"
while (cursor.next) {
val linkKey = PropertyKey.entryToPropertyKey(cursor.value)
val linkId = linkKey.propertyId
val entityLocalId = linkKey.entityLocalId
if (prevLinkId != linkId) {
if (prevLinkId == -1) {
prevLinkId = linkId
} else {
if (linkId < prevLinkId) {
throw IllegalStateException("Unsorted index")
}
done = dumpSetAndFlush(
format,
allLinksIndex,
txn,
total.toDouble(),
done,
prevLinkId,
idSet
)
prevLinkId = linkId
}
}
idSet.add(entityLocalId)
}
if (prevLinkId != -1) {
dumpSetAndFlush(
format,
allLinksIndex,
txn,
total.toDouble(),
done,
prevLinkId,
idSet
)
}
cursor.close()
} finally {
readonlySnapshot.abort()
}
}
private fun dumpSetAndFlush(
format: String,
allLinksIndex: FieldIndex,
txn: PersistentStoreTransaction,
total: Double,
done: Long,
prevLinkId: Int,
idSet: PersistentLongSet.MutableSet
): Long {
var done = done
val itr = idSet.longIterator()
while (itr.hasNext()) {
allLinksIndex.put(txn.environmentTransaction, prevLinkId, itr.nextLong())
done++
if (done % 10000 == 0L) {
logInfo(String.format(format, done.toDouble() * 100 / total))
}
if (done % 100000 == 0L && !txn.flush()) {
throw IllegalStateException("cannot flush")
}
}
idSet.clear()
return done
}
}
)
}
}
}
fun refactorDropEmptyPrimaryLinkTables() {
store.executeInReadonlyTransaction { txn ->
txn as PersistentStoreTransaction
for (entityType in store.getEntityTypes(txn)) {
runReadonlyTransactionSafeForEntityType(entityType) {
val envTxn = txn.environmentTransaction
val entityTypeId = store.getEntityTypeId(txn, entityType, false)
val linksTable = store.getLinksTable(txn, entityTypeId)
val primaryCount = linksTable.getPrimaryCount(envTxn)
if (primaryCount != 0L && linksTable.getSecondaryCount(envTxn) == 0L) {
store.environment.executeInTransaction { txn -> linksTable.truncateFirst(txn) }
logInfo("Drop links' tables when primary index is empty for [$entityType]")
}
}
}
}
}
fun refactorMakeLinkTablesConsistent(internalSettings: Store) {
store.executeInReadonlyTransaction { txn ->
txn as PersistentStoreTransaction
for (entityType in store.getEntityTypes(txn)) {
logInfo("Refactoring making links' tables consistent for [$entityType]")
runReadonlyTransactionSafeForEntityType(entityType) {
val redundantLinks = ArrayList<Pair<ByteIterable, ByteIterable>>()
val deleteLinks = ArrayList<Pair<ByteIterable, ByteIterable>>()
val entityTypeId = store.getEntityTypeId(txn, entityType, false)
val linksTable = store.getLinksTable(txn, entityTypeId)
val envTxn = txn.environmentTransaction
val all = (txn.getAll(entityType) as EntityIterableBase).toSet(txn)
val linkFilter = PackedLongHashSet()
val redundantLinkTypes = IntHashSet()
val deletedLinkTypes = IntHashSet()
val deletedLinkIds = IntHashSet()
linksTable.getFirstIndexCursor(envTxn).use { cursor ->
while (cursor.next) {
val first = cursor.key
val second = cursor.value
var linkValue: LinkValue? = null
val localId = LongBinding.compressedEntryToLong(first)
if (!all.contains(entityTypeId, localId)) {
try {
linkValue = LinkValue.entryToLinkValue(second)
deletedLinkTypes.add(linkValue.entityId.typeId)
deletedLinkIds.add(linkValue.linkId)
} catch (_: ExodusException) {
} catch (_: ArrayIndexOutOfBoundsException) {
}
do {
deleteLinks.add(ArrayByteIterable(first) to ArrayByteIterable(second))
} while (cursor.nextDup)
continue
} else {
linkFilter.add((first.hashCode().toLong() shl 31) + second.hashCode().toLong())
}
if (linkValue == null) {
try {
linkValue = LinkValue.entryToLinkValue(second)
} catch (ignore: ArrayIndexOutOfBoundsException) {
deleteLinks.add(ArrayByteIterable(first) to ArrayByteIterable(second))
}
}
if (linkValue != null) {
val targetEntityId = linkValue.entityId
// if target doesn't exist
if (store.getLastVersion(txn, targetEntityId) < 0) {
deletedLinkTypes.add(targetEntityId.typeId)
deletedLinkIds.add(linkValue.linkId)
deleteLinks.add(ArrayByteIterable(first) to ArrayByteIterable(second))
continue
} else {
linkFilter.add((first.hashCode().toLong() shl 31) + second.hashCode().toLong())
}
if (!linksTable.contains2(envTxn, first, second)) {
redundantLinkTypes.add(targetEntityId.typeId)
redundantLinks.add(ArrayByteIterable(first) to ArrayByteIterable(second))
}
}
}
}
if (redundantLinks.isNotEmpty()) {
store.environment.executeInExclusiveTransaction { txn ->
for (badLink in redundantLinks) {
linksTable.put(txn, badLink.first, badLink.second)
}
}
logInfo(redundantLinks.size.toString() + " missing links found for [" + entityType + ']')
redundantLinks.clear()
}
linksTable.getSecondIndexCursor(envTxn).use { cursor ->
while (cursor.next) {
val second = cursor.key
val first = cursor.value
if (!linkFilter.contains((first.hashCode().toLong() shl 31) + second.hashCode().toLong())) {
if (!linksTable.contains(envTxn, first, second)) {
redundantLinks.add(ArrayByteIterable(first) to ArrayByteIterable(second))
}
}
}
}
val redundantLinksSize = redundantLinks.size
val deleteLinksSize = deleteLinks.size
if (redundantLinksSize > 0 || deleteLinksSize > 0) {
store.environment.executeInExclusiveTransaction { txn ->
for (redundantLink in redundantLinks) {
deletePair(linksTable.getSecondIndexCursor(txn),
redundantLink.first,
redundantLink.second)
}
for (deleteLink in deleteLinks) {
deletePair(linksTable.getFirstIndexCursor(txn), deleteLink.first, deleteLink.second)
deletePair(linksTable.getSecondIndexCursor(txn), deleteLink.second, deleteLink.first)
}
}
if (logger.isInfoEnabled) {
if (redundantLinksSize > 0) {
val redundantLinkTypeNames = ArrayList<String>(redundantLinkTypes.size)
for (typeId in redundantLinkTypes) {
redundantLinkTypeNames.add(store.getEntityType(txn, typeId))
}
logInfo("$redundantLinksSize redundant links found and fixed for [$entityType] and targets: $redundantLinkTypeNames")
}
if (deleteLinksSize > 0) {
val deletedLinkTypeNames = ArrayList<String>(deletedLinkTypes.size)
for (typeId in deletedLinkTypes) {
try {
val entityTypeName = store.getEntityType(txn, typeId)
deletedLinkTypeNames.add(entityTypeName)
} catch (t: Throwable) {
// ignore
}
}
val deletedLinkIdsNames = ArrayList<String>(deletedLinkIds.size)
for (typeId in deletedLinkIds) {
try {
val linkName = store.getLinkName(txn, typeId)
linkName?.let { deletedLinkIdsNames.add(linkName) }
} catch (t: Throwable) {
// ignore
}
}
logInfo("$deleteLinksSize phantom links found and fixed for [$entityType] and targets: $deletedLinkTypeNames")
logInfo("Link types: $deletedLinkIdsNames")
}
}
}
Settings.delete(internalSettings, "Link null-indices present") // reset link null indices
}
}
}
}
fun refactorMakePropTablesConsistent() {
store.executeInReadonlyTransaction { txn ->
txn as PersistentStoreTransaction
for (entityType in store.getEntityTypes(txn)) {
logInfo("Refactoring making props' tables consistent for [$entityType]")
runReadonlyTransactionSafeForEntityType(entityType) {
val entityTypeId = store.getEntityTypeId(txn, entityType, false)
val propTable = store.getPropertiesTable(txn, entityTypeId)
val envTxn = txn.environmentTransaction
val props = IntHashMap<LongHashMap<PropertyValue>>()
val all = (txn.getAll(entityType) as EntityIterableBase).toSet(txn)
val propertyTypes = store.propertyTypes
val entitiesToDelete = LongHashSet()
store.getPrimaryPropertyIndexCursor(txn, propTable).use { cursor ->
while (cursor.next) {
val propKey = PropertyKey.entryToPropertyKey(cursor.key)
val localId = propKey.entityLocalId
if (!all.contains(entityTypeId, localId)) {
entitiesToDelete.add(localId)
continue
}
val propValue = propertyTypes.entryToPropertyValue(cursor.value)
val propId = propKey.propertyId
var entitiesToValues = props[propId]
if (entitiesToValues == null) {
entitiesToValues = LongHashMap()
props[propId] = entitiesToValues
}
entitiesToValues[localId] = propValue
}
}
if (!entitiesToDelete.isEmpty()) {
store.executeInExclusiveTransaction { txn ->
txn as PersistentStoreTransaction
for (localId in entitiesToDelete) {
store.deleteEntity(txn,
PersistentEntity(store, PersistentEntityId(entityTypeId, localId)))
}
}
}
val missingPairs = ArrayList<Pair<Int, Pair<ByteIterable, ByteIterable>>>()
val allPropsMap = IntHashMap<MutableSet<Long>>()
for (propId in props.keys) {
val valueIndex = propTable.getValueIndex(txn, propId, false)
val valueCursor = valueIndex?.openCursor(envTxn)
val entitiesToValues = props[propId]
entitiesToValues?.let {
val localIdSet: Set<Long> = entitiesToValues.keys
val sortedLocalIdSet = TreeSet(localIdSet)
allPropsMap[propId] = sortedLocalIdSet
val localIds = sortedLocalIdSet.toTypedArray()
for (localId in localIds) {
val propValue = checkNotNull(entitiesToValues[localId])
for (secondaryKey in PropertiesTable.createSecondaryKeys(
propertyTypes, PropertyTypes.propertyValueToEntry(propValue), propValue.type)) {
val secondaryValue: ByteIterable = LongBinding.longToCompressedEntry(localId)
if (valueCursor == null || !valueCursor.getSearchBoth(secondaryKey, secondaryValue)) {
missingPairs.add(propId to (secondaryKey to secondaryValue))
}
}
}
}
valueCursor?.close()
}
if (missingPairs.isNotEmpty()) {
store.executeInExclusiveTransaction { tx ->
val txn = tx as PersistentStoreTransaction
for (pair in missingPairs) {
val valueIndex = propTable.getValueIndex(txn, pair.first, true)
val missing = pair.second
if (valueIndex == null) {
throw NullPointerException("Can't be")
}
valueIndex.put(txn.environmentTransaction, missing.first, missing.second)
}
}
logInfo("${missingPairs.size} missing secondary keys found and fixed for [$entityType]")
}
val phantomPairs = ArrayList<Pair<Int, Pair<ByteIterable, ByteIterable>>>()
for ((propId, value1) in propTable.valueIndices) {
val entitiesToValues = props[propId] ?: continue
val c = value1.openCursor(envTxn)
while (c.next) {
val keyEntry = c.key
val valueEntry = c.value
val propValue = entitiesToValues[LongBinding.compressedEntryToLong(valueEntry)]
if (propValue != null) {
val data = propValue.data
val typeId = propValue.type.typeId
val dataClass: Class<out Comparable<Any>>?
val objectBinding: ComparableBinding
if (typeId == ComparableValueType.COMPARABLE_SET_VALUE_TYPE) {
@Suppress("UNCHECKED_CAST")
dataClass = (data as ComparableSet<Comparable<Any>>).itemClass
if (dataClass == null) {
phantomPairs.add(propId to (ArrayByteIterable(keyEntry) to ArrayByteIterable(valueEntry)))
continue
}
objectBinding = propertyTypes.getPropertyType(dataClass).binding
} else {
dataClass = data.javaClass
objectBinding = propValue.binding
}
try {
val value = objectBinding.entryToObject(keyEntry)
if (dataClass == value.javaClass) {
if (typeId == ComparableValueType.COMPARABLE_SET_VALUE_TYPE) {
if ((data as ComparableSet<*>).containsItem(value)) {
continue
}
} else if (PropertyTypes.toLowerCase(data).compareTo(value) == 0) {
continue
}
}
} catch (t: Throwable) {
logger.error("Error reading property value index ", t)
throwJVMError(t)
}
}
phantomPairs.add(propId to (ArrayByteIterable(keyEntry) to ArrayByteIterable(valueEntry)))
}
c.close()
}
if (phantomPairs.isNotEmpty()) {
store.executeInExclusiveTransaction { tx ->
val txn = tx as PersistentStoreTransaction
val envTxn = txn.environmentTransaction
for (pair in phantomPairs) {
val valueIndex = propTable.getValueIndex(txn, pair.first, true)
val phantom = pair.second
if (valueIndex == null) {
throw NullPointerException("Can't be")
}
deletePair(valueIndex.openCursor(envTxn), phantom.first, phantom.second)
}
}
logInfo("${phantomPairs.size} phantom secondary keys found and fixed for [$entityType]")
}
val phantomIds = ArrayList<Pair<Int, Long>>()
propTable.allPropsIndex.iterable(envTxn, 0).forEach { pair ->
val propId = pair.first
val localId = pair.second
val localIds = allPropsMap[propId]
if (localIds == null || !localIds.remove(localId)) {
phantomIds.add(Pair(propId, localId))
} else if (localIds.isEmpty()) {
allPropsMap.remove(propId)
}
}
if (!allPropsMap.isEmpty()) {
val added = store.computeInExclusiveTransaction { txn ->
var count = 0
val allPropsIndex = propTable.allPropsIndex
val envTxn = (txn as PersistentStoreTransaction).environmentTransaction
for ((key, value) in allPropsMap) {
for (localId in value) {
allPropsIndex.put(envTxn, key, localId)
++count
}
}
count
}
logInfo("$added missing id pairs found and fixed for [$entityType]")
}
if (phantomIds.isNotEmpty()) {
store.executeInExclusiveTransaction { txn ->
val envTxn = (txn as PersistentStoreTransaction).environmentTransaction
phantomIds.forEach { phantom ->
propTable.allPropsIndex.remove(envTxn,phantom.first, phantom.second)
}
}
logInfo("${phantomIds.size} phantom id pairs found and fixed for [$entityType]")
}
}
}
}
}
fun refactorFixNegativeFloatAndDoubleProps(settings: Store) {
store.executeInReadonlyTransaction { tx ->
for (entityType in store.getEntityTypes(tx as PersistentStoreTransaction).toList()) {
store.executeInTransaction { t ->
val txn = t as PersistentStoreTransaction
val settingName = "refactorFixNegativeFloatAndDoubleProps($entityType) applied"
if (Settings.get(txn.environmentTransaction, settings, settingName) == "y") {
return@executeInTransaction
}
logInfo("Refactoring fixing negative float & double props for [$entityType]")
val entityTypeId = store.getEntityTypeId(txn, entityType, false)
val propTable = store.getPropertiesTable(txn, entityTypeId)
val props = HashMap<PropertyKey, Pair<PropertyValue, ByteIterable>>()
val propertyTypes = store.propertyTypes
store.getPrimaryPropertyIndexCursor(txn, propTable).use { cursor ->
while (cursor.next) {
try {
ArrayByteIterable(cursor.value).let {
val propertyType = propertyTypes.getPropertyType((it.iterator()
.next() xor (0x80).toByte()).toInt())
when (propertyType.typeId) {
ComparableValueType.FLOAT_VALUE_TYPE -> {
props[PropertyKey.entryToPropertyKey(cursor.key)] =
propertyTypes.entryToPropertyValue(it, FloatBinding.BINDING) to it
}
ComparableValueType.DOUBLE_VALUE_TYPE -> {
props[PropertyKey.entryToPropertyKey(cursor.key)] =
propertyTypes.entryToPropertyValue(it, DoubleBinding.BINDING) to it
}
else -> {
}
}
}
} catch (_: Throwable) {
}
}
}
if (props.isNotEmpty()) {
props.keys.sortedBy { it.entityLocalId }.forEach { key ->
props[key]?.let { (propValue, it) ->
propTable.put(txn, key.entityLocalId,
PropertyTypes.propertyValueToEntry(propValue),
it, key.propertyId, propValue.type)
}
}
logInfo("${props.size} negative float & double props fixed.")
}
Settings.set(txn.environmentTransaction, settings, settingName, "y")
}
}
}
}
fun refactorBlobsToVersion2Format(settings: Store) {
fun dumpInPlaceBlobs(entityTypeId: Int, inPlaceBlobs: List<Pair<PropertyKey, ArrayByteIterable>>) {
store.executeInExclusiveTransaction { txn ->
txn as PersistentStoreTransaction
val blobsTable = store.getBlobsTable(txn, entityTypeId)
inPlaceBlobs.forEach { (blobKey, it) ->
blobsTable.put(txn.environmentTransaction,
blobKey.entityLocalId, blobKey.propertyId,
CompoundByteIterable(arrayOf(
store.blobHandleToEntry(IN_PLACE_BLOB_HANDLE), it))
)
}
}
}
store.executeInReadonlyTransaction { txn ->
for (entityType in store.getEntityTypes(txn as PersistentStoreTransaction).toList()) {
val settingName = "refactorBlobsToVersion2Format($entityType)"
val envTxn = txn.environmentTransaction
if (Settings.get(envTxn, settings, settingName) == "y") continue
val entityTypeId = store.getEntityTypeId(txn, entityType, false)
val blobsObsoleteTableName = store.namingRules.getBlobsObsoleteTableName(entityTypeId)
if (!store.environment.storeExists(blobsObsoleteTableName, envTxn)) continue
logInfo("Refactor blobs to version 2 format for [$entityType]")
val inPlaceBlobs = ArrayList<Pair<PropertyKey, ArrayByteIterable>>()
val blobHandles = ArrayList<Pair<PropertyKey, Long>>()
val oldBlobsTable = BlobsTable(store, txn, blobsObsoleteTableName, USE_EXISTING)
oldBlobsTable.primaryIndex.openCursor(envTxn).use { cursor ->
while (cursor.next) {
try {
val blobKey = PropertyKey.entryToPropertyKey(cursor.key)
val it = cursor.value.iterator()
when (val blobHandle = LongBinding.readCompressed(it)) {
IN_PLACE_BLOB_HANDLE -> {
inPlaceBlobs.add(blobKey to ArrayByteIterable(it))
if (inPlaceBlobs.size > 100) {
dumpInPlaceBlobs(entityTypeId, inPlaceBlobs)
inPlaceBlobs.clear()
}
}
else -> {
blobHandles.add(blobKey to blobHandle)
}
}
} catch (t: Throwable) {
logger.error("$settingName: error reading blobs", t)
throwJVMError(t)
}
}
}
if (inPlaceBlobs.isNotEmpty()) {
dumpInPlaceBlobs(entityTypeId, inPlaceBlobs)
}
store.executeInExclusiveTransaction { txn ->
txn as PersistentStoreTransaction
val blobsTable = store.getBlobsTable(txn, entityTypeId)
blobHandles.forEach { (blobKey, handle) ->
blobsTable.put(
txn.environmentTransaction,
blobKey.entityLocalId, blobKey.propertyId, store.blobHandleToEntry(handle)
)
}
safeRemoveStore(oldBlobsTable.primaryIndex.name, txn.environmentTransaction)
safeRemoveStore(oldBlobsTable.allBlobsIndex.getStore().name, txn.environmentTransaction)
}
store.environment.executeInExclusiveTransaction { txn ->
Settings.set(txn, settings, settingName, "y")
}
}
}
}
fun refactorEntitiesTablesToBitmap(settings: Store) {
fun dumpEntitiesAndFlush(tableName: String, entityIds: LongArrayList) {
store.executeInExclusiveTransaction { txn ->
txn as PersistentStoreTransaction
val entityOfTypeBitmap = store.environment.openBitmap(
tableName,
WITHOUT_DUPLICATES_WITH_PREFIXING,
txn.environmentTransaction
)
val oldEntitiesTable = SingleColumnTable(txn, tableName, USE_EXISTING)
entityIds.toArray().forEach { id ->
entityOfTypeBitmap.set(txn.environmentTransaction, id, true)
}
safeRemoveStore(oldEntitiesTable.database.name, txn.environmentTransaction)
}
}
store.executeInReadonlyTransaction { txn ->
for (entityType in store.getEntityTypes(txn as PersistentStoreTransaction).toList()) {
val settingName = "refactorEntitiesTablesToBitmap($entityType)"
val envTxn = txn.environmentTransaction
if (Settings.get(envTxn, settings, settingName) == "y") continue
val entityTypeId = store.getEntityTypeId(txn, entityType, false)
val obsoleteTableName = store.namingRules.getEntitiesTableName(entityTypeId)
if (!store.environment.storeExists(obsoleteTableName, envTxn)) continue
logInfo("Refactor entities of [$entityType] type table to bitmap")
val entityIds = LongArrayList()
SingleColumnTable(txn, obsoleteTableName, USE_EXISTING).database.openCursor(envTxn).use { cursor ->
while (cursor.next) {
entityIds.add(LongBinding.compressedEntryToLong(cursor.key))
}
}
if (!entityIds.isEmpty) {
dumpEntitiesAndFlush(obsoleteTableName, entityIds)
}
store.environment.executeInExclusiveTransaction { txn ->
Settings.set(txn, settings, settingName, "y")
}
}
}
}
fun refactorAllPropsIndexToBitmap() {
refactorAllIdxToBitmap("allPropsIndex") { entityTypeId ->
store.namingRules.getPropertiesTableName(entityTypeId) + Table.ALL_IDX
}
}
fun refactorAllLinksIndexToBitmap() {
refactorAllIdxToBitmap("allLinksIndex") { entityTypeId ->
store.namingRules.getLinksTableName(entityTypeId) + Table.ALL_IDX
}
}
fun refactorAllBlobsIndexToBitmap() {
refactorAllIdxToBitmap("allBlobsIndex") { entityTypeId ->
store.namingRules.getBlobsTableName(entityTypeId) + Table.ALL_IDX
}
}
fun refactorDeduplicateInPlaceBlobsPeriodically(settings: Store) {
store.environment.executeBeforeGc {
refactorDeduplicateInPlaceBlobs(settings)
}
}
@Deprecated(message = "This method can be used in tests only.")
fun refactorDeduplicateInPlaceBlobs() {
val env = store.environment
val store = env.computeInTransaction { txn ->
env.openStore("TestSettings", StoreConfig.WITHOUT_DUPLICATES, txn)
}
refactorDeduplicateInPlaceBlobs(store)
}
private fun refactorDeduplicateInPlaceBlobs(settings: Store) {
class DuplicateFoundException : ExodusException()
store.executeInReadonlyTransaction { txn ->
val config = store.config
for (entityType in store.getEntityTypes(txn as PersistentStoreTransaction).toList()) {
val settingName = "refactorDeduplicateInPlaceBlobs($entityType) applied"
val envTxn = txn.environmentTransaction
val lastApplied = Settings.get(envTxn, settings, settingName)
if ((lastApplied?.toLong() ?: 0L) +
(config.refactoringDeduplicateBlobsEvery.toLong() * 24L * 3600L * 1000L) > System.currentTimeMillis()) continue
logInfo("Deduplicate in-place blobs for [$entityType]")
val entityTypeId = store.getEntityTypeId(txn, entityType, false)
val inPlaceBlobs = IntHashMap<PropertyKey>()
val blobs = store.getBlobsTable(txn, entityTypeId)
blobs.primaryIndex.openCursor(envTxn).use { cursor ->
while (cursor.next) {
try {
val blobKey = PropertyKey.entryToPropertyKey(cursor.key)
val it = cursor.value.iterator()
val blobHandle = LongBinding.readCompressed(it)
// if in-place blob in the v2 format
if (blobHandle == 1L) {
val size = CompressedUnsignedLongByteIterable.getLong(it).toInt()
if (size < config.refactoringDeduplicateBlobsMinSize) continue
val stream = ByteArraySizedInputStream(ByteIterableBase.readIterator(it, size))
val streamHash = stream.hashCode()
inPlaceBlobs[streamHash]?.let { key ->
// due to snapshot isolation, we can read a value by stored in memory key
// as many times as we wish even if the value is being changed in nested txns
val testValue = blobs.get(envTxn, key)
testValue?.iterator()?.let { testIt ->
// skip handle
LongBinding.readCompressed(testIt)
// if duplicate
if (size == CompressedUnsignedLongByteIterable.getLong(testIt).toInt() && stream ==
ByteArraySizedInputStream(ByteIterableBase.readIterator(testIt, size))
) {
store.executeInExclusiveTransaction { txn ->
val blobHashes = store.getBlobHashesTable(
txn as PersistentStoreTransaction, entityTypeId
)
val hashEntry = IntegerBinding.intToEntry(streamHash)
val envTxn = txn.environmentTransaction
blobHashes.database.put(
envTxn, hashEntry,
ArrayByteIterable(stream.toByteArray(), size)
)
val refValue = CompoundByteIterable(
arrayOf(
store.blobHandleToEntry(IN_PLACE_BLOB_REFERENCE_HANDLE),
CompressedUnsignedLongByteIterable.getIterable(size.toLong()),
hashEntry
)
)
blobs.put(envTxn, key.entityLocalId, key.propertyId, refValue)
blobs.put(envTxn, blobKey.entityLocalId, blobKey.propertyId, refValue)
}
throw DuplicateFoundException()
}
}
}
inPlaceBlobs.putIfAbsent(streamHash, blobKey)
}
} catch (found: DuplicateFoundException) {
// it's okay, do nothing
} catch (t: Throwable) {
logger.error(
"refactorDeduplicateInPlaceBlobs(): error reading blobs for [$entityType]",
t
)
throwJVMError(t)
}
}
}
store.environment.executeInExclusiveTransaction { txn ->
Settings.set(txn, settings, settingName, System.currentTimeMillis().toString())
}
}
}
}
private fun refactorAllIdxToBitmap(indexName: String, getIndexName: (Int) -> String) {
store.executeInReadonlyTransaction { txn ->
for (entityType in store.getEntityTypes(txn as PersistentStoreTransaction)) {
val entityTypeId = store.getEntityTypeId(txn, entityType, false)
val obsoleteName = getIndexName(entityTypeId)
if (!store.environment.storeExists(obsoleteName, txn.environmentTransaction)) continue
logInfo("Refactoring $indexName to bitmaps for [$entityType]")
safeExecuteRefactoringForEntityType(entityType) { txn ->
txn as PersistentStoreTransaction
val envTxn = txn.environmentTransaction
val allPropsIndexBitmap =
envTxn.environment.openBitmap(obsoleteName, WITHOUT_DUPLICATES_WITH_PREFIXING, envTxn)
envTxn.environment.openStore(obsoleteName, USE_EXISTING, envTxn).openCursor(envTxn).use { c ->
while (c.next) {
val propertyId = IntegerBinding.compressedEntryToInt(c.key)
val localId = LongBinding.compressedEntryToLong(c.value)
allPropsIndexBitmap.set(envTxn, (propertyId.toLong() shl 32) + localId, true)
}
}
safeRemoveStore(obsoleteName, envTxn)
}
}
}
}
private fun safeExecuteRefactoringForEachEntityType(message: String,
executable: (String, PersistentStoreTransaction) -> Unit) {
val entityTypes = store.computeInReadonlyTransaction { txn ->
store.getEntityTypes(txn as PersistentStoreTransaction)
}
for (entityType in entityTypes) {
logInfo("$message for [$entityType]")
safeExecuteRefactoringForEntityType(entityType) { txn ->
executable(entityType, txn as PersistentStoreTransaction)
}
}
}
private fun safeExecuteRefactoringForEntityType(entityType: String, executable: StoreTransactionalExecutable) {
try {
store.executeInTransaction(executable)
} catch (t: Throwable) {
logger.error("Failed to execute refactoring for entity type: $entityType", t)
throwJVMError(t)
}
}
private fun safeRemoveStore(name: String, txn: Transaction) {
try {
with(txn.environment) {
if (storeExists(name, txn)) {
removeStore(name, txn);
}
}
} catch (e: ExodusException) {
logger.error("Failed to remove store $name", e)
}
}
companion object : KLogging() {
private fun runReadonlyTransactionSafeForEntityType(entityType: String, action: () -> Unit) {
try {
action()
} catch (ignore: ReadonlyTransactionException) {
// that fixes XD-377, XD-492 and similar not reported issues
} catch (t: Throwable) {
logger.error("Failed to execute refactoring for entity type: $entityType", t)
throwJVMError(t)
}
}
private fun deletePair(c: Cursor, key: ByteIterable, value: ByteIterable) {
c.use {
if (c.getSearchBoth(key, value)) {
c.deleteCurrent()
}
}
}
private fun throwJVMError(t: Throwable) {
if (t is VirtualMachineError) {
throw EntityStoreException(t)
}
}
private fun logInfo(message: String) {
if (logger.isInfoEnabled) {
logger.info(message)
}
}
}
}
| apache-2.0 | 98fcbf521170ca92688ccbf02b74249b | 53.151175 | 149 | 0.470197 | 6.321727 | false | false | false | false |
JetBrains/xodus | sshd/src/main/kotlin/jetbrains/exodus/javascript/RhinoCommand.kt | 1 | 10567 | /**
* Copyright 2010 - 2022 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package jetbrains.exodus.javascript
import jetbrains.exodus.core.dataStructures.NanoSet
import jetbrains.exodus.core.dataStructures.Priority
import jetbrains.exodus.core.execution.Job
import jetbrains.exodus.entitystore.PersistentEntityStoreImpl
import jetbrains.exodus.env.EnvironmentImpl
import jetbrains.exodus.kotlin.notNull
import org.apache.sshd.server.Environment
import org.apache.sshd.server.ExitCallback
import org.apache.sshd.server.channel.ChannelSession
import org.apache.sshd.server.command.Command
import org.mozilla.javascript.*
import org.mozilla.javascript.tools.ToolErrorReporter
import java.awt.event.KeyEvent
import java.io.*
abstract class RhinoCommand(protected val config: Map<String, *>) : Job(), Command {
companion object {
internal fun createCommand(config: Map<String, *>): RhinoCommand {
return when (config[API_LAYER]) {
ENVIRONMENTS -> EnvironmentRhinoCommand(config)
ENTITY_STORES -> EntityStoreRhinoCommand(config)
else -> throw IllegalArgumentException("The value of apiLayer should be 'Environments' or 'EntityStores'")
}
}
const val TXN_PARAM = "txn"
const val API_LAYER = "apiLayer"
const val ENVIRONMENTS = "environments"
const val ENTITY_STORES = "entitystores"
const val CONSOLE = "console"
const val ENVIRONMENT_INSTANCE = "environment instance"
const val ENTITY_STORE_INSTANCE = "entity store instance"
private const val JS_ENGINE_VERSION_PARAM = "jsEngineVersion"
private const val CONFIG_PARAM = "config"
private const val INTEROP_PARAM = "interop"
private val FORBIDDEN_CLASSES = NanoSet("java.lang.System")
private const val RECENT_COMMANDS_LIST_MAX_SIZE = 1000
private fun isPrintableChar(c: Char): Boolean {
val block = Character.UnicodeBlock.of(c)
return !Character.isISOControl(c) &&
c != KeyEvent.CHAR_UNDEFINED &&
block != null &&
block !== Character.UnicodeBlock.SPECIALS
}
}
private var callback: ExitCallback? = null
private var input: InputStream? = null
private var stopped = false
private var output: PrintStream? = null
private var error: PrintStream? = null
private val recentCommands: MutableList<String> = arrayListOf()
override fun setExitCallback(callback: ExitCallback?) {
this.callback = callback
}
override fun setInputStream(input: InputStream?) {
this.input = input
}
override fun destroy(channel: ChannelSession) {
stopped = true
}
override fun setErrorStream(err: OutputStream?) {
error = toPrintStream(err)
}
override fun setOutputStream(out: OutputStream?) {
output = toPrintStream(out)
}
override fun start(channel: ChannelSession, env: Environment?) {
processor = RhinoServer.commandProcessor
queue(Priority.normal)
}
override fun execute() {
val cx = Context.enter()
cx.setClassShutter { !FORBIDDEN_CLASSES.contains(it) }
cx.errorReporter = object : ErrorReporter {
override fun warning(message: String?, sourceName: String?, line: Int, lineSource: String?, lineOffset: Int) {
// ignore
}
override fun runtimeError(message: String?, sourceName: String?, line: Int, lineSource: String?, lineOffset: Int): EvaluatorException {
return EvaluatorException(message, sourceName, line, lineSource, lineOffset)
}
override fun error(message: String?, sourceName: String?, line: Int, lineSource: String?, lineOffset: Int) {
val out = output.notNull
if (sourceName != null) {
out.print("$sourceName: ")
}
if (line > 0) {
out.print("$line: ")
}
out.println(message)
out.flush()
}
}
try {
processInput(cx)
} finally {
try {
callback?.onExit(0)
} finally {
stopped = true
Context.exit()
}
}
}
protected fun evalResourceScripts(cx: Context, scope: Scriptable, vararg names: String) {
names.forEach {
cx.evaluateReader(scope, InputStreamReader(this.javaClass.getResourceAsStream(it)), it, 1, null)
}
}
fun evalFileSystemScript(cx: Context, scope: Scriptable, fileName: String) {
cx.evaluateReader(scope, FileReader(fileName), fileName, 1, null)
}
protected fun processScript(interop: Interop, script: Script, cx: Context, scope: Scriptable?) {
val result = script.exec(cx, scope)
if (result !== Context.getUndefinedValue()) {
interop.println(result)
}
}
protected open fun evalInitScripts(cx: Context, scope: Scriptable) {
evalResourceScripts(cx, scope, "bindings.js", "functions.js")
}
protected abstract fun evalTransactionalScript(cx: Context, script: Script, interop: Interop, scope: Scriptable)
private fun processInput(cx: Context) {
Interop(this, output.notNull,
config[ENVIRONMENT_INSTANCE] as? EnvironmentImpl,
config[ENTITY_STORE_INSTANCE] as? PersistentEntityStoreImpl).use { interop ->
interop.flushOutput()
val scope = createScope(cx, interop)
evalInitScripts(cx, scope)
while (!stopped) {
interop.printPrompt()
val cmd = buildString { readLine(this, interop) }
try {
if (cmd.isNotBlank()) {
// exit
if (cmd.equals("exit", true) || cmd.equals("quit", true)) {
if (isConsole) {
interop.println("Press Enter to $cmd...")
}
break
}
recentCommands.add(cmd)
if (recentCommands.size > RECENT_COMMANDS_LIST_MAX_SIZE) {
recentCommands.removeAt(0)
}
val script = cx.compileString(ScriptPreprocessor.preprocess { cmd }, "<stdin>", 0, null)
if (script != null) {
val start = System.currentTimeMillis()
// execute script in transaction if an Environment or an EntityStore is open
evalTransactionalScript(cx, script, interop, scope)
interop.println("Completed in ${(System.currentTimeMillis() - start)} ms")
}
}
} catch (rex: RhinoException) {
ToolErrorReporter.reportException(cx.errorReporter, rex)
} catch (ex: VirtualMachineError) {
// Treat StackOverflow and OutOfMemory as runtime errors
ex.printStackTrace()
Context.reportError(ex.toString())
}
}
}
}
private fun createScope(cx: Context, interop: Interop): Scriptable {
interop.cx = cx
val scope = cx.initStandardObjects(null, true)
interop.scope = scope
val config = NativeObject()
this.config.forEach {
config.defineProperty(it.key, it.value, NativeObject.READONLY)
}
config.defineProperty(JS_ENGINE_VERSION_PARAM, cx.implementationVersion, NativeObject.READONLY)
ScriptableObject.putProperty(scope, CONFIG_PARAM, config)
ScriptableObject.putProperty(scope, INTEROP_PARAM, Context.javaToJS(interop, scope))
return scope
}
private fun readLine(s: StringBuilder, interop: Interop) {
val inp = input ?: return
var cmdIdx = recentCommands.size
while (!stopped) {
val c = inp.read()
if (c == -1 || c == 3 || c == 26) break
val ch = c.toChar()
if (ch == '\n') {
if (!isConsole) {
interop.newLine()
}
break
}
when (c) {
// backspace
127 ->
if (s.isNotEmpty()) {
s.deleteCharAt(s.length - 1)
interop.backspace()
}
// up or down
27 -> {
inp.read()
var newCmdIdx = cmdIdx
val upOrDown = inp.read()
if (upOrDown == 65) {
--newCmdIdx
} else if (upOrDown == 66) {
++newCmdIdx
}
if (newCmdIdx >= 0 && newCmdIdx <= recentCommands.size && newCmdIdx != cmdIdx) {
cmdIdx = newCmdIdx
if (s.isNotEmpty()) {
interop.backspace(s.length)
s.delete(0, s.length)
}
if (newCmdIdx < recentCommands.size) {
s.append(recentCommands[cmdIdx])
}
interop.print(s)
}
}
else ->
if (isPrintableChar(ch)) {
if (!isConsole) {
interop.printChar(ch)
}
s.append(ch)
}
}
}
}
private fun toPrintStream(out: OutputStream?): PrintStream? {
return if (out == null) null else PrintStream(out)
}
private val isConsole = true == config[CONSOLE]
} | apache-2.0 | 70fd419fbfcba4ac9ae0f25189443dfc | 37.710623 | 147 | 0.552569 | 4.867342 | false | true | false | false |
Briseus/Lurker | app/src/main/java/torille/fi/lurkforreddit/subreddit/SubredditPresenter.kt | 1 | 4912 | package torille.fi.lurkforreddit.subreddit
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.CompositeDisposable
import io.reactivex.observers.DisposableObserver
import io.reactivex.schedulers.Schedulers
import timber.log.Timber
import torille.fi.lurkforreddit.data.RedditRepository
import torille.fi.lurkforreddit.data.models.view.Post
import torille.fi.lurkforreddit.data.models.view.Subreddit
import torille.fi.lurkforreddit.utils.MediaHelper
import torille.fi.lurkforreddit.utils.test.EspressoIdlingResource
import javax.inject.Inject
class SubredditPresenter @Inject
internal constructor(
private val redditRepository: RedditRepository,
private val subreddit: Subreddit
) : SubredditContract.Presenter {
private var subredditsView: SubredditContract.View? = null
private var nextPageId: String? = null
private var firstLoad = true
private val disposables = CompositeDisposable()
override fun openComments(clickedPost: Post) {
subredditsView?.showCommentsUI(clickedPost)
}
override fun openCustomTabs(url: String) {
subredditsView?.showCustomTabsUI(url)
}
override fun openMedia(post: Post) {
val domain = post.domain
val url = post.url
when {
MediaHelper.isContentMedia(url, domain) -> subredditsView?.showMedia(post)
MediaHelper.launchCustomActivity(post.domain) -> subredditsView?.launchCustomActivity(
post
)
post.isSelf -> openComments(post)
else -> subredditsView?.showCustomTabsUI(url)
}
}
override fun loadPosts() {
subredditsView?.setProgressIndicator(true)
// The network request might be handled in a different thread so make sure Espresso knows
// that the appm is busy until the response is handled.
EspressoIdlingResource.increment() // App is busy until further notice
disposables.add(
redditRepository.getSubredditPosts(subreddit.url)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribeWith(object : DisposableObserver<kotlin.Pair<String, List<Post>>>() {
override fun onNext(posts: kotlin.Pair<String, List<Post>>) {
Timber.d("Got posts to presenter")
nextPageId = posts.first
subredditsView?.showPosts(posts.second, posts.first)
}
override fun onError(e: Throwable) {
Timber.e("Got error")
Timber.e(e)
subredditsView?.onError(e.toString())
subredditsView?.setProgressIndicator(false)
}
override fun onComplete() {
Timber.d("Completed")
EspressoIdlingResource.decrement()
subredditsView?.setProgressIndicator(false)
}
})
)
}
override fun loadMorePosts() {
subredditsView?.setListProgressIndicator(true)
EspressoIdlingResource.increment()
if (nextPageId.isNullOrEmpty()) {
Timber.d("No more posts")
// TODO show no more posts
} else {
Timber.d("Fetching more posts at ${subreddit.url} subId $nextPageId")
disposables.add(redditRepository.getMoreSubredditPosts(subreddit.url, nextPageId!!)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribeWith(object : DisposableObserver<kotlin.Pair<String, List<Post>>>() {
override fun onNext(@io.reactivex.annotations.NonNull postsPair: kotlin.Pair<String, List<Post>>) {
nextPageId = postsPair.first
subredditsView?.setListProgressIndicator(false)
subredditsView?.addMorePosts(postsPair.second, postsPair.first)
}
override fun onError(@io.reactivex.annotations.NonNull e: Throwable) {
subredditsView?.onError(e.toString())
subredditsView?.setListErrorButton(true)
}
override fun onComplete() {
EspressoIdlingResource.decrement()
}
})
)
}
}
override fun retry() {
subredditsView?.setListErrorButton(false)
loadMorePosts()
}
override fun takeView(view: SubredditContract.View) {
subredditsView = view
if (firstLoad) {
loadPosts()
firstLoad = false
}
}
override fun dropView() {
disposables.dispose()
subredditsView = null
}
}
| mit | 99fe6d6c61f7e2304de4a16f03f7bcae | 35.656716 | 119 | 0.606678 | 5.356598 | false | false | false | false |
kivensolo/UiUsingListView | app-Kotlin-Coroutines-Examples/src/main/java/com/kingz/coroutines/learn/base/UserAdapter.kt | 1 | 1334 | package com.kingz.coroutines.learn.base
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.kingz.coroutines.data.local.entity.User
import com.zeke.example.coroutines.R
import kotlinx.android.synthetic.main.item_layout.view.*
class UserAdapter(
private val users: ArrayList<User>
) : RecyclerView.Adapter<UserAdapter.DataViewHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int) =
DataViewHolder(
LayoutInflater.from(parent.context).inflate(
R.layout.item_layout, parent,
false
)
)
override fun getItemCount(): Int = users.size
override fun onBindViewHolder(holder: DataViewHolder, position: Int) =
holder.bind(users[position])
fun addData(list: List<User>) {
users.addAll(list)
}
class DataViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
fun bind(user: User) {
itemView.textViewUserName.text = user.name
itemView.textViewUserEmail.text = user.email
Glide.with(itemView.imageViewAvatar.context)
.load(user.avatar)
.into(itemView.imageViewAvatar)
}
}
} | gpl-2.0 | be278b0fbe131ecc6f469795c838ab72 | 30.046512 | 78 | 0.682159 | 4.37377 | false | false | false | false |
jwren/intellij-community | java/idea-ui/src/com/intellij/ide/starters/shared/StarterSettings.kt | 4 | 3981 | @file:JvmName("StarterSettings")
package com.intellij.ide.starters.shared
import com.intellij.openapi.projectRoots.JavaSdkVersion
import com.intellij.openapi.util.NlsContexts.DialogTitle
import com.intellij.openapi.util.NlsContexts.Label
import com.intellij.openapi.util.NlsSafe
import com.intellij.openapi.util.UserDataHolderBase
data class StarterLanguage(
val id: String,
@NlsSafe val title: String,
val languageId: String,
val isBuiltIn: Boolean = false,
@NlsSafe val description: String? = null
)
data class StarterTestRunner(
val id: String,
@NlsSafe val title: String
)
data class StarterProjectType(
val id: String,
@NlsSafe val title: String,
@NlsSafe val description: String? = null
)
data class StarterAppType(
val id: String,
@NlsSafe val title: String
)
data class StarterAppPackaging(
val id: String,
@NlsSafe val title: String,
@NlsSafe val description: String? = null
)
data class StarterLanguageLevel(
val id: String,
@NlsSafe val title: String,
/**
* Version string that can be parsed with [JavaSdkVersion.fromVersionString].
*/
val javaVersion: String
)
class CustomizedMessages {
var projectTypeLabel: @Label String? = null
var serverUrlDialogTitle: @DialogTitle String? = null
var dependenciesLabel: @Label String? = null
var selectedDependenciesLabel: @Label String? = null
var noDependenciesSelectedLabel: @Label String? = null
var frameworkVersionLabel: @Label String? = null
}
class StarterWizardSettings(
val projectTypes: List<StarterProjectType>,
val languages: List<StarterLanguage>,
val isExampleCodeProvided: Boolean,
val isPackageNameEditable: Boolean,
val languageLevels: List<StarterLanguageLevel>,
val defaultLanguageLevel: StarterLanguageLevel?,
val packagingTypes: List<StarterAppPackaging>,
val applicationTypes: List<StarterAppType>,
val testFrameworks: List<StarterTestRunner>,
val customizedMessages: CustomizedMessages?
)
class PluginRecommendation(
val pluginId: String,
val dependencyIds: List<String>
) {
constructor(pluginId: String, vararg dependencyIds: String) : this(pluginId, dependencyIds.toList())
}
interface LibraryInfo {
@get:NlsSafe
val title: String
val description: String?
val links: List<LibraryLink>
val isRequired: Boolean
val isDefault: Boolean
}
class LibraryLink(
val type: LibraryLinkType,
@NlsSafe
val url: String,
@NlsSafe
val title: String? = null
)
const val DEFAULT_MODULE_NAME: String = "demo"
const val DEFAULT_MODULE_GROUP: String = "com.example"
const val DEFAULT_MODULE_ARTIFACT: String = "demo"
const val DEFAULT_MODULE_VERSION: String = "1.0-SNAPSHOT"
const val DEFAULT_PACKAGE_NAME: String = "$DEFAULT_MODULE_GROUP.$DEFAULT_MODULE_ARTIFACT"
val JAVA_STARTER_LANGUAGE: StarterLanguage = StarterLanguage("java", "Java", "JAVA", true)
val KOTLIN_STARTER_LANGUAGE: StarterLanguage = StarterLanguage("kotlin", "Kotlin", "kotlin")
val GROOVY_STARTER_LANGUAGE: StarterLanguage = StarterLanguage("groovy", "Groovy", "Groovy")
val MAVEN_PROJECT: StarterProjectType = StarterProjectType("maven", "Maven")
val GRADLE_PROJECT: StarterProjectType = StarterProjectType("gradle", "Gradle")
val JUNIT_TEST_RUNNER: StarterTestRunner = StarterTestRunner("junit", "JUnit")
val TESTNG_TEST_RUNNER: StarterTestRunner = StarterTestRunner("testng", "TestNG")
open class CommonStarterContext : UserDataHolderBase() {
var name: String = DEFAULT_MODULE_NAME
var group: String = DEFAULT_MODULE_GROUP
var artifact: String = DEFAULT_MODULE_ARTIFACT
var version: String = DEFAULT_MODULE_VERSION
var isCreatingNewProject: Boolean = false
var gitIntegration: Boolean = false
lateinit var language: StarterLanguage
var projectType: StarterProjectType? = null
var applicationType: StarterAppType? = null
var testFramework: StarterTestRunner? = null
var includeExamples: Boolean = true
}
const val ARTIFACT_ID_PROPERTY: String = "artifactId"
const val GROUP_ID_PROPERTY: String = "groupId" | apache-2.0 | 8eae9657da0d5cf1b6d1da9a43197cd6 | 29.868217 | 102 | 0.768651 | 4.133956 | false | true | false | false |
OpenConference/DroidconBerlin2017 | app/src/main/java/de/droidcon/berlin2018/ui/speakerdetail/SpeakerDetailsJobInfoAdapterDelegate.kt | 1 | 1686 | package de.droidcon.berlin2018.ui.speakerdetail
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import com.hannesdorfmann.adapterdelegates3.AbsListItemAdapterDelegate
import de.droidcon.berlin2018.R
/**
*
*
* @author Hannes Dorfmann
*/
class SpeakerDetailsJobInfoAdapterDelegate(
val inflater: LayoutInflater) : AbsListItemAdapterDelegate<SpeakerJobInfoItem, SpeakerDetailsItem, SpeakerDetailsJobInfoAdapterDelegate.JobInfoViewHolder>() {
override fun isForViewType(item: SpeakerDetailsItem, items: MutableList<SpeakerDetailsItem>,
position: Int): Boolean = item is SpeakerJobInfoItem
override fun onBindViewHolder(item: SpeakerJobInfoItem, viewHolder: JobInfoViewHolder,
payloads: MutableList<Any>) {
viewHolder.bind(item)
}
override fun onCreateViewHolder(parent: ViewGroup) = JobInfoViewHolder(
inflater.inflate(R.layout.item_speaker_details_jobinfo, parent, false))
class JobInfoViewHolder(v: View) : RecyclerView.ViewHolder(v) {
val jobTitle = v.findViewById<TextView>(R.id.jobTitle)
val companyName = v.findViewById<TextView>(R.id.company)
inline fun bind(info: SpeakerJobInfoItem) {
val title = info.jobTitle
if (title != null) {
jobTitle.text = title
jobTitle.visibility = View.VISIBLE
} else {
jobTitle.visibility = View.GONE
}
val company = info.company
if (company != null) {
companyName.text = company
companyName.visibility = View.VISIBLE
} else {
companyName.visibility = View.GONE
}
}
}
}
| apache-2.0 | 6d43198c409a9726a1361290e1819373 | 30.811321 | 162 | 0.734875 | 4.367876 | false | false | false | false |
androidx/androidx | compose/foundation/foundation/src/commonMain/kotlin/androidx/compose/foundation/lazy/staggeredgrid/LazyStaggeredGridMeasure.kt | 3 | 29148 | /*
* Copyright 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.compose.foundation.lazy.staggeredgrid
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.fastFold
import androidx.compose.foundation.fastMaxOfOrNull
import androidx.compose.foundation.lazy.layout.LazyLayoutItemProvider
import androidx.compose.foundation.lazy.layout.LazyLayoutMeasureScope
import androidx.compose.runtime.collection.MutableVector
import androidx.compose.runtime.snapshots.Snapshot
import androidx.compose.ui.layout.Placeable
import androidx.compose.ui.unit.Constraints
import androidx.compose.ui.unit.IntOffset
import androidx.compose.ui.unit.IntSize
import androidx.compose.ui.unit.constrainHeight
import androidx.compose.ui.unit.constrainWidth
import androidx.compose.ui.util.fastForEach
import kotlin.math.abs
import kotlin.math.min
import kotlin.math.roundToInt
import kotlin.math.sign
@ExperimentalFoundationApi
internal fun LazyLayoutMeasureScope.measureStaggeredGrid(
state: LazyStaggeredGridState,
itemProvider: LazyLayoutItemProvider,
resolvedSlotSums: IntArray,
constraints: Constraints,
isVertical: Boolean,
contentOffset: IntOffset,
mainAxisAvailableSize: Int,
mainAxisSpacing: Int,
crossAxisSpacing: Int,
beforeContentPadding: Int,
afterContentPadding: Int,
): LazyStaggeredGridMeasureResult {
val context = LazyStaggeredGridMeasureContext(
state = state,
itemProvider = itemProvider,
resolvedSlotSums = resolvedSlotSums,
constraints = constraints,
isVertical = isVertical,
contentOffset = contentOffset,
mainAxisAvailableSize = mainAxisAvailableSize,
beforeContentPadding = beforeContentPadding,
afterContentPadding = afterContentPadding,
mainAxisSpacing = mainAxisSpacing,
crossAxisSpacing = crossAxisSpacing,
measureScope = this,
)
val initialItemIndices: IntArray
val initialItemOffsets: IntArray
Snapshot.withoutReadObservation {
val firstVisibleIndices = state.scrollPosition.indices
val firstVisibleOffsets = state.scrollPosition.offsets
initialItemIndices =
if (firstVisibleIndices.size == resolvedSlotSums.size) {
firstVisibleIndices
} else {
// Grid got resized (or we are in a initial state)
// Adjust indices accordingly
context.spans.reset()
IntArray(resolvedSlotSums.size).apply {
// Try to adjust indices in case grid got resized
for (lane in indices) {
this[lane] = if (
lane < firstVisibleIndices.size && firstVisibleIndices[lane] != -1
) {
firstVisibleIndices[lane]
} else {
if (lane == 0) {
0
} else {
context.findNextItemIndex(this[lane - 1], lane)
}
}
// Ensure spans are updated to be in correct range
context.spans.setSpan(this[lane], lane)
}
}
}
initialItemOffsets =
if (firstVisibleOffsets.size == resolvedSlotSums.size) {
firstVisibleOffsets
} else {
// Grid got resized (or we are in a initial state)
// Adjust offsets accordingly
IntArray(resolvedSlotSums.size).apply {
// Adjust offsets to match previously set ones
for (lane in indices) {
this[lane] = if (lane < firstVisibleOffsets.size) {
firstVisibleOffsets[lane]
} else {
if (lane == 0) 0 else this[lane - 1]
}
}
}
}
}
return context.measure(
initialScrollDelta = state.scrollToBeConsumed.roundToInt(),
initialItemIndices = initialItemIndices,
initialItemOffsets = initialItemOffsets,
canRestartMeasure = true,
)
}
@OptIn(ExperimentalFoundationApi::class)
private class LazyStaggeredGridMeasureContext(
val state: LazyStaggeredGridState,
val itemProvider: LazyLayoutItemProvider,
val resolvedSlotSums: IntArray,
val constraints: Constraints,
val isVertical: Boolean,
val measureScope: LazyLayoutMeasureScope,
val mainAxisAvailableSize: Int,
val contentOffset: IntOffset,
val beforeContentPadding: Int,
val afterContentPadding: Int,
val mainAxisSpacing: Int,
val crossAxisSpacing: Int,
) {
val measuredItemProvider = LazyStaggeredGridMeasureProvider(
isVertical,
itemProvider,
measureScope,
resolvedSlotSums
) { index, lane, key, placeables ->
val isLastInLane = spans.findNextItemIndex(index, lane) >= itemProvider.itemCount
LazyStaggeredGridMeasuredItem(
index,
key,
placeables,
isVertical,
contentOffset,
if (isLastInLane) 0 else mainAxisSpacing
)
}
val spans = state.spans
}
@ExperimentalFoundationApi
private fun LazyStaggeredGridMeasureContext.measure(
initialScrollDelta: Int,
initialItemIndices: IntArray,
initialItemOffsets: IntArray,
canRestartMeasure: Boolean,
): LazyStaggeredGridMeasureResult {
with(measureScope) {
val itemCount = itemProvider.itemCount
if (itemCount <= 0 || resolvedSlotSums.isEmpty()) {
return LazyStaggeredGridMeasureResult(
firstVisibleItemIndices = initialItemIndices,
firstVisibleItemScrollOffsets = initialItemOffsets,
consumedScroll = 0f,
measureResult = layout(constraints.minWidth, constraints.minHeight) {},
canScrollForward = false,
canScrollBackward = false,
isVertical = isVertical,
visibleItemsInfo = emptyList(),
totalItemsCount = itemCount,
viewportSize = IntSize(constraints.minWidth, constraints.minHeight),
viewportStartOffset = -beforeContentPadding,
viewportEndOffset = mainAxisAvailableSize + afterContentPadding,
beforeContentPadding = beforeContentPadding,
afterContentPadding = afterContentPadding,
)
}
// represents the real amount of scroll we applied as a result of this measure pass.
var scrollDelta = initialScrollDelta
val firstItemIndices = initialItemIndices.copyOf()
val firstItemOffsets = initialItemOffsets.copyOf()
// update spans in case item count is lower than before
ensureIndicesInRange(firstItemIndices, itemCount)
// applying the whole requested scroll offset. we will figure out if we can't consume
// all of it later
firstItemOffsets.offsetBy(-scrollDelta)
// this will contain all the MeasuredItems representing the visible items
val measuredItems = Array(resolvedSlotSums.size) {
ArrayDeque<LazyStaggeredGridMeasuredItem>()
}
// include the start padding so we compose items in the padding area. before starting
// scrolling forward we would remove it back
firstItemOffsets.offsetBy(-beforeContentPadding)
fun hasSpaceBeforeFirst(): Boolean {
for (lane in firstItemIndices.indices) {
val itemIndex = firstItemIndices[lane]
val itemOffset = firstItemOffsets[lane]
if (itemOffset < -mainAxisSpacing && itemIndex > 0) {
return true
}
}
return false
}
var laneToCheckForGaps = -1
// we had scrolled backward or we compose items in the start padding area, which means
// items before current firstItemScrollOffset should be visible. compose them and update
// firstItemScrollOffset
while (hasSpaceBeforeFirst()) {
val laneIndex = firstItemOffsets.indexOfMinValue()
val previousItemIndex = findPreviousItemIndex(
item = firstItemIndices[laneIndex],
lane = laneIndex
)
if (previousItemIndex < 0) {
laneToCheckForGaps = laneIndex
break
}
if (spans.getSpan(previousItemIndex) == LazyStaggeredGridSpans.Unset) {
spans.setSpan(previousItemIndex, laneIndex)
}
val measuredItem = measuredItemProvider.getAndMeasure(
previousItemIndex,
laneIndex
)
measuredItems[laneIndex].addFirst(measuredItem)
firstItemIndices[laneIndex] = previousItemIndex
firstItemOffsets[laneIndex] += measuredItem.sizeWithSpacings
}
fun misalignedStart(referenceLane: Int): Boolean {
// If we scrolled past the first item in the lane, we have a point of reference
// to re-align items.
val laneRange = firstItemIndices.indices
// Case 1: Each lane has laid out all items, but offsets do no match
val misalignedOffsets = laneRange.any { lane ->
findPreviousItemIndex(firstItemIndices[lane], lane) == -1 &&
firstItemOffsets[lane] != firstItemOffsets[referenceLane]
}
// Case 2: Some lanes are still missing items, and there's no space left to place them
val moreItemsInOtherLanes = laneRange.any { lane ->
findPreviousItemIndex(firstItemIndices[lane], lane) != -1 &&
firstItemOffsets[lane] >= firstItemOffsets[referenceLane]
}
// Case 3: the first item is in the wrong lane (it should always be in
// the first one)
val firstItemInWrongLane = spans.getSpan(0) != 0
// If items are not aligned, reset all measurement data we gathered before and
// proceed with initial measure
return misalignedOffsets || moreItemsInOtherLanes || firstItemInWrongLane
}
// define min offset (currently includes beforeContentPadding)
val minOffset = -beforeContentPadding
// we scrolled backward, but there were not enough items to fill the start. this means
// some amount of scroll should be left over
if (firstItemOffsets[0] < minOffset) {
scrollDelta += firstItemOffsets[0]
firstItemOffsets.offsetBy(minOffset - firstItemOffsets[0])
}
// neutralize previously added start padding as we stopped filling the before content padding
firstItemOffsets.offsetBy(beforeContentPadding)
laneToCheckForGaps =
if (laneToCheckForGaps == -1) firstItemIndices.indexOf(0) else laneToCheckForGaps
// re-check if columns are aligned after measure
if (laneToCheckForGaps != -1) {
val lane = laneToCheckForGaps
if (misalignedStart(lane) && canRestartMeasure) {
spans.reset()
return measure(
initialScrollDelta = scrollDelta,
initialItemIndices = IntArray(firstItemIndices.size) { -1 },
initialItemOffsets = IntArray(firstItemOffsets.size) {
firstItemOffsets[lane]
},
canRestartMeasure = false
)
}
}
val currentItemIndices = initialItemIndices.copyOf().apply {
// ensure indices match item count, in case it decreased
ensureIndicesInRange(this, itemCount)
}
val currentItemOffsets = IntArray(initialItemOffsets.size) {
-(initialItemOffsets[it] - scrollDelta)
}
val maxOffset = (mainAxisAvailableSize + afterContentPadding).coerceAtLeast(0)
// compose first visible items we received from state
currentItemIndices.forEachIndexed { laneIndex, itemIndex ->
if (itemIndex < 0) return@forEachIndexed
val measuredItem = measuredItemProvider.getAndMeasure(itemIndex, laneIndex)
currentItemOffsets[laneIndex] += measuredItem.sizeWithSpacings
measuredItems[laneIndex].addLast(measuredItem)
spans.setSpan(itemIndex, laneIndex)
}
// then composing visible items forward until we fill the whole viewport.
// we want to have at least one item in visibleItems even if in fact all the items are
// offscreen, this can happen if the content padding is larger than the available size.
while (
currentItemOffsets.any {
it < maxOffset ||
it <= 0 // filling beforeContentPadding area
} || measuredItems.all { it.isEmpty() }
) {
val currentLaneIndex = currentItemOffsets.indexOfMinValue()
val nextItemIndex =
findNextItemIndex(currentItemIndices[currentLaneIndex], currentLaneIndex)
if (nextItemIndex >= itemCount) {
// if any items changed its size, the spans may not behave correctly
// there are no more items in this lane, but there could be more in others
// recheck if we can add more items and reset spans accordingly
var missedItemIndex = Int.MAX_VALUE
currentItemIndices.forEachIndexed { laneIndex, i ->
if (laneIndex == currentLaneIndex) return@forEachIndexed
var itemIndex = findNextItemIndex(i, laneIndex)
while (itemIndex < itemCount) {
missedItemIndex = minOf(itemIndex, missedItemIndex)
spans.setSpan(itemIndex, LazyStaggeredGridSpans.Unset)
itemIndex = findNextItemIndex(itemIndex, laneIndex)
}
}
// there's at least one missed item which may fit current lane
if (missedItemIndex != Int.MAX_VALUE && canRestartMeasure) {
// reset current lane to the missed item index and restart measure
initialItemIndices[currentLaneIndex] =
min(initialItemIndices[currentLaneIndex], missedItemIndex)
return measure(
initialScrollDelta = initialScrollDelta,
initialItemIndices = initialItemIndices,
initialItemOffsets = initialItemOffsets,
canRestartMeasure = false
)
} else {
break
}
}
if (firstItemIndices[currentLaneIndex] == -1) {
firstItemIndices[currentLaneIndex] = nextItemIndex
}
spans.setSpan(nextItemIndex, currentLaneIndex)
val measuredItem =
measuredItemProvider.getAndMeasure(nextItemIndex, currentLaneIndex)
currentItemOffsets[currentLaneIndex] += measuredItem.sizeWithSpacings
measuredItems[currentLaneIndex].addLast(measuredItem)
currentItemIndices[currentLaneIndex] = nextItemIndex
}
// some measured items are offscreen, remove them from the list and adjust indices/offsets
for (laneIndex in measuredItems.indices) {
val laneItems = measuredItems[laneIndex]
var offset = currentItemOffsets[laneIndex]
var inBoundsIndex = 0
for (i in laneItems.lastIndex downTo 0) {
val item = laneItems[i]
offset -= item.sizeWithSpacings
inBoundsIndex = i
if (offset <= minOffset + mainAxisSpacing) {
break
}
}
// the rest of the items are offscreen, update firstIndex/Offset for lane and remove
// items from measured list
for (i in 0 until inBoundsIndex) {
val item = laneItems.removeFirst()
firstItemOffsets[laneIndex] -= item.sizeWithSpacings
}
if (laneItems.isNotEmpty()) {
firstItemIndices[laneIndex] = laneItems.first().index
}
}
// we didn't fill the whole viewport with items starting from firstVisibleItemIndex.
// lets try to scroll back if we have enough items before firstVisibleItemIndex.
if (currentItemOffsets.all { it < mainAxisAvailableSize }) {
val maxOffsetLane = currentItemOffsets.indexOfMaxValue()
val toScrollBack = mainAxisAvailableSize - currentItemOffsets[maxOffsetLane]
firstItemOffsets.offsetBy(-toScrollBack)
currentItemOffsets.offsetBy(toScrollBack)
while (
firstItemOffsets.any { it < beforeContentPadding }
) {
val laneIndex = firstItemOffsets.indexOfMinValue()
val currentIndex =
if (firstItemIndices[laneIndex] == -1) {
itemCount
} else {
firstItemIndices[laneIndex]
}
val previousIndex =
findPreviousItemIndex(currentIndex, laneIndex)
if (previousIndex < 0) {
if (misalignedStart(laneIndex) && canRestartMeasure) {
spans.reset()
return measure(
initialScrollDelta = scrollDelta,
initialItemIndices = IntArray(firstItemIndices.size) { -1 },
initialItemOffsets = IntArray(firstItemOffsets.size) {
firstItemOffsets[laneIndex]
},
canRestartMeasure = false
)
}
break
}
spans.setSpan(previousIndex, laneIndex)
val measuredItem = measuredItemProvider.getAndMeasure(
previousIndex,
laneIndex
)
measuredItems[laneIndex].addFirst(measuredItem)
firstItemOffsets[laneIndex] += measuredItem.sizeWithSpacings
firstItemIndices[laneIndex] = previousIndex
}
scrollDelta += toScrollBack
val minOffsetLane = firstItemOffsets.indexOfMinValue()
if (firstItemOffsets[minOffsetLane] < 0) {
val offsetValue = firstItemOffsets[minOffsetLane]
scrollDelta += offsetValue
currentItemOffsets.offsetBy(offsetValue)
firstItemOffsets.offsetBy(-offsetValue)
}
}
// report the amount of pixels we consumed. scrollDelta can be smaller than
// scrollToBeConsumed if there were not enough items to fill the offered space or it
// can be larger if items were resized, or if, for example, we were previously
// displaying the item 15, but now we have only 10 items in total in the data set.
val consumedScroll = if (
state.scrollToBeConsumed.roundToInt().sign == scrollDelta.sign &&
abs(state.scrollToBeConsumed.roundToInt()) >= abs(scrollDelta)
) {
scrollDelta.toFloat()
} else {
state.scrollToBeConsumed
}
val itemScrollOffsets = firstItemOffsets.copyOf().transform { -it }
// even if we compose items to fill before content padding we should ignore items fully
// located there for the state's scroll position calculation (first item + first offset)
if (beforeContentPadding > 0) {
for (laneIndex in measuredItems.indices) {
val laneItems = measuredItems[laneIndex]
for (i in laneItems.indices) {
val size = laneItems[i].sizeWithSpacings
if (
i != laneItems.lastIndex &&
firstItemOffsets[laneIndex] != 0 &&
firstItemOffsets[laneIndex] >= size
) {
firstItemOffsets[laneIndex] -= size
firstItemIndices[laneIndex] = laneItems[i + 1].index
} else {
break
}
}
}
}
// end measure
val layoutWidth = if (isVertical) {
constraints.maxWidth
} else {
constraints.constrainWidth(currentItemOffsets.max())
}
val layoutHeight = if (isVertical) {
constraints.constrainHeight(currentItemOffsets.max())
} else {
constraints.maxHeight
}
// Placement
val positionedItems = MutableVector<LazyStaggeredGridPositionedItem>(
capacity = measuredItems.sumOf { it.size }
)
while (measuredItems.any { it.isNotEmpty() }) {
// find the next item to position
val laneIndex = measuredItems.indexOfMinBy {
it.firstOrNull()?.index ?: Int.MAX_VALUE
}
val item = measuredItems[laneIndex].removeFirst()
// todo(b/182882362): arrangement support
val mainAxisOffset = itemScrollOffsets[laneIndex]
val crossAxisOffset =
if (laneIndex == 0) {
0
} else {
resolvedSlotSums[laneIndex - 1] + crossAxisSpacing * laneIndex
}
positionedItems += item.position(laneIndex, mainAxisOffset, crossAxisOffset)
itemScrollOffsets[laneIndex] += item.sizeWithSpacings
}
// todo: reverse layout support
// End placement
// only scroll backward if the first item is not on screen or fully visible
val canScrollBackward = !(firstItemIndices[0] == 0 && firstItemOffsets[0] <= 0)
// only scroll forward if the last item is not on screen or fully visible
val canScrollForward = currentItemOffsets.any { it > mainAxisAvailableSize } ||
currentItemIndices.all { it < itemCount - 1 }
@Suppress("UNCHECKED_CAST")
return LazyStaggeredGridMeasureResult(
firstVisibleItemIndices = firstItemIndices,
firstVisibleItemScrollOffsets = firstItemOffsets,
consumedScroll = consumedScroll,
measureResult = layout(layoutWidth, layoutHeight) {
positionedItems.forEach { item ->
item.place(this)
}
},
canScrollForward = canScrollForward,
canScrollBackward = canScrollBackward,
isVertical = isVertical,
visibleItemsInfo = positionedItems.asMutableList(),
totalItemsCount = itemCount,
viewportSize = IntSize(layoutWidth, layoutHeight),
viewportStartOffset = minOffset,
viewportEndOffset = maxOffset,
beforeContentPadding = beforeContentPadding,
afterContentPadding = afterContentPadding
)
}
}
private fun IntArray.offsetBy(delta: Int) {
for (i in indices) {
this[i] = this[i] + delta
}
}
internal fun IntArray.indexOfMinValue(): Int {
var result = -1
var min = Int.MAX_VALUE
for (i in indices) {
if (min > this[i]) {
min = this[i]
result = i
}
}
return result
}
private inline fun <T> Array<T>.indexOfMinBy(block: (T) -> Int): Int {
var result = -1
var min = Int.MAX_VALUE
for (i in indices) {
val value = block(this[i])
if (min > value) {
min = value
result = i
}
}
return result
}
private fun IntArray.indexOfMaxValue(): Int {
var result = -1
var max = Int.MIN_VALUE
for (i in indices) {
if (max < this[i]) {
max = this[i]
result = i
}
}
return result
}
private inline fun IntArray.transform(block: (Int) -> Int): IntArray {
for (i in indices) {
this[i] = block(this[i])
}
return this
}
private fun LazyStaggeredGridMeasureContext.ensureIndicesInRange(
indices: IntArray,
itemCount: Int
) {
// reverse traverse to make sure last items are recorded to the latter lanes
for (i in indices.indices.reversed()) {
while (indices[i] >= itemCount) {
indices[i] = findPreviousItemIndex(indices[i], i)
}
if (indices[i] != -1) {
// reserve item for span
spans.setSpan(indices[i], i)
}
}
}
private fun LazyStaggeredGridMeasureContext.findPreviousItemIndex(item: Int, lane: Int): Int =
spans.findPreviousItemIndex(item, lane)
private fun LazyStaggeredGridMeasureContext.findNextItemIndex(item: Int, lane: Int): Int =
spans.findNextItemIndex(item, lane)
@OptIn(ExperimentalFoundationApi::class)
private class LazyStaggeredGridMeasureProvider(
private val isVertical: Boolean,
private val itemProvider: LazyLayoutItemProvider,
private val measureScope: LazyLayoutMeasureScope,
private val resolvedSlotSums: IntArray,
private val measuredItemFactory: MeasuredItemFactory
) {
private fun childConstraints(slot: Int): Constraints {
val previousSum = if (slot == 0) 0 else resolvedSlotSums[slot - 1]
val crossAxisSize = resolvedSlotSums[slot] - previousSum
return if (isVertical) {
Constraints.fixedWidth(crossAxisSize)
} else {
Constraints.fixedHeight(crossAxisSize)
}
}
fun getAndMeasure(index: Int, lane: Int): LazyStaggeredGridMeasuredItem {
val key = itemProvider.getKey(index)
val placeables = measureScope.measure(index, childConstraints(lane))
return measuredItemFactory.createItem(index, lane, key, placeables)
}
}
// This interface allows to avoid autoboxing on index param
private fun interface MeasuredItemFactory {
fun createItem(
index: Int,
lane: Int,
key: Any,
placeables: List<Placeable>
): LazyStaggeredGridMeasuredItem
}
private class LazyStaggeredGridMeasuredItem(
val index: Int,
val key: Any,
val placeables: List<Placeable>,
val isVertical: Boolean,
val contentOffset: IntOffset,
val spacing: Int
) {
val mainAxisSize: Int = placeables.fastFold(0) { size, placeable ->
size + if (isVertical) placeable.height else placeable.width
}
val sizeWithSpacings: Int = (mainAxisSize + spacing).coerceAtLeast(0)
val crossAxisSize: Int = placeables.fastMaxOfOrNull {
if (isVertical) it.width else it.height
} ?: 0
fun position(
lane: Int,
mainAxis: Int,
crossAxis: Int,
): LazyStaggeredGridPositionedItem =
LazyStaggeredGridPositionedItem(
offset = if (isVertical) {
IntOffset(crossAxis, mainAxis)
} else {
IntOffset(mainAxis, crossAxis)
},
lane = lane,
index = index,
key = key,
size = if (isVertical) {
IntSize(crossAxisSize, sizeWithSpacings)
} else {
IntSize(sizeWithSpacings, crossAxisSize)
},
placeables = placeables,
contentOffset = contentOffset,
isVertical = isVertical
)
}
@OptIn(ExperimentalFoundationApi::class)
private class LazyStaggeredGridPositionedItem(
override val offset: IntOffset,
override val index: Int,
override val lane: Int,
override val key: Any,
override val size: IntSize,
private val placeables: List<Placeable>,
private val contentOffset: IntOffset,
private val isVertical: Boolean
) : LazyStaggeredGridItemInfo {
fun place(scope: Placeable.PlacementScope) = with(scope) {
placeables.fastForEach { placeable ->
if (isVertical) {
placeable.placeWithLayer(offset + contentOffset)
} else {
placeable.placeRelativeWithLayer(offset + contentOffset)
}
}
}
}
| apache-2.0 | 03530e177ad5c5d99735af80da348f44 | 37.915888 | 101 | 0.602477 | 5.413819 | false | false | false | false |
JetBrains/kotlin-native | backend.native/tests/codegen/function/defaults3.kt | 4 | 552 | /*
* Copyright 2010-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license
* that can be found in the LICENSE file.
*/
package codegen.function.defaults3
import kotlin.test.*
fun foo(a:Int = 2, b:String = "Hello", c:Int = 4):String = "$b-$c$a"
fun foo(a:Int = 3, b:Int = a + 1, c:Int = a + b) = a + b + c
@Test fun runTest() {
val a = foo(b="Universe")
if (a != "Universe-42")
throw Error()
val b = foo(b = 5)
if (b != (/* a = */ 3 + /* b = */ 5 + /* c = */ (3 + 5)))
throw Error()
} | apache-2.0 | eb7e12f0a2b05a9d614e8ebb28883e92 | 25.333333 | 101 | 0.543478 | 2.816327 | false | true | false | false |
GunoH/intellij-community | platform/platform-impl/src/com/intellij/openapi/wm/impl/PlatformFrameTitleBuilder.kt | 2 | 2597 | // 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
import com.intellij.ide.ui.UISettings
import com.intellij.openapi.project.*
import com.intellij.openapi.roots.ProjectRootManager
import com.intellij.openapi.util.io.FileUtil
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.openapi.vfs.newvfs.VfsPresentationUtil
import com.intellij.util.PlatformUtils
import org.jetbrains.annotations.NonNls
import org.jetbrains.annotations.SystemIndependent
open class PlatformFrameTitleBuilder : FrameTitleBuilder() {
override fun getProjectTitle(project: Project): String {
val basePath: @SystemIndependent @NonNls String = project.basePath ?: return project.name
val projects = ProjectManager.getInstance().openProjects
val sameNamedProjects = projects.count { it.name == project.name }
if (sameNamedProjects == 1 && !UISettings.getInstance().fullPathsInWindowHeader) {
return project.name
}
return if (basePath == project.name && !UISettings.getInstance().fullPathsInWindowHeader) {
"[${FileUtil.getLocationRelativeToUserHome(basePath)}]"
}
else {
"${project.name} [${FileUtil.getLocationRelativeToUserHome(basePath)}]"
}
}
override fun getFileTitle(project: Project, file: VirtualFile): String {
val overriddenTitle = VfsPresentationUtil.getCustomPresentableNameForUI(project, file)
return when {
overriddenTitle != null -> overriddenTitle
file.parent == null -> file.presentableName
UISettings.getInstance().fullPathsInWindowHeader -> {
displayUrlRelativeToProject(file = file,
url = file.presentableUrl,
project = project,
isIncludeFilePath = true,
moduleOnTheLeft = false)
}
else -> {
val fileIndex = ProjectRootManager.getInstance(project).fileIndex
if (!fileIndex.isInContent(file)) {
val pathWithLibrary = decorateWithLibraryName(file, project, file.presentableName)
return pathWithLibrary ?: FileUtil.getLocationRelativeToUserHome(file.presentableUrl)
}
val fileTitle = VfsPresentationUtil.getPresentableNameForUI(project, file)
if (PlatformUtils.isCidr() || PlatformUtils.isRider()) {
fileTitle
}
else {
appendModuleName(file = file, project = project, result = fileTitle, moduleOnTheLeft = false)
}
}
}
}
} | apache-2.0 | 23351f26a687f48953039b0d66ed209a | 43.033898 | 120 | 0.690797 | 5.122288 | false | false | false | false |
kai0masanari/Forcelayout | forcelayout/src/main/kotlin/jp/kai/forcelayout/properties/ForceProperty.kt | 1 | 11122 | package jp.kai.forcelayout.properties
import android.content.Context
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.util.Pair
import jp.kai.forcelayout.ATTENUATION
import jp.kai.forcelayout.COULOMB
import jp.kai.forcelayout.Links
import jp.kai.forcelayout.Nodes
import jp.kai.forcelayout.Nodes.NodePair
import jp.kai.forcelayout.properties.GraphStyle.nodesWidth
import jp.kai.forcelayout.properties.GraphStyle.roundSize
import jp.kai.forcelayout.properties.Util.Companion.getCroppedBitmap
import jp.kai.forcelayout.properties.Util.Companion.resizeBitmap
import java.util.ArrayList
import android.view.WindowManager
/**
* Created by kai on 2017/05/01.
* Builder Class
*/
class ForceProperty(private val mContext: Context){
var isReady: Boolean = false
/** node's and link's List */
internal var nodes = ArrayList<Node>()
internal var edges = ArrayList<Edge>()
var nodeIndex: Int = 0
var nEdges: Int = 0
var nodeNameArray: Array<String?> = arrayOfNulls(0)
var nodesList = ArrayList<Pair<String, Bitmap>>()
/** draw area */
private var displayWidth: Float = 0f
private var displayHeight: Float = 0f
private var drawAreaWidth: Float = 0f /** draw-area means screen-size */
private var drawAreaHeight: Float = 0f
/** spring-like force */
private var distance: Int = 300
private var bounce: Double = 0.08
private var gravity: Double = 0.04
/** node style */
private var reduction: Int = 30
internal fun prepare(): ForceProperty {
val wm = mContext.getSystemService(Context.WINDOW_SERVICE) as WindowManager
val display = wm.defaultDisplay
displayWidth = display.width.toFloat()
displayHeight = display.height.toFloat()
isReady = false
return this
}
fun size(width: Int): ForceProperty {
GraphStyle.nodesWidth = width
return this
}
fun nodes(nodemaps: ArrayList<Pair<String, Int>>): ForceProperty {
initNodes()
GraphStyle.isImgDraw = true
val resource = mContext.resources
val iterator :Iterator<Pair<String, Int>> = nodemaps.iterator()
nodeNameArray = arrayOfNulls(nodemaps.size)
while (iterator.hasNext()){
/** Node List */
val pair: Pair<String, Int> = iterator.next()
/** get image properties */
val imageOptions = BitmapFactory.Options()
imageOptions.inPreferredConfig = Bitmap.Config.ARGB_8888
imageOptions.inJustDecodeBounds = true
BitmapFactory.decodeResource(resource, pair.second, imageOptions)
val bitmapWidth = imageOptions.outWidth
val bmfOptions = BitmapFactory.Options()
/** resize image */
reduction = bitmapWidth / nodesWidth
if (reduction != 0) {
bmfOptions.inSampleSize = reduction
}
var bitmap = BitmapFactory.decodeResource(resource, pair.second, bmfOptions)
var imgheight = bmfOptions.outHeight
var imgwidth = bmfOptions.outWidth
if (imgwidth != nodesWidth) {
bitmap = resizeBitmap(bitmap, nodesWidth)
imgheight = bitmap.height
imgwidth = bitmap.width
}
drawAreaWidth = displayWidth - imgwidth
drawAreaHeight = displayHeight - imgheight
addNode(pair.first, imgwidth, imgheight)
nodeNameArray[nodeIndex-1] = pair.first
nodesList.add(Pair(pair.first, getCroppedBitmap(bitmap, roundSize)))
}
for(i in (nodemaps.size - 1)..0){
nodemaps.removeAt(i)
}
nodemaps.clear()
return this
}
fun nodes(nodemaps: Nodes): ForceProperty {
initNodes()
GraphStyle.isImgDraw = true
val resource = mContext.resources
val iterator :Iterator<NodePair> = nodemaps.iterator()
nodeNameArray = arrayOfNulls(nodemaps.size)
while (iterator.hasNext()){
/** Node List */
val pair: NodePair = iterator.next()
/** get image properties */
val imageOptions = BitmapFactory.Options()
imageOptions.inPreferredConfig = Bitmap.Config.ARGB_8888
imageOptions.inJustDecodeBounds = true
BitmapFactory.decodeResource(resource, pair.getResource(), imageOptions)
val bitmapWidth = imageOptions.outWidth
val bmfOptions = BitmapFactory.Options()
/** resize image */
reduction = bitmapWidth / nodesWidth
if (reduction != 0) {
bmfOptions.inSampleSize = reduction
}
var bitmap = BitmapFactory.decodeResource(resource, pair.getResource(), bmfOptions)
var imgheight = bmfOptions.outHeight
var imgwidth = bmfOptions.outWidth
if (imgwidth != nodesWidth) {
bitmap = resizeBitmap(bitmap, nodesWidth)
imgheight = bitmap.height
imgwidth = bitmap.width
}
drawAreaWidth = displayWidth - imgwidth
drawAreaHeight = displayHeight - imgheight
addNode(pair.getLabel(), imgwidth, imgheight)
nodeNameArray[nodeIndex-1] = pair.getLabel()
nodesList.add(Pair(pair.getLabel(), getCroppedBitmap(bitmap, roundSize)))
}
for(i in (nodemaps.size - 1)..0){
nodemaps.removeAt(i)
}
nodemaps.clear()
return this
}
fun nodes(nodemaps: Array<String>): ForceProperty {
initNodes()
GraphStyle.isImgDraw = false
nodeNameArray = arrayOfNulls(nodemaps.size)
for (i in 0..nodemaps.size - 1){
addNode(nodemaps[i], nodesWidth, nodesWidth)
nodeNameArray[i] = nodemaps[i]
}
drawAreaWidth = displayWidth - nodesWidth
drawAreaHeight = displayHeight - nodesWidth
return this
}
fun links(linkMaps: List<String>): ForceProperty {
initEdges()
for (i in 0..nodeIndex - 1) {
for (j in 0..nodeIndex - 1) {
if (i != j) {
addEdge(i, j)
}
}
}
for (k in 0..linkMaps.size - 1) {
val pair = linkMaps[k].split("-")
if (pair.size == 2) {
for (i in 0..nEdges - 1) {
if (edges[i].from == nodeNameArray.indexOf(pair[0]) && edges[i].to == nodeNameArray.indexOf(pair[1]) || edges[i].to == nodeNameArray.indexOf(pair[0]) && edges[i].from == nodeNameArray.indexOf(pair[1])) {
edges[i].group = true
}
}
}
}
return this
}
fun links(linkMaps: Links): ForceProperty {
initEdges()
for (i in 0..nodeIndex -1) {
for (j in 0..nodeIndex - 1) {
if (i != j) {
addEdge(i, j)
}
}
}
for (k in 0..linkMaps.size - 1) {
val pair = linkMaps[k]
for (i in 0..nEdges - 1) {
if (edges[i].from == nodeNameArray.indexOf(pair.child()) && edges[i].to == nodeNameArray.indexOf(pair.parent()) || edges[i].to == nodeNameArray.indexOf(pair.child()) && edges[i].from == nodeNameArray.indexOf(pair.parent())) {
edges[i].group = true
}
}
}
for(i in (linkMaps.size - 1)..0){
linkMaps.removeAt(i)
}
linkMaps.clear()
return this
}
fun friction(bounce: Double): ForceProperty {
this.bounce = bounce
return this
}
fun distance(distance: Int): ForceProperty {
this.distance = distance
return this
}
fun gravity(gravity: Double): ForceProperty {
this.gravity = gravity
return this
}
fun start(){
isReady = true
}
private fun addNode(lbl: String, width: Int, height: Int) {
val n = Node()
n.x = drawAreaWidth * Math.random()
n.y = (drawAreaHeight - 10) * Math.random() + 10
n.nodename = lbl
n.width = width.toDouble()
n.height = height.toDouble()
n.dx = 0.0
n.dy = 0.0
nodes.add(n)
nodeIndex++
}
private fun addEdge(from: Int, to: Int) {
val e = Edge()
e.from = from
e.to = to
e.group = false
edges.add(e)
nEdges++
}
fun relax() {
for (i in 0..nodeIndex - 1) {
var fx = 0.0
var fy = 0.0
for (j in 0..nodeIndex - 1) {
val distX = ((nodes[i].x + nodes[i].width / 2 - (nodes[j].x + nodes[j].width / 2)).toInt()).toDouble()
val distY = ((nodes[i].y + nodes[i].height / 2 - (nodes[j].y + nodes[j].height / 2)).toInt()).toDouble()
var rsq = distX * distX + distY * distY
val rsqRound = rsq.toInt() * 100
rsq = (rsqRound / 100).toDouble()
var coulombDistX = COULOMB * distX
var coulombDistY = COULOMB * distY
val coulombDistRoundX = coulombDistX.toInt() * 100
val coulombDistRoundY = coulombDistY.toInt() * 100
coulombDistX = (coulombDistRoundX / 100).toDouble()
coulombDistY = (coulombDistRoundY / 100).toDouble()
if (rsq != 0.0 && Math.sqrt(rsq) < distance) {
fx += coulombDistX / rsq
fy += coulombDistY / rsq
}
}
/** calculate gravity */
val distXC = displayWidth / 2 - (nodes[i].x + nodes[i].width / 2)
val distYC = displayHeight / 2 - (nodes[i].y + nodes[i].height / 2)
fx += gravity * distXC
fy += gravity * distYC
/** calculate spring like force between from and to */
for (j in 0..nEdges - 1 - 1) {
var distX = 0.0
var distY = 0.0
if (edges[j].group) {
if (i == edges[j].from) {
distX = nodes[edges[j].to].x - nodes[i].x
distY = nodes[edges[j].to].y - nodes[i].y
} else if (i == edges[j].to) {
distX = nodes[edges[j].from].x - nodes[i].x
distY = nodes[edges[j].from].y - nodes[i].y
}
}
fx += bounce * distX
fy += bounce * distY
}
nodes[i].dx = (nodes[i].dx + fx) * ATTENUATION
nodes[i].dy = (nodes[i].dy + fy) * ATTENUATION
nodes[i].x += nodes[i].dx
nodes[i].y += nodes[i].dy
}
}
private fun initNodes() {
nodeIndex = 0
nodes = ArrayList<Node>()
nodeNameArray = arrayOfNulls(0)
nodesList.clear()
}
private fun initEdges(){
nEdges = 0
edges = ArrayList<Edge>()
}
}
| apache-2.0 | 2f52e9096dd040fb2144e5e437b3826f | 29.387978 | 241 | 0.546395 | 4.232116 | false | false | false | false |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.