repo_name
stringlengths 7
79
| path
stringlengths 8
206
| copies
stringclasses 36
values | size
stringlengths 2
6
| content
stringlengths 55
523k
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 7.18
99.5
| line_max
int64 16
979
| alpha_frac
float64 0.3
0.87
| ratio
float64 2.01
8.07
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
google/horologist | media-ui/src/main/java/com/google/android/horologist/media/ui/state/PlayerViewModel.kt | 1 | 1701 | /*
* Copyright 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
@file:OptIn(ExperimentalHorologistMediaApi::class)
package com.google.android.horologist.media.ui.state
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.google.android.horologist.media.ExperimentalHorologistMediaApi
import com.google.android.horologist.media.repository.PlayerRepository
import com.google.android.horologist.media.ui.ExperimentalHorologistMediaUiApi
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.stateIn
@ExperimentalHorologistMediaUiApi
public open class PlayerViewModel(
playerRepository: PlayerRepository
) : ViewModel() {
private val producer = PlayerUiStateProducer(playerRepository)
public val playerUiState: StateFlow<PlayerUiState> = producer.playerUiStateFlow.stateIn(
scope = viewModelScope,
started = SharingStarted.WhileSubscribed(stopTimeoutMillis = 5_000),
initialValue = PlayerUiState.NotConnected
)
public val playerUiController: PlayerUiController = PlayerUiController(playerRepository)
}
| apache-2.0 | e9c422cdd42eb407f7d25a964eba5bbd | 37.659091 | 92 | 0.795414 | 4.805085 | false | false | false | false |
icarumbas/bagel | core/src/ru/icarumbas/bagel/view/renderer/systems/AnimationSystem.kt | 1 | 2471 | package ru.icarumbas.bagel.view.renderer.systems
import com.badlogic.ashley.core.Entity
import com.badlogic.ashley.core.Family
import com.badlogic.ashley.systems.IteratingSystem
import com.badlogic.gdx.math.MathUtils
import ru.icarumbas.bagel.engine.components.other.RoomIdComponent
import ru.icarumbas.bagel.engine.components.other.StateComponent
import ru.icarumbas.bagel.engine.components.physics.StaticComponent
import ru.icarumbas.bagel.engine.entities.EntityState
import ru.icarumbas.bagel.engine.world.RoomWorld
import ru.icarumbas.bagel.utils.*
import ru.icarumbas.bagel.view.renderer.components.AlwaysRenderingMarkerComponent
import ru.icarumbas.bagel.view.renderer.components.AnimationComponent
class AnimationSystem(
private val rm: RoomWorld
) : IteratingSystem(Family.all(AnimationComponent::class.java, StateComponent::class.java)
.one(AlwaysRenderingMarkerComponent::class.java, RoomIdComponent::class.java, StaticComponent::class.java).get()) {
private fun flip(e: Entity) {
texture[e].tex?.let{
if (e.rotatedRight() && it.isFlipX) {
it.flip(true, false)
} else
if (!e.rotatedRight() && !it.isFlipX) {
it.flip(true, false)
}
}
}
override fun processEntity(e: Entity, deltaTime: Float) {
if (e.inView(rm)) {
state[e].stateTime += deltaTime
if (state[e].currentState == EntityState.ATTACKING) {
val frame = if (e.rotatedRight()){
body[weapon[e].entityRight].body.angleInDegrees().div(
MathUtils.PI / animation[e].animations[EntityState.ATTACKING]!!.keyFrames.size).toInt() * -1
} else {
body[weapon[e].entityLeft].body.angleInDegrees().div(
MathUtils.PI / animation[e].animations[EntityState.ATTACKING]!!.keyFrames.size).toInt()
}
texture[e].tex = animation[e].animations[state[e].currentState]!!.keyFrames.get(frame)
} else
if (animation[e].animations.containsKey(state[e].currentState)) {
texture[e].tex = animation[e].
animations[state[e].
currentState]!!.
getKeyFrame(state[e].stateTime)
}
flip(e)
}
}
} | apache-2.0 | 39c49ff50d0243aff1247eea279272d3 | 35.352941 | 131 | 0.611089 | 4.396797 | false | false | false | false |
AerisG222/maw_photos_android | MaWPhotos/src/main/java/us/mikeandwan/photos/domain/PhotoCategoryRepository.kt | 1 | 4195 | package us.mikeandwan.photos.domain
import androidx.room.withTransaction
import kotlinx.coroutines.flow.*
import us.mikeandwan.photos.api.ApiResult
import us.mikeandwan.photos.api.PhotoApiClient
import us.mikeandwan.photos.database.*
import us.mikeandwan.photos.domain.models.ExternalCallStatus
import us.mikeandwan.photos.domain.models.Photo
import javax.inject.Inject
class PhotoCategoryRepository @Inject constructor(
private val api: PhotoApiClient,
private val db: MawDatabase,
private val pcDao: PhotoCategoryDao,
private val idDao: ActiveIdDao,
private val apiErrorHandler: ApiErrorHandler
) {
companion object {
const val ERR_MSG_LOAD_CATEGORIES = "Unable to load categories at this time. Please try again later."
const val ERR_MSG_LOAD_PHOTOS = "Unable to load photos. Please try again later."
}
private var _lastCategoryId = -1
private var _lastCategoryPhotos = emptyList<Photo>()
fun getYears() = flow {
val data = pcDao.getYears()
if(data.first().isEmpty()) {
emit(emptyList())
loadCategories(-1, ERR_MSG_LOAD_CATEGORIES)
.collect { }
}
emitAll(data)
}
fun getNewCategories() = flow {
val category = pcDao
.getMostRecentCategory()
.first()
// do not show error messages as snackbar for this method as it is called only from
// the update categories worker - which will create an error notification on failure
val categories = if (category == null) {
loadCategories(-1, null)
} else {
loadCategories(category.id, null)
}
emitAll(categories)
}
fun getCategories() = pcDao
.getCategoriesForActiveYear()
.map { dbList ->
dbList.map { dbCat -> dbCat.toDomainPhotoCategory() }
}
fun getCategory() = pcDao
.getActiveCategory()
.filter { it != null }
.map { cat -> cat!!.toDomainPhotoCategory() }
fun getCategory(id: Int) = pcDao
.getCategory(id)
.filter { it != null }
.map { cat -> cat!!.toDomainPhotoCategory() }
fun getPhotos(categoryId: Int) = flow {
if(categoryId == _lastCategoryId) {
emit(ExternalCallStatus.Success(_lastCategoryPhotos))
} else {
emit(ExternalCallStatus.Loading)
when(val result = api.getPhotos(categoryId)) {
is ApiResult.Error -> emit(apiErrorHandler.handleError(result, ERR_MSG_LOAD_PHOTOS))
is ApiResult.Empty -> emit(apiErrorHandler.handleEmpty(result, ERR_MSG_LOAD_PHOTOS))
is ApiResult.Success -> {
_lastCategoryPhotos = result.result.items.map { it.toDomainPhoto() }
if (_lastCategoryPhotos.isNotEmpty()) {
_lastCategoryId = categoryId
}
emit(ExternalCallStatus.Success(_lastCategoryPhotos))
}
}
}
}
private fun loadCategories(mostRecentCategory: Int, errorMessage: String?) = flow {
emit(ExternalCallStatus.Loading)
when(val result = api.getRecentCategories(mostRecentCategory)) {
is ApiResult.Error -> emit(apiErrorHandler.handleError(result, errorMessage))
is ApiResult.Empty -> emit(apiErrorHandler.handleEmpty(result, errorMessage))
is ApiResult.Success -> {
val categories = result.result.items
if(categories.isEmpty()) {
emit(ExternalCallStatus.Success(emptyList()))
} else {
val dbCategories = categories.map { apiCat -> apiCat.toDatabasePhotoCategory() }
val maxYear = dbCategories.maxOf { it.year }
db.withTransaction {
pcDao.upsert(*dbCategories.toTypedArray())
idDao.setActiveId(ActiveId(ActiveIdType.PhotoCategoryYear, maxYear))
}
emit(ExternalCallStatus.Success(dbCategories.map { it.toDomainPhotoCategory() }))
}
}
}
}
} | mit | 056785fe5f9ec8018c985ea9a7f5f819 | 34.559322 | 110 | 0.604529 | 4.788813 | false | false | false | false |
mrkirby153/KirBot | src/main/kotlin/me/mrkirby153/KirBot/command/control/CommandGuildAccess.kt | 1 | 4179 | package me.mrkirby153.KirBot.command.control
import me.mrkirby153.KirBot.Bot
import me.mrkirby153.KirBot.command.CommandException
import me.mrkirby153.KirBot.command.annotations.AdminCommand
import me.mrkirby153.KirBot.command.annotations.Command
import me.mrkirby153.KirBot.command.args.CommandContext
import me.mrkirby153.KirBot.listener.WaitUtils
import me.mrkirby153.KirBot.module.ModuleManager
import me.mrkirby153.KirBot.modules.AccessModule
import me.mrkirby153.KirBot.utils.Context
import net.dv8tion.jda.api.sharding.ShardManager
import javax.inject.Inject
class CommandGuildAccess @Inject constructor(private val accessModule: AccessModule, private val shardManager: ShardManager){
@Command(name = "add", arguments = ["<list:string>", "<guild:snowflake>"],
parent = "guild-access")
@AdminCommand
fun add(context: Context, cmdContext: CommandContext) {
val guild = cmdContext.getNotNull<String>("guild")
val list = try {
AccessModule.WhitelistMode.valueOf(cmdContext.getNotNull<String>("list").toUpperCase())
} catch (e: IllegalArgumentException) {
throw CommandException(
"Not a valid access list. Valid lists are ${AccessModule.WhitelistMode.values().joinToString(
", ")}")
}
accessModule.addToList(guild, list)
context.send().success("Added `$guild` to the $list list").queue()
if (list == AccessModule.WhitelistMode.BLACKLIST) {
shardManager.getGuildById(guild)?.leave()?.queue()
}
}
@Command(name = "remove", arguments = ["<list:string>", "<guild:snowflake>"],
parent = "guild-access")
@AdminCommand
fun remove(context: Context, cmdContext: CommandContext) {
val guild = cmdContext.getNotNull<String>("guild")
val list = try {
AccessModule.WhitelistMode.valueOf(cmdContext.getNotNull<String>("list").toUpperCase())
} catch (e: IllegalArgumentException) {
throw CommandException(
"Not a valid access list. Valid lists are ${AccessModule.WhitelistMode.values().joinToString(
", ")}")
}
accessModule.removeFromList(guild, list)
context.send().success("Removed `$guild` from the $list list").queue()
}
@Command(name = "list", arguments = ["<list:string>"], parent = "guild-access")
@AdminCommand
fun list(context: Context, cmdContext: CommandContext) {
val list = try {
AccessModule.WhitelistMode.valueOf(cmdContext.getNotNull<String>("list").toUpperCase())
} catch (e: IllegalArgumentException) {
throw CommandException(
"Not a valid access list. Valid lists are ${AccessModule.WhitelistMode.values().joinToString(
", ")}")
}
val guilds = accessModule.getList(list).map { it ->
if (shardManager.getGuildById(it) != null) {
val guild = shardManager.getGuildById(it)!!
"${guild.name} (`${guild.id}`)"
} else {
it
}
}
var msg = "List: $list\n"
guilds.forEach {
val toAdd = " - $it\n"
if (msg.length + toAdd.length >= 1990) {
context.channel.sendMessage("$msg").queue()
msg = ""
} else {
msg += toAdd
}
}
if (msg != "")
context.channel.sendMessage(msg).queue()
}
@Command(name = "importWhitelist", parent = "guild-access")
@AdminCommand
fun import(context: Context, cmdContext: CommandContext) {
context.channel.sendMessage(
"Are you sure you want to import all guilds into the whitelist?").queue { msg ->
WaitUtils.confirmYesNo(msg, context.author, {
shardManager.guilds.forEach { g ->
accessModule.addToList(g.id, AccessModule.WhitelistMode.WHITELIST)
}
msg.editMessage("Done! Added ${shardManager.guilds.size} to the list").queue()
})
}
}
} | mit | 0eeda468c3a08a4478cdfd159abcfa89 | 39.192308 | 125 | 0.60804 | 4.522727 | false | false | false | false |
Sjtek/sjtekcontrol-core | data/src/main/kotlin/nl/sjtek/control/data/parsers/ResponseHolder.kt | 1 | 888 | package nl.sjtek.control.data.parsers
import nl.sjtek.control.data.response.*
import java.io.Serializable
@Suppress("MemberVisibilityCanPrivate")
data class ResponseHolder(val map: Map<String, Response> = mapOf(), @Transient val exception: Exception? = null) : Serializable {
val audio: Audio = map["audio"] as Audio
val base: Base = map["base"] as Base
val coffee: Coffee = map["coffee"] as Coffee
val lights: Lights = map["lights"] as Lights
val music: Music = map["music"] as Music
val nightMode: NightMode = map["nightmode"] as NightMode
val temperature: Temperature = map["temperature"] as Temperature
val tv: TV = map["tv"] as TV
@Suppress("UNNECESSARY_NOT_NULL_ASSERTION")
internal fun test() {
audio!!
base!!
coffee!!
lights!!
music!!
nightMode!!
temperature!!
tv!!
}
} | gpl-3.0 | 26a99a26d27910e5ac2052040b2ab4c7 | 30.75 | 129 | 0.64527 | 4.169014 | false | false | false | false |
square/duktape-android | zipline/src/engineMain/kotlin/app/cash/zipline/internal/CoroutineEventLoop.kt | 1 | 2150 | /*
* Copyright (C) 2021 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 app.cash.zipline.internal
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.CoroutineStart.UNDISPATCHED
import kotlinx.coroutines.Job
import kotlinx.coroutines.Runnable
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
/**
* We implement scheduled work with raw calls to [CoroutineDispatcher.dispatch] because it prevents
* recursion. Otherwise, it's easy to unintentionally have `setTimeout(0, ...)` calls that execute
* immediately, eventually exhausting stack space and crashing the process.
*/
internal class CoroutineEventLoop(
private val dispatcher: CoroutineDispatcher,
private val scope: CoroutineScope,
private val jsPlatform: JsPlatform,
) : EventLoop {
private val jobs = mutableMapOf<Int, DelayedJob>()
override fun setTimeout(timeoutId: Int, delayMillis: Int) {
val job = DelayedJob(timeoutId, delayMillis)
jobs[timeoutId] = job
dispatcher.dispatch(scope.coroutineContext, job)
}
override fun clearTimeout(timeoutId: Int) {
jobs.remove(timeoutId)?.cancel()
}
private inner class DelayedJob(
val timeoutId: Int,
val delayMillis: Int
) : Runnable {
var canceled = false
var job: Job? = null
override fun run() {
if (canceled) return
this.job = scope.launch(start = UNDISPATCHED) {
delay(delayMillis.toLong())
jsPlatform.runJob(timeoutId)
jobs.remove(timeoutId)
}
}
fun cancel() {
canceled = true
job?.cancel()
}
}
}
| apache-2.0 | 22a72042dddd93fbd6ee072dd27d48a8 | 30.15942 | 99 | 0.726512 | 4.308617 | false | false | false | false |
vhromada/Catalog-Swing | src/main/kotlin/cz/vhromada/catalog/gui/program/ProgramDataPanel.kt | 1 | 4750 | package cz.vhromada.catalog.gui.program
import cz.vhromada.catalog.entity.Program
import cz.vhromada.catalog.gui.common.AbstractDataPanel
import cz.vhromada.catalog.gui.common.WebPageButtonType
import javax.swing.GroupLayout
import javax.swing.JButton
import javax.swing.JLabel
/**
* A class represents panel with program's data.
*
* @author Vladimir Hromada
*/
class ProgramDataPanel(program: Program) : AbstractDataPanel<Program>() {
/**
* Label for name
*/
private val nameLabel = JLabel("Name")
/**
* Label with name
*/
private val nameData = JLabel()
/**
* Label for additional data
*/
private val dataLabel = JLabel("Additional data")
/**
* Label with additional data
*/
private val dataData = JLabel()
/**
* Label for count of media
*/
private val mediaCountLabel = JLabel("Count of media")
/**
* Label with count of media
*/
private val mediaCountData = JLabel()
/**
* Label for note
*/
private val noteLabel = JLabel("Note")
/**
* Label with note
*/
private val noteData = JLabel()
/**
* Button for showing program's czech Wikipedia page
*/
private val wikiCzButton = JButton("Czech Wikipedia")
/**
* Button for showing program's english Wikipedia page
*/
private val wikiEnButton = JButton("English Wikipedia")
/**
* URL to czech Wikipedia page about program
*/
private var wikiCz: String? = null
/**
* URL to english Wikipedia page about program
*/
private var wikiEn: String? = null
init {
updateData(program)
initData(nameLabel, nameData)
initData(dataLabel, dataData)
initData(mediaCountLabel, mediaCountData)
initData(noteLabel, noteData)
initButton(wikiCzButton, WebPageButtonType.WIKI_CZ)
initButton(wikiEnButton, WebPageButtonType.WIKI_EN)
createLayout()
}
@Suppress("DuplicatedCode")
override fun updateComponentData(data: Program) {
nameData.text = data.name
dataData.text = getAdditionalData(data)
mediaCountData.text = data.mediaCount?.toString()
noteData.text = data.note
wikiCz = data.wikiCz
wikiEn = data.wikiEn
wikiCzButton.isEnabled = !wikiCz.isNullOrBlank()
wikiEnButton.isEnabled = !wikiEn.isNullOrBlank()
}
override fun getCzWikiUrl(): String {
return wikiCz!!
}
override fun getEnWikiUrl(): String {
return wikiEn!!
}
override fun getCsfdUrl(): String {
error { "Getting URL to ČSFD page is not allowed for programs." }
}
override fun getImdbUrl(): Int {
error { "Getting URL to IMDB page is not allowed for programs." }
}
override fun getHorizontalLayoutWithComponents(layout: GroupLayout, group: GroupLayout.Group): GroupLayout.Group {
return group
.addGroup(createHorizontalDataComponents(layout, nameLabel, nameData))
.addGroup(createHorizontalDataComponents(layout, dataLabel, dataData))
.addGroup(createHorizontalDataComponents(layout, mediaCountLabel, mediaCountData))
.addGroup(createHorizontalDataComponents(layout, noteLabel, noteData))
.addGroup(createHorizontalButtons(layout, wikiCzButton, wikiEnButton))
}
override fun getVerticalLayoutWithComponents(layout: GroupLayout, group: GroupLayout.Group): GroupLayout.Group {
return group
.addGroup(createVerticalComponents(layout, nameLabel, nameData))
.addGap(VERTICAL_GAP_SIZE)
.addGroup(createVerticalComponents(layout, dataLabel, dataData))
.addGap(VERTICAL_GAP_SIZE)
.addGroup(createVerticalComponents(layout, mediaCountLabel, mediaCountData))
.addGap(VERTICAL_GAP_SIZE)
.addGroup(createVerticalComponents(layout, noteLabel, noteData))
.addGap(VERTICAL_GAP_SIZE)
.addGroup(createVerticalButtons(layout, wikiCzButton, wikiEnButton))
}
/**
* Returns additional data.
*
* @param program program
* @return additional data
*/
private fun getAdditionalData(program: Program): String {
val result = StringBuilder()
if (program.crack!!) {
result.append("Crack")
}
addAdditionalDataToResult(result, program.serialKey!!, "serial key")
if (!program.otherData.isNullOrBlank()) {
if (result.isNotEmpty()) {
result.append(", ")
}
result.append(program.otherData)
}
return result.toString()
}
}
| mit | e2fe22595eb3b6a572a672ff0f0edead | 27.781818 | 118 | 0.635502 | 4.900929 | false | false | false | false |
RFonzi/RxAware | rxaware-lib/src/main/java/io/github/rfonzi/rxaware/bus/RxBus.kt | 1 | 573 | package io.github.rfonzi.rxaware.bus
import com.jakewharton.rxrelay2.BehaviorRelay
import io.github.rfonzi.rxaware.bus.events.FlushEvent
import io.reactivex.Observable
/**
* Created by ryan on 8/24/17.
*/
object RxBus {
private val subject: BehaviorRelay<Any> = BehaviorRelay.create()
fun post(event: Any) = subject.accept(event)
fun <T> toObservable(eventType: Class<T>): Observable<T> = subject.ofType(eventType)
fun clear() = post(FlushEvent())
}
//val questionBankRelayModule = Kodein.Module {
// bind<RxBus>() with singleton { RxBus() }
//} | mit | 88fec1caeca8a588426c7ce10f6270d8 | 23.956522 | 88 | 0.719023 | 3.472727 | false | false | false | false |
damien5314/HoldTheNarwhal | app/src/main/java/com/ddiehl/android/htn/listings/BaseListingsFragment.kt | 1 | 5827 | package com.ddiehl.android.htn.listings
import android.os.Bundle
import android.view.*
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout
import com.ddiehl.android.htn.R
import com.ddiehl.android.htn.listings.report.ReportViewRouter
import com.ddiehl.android.htn.routing.AppRouter
import com.ddiehl.android.htn.view.BaseFragment
import com.google.android.material.snackbar.Snackbar
import javax.inject.Inject
abstract class BaseListingsFragment : BaseFragment(),
ListingsView,
SwipeRefreshLayout.OnRefreshListener {
@Inject
internal lateinit var appRouter: AppRouter
@Inject
internal lateinit var reportViewRouter: ReportViewRouter
lateinit var recyclerView: RecyclerView
protected lateinit var swipeRefreshLayout: SwipeRefreshLayout
protected lateinit var listingsPresenter: BaseListingsPresenter
protected abstract val listingsAdapter: ListingsAdapter
protected lateinit var callbacks: ListingsView.Callbacks
private val onScrollListener: RecyclerView.OnScrollListener
get() = object : RecyclerView.OnScrollListener() {
override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
with(recyclerView.layoutManager as LinearLayoutManager) {
handleScroll(childCount, itemCount, findFirstVisibleItemPosition())
}
}
private fun handleScroll(visible: Int, total: Int, firstVisible: Int) {
if (firstVisible == 0) {
callbacks.onFirstItemShown()
} else if (visible + firstVisible >= total) {
callbacks.onLastItemShown()
}
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
retainInstance = true
setHasOptionsMenu(true)
listenForReportViewResults()
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, state: Bundle?): View {
return super.onCreateView(inflater, container, state).also {
recyclerView = it.findViewById(R.id.recycler_view);
instantiateListView()
}
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
swipeRefreshLayout = view.findViewById(R.id.swipe_refresh_layout)
swipeRefreshLayout.setOnRefreshListener(this)
}
private fun instantiateListView() {
with(recyclerView) {
layoutManager = LinearLayoutManager(activity)
clearOnScrollListeners()
addOnScrollListener(onScrollListener)
adapter = listingsAdapter
}
}
override fun onStart() {
super.onStart()
// FIXME Do we need to check nextRequested here?
if (!listingsPresenter.hasData()) {
listingsPresenter.refreshData()
}
}
override fun onDestroy() {
recyclerView.adapter = null
// To disable the memory dereferencing functionality just comment these lines
listingsPresenter.clearData()
super.onDestroy()
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
R.id.action_refresh -> {
listingsPresenter.refreshData()
return true
}
R.id.action_settings -> {
appRouter.showSettings()
return true
}
}
return false
}
protected fun hideTimespanOptionIfUnsupported(menu: Menu, sort: String) {
menu.findItem(R.id.action_change_sort).isVisible = true
when (sort) {
"controversial", "top" -> menu.findItem(R.id.action_change_timespan).isVisible = true
"hot", "new", "rising" -> menu.findItem(R.id.action_change_timespan).isVisible = false
else -> menu.findItem(R.id.action_change_timespan).isVisible = false
}
}
override fun onContextItemSelected(item: MenuItem): Boolean {
return listingsPresenter.onContextItemSelected(item)
}
override fun notifyDataSetChanged() = listingsAdapter.notifyDataSetChanged()
override fun notifyItemChanged(position: Int) = listingsAdapter.notifyItemChanged(position)
override fun notifyItemInserted(position: Int) = listingsAdapter.notifyItemInserted(position)
override fun notifyItemRemoved(position: Int) = listingsAdapter.notifyItemRemoved(position)
override fun notifyItemRangeChanged(position: Int, count: Int) =
listingsAdapter.notifyItemRangeChanged(position, count)
override fun notifyItemRangeInserted(position: Int, count: Int) =
listingsAdapter.notifyItemRangeInserted(position, count)
override fun notifyItemRangeRemoved(position: Int, count: Int) =
listingsAdapter.notifyItemRangeRemoved(position, count)
override fun onRefresh() {
swipeRefreshLayout.isRefreshing = false
listingsPresenter.refreshData()
}
private fun listenForReportViewResults() {
reportViewRouter.observeReportResults()
.subscribe { result ->
when (result) {
ReportViewRouter.ReportResult.SUCCESS -> showReportSuccessToast()
ReportViewRouter.ReportResult.CANCELED -> showReportErrorToast()
null -> { }
}
}
}
private fun showReportSuccessToast() {
Snackbar.make(chromeView, R.string.report_successful, Snackbar.LENGTH_LONG).show()
}
private fun showReportErrorToast() {
Snackbar.make(chromeView, R.string.report_error, Snackbar.LENGTH_LONG).show()
}
}
| apache-2.0 | 4a4724412fe44e47271aff893f60a496 | 35.879747 | 102 | 0.672902 | 5.244824 | false | false | false | false |
ccomeaux/boardgamegeek4android | app/src/main/java/com/boardgamegeek/extensions/Menu.kt | 1 | 662 | package com.boardgamegeek.extensions
import android.view.Menu
import android.widget.TextView
import androidx.annotation.IdRes
fun Menu.setActionBarCount(@IdRes id: Int, count: Int, text: String? = null) {
setActionBarText(id,
if (count <= 0) "" else "%,d".format(count),
if (count <= 0) "" else text)
}
private fun Menu.setActionBarText(@IdRes id: Int, text1: String, text2: String?) {
val actionView = findItem(id).actionView ?: return
actionView.findViewById<TextView>(android.R.id.text1)?.text = text1
if (!text2.isNullOrBlank()) {
actionView.findViewById<TextView>(android.R.id.text2)?.text = text2
}
}
| gpl-3.0 | 9f6247b32a357c598b8ec1b749132bf5 | 33.842105 | 82 | 0.68429 | 3.637363 | false | false | false | false |
LanternPowered/LanternServer | src/main/kotlin/org/lanternpowered/server/timings/DummyTimingsFactory.kt | 1 | 1201 | /*
* Lantern
*
* Copyright (c) LanternPowered <https://www.lanternpowered.org>
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* This work is licensed under the terms of the MIT License (MIT). For
* a copy, see 'LICENSE.txt' or <https://opensource.org/licenses/MIT>.
*/
package org.lanternpowered.server.timings
import co.aikar.timings.Timing
import co.aikar.timings.TimingsFactory
import org.lanternpowered.api.audience.Audience
import org.lanternpowered.api.plugin.PluginContainer
object DummyTimingsFactory : TimingsFactory {
override fun of(plugin: PluginContainer, name: String, groupHandler: Timing?): Timing = DummyTiming
override fun isTimingsEnabled(): Boolean = false
override fun setTimingsEnabled(enabled: Boolean) {}
override fun isVerboseTimingsEnabled(): Boolean = false
override fun setVerboseTimingsEnabled(enabled: Boolean) {}
override fun getHistoryInterval(): Int = 0
override fun setHistoryInterval(interval: Int) {}
override fun getHistoryLength(): Int = 0
override fun setHistoryLength(length: Int) {}
override fun reset() {}
override fun generateReport(channel: Audience) {}
}
| mit | 54353486a70fc76dc36ec7e61e5017e8 | 39.033333 | 103 | 0.751041 | 4.289286 | false | false | false | false |
ken-kentan/student-portal-plus | app/src/main/java/jp/kentan/studentportalplus/data/dao/DatabaseMigrationHelper.kt | 1 | 3103 | package jp.kentan.studentportalplus.data.dao
import android.database.sqlite.SQLiteDatabase
import androidx.core.database.getStringOrNull
import jp.kentan.studentportalplus.data.component.ClassWeek
import jp.kentan.studentportalplus.util.Murmur3
import org.jetbrains.anko.db.dropTable
import org.jetbrains.anko.db.insert
import org.jetbrains.anko.db.select
import org.jetbrains.anko.db.transaction
import kotlin.math.max
class DatabaseMigrationHelper {
companion object {
fun upgradeVersion3From2(db: SQLiteDatabase, createTablesIfNotExist: (SQLiteDatabase) -> Unit) {
db.transaction {
db.execSQL("ALTER TABLE my_class RENAME TO tmp_my_class")
db.dropTable("news", true)
db.dropTable("lecture_info", true)
db.dropTable("lecture_cancel", true)
db.dropTable("my_class", true)
db.execSQL("DELETE FROM sqlite_sequence")
createTablesIfNotExist(db)
db.select("tmp_my_class").exec {
while (moveToNext()) {
val week: ClassWeek = getLong(1).let {
return@let ClassWeek.valueOf(it.toInt() + 1)
}
val period = getLong(2).let { if (it > 0) it else 0 }
val scheduleCode = getLong(8).let { code ->
if (code < 0L) "" else code.toString()
}
val credit = max(getLong(7), 0)
val category = getStringOrNull(6) ?: ""
val subject = getString(3)
val isUser = getLong(10) == 1L
val instructor = getStringOrNull(4)?.let {
return@let if (isUser) it else it.replace(' ', ' ')
} ?: ""
val location = getStringOrNull(5)?.let {
val trim = it.trim()
return@let if (trim.isBlank()) null else trim
}
val hash = Murmur3.hash64("$week$period$scheduleCode$credit$category$subject$instructor$isUser")
db.insert("my_class",
"_id" to null,
"hash" to hash,
"week" to week.code,
"period" to period,
"schedule_code" to scheduleCode,
"credit" to credit,
"category" to category,
"subject" to subject,
"instructor" to instructor,
"user" to isUser.toLong(),
"color" to getLong(9),
"location" to location)
}
}
db.dropTable("tmp_my_class")
}
}
private fun Boolean.toLong() = if (this) 1L else 0L
}
} | gpl-3.0 | 4300073f9fc276d1f896d49fdd7efb8b | 40.918919 | 120 | 0.467914 | 5.134106 | false | false | false | false |
AoEiuV020/PaNovel | api/src/main/java/cc/aoeiuv020/panovel/api/site/bqg5200.kt | 1 | 2584 | package cc.aoeiuv020.panovel.api.site
import cc.aoeiuv020.panovel.api.base.DslJsoupNovelContext
import cc.aoeiuv020.panovel.api.firstThreeIntPattern
/**
* Created by AoEiuV020 on 2018.06.06-18:51:02.
*/
class Bqg5200 : DslJsoupNovelContext() {init {
// 已经废了,域名都丢了,
hide = true
site {
name = "笔趣阁5200"
baseUrl = "https://www.biquge5200.com"
logo = "https://www.biquge5200.com/skin/images/logo.png"
}
search {
get {
// https://www.bqg5200.com/modules/article/search.php?searchtype=articlename&searchkey=%B6%BC%CA%D0&page=1
charset = "GBK"
url = "/modules/article/search.php"
data {
"searchtype" to "articlename"
"searchkey" to it
// 加上&page=1可以避开搜索时间间隔的限制,
// 也可以通过不加载cookies避开搜索时间间隔的限制,
"page" to "1"
}
}
document {
single("^/book/") {
name("#bookinfo > div.bookright > div.booktitle > h1")
author("#author", block = pickString("作\\s*者:(\\S+)"))
}
items("#conn > table > tbody > tr:not(:nth-child(1))") {
name("> td:nth-child(1) > a")
author("> td:nth-child(3)")
}
}
}
// https://www.bqg5200.com/book/2889/
bookIdRegex = "/(book|xiaoshuo/\\d+)/(\\d+)"
bookIdIndex = 1
detailPageTemplate = "/book/%s/"
detail {
document {
novel {
name("#bookinfo > div.bookright > div.booktitle > h1")
author("#author", block = pickString("作\\s*者:(\\S+)"))
}
image("#bookimg > img")
update("#bookinfo > div.bookright > div.new > span.new_t", format = "最后更新:yyyy-MM-dd")
introduction("#bookintro > p", block = ownLinesString())
}
}
// https://www.bqg5200.com/xiaoshuo/2/2889/
chapterDivision = 1000
chaptersPageTemplate = "/xiaoshuo/%d/%s/"
chapters {
document {
items("#readerlist > ul > li > a")
lastUpdate("#smallcons > span:nth-child(4)", format = "yyyy-MM-dd HH:mm")
}
}
// https://www.bqg5200.com/xiaoshuo/3/3590/11768349.html
bookIdWithChapterIdRegex = firstThreeIntPattern
contentPageTemplate = "/xiaoshuo/%s.html"
content {
document {
items("#content", block = ownLinesSplitWhitespace())
}
}
}
}
| gpl-3.0 | 94400b0aa50f797232e1c2d2e8480091 | 31.826667 | 118 | 0.530057 | 3.55267 | false | false | false | false |
jonalmeida/focus-android | app/src/main/java/org/mozilla/focus/settings/SettingsFragment.kt | 1 | 2741 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
@file:Suppress("ForbiddenComment")
package org.mozilla.focus.settings
import android.content.SharedPreferences
import android.os.Bundle
import org.mozilla.focus.R
import org.mozilla.focus.telemetry.TelemetryWrapper
import org.mozilla.focus.utils.AppConstants
class SettingsFragment : BaseSettingsFragment(), SharedPreferences.OnSharedPreferenceChangeListener {
override fun onCreatePreferences(bundle: Bundle?, s: String?) {
addPreferencesFromResource(R.xml.settings)
if (!AppConstants.isGeckoBuild && !AppConstants.isDevBuild) {
preferenceScreen.removePreference(findPreference(getString(R.string.pref_key_advanced_screen)))
}
}
override fun onResume() {
super.onResume()
preferenceManager.sharedPreferences.registerOnSharedPreferenceChangeListener(this)
// Update title and icons when returning to fragments.
val updater = activity as BaseSettingsFragment.ActionBarUpdater?
updater!!.updateTitle(R.string.menu_settings)
updater.updateIcon(R.drawable.ic_back)
}
override fun onPause() {
preferenceManager.sharedPreferences.unregisterOnSharedPreferenceChangeListener(this)
super.onPause()
}
override fun onPreferenceTreeClick(preference: androidx.preference.Preference): Boolean {
val resources = resources
when {
preference.key == resources.getString(R.string
.pref_key_general_screen) -> navigateToFragment(GeneralSettingsFragment())
preference.key == resources.getString(R.string
.pref_key_privacy_security_screen) -> navigateToFragment(PrivacySecuritySettingsFragment())
preference.key == resources.getString(R.string
.pref_key_search_screen) -> navigateToFragment(SearchSettingsFragment())
preference.key == resources.getString(R.string
.pref_key_advanced_screen) -> navigateToFragment(AdvancedSettingsFragment())
preference.key == resources.getString(R.string
.pref_key_mozilla_screen) -> navigateToFragment(MozillaSettingsFragment())
}
return super.onPreferenceTreeClick(preference)
}
override fun onSharedPreferenceChanged(sharedPreferences: SharedPreferences, key: String) {
TelemetryWrapper.settingsEvent(key, sharedPreferences.all[key].toString())
}
companion object {
fun newInstance(): SettingsFragment {
return SettingsFragment()
}
}
}
| mpl-2.0 | 1f00a5dbaa860f80e56422716b649951 | 39.308824 | 111 | 0.703028 | 5.211027 | false | false | false | false |
arturbosch/detekt | detekt-rules-naming/src/main/kotlin/io/gitlab/arturbosch/detekt/rules/naming/NonBooleanPropertyPrefixedWithIs.kt | 1 | 3106 | package io.gitlab.arturbosch.detekt.rules.naming
import io.gitlab.arturbosch.detekt.api.CodeSmell
import io.gitlab.arturbosch.detekt.api.Config
import io.gitlab.arturbosch.detekt.api.Debt
import io.gitlab.arturbosch.detekt.api.Entity
import io.gitlab.arturbosch.detekt.api.Issue
import io.gitlab.arturbosch.detekt.api.Rule
import io.gitlab.arturbosch.detekt.api.Severity
import io.gitlab.arturbosch.detekt.api.internal.RequiresTypeResolution
import io.gitlab.arturbosch.detekt.rules.fqNameOrNull
import io.gitlab.arturbosch.detekt.rules.identifierName
import org.jetbrains.kotlin.psi.KtCallableDeclaration
import org.jetbrains.kotlin.psi.KtParameter
import org.jetbrains.kotlin.psi.KtProperty
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.typeBinding.createTypeBindingForReturnType
/**
* Reports when property with 'is' prefix doesn't have a boolean type.
* Please check the [chapter 8.3.2 at Java Language Specification](https://docs.oracle.com/javase/specs/jls/se8/html/jls-8.html#jls-8.3.2)
*
* <noncompliant>
* val isEnabled: Int = 500
* </noncompliant>
*
* <compliant>
* val isEnabled: Boolean = false
* </compliant>
*/
@RequiresTypeResolution
class NonBooleanPropertyPrefixedWithIs(config: Config = Config.empty) : Rule(config) {
private val kotlinBooleanTypeName = "kotlin.Boolean"
private val javaBooleanTypeName = "java.lang.Boolean"
override val issue = Issue(
javaClass.simpleName,
Severity.Warning,
"Only boolean property names can start with 'is' prefix.",
debt = Debt.FIVE_MINS
)
override fun visitParameter(parameter: KtParameter) {
super.visitParameter(parameter)
if (parameter.hasValOrVar()) {
validateDeclaration(parameter)
}
}
override fun visitProperty(property: KtProperty) {
super.visitProperty(property)
validateDeclaration(property)
}
private fun validateDeclaration(declaration: KtCallableDeclaration) {
if (bindingContext == BindingContext.EMPTY) {
return
}
val name = declaration.identifierName()
if (name.startsWith("is") && name.length > 2 && !name[2].isLowerCase()) {
val typeName = getTypeName(declaration)
if (typeName != null && typeName != kotlinBooleanTypeName && typeName != javaBooleanTypeName) {
report(
reportCodeSmell(declaration, name, typeName)
)
}
}
}
private fun reportCodeSmell(
declaration: KtCallableDeclaration,
name: String,
typeName: String
): CodeSmell {
return CodeSmell(
issue,
Entity.from(declaration),
message = "Non-boolean properties shouldn't start with 'is' prefix. Actual type of $name: $typeName"
)
}
private fun getTypeName(parameter: KtCallableDeclaration): String? {
return parameter.createTypeBindingForReturnType(bindingContext)
?.type
?.fqNameOrNull()
?.asString()
}
}
| apache-2.0 | 61cb373a1eed27495cff02f04ffa2900 | 32.042553 | 138 | 0.689311 | 4.494935 | false | true | false | false |
hewking/HUILibrary | app/src/main/java/com/hewking/demo/TinderStackLayoutFragment.kt | 1 | 2620 | package com.hewking.demo
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.Toast
import com.hewking.custom.R
import com.hewking.custom.tinderstack.TinderStackLayout
import com.hewking.custom.util.dp2px
import com.hewking.custom.util.load
import kotlinx.android.synthetic.main.fragment_tinder.*
/**
* 类的描述:
* 创建人员:hewking
* 创建时间:2018/12/9
* 修改人员:hewking
* 修改时间:2018/12/9
* 修改备注:
* Version: 1.0.0
*/
class TinderStackLayoutFragment : androidx.fragment.app.Fragment(){
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
return inflater.inflate(R.layout.fragment_tinder,container,false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
tinderStack.adapter = TinderCardAdapter().apply {
}
tinderStack.setChooseListener {
if (it == 1) {
Toast.makeText(activity,"right swipe select",Toast.LENGTH_SHORT).show()
} else {
Toast.makeText(activity,"left swipe select",Toast.LENGTH_SHORT).show()
}
}
}
inner class TinderCardAdapter : TinderStackLayout.BaseCardAdapter{
val datas = mutableListOf<String>("https://tuimeizi.cn/random?w=665&h=656"
,"https://tuimeizi.cn/random?w=665&h=656"
,"https://tuimeizi.cn/random?w=667&h=656"
,"https://tuimeizi.cn/random?w=665&h=656"
,"https://tuimeizi.cn/random?w=668&h=656"
,"https://tuimeizi.cn/random?w=665&h=656"
,"https://tuimeizi.cn/random?w=665&h=659"
,"https://tuimeizi.cn/random?w=665&h=653"
,"https://tuimeizi.cn/random?w=665&h=656"
,"https://tuimeizi.cn/random?w=665&h=653")
private var index = 0
override fun getItemCount(): Int {
return datas.size
}
override fun getView(): View? {
if (index > datas.size - 1) {
return null
}
val img = ImageView(activity)
img.scaleType = ImageView.ScaleType.CENTER_CROP
img.layoutParams = ViewGroup.LayoutParams(dp2px(350f),dp2px(350f))
img.load(datas[index])
index ++
return img
}
}
} | mit | c3b2d7b712143a812a9fd02645ef0e3c | 30.846154 | 116 | 0.599609 | 3.792593 | false | false | false | false |
dewarder/Android-Kotlin-Commons | akommons-bindings/src/androidTest/java/com/dewarder/akommons/binding/TestActivity.kt | 1 | 2213 | package com.dewarder.akommons.binding
import android.app.Dialog
import android.app.Fragment
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.view.View
import android.widget.FrameLayout
import com.dewarder.akommons.binding.common.R
import android.support.v4.app.Fragment as SupportFragment
open class TestActivity : AppCompatActivity() {
private lateinit var view: View
private lateinit var fragment: Fragment
private lateinit var supportFragment: SupportFragment
private lateinit var dialog: Dialog
private lateinit var contextProvider: ContextProvider
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val container = FrameLayout(this).apply {
id = R.id.action_container
}
setContentView(container)
initView()?.let {
view = it
container.addView(view)
}
initFragment()?.let {
fragment = it
fragmentManager.beginTransaction()
.replace(R.id.action_container, fragment)
.commit()
}
initSupportFragment()?.let {
supportFragment = it
supportFragmentManager.beginTransaction()
.replace(R.id.action_container, supportFragment)
.commit()
}
initDialog()?.let {
dialog = it
dialog.show()
}
initContextProvider()?.let {
contextProvider = it
}
}
protected open fun initView(): View? = null
protected open fun initFragment(): Fragment? = null
protected open fun initSupportFragment(): SupportFragment? = null
protected open fun initDialog(): Dialog? = null
protected open fun initContextProvider(): ContextProvider? = null
fun <T> getView(): T {
return view as T
}
fun <T> getFragment(): T {
return fragment as T
}
fun <T> getSupportFragment(): T {
return supportFragment as T
}
fun <T> getDialog(): T {
return dialog as T
}
fun <T> getContextProvider(): T {
return contextProvider as T
}
} | apache-2.0 | 5f557c1ef87d049b0c1a138c8c107de8 | 25.047059 | 69 | 0.622232 | 5.146512 | false | false | false | false |
androhi/AndroidDrawableViewer | src/main/kotlin/com/androhi/androiddrawableviewer/form/ImageListCellRenderer.kt | 1 | 1151 | package com.androhi.androiddrawableviewer.form
import com.intellij.ui.JBColor
import java.awt.Component
import javax.swing.*
class ImageListCellRenderer : ListCellRenderer<Any> {
override fun getListCellRendererComponent(list: JList<out Any>?, value: Any?, index: Int, isSelected: Boolean, cellHasFocus: Boolean): Component =
when (value) {
is JPanel -> {
setLabelColor(value, isSelected)
val normalColor = if (index % 2 == 0) JBColor.border() else JBColor.background()
val selectedColor = UIManager.getColor("List.selectionBackground")
value.apply {
background = if (isSelected) selectedColor else normalColor
}
}
else -> {
JLabel("")
}
}
private fun setLabelColor(panel: JPanel, isSelected: Boolean) =
panel.components.forEach {
it.foreground = if (isSelected) {
UIManager.getColor("List.selectionForeground")
} else {
JBColor.foreground()
}
}
} | apache-2.0 | f4d306c14c985ea4457872d649fcd5d4 | 35 | 150 | 0.566464 | 5.328704 | false | false | false | false |
panpf/sketch | sketch/src/androidTest/java/com/github/panpf/sketch/test/ComponentRegistryTest.kt | 1 | 27573 | /*
* Copyright (C) 2022 panpf <panpfpanpf@outlook.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.panpf.sketch.test
import androidx.test.ext.junit.runners.AndroidJUnit4
import com.github.panpf.sketch.ComponentRegistry
import com.github.panpf.sketch.decode.internal.DefaultBitmapDecoder
import com.github.panpf.sketch.decode.internal.DefaultDrawableDecoder
import com.github.panpf.sketch.decode.internal.EngineBitmapDecodeInterceptor
import com.github.panpf.sketch.decode.internal.EngineDrawableDecodeInterceptor
import com.github.panpf.sketch.decode.internal.XmlDrawableBitmapDecoder
import com.github.panpf.sketch.fetch.AssetUriFetcher
import com.github.panpf.sketch.fetch.Base64UriFetcher
import com.github.panpf.sketch.fetch.HttpUriFetcher
import com.github.panpf.sketch.fetch.ResourceUriFetcher
import com.github.panpf.sketch.isNotEmpty
import com.github.panpf.sketch.merged
import com.github.panpf.sketch.request.DisplayRequest
import com.github.panpf.sketch.request.internal.EngineRequestInterceptor
import com.github.panpf.sketch.test.utils.Test2BitmapDecodeInterceptor
import com.github.panpf.sketch.test.utils.Test2DrawableDecodeInterceptor
import com.github.panpf.sketch.test.utils.TestAssets
import com.github.panpf.sketch.test.utils.TestBitmapDecodeInterceptor
import com.github.panpf.sketch.test.utils.TestBitmapDecoder
import com.github.panpf.sketch.test.utils.TestDrawableDecodeInterceptor
import com.github.panpf.sketch.test.utils.TestDrawableDecoder
import com.github.panpf.sketch.test.utils.TestFetcher
import com.github.panpf.sketch.test.utils.TestRequestInterceptor
import com.github.panpf.sketch.test.utils.getTestContext
import com.github.panpf.sketch.test.utils.newSketch
import com.github.panpf.sketch.test.utils.toRequestContext
import com.github.panpf.sketch.transform.internal.BitmapTransformationDecodeInterceptor
import com.github.panpf.tools4j.test.ktx.assertNoThrow
import com.github.panpf.tools4j.test.ktx.assertThrow
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.runBlocking
import org.junit.Assert
import org.junit.Test
import org.junit.runner.RunWith
@RunWith(AndroidJUnit4::class)
class ComponentRegistryTest {
@Test
fun testNewBuilder() {
ComponentRegistry.Builder().apply {
addFetcher(HttpUriFetcher.Factory())
addBitmapDecoder(XmlDrawableBitmapDecoder.Factory())
addDrawableDecoder(DefaultDrawableDecoder.Factory())
}.build().apply {
Assert.assertEquals(
listOf(HttpUriFetcher.Factory()),
fetcherFactoryList
)
Assert.assertEquals(
listOf(XmlDrawableBitmapDecoder.Factory()),
bitmapDecoderFactoryList
)
Assert.assertEquals(
listOf(DefaultDrawableDecoder.Factory()),
drawableDecoderFactoryList
)
Assert.assertTrue(requestInterceptorList.isEmpty())
Assert.assertTrue(bitmapDecodeInterceptorList.isEmpty())
Assert.assertTrue(drawableDecodeInterceptorList.isEmpty())
}.newBuilder().build().apply {
Assert.assertEquals(
listOf(HttpUriFetcher.Factory()),
fetcherFactoryList
)
Assert.assertEquals(
listOf(XmlDrawableBitmapDecoder.Factory()),
bitmapDecoderFactoryList
)
Assert.assertEquals(
listOf(DefaultDrawableDecoder.Factory()),
drawableDecoderFactoryList
)
Assert.assertTrue(requestInterceptorList.isEmpty())
Assert.assertTrue(bitmapDecodeInterceptorList.isEmpty())
Assert.assertTrue(drawableDecodeInterceptorList.isEmpty())
}.newBuilder {
addRequestInterceptor(EngineRequestInterceptor())
addBitmapDecodeInterceptor(EngineBitmapDecodeInterceptor())
addDrawableDecodeInterceptor(EngineDrawableDecodeInterceptor())
}.build().apply {
Assert.assertEquals(
listOf(HttpUriFetcher.Factory()),
fetcherFactoryList
)
Assert.assertEquals(
listOf(XmlDrawableBitmapDecoder.Factory()),
bitmapDecoderFactoryList
)
Assert.assertEquals(
listOf(DefaultDrawableDecoder.Factory()),
drawableDecoderFactoryList
)
Assert.assertEquals(listOf(EngineRequestInterceptor()), requestInterceptorList)
Assert.assertEquals(
listOf(EngineBitmapDecodeInterceptor()),
bitmapDecodeInterceptorList
)
Assert.assertEquals(
listOf(EngineDrawableDecodeInterceptor()),
drawableDecodeInterceptorList
)
}
}
@Test
fun testNewRegistry() {
ComponentRegistry.Builder().apply {
addFetcher(HttpUriFetcher.Factory())
addBitmapDecoder(XmlDrawableBitmapDecoder.Factory())
addDrawableDecoder(DefaultDrawableDecoder.Factory())
}.build().apply {
Assert.assertEquals(
listOf(HttpUriFetcher.Factory()),
fetcherFactoryList
)
Assert.assertEquals(
listOf(XmlDrawableBitmapDecoder.Factory()),
bitmapDecoderFactoryList
)
Assert.assertEquals(
listOf(DefaultDrawableDecoder.Factory()),
drawableDecoderFactoryList
)
Assert.assertTrue(requestInterceptorList.isEmpty())
Assert.assertTrue(bitmapDecodeInterceptorList.isEmpty())
Assert.assertTrue(drawableDecodeInterceptorList.isEmpty())
}.newRegistry().apply {
Assert.assertEquals(
listOf(HttpUriFetcher.Factory()),
fetcherFactoryList
)
Assert.assertEquals(
listOf(XmlDrawableBitmapDecoder.Factory()),
bitmapDecoderFactoryList
)
Assert.assertEquals(
listOf(DefaultDrawableDecoder.Factory()),
drawableDecoderFactoryList
)
Assert.assertTrue(requestInterceptorList.isEmpty())
Assert.assertTrue(bitmapDecodeInterceptorList.isEmpty())
Assert.assertTrue(drawableDecodeInterceptorList.isEmpty())
}.newRegistry {
addRequestInterceptor(EngineRequestInterceptor())
addBitmapDecodeInterceptor(EngineBitmapDecodeInterceptor())
addDrawableDecodeInterceptor(EngineDrawableDecodeInterceptor())
}.apply {
Assert.assertEquals(
listOf(HttpUriFetcher.Factory()),
fetcherFactoryList
)
Assert.assertEquals(
listOf(XmlDrawableBitmapDecoder.Factory()),
bitmapDecoderFactoryList
)
Assert.assertEquals(
listOf(DefaultDrawableDecoder.Factory()),
drawableDecoderFactoryList
)
Assert.assertEquals(listOf(EngineRequestInterceptor()), requestInterceptorList)
Assert.assertEquals(
listOf(EngineBitmapDecodeInterceptor()),
bitmapDecodeInterceptorList
)
Assert.assertEquals(
listOf(EngineDrawableDecodeInterceptor()),
drawableDecodeInterceptorList
)
}
}
@Test
fun testIsEmpty() {
ComponentRegistry.Builder().build().apply {
Assert.assertTrue(isEmpty())
Assert.assertFalse(isNotEmpty())
}
ComponentRegistry.Builder().apply {
addFetcher(HttpUriFetcher.Factory())
}.build().apply {
Assert.assertFalse(isEmpty())
Assert.assertTrue(isNotEmpty())
}
ComponentRegistry.Builder().apply {
addBitmapDecoder(DefaultBitmapDecoder.Factory())
}.build().apply {
Assert.assertFalse(isEmpty())
Assert.assertTrue(isNotEmpty())
}
ComponentRegistry.Builder().apply {
addDrawableDecoder(DefaultDrawableDecoder.Factory())
}.build().apply {
Assert.assertFalse(isEmpty())
Assert.assertTrue(isNotEmpty())
}
ComponentRegistry.Builder().apply {
addRequestInterceptor(EngineRequestInterceptor())
}.build().apply {
Assert.assertFalse(isEmpty())
Assert.assertTrue(isNotEmpty())
}
ComponentRegistry.Builder().apply {
addBitmapDecodeInterceptor(EngineBitmapDecodeInterceptor())
}.build().apply {
Assert.assertFalse(isEmpty())
Assert.assertTrue(isNotEmpty())
}
ComponentRegistry.Builder().apply {
addDrawableDecodeInterceptor(EngineDrawableDecodeInterceptor())
}.build().apply {
Assert.assertFalse(isEmpty())
Assert.assertTrue(isNotEmpty())
}
}
@Test
fun testNewFetcher() {
val context = getTestContext()
val sketch = newSketch()
ComponentRegistry.Builder().build().apply {
assertThrow(IllegalStateException::class) {
runBlocking(Dispatchers.Main) {
newFetcher(sketch, DisplayRequest(context, TestAssets.SAMPLE_JPEG_URI))
}
}
}
ComponentRegistry.Builder().build().apply {
assertThrow(IllegalArgumentException::class) {
newFetcher(sketch, DisplayRequest(context, TestAssets.SAMPLE_JPEG_URI))
}
assertThrow(IllegalArgumentException::class) {
newFetcher(sketch, DisplayRequest(context, "http://sample.com/sample.jpeg"))
}
Assert.assertNull(
newFetcherOrNull(sketch, DisplayRequest(context, TestAssets.SAMPLE_JPEG_URI))
)
Assert.assertNull(
newFetcherOrNull(sketch, DisplayRequest(context, "http://sample.com/sample.jpeg"))
)
}
ComponentRegistry.Builder().apply {
addFetcher(AssetUriFetcher.Factory())
}.build().apply {
assertNoThrow {
newFetcher(sketch, DisplayRequest(context, TestAssets.SAMPLE_JPEG_URI))
}
assertThrow(IllegalArgumentException::class) {
newFetcher(sketch, DisplayRequest(context, "http://sample.com/sample.jpeg"))
}
Assert.assertNotNull(
newFetcherOrNull(sketch, DisplayRequest(context, TestAssets.SAMPLE_JPEG_URI))
)
Assert.assertNull(
newFetcherOrNull(sketch, DisplayRequest(context, "http://sample.com/sample.jpeg"))
)
}
ComponentRegistry.Builder().apply {
addFetcher(AssetUriFetcher.Factory())
addFetcher(HttpUriFetcher.Factory())
}.build().apply {
assertNoThrow {
newFetcher(sketch, DisplayRequest(context, TestAssets.SAMPLE_JPEG_URI))
}
assertNoThrow {
newFetcher(sketch, DisplayRequest(context, "http://sample.com/sample.jpeg"))
}
Assert.assertNotNull(
newFetcherOrNull(sketch, DisplayRequest(context, TestAssets.SAMPLE_JPEG_URI))
)
Assert.assertNotNull(
newFetcherOrNull(sketch, DisplayRequest(context, "http://sample.com/sample.jpeg"))
)
}
}
@Test
fun testBitmapDecoder() {
val context = getTestContext()
val sketch = newSketch()
val request = DisplayRequest(context, TestAssets.SAMPLE_JPEG_URI)
val requestContext = request.toRequestContext()
ComponentRegistry.Builder().apply {
addFetcher(AssetUriFetcher.Factory())
}.build().apply {
val fetcher = newFetcher(sketch, DisplayRequest(context, TestAssets.SAMPLE_JPEG_URI))
val fetchResult = runBlocking { fetcher.fetch() }
assertThrow(IllegalStateException::class) {
runBlocking(Dispatchers.Main) {
newBitmapDecoder(sketch, requestContext, fetchResult)
}
}
}
ComponentRegistry.Builder().apply {
addFetcher(AssetUriFetcher.Factory())
}.build().apply {
val fetcher = newFetcher(sketch, DisplayRequest(context, TestAssets.SAMPLE_JPEG_URI))
val fetchResult = runBlocking { fetcher.fetch() }
assertThrow(IllegalArgumentException::class) {
newBitmapDecoder(sketch, requestContext, fetchResult)
}
Assert.assertNull(
newBitmapDecoderOrNull(sketch, requestContext, fetchResult)
)
}
ComponentRegistry.Builder().apply {
addFetcher(AssetUriFetcher.Factory())
addBitmapDecoder(DefaultBitmapDecoder.Factory())
}.build().apply {
val fetcher = newFetcher(sketch, DisplayRequest(context, TestAssets.SAMPLE_JPEG_URI))
val fetchResult = runBlocking { fetcher.fetch() }
assertNoThrow {
newBitmapDecoder(sketch, requestContext, fetchResult)
}
Assert.assertNotNull(
newBitmapDecoderOrNull(sketch, requestContext, fetchResult)
)
}
}
@Test
fun testDrawableDecoder() {
val context = getTestContext()
val sketch = newSketch()
val request = DisplayRequest(context, TestAssets.SAMPLE_JPEG_URI)
val requestContext =
request.toRequestContext()
ComponentRegistry.Builder().apply {
addFetcher(AssetUriFetcher.Factory())
}.build().apply {
val fetcher = newFetcher(sketch, DisplayRequest(context, TestAssets.SAMPLE_JPEG_URI))
val fetchResult = runBlocking { fetcher.fetch() }
assertThrow(IllegalStateException::class) {
runBlocking(Dispatchers.Main) {
newDrawableDecoder(sketch, requestContext, fetchResult)
}
}
}
ComponentRegistry.Builder().apply {
addFetcher(AssetUriFetcher.Factory())
}.build().apply {
val fetcher = newFetcher(sketch, DisplayRequest(context, TestAssets.SAMPLE_JPEG_URI))
val fetchResult = runBlocking { fetcher.fetch() }
assertThrow(IllegalArgumentException::class) {
newDrawableDecoder(sketch, requestContext, fetchResult)
}
Assert.assertNull(
newDrawableDecoderOrNull(sketch, requestContext, fetchResult)
)
}
ComponentRegistry.Builder().apply {
addFetcher(AssetUriFetcher.Factory())
addDrawableDecoder(DefaultDrawableDecoder.Factory())
}.build().apply {
val fetcher = newFetcher(sketch, DisplayRequest(context, TestAssets.SAMPLE_JPEG_URI))
val fetchResult = runBlocking { fetcher.fetch() }
assertNoThrow {
newDrawableDecoder(sketch, requestContext, fetchResult)
}
Assert.assertNotNull(
newDrawableDecoderOrNull(sketch, requestContext, fetchResult)
)
}
}
@Test
fun testMerged() {
val componentRegistry = ComponentRegistry.Builder().apply {
addFetcher(TestFetcher.Factory())
addBitmapDecoder(TestBitmapDecoder.Factory())
addDrawableDecoder(TestDrawableDecoder.Factory())
addRequestInterceptor(TestRequestInterceptor())
addBitmapDecodeInterceptor(TestBitmapDecodeInterceptor())
addDrawableDecodeInterceptor(TestDrawableDecodeInterceptor())
}.build().apply {
Assert.assertEquals(
"ComponentRegistry(" +
"fetcherFactoryList=[TestFetcher]," +
"bitmapDecoderFactoryList=[TestBitmapDecoder]," +
"drawableDecoderFactoryList=[TestDrawableDecoder]," +
"requestInterceptorList=[TestRequestInterceptor(sortWeight=0)]," +
"bitmapDecodeInterceptorList=[TestBitmapDecodeInterceptor(sortWeight=0)]," +
"drawableDecodeInterceptorList=[TestDrawableDecodeInterceptor(sortWeight=0)]" +
")",
toString()
)
}
val componentRegistry1 = ComponentRegistry.Builder().apply {
addFetcher(HttpUriFetcher.Factory())
addBitmapDecoder(DefaultBitmapDecoder.Factory())
addDrawableDecoder(DefaultDrawableDecoder.Factory())
addRequestInterceptor(EngineRequestInterceptor())
addBitmapDecodeInterceptor(Test2BitmapDecodeInterceptor())
addDrawableDecodeInterceptor(Test2DrawableDecodeInterceptor())
}.build().apply {
Assert.assertEquals(
"ComponentRegistry(" +
"fetcherFactoryList=[HttpUriFetcher]," +
"bitmapDecoderFactoryList=[DefaultBitmapDecoder]," +
"drawableDecoderFactoryList=[DefaultDrawableDecoder]," +
"requestInterceptorList=[EngineRequestInterceptor(sortWeight=100)]," +
"bitmapDecodeInterceptorList=[Test2BitmapDecodeInterceptor(sortWeight=0)]," +
"drawableDecodeInterceptorList=[Test2DrawableDecodeInterceptor(sortWeight=0)]" +
")",
toString()
)
}
Assert.assertNotEquals(componentRegistry, componentRegistry1)
val componentRegistry2 = componentRegistry.merged(componentRegistry1).apply {
Assert.assertEquals(
"ComponentRegistry(" +
"fetcherFactoryList=[TestFetcher,HttpUriFetcher]," +
"bitmapDecoderFactoryList=[TestBitmapDecoder,DefaultBitmapDecoder]," +
"drawableDecoderFactoryList=[TestDrawableDecoder,DefaultDrawableDecoder]," +
"requestInterceptorList=[TestRequestInterceptor(sortWeight=0),EngineRequestInterceptor(sortWeight=100)]," +
"bitmapDecodeInterceptorList=[TestBitmapDecodeInterceptor(sortWeight=0),Test2BitmapDecodeInterceptor(sortWeight=0)]," +
"drawableDecodeInterceptorList=[TestDrawableDecodeInterceptor(sortWeight=0),Test2DrawableDecodeInterceptor(sortWeight=0)]" +
")",
toString()
)
}
Assert.assertNotEquals(componentRegistry, componentRegistry2)
Assert.assertNotEquals(componentRegistry1, componentRegistry2)
Assert.assertSame(componentRegistry, componentRegistry.merged(null))
Assert.assertSame(componentRegistry, null.merged(componentRegistry))
}
@Test
fun testToString() {
ComponentRegistry.Builder().build().apply {
Assert.assertEquals(
"ComponentRegistry(" +
"fetcherFactoryList=[]," +
"bitmapDecoderFactoryList=[]," +
"drawableDecoderFactoryList=[]," +
"requestInterceptorList=[]," +
"bitmapDecodeInterceptorList=[]," +
"drawableDecodeInterceptorList=[]" +
")",
toString()
)
}
ComponentRegistry.Builder().apply {
addFetcher(HttpUriFetcher.Factory())
addFetcher(Base64UriFetcher.Factory())
addFetcher(ResourceUriFetcher.Factory())
addBitmapDecoder(XmlDrawableBitmapDecoder.Factory())
addBitmapDecoder(DefaultBitmapDecoder.Factory())
addDrawableDecoder(DefaultDrawableDecoder.Factory())
addRequestInterceptor(EngineRequestInterceptor())
addBitmapDecodeInterceptor(EngineBitmapDecodeInterceptor())
addBitmapDecodeInterceptor(BitmapTransformationDecodeInterceptor())
addDrawableDecodeInterceptor(EngineDrawableDecodeInterceptor())
}.build().apply {
Assert.assertEquals(
"ComponentRegistry(" +
"fetcherFactoryList=[HttpUriFetcher,Base64UriFetcher,ResourceUriFetcher]," +
"bitmapDecoderFactoryList=[XmlDrawableBitmapDecoder,DefaultBitmapDecoder]," +
"drawableDecoderFactoryList=[DefaultDrawableDecoder]," +
"requestInterceptorList=[EngineRequestInterceptor(sortWeight=100)]," +
"bitmapDecodeInterceptorList=[BitmapTransformationDecodeInterceptor(sortWeight=90),EngineBitmapDecodeInterceptor(sortWeight=100)]," +
"drawableDecodeInterceptorList=[EngineDrawableDecodeInterceptor(sortWeight=100)]" +
")",
toString()
)
}
}
@Test
fun testEquals() {
val componentRegistry0 = ComponentRegistry.Builder().build()
val componentRegistry1 = ComponentRegistry.Builder().apply {
addFetcher(HttpUriFetcher.Factory())
}.build()
val componentRegistry11 = ComponentRegistry.Builder().apply {
addFetcher(HttpUriFetcher.Factory())
}.build()
val componentRegistry2 = ComponentRegistry.Builder().apply {
addBitmapDecoder(XmlDrawableBitmapDecoder.Factory())
}.build()
val componentRegistry3 = ComponentRegistry.Builder().apply {
addDrawableDecoder(DefaultDrawableDecoder.Factory())
}.build()
val componentRegistry4 = ComponentRegistry.Builder().apply {
addRequestInterceptor(EngineRequestInterceptor())
}.build()
val componentRegistry5 = ComponentRegistry.Builder().apply {
addBitmapDecodeInterceptor(EngineBitmapDecodeInterceptor())
}.build()
val componentRegistry6 = ComponentRegistry.Builder().apply {
addDrawableDecodeInterceptor(EngineDrawableDecodeInterceptor())
}.build()
Assert.assertEquals(componentRegistry0, componentRegistry0)
Assert.assertEquals(componentRegistry1, componentRegistry11)
Assert.assertNotEquals(componentRegistry1, Any())
Assert.assertNotEquals(componentRegistry1, null)
Assert.assertNotEquals(componentRegistry0, componentRegistry1)
Assert.assertNotEquals(componentRegistry0, componentRegistry2)
Assert.assertNotEquals(componentRegistry0, componentRegistry3)
Assert.assertNotEquals(componentRegistry0, componentRegistry4)
Assert.assertNotEquals(componentRegistry0, componentRegistry5)
Assert.assertNotEquals(componentRegistry0, componentRegistry6)
Assert.assertNotEquals(componentRegistry1, componentRegistry2)
Assert.assertNotEquals(componentRegistry1, componentRegistry3)
Assert.assertNotEquals(componentRegistry1, componentRegistry4)
Assert.assertNotEquals(componentRegistry1, componentRegistry5)
Assert.assertNotEquals(componentRegistry1, componentRegistry6)
Assert.assertNotEquals(componentRegistry2, componentRegistry3)
Assert.assertNotEquals(componentRegistry2, componentRegistry4)
Assert.assertNotEquals(componentRegistry2, componentRegistry5)
Assert.assertNotEquals(componentRegistry2, componentRegistry6)
Assert.assertNotEquals(componentRegistry3, componentRegistry4)
Assert.assertNotEquals(componentRegistry3, componentRegistry5)
Assert.assertNotEquals(componentRegistry3, componentRegistry6)
Assert.assertNotEquals(componentRegistry4, componentRegistry5)
Assert.assertNotEquals(componentRegistry4, componentRegistry6)
Assert.assertNotEquals(componentRegistry5, componentRegistry6)
}
@Test
fun testHashCode() {
val componentRegistry0 = ComponentRegistry.Builder().build()
val componentRegistry1 = ComponentRegistry.Builder().apply {
addFetcher(HttpUriFetcher.Factory())
}.build()
val componentRegistry2 = ComponentRegistry.Builder().apply {
addBitmapDecoder(XmlDrawableBitmapDecoder.Factory())
}.build()
val componentRegistry3 = ComponentRegistry.Builder().apply {
addDrawableDecoder(DefaultDrawableDecoder.Factory())
}.build()
val componentRegistry4 = ComponentRegistry.Builder().apply {
addRequestInterceptor(EngineRequestInterceptor())
}.build()
val componentRegistry5 = ComponentRegistry.Builder().apply {
addBitmapDecodeInterceptor(EngineBitmapDecodeInterceptor())
}.build()
val componentRegistry6 = ComponentRegistry.Builder().apply {
addDrawableDecodeInterceptor(EngineDrawableDecodeInterceptor())
}.build()
Assert.assertNotEquals(componentRegistry0.hashCode(), componentRegistry1.hashCode())
Assert.assertNotEquals(componentRegistry0.hashCode(), componentRegistry2.hashCode())
Assert.assertNotEquals(componentRegistry0.hashCode(), componentRegistry3.hashCode())
Assert.assertNotEquals(componentRegistry0.hashCode(), componentRegistry4.hashCode())
Assert.assertNotEquals(componentRegistry0.hashCode(), componentRegistry5.hashCode())
Assert.assertNotEquals(componentRegistry0.hashCode(), componentRegistry6.hashCode())
Assert.assertNotEquals(componentRegistry1.hashCode(), componentRegistry2.hashCode())
Assert.assertNotEquals(componentRegistry1.hashCode(), componentRegistry3.hashCode())
Assert.assertNotEquals(componentRegistry1.hashCode(), componentRegistry4.hashCode())
Assert.assertNotEquals(componentRegistry1.hashCode(), componentRegistry5.hashCode())
Assert.assertNotEquals(componentRegistry1.hashCode(), componentRegistry6.hashCode())
Assert.assertNotEquals(componentRegistry2.hashCode(), componentRegistry3.hashCode())
Assert.assertNotEquals(componentRegistry2.hashCode(), componentRegistry4.hashCode())
Assert.assertNotEquals(componentRegistry2.hashCode(), componentRegistry5.hashCode())
Assert.assertNotEquals(componentRegistry2.hashCode(), componentRegistry6.hashCode())
Assert.assertNotEquals(componentRegistry3.hashCode(), componentRegistry4.hashCode())
Assert.assertNotEquals(componentRegistry3.hashCode(), componentRegistry5.hashCode())
Assert.assertNotEquals(componentRegistry3.hashCode(), componentRegistry6.hashCode())
Assert.assertNotEquals(componentRegistry4.hashCode(), componentRegistry5.hashCode())
Assert.assertNotEquals(componentRegistry4.hashCode(), componentRegistry6.hashCode())
Assert.assertNotEquals(componentRegistry5.hashCode(), componentRegistry6.hashCode())
}
} | apache-2.0 | b0321f5cbdf08f0f8a7a3be06f8de223 | 44.652318 | 157 | 0.649947 | 6.01374 | false | true | false | false |
kjkrol/kotlin4fun-eshop-app | ordering-service/src/main/kotlin/kotlin4fun/eshop/ordering/integration/ProductCatalogClient.kt | 1 | 1205 | package kotlin4fun.eshop.ordering.integration
import com.fasterxml.jackson.annotation.JsonCreator
import com.fasterxml.jackson.annotation.JsonIgnoreProperties
import com.fasterxml.jackson.annotation.JsonProperty
import org.springframework.cloud.netflix.feign.FeignClient
import org.springframework.hateoas.PagedResources
import org.springframework.hateoas.Resource
import org.springframework.hateoas.core.Relation
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RequestMethod
import org.springframework.web.bind.annotation.RequestParam
import java.util.UUID
@FeignClient(serviceId = "PRODUCT-CATALOG-SERVICE")
internal interface ProductCatalogClient {
@RequestMapping(path = arrayOf("/product"), method = arrayOf(RequestMethod.GET))
fun findAll(@RequestParam("ids") ids: List<UUID>): PagedResources<Resource<ProductResponse>>
}
@JsonIgnoreProperties(ignoreUnknown = true)
@Relation(collectionRelation = "products")
internal data class ProductResponse @JsonCreator constructor(
@JsonProperty("productId") val productId: UUID,
@JsonProperty("name") val name: String,
@JsonProperty("price") val price: Double
) | apache-2.0 | 8e7c53cbe9b8bfba40ab4ce47d5b68f1 | 40.586207 | 96 | 0.814938 | 4.530075 | false | false | false | false |
chadrick-kwag/datalabeling_app | app/src/main/java/com/example/chadrick/datalabeling/Models/RecentActivityLogManager.kt | 1 | 4768 | package com.example.chadrick.datalabeling.Models
import android.content.Context
import android.util.Log
import org.json.JSONArray
import org.json.JSONException
import org.json.JSONObject
import java.io.*
import java.lang.ref.WeakReference
import java.nio.charset.Charset
import java.util.*
import java.util.concurrent.CancellationException
import kotlin.collections.ArrayList
/**
* Created by chadrick on 17. 12. 5.
*/
class RecentActivityLogManager {
// var mcontext: Context
var mcontext: Context by WeakRefHolder()
companion object {
@Volatile private var INSTANCE: RecentActivityLogManager? = null
fun getInstance(context: Context): RecentActivityLogManager =
INSTANCE ?: synchronized(this) {
INSTANCE ?: RecentActivityLogManager(context).also { INSTANCE = it }
}
val TAG: String = "RecentActivityLogManager"
val RAitemMap = HashMap<Int, Pair<DataSet, Long>>() // Int is the dataset id of DataSet
val jsonfilename = "recentactivitylog.json"
lateinit var jsonfilefullpath: File
}
private constructor(context: Context) {
// mcontext = context
try {
mcontext = context
readparse()
}
catch(e: CancellationException){
}
}
private fun readparse() {
jsonfilefullpath = File(mcontext.filesDir, jsonfilename)
Log.d(TAG, "ralogfile=" + jsonfilefullpath)
if (!jsonfilefullpath.exists()) {
return
}
val inputstream = FileInputStream(jsonfilefullpath)
var size = inputstream.available()
val buffer = ByteArray(size)
inputstream.read(buffer)
inputstream.close()
val jsonfilereadraw = String(buffer, Charset.forName("UTF-8"))
Log.d(TAG, "jsonfile read raw=" + jsonfilereadraw)
val rootobj = JSONObject(jsonfilereadraw)
val RAarray = rootobj.getJSONArray("items")
for (i in 0..RAarray.length() - 1) {
try {
val item = RAarray.getJSONObject(i)
var extractedDS: DataSet = DataSet.deserialize(item.getString("dataset"))
RAitemMap.put(extractedDS.id, Pair<DataSet, Long>(extractedDS, item.getLong("recent_access_time")))
} catch (e: JSONException) {
// the file is corrupt. delete it.
Log.d(TAG, "the ra json file is corrupt. delete it")
jsonfilefullpath.delete()
return
}
}
// mid check
Log.d(TAG, "RAitemMap size=" + RAitemMap.size)
// print all objects
for (item in RAitemMap) {
Log.d(TAG, "key=" + item.key + ", value=" + item.value)
}
}
fun updateRAitem(dataset: DataSet, access_datetime: Long) {
RAitemMap.put(dataset.id, Pair<DataSet, Long>(dataset, access_datetime))
// val sortedMap = RAitemMap.toList().sortedBy { (key,value) -> -value }.toMap()
// // print the contents of sortedMap
// Log.d(TAG,"print sorted result")
// for(item in sortedMap){
// Log.d(TAG,"key="+item.key+", value="+item.value)
// }
Log.d(TAG, "print RAitemMap")
for (item in RAitemMap) {
Log.d(TAG, "key.id=" + item.key + ", value=" + item.value)
}
savetojsonfile()
}
fun savetojsonfile() {
Log.d(TAG, "inside savetojsonfile")
// convert RAitemmap to json obj
// create individual jsonojects for each RAitemmap item
val convertedJsonobjs = ArrayList<JSONObject>()
for (item in RAitemMap) {
val jsonobj = JSONObject()
jsonobj.put("dataset", item.value.first.serialize())
jsonobj.put("recent_access_time", item.value.second)
convertedJsonobjs.add(jsonobj)
}
val itemjsonarray = JSONArray(convertedJsonobjs)
Log.d(TAG, "print itemjsonarray = " + itemjsonarray.toString())
val rootobj = JSONObject()
rootobj.put("items", itemjsonarray)
// print completed jsonobj
Log.d(TAG, "temp created root jsonobj: " + rootobj.toString())
if (jsonfilefullpath.exists()) {
jsonfilefullpath.delete()
}
val fileWriter = FileWriter(jsonfilefullpath)
val output = BufferedWriter(fileWriter)
output.write(rootobj.toString())
output.close()
}
fun getsortedlist(): ArrayList<DataSet> {
val pairlist = RAitemMap.toList().sortedBy { (key, value) -> -value.second }
val dsidlist = ArrayList<DataSet>()
pairlist.forEach { (key, value) -> dsidlist.add(value.first) }
return dsidlist
}
} | mit | d997d5bbdb7652b47070a52b8bbf7229 | 25.792135 | 115 | 0.602978 | 4.135299 | false | false | false | false |
AndroidX/androidx | compose/ui/ui/src/androidAndroidTest/kotlin/androidx/compose/ui/node/ObserverNodeTest.kt | 3 | 5380 | /*
* 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.ui.node
import androidx.compose.foundation.layout.Box
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.compose.ui.ExperimentalComposeUiApi
import androidx.compose.ui.Modifier
import androidx.compose.ui.test.junit4.createComposeRule
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.filters.MediumTest
import com.google.common.truth.Truth.assertThat
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
@OptIn(ExperimentalComposeUiApi::class)
@MediumTest
@RunWith(AndroidJUnit4::class)
class ObserverNodeTest {
@get:Rule
val rule = createComposeRule()
@Test
fun simplyObservingValue_doesNotTriggerCallback() {
// Arrange.
val value by mutableStateOf(1)
var callbackInvoked = false
val observerNode = TestObserverNode { callbackInvoked = true }
rule.setContent {
Box(Modifier.modifierElementOf { observerNode })
}
// Act.
rule.runOnIdle {
// Read value to observe changes.
observerNode.observeReads { value.toString() }
}
// Assert.
rule.runOnIdle {
assertThat(callbackInvoked).isFalse()
}
}
@Test
fun changeInObservedValue_triggersCallback() {
// Arrange.
var value by mutableStateOf(1)
var callbackInvoked = false
val observerNode = TestObserverNode { callbackInvoked = true }
rule.setContent {
Box(Modifier.modifierElementOf { observerNode })
}
// Act.
rule.runOnIdle {
// Read value to observe changes.
observerNode.observeReads { value.toString() }
// Write to the read value to trigger onObservedReadsChanged.
value = 3
}
// Assert.
rule.runOnIdle {
assertThat(callbackInvoked).isTrue()
}
}
@Test(expected = IllegalStateException::class)
fun unusedNodeDoesNotObserve() {
// Arrange.
var value by mutableStateOf(1)
var callbackInvoked = false
val observerNode = TestObserverNode { callbackInvoked = true }
// Act.
rule.runOnIdle {
// Read value to observe changes.
observerNode.observeReads { value.toString() }
// Write to the read value to trigger onObservedReadsChanged.
value = 3
}
// Assert.
rule.runOnIdle {
assertThat(callbackInvoked).isFalse()
}
}
@Test
fun detachedNodeCanObserveReads() {
// Arrange.
var value by mutableStateOf(1)
var callbackInvoked = false
val observerNode = TestObserverNode { callbackInvoked = true }
var attached by mutableStateOf(true)
rule.setContent {
Box(if (attached) modifierElementOf { observerNode } else Modifier)
}
// Act.
// Read value while not attached.
rule.runOnIdle { attached = false }
rule.runOnIdle { observerNode.observeReads { value.toString() } }
rule.runOnIdle { attached = true }
// Write to the read value to trigger onObservedReadsChanged.
rule.runOnIdle { value = 3 }
// Assert.
rule.runOnIdle {
assertThat(callbackInvoked).isTrue()
}
}
@Test
fun detachedNodeDoesNotCallOnObservedReadsChanged() {
// Arrange.
var value by mutableStateOf(1)
var callbackInvoked = false
val observerNode = TestObserverNode { callbackInvoked = true }
var attached by mutableStateOf(true)
rule.setContent {
Box(if (attached) modifierElementOf { observerNode } else Modifier)
}
// Act.
rule.runOnIdle {
// Read value to observe changes.
observerNode.observeReads { value.toString() }
}
rule.runOnIdle {
attached = false
}
// Write to the read value to trigger onObservedReadsChanged.
rule.runOnIdle { value = 3 }
// Assert.
rule.runOnIdle {
assertThat(callbackInvoked).isFalse()
}
}
@ExperimentalComposeUiApi
private inline fun <reified T : Modifier.Node> Modifier.modifierElementOf(
crossinline create: () -> T,
): Modifier {
return this.then(modifierElementOf(create) { name = "testNode" })
}
class TestObserverNode(
private val onObserveReadsChanged: () -> Unit,
) : ObserverNode, Modifier.Node() {
override fun onObservedReadsChanged() {
this.onObserveReadsChanged()
}
}
}
| apache-2.0 | 54e14dba69e2f37b529ec0c654d4f3e8 | 29.39548 | 79 | 0.634758 | 4.807864 | false | true | false | false |
Xenoage/Zong | utils-kotlin/src/com/xenoage/utils/sequences/MapWithPreviousSequence.kt | 1 | 1329 | package com.xenoage.utils.sequences
/**
* A sequence that returns projected values from the underlying [sequence].
* It is identical to the [MappingSequence] from the
* standard library but also provides the previous filtered value at each item.
*/
class MapWithPreviousSequence<I, O>(
private val sequence: Sequence<I>,
private val map: (current: I, previous: O?) -> O
) : Sequence<O> {
override fun iterator(): Iterator<O> = object : Iterator<O> {
val iterator = sequence.iterator()
var nextState: Int = -1 // -1 for unknown, 0 for done, 1 for continue
var previousMappedItem: O? = null //at the beginning, no item was mapped yet
private fun calcNext() {
while (iterator.hasNext()) {
val item = iterator.next()
previousMappedItem = map(item, previousMappedItem)
nextState = 1
return
}
nextState = 0
}
override fun next(): O {
if (nextState == -1)
calcNext()
if (nextState == 0)
throw NoSuchElementException()
val result = previousMappedItem!!
nextState = -1
return result
}
override fun hasNext(): Boolean {
if (nextState == -1)
calcNext()
return nextState == 1
}
}
}
/** See [MapWithPreviousSequence]. */
fun <I, O> Sequence<I>.mapWithPrevious(map: (current: I, previous: O?) -> O): Sequence<O> =
MapWithPreviousSequence(this, map) | agpl-3.0 | fabf983fcd737cf403e65d1b9c7f449b | 26.142857 | 91 | 0.671934 | 3.544 | false | false | false | false |
codeka/wwmmo | client/src/main/kotlin/au/com/codeka/warworlds/client/game/sitrep/SitReportAdapter.kt | 1 | 6540 | package au.com.codeka.warworlds.client.game.sitrep
import android.text.Html
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import au.com.codeka.warworlds.client.R
import au.com.codeka.warworlds.client.concurrency.Threads
import au.com.codeka.warworlds.client.ctrl.fromHtml
import au.com.codeka.warworlds.client.game.build.BuildViewHelper
import au.com.codeka.warworlds.client.game.world.ImageHelper
import au.com.codeka.warworlds.client.game.world.StarManager
import au.com.codeka.warworlds.common.proto.Design
import au.com.codeka.warworlds.common.proto.SituationReport
import au.com.codeka.warworlds.common.proto.Star
import au.com.codeka.warworlds.common.sim.DesignHelper
import java.time.LocalDate
import java.time.LocalDateTime
import java.time.ZoneOffset
import java.time.format.DateTimeFormatter
import java.util.*
class SitReportAdapter(private val layoutInflater: LayoutInflater)
: RecyclerView.Adapter<SitReportAdapter.SitReportViewHolder>() {
private val rows = ArrayList<RowData>()
private val starRowMap = HashMap<Long, Set<Int>>()
companion object {
val dateFormat: DateTimeFormatter = DateTimeFormatter.ofPattern("dd MMM, yyyy", Locale.ENGLISH)
val timeFormat: DateTimeFormatter = DateTimeFormatter.ofPattern("h:mm\na", Locale.ENGLISH)
}
fun refresh(sitReports: List<SituationReport>) {
Threads.checkOnThread(Threads.UI)
rows.clear()
starRowMap.clear()
var lastDate: LocalDate? = null
for ((i, sitReport) in sitReports.withIndex()) {
val date =
LocalDateTime.ofEpochSecond(sitReport.report_time / 1000, 0, ZoneOffset.UTC).toLocalDate()
if (lastDate == null || lastDate != date) {
rows.add(RowData(date, null))
lastDate = date
}
rows.add(RowData(null, sitReport))
val positions = starRowMap[sitReport.star_id] ?: HashSet()
starRowMap[sitReport.star_id] = positions
positions.plus(i)
}
notifyDataSetChanged()
}
fun onStarUpdated(star: Star) {
val positions = starRowMap[star.id]
if (positions != null) {
for (position in positions) {
notifyItemChanged(position)
}
}
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): SitReportViewHolder {
val view = layoutInflater.inflate(viewType, parent, false)
return SitReportViewHolder(viewType, view)
}
override fun getItemCount(): Int {
return rows.size
}
override fun getItemViewType(position: Int): Int {
return when {
rows[position].date != null -> R.layout.sitreport_row_day
else -> R.layout.sitreport_row
}
}
override fun onBindViewHolder(holder: SitReportViewHolder, position: Int) {
holder.bind(rows[position])
}
class SitReportViewHolder(viewType: Int, itemView: View) : RecyclerView.ViewHolder(itemView) {
private val dateViewBinding: DateViewBinding?
private val sitReportViewBinding: SitReportViewBinding?
init {
if (viewType == R.layout.sitreport_row_day) {
dateViewBinding = DateViewBinding(itemView)
sitReportViewBinding = null
} else {
dateViewBinding = null
sitReportViewBinding = SitReportViewBinding(itemView)
}
}
fun bind(row: RowData) {
when {
row.date != null -> dateViewBinding!!.bind(row.date)
row.sitReport != null -> sitReportViewBinding!!.bind(row.sitReport)
}
}
}
class DateViewBinding(view: View) {
private val dateView: TextView = view as TextView
fun bind(date: LocalDate) {
// TODO: special-case TODAY and YESTERDAY
dateView.text = date.format(dateFormat)
}
}
class SitReportViewBinding(view: View) {
private val timeView: TextView = view.findViewById(R.id.time)
private val starIconView: ImageView = view.findViewById(R.id.star_icon)
private val designIconView: ImageView = view.findViewById(R.id.design_icon)
private val reportTitleView: TextView = view.findViewById(R.id.report_title)
private val reportDetailsView: TextView = view.findViewById(R.id.report_details)
fun bind(sitReport: SituationReport) {
val res = timeView.context.resources
val reportTime =
LocalDateTime.ofEpochSecond(sitReport.report_time / 1000, 0, ZoneOffset.UTC).toLocalTime()
timeView.text = reportTime.format(timeFormat)
val star = StarManager.getStar(sitReport.star_id)
if (star != null) {
ImageHelper.bindStarIcon(starIconView, star)
}
val design: Design?
val buildCompleteReport = sitReport.build_complete_record
val moveCompleteReport = sitReport.move_complete_record
when {
buildCompleteReport != null -> {
design = DesignHelper.getDesign(buildCompleteReport.design_type)
reportTitleView.text =
fromHtml(res.getString(R.string.build_complete, star?.name ?: "..."))
if (design.design_kind == Design.DesignKind.SHIP) {
// TODO: handle was_destroyed when we have it.
reportDetailsView.text =
res.getString(
R.string.fleet_details_not_destroyed,
buildCompleteReport.count.toFloat(),
design.display_name)
} else {
reportDetailsView.text = res.getString(R.string.build_details, design.display_name)
}
}
moveCompleteReport != null -> {
design = DesignHelper.getDesign(moveCompleteReport.design_type)
reportTitleView.text =
fromHtml(res.getString(R.string.fleet_move_complete, star?.name ?: "..."))
val resId =
if (design.design_kind == Design.DesignKind.SHIP && moveCompleteReport.was_destroyed) {
R.string.fleet_details_destroyed
} else /* if (design.design_kind == Design.DesignKind.SHIP) */ {
R.string.fleet_details_not_destroyed
}
reportDetailsView.text =
res.getString(resId, moveCompleteReport.num_ships, design.display_name)
}
else -> {
design = null
reportTitleView.text =
fromHtml(res.getString(R.string.attack_on_star, star?.name ?: "..."))
}
}
if (design != null) {
BuildViewHelper.setDesignIcon(design, designIconView)
}
}
}
data class RowData(val date: LocalDate?, val sitReport: SituationReport?)
}
| mit | bc86daf2255fa1e9543385041957e1e0 | 33.973262 | 100 | 0.681193 | 4.123581 | false | false | false | false |
Undin/intellij-rust | src/test/kotlin/org/rust/lang/core/stubs/RsBlockStubTest.kt | 2 | 3098 | /*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.lang.core.stubs
import com.intellij.psi.impl.DebugUtil
import org.intellij.lang.annotations.Language
import org.rust.RsTestBase
import org.rust.lang.core.psi.RsFunction
import org.rust.lang.core.psi.ext.block
import org.rust.lang.core.psi.ext.childOfType
import org.rust.lang.core.resolve2.util.buildStub
class RsBlockStubTest : RsTestBase() {
fun `test empty`() = doTest("""
fn f() {}
""", """
BLOCK:RsPlaceholderStub
""")
fun `test not stubbed`() = doTest("""
fn f() {
0;
let x = 1;
func();
impl Foo {}
// block expr
{ 1 }
}
""", """
BLOCK:RsPlaceholderStub
""")
fun `test imports`() = doTest("""
fn f() {
use foo1::item1;
use foo2::item2 as item3;
use foo3::{item4, item5};
}
""", """
BLOCK:RsPlaceholderStub
USE_ITEM:RsUseItemStub
USE_SPECK:RsUseSpeckStub
PATH:RsPathStub
PATH:RsPathStub
USE_ITEM:RsUseItemStub
USE_SPECK:RsUseSpeckStub
PATH:RsPathStub
PATH:RsPathStub
ALIAS:RsAliasStub
USE_ITEM:RsUseItemStub
USE_SPECK:RsUseSpeckStub
PATH:RsPathStub
USE_GROUP:RsPlaceholderStub
USE_SPECK:RsUseSpeckStub
PATH:RsPathStub
USE_SPECK:RsUseSpeckStub
PATH:RsPathStub
""")
fun `test items`() = doTest("""
fn f() {
fn func(a: i32) -> i32 { 0 }
struct Struct1;
struct Struct2(i32);
struct Struct3 { a: i32 }
enum E {
E1,
E2(i32),
E3 { a: i32 },
}
}
""", """
BLOCK:RsPlaceholderStub
FUNCTION:RsFunctionStub
STRUCT_ITEM:RsStructItemStub
STRUCT_ITEM:RsStructItemStub
STRUCT_ITEM:RsStructItemStub
ENUM_ITEM:RsEnumItemStub
ENUM_BODY:RsPlaceholderStub
ENUM_VARIANT:RsEnumVariantStub
ENUM_VARIANT:RsEnumVariantStub
ENUM_VARIANT:RsEnumVariantStub
""")
fun `test macros`() = doTest("""
fn f() {
macro macro1() { 1 }
macro_rules! macro2 { () => { 1 }; }
macro1!(1);
}
""", """
BLOCK:RsPlaceholderStub
MACRO_2:RsMacro2Stub
MACRO:RsMacroStub
MACRO_CALL:RsMacroCallStub
PATH:RsPathStub
""")
private fun doTest(@Language("Rust") code: String, expectedStubText: String) {
InlineFile(code)
val file = myFixture.file
val block = file.childOfType<RsFunction>()!!.block!!
val stub = block.buildStub()!!
val stubText = DebugUtil.stubTreeToString(stub)
assertEquals(expectedStubText.trimIndent() + "\n", stubText)
}
}
| mit | cdd5fba4405b9db12d9d1017ac2cf886 | 26.90991 | 82 | 0.528405 | 4.351124 | false | true | false | false |
Undin/intellij-rust | src/main/kotlin/org/rust/ide/inspections/lints/RsUnnecessaryQualificationsInspection.kt | 2 | 4663 | /*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.ide.inspections.lints
import com.intellij.openapi.util.TextRange
import com.intellij.psi.PsiElement
import com.intellij.psi.util.parentOfType
import org.rust.ide.inspections.RsProblemsHolder
import org.rust.ide.inspections.fixes.SubstituteTextFix
import org.rust.lang.core.parser.RustParserUtil
import org.rust.lang.core.psi.*
import org.rust.lang.core.psi.ext.*
import org.rust.lang.core.resolve.TYPES_N_VALUES_N_MACROS
class RsUnnecessaryQualificationsInspection : RsLintInspection() {
override fun getLint(element: PsiElement): RsLint = RsLint.UnusedQualifications
override fun buildVisitor(holder: RsProblemsHolder, isOnTheFly: Boolean): RsVisitor = object : RsVisitor() {
override fun visitPath(path: RsPath) {
val shouldCheckPath = path.parentOfType<RsUseItem>() == null
&& path.parentOfType<RsVisRestriction>() == null
&& path.rootPath() == path
&& path.canBeShortened()
if (shouldCheckPath) {
val target = getUnnecessarilyQualifiedPath(path)
if (target != null) {
val pathRestStart = target.referenceNameElement!!.startOffset
val unnecessaryLength = pathRestStart - path.startOffset
val range = TextRange(0, unnecessaryLength)
val fix = SubstituteTextFix.delete(
"Remove unnecessary path prefix",
path.containingFile,
TextRange(path.startOffset, pathRestStart)
)
holder.registerLintProblem(path, "Unnecessary qualification", range, RsLintHighlightingType.UNUSED_SYMBOL, listOf(fix))
}
}
super.visitPath(path)
}
}
/**
* Consider a path like `a::b::c::d`.
* We will try to walk it from the "root" (the rightmost sub-path).
* First we try `d`, then `c::d`, then `b::c::d`, etc.
* Once we find a path that can be resolved and which is shorter than the original path, we will return it.
*/
private fun getUnnecessarilyQualifiedPath(path: RsPath): RsPath? {
if (path.resolveStatus == PathResolveStatus.UNRESOLVED) return null
val target = path.reference?.resolve() ?: return null
// From `a::b::c::d` generates paths `a::b::c::d`, `a::b::c`, `a::b` and `a`.
val subPaths = generateSequence(path) { it.qualifier }.toList()
// If any part of the path has type qualifiers/arguments, we don't want to erase parts of that path to the
// right of the type, because the qualifiers/arguments can be important for type inference.
val lastSubPathWithType = subPaths.indexOfLast { it.typeQual != null || it.typeArgumentList != null }
.takeIf { it != -1 } ?: 0
val rootPathText = subPaths.getOrNull(0)?.referenceName ?: return null
// From `a::b::c::d` generates strings `d`, `c::d`, `b::c::d`, `a::b::c::d`.
val pathTexts = subPaths.drop(1).runningFold(rootPathText) { accumulator, subPath ->
"${subPath.referenceName}::$accumulator"
}
val basePath = path.basePath()
for ((subPath, subPathText) in subPaths.zip(pathTexts).drop(lastSubPathWithType)) {
val fragment = RsPathCodeFragment(
path.project, subPathText, false, path, RustParserUtil.PathParsingMode.TYPE,
TYPES_N_VALUES_N_MACROS
)
// If the subpath is resolvable, we want to ignore it if it is the last fragment ("base") of the original path.
// However, leading `::` has to be handled in a special way.
// If `a::b::c::d` resolves to the same item as `::a::b::c::d`, we don't want to ignore `a`.
// To recognize this, we check if the current path corresponds to the base path, and if the base path
// doesn't have a leading `::`. In that case, the paths are the same and there's nothing to shorten.
// On the other hand, `subPathText` will never have a leading `::`, so if the base path has `::` and `a`
// resolves to the same thing as `::a`, we can still shorten the path.
val sameAsBase = subPath == basePath && !basePath.hasColonColon
if (fragment.path?.reference?.resolve() == target && !sameAsBase) {
return subPath
}
}
return null
}
}
private fun RsPath.canBeShortened(): Boolean {
return path != null || coloncolon != null
}
| mit | 21893f36e0a61630675812e56263a49e | 47.072165 | 139 | 0.621703 | 4.309612 | false | false | false | false |
cat-in-the-dark/GamesServer | lib-libgdx/src/main/kotlin/org/catinthedark/shared/libgdx/control/Control.kt | 1 | 5032 | package org.catinthedark.shared.libgdx.control
import com.badlogic.gdx.Gdx
import com.badlogic.gdx.Input
import com.badlogic.gdx.controllers.Controller
import com.badlogic.gdx.controllers.ControllerAdapter
import com.badlogic.gdx.controllers.Controllers
import com.badlogic.gdx.controllers.PovDirection
import org.slf4j.LoggerFactory
object Control {
enum class Type {
KEYBOARD, CONTROLLER
}
enum class Button {
UP, DOWN, LEFT, RIGHT, BUTTON0, BUTTON1, BUTTON2, BUTTON3
}
private val logger = LoggerFactory.getLogger(javaClass)
private val types = mutableSetOf<Type>(Type.KEYBOARD)
private var controller: Controller? = null
init {
val controllers = Controllers.getControllers()
if (controllers.size > 0) {
controller = controllers[0]
types.add(Type.CONTROLLER)
logger.info("Controller found: {}", controller?.name)
}
Controllers.addListener(object : ControllerAdapter() {
override fun connected(controller: Controller?) {
Control.controller = controller
types.add(Type.CONTROLLER)
logger.info("Controller connected: {}", Control.controller?.name)
}
override fun disconnected(controller: Controller?) {
Control.controller = null
types.remove(Type.CONTROLLER)
logger.info("Controller disconnected: {}", controller?.name)
}
})
}
fun avaiableTypes(): Set<Type> {
return types
}
fun pressed(): Set<Button> {
val controllerPressed = controllerButtons(*Button.values())
val keyboardPressed = keyboardButtons(*Button.values())
return controllerPressed union keyboardPressed
}
fun isPressed(vararg buttons: Button): Boolean {
val controllerPressed = buttons intersect controllerButtons(*buttons)
val keyboardPressed = buttons intersect keyboardButtons(*buttons)
return (controllerPressed union keyboardPressed).size == buttons.size
}
private fun controllerButtons(vararg buttons: Button): Set<Button> {
if (controller == null) {
return setOf()
}
val pressedButtons = mutableSetOf<Button>()
val direction = controller?.getPov(0)
pressedButtons.addAll(when (direction) {
PovDirection.center -> setOf()
PovDirection.east -> setOf(Button.RIGHT)
PovDirection.north -> setOf(Button.UP)
PovDirection.northEast -> setOf(Button.UP, Button.RIGHT)
PovDirection.northWest -> setOf(Button.UP, Button.LEFT)
PovDirection.south -> setOf(Button.DOWN)
PovDirection.southEast -> setOf(Button.DOWN, Button.RIGHT)
PovDirection.southWest -> setOf(Button.DOWN, Button.LEFT)
PovDirection.west -> setOf(Button.LEFT)
else -> setOf()
})
val axis0 = controller?.getAxis(0)
val axis1 = controller?.getAxis(1)
for (button in buttons) {
when (button) {
Button.LEFT -> if (axis0 != null && axis0 < -0.5) pressedButtons.add(button)
Button.RIGHT -> if (axis0 != null && axis0 > 0.5) pressedButtons.add(button)
Button.UP -> if (axis1 != null && axis1 < -0.5) pressedButtons.add(button)
Button.DOWN -> if (axis1 != null && axis1 > 0.5) pressedButtons.add(button)
else -> {
}
}
}
for (button in buttons) {
val buttonCode = when (button) {
Button.BUTTON0 -> 0
Button.BUTTON1 -> 1
Button.BUTTON2 -> 2
Button.BUTTON3 -> 3
else -> -1
}
if (controller?.getButton(buttonCode) ?: false) {
pressedButtons.add(button)
}
}
return pressedButtons
}
private fun keyboardButtons(vararg buttons: Button): Set<Button> {
val pressedButtons = mutableSetOf<Button>()
for (button in buttons) {
val keyCodes = when (button) {
Button.UP -> setOf(Input.Keys.W, Input.Keys.UP, Input.Keys.DPAD_UP)
Button.DOWN -> setOf(Input.Keys.S, Input.Keys.DOWN, Input.Keys.DPAD_DOWN)
Button.LEFT -> setOf(Input.Keys.A, Input.Keys.LEFT, Input.Keys.DPAD_LEFT)
Button.RIGHT -> setOf(Input.Keys.D, Input.Keys.RIGHT, Input.Keys.DPAD_RIGHT)
Button.BUTTON0 -> setOf(Input.Keys.SPACE, Input.Keys.DPAD_CENTER)
Button.BUTTON1 -> setOf(Input.Keys.SHIFT_LEFT)
Button.BUTTON2 -> setOf(Input.Keys.SHIFT_RIGHT)
Button.BUTTON3 -> setOf(Input.Keys.ENTER)
}
for (keyCode in keyCodes) {
if (Gdx.input.isKeyPressed(keyCode)) {
pressedButtons.add(button)
}
}
}
return pressedButtons
}
}
| mit | af854dce94225539a06199217ec68ec5 | 35.729927 | 92 | 0.588037 | 4.453097 | false | false | false | false |
handstandsam/ShoppingApp | app/src/main/java/com/handstandsam/shoppingapp/compose/Theme.kt | 1 | 3108 | package com.handstandsam.shoppingapp.compose
import androidx.compose.foundation.isSystemInDarkTheme
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Shapes
import androidx.compose.material.Typography
import androidx.compose.material.darkColors
import androidx.compose.material.lightColors
import androidx.compose.runtime.Composable
import androidx.compose.ui.text.font.Font
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.font.FontStyle
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import com.handstandsam.shoppingapp.R
private val appFontFamily = FontFamily(
fonts = listOf(
Font(
resId = R.font.roboto_black,
weight = FontWeight.W900,
style = FontStyle.Normal
),
Font(
resId = R.font.roboto_black_italic,
weight = FontWeight.W900,
style = FontStyle.Italic
),
Font(
resId = R.font.roboto_bold,
weight = FontWeight.W700,
style = FontStyle.Normal
)
)
)
private val defaultTypography = Typography()
val appTypography = Typography(
h1 = defaultTypography.h1.copy(fontFamily = appFontFamily),
h2 = defaultTypography.h2.copy(fontFamily = appFontFamily),
h3 = defaultTypography.h3.copy(fontFamily = appFontFamily),
h4 = defaultTypography.h4.copy(fontFamily = appFontFamily),
h5 = defaultTypography.h5.copy(fontFamily = appFontFamily),
h6 = defaultTypography.h6.copy(fontFamily = appFontFamily),
subtitle1 = defaultTypography.subtitle1.copy(fontFamily = appFontFamily),
subtitle2 = defaultTypography.subtitle2.copy(fontFamily = appFontFamily),
body1 = defaultTypography.body1.copy(fontFamily = appFontFamily),
body2 = defaultTypography.body2.copy(fontFamily = appFontFamily),
button = defaultTypography.button.copy(fontFamily = appFontFamily),
caption = defaultTypography.caption.copy(fontFamily = appFontFamily),
overline = defaultTypography.overline.copy(fontFamily = appFontFamily)
)
private val dark = darkColors(
// primary = purple200,
// primaryVariant = purple700,
// secondary = teal200
)
private val light = lightColors(
// background = Color.White,
// secondary = teal200,
// background = Color.LightGray
/* Other default colors to override
background = Color.White,
surface = Color.White,
onPrimary = Color.White,
onSecondary = Color.Black,
onBackground = Color.Black,
onSurface = Color.Black,
*/
)
val shapes = Shapes(
small = RoundedCornerShape(4.dp),
medium = RoundedCornerShape(4.dp),
large = RoundedCornerShape(0.dp)
)
@Composable
fun MyApplicationTheme(
isSystemInDarkTheme: Boolean = isSystemInDarkTheme(),
content: @Composable () -> Unit
) {
val colors = if (isSystemInDarkTheme) dark else light
MaterialTheme(
colors = colors,
typography = appTypography,
shapes = shapes,
content = content
)
} | apache-2.0 | fb57afbb996167e2af12c10ac760ba3a | 31.385417 | 77 | 0.712999 | 4.292818 | false | false | false | false |
googleads/googleads-mobile-android-examples | kotlin/admob/AppOpenExample/app/src/main/java/com/google/android/gms/example/appopenexample/MyApplication.kt | 1 | 8687 | package com.google.android.gms.example.appopenexample
import android.app.Activity
import android.app.Application
import android.content.Context
import android.os.Bundle
import android.util.Log
import android.widget.Toast
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleObserver
import androidx.lifecycle.OnLifecycleEvent
import androidx.lifecycle.ProcessLifecycleOwner
import androidx.multidex.MultiDexApplication
import com.google.android.gms.ads.AdError
import com.google.android.gms.ads.AdRequest
import com.google.android.gms.ads.FullScreenContentCallback
import com.google.android.gms.ads.LoadAdError
import com.google.android.gms.ads.MobileAds
import com.google.android.gms.ads.appopen.AppOpenAd
import com.google.android.gms.ads.appopen.AppOpenAd.AppOpenAdLoadCallback
import java.util.Date
private const val AD_UNIT_ID = "ca-app-pub-3940256099942544/3419835294"
private const val LOG_TAG = "MyApplication"
/** Application class that initializes, loads and show ads when activities change states. */
class MyApplication :
MultiDexApplication(), Application.ActivityLifecycleCallbacks, LifecycleObserver {
private lateinit var appOpenAdManager: AppOpenAdManager
private var currentActivity: Activity? = null
override fun onCreate() {
super.onCreate()
registerActivityLifecycleCallbacks(this)
// Log the Mobile Ads SDK version.
Log.d(LOG_TAG, "Google Mobile Ads SDK Version: " + MobileAds.getVersion())
MobileAds.initialize(this) {}
ProcessLifecycleOwner.get().lifecycle.addObserver(this)
appOpenAdManager = AppOpenAdManager()
}
/** LifecycleObserver method that shows the app open ad when the app moves to foreground. */
@OnLifecycleEvent(Lifecycle.Event.ON_START)
fun onMoveToForeground() {
// Show the ad (if available) when the app moves to foreground.
currentActivity?.let { appOpenAdManager.showAdIfAvailable(it) }
}
/** ActivityLifecycleCallback methods. */
override fun onActivityCreated(activity: Activity, savedInstanceState: Bundle?) {}
override fun onActivityStarted(activity: Activity) {
// An ad activity is started when an ad is showing, which could be AdActivity class from Google
// SDK or another activity class implemented by a third party mediation partner. Updating the
// currentActivity only when an ad is not showing will ensure it is not an ad activity, but the
// one that shows the ad.
if (!appOpenAdManager.isShowingAd) {
currentActivity = activity
}
}
override fun onActivityResumed(activity: Activity) {}
override fun onActivityPaused(activity: Activity) {}
override fun onActivityStopped(activity: Activity) {}
override fun onActivitySaveInstanceState(activity: Activity, outState: Bundle) {}
override fun onActivityDestroyed(activity: Activity) {}
/**
* Shows an app open ad.
*
* @param activity the activity that shows the app open ad
* @param onShowAdCompleteListener the listener to be notified when an app open ad is complete
*/
fun showAdIfAvailable(activity: Activity, onShowAdCompleteListener: OnShowAdCompleteListener) {
// We wrap the showAdIfAvailable to enforce that other classes only interact with MyApplication
// class.
appOpenAdManager.showAdIfAvailable(activity, onShowAdCompleteListener)
}
/**
* Interface definition for a callback to be invoked when an app open ad is complete (i.e.
* dismissed or fails to show).
*/
interface OnShowAdCompleteListener {
fun onShowAdComplete()
}
/** Inner class that loads and shows app open ads. */
private inner class AppOpenAdManager {
private var appOpenAd: AppOpenAd? = null
private var isLoadingAd = false
var isShowingAd = false
/** Keep track of the time an app open ad is loaded to ensure you don't show an expired ad. */
private var loadTime: Long = 0
/**
* Load an ad.
*
* @param context the context of the activity that loads the ad
*/
fun loadAd(context: Context) {
// Do not load ad if there is an unused ad or one is already loading.
if (isLoadingAd || isAdAvailable()) {
return
}
isLoadingAd = true
val request = AdRequest.Builder().build()
AppOpenAd.load(
context,
AD_UNIT_ID,
request,
AppOpenAd.APP_OPEN_AD_ORIENTATION_PORTRAIT,
object : AppOpenAdLoadCallback() {
/**
* Called when an app open ad has loaded.
*
* @param ad the loaded app open ad.
*/
override fun onAdLoaded(ad: AppOpenAd) {
appOpenAd = ad
isLoadingAd = false
loadTime = Date().time
Log.d(LOG_TAG, "onAdLoaded.")
Toast.makeText(context, "onAdLoaded", Toast.LENGTH_SHORT).show()
}
/**
* Called when an app open ad has failed to load.
*
* @param loadAdError the error.
*/
override fun onAdFailedToLoad(loadAdError: LoadAdError) {
isLoadingAd = false
Log.d(LOG_TAG, "onAdFailedToLoad: " + loadAdError.message)
Toast.makeText(context, "onAdFailedToLoad", Toast.LENGTH_SHORT).show()
}
}
)
}
/** Check if ad was loaded more than n hours ago. */
private fun wasLoadTimeLessThanNHoursAgo(numHours: Long): Boolean {
val dateDifference: Long = Date().time - loadTime
val numMilliSecondsPerHour: Long = 3600000
return dateDifference < numMilliSecondsPerHour * numHours
}
/** Check if ad exists and can be shown. */
private fun isAdAvailable(): Boolean {
// Ad references in the app open beta will time out after four hours, but this time limit
// may change in future beta versions. For details, see:
// https://support.google.com/admob/answer/9341964?hl=en
return appOpenAd != null && wasLoadTimeLessThanNHoursAgo(4)
}
/**
* Show the ad if one isn't already showing.
*
* @param activity the activity that shows the app open ad
*/
fun showAdIfAvailable(activity: Activity) {
showAdIfAvailable(
activity,
object : OnShowAdCompleteListener {
override fun onShowAdComplete() {
// Empty because the user will go back to the activity that shows the ad.
}
}
)
}
/**
* Show the ad if one isn't already showing.
*
* @param activity the activity that shows the app open ad
* @param onShowAdCompleteListener the listener to be notified when an app open ad is complete
*/
fun showAdIfAvailable(activity: Activity, onShowAdCompleteListener: OnShowAdCompleteListener) {
// If the app open ad is already showing, do not show the ad again.
if (isShowingAd) {
Log.d(LOG_TAG, "The app open ad is already showing.")
return
}
// If the app open ad is not available yet, invoke the callback then load the ad.
if (!isAdAvailable()) {
Log.d(LOG_TAG, "The app open ad is not ready yet.")
onShowAdCompleteListener.onShowAdComplete()
loadAd(activity)
return
}
Log.d(LOG_TAG, "Will show ad.")
appOpenAd!!.setFullScreenContentCallback(
object : FullScreenContentCallback() {
/** Called when full screen content is dismissed. */
override fun onAdDismissedFullScreenContent() {
// Set the reference to null so isAdAvailable() returns false.
appOpenAd = null
isShowingAd = false
Log.d(LOG_TAG, "onAdDismissedFullScreenContent.")
Toast.makeText(activity, "onAdDismissedFullScreenContent", Toast.LENGTH_SHORT).show()
onShowAdCompleteListener.onShowAdComplete()
loadAd(activity)
}
/** Called when fullscreen content failed to show. */
override fun onAdFailedToShowFullScreenContent(adError: AdError) {
appOpenAd = null
isShowingAd = false
Log.d(LOG_TAG, "onAdFailedToShowFullScreenContent: " + adError.message)
Toast.makeText(activity, "onAdFailedToShowFullScreenContent", Toast.LENGTH_SHORT).show()
onShowAdCompleteListener.onShowAdComplete()
loadAd(activity)
}
/** Called when fullscreen content is shown. */
override fun onAdShowedFullScreenContent() {
Log.d(LOG_TAG, "onAdShowedFullScreenContent.")
Toast.makeText(activity, "onAdShowedFullScreenContent", Toast.LENGTH_SHORT).show()
}
}
)
isShowingAd = true
appOpenAd!!.show(activity)
}
}
}
| apache-2.0 | 89aeaf82eeaafcc1840dda93b49dd51c | 35.045643 | 100 | 0.676643 | 4.515073 | false | false | false | false |
czyzby/ktx | tiled/src/test/kotlin/ktx/tiled/MapLayerTest.kt | 2 | 2194 | package ktx.tiled
import com.badlogic.gdx.maps.MapLayer
import com.badlogic.gdx.maps.MapLayers
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertNull
import org.junit.Assert.assertTrue
import org.junit.Test
class MapLayerTest {
private val mapLayer = MapLayer().apply {
properties.apply {
put("active", true)
put("customProperty", 123)
}
}
@Test
fun `should retrieve properties from MapLayer`() {
assertEquals(true, mapLayer.property<Boolean>("active"))
assertEquals(123, mapLayer.property<Int>("customProperty"))
}
@Test
fun `should retrieve properties from MapLayer with default value`() {
assertEquals(true, mapLayer.property("active", false))
assertEquals(123, mapLayer.property("customProperty", 0))
assertEquals(-1f, mapLayer.property("x", -1f))
}
@Test
fun `should retrieve properties from MapLayer without default value`() {
assertNull(mapLayer.propertyOrNull("x"))
assertEquals(123, mapLayer.propertyOrNull<Int>("customProperty"))
}
@Test
fun `should check if property from MapLayer exists`() {
assertTrue(mapLayer.containsProperty("active"))
assertFalse(mapLayer.containsProperty("x"))
}
@Test(expected = MissingPropertyException::class)
fun `should not retrieve non-existing property from MapLayer`() {
mapLayer.property<String>("non-existing")
}
@Test
fun `should return true when MapLayers is empty`() {
val actual = MapLayers()
assertTrue(actual.isEmpty())
}
@Test
fun `should return false when MapLayers is not empty`() {
val actual = MapLayers()
actual.add(MapLayer())
assertFalse(actual.isEmpty())
}
@Test
fun `should return true when MapLayers becomes empty`() {
val actual = MapLayers()
actual.add(MapLayer())
actual.remove(0)
assertTrue(actual.isEmpty())
}
@Test
fun `should return true when MapLayers is not empty`() {
val actual = MapLayers()
actual.add(MapLayer())
assertTrue(actual.isNotEmpty())
}
@Test
fun `should return false when MapLayers is empty`() {
val actual = MapLayers()
assertFalse(actual.isNotEmpty())
}
}
| cc0-1.0 | 18439f86930add2d0db68de432c705d1 | 24.218391 | 74 | 0.699635 | 4.108614 | false | true | false | false |
PropaFramework/Propa | src/main/kotlin/io/propa/framework/common/Delegates.kt | 1 | 1142 | package io.propa.framework.common
import com.github.snabbdom._get
import com.github.snabbdom._set
import kotlin.reflect.KProperty
/**
* Created by gbaldeck on 6/16/2017.
*/
class PropaAssignOnce<T>(val exceptionMsgGet: String? = null, val exceptionMsgSet: String? = null){
private var value: T? = null
operator fun getValue(thisRef: Any, property: KProperty<*>): T =
value ?: throwPropaException(exceptionMsgGet ?: "Property '${property.name}' in ${thisRef::class.simpleName} has not been set.")
operator fun setValue(thisRef: Any, property: KProperty<*>, value: T) =
if(this.value == null)
this.value = value
else
throwPropaException(exceptionMsgSet ?: "Property '${property.name}' in ${thisRef::class.simpleName} has already been set.")
}
class PropaDelegateProperty(val backingObj: () -> Any, val propertyName: String? = null){
operator fun getValue(thisRef: Any?, property: KProperty<*>): dynamic =
backingObj()._get(propertyName ?: property.name)
operator fun setValue(thisRef: Any?, property: KProperty<*>, value: dynamic) {
backingObj()._set(propertyName ?: property.name, value)
}
} | mit | 6a6dd91a0a4a22402c1e9b37bcef6423 | 37.1 | 132 | 0.711033 | 3.858108 | false | false | false | false |
heinika/MyGankio | app/src/main/java/lijin/heinika/cn/mygankio/parser/ULParser.kt | 1 | 2434 | package lijin.heinika.cn.mygankio.parser
import android.annotation.SuppressLint
import android.content.Context
import android.text.SpannableString
import android.text.method.LinkMovementMethod
import android.util.Log
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.TextView
import com.bumptech.glide.Glide
import org.jsoup.Jsoup
import org.jsoup.helper.StringUtil
import org.jsoup.nodes.Document
import org.jsoup.nodes.Element
import org.jsoup.nodes.Node
import java.util.ArrayList
import lijin.heinika.cn.mygankio.utils.SpanUtils
/**
* Created by yun on 2017/9/16.
* ul解析
*/
class ULParser : BaseParser() {
private val TAG = ULParser::class.java.simpleName
@SuppressLint("SetTextI18n")
override fun parse(node: Node, context: Context): List<View>? {
val lists = ArrayList<View>()
Log.i(TAG, "parse: " + node.toString())
for (n in node.childNodes()) {
val content = StringBuilder()
var html = ""
var src = ""
val document = Jsoup.parse(n.toString())
if (document.getElementsByTag("li").size != 0) {
val a = document.getElementsByTag("a")[0]
content.append(a.text()).append("\n")
html = a.attr("href")
Log.i(TAG, "html:$html")
if (document.getElementsByTag("img").size != 0) {
val img = document.getElementsByTag("img")[0]
src = img.attr("src")
Log.i(TAG, "src:$src")
}
}
if (!StringUtil.isBlank(content.toString())) {
val textView = TextView(context)
val spannableString = SpanUtils.getULSpannableString(content.toString(), html)
textView.text = spannableString
textView.movementMethod = LinkMovementMethod.getInstance()
lists.add(textView)
if (!StringUtil.isBlank(src)) {
val imageView = ImageView(context)
imageView.layoutParams = LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)
Glide.with(context).load(src).into(imageView)
lists.add(imageView)
}
}
}
return lists
}
}
| apache-2.0 | 7097a2d9a439275c4e94a3836a8d8fd9 | 33.714286 | 144 | 0.609465 | 4.5 | false | false | false | false |
docker-client/docker-compose-v3 | src/main/kotlin/de/gesellix/docker/compose/adapters/MapOrListToLabelAdapter.kt | 1 | 1909 | package de.gesellix.docker.compose.adapters
import com.squareup.moshi.FromJson
import com.squareup.moshi.JsonReader
import com.squareup.moshi.ToJson
import de.gesellix.docker.compose.types.Labels
class MapOrListToLabelAdapter {
@ToJson
fun toJson(@LabelsType labels: Labels): Map<String, String> {
throw UnsupportedOperationException()
}
@FromJson
@LabelsType
fun fromJson(reader: JsonReader): Labels {
val labels = Labels()
when (reader.peek()) {
JsonReader.Token.BEGIN_ARRAY -> {
reader.beginArray()
while (reader.peek() != JsonReader.Token.END_ARRAY) {
val entry = reader.nextString()
val keyAndValue = entry.split(Regex("="), 2)
labels.entries[keyAndValue[0]] = if (keyAndValue.size > 1) keyAndValue[1] else ""
}
reader.endArray()
}
JsonReader.Token.BEGIN_OBJECT -> {
reader.beginObject()
while (reader.peek() != JsonReader.Token.END_OBJECT) {
val name = reader.nextName()
val value: String? = if (reader.peek() == JsonReader.Token.NULL) {
reader.nextNull()
} else if (reader.peek() == JsonReader.Token.NUMBER) {
val d = reader.nextDouble()
if ((d % 1) == 0.0) {
d.toInt().toString()
} else {
d.toString()
}
} else {
reader.nextString()
}
labels.entries[name] = value ?: ""
}
reader.endObject()
}
else -> {
// ...
}
}
return labels
}
}
| mit | 8bac058d809b88947b0f37178444c29f | 33.709091 | 101 | 0.467784 | 5.023684 | false | false | false | false |
fredyw/leetcode | src/main/kotlin/leetcode/Problem2085.kt | 1 | 696 | package leetcode
/**
* https://leetcode.com/problems/count-common-words-with-one-occurrence/
*/
class Problem2085 {
fun countWords(words1: Array<String>, words2: Array<String>): Int {
val map1 = mutableMapOf<String, Int>()
words1.forEach { map1[it] = (map1[it] ?: 0) + 1 }
val map2 = mutableMapOf<String, Int>()
words2.forEach { map2[it] = (map2[it] ?: 0) + 1 }
var answer = 0
for ((key1, count1) in map1) {
if (count1 > 1) {
continue
}
val count2 = map2[key1]
if (count2 != null && count2 == 1) {
answer++
}
}
return answer
}
}
| mit | 29c8a4b7c9d5692c3d59b54f37d925f8 | 28 | 72 | 0.5 | 3.497487 | false | false | false | false |
kvakil/venus | src/main/kotlin/venus/riscv/insts/srai.kt | 1 | 256 | package venus.riscv.insts
import venus.riscv.insts.dsl.ShiftImmediateInstruction
val srai = ShiftImmediateInstruction(
name = "srai",
funct3 = 0b101,
funct7 = 0b0100000,
eval32 = { a, b -> if (b == 0) a else (a shr b) }
)
| mit | bf85e264a589fa49603964a0444d0592 | 24.6 | 57 | 0.621094 | 3.121951 | false | false | false | false |
prt2121/android-workspace | Everywhere/app/src/main/kotlin/com/prt2121/everywhere/MainActivity.kt | 1 | 2834 | package com.prt2121.everywhere
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.view.Window
import android.webkit.WebView
import android.webkit.WebViewClient
import net.smartam.leeloo.client.OAuthClient
import net.smartam.leeloo.client.URLConnectionClient
import net.smartam.leeloo.client.request.OAuthClientRequest
import net.smartam.leeloo.common.exception.OAuthSystemException
import net.smartam.leeloo.common.message.types.GrantType
import org.jetbrains.anko.async
/**
* Created by pt2121 on 1/17/16.
*/
class MainActivity : BaseActivity() {
val CONSUMER_KEY by lazy { getString(R.string.consumer_key) }
val CONSUMER_SECRET by lazy { getString(R.string.consumer_secret) }
override fun onCreate(savedInstanceState: Bundle?) {
requestWindowFeature(Window.FEATURE_NO_TITLE)
super.onCreate(savedInstanceState)
val webView = WebView(this)
webView.setWebViewClient(LoginWebViewClient())
setContentView(webView)
webView.settings.javaScriptEnabled = true
try {
val request = OAuthClientRequest
.authorizationLocation(AUTH_URL)
.setClientId(CONSUMER_KEY)
.setRedirectURI(REDIRECT_URI)
.buildQueryMessage()
webView.loadUrl("${request.locationUri}&response_type=code&set_mobile=on")
} catch (e: OAuthSystemException) {
println("OAuth request failed ${e.message}")
}
}
inner class LoginWebViewClient : WebViewClient() {
override fun shouldOverrideUrlLoading(view: WebView?, url: String?): Boolean {
val uri = Uri.parse(url)
val code = uri.getQueryParameter("code")
val error = uri.getQueryParameter("error")
if (code != null) {
val request = OAuthClientRequest.tokenLocation(TOKEN_URL)
.setGrantType(GrantType.AUTHORIZATION_CODE)
.setClientId(CONSUMER_KEY)
.setClientSecret(CONSUMER_SECRET)
.setRedirectURI(REDIRECT_URI)
.setCode(code)
.buildBodyMessage()
val oAuthClient = OAuthClient(URLConnectionClient())
async() {
val response = oAuthClient.accessToken(request)
TokenStorage(this@MainActivity).save(response.accessToken)
runOnUiThread {
val intent = Intent(this@MainActivity, GroupActivity::class.java)
intent.putExtra(ACCESS_EXTRA, response.accessToken)
startActivity(intent)
finish()
}
}
} else if (error != null) {
println("error $error")
}
return false
}
}
companion object {
const val AUTH_URL = "https://secure.meetup.com/oauth2/authorize"
const val TOKEN_URL = "https://secure.meetup.com/oauth2/access"
const val REDIRECT_URI = "http://prt2121.github.io"
const val ACCESS_EXTRA = "access_token"
}
} | apache-2.0 | 8ae59e7568dc90cf9af63c97f7b4e4e9 | 32.75 | 82 | 0.689485 | 4.236173 | false | false | false | false |
kevinhinterlong/archwiki-viewer | app/src/main/java/com/jtmcn/archwiki/viewer/MainActivity.kt | 2 | 5317 | package com.jtmcn.archwiki.viewer
import android.app.SearchManager
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.view.Menu
import android.view.MenuItem
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.widget.SearchView
import com.jtmcn.archwiki.viewer.data.SearchResult
import com.jtmcn.archwiki.viewer.data.getSearchQuery
import com.jtmcn.archwiki.viewer.tasks.Fetch
import com.jtmcn.archwiki.viewer.utils.getTextZoom
import kotlinx.android.synthetic.main.activity_main.*
import kotlinx.android.synthetic.main.toolbar.*
import timber.log.Timber
import java.util.*
class MainActivity : AppCompatActivity() {
private lateinit var searchView: SearchView
private lateinit var searchMenuItem: MenuItem
private var currentSuggestions: List<SearchResult>? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
setSupportActionBar(toolbar)
wikiViewer.buildView(progressBar, supportActionBar)
handleIntent(intent)
}
override fun onResume() {
super.onResume()
updateWebSettings()
}
override fun onNewIntent(intent: Intent) {
super.onNewIntent(intent)
handleIntent(intent)
}
private fun handleIntent(intent: Intent?) {
if (intent == null) {
return
}
if (Intent.ACTION_SEARCH == intent.action) {
val query = intent.getStringExtra(SearchManager.QUERY)
wikiViewer.passSearch(query!!)
hideSearchView()
} else if (Intent.ACTION_VIEW == intent.action) {
val url = intent.dataString
wikiViewer.wikiClient.shouldOverrideUrlLoading(wikiViewer, url!!)
}
}
/**
* Update the font size used in the webview.
*/
private fun updateWebSettings() {
wikiViewer.settings.textZoom = getTextZoom(this)
}
override fun onPrepareOptionsMenu(menu: Menu): Boolean {
val searchManager = getSystemService(Context.SEARCH_SERVICE) as SearchManager
searchMenuItem = menu.findItem(R.id.menu_search)
searchView = searchMenuItem.actionView as SearchView
searchView.setOnQueryTextFocusChangeListener { _, hasFocus ->
if (!hasFocus) {
hideSearchView()
}
}
searchView.setSearchableInfo(searchManager.getSearchableInfo(componentName))
searchView.setOnQueryTextListener(object : SearchView.OnQueryTextListener {
override fun onQueryTextSubmit(query: String): Boolean {
wikiViewer.passSearch(query)
return false
}
override fun onQueryTextChange(newText: String): Boolean {
if (newText.isEmpty()) {
setCursorAdapter(ArrayList())
return true
} else {
val searchUrl = getSearchQuery(newText)
Fetch.search({
currentSuggestions = it
setCursorAdapter(currentSuggestions)
}, searchUrl)
return true
}
}
})
searchView.setOnSuggestionListener(object : SearchView.OnSuggestionListener {
override fun onSuggestionSelect(position: Int): Boolean {
return false
}
override fun onSuggestionClick(position: Int): Boolean {
val (pageName, pageURL) = currentSuggestions!![position]
Timber.d("Opening '$pageName' from search suggestion.")
wikiViewer.wikiClient.shouldOverrideUrlLoading(wikiViewer, pageURL)
hideSearchView()
return true
}
})
return true
}
private fun hideSearchView() {
searchMenuItem.collapseActionView()
wikiViewer.requestFocus() //pass control back to the wikiview
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
val inflater = menuInflater
inflater.inflate(R.menu.menu, menu)
return true
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
R.id.menu_share -> {
val wikiPage = wikiViewer.currentWebPage
if (wikiPage != null) {
val sharingIntent = Intent()
sharingIntent.type = TEXT_PLAIN_MIME
sharingIntent.action = Intent.ACTION_SEND
sharingIntent.putExtra(Intent.EXTRA_TITLE, wikiPage.pageTitle)
sharingIntent.putExtra(Intent.EXTRA_TEXT, wikiPage.pageUrl)
startActivity(Intent.createChooser(sharingIntent, null))
}
}
R.id.refresh -> wikiViewer.onRefresh()
R.id.menu_settings -> startActivity(Intent(this, PreferencesActivity::class.java))
R.id.exit -> finish()
}
return super.onOptionsItemSelected(item)
}
private fun setCursorAdapter(currentSuggestions: List<SearchResult>?) {
searchView.suggestionsAdapter = SearchResultsAdapter.getCursorAdapter(this, currentSuggestions!!)
}
} | apache-2.0 | 10626d88d77246b97271674ddab32f69 | 34.691275 | 105 | 0.630055 | 5.327655 | false | false | false | false |
Maccimo/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/branchedTransformations/IfThenToElvisInspection.kt | 2 | 5745 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.kotlin.idea.inspections.branchedTransformations
import com.intellij.codeInspection.ProblemHighlightType
import com.intellij.codeInspection.ui.MultipleCheckboxOptionsPanel
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import org.jetbrains.kotlin.KtNodeTypes
import org.jetbrains.kotlin.builtins.KotlinBuiltIns
import org.jetbrains.kotlin.idea.KotlinBundle
import org.jetbrains.kotlin.idea.caches.resolve.analyze
import org.jetbrains.kotlin.idea.base.psi.replaced
import org.jetbrains.kotlin.idea.formatter.rightMarginOrDefault
import org.jetbrains.kotlin.idea.inspections.AbstractApplicabilityBasedInspection
import org.jetbrains.kotlin.idea.intentions.branchedTransformations.*
import org.jetbrains.kotlin.idea.util.CommentSaver
import org.jetbrains.kotlin.idea.util.application.runWriteAction
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.resolve.bindingContextUtil.isUsedAsExpression
import org.jetbrains.kotlin.resolve.calls.util.getType
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
import javax.swing.JComponent
class IfThenToElvisInspection @JvmOverloads constructor(
@JvmField var highlightStatement: Boolean = false,
private val inlineWithPrompt: Boolean = true
) : AbstractApplicabilityBasedInspection<KtIfExpression>(KtIfExpression::class.java) {
override fun inspectionText(element: KtIfExpression): String = KotlinBundle.message("if.then.foldable.to")
override val defaultFixText: String get() = INTENTION_TEXT
override fun isApplicable(element: KtIfExpression): Boolean = isApplicableTo(element, expressionShouldBeStable = true)
override fun inspectionHighlightType(element: KtIfExpression): ProblemHighlightType =
if (element.shouldBeTransformed() && (highlightStatement || element.isUsedAsExpression(element.analyze(BodyResolveMode.PARTIAL_WITH_CFA))))
super.inspectionHighlightType(element)
else
ProblemHighlightType.INFORMATION
override fun applyTo(element: KtIfExpression, project: Project, editor: Editor?) {
convert(element, editor, inlineWithPrompt)
}
override fun inspectionHighlightRangeInElement(element: KtIfExpression) = element.fromIfKeywordToRightParenthesisTextRangeInThis()
override fun createOptionsPanel(): JComponent = MultipleCheckboxOptionsPanel(this).also {
it.addCheckbox(KotlinBundle.message("report.also.on.statement"), "highlightStatement")
}
companion object {
val INTENTION_TEXT get() = KotlinBundle.message("replace.if.expression.with.elvis.expression")
fun convert(element: KtIfExpression, editor: Editor?, inlineWithPrompt: Boolean) {
val ifThenToSelectData = element.buildSelectTransformationData() ?: return
val factory = KtPsiFactory(element)
val commentSaver = CommentSaver(element, saveLineBreaks = false)
val margin = element.containingKtFile.rightMarginOrDefault
val elvis = runWriteAction {
val replacedBaseClause = ifThenToSelectData.replacedBaseClause(factory)
val negatedClause = ifThenToSelectData.negatedClause!!
val newExpr = element.replaced(
factory.createExpressionByPattern(
elvisPattern(replacedBaseClause.textLength + negatedClause.textLength + 5 >= margin),
replacedBaseClause,
negatedClause
)
)
(KtPsiUtil.deparenthesize(newExpr) as KtBinaryExpression).also {
commentSaver.restore(it)
}
}
if (editor != null) {
elvis.inlineLeftSideIfApplicable(editor, inlineWithPrompt)
with(IfThenToSafeAccessInspection) {
(elvis.left as? KtSafeQualifiedExpression)?.renameLetParameter(editor)
}
}
}
fun isApplicableTo(element: KtIfExpression, expressionShouldBeStable: Boolean): Boolean {
val ifThenToSelectData = element.buildSelectTransformationData() ?: return false
if (expressionShouldBeStable &&
!ifThenToSelectData.receiverExpression.isStableSimpleExpression(ifThenToSelectData.context)
) return false
val type = element.getType(ifThenToSelectData.context) ?: return false
if (KotlinBuiltIns.isUnit(type)) return false
return ifThenToSelectData.clausesReplaceableByElvis()
}
private fun KtExpression.isNullOrBlockExpression(): Boolean {
val innerExpression = this.unwrapBlockOrParenthesis()
return innerExpression is KtBlockExpression || innerExpression.node.elementType == KtNodeTypes.NULL
}
private fun IfThenToSelectData.clausesReplaceableByElvis(): Boolean =
when {
baseClause == null || negatedClause == null || negatedClause.isNullOrBlockExpression() ->
false
negatedClause is KtThrowExpression && negatedClause.throwsNullPointerExceptionWithNoArguments() ->
false
baseClause.evaluatesTo(receiverExpression) ->
true
baseClause.anyArgumentEvaluatesTo(receiverExpression) ->
true
hasImplicitReceiverReplaceableBySafeCall() || baseClause.hasFirstReceiverOf(receiverExpression) ->
!baseClause.hasNullableType(context)
else ->
false
}
}
}
| apache-2.0 | 9587f1685888ddc8a0ebbbd9670db0da | 47.686441 | 147 | 0.704091 | 5.58309 | false | false | false | false |
gonzalonm/sample-my-shopping | data/src/main/kotlin/com/lalosoft/myshopping/data/repository/CloudItemRepository.kt | 1 | 1163 | package com.lalosoft.myshopping.data.repository
import com.lalosoft.myshopping.domain.Item
import com.lalosoft.myshopping.domain.repository.ItemDataCallback
import com.lalosoft.myshopping.domain.repository.ItemRepository
import org.json.JSONObject
class CloudItemRepository : BaseCloudRepository(), ItemRepository {
val ITEMS_URL = "$HOST/items"
override fun getAllItems(userId: String, callback: ItemDataCallback) {
val url = ITEMS_URL + "/" + userId
api.doGetRequest(url, { apiResponse ->
if (apiResponse.success) {
callback.retrieveItemsSuccess(convertToList(apiResponse.content))
} else {
callback.retrieveItemsFailure()
}
})
}
private fun convertToList(content: String?): List<Item> {
val list = arrayListOf<Item>()
val json = JSONObject(content)
val jsonArray = json.getJSONArray("items")
var pos = 0
while (pos < jsonArray.length()) {
val jsonItem = jsonArray.getJSONObject(pos)
list.add(Item.fromJson(jsonItem.toString()))
pos++
}
return list
}
} | apache-2.0 | 379ac37853d0b3a43c3e0d59abacf7ee | 32.257143 | 81 | 0.644884 | 4.633466 | false | false | false | false |
JetBrains/ideavim | src/main/java/com/maddyhome/idea/vim/helper/CommandLineHelper.kt | 1 | 2882 | /*
* Copyright 2003-2022 The IdeaVim authors
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE.txt file or at
* https://opensource.org/licenses/MIT.
*/
package com.maddyhome.idea.vim.helper
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.components.Service
import com.maddyhome.idea.vim.action.change.Extension
import com.maddyhome.idea.vim.api.VimEditor
import com.maddyhome.idea.vim.newapi.ij
import com.maddyhome.idea.vim.newapi.vim
import com.maddyhome.idea.vim.ui.ModalEntry
import com.maddyhome.idea.vim.ui.ex.ExEntryPanel
import java.awt.event.KeyEvent
import javax.swing.KeyStroke
@Service
class CommandLineHelper : VimCommandLineHelper {
override fun inputString(vimEditor: VimEditor, prompt: String, finishOn: Char?): String? {
val editor = vimEditor.ij
if (vimEditor.vimStateMachine.isDotRepeatInProgress) {
val input = Extension.consumeString()
return input ?: error("Not enough strings saved: ${Extension.lastExtensionHandler}")
}
if (ApplicationManager.getApplication().isUnitTestMode) {
val builder = StringBuilder()
val inputModel = TestInputModel.getInstance(editor)
var key: KeyStroke? = inputModel.nextKeyStroke()
while (key != null &&
!key.isCloseKeyStroke() && key.keyCode != KeyEvent.VK_ENTER &&
(finishOn == null || key.keyChar != finishOn)
) {
val c = key.keyChar
if (c != KeyEvent.CHAR_UNDEFINED) {
builder.append(c)
}
key = inputModel.nextKeyStroke()
}
if (finishOn != null && key != null && key.keyChar == finishOn) {
builder.append(key.keyChar)
}
Extension.addString(builder.toString())
return builder.toString()
} else {
var text: String? = null
// XXX: The Ex entry panel is used only for UI here, its logic might be inappropriate for input()
val exEntryPanel = ExEntryPanel.getInstanceWithoutShortcuts()
exEntryPanel.activate(editor, EditorDataContext.init(editor), prompt.ifEmpty { " " }, "", 1)
ModalEntry.activate(editor.vim) { key: KeyStroke ->
return@activate when {
key.isCloseKeyStroke() -> {
exEntryPanel.deactivate(true)
false
}
key.keyCode == KeyEvent.VK_ENTER -> {
text = exEntryPanel.text
exEntryPanel.deactivate(true)
false
}
finishOn != null && key.keyChar == finishOn -> {
exEntryPanel.handleKey(key)
text = exEntryPanel.text
exEntryPanel.deactivate(true)
false
}
else -> {
exEntryPanel.handleKey(key)
true
}
}
}
if (text != null) {
Extension.addString(text!!)
}
return text
}
}
}
| mit | df7a35292ed3eb91a92e4c1f4b506f85 | 32.905882 | 103 | 0.64018 | 4.201166 | false | false | false | false |
fengzhizi715/SAF-Kotlin-Utils | saf-kotlin-utils/src/main/java/com/safframework/utils/AppUtils.kt | 1 | 5406 | package com.safframework.utils
import android.app.ActivityManager
import android.app.ActivityManager.MemoryInfo
import android.app.ActivityManager.RunningAppProcessInfo
import android.content.Context
import android.content.pm.PackageManager
import android.util.Log
import com.safframework.tony.common.reflect.Reflect
import java.lang.reflect.InvocationTargetException
/**
* Created by tony on 2017/2/26.
*/
private var mContext: Context? = null
/**
* 获取全局的context,也就是Application Context
* @return
*/
fun getApplicationContext(): Context? {
if (mContext == null) {
mContext = Reflect.on("android.app.ActivityThread").call("currentApplication").get()
}
return mContext
}
/**
* 获取手机系统SDK版本
*
* @return
*/
fun getSDKVersion(): Int = android.os.Build.VERSION.SDK_INT
/**
* 是否Dalvik模式
*
* @return 结果
*/
fun isDalvik(): Boolean = "Dalvik" == getCurrentRuntimeValue()
/**
* 是否ART模式
*
* @return 结果
*/
fun isART(): Boolean {
val currentRuntime = getCurrentRuntimeValue()
return "ART" == currentRuntime || "ART debug build" == currentRuntime
}
/**
* 获取手机当前的Runtime
*
* @return 正常情况下可能取值Dalvik, ART, ART debug build;
*/
fun getCurrentRuntimeValue(): String {
try {
val systemProperties = Class.forName("android.os.SystemProperties")
try {
val get = systemProperties.getMethod("get",
String::class.java, String::class.java) ?: return "WTF?!"
try {
val value = get.invoke(
systemProperties, "persist.sys.dalvik.vm.lib",
/* Assuming default is */"Dalvik") as String
if ("libdvm.so" == value) {
return "Dalvik"
} else if ("libart.so" == value) {
return "ART"
} else if ("libartd.so" == value) {
return "ART debug build"
}
return value
} catch (e: IllegalAccessException) {
return "IllegalAccessException"
} catch (e: IllegalArgumentException) {
return "IllegalArgumentException"
} catch (e: InvocationTargetException) {
return "InvocationTargetException"
}
} catch (e: NoSuchMethodException) {
return "SystemProperties.get(String key, String def) method is not found"
}
} catch (e: ClassNotFoundException) {
return "SystemProperties class is not found"
}
}
/**
* 获取设备的可用内存大小,单位是M
*
* @param context 应用上下文对象context
* @return 当前内存大小
*/
fun getDeviceUsableMemory(context: Context): Long {
val am = context.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
val mi = MemoryInfo()
am.getMemoryInfo(mi)
// 返回当前系统的可用内存
return mi.availMem / (1024 * 1024)
}
/**
* 清理后台进程与服务
* @param context 应用上下文对象context
*
* @return 被清理的数量
*/
fun gc(context: Context): Int {
val i = getDeviceUsableMemory(context)
var count = 0 // 清理掉的进程数
val am = context
.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
// 获取正在运行的service列表
val serviceList = am.getRunningServices(100)
if (serviceList != null)
for (service in serviceList) {
if (service.pid === android.os.Process.myPid())
continue
try {
android.os.Process.killProcess(service.pid)
count++
} catch (e: Exception) {
e.message
}
}
// 获取正在运行的进程列表
val processList = am.runningAppProcesses
if (processList != null)
for (process in processList) {
// 一般数值大于RunningAppProcessInfo.IMPORTANCE_SERVICE的进程都长时间没用或者空进程了
// 一般数值大于RunningAppProcessInfo.IMPORTANCE_VISIBLE的进程都是非可见进程,也就是在后台运行着
if (process.importance > RunningAppProcessInfo.IMPORTANCE_VISIBLE) {
// pkgList 得到该进程下运行的包名
val pkgList = process.pkgList
for (pkgName in pkgList) {
Log.d("AppUtils", "======正在杀死包名:" + pkgName)
try {
am.killBackgroundProcesses(pkgName)
count++
} catch (e: Exception) { // 防止意外发生
e.message
}
}
}
}
Log.d("AppUtils", "清理了" + (getDeviceUsableMemory(context) - i) + "M内存")
return count
}
/**
* 检查某个权限是否开启
*
* @param permission
* @return true or false
*/
fun checkPermission(context: Context, permission: String): Boolean {
if (!isMOrHigher()) {
val localPackageManager = context.applicationContext.packageManager
return localPackageManager.checkPermission(permission, context.applicationContext.packageName) == PackageManager.PERMISSION_GRANTED
} else {
return context.checkSelfPermission(permission) == PackageManager.PERMISSION_GRANTED
}
}
| apache-2.0 | 7a3422dc84635a6c4e89eccc837599e7 | 26.15847 | 139 | 0.600201 | 4.211864 | false | false | false | false |
kelsos/mbrc | app/src/main/kotlin/com/kelsos/mbrc/utilities/RemoteViewIntentBuilder.kt | 1 | 2566 | package com.kelsos.mbrc.utilities
import android.app.PendingIntent
import android.app.PendingIntent.FLAG_UPDATE_CURRENT
import android.content.Context
import android.content.Intent
import androidx.annotation.IntDef
import com.kelsos.mbrc.ui.navigation.main.MainActivity
object RemoteViewIntentBuilder {
const val REMOTE_PLAY_PRESSED = "com.kelsos.mbrc.notification.play"
const val REMOTE_NEXT_PRESSED = "com.kelsos.mbrc.notification.next"
const val REMOTE_CLOSE_PRESSED = "com.kelsos.mbrc.notification.close"
const val REMOTE_PREVIOUS_PRESSED = "com.kelsos.mbrc.notification.previous"
const val CANCELLED_NOTIFICATION = "com.kelsos.mbrc.notification.cancel"
const val OPEN = 0
const val PLAY = 1
const val NEXT = 2
const val CLOSE = 3
const val PREVIOUS = 4
const val CANCEL = 5
fun getPendingIntent(@ButtonAction id: Int, mContext: Context): PendingIntent {
when (id) {
OPEN -> {
val notificationIntent = Intent(mContext, MainActivity::class.java)
return PendingIntent.getActivity(
mContext,
0,
notificationIntent,
FLAG_UPDATE_CURRENT
)
}
PLAY -> {
val playPressedIntent = Intent(REMOTE_PLAY_PRESSED)
return PendingIntent.getBroadcast(
mContext,
1,
playPressedIntent,
FLAG_UPDATE_CURRENT
)
}
NEXT -> {
val mediaNextButtonIntent = Intent(REMOTE_NEXT_PRESSED)
return PendingIntent.getBroadcast(
mContext,
2,
mediaNextButtonIntent,
FLAG_UPDATE_CURRENT
)
}
CLOSE -> {
val clearNotificationIntent = Intent(REMOTE_CLOSE_PRESSED)
return PendingIntent.getBroadcast(
mContext,
3,
clearNotificationIntent,
FLAG_UPDATE_CURRENT
)
}
PREVIOUS -> {
val mediaPreviousButtonIntent = Intent(REMOTE_PREVIOUS_PRESSED)
return PendingIntent.getBroadcast(
mContext,
4,
mediaPreviousButtonIntent,
FLAG_UPDATE_CURRENT
)
}
CANCEL -> {
val cancelIntent = Intent(CANCELLED_NOTIFICATION)
return PendingIntent.getBroadcast(
mContext,
4,
cancelIntent,
FLAG_UPDATE_CURRENT
)
}
else -> throw IndexOutOfBoundsException()
}
}
@IntDef(
OPEN,
PLAY,
CLOSE,
PREVIOUS,
NEXT,
CANCEL
)
@kotlin.annotation.Retention(AnnotationRetention.SOURCE)
annotation class ButtonAction
}
| gpl-3.0 | a00363bdf0385a9413af3ab82b67f78b | 26.591398 | 81 | 0.636399 | 4.691042 | false | false | false | false |
micolous/metrodroid | src/main/java/au/id/micolous/metrodroid/ui/TabPagerAdapter.kt | 1 | 2964 | /*
* TabPagerAdapter.kt
*
* Copyright (C) 2011 Eric Butler <eric@codebutler.com>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package au.id.micolous.metrodroid.ui
import android.annotation.SuppressLint
import android.os.Bundle
import android.os.Parcelable
import android.view.View
import androidx.appcompat.app.AppCompatActivity
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentPagerAdapter
import androidx.fragment.app.FragmentTransaction
import androidx.viewpager.widget.ViewPager
import au.id.micolous.metrodroid.multi.Localizer
class TabPagerAdapter(private val mActivity: AppCompatActivity, private val mViewPager: ViewPager) : FragmentPagerAdapter(mActivity.supportFragmentManager) {
private val mTabs = ArrayList<TabInfo>()
private var mCurTransaction: FragmentTransaction? = null
init {
mViewPager.adapter = this
}
fun addTab(nameResource: Int, clss: Class<*>, args: Bundle?) {
val info = TabInfo(clss, args, Localizer.localizeString(nameResource))
mTabs.add(info)
notifyDataSetChanged()
}
override fun getCount(): Int = mTabs.size
override fun startUpdate(view: View) {}
override fun getItem(p0: Int): Fragment {
val info = mTabs[p0]
return Fragment.instantiate(mActivity, info.mClass.name, info.mArgs)
}
override fun getPageTitle(p0: Int): CharSequence = mTabs[p0].mName
@SuppressLint("CommitTransaction")
override fun destroyItem(view: View, i: Int, obj: Any) {
if (mCurTransaction == null) {
mCurTransaction = mActivity.supportFragmentManager.beginTransaction()
}
mCurTransaction!!.hide(obj as Fragment)
}
override fun finishUpdate(view: View) {
if (mCurTransaction != null) {
mCurTransaction?.commitAllowingStateLoss()
mCurTransaction = null
mActivity.supportFragmentManager.executePendingTransactions()
}
}
override fun isViewFromObject(view: View, obj: Any): Boolean {
return (obj as Fragment).view === view
}
override fun saveState(): Parcelable? = null
override fun restoreState(parcelable: Parcelable?, classLoader: ClassLoader?) {}
private class TabInfo internal constructor(internal val mClass: Class<*>, internal val mArgs: Bundle?, internal val mName: String)
}
| gpl-3.0 | a2898abe933137c73769979db4322dfd | 34.710843 | 157 | 0.720985 | 4.574074 | false | false | false | false |
android/nowinandroid | feature/foryou/src/main/java/com/google/samples/apps/nowinandroid/feature/foryou/ForYouScreen.kt | 1 | 20090 | /*
* Copyright 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.samples.apps.nowinandroid.feature.foryou
import android.app.Activity
import androidx.compose.animation.AnimatedVisibility
import androidx.compose.animation.fadeIn
import androidx.compose.animation.fadeOut
import androidx.compose.animation.slideInVertically
import androidx.compose.animation.slideOutVertically
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.BoxWithConstraints
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.WindowInsets
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.heightIn
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.safeDrawing
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.layout.windowInsetsBottomHeight
import androidx.compose.foundation.lazy.LazyListScope
import androidx.compose.foundation.lazy.grid.GridCells
import androidx.compose.foundation.lazy.grid.GridCells.Adaptive
import androidx.compose.foundation.lazy.grid.GridItemSpan
import androidx.compose.foundation.lazy.grid.LazyGridScope
import androidx.compose.foundation.lazy.grid.LazyHorizontalGrid
import androidx.compose.foundation.lazy.grid.LazyVerticalGrid
import androidx.compose.foundation.lazy.grid.items
import androidx.compose.foundation.lazy.grid.rememberLazyGridState
import androidx.compose.foundation.shape.CornerSize
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.ColorFilter
import androidx.compose.ui.layout.layout
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.platform.LocalView
import androidx.compose.ui.platform.testTag
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.max
import androidx.compose.ui.unit.sp
import androidx.compose.ui.util.trace
import androidx.core.view.doOnPreDraw
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.lifecycle.compose.ExperimentalLifecycleComposeApi
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import coil.compose.AsyncImage
import com.google.samples.apps.nowinandroid.core.designsystem.component.NiaFilledButton
import com.google.samples.apps.nowinandroid.core.designsystem.component.NiaOverlayLoadingWheel
import com.google.samples.apps.nowinandroid.core.designsystem.component.NiaToggleButton
import com.google.samples.apps.nowinandroid.core.designsystem.icon.NiaIcons
import com.google.samples.apps.nowinandroid.core.designsystem.theme.NiaTheme
import com.google.samples.apps.nowinandroid.core.domain.model.FollowableAuthor
import com.google.samples.apps.nowinandroid.core.domain.model.FollowableTopic
import com.google.samples.apps.nowinandroid.core.domain.model.SaveableNewsResource
import com.google.samples.apps.nowinandroid.core.model.data.previewAuthors
import com.google.samples.apps.nowinandroid.core.model.data.previewNewsResources
import com.google.samples.apps.nowinandroid.core.model.data.previewTopics
import com.google.samples.apps.nowinandroid.core.ui.DevicePreviews
import com.google.samples.apps.nowinandroid.core.ui.NewsFeedUiState
import com.google.samples.apps.nowinandroid.core.ui.TrackScrollJank
import com.google.samples.apps.nowinandroid.core.ui.newsFeed
@OptIn(ExperimentalLifecycleComposeApi::class)
@Composable
internal fun ForYouRoute(
modifier: Modifier = Modifier,
viewModel: ForYouViewModel = hiltViewModel()
) {
val onboardingUiState by viewModel.onboardingUiState.collectAsStateWithLifecycle()
val feedState by viewModel.feedState.collectAsStateWithLifecycle()
val isSyncing by viewModel.isSyncing.collectAsStateWithLifecycle()
ForYouScreen(
isSyncing = isSyncing,
onboardingUiState = onboardingUiState,
feedState = feedState,
onTopicCheckedChanged = viewModel::updateTopicSelection,
onAuthorCheckedChanged = viewModel::updateAuthorSelection,
saveFollowedTopics = viewModel::dismissOnboarding,
onNewsResourcesCheckedChanged = viewModel::updateNewsResourceSaved,
modifier = modifier
)
}
@Composable
internal fun ForYouScreen(
isSyncing: Boolean,
onboardingUiState: OnboardingUiState,
feedState: NewsFeedUiState,
onTopicCheckedChanged: (String, Boolean) -> Unit,
onAuthorCheckedChanged: (String, Boolean) -> Unit,
saveFollowedTopics: () -> Unit,
onNewsResourcesCheckedChanged: (String, Boolean) -> Unit,
modifier: Modifier = Modifier,
) {
// Workaround to call Activity.reportFullyDrawn from Jetpack Compose.
// This code should be called when the UI is ready for use
// and relates to Time To Full Display.
val onboardingLoaded =
onboardingUiState !is OnboardingUiState.Loading
val feedLoaded = feedState !is NewsFeedUiState.Loading
if (onboardingLoaded && feedLoaded) {
val localView = LocalView.current
// We use Unit to call reportFullyDrawn only on the first recomposition,
// however it will be called again if this composable goes out of scope.
// Activity.reportFullyDrawn() has its own check for this
// and is safe to call multiple times though.
LaunchedEffect(Unit) {
// We're leveraging the fact, that the current view is directly set as content of Activity.
val activity = localView.context as? Activity ?: return@LaunchedEffect
// To be sure not to call in the middle of a frame draw.
localView.doOnPreDraw { activity.reportFullyDrawn() }
}
}
val state = rememberLazyGridState()
TrackScrollJank(scrollableState = state, stateName = "forYou:feed")
LazyVerticalGrid(
columns = Adaptive(300.dp),
contentPadding = PaddingValues(16.dp),
horizontalArrangement = Arrangement.spacedBy(16.dp),
verticalArrangement = Arrangement.spacedBy(24.dp),
modifier = modifier
.fillMaxSize()
.testTag("forYou:feed"),
state = state
) {
onboarding(
onboardingUiState = onboardingUiState,
onAuthorCheckedChanged = onAuthorCheckedChanged,
onTopicCheckedChanged = onTopicCheckedChanged,
saveFollowedTopics = saveFollowedTopics,
// Custom LayoutModifier to remove the enforced parent 16.dp contentPadding
// from the LazyVerticalGrid and enable edge-to-edge scrolling for this section
interestsItemModifier = Modifier.layout { measurable, constraints ->
val placeable = measurable.measure(
constraints.copy(
maxWidth = constraints.maxWidth + 32.dp.roundToPx()
)
)
layout(placeable.width, placeable.height) {
placeable.place(0, 0)
}
}
)
newsFeed(
feedState = feedState,
onNewsResourcesCheckedChanged = onNewsResourcesCheckedChanged,
)
item(span = { GridItemSpan(maxLineSpan) }) {
Column {
Spacer(modifier = Modifier.height(8.dp))
// Add space for the content to clear the "offline" snackbar.
// TODO: Check that the Scaffold handles this correctly in NiaApp
// if (isOffline) Spacer(modifier = Modifier.height(48.dp))
Spacer(Modifier.windowInsetsBottomHeight(WindowInsets.safeDrawing))
}
}
}
AnimatedVisibility(
visible = isSyncing ||
feedState is NewsFeedUiState.Loading ||
onboardingUiState is OnboardingUiState.Loading,
enter = slideInVertically(
initialOffsetY = { fullHeight -> -fullHeight },
) + fadeIn(),
exit = slideOutVertically(
targetOffsetY = { fullHeight -> -fullHeight },
) + fadeOut(),
) {
val loadingContentDescription = stringResource(id = R.string.for_you_loading)
Box(
modifier = Modifier.fillMaxWidth()
) {
NiaOverlayLoadingWheel(
modifier = Modifier.align(Alignment.Center),
contentDesc = loadingContentDescription
)
}
}
}
/**
* An extension on [LazyListScope] defining the onboarding portion of the for you screen.
* Depending on the [onboardingUiState], this might emit no items.
*
*/
private fun LazyGridScope.onboarding(
onboardingUiState: OnboardingUiState,
onAuthorCheckedChanged: (String, Boolean) -> Unit,
onTopicCheckedChanged: (String, Boolean) -> Unit,
saveFollowedTopics: () -> Unit,
interestsItemModifier: Modifier = Modifier
) {
when (onboardingUiState) {
OnboardingUiState.Loading,
OnboardingUiState.LoadFailed,
OnboardingUiState.NotShown -> Unit
is OnboardingUiState.Shown -> {
item(span = { GridItemSpan(maxLineSpan) }) {
Column(modifier = interestsItemModifier) {
Text(
text = stringResource(R.string.onboarding_guidance_title),
textAlign = TextAlign.Center,
modifier = Modifier
.fillMaxWidth()
.padding(top = 24.dp),
style = MaterialTheme.typography.titleMedium
)
Text(
text = stringResource(R.string.onboarding_guidance_subtitle),
modifier = Modifier
.fillMaxWidth()
.padding(top = 8.dp, start = 16.dp, end = 16.dp),
textAlign = TextAlign.Center,
style = MaterialTheme.typography.bodyMedium
)
AuthorsCarousel(
authors = onboardingUiState.authors,
onAuthorClick = onAuthorCheckedChanged,
modifier = Modifier
.fillMaxWidth()
.padding(vertical = 8.dp)
)
TopicSelection(
onboardingUiState,
onTopicCheckedChanged,
Modifier.padding(bottom = 8.dp)
)
// Done button
Row(
horizontalArrangement = Arrangement.Center,
modifier = Modifier.fillMaxWidth()
) {
NiaFilledButton(
onClick = saveFollowedTopics,
enabled = onboardingUiState.isDismissable,
modifier = Modifier
.padding(horizontal = 40.dp)
.width(364.dp)
) {
Text(
text = stringResource(R.string.done)
)
}
}
}
}
}
}
}
@Composable
private fun TopicSelection(
onboardingUiState: OnboardingUiState.Shown,
onTopicCheckedChanged: (String, Boolean) -> Unit,
modifier: Modifier = Modifier
) = trace("TopicSelection") {
val lazyGridState = rememberLazyGridState()
TrackScrollJank(scrollableState = lazyGridState, stateName = "forYou:TopicSelection")
LazyHorizontalGrid(
state = lazyGridState,
rows = GridCells.Fixed(3),
horizontalArrangement = Arrangement.spacedBy(12.dp),
verticalArrangement = Arrangement.spacedBy(12.dp),
contentPadding = PaddingValues(24.dp),
modifier = modifier
// LazyHorizontalGrid has to be constrained in height.
// However, we can't set a fixed height because the horizontal grid contains
// vertical text that can be rescaled.
// When the fontScale is at most 1, we know that the horizontal grid will be at most
// 240dp tall, so this is an upper bound for when the font scale is at most 1.
// When the fontScale is greater than 1, the height required by the text inside the
// horizontal grid will increase by at most the same factor, so 240sp is a valid
// upper bound for how much space we need in that case.
// The maximum of these two bounds is therefore a valid upper bound in all cases.
.heightIn(max = max(240.dp, with(LocalDensity.current) { 240.sp.toDp() }))
.fillMaxWidth()
) {
items(onboardingUiState.topics) {
SingleTopicButton(
name = it.topic.name,
topicId = it.topic.id,
imageUrl = it.topic.imageUrl,
isSelected = it.isFollowed,
onClick = onTopicCheckedChanged
)
}
}
}
@OptIn(ExperimentalMaterial3Api::class)
@Composable
private fun SingleTopicButton(
name: String,
topicId: String,
imageUrl: String,
isSelected: Boolean,
onClick: (String, Boolean) -> Unit
) = trace("SingleTopicButton") {
Surface(
modifier = Modifier
.width(312.dp)
.heightIn(min = 56.dp),
shape = RoundedCornerShape(corner = CornerSize(8.dp)),
color = MaterialTheme.colorScheme.surface,
selected = isSelected,
onClick = {
onClick(topicId, !isSelected)
}
) {
Row(
verticalAlignment = Alignment.CenterVertically,
modifier = Modifier.padding(start = 12.dp, end = 8.dp)
) {
TopicIcon(
imageUrl = imageUrl
)
Text(
text = name,
style = MaterialTheme.typography.titleSmall,
modifier = Modifier
.padding(horizontal = 12.dp)
.weight(1f),
color = MaterialTheme.colorScheme.onSurface
)
NiaToggleButton(
checked = isSelected,
onCheckedChange = { checked -> onClick(topicId, checked) },
icon = {
Icon(
imageVector = NiaIcons.Add,
contentDescription = name
)
},
checkedIcon = {
Icon(
imageVector = NiaIcons.Check,
contentDescription = name
)
}
)
}
}
}
@Composable
fun TopicIcon(
imageUrl: String,
modifier: Modifier = Modifier
) {
AsyncImage(
// TODO b/228077205, show loading image visual instead of static placeholder
placeholder = painterResource(R.drawable.ic_icon_placeholder),
model = imageUrl,
contentDescription = null, // decorative
colorFilter = ColorFilter.tint(MaterialTheme.colorScheme.primary),
modifier = modifier
.padding(10.dp)
.size(32.dp)
)
}
@DevicePreviews
@Composable
fun ForYouScreenPopulatedFeed() {
BoxWithConstraints {
NiaTheme {
ForYouScreen(
isSyncing = false,
onboardingUiState = OnboardingUiState.NotShown,
feedState = NewsFeedUiState.Success(
feed = previewNewsResources.map {
SaveableNewsResource(it, false)
}
),
onTopicCheckedChanged = { _, _ -> },
onAuthorCheckedChanged = { _, _ -> },
saveFollowedTopics = {},
onNewsResourcesCheckedChanged = { _, _ -> }
)
}
}
}
@DevicePreviews
@Composable
fun ForYouScreenOfflinePopulatedFeed() {
BoxWithConstraints {
NiaTheme {
ForYouScreen(
isSyncing = false,
onboardingUiState = OnboardingUiState.NotShown,
feedState = NewsFeedUiState.Success(
feed = previewNewsResources.map {
SaveableNewsResource(it, false)
}
),
onTopicCheckedChanged = { _, _ -> },
onAuthorCheckedChanged = { _, _ -> },
saveFollowedTopics = {},
onNewsResourcesCheckedChanged = { _, _ -> }
)
}
}
}
@DevicePreviews
@Composable
fun ForYouScreenTopicSelection() {
BoxWithConstraints {
NiaTheme {
ForYouScreen(
isSyncing = false,
onboardingUiState = OnboardingUiState.Shown(
topics = previewTopics.map { FollowableTopic(it, false) },
authors = previewAuthors.map { FollowableAuthor(it, false) }
),
feedState = NewsFeedUiState.Success(
feed = previewNewsResources.map {
SaveableNewsResource(it, false)
}
),
onTopicCheckedChanged = { _, _ -> },
onAuthorCheckedChanged = { _, _ -> },
saveFollowedTopics = {},
onNewsResourcesCheckedChanged = { _, _ -> }
)
}
}
}
@DevicePreviews
@Composable
fun ForYouScreenLoading() {
BoxWithConstraints {
NiaTheme {
ForYouScreen(
isSyncing = false,
onboardingUiState = OnboardingUiState.Loading,
feedState = NewsFeedUiState.Loading,
onTopicCheckedChanged = { _, _ -> },
onAuthorCheckedChanged = { _, _ -> },
saveFollowedTopics = {},
onNewsResourcesCheckedChanged = { _, _ -> }
)
}
}
}
@DevicePreviews
@Composable
fun ForYouScreenPopulatedAndLoading() {
BoxWithConstraints {
NiaTheme {
ForYouScreen(
isSyncing = true,
onboardingUiState = OnboardingUiState.Loading,
feedState = NewsFeedUiState.Success(
feed = previewNewsResources.map {
SaveableNewsResource(it, false)
}
),
onTopicCheckedChanged = { _, _ -> },
onAuthorCheckedChanged = { _, _ -> },
saveFollowedTopics = {},
onNewsResourcesCheckedChanged = { _, _ -> }
)
}
}
}
| apache-2.0 | c6478c0a1ce85978fd2a49d81dda163a | 38.315068 | 103 | 0.623196 | 5.132856 | false | false | false | false |
iPoli/iPoli-android | app/src/main/java/io/ipoli/android/store/gem/GemStoreViewController.kt | 1 | 10943 | package io.ipoli.android.store.gem
import android.annotation.SuppressLint
import android.os.Bundle
import android.view.LayoutInflater
import android.view.MenuItem
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import com.android.billingclient.api.BillingClient
import com.android.billingclient.api.BillingClient.SkuType
import com.android.billingclient.api.BillingClient.newBuilder
import com.android.billingclient.api.BillingFlowParams
import com.android.billingclient.api.Purchase
import com.android.billingclient.api.SkuDetailsParams
import com.mikepenz.google_material_typeface_library.GoogleMaterial
import com.mikepenz.iconics.IconicsDrawable
import io.ipoli.android.Constants.Companion.GEM_PACK_TYPE_TO_GEMS
import io.ipoli.android.Constants.Companion.GEM_PACK_TYPE_TO_SKU
import io.ipoli.android.Constants.Companion.SKU_TO_GEM_PACK_TYPE
import io.ipoli.android.R
import io.ipoli.android.common.billing.BillingResponseHandler
import io.ipoli.android.common.redux.android.ReduxViewController
import io.ipoli.android.common.view.*
import io.ipoli.android.player.inventory.InventoryViewController
import io.ipoli.android.store.gem.GemStoreViewState.StateType.*
import kotlinx.android.synthetic.main.controller_gem_store.view.*
import kotlinx.android.synthetic.main.view_inventory_toolbar.view.*
import space.traversal.kapsule.required
import java.util.concurrent.atomic.AtomicInteger
/**
* Created by Venelin Valkov <venelin@io.ipoli.io>
* on 27.12.17.
*/
class GemStoreViewController(args: Bundle? = null) :
ReduxViewController<GemStoreAction, GemStoreViewState, GemStoreReducer>(
args
) {
override val reducer = GemStoreReducer
private val billingResponseHandler by required { billingResponseHandler }
private val billingRequestExecutor by required { billingRequestExecutor }
private lateinit var billingClient: BillingClient
private val failureListener = object : BillingResponseHandler.FailureListener {
override fun onCanceledByUser() {
onBillingCanceledByUser()
}
override fun onDisconnected() {
onBillingDisconnected()
}
override fun onUnavailable(responseCode: Int) {
onBillingUnavailable()
}
override fun onError(responseCode: Int) {
onBillingError()
}
}
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup,
savedViewState: Bundle?
): View {
setHasOptionsMenu(true)
val view = inflater.inflate(R.layout.controller_gem_store, container, false)
setToolbar(view.toolbar)
view.toolbarTitle.setText(R.string.gem_store)
setChildController(
view.playerGems,
InventoryViewController(showCurrencyConverter = false)
)
view.mostPopular.setCompoundDrawablesWithIntrinsicBounds(
IconicsDrawable(view.context)
.icon(GoogleMaterial.Icon.gmd_favorite)
.colorRes(R.color.md_white)
.sizeDp(24),
null, null, null
)
billingClient =
newBuilder(activity!!).setListener { responseCode, purchases ->
billingResponseHandler.handle(responseCode, {
purchases!!.forEach {
dispatch(GemStoreAction.GemPackBought(SKU_TO_GEM_PACK_TYPE[it.sku]!!))
}
consumePurchases(purchases)
}, failureListener)
}
.build()
return view
}
private fun consumePurchases(purchases: List<Purchase>?, listener: (() -> Unit)? = null) {
if (purchases == null || purchases.isEmpty()) {
listener?.invoke()
return
}
val count = AtomicInteger(0)
purchases.forEach { p ->
billingClient.execute { bc ->
bc.consumeAsync(
p.purchaseToken
) { _, _ ->
if (count.incrementAndGet() == purchases.size) {
listener?.invoke()
}
}
}
}
}
override fun onAttach(view: View) {
super.onAttach(view)
showBackButton()
billingClient.execute { bc ->
val params = SkuDetailsParams.newBuilder()
.setSkusList(GEM_PACK_TYPE_TO_SKU.values.toList())
.setType(SkuType.INAPP)
.build()
bc.querySkuDetailsAsync(params) { responseCode, skuDetailsList ->
billingResponseHandler.handle(
responseCode = responseCode,
onSuccess = {
val gemPacks = GEM_PACK_TYPE_TO_SKU.map { (k, v) ->
val sku = skuDetailsList.first { it.sku == v }
val gems = GEM_PACK_TYPE_TO_GEMS[k]!!
val titleRes = when (k) {
GemPackType.BASIC -> R.string.gem_pack_basic_title
GemPackType.SMART -> R.string.gem_pack_smart_title
GemPackType.PLATINUM -> R.string.gem_pack_platinum_title
}
val shortTitleRes = when (k) {
GemPackType.BASIC -> R.string.gem_pack_basic_title_short
GemPackType.SMART -> R.string.gem_pack_smart_title_short
GemPackType.PLATINUM -> R.string.gem_pack_platinum_title_short
}
GemPack(
stringRes(titleRes),
stringRes(shortTitleRes),
sku.price,
gems,
k
)
}
dispatch(GemStoreAction.Load(gemPacks))
},
failureListener = failureListener
)
}
}
}
private fun onBillingUnavailable() {
enableButtons()
activity?.let {
Toast.makeText(it, R.string.billing_unavailable, Toast.LENGTH_LONG).show()
}
}
private fun onBillingError() {
enableButtons()
activity?.let {
Toast.makeText(it, R.string.purchase_failed, Toast.LENGTH_LONG).show()
}
}
private fun onBillingCanceledByUser() {
enableButtons()
}
private fun onBillingDisconnected() {
enableButtons()
activity?.let {
Toast.makeText(it, R.string.billing_disconnected, Toast.LENGTH_LONG).show()
}
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
if (item.itemId == android.R.id.home) {
return router.handleBack()
}
return super.onOptionsItemSelected(item)
}
override fun onDetach(view: View) {
billingClient.endConnection()
super.onDetach(view)
}
override fun render(state: GemStoreViewState, view: View) {
when (state.type) {
PLAYER_CHANGED ->
if (state.isGiftPurchased)
showMostPopular(view)
GEM_PACKS_LOADED -> {
if (state.isGiftPurchased)
showMostPopular(view)
state.gemPacks.forEach {
val gp = it
when (it.type) {
GemPackType.BASIC -> {
view.basicPackPrice.text = it.price
view.basicPackTitle.text = it.title
@SuppressLint("SetTextI18n")
view.basicPackGems.text = "x ${it.gems}"
view.basicPackBuy.onDebounceClick {
disableButtons()
buyPack(gp)
}
}
GemPackType.SMART -> {
view.smartPackPrice.text = it.price
view.smartPackTitle.text = it.title
@SuppressLint("SetTextI18n")
view.smartPackGems.text = "x ${it.gems}"
view.smartPackBuy.onDebounceClick {
disableButtons()
buyPack(gp)
}
}
GemPackType.PLATINUM -> {
view.platinumPackPrice.text = it.price
view.platinumPackTitle.text = it.title
@SuppressLint("SetTextI18n")
view.platinumPackGems.text = "x ${it.gems}"
view.platinumPackBuy.onDebounceClick {
disableButtons()
buyPack(gp)
}
}
}
}
}
GEM_PACK_PURCHASED -> {
enableButtons()
Toast.makeText(view.context, R.string.gem_pack_purchased, Toast.LENGTH_LONG).show()
}
DOG_UNLOCKED -> {
showMostPopular(view)
Toast.makeText(view.context, R.string.gift_unlocked, Toast.LENGTH_LONG).show()
}
else -> {
}
}
}
private fun buyPack(gemPack: GemPack) {
val r = billingClient.queryPurchases(BillingClient.SkuType.INAPP)
billingResponseHandler.handle(r.responseCode, {
consumePurchases(r.purchasesList) {
val flowParams = BillingFlowParams.newBuilder()
.setSku(GEM_PACK_TYPE_TO_SKU[gemPack.type])
.setType(SkuType.INAPP)
.build()
billingResponseHandler.handle(
responseCode = billingClient.launchBillingFlow(activity!!, flowParams),
listener = failureListener
)
}
}, failureListener)
}
private fun enableButtons() {
view?.basicPackBuy?.enableClick()
view?.smartPackBuy?.enableClick()
view?.platinumPackBuy?.enableClick()
}
private fun disableButtons() {
view?.basicPackBuy?.disableClick()
view?.smartPackBuy?.disableClick()
view?.platinumPackBuy?.disableClick()
}
private fun showMostPopular(view: View) {
view.giftContainer.visibility = View.GONE
view.mostPopular.visibility = View.VISIBLE
}
private fun BillingClient.execute(request: (BillingClient) -> Unit) {
billingRequestExecutor.execute(this, request, failureListener)
}
} | gpl-3.0 | 5a0e4110b753b4bd7b5a9000e07c865e | 33.632911 | 99 | 0.544183 | 5.063859 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/intentions/RemoveExplicitSuperQualifierIntention.kt | 4 | 3364 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.kotlin.idea.intentions
import com.intellij.codeInspection.CleanupLocalInspectionTool
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.util.TextRange
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.caches.resolve.analyze
import org.jetbrains.kotlin.idea.caches.resolve.analyzeAsReplacement
import org.jetbrains.kotlin.idea.codeinsight.api.classic.intentions.SelfTargetingRangeIntention
import org.jetbrains.kotlin.idea.codeinsight.api.classic.inspections.IntentionBasedInspection
import org.jetbrains.kotlin.psi.KtPsiFactory
import org.jetbrains.kotlin.psi.KtQualifiedExpression
import org.jetbrains.kotlin.psi.KtSuperExpression
import org.jetbrains.kotlin.psi.createExpressionByPattern
import org.jetbrains.kotlin.psi.psiUtil.endOffset
import org.jetbrains.kotlin.psi.psiUtil.getQualifiedExpressionForReceiver
import org.jetbrains.kotlin.psi.psiUtil.startOffset
import org.jetbrains.kotlin.resolve.calls.util.getResolvedCall
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
import org.jetbrains.kotlin.types.error.ErrorUtils
@Suppress("DEPRECATION")
class RemoveExplicitSuperQualifierInspection : IntentionBasedInspection<KtSuperExpression>(
RemoveExplicitSuperQualifierIntention::class
), CleanupLocalInspectionTool
class RemoveExplicitSuperQualifierIntention : SelfTargetingRangeIntention<KtSuperExpression>(
KtSuperExpression::class.java,
KotlinBundle.lazyMessage("remove.explicit.supertype.qualification")
) {
override fun applicabilityRange(element: KtSuperExpression): TextRange? {
if (element.superTypeQualifier == null) return null
val qualifiedExpression = element.getQualifiedExpressionForReceiver() ?: return null
val selector = qualifiedExpression.selectorExpression ?: return null
val bindingContext = selector.analyze(BodyResolveMode.PARTIAL_WITH_CFA)
if (selector.getResolvedCall(bindingContext) == null) return null
val newQualifiedExpression = KtPsiFactory(element).createExpressionByPattern(
"$0.$1", toNonQualified(element, reformat = false), selector,
reformat = false
) as KtQualifiedExpression
val newBindingContext = newQualifiedExpression.analyzeAsReplacement(qualifiedExpression, bindingContext)
val newResolvedCall = newQualifiedExpression.selectorExpression.getResolvedCall(newBindingContext) ?: return null
if (ErrorUtils.isError(newResolvedCall.resultingDescriptor)) return null
return TextRange(element.instanceReference.endOffset, element.labelQualifier?.startOffset ?: element.endOffset)
}
override fun applyTo(element: KtSuperExpression, editor: Editor?) {
element.replace(toNonQualified(element, reformat = true))
}
private fun toNonQualified(superExpression: KtSuperExpression, reformat: Boolean): KtSuperExpression {
val factory = KtPsiFactory(superExpression)
val labelName = superExpression.getLabelNameAsName()
return (if (labelName != null)
factory.createExpressionByPattern("super@$0", labelName, reformat = reformat)
else
factory.createExpression("super")) as KtSuperExpression
}
} | apache-2.0 | 3bf75e4b55fd84689bb8fbf06e63b867 | 49.984848 | 121 | 0.796373 | 5.3824 | false | false | false | false |
GunoH/intellij-community | platform/vcs-impl/src/com/intellij/openapi/vcs/statistics/VcsUsagesCollector.kt | 9 | 4509 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.openapi.vcs.statistics
import com.intellij.internal.statistic.beans.MetricEvent
import com.intellij.internal.statistic.eventLog.EventLogGroup
import com.intellij.internal.statistic.eventLog.events.EventFields
import com.intellij.internal.statistic.eventLog.events.EventPair
import com.intellij.internal.statistic.eventLog.events.StringEventField
import com.intellij.internal.statistic.service.fus.collectors.ProjectUsagesCollector
import com.intellij.internal.statistic.utils.getPluginInfo
import com.intellij.openapi.project.Project
import com.intellij.openapi.vcs.changes.ChangeListManager
import com.intellij.openapi.vcs.ex.ProjectLevelVcsManagerEx
import com.intellij.util.text.nullize
import com.intellij.vcsUtil.VcsUtil
class VcsUsagesCollector : ProjectUsagesCollector() {
override fun getGroup(): EventLogGroup {
return GROUP
}
override fun getMetrics(project: Project): Set<MetricEvent> {
val set = HashSet<MetricEvent>()
val vcsManager = ProjectLevelVcsManagerEx.getInstanceEx(project)
val clm = ChangeListManager.getInstance(project)
val projectBaseDir = project.basePath?.let { VcsUtil.getVirtualFile(it) }
for (vcs in vcsManager.allActiveVcss) {
val pluginInfo = getPluginInfo(vcs.javaClass)
set.add(ACTIVE_VCS.metric(pluginInfo, vcs.name))
}
for (mapping in vcsManager.directoryMappings) {
val vcsName = mapping.vcs.nullize(true)
val vcs = vcsManager.findVcsByName(vcsName)
val pluginInfo = vcs?.let { getPluginInfo(it.javaClass) }
val data = mutableListOf<EventPair<*>>()
data.add(EventFields.PluginInfo.with(pluginInfo))
data.add(IS_PROJECT_MAPPING_FIELD.with(mapping.isDefaultMapping))
data.add(VCS_FIELD_WITH_NONE.with(vcsName ?: "None"))
if (!mapping.isDefaultMapping) {
data.add(IS_BASE_DIR_FIELD.with(projectBaseDir != null &&
projectBaseDir == VcsUtil.getVirtualFile(mapping.directory)))
}
set.add(MAPPING.metric(data))
}
val defaultVcs = vcsManager.findVcsByName(vcsManager.haveDefaultMapping())
if (defaultVcs != null) {
val pluginInfo = getPluginInfo(defaultVcs.javaClass)
val explicitRoots = vcsManager.directoryMappings
.filter { it.vcs == defaultVcs.name }
.filter { it.directory.isNotEmpty() }
.map { VcsUtil.getVirtualFile(it.directory) }
.toSet()
val projectMappedRoots = vcsManager.allVcsRoots
.filter { it.vcs == defaultVcs }
.filter { !explicitRoots.contains(it.path) }
for (vcsRoot in projectMappedRoots) {
set.add(PROJECT_MAPPED_ROOTS.metric(pluginInfo, defaultVcs.name, vcsRoot.path == projectBaseDir))
}
}
set.add(MAPPED_ROOTS.metric(vcsManager.allVcsRoots.size))
set.add(CHANGELISTS.metric(clm.changeListsNumber))
set.add(UNVERSIONED_FILES.metric(clm.unversionedFilesPaths.size))
set.add(IGNORED_FILES.metric(clm.ignoredFilePaths.size))
return set
}
companion object {
private val GROUP = EventLogGroup("vcs.configuration", 3)
private val VCS_FIELD = EventFields.StringValidatedByEnum("vcs", "vcs")
private val ACTIVE_VCS = GROUP.registerEvent("active.vcs", EventFields.PluginInfo,
VCS_FIELD)
private val IS_PROJECT_MAPPING_FIELD = EventFields.Boolean("is_project_mapping")
private val IS_BASE_DIR_FIELD = EventFields.Boolean("is_base_dir")
private val VCS_FIELD_WITH_NONE = object : StringEventField("vcs") {
override val validationRule: List<String>
get() = listOf("{enum#vcs}", "{enum:None}")
}
private val MAPPING = GROUP.registerVarargEvent(
"mapping", EventFields.PluginInfo,
VCS_FIELD_WITH_NONE, IS_PROJECT_MAPPING_FIELD, IS_BASE_DIR_FIELD
)
private val PROJECT_MAPPED_ROOTS = GROUP.registerEvent(
"project.mapped.root", EventFields.PluginInfo,
VCS_FIELD, EventFields.Boolean("is_base_dir")
)
private val MAPPED_ROOTS = GROUP.registerEvent("mapped.roots", EventFields.Count)
private val CHANGELISTS = GROUP.registerEvent("changelists", EventFields.Count)
private val UNVERSIONED_FILES = GROUP.registerEvent("unversioned.files", EventFields.Count)
private val IGNORED_FILES = GROUP.registerEvent("ignored.files", EventFields.Count)
}
}
| apache-2.0 | 9f0e9e870fbced86544c85ceb88b517a | 43.205882 | 158 | 0.722555 | 4.310707 | false | false | false | false |
cleverchap/AutoAnylysis | src/com/cc/io/XmlManager.kt | 1 | 2978 | package com.cc.io
import org.dom4j.Attribute
import org.dom4j.Document
import org.dom4j.Element
import org.dom4j.io.SAXReader
import java.io.File
/**
* 参考文章:http://blog.csdn.net/yyywyr/article/details/38359049
*/
class XmlManager {
private val SPLIT_CHAR = "@"
private val MODULE_NAME = "Module"
private val TESTCASE_NAME = "TestCase"
private val TEST_NAME = "Test"
private val mConcernNodeNameList = mutableListOf(MODULE_NAME, TESTCASE_NAME, TEST_NAME)
private val mConcernNodePropertyList = mutableListOf("name")
private var mLastModuleName = ""
private var mLastTestCaseName = ""
private var mLastTestName = ""
fun testCode() {
// 1. 创建SAXReader对象
val reader = SAXReader()
// 2. 读取文件
val file = File("D:\\Temp\\Cts_logs\\1.xml")
// 3. 转换成Document
val document : Document = reader.read(file)
// 4. 获取根节点元素对象
val root : Element = document.rootElement
// 5. 遍历
listNodes(root)
}
//遍历当前节点下的所有节点
private fun listNodes(node: Element) {
val isConcern = isConcernNode(node.name)
log(isConcern, "当前节点的名称:" + node.name)
// 5.1 首先获取当前节点的所有属性节点
val list = node.attributes() as List<Attribute>
// 5.2 遍历属性节点
for (attribute in list) {
val isConcernProperty = isConcernProperty(attribute.name)
log(isConcernProperty, "属性" + attribute.name + ":" + attribute.value)
if (isConcernProperty) {
logMajorContent(node, attribute)
}
}
// 5.3 如果当前节点内容不为空,则输出
if (node.textTrim != "") {
val isConcernProperty = isConcernProperty(node.name)
log(isConcernProperty, node.name + ":" + node.text)
}
// 5.4 同时迭代当前节点下面的所有子节点
// 5.5 使用递归
val iterator = node.elementIterator()
while (iterator.hasNext()) {
val e = iterator.next() as Element
listNodes(e)
}
}
//只处理关心结点的信息
private fun isConcernNode(nodeName: String) = nodeName in mConcernNodeNameList
private fun isConcernProperty(propertyName : String) = propertyName in mConcernNodePropertyList
private fun log(isConcern: Boolean, content: String) {
// if (isConcern) println(content)
}
private fun logMajorContent(node:Element, attribute: Attribute) {
when (node.name) {
MODULE_NAME -> mLastModuleName = attribute.value
TESTCASE_NAME -> mLastTestCaseName = attribute.value
TEST_NAME -> {
mLastTestName = attribute.value
println(mLastModuleName + SPLIT_CHAR + mLastTestCaseName + SPLIT_CHAR + mLastTestName)
}
}
}
}
| apache-2.0 | fa2bb73d57ffb30c6949e12b5e29967d | 31.690476 | 102 | 0.61362 | 3.856742 | false | true | false | false |
chiclaim/android-sample | language-kotlin/kotlin-sample/kotlin-in-action/src/new_class/SealedClassTest.kt | 1 | 1464 | package new_class
/**
* desc: sealed class 演示
*
* Created by Chiclaim on 2018/09/22
*/
/*
小结:
当我们使用when语句通常需要加else分支,如果when是判断某个复杂类型,如果该类型后面有新的子类,when语句就会走else分支
sealed class就是用来解决这个问题的。
当when判断的是sealed class,那么不需要加else默认分支,如果有新的子类,编译器会通过编译报错的方式提醒开发者添加新分支,从而保证逻辑的完整性和正确性
需要注意的是,当when判断的是sealed class,千万不要添加else分支,否则有新子类编译器也不会提醒
sealed class 在外部不能被继承,私有构造方法是私有的
*/
sealed class Expr {
class Num(val value: Int) : Expr()
class Sum(val left: Expr, val right: Expr) : Expr()
}
fun eval(e: Expr): Int =
when (e) {
is Expr.Num -> e.value
is Expr.Sum -> eval(e.left) + eval(e.right)
}
//=========================================================
open class Expr2;
class Num2(val value: Int) : Expr2()
class Sum2(val left: Expr2, val right: Expr2) : Expr2()
fun eval2(e: Expr2): Int =
when (e) {
is Num2 -> e.value
is Sum2 -> eval2(e.left) + eval2(e.right)
else -> -1
}
fun main(args: Array<String>) {
val sum = eval(Expr.Sum(Expr.Num(1), Expr.Num(2)))
println("sum = $sum")
}
| apache-2.0 | 3b011bf9baabbe6c9c80e9ca35f3d32e | 18.298246 | 83 | 0.594545 | 2.600473 | false | false | false | false |
AntonovAlexander/activecore | kernelip/cyclix/src/hw_subproc.kt | 1 | 4583 | /*
* hw_subproc.kt
*
* Created on: 05.06.2019
* Author: Alexander Antonov <antonov.alex.alex@gmail.com>
* License: See LICENSE file for details
*/
package cyclix
import hwast.*
class hw_subproc(var inst_name : String, var src_module: Generic, var parent_module: Generic) {
var RootResetDriver = parent_module.ulocal("gensubmod_" + inst_name + "_genrst", 0, 0, "0")
var AppResetDrivers = ArrayList<hw_var>()
var Ports = mutableMapOf<String, hw_port>()
var PortConnections = mutableMapOf<hw_port, hw_param>()
var fifo_ifs = mutableMapOf<String, hw_structvar>()
var FifoConnections = mutableMapOf<hw_structvar, hw_param>()
init {
for (port in src_module.Ports) {
Ports.put(port.name, port)
}
for (fifo in src_module.fifo_ifs) {
fifo_ifs.put(fifo.value.name, fifo.value)
}
}
fun AddResetDriver() : hw_var {
var rst_var = parent_module.ulocal(parent_module.GetGenName("genrst"), 0, 0, "0")
AppResetDrivers.add(rst_var)
return rst_var
}
fun AddResetDriver(rst_var : hw_var) : hw_var {
AppResetDrivers.add(rst_var)
return rst_var
}
fun getPortByName(name : String) : hw_port {
if (!Ports.containsKey(name)) ERROR("Port " + name + " is unknown for instance " + inst_name)
return Ports[name]!!
}
fun getFifoByName(name : String) : hw_structvar {
return fifo_ifs[name]!!
}
fun connectPort(port : hw_port, src : hw_param) {
if (!Ports.containsValue(port)) ERROR("Port " + port.name + " is unknown!")
if (PortConnections.containsKey(port)) ERROR("port " + port.name + " for instance " + inst_name
+ "cannot be connected to src " + src.GetString() +
" - it is already connected to src " + PortConnections[port]!!.GetString())
PortConnections.put(port, src)
if (src is hw_var) {
if (port.port_dir == PORT_DIR.IN) src.read_done = true
else if (port.port_dir == PORT_DIR.OUT) src.write_done = true
else {
src.read_done = true
src.write_done = true
}
}
}
fun connectPort(port : hw_port, value : Int) {
connectPort(port, hw_imm(value))
}
fun connectPort(port_name : String, src : hw_param) {
var port = getPortByName(port_name)
connectPort(port, src)
}
fun connectPort(port_name : String, value : Int) {
connectPort(port_name, hw_imm(value))
}
fun connectPortGen(port_name : String) : hw_var {
var part_var = parent_module.local(parent_module.GetGenName(port_name), getPortByName(port_name).vartype, getPortByName(port_name).defval)
connectPort(port_name, part_var)
return part_var
}
/*
fun connectFifo(fifo : hw_structvar, src : hw_param) {
if (!fifo_ifs.containsValue(fifo)) ERROR("Port " + fifo.name + " is unknown!")
if (FifoConnections.containsKey(fifo)) ERROR("port " + fifo.name + " for instance " + inst_name
+ "cannot be connected to src " + src.GetString() +
" - it is already connected to src " + FifoConnections[fifo]!!.GetString())
FifoConnections.put(fifo, src)
if (src is hw_var) {
if (fifo is hw_fifo_in) src.read_done = true
else if (fifo is hw_fifo_out) src.write_done = true
else {
src.read_done = true
src.write_done = true
}
}
}
fun connectFifo(fifo_name : String, src : hw_param) {
var fifo = getFifoByName(fifo_name)
connectFifo(fifo, src)
}
fun connectFifoGen(fifo_name : String) : hw_var {
var part_var = parent_module.local(parent_module.GetGenName(fifo_name), getFifoByName(fifo_name).vartype, getFifoByName(fifo_name).defval)
connectFifo(fifo_name, part_var)
return part_var
}
*/
fun fifo_internal_wr_unblk(fifo_name : String, wdata : hw_param) : hw_var {
return parent_module.fifo_internal_wr_unblk(this, fifo_name, wdata)
}
fun fifo_internal_rd_unblk(fifo_name : String, rdata : hw_var) : hw_var {
return parent_module.fifo_internal_rd_unblk(this, fifo_name, rdata)
}
fun fifo_internal_wr_blk(fifo_name : String, wdata : hw_param) {
parent_module.fifo_internal_wr_blk(this, fifo_name, wdata)
}
fun fifo_internal_rd_blk(fifo_name : String) : hw_var {
return parent_module.fifo_internal_rd_blk(this, fifo_name)
}
} | apache-2.0 | 9b519c8a071bd4119cadbbf952b2b0dc | 33.727273 | 146 | 0.597862 | 3.485171 | false | false | false | false |
oldergod/android-architecture | app/src/androidTest/java/com/example/android/architecture/blueprints/todoapp/TestUtils.kt | 1 | 2921 | /*
* Copyright 2016, The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.android.architecture.blueprints.todoapp
import android.app.Activity
import android.content.pm.ActivityInfo
import android.content.res.Configuration
import android.support.annotation.IdRes
import android.support.test.InstrumentationRegistry.getInstrumentation
import android.support.test.runner.lifecycle.ActivityLifecycleMonitor
import android.support.test.runner.lifecycle.ActivityLifecycleMonitorRegistry
import android.support.test.runner.lifecycle.Stage.RESUMED
import android.support.v7.widget.Toolbar
/**
* Useful test methods common to all activities
*/
/**
* Gets an Activity in the RESUMED stage.
*
*
* This method should never be called from the Main thread. In certain situations there might
* be more than one Activities in RESUMED stage, but only one is returned.
* See [ActivityLifecycleMonitor].
*/
// The array is just to wrap the Activity and be able to access it from the Runnable.
fun getCurrentActivity(): Activity {
val resumedActivity = arrayOfNulls<Activity>(1)
getInstrumentation().runOnMainSync {
val resumedActivities =
ActivityLifecycleMonitorRegistry.getInstance().getActivitiesInStage(RESUMED)
if (resumedActivities.iterator().hasNext()) {
resumedActivity[0] = resumedActivities.iterator().next() as Activity
} else {
throw IllegalStateException("No Activity in stage RESUMED")
}
}
return resumedActivity[0]!!
}
private fun rotateToLandscape(activity: Activity) {
activity.requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE
}
private fun rotateToPortrait(activity: Activity) {
activity.requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT
}
fun rotateOrientation(activity: Activity) {
val currentOrientation = activity.resources.configuration.orientation
when (currentOrientation) {
Configuration.ORIENTATION_LANDSCAPE -> rotateToPortrait(activity)
Configuration.ORIENTATION_PORTRAIT -> rotateToLandscape(activity)
else -> rotateToLandscape(activity)
}
}
/**
* Returns the content description for the navigation button view in the toolbar.
*/
fun getToolbarNavigationContentDescription(
activity: Activity,
@IdRes toolbar1: Int
): String {
return activity.findViewById<Toolbar>(toolbar1).navigationContentDescription!!.toString()
}
| apache-2.0 | 7fce60c153c0eae4dcf2214a303f7e9a | 33.77381 | 93 | 0.777473 | 4.688604 | false | true | false | false |
inorichi/mangafeed | app/src/main/java/eu/kanade/tachiyomi/ui/setting/SettingsAppearanceController.kt | 1 | 6587 | package eu.kanade.tachiyomi.ui.setting
import android.os.Build
import android.os.Bundle
import android.view.View
import androidx.core.app.ActivityCompat
import androidx.preference.PreferenceScreen
import eu.kanade.tachiyomi.R
import eu.kanade.tachiyomi.util.preference.bindTo
import eu.kanade.tachiyomi.util.preference.defaultValue
import eu.kanade.tachiyomi.util.preference.entriesRes
import eu.kanade.tachiyomi.util.preference.initThenAdd
import eu.kanade.tachiyomi.util.preference.intListPreference
import eu.kanade.tachiyomi.util.preference.listPreference
import eu.kanade.tachiyomi.util.preference.onChange
import eu.kanade.tachiyomi.util.preference.preferenceCategory
import eu.kanade.tachiyomi.util.preference.switchPreference
import eu.kanade.tachiyomi.util.preference.titleRes
import eu.kanade.tachiyomi.util.system.DeviceUtil
import eu.kanade.tachiyomi.util.system.isTablet
import eu.kanade.tachiyomi.widget.preference.ThemesPreference
import java.util.Date
import eu.kanade.tachiyomi.data.preference.PreferenceKeys as Keys
import eu.kanade.tachiyomi.data.preference.PreferenceValues as Values
class SettingsAppearanceController : SettingsController() {
private var themesPreference: ThemesPreference? = null
override fun setupPreferenceScreen(screen: PreferenceScreen) = screen.apply {
titleRes = R.string.pref_category_appearance
preferenceCategory {
titleRes = R.string.pref_category_theme
listPreference {
bindTo(preferences.themeMode())
titleRes = R.string.pref_theme_mode
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
entriesRes = arrayOf(
R.string.theme_system,
R.string.theme_light,
R.string.theme_dark
)
entryValues = arrayOf(
Values.ThemeMode.system.name,
Values.ThemeMode.light.name,
Values.ThemeMode.dark.name
)
} else {
entriesRes = arrayOf(
R.string.theme_light,
R.string.theme_dark
)
entryValues = arrayOf(
Values.ThemeMode.light.name,
Values.ThemeMode.dark.name
)
}
summary = "%s"
}
themesPreference = initThenAdd(ThemesPreference(context)) {
bindTo(preferences.appTheme())
titleRes = R.string.pref_app_theme
val appThemes = Values.AppTheme.values().filter {
val monetFilter = if (it == Values.AppTheme.MONET) {
DeviceUtil.isDynamicColorAvailable
} else {
true
}
it.titleResId != null && monetFilter
}
entries = appThemes
onChange {
activity?.let { ActivityCompat.recreate(it) }
true
}
}
switchPreference {
bindTo(preferences.themeDarkAmoled())
titleRes = R.string.pref_dark_theme_pure_black
visibleIf(preferences.themeMode()) { it != Values.ThemeMode.light }
onChange {
activity?.let { ActivityCompat.recreate(it) }
true
}
}
}
preferenceCategory {
titleRes = R.string.pref_category_navigation
if (context.isTablet()) {
intListPreference {
bindTo(preferences.sideNavIconAlignment())
titleRes = R.string.pref_side_nav_icon_alignment
entriesRes = arrayOf(
R.string.alignment_top,
R.string.alignment_center,
R.string.alignment_bottom,
)
entryValues = arrayOf("0", "1", "2")
summary = "%s"
}
} else {
switchPreference {
bindTo(preferences.hideBottomBarOnScroll())
titleRes = R.string.pref_hide_bottom_bar_on_scroll
}
}
}
preferenceCategory {
titleRes = R.string.pref_category_timestamps
intListPreference {
bindTo(preferences.relativeTime())
titleRes = R.string.pref_relative_format
val values = arrayOf("0", "2", "7")
entryValues = values
entries = values.map {
when (it) {
"0" -> context.getString(R.string.off)
"2" -> context.getString(R.string.pref_relative_time_short)
else -> context.getString(R.string.pref_relative_time_long)
}
}.toTypedArray()
summary = "%s"
}
listPreference {
key = Keys.dateFormat
titleRes = R.string.pref_date_format
entryValues = arrayOf("", "MM/dd/yy", "dd/MM/yy", "yyyy-MM-dd", "dd MMM yyyy", "MMM dd, yyyy")
val now = Date().time
entries = entryValues.map { value ->
val formattedDate = preferences.dateFormat(value.toString()).format(now)
if (value == "") {
"${context.getString(R.string.label_default)} ($formattedDate)"
} else {
"$value ($formattedDate)"
}
}.toTypedArray()
defaultValue = ""
summary = "%s"
}
}
}
override fun onSaveViewState(view: View, outState: Bundle) {
themesPreference?.let {
outState.putInt(THEMES_SCROLL_POSITION, it.lastScrollPosition ?: 0)
}
super.onSaveInstanceState(outState)
}
override fun onRestoreViewState(view: View, savedViewState: Bundle) {
super.onRestoreViewState(view, savedViewState)
themesPreference?.lastScrollPosition = savedViewState.getInt(THEMES_SCROLL_POSITION, 0)
}
override fun onDestroyView(view: View) {
super.onDestroyView(view)
themesPreference = null
}
}
private const val THEMES_SCROLL_POSITION = "themesScrollPosition"
| apache-2.0 | dcdf0ac19e8ea271b2ecfc0c3905e268 | 36.426136 | 110 | 0.542432 | 5.178459 | false | false | false | false |
ClearVolume/scenery | src/main/kotlin/graphics/scenery/backends/UBO.kt | 2 | 11970 | package graphics.scenery.backends
import cleargl.GLMatrix
import cleargl.GLVector
import gnu.trove.map.hash.TIntObjectHashMap
import graphics.scenery.utils.LazyLogger
import org.joml.*
import org.lwjgl.system.MemoryUtil
import java.nio.ByteBuffer
import java.nio.ByteOrder
import java.util.*
import kotlin.collections.LinkedHashMap
import kotlin.math.max
/**
* UBO base class, providing API-independent uniform buffer serialisation
* functionality for both OpenGL and Vulkan.
*
* @author Ulrik Günther <hello@ulrik.is>
*/
open class UBO {
/** Name of this UBO */
var name = ""
protected var members = LinkedHashMap<String, () -> Any>()
protected var memberOffsets = HashMap<String, Int>()
protected val logger by LazyLogger()
/** Hash value of all the members, gets updated by [populate()] */
var hash: Int = 0
private set
/** Cached size of the UBO, -1 if the UBO has not been populated yet. */
var sizeCached = -1
protected set
companion object {
/** Cache for alignment data inside buffers */
internal var alignments = TIntObjectHashMap<Pair<Int, Int>>()
}
/**
* Returns the size of [element] inside an uniform buffer.
*/
@Suppress("PLATFORM_CLASS_MAPPED_TO_KOTLIN")
protected fun sizeOf(element: Any): Int {
return when(element) {
is Vector2f, is Vector2i -> 2
is Vector3f, is Vector3i -> 3
is Vector4f, is Vector4i -> 4
is Matrix4f -> 4 * 4
is Float, is java.lang.Float -> 4
is Double, is java.lang.Double -> 8
is Int, is Integer -> 4
is Short, is java.lang.Short -> 2
is Boolean, is java.lang.Boolean -> 4
is Enum<*> -> 4
is FloatArray -> element.size * 4
else -> { logger.error("Don't know how to determine size of $element"); 0 }
}
}
/**
* Translates an object to an integer ID for more efficient storage in [alignments].
*/
@Suppress("PLATFORM_CLASS_MAPPED_TO_KOTLIN")
protected fun Any.objectId(): Int {
return when(this) {
is GLVector -> 0
is GLMatrix -> 1
is Float, is java.lang.Float -> 2
is Double, is java.lang.Double -> 3
is Int, is Integer -> 4
is Short, is java.lang.Short -> 5
is Boolean, is java.lang.Boolean -> 6
is Enum<*> -> 7
is Vector2f -> 8
is Vector3f -> 9
is Vector4f -> 10
is Vector2i -> 11
is Vector3i -> 12
is Vector4i -> 13
is Matrix4f -> 14
is FloatArray -> 15
else -> { logger.error("Don't know how to determine object ID of $this/${this.javaClass.simpleName}"); -1 }
}
}
/**
* Returns the size occupied and alignment required for [element] inside a uniform buffer.
* Pair layout is <size, alignment>.
*/
@Suppress("PLATFORM_CLASS_MAPPED_TO_KOTLIN")
fun getSizeAndAlignment(element: Any): Pair<Int, Int> {
// pack object id and size into one integer
val key = (element.objectId() shl 16) or (sizeOf(element) and 0xffff)
if(alignments.containsKey(key)) {
return alignments.get(key)
} else {
val sa = when (element) {
is Matrix4f -> Pair(4 * 4 * 4, 4 * 4)
is Vector2f, is Vector2i -> Pair(2*4, 2*4)
is Vector3f, is Vector3i -> Pair(3*4, 4*4)
is Vector4f, is Vector4i -> Pair(4*4, 4*4)
is Float -> Pair(4, 4)
is Double -> Pair(8, 8)
is Integer -> Pair(4, 4)
is Int -> Pair(4, 4)
is Short -> Pair(2, 2)
is Boolean -> Pair(4, 4)
is Enum<*> -> Pair(4, 4)
is FloatArray -> Pair(4*element.size, 4*4)
else -> {
logger.error("Unknown VulkanUBO member type: ${element.javaClass.simpleName}")
Pair(0, 0)
}
}
alignments.put(key, sa)
return sa
}
}
/**
* Returns the total size in bytes required to store the contents of this UBO in a uniform buffer.
*/
fun getSize(): Int {
val totalSize = if(sizeCached == -1) {
val size = members.map {
getSizeAndAlignment(it.value.invoke())
}.fold(0) { current_position, (first, second) ->
// next element should start at the position
// required by it's alignment
val remainder = current_position.rem(second)
val new_position = if (remainder != 0) {
current_position + second - remainder + first
} else {
current_position + first
}
new_position
}
sizeCached = size
size
} else {
sizeCached
}
return totalSize
}
/**
* Populates the [ByteBuffer] [data] with the members of this UBO, subject to the determined
* sizes and alignments. A buffer [offset] can be given, as well as a list of [elements] that
* would override the UBO's members. This routine checks if an actual buffer update is required,
* and if not, will just set the buffer to the cached position. Otherwise it will serialise all
* the members into [data].
*
* Returns true if [data] has been updated, and false if not.
*/
@Suppress("PLATFORM_CLASS_MAPPED_TO_KOTLIN")
fun populate(data: ByteBuffer, offset: Long = -1L, elements: (LinkedHashMap<String, () -> Any>)? = null): Boolean {
// no need to look further
if(members.size == 0) {
return false
}
if(offset != -1L) {
data.position(offset.toInt())
}
val originalPos = data.position()
var endPos = originalPos
val oldHash = hash
if(sizeCached > 0 && elements == null) {
// the members hash is also based on the memory address of the buffer, which is calculated at the
// end of the routine and therefore dependent on the final buffer position.
val newHash = getMembersHash(data.duplicate().order(ByteOrder.LITTLE_ENDIAN).position(originalPos + sizeCached) as ByteBuffer)
if(oldHash == newHash) {
data.position(originalPos + sizeCached)
logger.trace("UBO members of {} have not changed, {} vs {}", this, hash, newHash)
// indicates the buffer will not be updated, but only forwarded to the cached position
return false
}
}
// iterate over members, or over elements, if given
(elements ?: members).forEach {
var pos = data.position()
val value = it.value.invoke()
val (size, alignment) = getSizeAndAlignment(value)
if(logger.isTraceEnabled) {
logger.trace("Populating {} of type {} size={} alignment={}", it.key, value.javaClass.simpleName, size, alignment)
}
val memberOffset = memberOffsets[it.key]
if(memberOffset != null) {
// position in buffer is known, use it
if(logger.isTraceEnabled) {
logger.trace("{} goes to {}", it.key, memberOffset)
}
pos = (originalPos + memberOffset)
data.position(pos)
} else {
// position in buffer is not explicitly known, advance based on size
if (pos.rem(alignment) != 0) {
pos = pos + alignment - (pos.rem(alignment))
data.position(pos)
}
}
when (value) {
is Matrix4f -> value.get(data)
is Vector2i -> value.get(data)
is Vector3i -> value.get(data)
is Vector4i -> value.get(data)
is Vector2f -> value.get(data)
is Vector3f -> value.get(data)
is Vector4f -> value.get(data)
is Float -> data.asFloatBuffer().put(0, value)
is Double -> data.asDoubleBuffer().put(0, value)
is Integer -> data.asIntBuffer().put(0, value.toInt())
is Int -> data.asIntBuffer().put(0, value)
is Short -> data.asShortBuffer().put(0, value)
is Boolean -> data.asIntBuffer().put(0, value.toInt())
is Enum<*> -> data.asIntBuffer().put(0, value.ordinal)
is FloatArray -> data.asFloatBuffer().put(value)
}
data.position(pos + size)
endPos = max(pos + size, endPos)
}
data.position(endPos)
sizeCached = data.position() - originalPos
if(elements == null) {
updateHash(data)
}
logger.trace("UBO {} updated, {} -> {}", this, oldHash, hash)
// indicates the buffer has been updated
return true
}
/**
* Adds a member with [name] to this UBO. [value] is given as a lambda
* that will return the actual value when invoked. An optional [offset] can be
* given, otherwise it will be calculated automatically.
*
* Invalidates the UBO's hash if no previous member is associated with [name],
* or if a previous member already bears [name], but has another type than the
* invocation of [value].
*/
fun add(name: String, value: () -> Any, offset: Int? = null) {
val previous = members.put(name, value)
offset?.let {
memberOffsets.put(name, offset)
}
if(previous == null || previous.invoke().javaClass != value.invoke().javaClass) {
// invalidate sizes
sizeCached = -1
}
}
/**
* Adds the member only if its missing.
*/
fun addIfMissing(name: String, value: () -> Any, offset: Int? = null) {
if(!members.containsKey(name)) {
add(name, value, offset)
}
}
/**
* Returns the members of the UBO as string.
*/
fun members(): String {
return members.keys.joinToString(", ")
}
/**
* Returns the members of the UBO and their values as string.
*/
fun membersAndContent(): String {
return members.entries.joinToString { "${it.key} -> ${it.value.invoke()}" }
}
/**
* Returns the number of members of this UBO.
*/
fun memberCount(): Int {
return members.size
}
/**
* For debugging purposes. Returns the hashes of all members as string.
*/
@Suppress("unused")
internal fun perMemberHashes(): String {
return members.map { "${it.key} -> ${it.key.hashCode()} ${it.value.invoke().hashCode()}" }.joinToString("\n")
}
/**
* Returns the hash value of all current members.
*
* Takes into consideration the member's name and _invoked_ value, as well as the
* buffer's memory address to discern buffer switches the UBO is oblivious to.
*/
protected fun getMembersHash(buffer: ByteBuffer): Int {
return members.map { (it.key.hashCode() xor it.value.invoke().hashCode()).toLong() }
.fold(31L) { acc, value -> acc + (value xor (value.ushr(32)))}.toInt() + MemoryUtil.memAddress(buffer).hashCode()
}
/**
* Updates the currently stored member hash.
*/
protected fun updateHash(buffer: ByteBuffer) {
hash = getMembersHash(buffer)
}
/**
* Returns the lambda associated with member of [name], or null
* if it does not exist.
*/
fun get(name: String): (() -> Any)? {
return members[name]
}
private fun Boolean.toInt(): Int {
return if(this) { 1 } else { 0 }
}
}
| lgpl-3.0 | 39d775fc3d7a860a16cd5184e98da7e0 | 32.339833 | 138 | 0.550338 | 4.339739 | false | false | false | false |
McMoonLakeDev/MoonLake | API/src/main/kotlin/com/mcmoonlake/api/chat/ChatStyle.kt | 1 | 8926 | /*
* Copyright (C) 2016-Present The MoonLake (mcmoonlake@hotmail.com)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.mcmoonlake.api.chat
/**
* ## ChatStyle (聊天样式)
*
* @author lgou2w
* @since 2.0
*/
open class ChatStyle {
/** member */
private var parent: ChatStyle? = null
@JvmField internal var color: ChatColor? = null
@JvmField internal var bold: Boolean? = null
@JvmField internal var italic: Boolean? = null
@JvmField internal var underlined: Boolean? = null
@JvmField internal var strikethrough: Boolean? = null
@JvmField internal var obfuscated: Boolean? = null
@JvmField internal var clickEvent: ChatClickEvent? = null
@JvmField internal var hoverEvent: ChatHoverEvent? = null
@JvmField internal var insertion: String? = null
/** static */
companion object {
@JvmStatic
private val ROOT = object: ChatStyle() {
override fun getColor(): ChatColor?
= null
override fun getBold(): Boolean?
= false
override fun getItalic(): Boolean?
= false
override fun getStrikethrough(): Boolean?
= false
override fun getUnderlined(): Boolean?
= false
override fun getObfuscated(): Boolean?
= false
override fun getClickEvent(): ChatClickEvent?
= null
override fun getHoverEvent(): ChatHoverEvent?
= null
override fun getInsertion(): String?
= null
override fun setParent(parent: ChatStyle?): ChatStyle
= throw UnsupportedOperationException()
override fun setColor(color: ChatColor?): ChatStyle
= throw UnsupportedOperationException()
override fun setBold(bold: Boolean?): ChatStyle
= throw UnsupportedOperationException()
override fun setItalic(italic: Boolean?): ChatStyle
= throw UnsupportedOperationException()
override fun setStrikethrough(strikethrough: Boolean?): ChatStyle
= throw UnsupportedOperationException()
override fun setUnderlined(underlined: Boolean?): ChatStyle
= throw UnsupportedOperationException()
override fun setObfuscated(obfuscated: Boolean?): ChatStyle
= throw UnsupportedOperationException()
override fun setClickEvent(clickEvent: ChatClickEvent?): ChatStyle
= throw UnsupportedOperationException()
override fun setHoverEvent(hoverEvent: ChatHoverEvent?): ChatStyle
= throw UnsupportedOperationException()
override fun setInsertion(insertion: String?): ChatStyle
= throw UnsupportedOperationException()
override fun toString(): String
= "ChatStyle.ROOT"
}
}
private fun getParent(): ChatStyle
= parent ?: ROOT
/**
* @see [ChatColor]
*/
open fun getColor(): ChatColor?
= color ?: getParent().getColor()
/**
* @see [ChatColor.BOLD]
*/
open fun getBold(): Boolean?
= bold ?: getParent().getBold()
/**
* @see [ChatColor.ITALIC]
*/
open fun getItalic(): Boolean?
= italic ?: getParent().getItalic()
/**
* @see [ChatColor.STRIKETHROUGH]
*/
open fun getStrikethrough(): Boolean?
= strikethrough ?: getParent().getStrikethrough()
/**
* @see [ChatColor.UNDERLINE]
*/
open fun getUnderlined(): Boolean?
= underlined ?: getParent().getUnderlined()
/**
* @see [ChatColor.OBFUSCATED]
*/
open fun getObfuscated(): Boolean?
= obfuscated ?: getParent().getObfuscated()
/**
* @see [ChatClickEvent]
*/
open fun getClickEvent(): ChatClickEvent?
= clickEvent ?: getParent().getClickEvent()
/**
* @see [ChatHoverEvent]
*/
open fun getHoverEvent(): ChatHoverEvent?
= hoverEvent ?: getParent().getHoverEvent()
open fun getInsertion(): String?
= insertion ?: getParent().getInsertion()
open fun setParent(parent: ChatStyle?): ChatStyle
{ this.parent = parent; return this; }
/**
* @see [ChatColor]
*/
open fun setColor(color: ChatColor?): ChatStyle
{ this.color = color; return this; }
/**
* @see [ChatColor.BOLD]
*/
open fun setBold(bold: Boolean?): ChatStyle
{ this.bold = bold; return this; }
/**
* @see [ChatColor.ITALIC]
*/
open fun setItalic(italic: Boolean?): ChatStyle
{ this.italic = italic; return this; }
/**
* @see [ChatColor.STRIKETHROUGH]
*/
open fun setStrikethrough(strikethrough: Boolean?): ChatStyle
{ this.strikethrough = strikethrough; return this; }
/**
* @see [ChatColor.UNDERLINE]
*/
open fun setUnderlined(underlined: Boolean?): ChatStyle
{ this.underlined = underlined; return this; }
/**
* @see [ChatColor.OBFUSCATED]
*/
open fun setObfuscated(obfuscated: Boolean?): ChatStyle
{ this.obfuscated = obfuscated; return this; }
/**
* @see [ChatClickEvent]
*/
open fun setClickEvent(clickEvent: ChatClickEvent?): ChatStyle
{ this.clickEvent = clickEvent; return this; }
/**
* @see [ChatHoverEvent]
*/
open fun setHoverEvent(hoverEvent: ChatHoverEvent?): ChatStyle
{ this.hoverEvent = hoverEvent; return this; }
open fun setInsertion(insertion: String?): ChatStyle
{ this.insertion = insertion; return this; }
/**
* * Get this chat style is empty.
* * 获取此聊天样式是否为空.
*/
fun isEmpty(): Boolean
= color == null && bold == null && italic == null && strikethrough == null && underlined == null && obfuscated == null && clickEvent == null && hoverEvent == null && insertion == null
/**
* * Shallow a clone of this chat style object.
* * 浅克隆一份此聊天样式的对象.
*/
fun clone(): ChatStyle {
val copy = ChatStyle()
copy.color = color
copy.bold = bold
copy.italic = italic
copy.strikethrough = strikethrough
copy.underlined = underlined
copy.obfuscated = obfuscated
copy.clickEvent = clickEvent
copy.hoverEvent = hoverEvent
copy.insertion = insertion
return copy
}
override fun equals(other: Any?): Boolean {
if(other === this)
return true
if(other is ChatStyle) {
if(parent != other.parent) return false
if(color != other.color) return false
if(bold != other.bold) return false
if(italic != other.italic) return false
if(underlined != other.underlined) return false
if(strikethrough != other.strikethrough) return false
if(obfuscated != other.obfuscated) return false
if(clickEvent != other.clickEvent) return false
if(hoverEvent != other.hoverEvent) return false
if(insertion != other.insertion) return false
return true
}
return false
}
override fun hashCode(): Int {
var result = color?.hashCode() ?: 0
result = 31 * result + (bold?.hashCode() ?: 0)
result = 31 * result + (italic?.hashCode() ?: 0)
result = 31 * result + (underlined?.hashCode() ?: 0)
result = 31 * result + (strikethrough?.hashCode() ?: 0)
result = 31 * result + (obfuscated?.hashCode() ?: 0)
result = 31 * result + (clickEvent?.hashCode() ?: 0)
result = 31 * result + (hoverEvent?.hashCode() ?: 0)
result = 31 * result + (insertion?.hashCode() ?: 0)
return result
}
override fun toString(): String {
return "ChatStyle(hasParent=${parent != null}, color=$color, bold=$bold, italic=$italic, underlined=$underlined, strikethrough=$strikethrough, obfuscated=$obfuscated, clickEvent=$clickEvent, hoverEvent=$hoverEvent, insertion=$insertion)"
}
}
| gpl-3.0 | c2f08446cf9d37dcacef6695f344f5ff | 33.247104 | 245 | 0.592108 | 4.933259 | false | false | false | false |
dhis2/dhis2-android-sdk | core/src/main/java/org/hisp/dhis/android/core/category/CategoryOptionComboService.kt | 1 | 3526 | /*
* 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.category
import dagger.Reusable
import io.reactivex.Single
import java.util.Date
import javax.inject.Inject
@Reusable
class CategoryOptionComboService @Inject constructor(
private val categoryOptionRepository: CategoryOptionCollectionRepository
) {
fun blockingHasAccess(categoryOptionComboUid: String, date: Date?, orgUnitUid: String? = null): Boolean {
val categoryOptions = categoryOptionRepository
.byCategoryOptionComboUid(categoryOptionComboUid)
.blockingGet()
return blockingIsAssignedToOrgUnit(categoryOptionComboUid, orgUnitUid) &&
blockingHasWriteAccess(categoryOptions) &&
isInOptionRange(categoryOptions, date)
}
fun blockingHasWriteAccess(
categoryOptions: List<CategoryOption>,
): Boolean {
return categoryOptions.none { it.access().data().write() == false }
}
fun blockingIsAssignedToOrgUnit(
categoryOptionComboUid: String,
orgUnitUid: String?
): Boolean {
return orgUnitUid?.let {
val categoryOptions = categoryOptionRepository
.byCategoryOptionComboUid(categoryOptionComboUid)
.withOrganisationUnits()
.blockingGet()
categoryOptions.all { categoryOption ->
categoryOption.organisationUnits()?.any {
it.uid() == orgUnitUid
} ?: true
}
} ?: true
}
fun hasAccess(categoryOptionComboUid: String, date: Date?): Single<Boolean> {
return Single.fromCallable { blockingHasAccess(categoryOptionComboUid, date) }
}
fun isInOptionRange(options: List<CategoryOption>, date: Date?): Boolean {
return date?.let {
options.all { option ->
option.startDate()?.before(date) ?: true && option.endDate()?.after(date) ?: true
}
} ?: true
}
}
| bsd-3-clause | 2e016395cc7a0f154333a159039b2b95 | 40.482353 | 109 | 0.700794 | 4.994334 | false | false | false | false |
mikepenz/FastAdapter | app/src/main/java/com/mikepenz/fastadapter/app/model/ModelIconItem.kt | 1 | 1996 | package com.mikepenz.fastadapter.app.model
import android.view.View
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.mikepenz.fastadapter.app.R
import com.mikepenz.fastadapter.app.utils.getThemeColor
import com.mikepenz.fastadapter.items.ModelAbstractItem
import com.mikepenz.iconics.IconicsDrawable
import com.mikepenz.iconics.utils.colorInt
import com.mikepenz.iconics.view.IconicsImageView
/**
* Created by mikepenz on 28.12.15.
*/
open class ModelIconItem(icon: IconModel) : ModelAbstractItem<IconModel, ModelIconItem.ViewHolder>(icon) {
/**
* defines the type defining this item. must be unique. preferably an id
*
* @return the type
*/
override val type: Int
get() = R.id.fastadapter_model_icon_item_id
/**
* defines the layout which will be used for this item in the list
*
* @return the layout for this item
*/
override val layoutRes: Int
get() = R.layout.icon_item
/**
* binds the data of this item onto the viewHolder
*
* @param holder the viewHolder of this item
*/
override fun bindView(holder: ViewHolder, payloads: List<Any>) {
super.bindView(holder, payloads)
//define our data for the view
holder.image.icon = IconicsDrawable(holder.image.context, model.icon).apply {
colorInt = holder.view.context.getThemeColor(R.attr.colorOnSurface)
}
holder.name.text = model.icon.name
}
override fun unbindView(holder: ViewHolder) {
super.unbindView(holder)
holder.image.setImageDrawable(null)
holder.name.text = null
}
override fun getViewHolder(v: View): ViewHolder {
return ViewHolder(v)
}
/**
* our ViewHolder
*/
class ViewHolder(val view: View) : RecyclerView.ViewHolder(view) {
var name: TextView = view.findViewById(R.id.name)
var image: IconicsImageView = view.findViewById(R.id.icon)
}
}
| apache-2.0 | 4d37c044275b284a2ab5285e4197b932 | 29.242424 | 106 | 0.682365 | 4.132505 | false | false | false | false |
dahlstrom-g/intellij-community | platform/script-debugger/debugger-ui/src/org/jetbrains/debugger/frame/CallFrameView.kt | 12 | 4189 | // 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.debugger.frame
import com.intellij.icons.AllIcons
import com.intellij.openapi.util.NlsSafe
import com.intellij.ui.ColoredTextContainer
import com.intellij.ui.SimpleTextAttributes
import com.intellij.xdebugger.XDebuggerBundle
import com.intellij.xdebugger.evaluation.XDebuggerEvaluator
import com.intellij.xdebugger.frame.XCompositeNode
import com.intellij.xdebugger.frame.XStackFrame
import com.intellij.xdebugger.frame.XValueChildrenList
import org.jetbrains.concurrency.Promise
import org.jetbrains.debugger.*
// isInLibraryContent call could be costly, so we compute it only once (our customizePresentation called on each repaint)
class CallFrameView @JvmOverloads constructor(val callFrame: CallFrame,
override val viewSupport: DebuggerViewSupport,
val script: Script? = null,
sourceInfo: SourceInfo? = null,
isInLibraryContent: Boolean? = null,
override val vm: Vm? = null,
val methodReturnValue: Variable? = null) : XStackFrame(), VariableContext {
private val sourceInfo = sourceInfo ?: viewSupport.getSourceInfo(script, callFrame)
private val isInLibraryContent: Boolean = isInLibraryContent ?: (this.sourceInfo != null && viewSupport.isInLibraryContent(this.sourceInfo, script))
private var evaluator: XDebuggerEvaluator? = null
override fun getEqualityObject(): Any = callFrame.equalityObject
override fun computeChildren(node: XCompositeNode) {
node.setAlreadySorted(true)
methodReturnValue?.let {
val list = XValueChildrenList.singleton(VariableView(methodReturnValue, this))
node.addChildren(list, false)
}
createAndAddScopeList(node, callFrame.variableScopes, this, callFrame)
}
override val evaluateContext: EvaluateContext
get() = callFrame.evaluateContext
override fun watchableAsEvaluationExpression(): Boolean = true
override val memberFilter: Promise<MemberFilter>
get() = viewSupport.getMemberFilter(this)
fun getMemberFilter(scope: Scope): Promise<MemberFilter> = createVariableContext(scope, this, callFrame).memberFilter
override fun getEvaluator(): XDebuggerEvaluator? {
if (evaluator == null) {
evaluator = viewSupport.createFrameEvaluator(this)
}
return evaluator
}
override fun getSourcePosition(): SourceInfo? = sourceInfo
override fun customizePresentation(component: ColoredTextContainer) {
if (sourceInfo == null) {
val scriptName = if (script == null) XDebuggerBundle.message("stack.frame.function.unknown") else script.url.trimParameters().toDecodedForm()
val line = callFrame.line
component.append(if (line == -1) scriptName else "$scriptName:$line", SimpleTextAttributes.ERROR_ATTRIBUTES)
return
}
val fileName = sourceInfo.file.name
val line = sourceInfo.line + 1
val textAttributes =
if (isInLibraryContent || callFrame.isFromAsyncStack) SimpleTextAttributes.GRAYED_ATTRIBUTES
else SimpleTextAttributes.REGULAR_ATTRIBUTES
@NlsSafe val functionName = sourceInfo.functionName
if (functionName == null || (functionName.isEmpty() && callFrame.hasOnlyGlobalScope)) {
if (fileName.startsWith("index.")) {
sourceInfo.file.parent?.let {
component.append("${it.name}/", textAttributes)
}
}
component.append("$fileName:$line", textAttributes)
}
else {
if (functionName.isEmpty()) {
component.append(XDebuggerBundle.message("stack.frame.function.name.anonymous"), if (isInLibraryContent) SimpleTextAttributes.GRAYED_ITALIC_ATTRIBUTES else SimpleTextAttributes.REGULAR_ITALIC_ATTRIBUTES)
}
else {
component.append(functionName, textAttributes)
}
component.append("(), $fileName:$line", textAttributes)
}
component.setIcon(AllIcons.Debugger.Frame)
}
} | apache-2.0 | 7d401d7877f46ec2a4dcabf34704a51d | 43.105263 | 211 | 0.705419 | 5.31599 | false | false | false | false |
awsdocs/aws-doc-sdk-examples | kotlin/usecases/serverless_rds/src/main/kotlin/com/example/demo/DemoApplication.kt | 1 | 3077 | /*
Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
SPDX-License-Identifier: Apache-2.0
*/
package com.example.demo
import kotlinx.coroutines.runBlocking
import org.springframework.boot.autoconfigure.SpringBootApplication
import org.springframework.boot.runApplication
import org.springframework.web.bind.annotation.CrossOrigin
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.PathVariable
import org.springframework.web.bind.annotation.PostMapping
import org.springframework.web.bind.annotation.PutMapping
import org.springframework.web.bind.annotation.RequestBody
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RestController
import java.io.IOException
@SpringBootApplication
open class DemoApplication
fun main(args: Array<String>) {
runApplication<DemoApplication>(*args)
}
@CrossOrigin(origins = ["*"])
@RestController
@RequestMapping("api/")
class MessageResource {
// Add a new item.
@PostMapping("/add")
fun addItems(@RequestBody payLoad: Map<String, Any>): String = runBlocking {
val injectWorkService = InjectWorkService()
val nameVal = "user"
val guideVal = payLoad.get("guide").toString()
val descriptionVal = payLoad.get("description").toString()
val statusVal = payLoad.get("status").toString()
// Create a Work Item object.
val myWork = WorkItem()
myWork.guide = guideVal
myWork.description = descriptionVal
myWork.status = statusVal
myWork.name = nameVal
val id = injectWorkService.injestNewSubmission(myWork)
return@runBlocking "Item $id added successfully!"
}
// Retrieve items.
@GetMapping("items/{state}")
fun getItems(@PathVariable state: String): MutableList<WorkItem> = runBlocking {
val retrieveItems = RetrieveItems()
val list: MutableList<WorkItem>
val name = "user"
if (state.compareTo("archive") == 0) {
list = retrieveItems.getItemsDataSQL(name, 1)
} else {
list = retrieveItems.getItemsDataSQL(name, 0)
}
return@runBlocking list
}
// Flip an item from Active to Archive.
@PutMapping("mod/{id}")
fun modUser(@PathVariable id: String): String = runBlocking {
val retrieveItems = RetrieveItems()
retrieveItems.flipItemArchive(id)
return@runBlocking id
}
// Send a report through Amazon SES.
@PutMapping("report/{email}")
fun sendReport(@PathVariable email: String): String = runBlocking {
val retrieveItems = RetrieveItems()
val nameVal = "user"
val sendMsg = SendMessage()
val xml = retrieveItems.getItemsDataSQLReport(nameVal, 0)
try {
sendMsg.send(email, xml)
} catch (e: IOException) {
e.stackTrace
}
return@runBlocking "Report was sent"
}
}
| apache-2.0 | 058248cce145876cd46a7480e21fb7c2 | 32.965909 | 84 | 0.671108 | 4.446532 | false | false | false | false |
gamerson/liferay-blade-samples | gradle/apps/kotlin-portlet/src/main/kotlin/com/liferay/blade/samples/portlet/kotlin/KotlinGreeterPortlet.kt | 1 | 2038 | /**
* Copyright 2000-present Liferay, 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.liferay.blade.samples.portlet.kotlin
import com.liferay.blade.samples.portlet.kotlin.constants.KotlinGreeterPortletKeys
import com.liferay.portal.kernel.portlet.bridges.mvc.MVCPortlet
import java.io.IOException
import javax.portlet.Portlet
import javax.portlet.PortletException
import javax.portlet.RenderRequest
import javax.portlet.RenderResponse
import org.osgi.service.component.annotations.Component
/**
* @author Liferay
*/
@Component(
immediate = true,
property = arrayOf(
"com.liferay.portlet.css-class-wrapper=portlet-greeter",
"com.liferay.portlet.display-category=category.sample",
"com.liferay.portlet.instanceable=true",
"javax.portlet.display-name=Kotlin Greeter Portlet",
"javax.portlet.init-param.template-path=/",
"javax.portlet.init-param.view-template=/view.jsp",
"javax.portlet.name=" + KotlinGreeterPortletKeys.KotlinGreeterPortlet,
"javax.portlet.security-role-ref=power-user,user"
),
service = arrayOf(Portlet::class)
)
class KotlinGreeterPortlet : MVCPortlet() {
@Throws(IOException::class, PortletException::class)
override fun doView(
renderRequest: RenderRequest, renderResponse: RenderResponse) {
val greeting: String? = renderRequest.getAttribute(KotlinGreeterPortletKeys.GreeterMessage) as String?
if (greeting == null) {
renderRequest.setAttribute(KotlinGreeterPortletKeys.GreeterMessage, "")
}
super.doView(renderRequest, renderResponse)
}
} | apache-2.0 | abdc52a4c000b5d3a2e33a7bc831bd40 | 31.365079 | 104 | 0.77527 | 3.430976 | false | false | false | false |
zanata/zanata-platform | server/services/src/test/java/org/zanata/email/multipart.kt | 1 | 986 | package org.zanata.email
import org.assertj.core.api.Assertions
import javax.mail.Multipart
import javax.mail.internet.MimeMessage
/**
* @author Sean Flanigan <a href="mailto:sflaniga@redhat.com">sflaniga@redhat.com</a>
*/
internal data class MultipartContents(val text: String, val html: String)
internal fun extractMultipart(message: MimeMessage): MultipartContents {
val multipart = message.content as Multipart
// one for html, one for text
Assertions.assertThat(multipart.count).isEqualTo(2)
// Text should appear first (because HTML is the preferred format)
val textPart = multipart.getBodyPart(0)
Assertions.assertThat(textPart.dataHandler.contentType).isEqualTo(
"text/plain; charset=UTF-8")
val htmlPart = multipart.getBodyPart(1)
Assertions.assertThat(htmlPart.dataHandler.contentType).isEqualTo(
"text/html; charset=UTF-8")
return MultipartContents(textPart.content as String, htmlPart.content as String)
}
| lgpl-2.1 | ec3b5f94297421e9843d07fbf2e78bd0 | 35.518519 | 85 | 0.751521 | 4.00813 | false | false | false | false |
gmariotti/kotlin-koans | util/src/koansTestUtil.kt | 2 | 338 | package koans.util
fun String.toMessage() = "The function '$this' is implemented incorrectly"
fun String.toMessageInEquals() = toMessage().inEquals()
fun String.inEquals() = this + ":" + if (mode == Mode.WEB_DEMO) " " else "<br><br>"
private enum class Mode { WEB_DEMO, EDUCATIONAL_PLUGIN }
private val mode = Mode.EDUCATIONAL_PLUGIN
| mit | 07d620499052391589397a45e7d2cb01 | 32.8 | 83 | 0.713018 | 3.484536 | false | false | false | false |
google/intellij-community | plugins/kotlin/code-insight/intentions-k2/src/org/jetbrains/kotlin/idea/k2/codeinsight/intentions/AddNameToArgumentIntention.kt | 3 | 3762 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.kotlin.idea.k2.codeinsight.intentions
import com.intellij.codeInsight.intention.LowPriorityAction
import com.intellij.psi.PsiElement
import org.jetbrains.kotlin.analysis.api.KtAnalysisSession
import org.jetbrains.kotlin.analysis.api.calls.KtFunctionCall
import org.jetbrains.kotlin.analysis.api.calls.singleFunctionCallOrNull
import org.jetbrains.kotlin.analysis.api.calls.symbol
import org.jetbrains.kotlin.config.LanguageFeature
import org.jetbrains.kotlin.idea.base.projectStructure.languageVersionSettings
import org.jetbrains.kotlin.idea.codeinsight.api.applicators.AbstractKotlinApplicatorBasedIntention
import org.jetbrains.kotlin.idea.codeinsight.api.applicators.inputProvider
import org.jetbrains.kotlin.idea.codeinsights.impl.base.applicators.AddArgumentNamesApplicators
import org.jetbrains.kotlin.idea.codeinsights.impl.base.applicators.ApplicabilityRanges
import org.jetbrains.kotlin.name.Name
import org.jetbrains.kotlin.psi.KtCallElement
import org.jetbrains.kotlin.psi.KtContainerNode
import org.jetbrains.kotlin.psi.KtValueArgument
import org.jetbrains.kotlin.psi.KtValueArgumentList
internal class AddNameToArgumentIntention :
AbstractKotlinApplicatorBasedIntention<KtValueArgument, AddArgumentNamesApplicators.SingleArgumentInput>(KtValueArgument::class),
LowPriorityAction {
override fun getApplicator() = AddArgumentNamesApplicators.singleArgumentApplicator
override fun getApplicabilityRange() = ApplicabilityRanges.VALUE_ARGUMENT_EXCLUDING_LAMBDA
override fun getInputProvider() = inputProvider { element: KtValueArgument ->
val argumentList = element.parent as? KtValueArgumentList ?: return@inputProvider null
val shouldBeLastUnnamed =
!element.languageVersionSettings.supportsFeature(LanguageFeature.MixedNamedArgumentsInTheirOwnPosition)
if (shouldBeLastUnnamed && element != argumentList.arguments.last { !it.isNamed() }) return@inputProvider null
val callElement = argumentList.parent as? KtCallElement ?: return@inputProvider null
val resolvedCall = callElement.resolveCall().singleFunctionCallOrNull() ?: return@inputProvider null
if (!resolvedCall.symbol.hasStableParameterNames) {
return@inputProvider null
}
getArgumentNameIfCanBeUsedForCalls(element, resolvedCall)?.let(AddArgumentNamesApplicators::SingleArgumentInput)
}
override fun skipProcessingFurtherElementsAfter(element: PsiElement) = element is KtValueArgumentList ||
element is KtContainerNode || super.skipProcessingFurtherElementsAfter(element)
}
fun KtAnalysisSession.getArgumentNameIfCanBeUsedForCalls(argument: KtValueArgument, resolvedCall: KtFunctionCall<*>): Name? {
val valueParameterSymbol = resolvedCall.argumentMapping[argument.getArgumentExpression()]?.symbol ?: return null
if (valueParameterSymbol.isVararg) {
if (argument.languageVersionSettings.supportsFeature(LanguageFeature.ProhibitAssigningSingleElementsToVarargsInNamedForm) &&
!argument.isSpread
) {
return null
}
// We can only add the parameter name for an argument for a vararg parameter if it's the ONLY argument for the parameter. E.g.,
//
// fun foo(vararg i: Int) {}
//
// foo(1, 2) // Can NOT add `i = ` to either argument
// foo(1) // Can change to `i = 1`
val varargArgumentCount = resolvedCall.argumentMapping.values.count { it.symbol == valueParameterSymbol }
if (varargArgumentCount != 1) {
return null
}
}
return valueParameterSymbol.name
} | apache-2.0 | 06d4394fb267dc485b50384e1bf1494e | 51.263889 | 135 | 0.77512 | 5.125341 | false | false | false | false |
Atsky/haskell-idea-plugin | plugin/src/org/jetbrains/haskell/vfs/TarGzArchive.kt | 1 | 915 | package org.jetbrains.haskell.vfs
import java.io.File
import java.io.BufferedInputStream
import java.io.InputStream
import org.apache.commons.compress.compressors.gzip.GzipCompressorInputStream
import org.apache.commons.compress.archivers.tar.TarArchiveInputStream
import java.io.FileInputStream
import java.util.ArrayList
/**
* Created by atsky on 12/12/14.
*/
class TarGzArchive(val file : File) {
val filesList : List<String>
init {
val bin = BufferedInputStream(FileInputStream(file))
val gzIn = GzipCompressorInputStream(bin)
val tarArchiveInputStream = TarArchiveInputStream(gzIn)
var file = ArrayList<String>()
while (true) {
val entry = tarArchiveInputStream.nextTarEntry
if (entry == null) {
break
}
file.add(entry.name)
}
filesList = file
bin.close()
}
} | apache-2.0 | 438a5888112ddb41fe25ecda17c1a061 | 23.105263 | 77 | 0.66776 | 4.463415 | false | false | false | false |
NeatoRobotics/neato-sdk-android | Neato-SDK/neato-sdk-android/src/main/java/com/neatorobotics/sdk/android/robotservices/housecleaning/HouseCleaningBasic3Service.kt | 1 | 711 | /*
* Copyright (c) 2019.
* Neato Robotics Inc.
*/
package com.neatorobotics.sdk.android.robotservices.housecleaning
class HouseCleaningBasic3Service : HouseCleaningService() {
override val isMultipleZonesCleaningSupported: Boolean
get() = false
override val isEcoModeSupported: Boolean
get() = true
override val isTurboModeSupported: Boolean
get() = true
override val isExtraCareModeSupported: Boolean
get() = true
override val isCleaningAreaSupported: Boolean
get() = false
override val isCleaningFrequencySupported: Boolean
get() = false
companion object {
private const val TAG = "HouseCleaningBasic3"
}
}
| mit | 2f2cf44148b9271b4ee31233971f75d1 | 20.545455 | 65 | 0.68917 | 4.677632 | false | false | false | false |
nathanj/ogsdroid | app/src/main/java/com/ogs/Challenge.kt | 1 | 4569 | package com.ogs
import org.json.JSONException
import org.json.JSONObject
class Challenge : Comparable<Challenge> {
var challengeId: Int = 0
var name: String = ""
var username: String = ""
var ranked: Boolean = false
var rank: Int = 0
var minRank: Int = 0
var maxRank: Int = 0
var handicap: Int = 0
var timePerMove: Int = 0
var width: Int = 0
var height: Int = 0
var timeControlParameters: JSONObject? = null
constructor(id: Int) {
challengeId = id
}
constructor(obj: JSONObject) {
try {
challengeId = obj.getInt("challenge_id")
username = obj.getString("username")
name = obj.getString("name")
timePerMove = obj.getInt("time_per_move")
ranked = obj.getBoolean("ranked")
rank = obj.getInt("rank")
minRank = obj.getInt("min_rank")
maxRank = obj.getInt("max_rank")
handicap = obj.getInt("handicap")
width = obj.getInt("width")
height = obj.getInt("height")
timeControlParameters = obj.getJSONObject("time_control_parameters")
} catch (e: JSONException) {
e.printStackTrace()
}
}
private fun rankToString(rank: Int): String {
if (rank < 30)
return String.format("%d Kyu", 30 - rank)
else
return String.format("%d Dan", rank - 30 + 1)
}
override fun toString(): String {
val handicapStr = if (handicap == -1)
"Auto Handicap"
else if (handicap == 0)
"No Handicap"
else
String.format("%d Stones", handicap)
return String.format("%s - %dx%d - %s (%s) - %s - %s - %s",
name, width, height, username, rankToString(rank),
if (ranked) "Ranked" else "Casual",
handicapStr,
formatTime())
}
fun prettyTime(time: Int): String {
if (time > 24 * 3600)
return (time / 24 / 3600).toString() + "d"
else if (time > 3600)
return (time / 3600).toString() + "h"
else if (time > 60)
return (time / 60).toString() + "m"
return time.toString() + "s"
}
fun formatTime(): String {
try {
val tcp = timeControlParameters
if (tcp != null) {
val control = tcp.getString("time_control")
if (control == "byoyomi") {
val periodTime = tcp.getInt("period_time")
val mainTime = tcp.getInt("main_time")
val periods = tcp.getInt("periods")
return "${prettyTime(mainTime)} + ${prettyTime(periodTime)} x $periods"
} else if (control == "fischer") {
val initialTime = tcp.getInt("initial_time")
val maxTime = tcp.getInt("max_time")
val increment = tcp.getInt("time_increment")
return "${prettyTime(initialTime)} + ${prettyTime(increment)} up to ${prettyTime(maxTime)}"
} else if (control == "canadian") {
val periodTime = tcp.getInt("period_time")
val mainTime = tcp.getInt("main_time")
val stonesPerPeriod = tcp.getInt("stones_per_period")
return "${prettyTime(mainTime)} + ${prettyTime(periodTime)} per $stonesPerPeriod stones"
} else if (control == "absolute") {
val totalTime = tcp.getInt("total_time")
return prettyTime(totalTime)
} else if (control == "simple") {
val perMove = tcp.getInt("per_move")
return prettyTime(perMove)
} else {
System.err.println("error: control = $control tcp=$tcp")
}
}
} catch (ex: JSONException) {
// nothing, move along
}
return prettyTime(timePerMove) + " / move"
}
override fun equals(other: Any?): Boolean {
if (other is Challenge)
return other.challengeId == challengeId
else
return false
}
fun canAccept(myRanking: Int): Boolean {
return myRanking >= minRank && myRanking <= maxRank && (!ranked || Math.abs(myRanking - rank) <= 9)
}
override fun compareTo(other: Challenge): Int {
if (other.timePerMove == timePerMove)
return rank - other.rank
return timePerMove - other.timePerMove
}
}
| mit | 2d2797b7ee571efb1695d8dc7503079f | 34.976378 | 111 | 0.521121 | 4.310377 | false | false | false | false |
allotria/intellij-community | platform/platform-impl/src/com/intellij/diagnostic/JetBrainsAccountDialog.kt | 1 | 2964 | // 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.diagnostic
import com.intellij.credentialStore.CredentialAttributes
import com.intellij.credentialStore.Credentials
import com.intellij.credentialStore.RememberCheckBoxState
import com.intellij.ide.BrowserUtil
import com.intellij.ide.passwordSafe.PasswordSafe
import com.intellij.openapi.project.Project
import com.intellij.ui.UIBundle
import com.intellij.ui.components.CheckBox
import com.intellij.ui.components.dialog
import com.intellij.ui.layout.*
import com.intellij.util.io.encodeUrlQueryParameter
import com.intellij.util.text.nullize
import java.awt.Component
import javax.swing.JPasswordField
import javax.swing.JTextField
@JvmOverloads
fun askJBAccountCredentials(parent: Component, project: Project?, authFailed: Boolean = false): Credentials? {
val credentials = ErrorReportConfigurable.getCredentials()
val remember = if (credentials?.userName == null) PasswordSafe.instance.isRememberPasswordByDefault // EA credentials were never stored
else !credentials.password.isNullOrEmpty() // a password was stored already
val prompt = if (authFailed) DiagnosticBundle.message("error.report.auth.failed")
else DiagnosticBundle.message("error.report.auth.prompt")
val userField = JTextField(credentials?.userName)
val passwordField = JPasswordField(credentials?.getPasswordAsString())
val rememberCheckBox = CheckBox(UIBundle.message("auth.remember.cb"), remember)
val panel = panel {
noteRow(prompt)
row(DiagnosticBundle.message("error.report.auth.user")) { userField(growPolicy = GrowPolicy.SHORT_TEXT) }
row(DiagnosticBundle.message("error.report.auth.pass")) { passwordField() }
row {
rememberCheckBox()
right {
link(DiagnosticBundle.message("error.report.auth.restore")) {
val userName = userField.text.trim().encodeUrlQueryParameter()
BrowserUtil.browse("https://account.jetbrains.com/forgot-password?username=$userName")
}
}
}
noteRow(DiagnosticBundle.message("error.report.auth.enlist", "https://account.jetbrains.com/login?signup"))
}
val dialog = dialog(
title = DiagnosticBundle.message("error.report.auth.title"),
panel = panel,
focusedComponent = if (credentials?.userName == null) userField else passwordField,
project = project,
parent = if (parent.isShowing) parent else null)
if (!dialog.showAndGet()) {
return null
}
val userName = userField.text.nullize(true)
val password = passwordField.password
val passwordToRemember = if (rememberCheckBox.isSelected) password else null
RememberCheckBoxState.update(rememberCheckBox)
PasswordSafe.instance.set(CredentialAttributes(ErrorReportConfigurable.SERVICE_NAME, userName), Credentials(userName, passwordToRemember))
return Credentials(userName, password)
}
| apache-2.0 | 5058431d8be56f9fd45286e7a640a2dc | 44.6 | 140 | 0.767544 | 4.457143 | false | false | false | false |
allotria/intellij-community | python/python-grazie/src/com/intellij/grazie/ide/language/python/PythonGrammarCheckingStrategy.kt | 2 | 2049 | // 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.language.python
import com.intellij.grazie.grammar.strategy.BaseGrammarCheckingStrategy
import com.intellij.grazie.grammar.strategy.GrammarCheckingStrategy
import com.intellij.grazie.grammar.strategy.StrategyUtils
import com.intellij.grazie.grammar.strategy.impl.RuleGroup
import com.intellij.psi.PsiElement
import com.intellij.psi.impl.source.tree.LeafPsiElement
import com.intellij.psi.impl.source.tree.PsiCommentImpl
import com.intellij.psi.util.elementType
import com.jetbrains.python.PyTokenTypes
import com.jetbrains.python.PyTokenTypes.FSTRING_TEXT
import com.jetbrains.python.psi.PyFormattedStringElement
import com.jetbrains.python.psi.PyStringLiteralExpression
internal class PythonGrammarCheckingStrategy : BaseGrammarCheckingStrategy {
override fun isMyContextRoot(element: PsiElement) = element is PsiCommentImpl || element.elementType in PyTokenTypes.STRING_NODES
override fun getContextRootTextDomain(root: PsiElement) = when (root.elementType) {
PyTokenTypes.DOCSTRING -> GrammarCheckingStrategy.TextDomain.DOCS
PyTokenTypes.END_OF_LINE_COMMENT -> GrammarCheckingStrategy.TextDomain.COMMENTS
in PyTokenTypes.STRING_NODES -> GrammarCheckingStrategy.TextDomain.LITERALS
else -> GrammarCheckingStrategy.TextDomain.NON_TEXT
}
override fun isAbsorb(element: PsiElement): Boolean {
if (element.parent is PyFormattedStringElement) {
return element !is LeafPsiElement || element.elementType != FSTRING_TEXT
}
return false
}
override fun getIgnoredRuleGroup(root: PsiElement, child: PsiElement) = if (root is PyStringLiteralExpression) {
RuleGroup.LITERALS
}
else null
override fun getStealthyRanges(root: PsiElement, text: CharSequence) = when (root) {
is PsiCommentImpl -> StrategyUtils.indentIndexes(text, setOf(' ', '\t', '#'))
else -> StrategyUtils.indentIndexes(text, setOf(' ', '\t'))
}
}
| apache-2.0 | 70ca0f7c5da2114cf2cc2844c58b703a | 45.568182 | 140 | 0.79795 | 4.242236 | false | false | false | false |
allotria/intellij-community | java/java-impl/src/com/intellij/refactoring/extractMethod/newImpl/inplace/LegacyMethodExtractor.kt | 1 | 2841 | // Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.refactoring.extractMethod.newImpl.inplace
import com.intellij.openapi.editor.Editor
import com.intellij.psi.PsiClass
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiMethod
import com.intellij.psi.PsiMethodCallExpression
import com.intellij.psi.search.searches.MethodReferencesSearch
import com.intellij.psi.util.PsiTreeUtil
import com.intellij.refactoring.extractMethod.ExtractMethodHandler
import com.intellij.refactoring.extractMethod.ExtractMethodProcessor
import com.intellij.refactoring.util.duplicates.DuplicatesImpl
class LegacyMethodExtractor: InplaceExtractMethodProvider {
var processor: ExtractMethodProcessor? = null
override fun extract(targetClass: PsiClass, elements: List<PsiElement>, methodName: String, makeStatic: Boolean): Pair<PsiMethod, PsiMethodCallExpression> {
val project = targetClass.project
val processor = ExtractMethodHandler.getProcessor(project, elements.toTypedArray(), targetClass.containingFile, false)
processor ?: throw IllegalStateException("Failed to create processor for selected elements")
processor.prepare()
processor.prepareVariablesAndName()
processor.methodName = methodName
processor.targetClass = targetClass
processor.isStatic = makeStatic
processor.prepareNullability()
ExtractMethodHandler.extractMethod(project, processor)
val method = processor.extractedMethod
val call = findSingleMethodCall(method)!!
this.processor = processor
return Pair(method, call)
}
override fun extractInDialog(targetClass: PsiClass, elements: List<PsiElement>, methodName: String, makeStatic: Boolean) {
val project = targetClass.project
val file = targetClass.containingFile
val processor = ExtractMethodHandler.getProcessor(project, elements.toTypedArray(), file, false)
if (processor != null) {
ExtractMethodHandler.invokeOnElements(project, processor, file, false)
}
}
override fun postprocess(editor: Editor, method: PsiMethod) {
val handler = processor ?: return
val project = editor.project ?: return
val methodCall = findSingleMethodCall(method) ?: return
handler.extractedMethod = method
handler.methodCall = methodCall
handler.methodName = method.name
handler.parametrizedDuplicates?.apply {
setParametrizedMethod(method)
setParametrizedCall(methodCall)
}
DuplicatesImpl.processDuplicates(handler, project, editor)
}
private fun findSingleMethodCall(method: PsiMethod): PsiMethodCallExpression? {
val reference = MethodReferencesSearch.search(method).single().element
return PsiTreeUtil.getParentOfType(reference, PsiMethodCallExpression::class.java, false)
}
} | apache-2.0 | 22e020cba8632809988898b7d227e84f | 44.111111 | 158 | 0.787751 | 5.028319 | false | false | false | false |
Kotlin/kotlinx.coroutines | kotlinx-coroutines-core/jvm/src/internal/FastServiceLoader.kt | 1 | 6915 | /*
* Copyright 2016-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license.
*/
package kotlinx.coroutines.internal
import java.io.*
import java.net.*
import java.util.*
import java.util.jar.*
import java.util.zip.*
import kotlin.collections.ArrayList
/**
* Don't use JvmField here to enable R8 optimizations via "assumenosideeffects"
*/
internal val ANDROID_DETECTED = runCatching { Class.forName("android.os.Build") }.isSuccess
/**
* A simplified version of [ServiceLoader].
* FastServiceLoader locates and instantiates all service providers named in configuration
* files placed in the resource directory <tt>META-INF/services</tt>.
*
* The main difference between this class and classic service loader is in skipping
* verification JARs. A verification requires reading the whole JAR (and it causes problems and ANRs on Android devices)
* and prevents only trivial checksum issues. See #878.
*
* If any error occurs during loading, it fallbacks to [ServiceLoader], mostly to prevent R8 issues.
*/
internal object FastServiceLoader {
private const val PREFIX: String = "META-INF/services/"
/**
* This method attempts to load [MainDispatcherFactory] in Android-friendly way.
*
* If we are not on Android, this method fallbacks to a regular service loading,
* else we attempt to do `Class.forName` lookup for
* `AndroidDispatcherFactory` and `TestMainDispatcherFactory`.
* If lookups are successful, we return resultinAg instances because we know that
* `MainDispatcherFactory` API is internal and this is the only possible classes of `MainDispatcherFactory` Service on Android.
*
* Such intricate dance is required to avoid calls to `ServiceLoader.load` for multiple reasons:
* 1) It eliminates disk lookup on potentially slow devices on the Main thread.
* 2) Various Android toolchain versions by various vendors don't tend to handle ServiceLoader calls properly.
* Sometimes META-INF is removed from the resulting APK, sometimes class names are mangled, etc.
* While it is not the problem of `kotlinx.coroutines`, it significantly worsens user experience, thus we are workarounding it.
* Examples of such issues are #932, #1072, #1557, #1567
*
* We also use SL for [CoroutineExceptionHandler], but we do not experience the same problems and CEH is a public API
* that may already be injected vis SL, so we are not using the same technique for it.
*/
internal fun loadMainDispatcherFactory(): List<MainDispatcherFactory> {
val clz = MainDispatcherFactory::class.java
if (!ANDROID_DETECTED) {
return load(clz, clz.classLoader)
}
return try {
val result = ArrayList<MainDispatcherFactory>(2)
createInstanceOf(clz, "kotlinx.coroutines.android.AndroidDispatcherFactory")?.apply { result.add(this) }
createInstanceOf(clz, "kotlinx.coroutines.test.internal.TestMainDispatcherFactory")?.apply { result.add(this) }
result
} catch (e: Throwable) {
// Fallback to the regular SL in case of any unexpected exception
load(clz, clz.classLoader)
}
}
/*
* This method is inline to have a direct Class.forName("string literal") in the byte code to avoid weird interactions with ProGuard/R8.
*/
@Suppress("NOTHING_TO_INLINE")
private inline fun createInstanceOf(
baseClass: Class<MainDispatcherFactory>,
serviceClass: String
): MainDispatcherFactory? {
return try {
val clz = Class.forName(serviceClass, true, baseClass.classLoader)
baseClass.cast(clz.getDeclaredConstructor().newInstance())
} catch (e: ClassNotFoundException) { // Do not fail if TestMainDispatcherFactory is not found
null
}
}
private fun <S> load(service: Class<S>, loader: ClassLoader): List<S> {
return try {
loadProviders(service, loader)
} catch (e: Throwable) {
// Fallback to default service loader
ServiceLoader.load(service, loader).toList()
}
}
// Visible for tests
internal fun <S> loadProviders(service: Class<S>, loader: ClassLoader): List<S> {
val fullServiceName = PREFIX + service.name
// Filter out situations when both JAR and regular files are in the classpath (e.g. IDEA)
val urls = loader.getResources(fullServiceName)
val providers = urls.toList().flatMap { parse(it) }.toSet()
require(providers.isNotEmpty()) { "No providers were loaded with FastServiceLoader" }
return providers.map { getProviderInstance(it, loader, service) }
}
private fun <S> getProviderInstance(name: String, loader: ClassLoader, service: Class<S>): S {
val clazz = Class.forName(name, false, loader)
require(service.isAssignableFrom(clazz)) { "Expected service of class $service, but found $clazz" }
return service.cast(clazz.getDeclaredConstructor().newInstance())
}
private fun parse(url: URL): List<String> {
val path = url.toString()
// Fast-path for JARs
if (path.startsWith("jar")) {
val pathToJar = path.substringAfter("jar:file:").substringBefore('!')
val entry = path.substringAfter("!/")
// mind the verify = false flag!
(JarFile(pathToJar, false)).use { file ->
BufferedReader(InputStreamReader(file.getInputStream(ZipEntry(entry)), "UTF-8")).use { r ->
return parseFile(r)
}
}
}
// Regular path for everything else
return BufferedReader(InputStreamReader(url.openStream())).use { reader ->
parseFile(reader)
}
}
// JarFile does no implement Closesable on Java 1.6
private inline fun <R> JarFile.use(block: (JarFile) -> R): R {
var cause: Throwable? = null
try {
return block(this)
} catch (e: Throwable) {
cause = e
throw e
} finally {
try {
close()
} catch (closeException: Throwable) {
if (cause === null) throw closeException
cause.addSuppressed(closeException)
throw cause
}
}
}
private fun parseFile(r: BufferedReader): List<String> {
val names = mutableSetOf<String>()
while (true) {
val line = r.readLine() ?: break
val serviceName = line.substringBefore("#").trim()
require(serviceName.all { it == '.' || Character.isJavaIdentifierPart(it) }) { "Illegal service provider class name: $serviceName" }
if (serviceName.isNotEmpty()) {
names.add(serviceName)
}
}
return names.toList()
}
}
| apache-2.0 | 5984391293fc74aa3f89320fbaeb7077 | 42.21875 | 144 | 0.648156 | 4.647177 | false | false | false | false |
zdary/intellij-community | platform/vcs-log/impl/src/com/intellij/vcs/log/history/VcsLogFileHistoryProviderImpl.kt | 3 | 8322 | // Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.vcs.log.history
import com.google.common.util.concurrent.SettableFuture
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.registry.Registry
import com.intellij.openapi.vcs.FilePath
import com.intellij.openapi.vcs.VcsBundle
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.ui.content.TabGroupId
import com.intellij.vcs.log.*
import com.intellij.vcs.log.data.VcsLogData
import com.intellij.vcs.log.data.VcsLogStorage
import com.intellij.vcs.log.impl.*
import com.intellij.vcs.log.statistics.VcsLogUsageTriggerCollector
import com.intellij.vcs.log.ui.MainVcsLogUi
import com.intellij.vcs.log.ui.VcsLogUiEx
import com.intellij.vcs.log.ui.table.GraphTableModel
import com.intellij.vcs.log.util.VcsLogUtil
import com.intellij.vcs.log.util.VcsLogUtil.jumpToRow
import com.intellij.vcs.log.visible.VisiblePack
import com.intellij.vcs.log.visible.filters.VcsLogFilterObject
import com.intellij.vcs.log.visible.filters.matches
import com.intellij.vcsUtil.VcsUtil
import java.util.function.Function
fun isNewHistoryEnabled() = Registry.`is`("vcs.new.history")
class VcsLogFileHistoryProviderImpl : VcsLogFileHistoryProvider {
private val tabGroupId: TabGroupId = TabGroupId("History", VcsBundle.messagePointer("file.history.tab.name"), false)
override fun canShowFileHistory(project: Project, paths: Collection<FilePath>, revisionNumber: String?): Boolean {
if (!isNewHistoryEnabled()) return false
val dataManager = VcsProjectLog.getInstance(project).dataManager ?: return false
if (paths.size == 1) {
return canShowSingleFileHistory(project, dataManager, paths.single(), revisionNumber != null)
}
return revisionNumber == null && createPathsFilter(project, dataManager, paths) != null
}
private fun canShowSingleFileHistory(project: Project, dataManager: VcsLogData, path: FilePath, isRevisionHistory: Boolean): Boolean {
val root = VcsLogUtil.getActualRoot(project, path) ?: return false
return dataManager.index.isIndexingEnabled(root) ||
canShowHistoryInLog(dataManager, getCorrectedPath(project, path, root, isRevisionHistory), root)
}
override fun showFileHistory(project: Project, paths: Collection<FilePath>, revisionNumber: String?) {
val hash = revisionNumber?.let { HashImpl.build(it) }
val root = VcsLogUtil.getActualRoot(project, paths.first())!!
triggerFileHistoryUsage(project, paths, hash)
val logManager = VcsProjectLog.getInstance(project).logManager!!
val historyUiConsumer = { ui: VcsLogUiEx, firstTime: Boolean ->
if (hash != null) {
ui.jumpToNearestCommit(logManager.dataManager.storage, hash, root, true)
}
else if (firstTime) {
jumpToRow(ui, 0, true)
}
}
if (paths.size == 1) {
val correctedPath = getCorrectedPath(project, paths.single(), root, revisionNumber != null)
if (!canShowHistoryInLog(logManager.dataManager, correctedPath, root)) {
findOrOpenHistory(project, logManager, root, correctedPath, hash, historyUiConsumer)
return
}
}
findOrOpenFolderHistory(project, createHashFilter(hash, root), createPathsFilter(project, logManager.dataManager, paths)!!,
historyUiConsumer)
}
private fun canShowHistoryInLog(dataManager: VcsLogData,
correctedPath: FilePath,
root: VirtualFile): Boolean {
if (!correctedPath.isDirectory) {
return false
}
val logProvider = dataManager.logProviders[root] ?: return false
return VcsLogProperties.SUPPORTS_LOG_DIRECTORY_HISTORY.getOrDefault(logProvider)
}
private fun triggerFileHistoryUsage(project: Project, paths: Collection<FilePath>, hash: Hash?) {
VcsLogUsageTriggerCollector.triggerUsage(VcsLogUsageTriggerCollector.VcsLogEvent.HISTORY_SHOWN, { data ->
val kind = if (paths.size > 1) "multiple" else if (paths.first().isDirectory) "folder" else "file"
data.addData("kind", kind).addData("has_revision", hash != null)
}, project)
}
private fun findOrOpenHistory(project: Project, logManager: VcsLogManager,
root: VirtualFile, path: FilePath, hash: Hash?,
consumer: (VcsLogUiEx, Boolean) -> Unit) {
var fileHistoryUi = VcsLogContentUtil.findAndSelect(project, FileHistoryUi::class.java) { ui -> ui.matches(path, hash) }
val firstTime = fileHistoryUi == null
if (firstTime) {
val suffix = if (hash != null) " (" + hash.toShortString() + ")" else ""
fileHistoryUi = VcsLogContentUtil.openLogTab(project, logManager, tabGroupId, Function { path.name + suffix },
FileHistoryUiFactory(path, root, hash), true)
}
consumer(fileHistoryUi!!, firstTime)
}
private fun findOrOpenFolderHistory(project: Project, hashFilter: VcsLogFilter, pathsFilter: VcsLogFilter,
consumer: (VcsLogUiEx, Boolean) -> Unit) {
var ui = VcsLogContentUtil.findAndSelect(project, MainVcsLogUi::class.java) { logUi ->
matches(logUi.filterUi.filters, pathsFilter, hashFilter)
}
val firstTime = ui == null
if (firstTime) {
val filters = VcsLogFilterObject.collection(pathsFilter, hashFilter)
ui = VcsProjectLog.getInstance(project).openLogTab(filters) ?: return
ui.properties.set(MainVcsLogUiProperties.SHOW_ONLY_AFFECTED_CHANGES, true)
}
consumer(ui!!, firstTime)
}
private fun createPathsFilter(project: Project, dataManager: VcsLogData, paths: Collection<FilePath>): VcsLogFilter? {
val forRootFilter = mutableSetOf<VirtualFile>()
val forPathsFilter = mutableListOf<FilePath>()
for (path in paths) {
val root = VcsLogUtil.getActualRoot(project, path)
if (root == null) return null
if (!dataManager.roots.contains(root) ||
!VcsLogProperties.SUPPORTS_LOG_DIRECTORY_HISTORY.getOrDefault(dataManager.getLogProvider(root))) return null
val correctedPath = getCorrectedPath(project, path, root, false)
if (!correctedPath.isDirectory) return null
if (path.virtualFile == root) {
forRootFilter.add(root)
}
else {
forPathsFilter.add(correctedPath)
}
if (forPathsFilter.isNotEmpty() && forRootFilter.isNotEmpty()) return null
}
if (forPathsFilter.isNotEmpty()) return VcsLogFilterObject.fromPaths(forPathsFilter)
return VcsLogFilterObject.fromRoots(forRootFilter)
}
private fun createHashFilter(hash: Hash?, root: VirtualFile): VcsLogFilter {
if (hash == null) {
return VcsLogFilterObject.fromBranch(VcsLogUtil.HEAD)
}
return VcsLogFilterObject.fromCommit(CommitId(hash, root))
}
private fun matches(filters: VcsLogFilterCollection, pathsFilter: VcsLogFilter, hashFilter: VcsLogFilter): Boolean {
if (!filters.matches(hashFilter.key, pathsFilter.key)) {
return false
}
return filters.get(pathsFilter.key) == pathsFilter && filters.get(hashFilter.key) == hashFilter
}
private fun getCorrectedPath(project: Project, path: FilePath, root: VirtualFile,
isRevisionHistory: Boolean): FilePath {
var correctedPath = path
if (root != VcsUtil.getVcsRootFor(project, correctedPath) && correctedPath.isDirectory) {
correctedPath = VcsUtil.getFilePath(correctedPath.path, false)
}
if (!isRevisionHistory) {
return VcsUtil.getLastCommitPath(project, correctedPath)
}
return correctedPath
}
}
private fun VcsLogUiEx.jumpToNearestCommit(storage: VcsLogStorage, hash: Hash, root: VirtualFile, silently: Boolean) {
jumpTo(hash, { visiblePack: VisiblePack, h: Hash? ->
if (!storage.containsCommit(CommitId(h!!, root))) return@jumpTo GraphTableModel.COMMIT_NOT_FOUND
val commitIndex: Int = storage.getCommitIndex(h, root)
var rowIndex = visiblePack.visibleGraph.getVisibleRowIndex(commitIndex)
if (rowIndex == null) {
rowIndex = findVisibleAncestorRow(commitIndex, visiblePack)
}
rowIndex ?: GraphTableModel.COMMIT_DOES_NOT_MATCH
}, SettableFuture.create(), silently, true)
}
| apache-2.0 | bc7b58ebd99faedfd31e52217f0ef8e9 | 43.031746 | 140 | 0.715333 | 4.728409 | false | false | false | false |
io53/Android_RuuvitagScanner | app/src/main/java/com/ruuvi/station/settings/ui/AppSettingsBackgroundScanViewModel.kt | 1 | 2030 | package com.ruuvi.station.settings.ui
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import android.os.Build
import com.ruuvi.station.R
import com.ruuvi.station.app.preferences.Preferences
import com.ruuvi.station.util.BackgroundScanModes
class AppSettingsBackgroundScanViewModel (private val preferences: Preferences): ViewModel() {
private val scanMode = MutableLiveData<BackgroundScanModes>()
private val interval = MutableLiveData<Int>()
init {
scanMode.value = preferences.backgroundScanMode
interval.value = preferences.backgroundScanInterval
}
fun observeScanMode(): LiveData<BackgroundScanModes> = scanMode
fun observeInterval(): LiveData<Int> = interval
fun setBackgroundMode(mode: BackgroundScanModes){
preferences.backgroundScanMode = mode
}
fun setBackgroundScanInterval(newInterval: Int) {
preferences.backgroundScanInterval = newInterval
}
fun getPossibleScanModes() = listOf(
BackgroundScanModes.DISABLED,
BackgroundScanModes.BACKGROUND
)
fun getBatteryOptimizationMessageId(): Int {
val deviceManufacturer = Build.MANUFACTURER.toUpperCase()
val deviceApi = Build.VERSION.SDK_INT
return when (deviceManufacturer) {
SAMSUNG_MANUFACTURER ->
if (deviceApi <= Build.VERSION_CODES.M) {
R.string.background_scan_samsung23_instructions
} else {
R.string.background_scan_samsung_instructions
}
XIAOMI_MANUFACTURER -> R.string.background_scan_xiaomi_instructions
HUAWEI_MANUFACTURER -> R.string.background_scan_huawei_instructions
else -> R.string.background_scan_common_instructions
}
}
companion object {
const val SAMSUNG_MANUFACTURER = "SAMSUNG"
const val XIAOMI_MANUFACTURER = "XIAOMI"
const val HUAWEI_MANUFACTURER = "HUAWEI"
}
} | mit | 3b9d9f267e595bb6a293278aef98f94a | 33.423729 | 94 | 0.694581 | 4.776471 | false | false | false | false |
faceofcat/Tesla-Core-Lib | src/main/kotlin/net/ndrei/teslacorelib/items/TeslaBattery.kt | 1 | 6504 | package net.ndrei.teslacorelib.items
import cofh.redstoneflux.api.IEnergyContainerItem
import com.mojang.realmsclient.gui.ChatFormatting
import net.minecraft.client.util.ITooltipFlag
import net.minecraft.creativetab.CreativeTabs
import net.minecraft.item.ItemStack
import net.minecraft.nbt.NBTTagCompound
import net.minecraft.util.EnumFacing
import net.minecraft.util.NonNullList
import net.minecraft.util.ResourceLocation
import net.minecraft.world.World
import net.minecraftforge.common.capabilities.Capability
import net.minecraftforge.common.capabilities.ICapabilityProvider
import net.minecraftforge.common.util.Constants
import net.minecraftforge.common.util.INBTSerializable
import net.minecraftforge.energy.CapabilityEnergy
import net.minecraftforge.energy.EnergyStorage
import net.minecraftforge.fml.common.Optional
import net.minecraftforge.fml.relauncher.Side
import net.minecraftforge.fml.relauncher.SideOnly
import net.ndrei.teslacorelib.annotations.AutoRegisterItem
import net.ndrei.teslacorelib.compatibility.RFPowerProxy
import net.ndrei.teslacorelib.config.TeslaCoreLibConfig
/**
* Created by CF on 2017-06-27.
*/
@AutoRegisterItem(TeslaCoreLibConfig.REGISTER_BATTERY)
@Optional.Interface(iface = "cofh.redstoneflux.api.IEnergyContainerItem", modid = RFPowerProxy.MODID, striprefs = true)
object TeslaBattery
: CoreItem("battery"), IEnergyContainerItem {
init {
super
.setHasSubtypes(true)
.addPropertyOverride(ResourceLocation("power"), { stack, _, _ ->
val energy = stack.getCapability(CapabilityEnergy.ENERGY, null)
if (energy == null) {
0.0f
} else {
val thing = Math.round(energy.energyStored.toDouble() / energy.maxEnergyStored.toDouble() * 6)
Math.max(0, Math.min(6, thing)).toFloat()
}
})
}
override fun initCapabilities(stack: ItemStack?, nbt: NBTTagCompound?): ICapabilityProvider? {
return object: ICapabilityProvider, INBTSerializable<NBTTagCompound> {
private var storage = EnergyStorage(10000, 100, 100)
@Suppress("UNCHECKED_CAST")
override fun <T : Any?> getCapability(capability: Capability<T>, facing: EnumFacing?): T?
= if (capability == CapabilityEnergy.ENERGY) (this.storage as? T) else null
override fun hasCapability(capability: Capability<*>, facing: EnumFacing?)
= capability == CapabilityEnergy.ENERGY
override fun deserializeNBT(nbt: NBTTagCompound?) {
val capacity = if ((nbt != null) && nbt.hasKey("capacity", Constants.NBT.TAG_INT))
nbt.getInteger("capacity")
else 10000
val stored = if ((nbt != null) && nbt.hasKey("stored", Constants.NBT.TAG_INT))
nbt.getInteger("stored")
else 0
val inputRate = /*if ((nbt != null) && nbt.hasKey("input_rate", Constants.NBT.TAG_INT))
nbt.getInteger("input_rate")
else*/ 100
val outputRate = /*if ((nbt != null) && nbt.hasKey("output_rate", Constants.NBT.TAG_INT))
nbt.getInteger("output_rate")
else*/ 100
this.storage = EnergyStorage(capacity, inputRate, outputRate, stored)
}
override fun serializeNBT(): NBTTagCompound {
return NBTTagCompound().also {
it.setInteger("capacity", this.storage.maxEnergyStored)
it.setInteger("stored", this.storage.energyStored)
// it.setInteger("input_rate", 100)
// it.setInteger("output_rate", 100)
}
}
}
}
override fun getItemStackLimit(stack: ItemStack?): Int {
val energy = stack?.getCapability(CapabilityEnergy.ENERGY, null)
return if ((energy == null) || (energy.energyStored == 0)) 16 else 1
}
@SideOnly(Side.CLIENT)
override fun addInformation(stack: ItemStack?, worldIn: World?, tooltip: MutableList<String>?, flagIn: ITooltipFlag?) {
val energy = stack?.getCapability(CapabilityEnergy.ENERGY, null)
if (energy != null) {
if (energy.energyStored > 0) {
tooltip!!.add(ChatFormatting.AQUA.toString() + "Power: " + energy.energyStored + ChatFormatting.RESET + " of " + ChatFormatting.AQUA + energy.maxEnergyStored)
} else {
tooltip!!.add(ChatFormatting.RED.toString() + "EMPTY!")
}
}
super.addInformation(stack, worldIn, tooltip, flagIn)
}
@SideOnly(Side.CLIENT)
override fun getSubItems(tab: CreativeTabs, subItems: NonNullList<ItemStack>) {
if (this.isInCreativeTab(tab)) {
subItems.add(ItemStack(this))
val full = ItemStack(this)
val energy = full.getCapability(CapabilityEnergy.ENERGY, null)
if (energy != null) {
var cycle = 0
while(energy.canReceive() && (energy.maxEnergyStored > energy.energyStored) && (cycle++ < 100)) {
energy.receiveEnergy(energy.maxEnergyStored - energy.energyStored, false)
}
}
subItems.add(full)
}
}
//#region IEnergyContainerItem members
@Optional.Method(modid = RFPowerProxy.MODID)
override fun getMaxEnergyStored(container: ItemStack?): Int {
val energy = container?.getCapability(CapabilityEnergy.ENERGY, null) ?: return 0
return energy.maxEnergyStored
}
@Optional.Method(modid = RFPowerProxy.MODID)
override fun getEnergyStored(container: ItemStack?): Int {
val energy = container?.getCapability(CapabilityEnergy.ENERGY, null) ?: return 0
return energy.energyStored
}
@Optional.Method(modid = RFPowerProxy.MODID)
override fun extractEnergy(container: ItemStack?, maxExtract: Int, simulate: Boolean): Int {
val energy = container?.getCapability(CapabilityEnergy.ENERGY, null) ?: return 0
return energy.extractEnergy(maxExtract, simulate)
}
@Optional.Method(modid = RFPowerProxy.MODID)
override fun receiveEnergy(container: ItemStack?, maxReceive: Int, simulate: Boolean): Int {
val energy = container?.getCapability(CapabilityEnergy.ENERGY, null) ?: return 0
return energy.receiveEnergy(maxReceive, simulate)
}
//#endregion
}
| mit | c705db396503817be94adabf66d280ce | 42.072848 | 174 | 0.647755 | 4.609497 | false | false | false | false |
AndroidX/androidx | compose/material/material/src/commonMain/kotlin/androidx/compose/material/Colors.kt | 3 | 13326 | /*
* Copyright 2019 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.compose.material
import androidx.compose.runtime.Composable
import androidx.compose.runtime.ReadOnlyComposable
import androidx.compose.runtime.Stable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.compose.runtime.staticCompositionLocalOf
import androidx.compose.runtime.structuralEqualityPolicy
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.takeOrElse
/**
* <a href="https://material.io/design/color/the-color-system.html" class="external" target="_blank">Material Design color system</a>.
*
* The Material Design color system can help you create a color theme that reflects your brand or
* style.
*
* 
*
* To create a light set of colors using the baseline values, use [lightColors]
* To create a dark set of colors using the baseline values, use [darkColors]
*
* @property primary The primary color is the color displayed most frequently across your app’s
* screens and components.
* @property primaryVariant The primary variant color is used to distinguish two elements of the
* app using the primary color, such as the top app bar and the system bar.
* @property secondary The secondary color provides more ways to accent and distinguish your
* product. Secondary colors are best for:
* - Floating action buttons
* - Selection controls, like checkboxes and radio buttons
* - Highlighting selected text
* - Links and headlines
* @property secondaryVariant The secondary variant color is used to distinguish two elements of the
* app using the secondary color.
* @property background The background color appears behind scrollable content.
* @property surface The surface color is used on surfaces of components, such as cards, sheets and
* menus.
* @property error The error color is used to indicate error within components, such as text fields.
* @property onPrimary Color used for text and icons displayed on top of the primary color.
* @property onSecondary Color used for text and icons displayed on top of the secondary color.
* @property onBackground Color used for text and icons displayed on top of the background color.
* @property onSurface Color used for text and icons displayed on top of the surface color.
* @property onError Color used for text and icons displayed on top of the error color.
* @property isLight Whether this Colors is considered as a 'light' or 'dark' set of colors. This
* affects default behavior for some components: for example, in a light theme a [TopAppBar] will
* use [primary] by default for its background color, when in a dark theme it will use [surface].
*/
@Stable
class Colors(
primary: Color,
primaryVariant: Color,
secondary: Color,
secondaryVariant: Color,
background: Color,
surface: Color,
error: Color,
onPrimary: Color,
onSecondary: Color,
onBackground: Color,
onSurface: Color,
onError: Color,
isLight: Boolean
) {
var primary by mutableStateOf(primary, structuralEqualityPolicy())
internal set
var primaryVariant by mutableStateOf(primaryVariant, structuralEqualityPolicy())
internal set
var secondary by mutableStateOf(secondary, structuralEqualityPolicy())
internal set
var secondaryVariant by mutableStateOf(secondaryVariant, structuralEqualityPolicy())
internal set
var background by mutableStateOf(background, structuralEqualityPolicy())
internal set
var surface by mutableStateOf(surface, structuralEqualityPolicy())
internal set
var error by mutableStateOf(error, structuralEqualityPolicy())
internal set
var onPrimary by mutableStateOf(onPrimary, structuralEqualityPolicy())
internal set
var onSecondary by mutableStateOf(onSecondary, structuralEqualityPolicy())
internal set
var onBackground by mutableStateOf(onBackground, structuralEqualityPolicy())
internal set
var onSurface by mutableStateOf(onSurface, structuralEqualityPolicy())
internal set
var onError by mutableStateOf(onError, structuralEqualityPolicy())
internal set
var isLight by mutableStateOf(isLight, structuralEqualityPolicy())
internal set
/**
* Returns a copy of this Colors, optionally overriding some of the values.
*/
fun copy(
primary: Color = this.primary,
primaryVariant: Color = this.primaryVariant,
secondary: Color = this.secondary,
secondaryVariant: Color = this.secondaryVariant,
background: Color = this.background,
surface: Color = this.surface,
error: Color = this.error,
onPrimary: Color = this.onPrimary,
onSecondary: Color = this.onSecondary,
onBackground: Color = this.onBackground,
onSurface: Color = this.onSurface,
onError: Color = this.onError,
isLight: Boolean = this.isLight
): Colors = Colors(
primary,
primaryVariant,
secondary,
secondaryVariant,
background,
surface,
error,
onPrimary,
onSecondary,
onBackground,
onSurface,
onError,
isLight
)
override fun toString(): String {
return "Colors(" +
"primary=$primary, " +
"primaryVariant=$primaryVariant, " +
"secondary=$secondary, " +
"secondaryVariant=$secondaryVariant, " +
"background=$background, " +
"surface=$surface, " +
"error=$error, " +
"onPrimary=$onPrimary, " +
"onSecondary=$onSecondary, " +
"onBackground=$onBackground, " +
"onSurface=$onSurface, " +
"onError=$onError, " +
"isLight=$isLight" +
")"
}
}
/**
* Creates a complete color definition for the
* [Material color specification](https://material.io/design/color/the-color-system.html#color-theme-creation)
* using the default light theme values.
*
* @see darkColors
*/
fun lightColors(
primary: Color = Color(0xFF6200EE),
primaryVariant: Color = Color(0xFF3700B3),
secondary: Color = Color(0xFF03DAC6),
secondaryVariant: Color = Color(0xFF018786),
background: Color = Color.White,
surface: Color = Color.White,
error: Color = Color(0xFFB00020),
onPrimary: Color = Color.White,
onSecondary: Color = Color.Black,
onBackground: Color = Color.Black,
onSurface: Color = Color.Black,
onError: Color = Color.White
): Colors = Colors(
primary,
primaryVariant,
secondary,
secondaryVariant,
background,
surface,
error,
onPrimary,
onSecondary,
onBackground,
onSurface,
onError,
true
)
/**
* Creates a complete color definition for the
* [Material color specification](https://material.io/design/color/the-color-system.html#color-theme-creation)
* using the default dark theme values.
*
* Note: [secondaryVariant] is typically the same as [secondary] in dark theme since contrast
* levels are higher, and hence there is less need for a separate secondary color.
*
* @see lightColors
*/
fun darkColors(
primary: Color = Color(0xFFBB86FC),
primaryVariant: Color = Color(0xFF3700B3),
secondary: Color = Color(0xFF03DAC6),
secondaryVariant: Color = secondary,
background: Color = Color(0xFF121212),
surface: Color = Color(0xFF121212),
error: Color = Color(0xFFCF6679),
onPrimary: Color = Color.Black,
onSecondary: Color = Color.Black,
onBackground: Color = Color.White,
onSurface: Color = Color.White,
onError: Color = Color.Black
): Colors = Colors(
primary,
primaryVariant,
secondary,
secondaryVariant,
background,
surface,
error,
onPrimary,
onSecondary,
onBackground,
onSurface,
onError,
false
)
/**
* primarySurface represents the background color of components that are [Colors.primary]
* in light theme, and [Colors.surface] in dark theme, such as [androidx.compose.material.TabRow]
* and [androidx.compose.material.TopAppBar]. This is to reduce brightness of large surfaces in dark
* theme, aiding contrast and readability. See
* [Dark Theme](https://material.io/design/color/dark-theme.html#custom-application).
*
* @return [Colors.primary] if in light theme, else [Colors.surface]
*/
val Colors.primarySurface: Color get() = if (isLight) primary else surface
/**
* The Material color system contains pairs of colors that are typically used for the background
* and content color inside a component. For example, a [Button] typically uses `primary` for its
* background, and `onPrimary` for the color of its content (usually text or iconography).
*
* This function tries to match the provided [backgroundColor] to a 'background' color in this
* [Colors], and then will return the corresponding color used for content. For example, when
* [backgroundColor] is [Colors.primary], this will return [Colors.onPrimary].
*
* If [backgroundColor] does not match a background color in the theme, this will return
* [Color.Unspecified].
*
* @return the matching content color for [backgroundColor]. If [backgroundColor] is not present in
* the theme's [Colors], then returns [Color.Unspecified].
*
* @see contentColorFor
*/
fun Colors.contentColorFor(backgroundColor: Color): Color {
return when (backgroundColor) {
primary -> onPrimary
primaryVariant -> onPrimary
secondary -> onSecondary
secondaryVariant -> onSecondary
background -> onBackground
surface -> onSurface
error -> onError
else -> Color.Unspecified
}
}
/**
* The Material color system contains pairs of colors that are typically used for the background
* and content color inside a component. For example, a [Button] typically uses `primary` for its
* background, and `onPrimary` for the color of its content (usually text or iconography).
*
* This function tries to match the provided [backgroundColor] to a 'background' color in this
* [Colors], and then will return the corresponding color used for content. For example, when
* [backgroundColor] is [Colors.primary], this will return [Colors.onPrimary].
*
* If [backgroundColor] does not match a background color in the theme, this will return
* the current value of [LocalContentColor] as a best-effort color.
*
* @return the matching content color for [backgroundColor]. If [backgroundColor] is not present in
* the theme's [Colors], then returns the current value of [LocalContentColor].
*
* @see Colors.contentColorFor
*/
@Composable
@ReadOnlyComposable
fun contentColorFor(backgroundColor: Color) =
MaterialTheme.colors.contentColorFor(backgroundColor).takeOrElse { LocalContentColor.current }
/**
* Updates the internal values of the given [Colors] with values from the [other] [Colors]. This
* allows efficiently updating a subset of [Colors], without recomposing every composable that
* consumes values from [LocalColors].
*
* Because [Colors] is very wide-reaching, and used by many expensive composables in the
* hierarchy, providing a new value to [LocalColors] causes every composable consuming
* [LocalColors] to recompose, which is prohibitively expensive in cases such as animating one
* color in the theme. Instead, [Colors] is internally backed by [mutableStateOf], and this
* function mutates the internal state of [this] to match values in [other]. This means that any
* changes will mutate the internal state of [this], and only cause composables that are reading
* the specific changed value to recompose.
*/
internal fun Colors.updateColorsFrom(other: Colors) {
primary = other.primary
primaryVariant = other.primaryVariant
secondary = other.secondary
secondaryVariant = other.secondaryVariant
background = other.background
surface = other.surface
error = other.error
onPrimary = other.onPrimary
onSecondary = other.onSecondary
onBackground = other.onBackground
onSurface = other.onSurface
onError = other.onError
isLight = other.isLight
}
/**
* CompositionLocal used to pass [Colors] down the tree.
*
* Setting the value here is typically done as part of [MaterialTheme], which will
* automatically handle efficiently updating any changed colors without causing unnecessary
* recompositions, using [Colors.updateColorsFrom].
* To retrieve the current value of this CompositionLocal, use [MaterialTheme.colors].
*/
internal val LocalColors = staticCompositionLocalOf { lightColors() }
| apache-2.0 | d791954c2d376467ff7fbec90f257e90 | 38.654762 | 134 | 0.720354 | 4.647367 | false | false | false | false |
hannesa2/owncloud-android | owncloudData/src/main/java/com/owncloud/android/data/sharing/shares/datasources/mapper/RemoteShareMapper.kt | 2 | 2746 | /**
* ownCloud Android client application
*
* @author David González Verdugo
* Copyright (C) 2020 ownCloud GmbH.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2,
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.owncloud.android.data.sharing.shares.datasources.mapper
import com.owncloud.android.domain.mappers.RemoteMapper
import com.owncloud.android.domain.sharing.shares.model.OCShare
import com.owncloud.android.domain.sharing.shares.model.ShareType
import com.owncloud.android.lib.resources.shares.RemoteShare
import com.owncloud.android.lib.resources.shares.ShareType as RemoteShareType
class RemoteShareMapper : RemoteMapper<OCShare, RemoteShare> {
override fun toModel(remote: RemoteShare?): OCShare? =
remote?.let {
OCShare(
shareType = ShareType.fromValue(remote.shareType!!.value)!!,
shareWith = remote.shareWith,
path = remote.path,
permissions = remote.permissions,
sharedDate = remote.sharedDate,
expirationDate = remote.expirationDate,
token = remote.token,
sharedWithDisplayName = remote.sharedWithDisplayName,
sharedWithAdditionalInfo = remote.sharedWithAdditionalInfo,
isFolder = remote.isFolder,
remoteId = remote.id,
name = remote.name,
shareLink = remote.shareLink
)
}
override fun toRemote(model: OCShare?): RemoteShare? =
model?.let {
RemoteShare(
id = model.remoteId,
shareWith = model.shareWith!!,
path = model.path,
token = model.token!!,
sharedWithDisplayName = model.sharedWithDisplayName!!,
sharedWithAdditionalInfo = model.sharedWithAdditionalInfo!!,
name = model.name!!,
shareLink = model.shareLink!!,
shareType = RemoteShareType.fromValue(model.shareType.value),
permissions = model.permissions,
sharedDate = model.sharedDate,
expirationDate = model.expirationDate,
isFolder = model.isFolder,
)
}
}
| gpl-2.0 | b5504073394350f29ea2581d2111ff86 | 40.590909 | 77 | 0.641894 | 5.018282 | false | false | false | false |
mglukhikh/intellij-community | plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/resolve/ResolveUtil.kt | 1 | 6262 | // 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.
@file:Suppress("LoopToCallChain")
package org.jetbrains.plugins.groovy.lang.resolve
import com.intellij.openapi.util.Key
import com.intellij.psi.*
import com.intellij.psi.scope.ElementClassHint
import com.intellij.psi.scope.ElementClassHint.DeclarationKind
import com.intellij.psi.scope.NameHint
import com.intellij.psi.scope.PsiScopeProcessor
import com.intellij.psi.util.CachedValueProvider.Result
import com.intellij.psi.util.CachedValuesManager.getCachedValue
import org.jetbrains.plugins.groovy.lang.psi.GroovyFileBase
import org.jetbrains.plugins.groovy.lang.psi.api.auxiliary.modifiers.annotation.GrAnnotation
import org.jetbrains.plugins.groovy.lang.psi.api.statements.GrStatement
import org.jetbrains.plugins.groovy.lang.psi.api.types.GrCodeReferenceElement
import org.jetbrains.plugins.groovy.lang.psi.api.util.GrStatementOwner
import org.jetbrains.plugins.groovy.lang.psi.impl.statements.expressions.TypesUtil
import org.jetbrains.plugins.groovy.lang.psi.impl.synthetic.DefaultConstructor
import org.jetbrains.plugins.groovy.lang.psi.util.skipSameTypeParents
import org.jetbrains.plugins.groovy.lang.resolve.processors.DynamicMembersHint
import org.jetbrains.plugins.groovy.lang.resolve.processors.GroovyResolveKind
import org.jetbrains.plugins.groovy.lang.resolve.processors.GroovyResolverProcessor
@JvmField
val NON_CODE = Key.create<Boolean?>("groovy.process.non.code.members")
fun initialState(processNonCodeMembers: Boolean) = ResolveState.initial().put(NON_CODE, processNonCodeMembers)
fun ResolveState.processNonCodeMembers(): Boolean = get(NON_CODE).let { it == null || it }
fun treeWalkUp(place: PsiElement, processor: PsiScopeProcessor, state: ResolveState): Boolean {
return ResolveUtil.treeWalkUp(place, place, processor, state)
}
fun GrStatementOwner.processStatements(lastParent: PsiElement?, processor: (GrStatement) -> Boolean): Boolean {
var run = if (lastParent == null) lastChild else lastParent.prevSibling
while (run != null) {
if (run is GrStatement && !processor(run)) return false
run = run.prevSibling
}
return true
}
fun GrStatementOwner.processLocals(processor: PsiScopeProcessor, state: ResolveState, lastParent: PsiElement?, place: PsiElement): Boolean {
return !processor.shouldProcessLocals() || processStatements(lastParent) {
it.processDeclarations(processor, state, null, place)
}
}
fun PsiScopeProcessor.checkName(name: String, state: ResolveState): Boolean {
val expectedName = getName(state) ?: return true
return expectedName == name
}
fun PsiScopeProcessor.getName(state: ResolveState): String? = getHint(NameHint.KEY)?.getName(state)
fun shouldProcessDynamicMethods(processor: PsiScopeProcessor): Boolean {
return processor.getHint(DynamicMembersHint.KEY)?.shouldProcessMethods() ?: false
}
fun PsiScopeProcessor.shouldProcessDynamicProperties(): Boolean {
return getHint(DynamicMembersHint.KEY)?.shouldProcessProperties() ?: false
}
fun PsiScopeProcessor.shouldProcessLocals(): Boolean = shouldProcess(GroovyResolveKind.VARIABLE)
fun PsiScopeProcessor.shouldProcessFields(): Boolean = shouldProcess(GroovyResolveKind.FIELD)
fun PsiScopeProcessor.shouldProcessMethods(): Boolean {
return ResolveUtil.shouldProcessMethods(getHint(ElementClassHint.KEY))
}
fun PsiScopeProcessor.shouldProcessClasses(): Boolean {
return ResolveUtil.shouldProcessClasses(getHint(ElementClassHint.KEY))
}
fun PsiScopeProcessor.shouldProcessMembers(): Boolean {
val hint = getHint(ElementClassHint.KEY) ?: return true
return hint.shouldProcess(DeclarationKind.CLASS) ||
hint.shouldProcess(DeclarationKind.FIELD) ||
hint.shouldProcess(DeclarationKind.METHOD)
}
fun PsiScopeProcessor.shouldProcessTypeParameters(): Boolean {
if (shouldProcessClasses()) return true
val groovyKindHint = getHint(GroovyResolveKind.HINT_KEY) ?: return true
return groovyKindHint.shouldProcess(GroovyResolveKind.TYPE_PARAMETER)
}
fun PsiScopeProcessor.shouldProcessProperties(): Boolean {
return this is GroovyResolverProcessor && isPropertyResolve
}
fun PsiScopeProcessor.shouldProcessPackages(): Boolean = shouldProcess(GroovyResolveKind.PACKAGE)
private fun PsiScopeProcessor.shouldProcess(kind: GroovyResolveKind): Boolean {
val resolveKindHint = getHint(GroovyResolveKind.HINT_KEY)
if (resolveKindHint != null) return resolveKindHint.shouldProcess(kind)
val elementClassHint = getHint(ElementClassHint.KEY) ?: return true
return kind.declarationKinds.any(elementClassHint::shouldProcess)
}
fun wrapClassType(type: PsiType, context: PsiElement) = TypesUtil.createJavaLangClassType(type, context.project, context.resolveScope)
fun getDefaultConstructor(clazz: PsiClass): PsiMethod {
return getCachedValue(clazz) {
Result.create(DefaultConstructor(clazz), clazz)
}
}
fun GroovyFileBase.processClassesInFile(processor: PsiScopeProcessor, state: ResolveState): Boolean {
if (!processor.shouldProcessClasses()) return true
val scriptClass = scriptClass
if (scriptClass != null && !ResolveUtil.processElement(processor, scriptClass, state)) return false
for (definition in typeDefinitions) {
if (!ResolveUtil.processElement(processor, definition, state)) return false
}
return true
}
fun GroovyFileBase.processClassesInPackage(processor: PsiScopeProcessor, state: ResolveState, place: PsiElement = this): Boolean {
if (!processor.shouldProcessClasses()) return true
val aPackage = JavaPsiFacade.getInstance(project).findPackage(packageName) ?: return true
return aPackage.processDeclarations(PackageSkippingProcessor(processor), state, null, place)
}
val PsiScopeProcessor.annotationHint: AnnotationHint? get() = getHint(AnnotationHint.HINT_KEY)
fun PsiScopeProcessor.isAnnotationResolve(): Boolean {
val hint = annotationHint ?: return false
return hint.isAnnotationResolve
}
fun PsiScopeProcessor.isNonAnnotationResolve(): Boolean {
val hint = annotationHint ?: return false
return !hint.isAnnotationResolve
}
fun GrCodeReferenceElement.isAnnotationReference(): Boolean {
val (possibleAnnotation, _) = skipSameTypeParents()
return possibleAnnotation is GrAnnotation
}
| apache-2.0 | 4dfee24a22bbcddf7d10e619f4f004bf | 42.186207 | 140 | 0.807729 | 4.641957 | false | false | false | false |
jotomo/AndroidAPS | app/src/main/java/info/nightscout/androidaps/plugins/profile/local/LocalProfilePlugin.kt | 1 | 12936 | package info.nightscout.androidaps.plugins.profile.local
import androidx.fragment.app.FragmentActivity
import dagger.android.HasAndroidInjector
import info.nightscout.androidaps.Constants
import info.nightscout.androidaps.R
import info.nightscout.androidaps.data.Profile
import info.nightscout.androidaps.events.EventProfileStoreChanged
import info.nightscout.androidaps.interfaces.*
import info.nightscout.androidaps.logging.AAPSLogger
import info.nightscout.androidaps.logging.LTag
import info.nightscout.androidaps.plugins.bus.RxBusWrapper
import info.nightscout.androidaps.plugins.general.nsclient.NSUpload
import info.nightscout.androidaps.utils.DateUtil
import info.nightscout.androidaps.utils.DecimalFormatter
import info.nightscout.androidaps.utils.alertDialogs.OKDialog
import info.nightscout.androidaps.utils.resources.ResourceHelper
import info.nightscout.androidaps.utils.sharedPreferences.SP
import org.json.JSONArray
import org.json.JSONException
import org.json.JSONObject
import java.util.*
import javax.inject.Inject
import javax.inject.Singleton
import kotlin.collections.ArrayList
@Singleton
class LocalProfilePlugin @Inject constructor(
injector: HasAndroidInjector,
aapsLogger: AAPSLogger,
private val rxBus: RxBusWrapper,
resourceHelper: ResourceHelper,
private val sp: SP,
private val profileFunction: ProfileFunction,
private val nsUpload: NSUpload
) : PluginBase(PluginDescription()
.mainType(PluginType.PROFILE)
.fragmentClass(LocalProfileFragment::class.java.name)
.enableByDefault(true)
.pluginIcon(R.drawable.ic_local_profile)
.pluginName(R.string.localprofile)
.shortName(R.string.localprofile_shortname)
.description(R.string.description_profile_local)
.setDefault(),
aapsLogger, resourceHelper, injector
), ProfileInterface {
private var rawProfile: ProfileStore? = null
private val defaultArray = "[{\"time\":\"00:00\",\"timeAsSeconds\":0,\"value\":0}]"
override fun onStart() {
super.onStart()
loadSettings()
}
class SingleProfile {
internal var name: String? = null
internal var mgdl: Boolean = false
internal var dia: Double = Constants.defaultDIA
internal var ic: JSONArray? = null
internal var isf: JSONArray? = null
internal var basal: JSONArray? = null
internal var targetLow: JSONArray? = null
internal var targetHigh: JSONArray? = null
fun deepClone(): SingleProfile {
val sp = SingleProfile()
sp.name = name
sp.mgdl = mgdl
sp.dia = dia
sp.ic = JSONArray(ic.toString())
sp.isf = JSONArray(isf.toString())
sp.basal = JSONArray(basal.toString())
sp.targetLow = JSONArray(targetLow.toString())
sp.targetHigh = JSONArray(targetHigh.toString())
return sp
}
}
var isEdited: Boolean = false
var profiles: ArrayList<SingleProfile> = ArrayList()
var numOfProfiles = 0
internal var currentProfileIndex = 0
fun currentProfile(): SingleProfile? = if (numOfProfiles > 0) profiles[currentProfileIndex] else null
@Synchronized
fun isValidEditState(): Boolean {
return createProfileStore().getDefaultProfile()?.isValid(resourceHelper.gs(R.string.localprofile), false)
?: false
}
@Synchronized
fun storeSettings(activity: FragmentActivity? = null) {
for (i in 0 until numOfProfiles) {
profiles[i].run {
val localProfileNumbered = Constants.LOCAL_PROFILE + "_" + i + "_"
sp.putString(localProfileNumbered + "name", name!!)
sp.putBoolean(localProfileNumbered + "mgdl", mgdl)
sp.putDouble(localProfileNumbered + "dia", dia)
sp.putString(localProfileNumbered + "ic", ic.toString())
sp.putString(localProfileNumbered + "isf", isf.toString())
sp.putString(localProfileNumbered + "basal", basal.toString())
sp.putString(localProfileNumbered + "targetlow", targetLow.toString())
sp.putString(localProfileNumbered + "targethigh", targetHigh.toString())
}
}
sp.putInt(Constants.LOCAL_PROFILE + "_profiles", numOfProfiles)
createAndStoreConvertedProfile()
isEdited = false
aapsLogger.debug(LTag.PROFILE, "Storing settings: " + rawProfile?.data.toString())
rxBus.send(EventProfileStoreChanged())
var namesOK = true
profiles.forEach {
val name = it.name ?: "."
if (name.contains(".")) namesOK = false
}
if (namesOK)
rawProfile?.let { nsUpload.uploadProfileStore(it.data) }
else
activity?.let {
OKDialog.show(it, "", resourceHelper.gs(R.string.profilenamecontainsdot))
}
}
@Synchronized
fun loadSettings() {
numOfProfiles = sp.getInt(Constants.LOCAL_PROFILE + "_profiles", 0)
profiles.clear()
// numOfProfiles = max(numOfProfiles, 1) // create at least one default profile if none exists
for (i in 0 until numOfProfiles) {
val p = SingleProfile()
val localProfileNumbered = Constants.LOCAL_PROFILE + "_" + i + "_"
p.name = sp.getString(localProfileNumbered + "name", Constants.LOCAL_PROFILE + i)
if (isExistingName(p.name)) continue
p.mgdl = sp.getBoolean(localProfileNumbered + "mgdl", false)
p.dia = sp.getDouble(localProfileNumbered + "dia", Constants.defaultDIA)
try {
p.ic = JSONArray(sp.getString(localProfileNumbered + "ic", defaultArray))
} catch (e1: JSONException) {
try {
p.ic = JSONArray(defaultArray)
} catch (ignored: JSONException) {
}
aapsLogger.error("Exception", e1)
}
try {
p.isf = JSONArray(sp.getString(localProfileNumbered + "isf", defaultArray))
} catch (e1: JSONException) {
try {
p.isf = JSONArray(defaultArray)
} catch (ignored: JSONException) {
}
aapsLogger.error("Exception", e1)
}
try {
p.basal = JSONArray(sp.getString(localProfileNumbered + "basal", defaultArray))
} catch (e1: JSONException) {
try {
p.basal = JSONArray(defaultArray)
} catch (ignored: JSONException) {
}
aapsLogger.error("Exception", e1)
}
try {
p.targetLow = JSONArray(sp.getString(localProfileNumbered + "targetlow", defaultArray))
} catch (e1: JSONException) {
try {
p.targetLow = JSONArray(defaultArray)
} catch (ignored: JSONException) {
}
aapsLogger.error("Exception", e1)
}
try {
p.targetHigh = JSONArray(sp.getString(localProfileNumbered + "targethigh", defaultArray))
} catch (e1: JSONException) {
try {
p.targetHigh = JSONArray(defaultArray)
} catch (ignored: JSONException) {
}
aapsLogger.error("Exception", e1)
}
profiles.add(p)
}
isEdited = false
numOfProfiles = profiles.size
createAndStoreConvertedProfile()
}
fun copyFrom(profile: Profile, newName: String): SingleProfile {
var verifiedName = newName
if (rawProfile?.getSpecificProfile(newName) != null) {
verifiedName += " " + DateUtil.now().toString()
}
val sp = SingleProfile()
sp.name = verifiedName
sp.mgdl = profile.units == Constants.MGDL
sp.dia = profile.dia
sp.ic = JSONArray(profile.data.getJSONArray("carbratio").toString())
sp.isf = JSONArray(profile.data.getJSONArray("sens").toString())
sp.basal = JSONArray(profile.data.getJSONArray("basal").toString())
sp.targetLow = JSONArray(profile.data.getJSONArray("target_low").toString())
sp.targetHigh = JSONArray(profile.data.getJSONArray("target_high").toString())
return sp
}
private fun isExistingName(name: String?): Boolean {
for (p in profiles) {
if (p.name == name) return true
}
return false
}
/*
{
"_id": "576264a12771b7500d7ad184",
"startDate": "2016-06-16T08:35:00.000Z",
"defaultProfile": "Default",
"store": {
"Default": {
"dia": "3",
"carbratio": [{
"time": "00:00",
"value": "30"
}],
"carbs_hr": "20",
"delay": "20",
"sens": [{
"time": "00:00",
"value": "100"
}],
"timezone": "UTC",
"basal": [{
"time": "00:00",
"value": "0.1"
}],
"target_low": [{
"time": "00:00",
"value": "0"
}],
"target_high": [{
"time": "00:00",
"value": "0"
}],
"startDate": "1970-01-01T00:00:00.000Z",
"units": "mmol"
}
},
"created_at": "2016-06-16T08:34:41.256Z"
}
*/
private fun createAndStoreConvertedProfile() {
rawProfile = createProfileStore()
}
fun addNewProfile() {
var free = 0
for (i in 1..10000) {
if (rawProfile?.getSpecificProfile(Constants.LOCAL_PROFILE + i) == null) {
free = i
break
}
}
val p = SingleProfile()
p.name = Constants.LOCAL_PROFILE + free
p.mgdl = profileFunction.getUnits() == Constants.MGDL
p.dia = Constants.defaultDIA
p.ic = JSONArray(defaultArray)
p.isf = JSONArray(defaultArray)
p.basal = JSONArray(defaultArray)
p.targetLow = JSONArray(defaultArray)
p.targetHigh = JSONArray(defaultArray)
profiles.add(p)
currentProfileIndex = profiles.size - 1
numOfProfiles++
createAndStoreConvertedProfile()
storeSettings()
}
fun cloneProfile() {
val p = profiles[currentProfileIndex].deepClone()
p.name = p.name + " copy"
profiles.add(p)
currentProfileIndex = profiles.size - 1
numOfProfiles++
createAndStoreConvertedProfile()
storeSettings()
isEdited = false
}
fun addProfile(p: SingleProfile) {
profiles.add(p)
currentProfileIndex = profiles.size - 1
numOfProfiles++
createAndStoreConvertedProfile()
storeSettings()
isEdited = false
}
fun removeCurrentProfile() {
profiles.removeAt(currentProfileIndex)
numOfProfiles--
if (profiles.size == 0) addNewProfile()
currentProfileIndex = 0
createAndStoreConvertedProfile()
storeSettings()
isEdited = false
}
fun createProfileStore(): ProfileStore {
val json = JSONObject()
val store = JSONObject()
try {
for (i in 0 until numOfProfiles) {
profiles[i].run {
val profile = JSONObject()
profile.put("dia", dia)
profile.put("carbratio", ic)
profile.put("sens", isf)
profile.put("basal", basal)
profile.put("target_low", targetLow)
profile.put("target_high", targetHigh)
profile.put("units", if (mgdl) Constants.MGDL else Constants.MMOL)
profile.put("timezone", TimeZone.getDefault().id)
store.put(name, profile)
}
}
if (numOfProfiles > 0) json.put("defaultProfile", currentProfile()?.name)
json.put("startDate", DateUtil.toISOAsUTC(DateUtil.now()))
json.put("store", store)
} catch (e: JSONException) {
aapsLogger.error("Unhandled exception", e)
}
return ProfileStore(injector, json)
}
override fun getProfile(): ProfileStore? {
return rawProfile
}
override fun getProfileName(): String {
return DecimalFormatter.to2Decimal(rawProfile?.getDefaultProfile()?.percentageBasalSum()
?: 0.0) + "U "
}
}
| agpl-3.0 | 6bc5bc64758a419c606be70a2f009b12 | 35.134078 | 113 | 0.568491 | 4.670036 | false | false | false | false |
siosio/intellij-community | plugins/kotlin/project-wizard/core/src/org/jetbrains/kotlin/tools/projectWizard/Versions.kt | 1 | 1915 | /*
* Copyright 2010-2020 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlin.tools.projectWizard
import org.jetbrains.kotlin.tools.projectWizard.settings.version.Version
@Suppress("ClassName", "SpellCheckingInspection")
object Versions {
val KOTLIN = version("1.4.10") // used as fallback version
val GRADLE = version("6.6.1")
val KTOR = version("1.5.2")
val JUNIT = version("4.13")
val JUNIT5 = version("5.6.0")
val JETBRAINS_COMPOSE = version("0.4.0")
val KOTLIN_VERSION_FOR_COMPOSE = version("1.5.10")
val GRADLE_VERSION_FOR_COMPOSE = version("6.9")
object COMPOSE {
val ANDROID_ACTIVITY_COMPOSE = version("1.3.0-alpha03")
}
object ANDROID {
val ANDROID_MATERIAL = version("1.2.1")
val ANDROIDX_APPCOMPAT = version("1.2.0")
val ANDROIDX_CONSTRAINTLAYOUT = version("2.0.2")
val ANDROIDX_KTX = version("1.3.1")
}
object KOTLINX {
val KOTLINX_HTML = version("0.7.2")
val KOTLINX_NODEJS: Version = version("0.0.7")
}
object JS_WRAPPERS {
val KOTLIN_REACT = wrapperVersion("17.0.2")
val KOTLIN_REACT_DOM = KOTLIN_REACT
val KOTLIN_STYLED = wrapperVersion("5.3.0")
val KOTLIN_REACT_ROUTER_DOM = wrapperVersion("5.2.0")
val KOTLIN_REDUX = wrapperVersion("4.0.5")
val KOTLIN_REACT_REDUX = wrapperVersion("7.2.3")
private fun wrapperVersion(version: String): Version =
version("$version-pre.206-kotlin-1.5.10")
}
object GRADLE_PLUGINS {
val ANDROID = version("4.0.2")
}
object MAVEN_PLUGINS {
val SUREFIRE = version("2.22.2")
val FAILSAFE = SUREFIRE
}
}
private fun version(version: String) = Version.fromString(version)
| apache-2.0 | d84c30238fe6b39d3a11b86fe623f32e | 30.916667 | 115 | 0.643342 | 3.539741 | false | false | false | false |
siosio/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/HasPlatformTypeInspection.kt | 1 | 2627 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.inspections
import com.intellij.codeInspection.IntentionWrapper
import com.intellij.codeInspection.LocalQuickFix
import com.intellij.codeInspection.ui.MultipleCheckboxOptionsPanel
import org.jetbrains.kotlin.idea.KotlinBundle
import org.jetbrains.kotlin.idea.intentions.SpecifyTypeExplicitlyIntention
import org.jetbrains.kotlin.idea.intentions.isFlexibleRecursive
import org.jetbrains.kotlin.idea.quickfix.AddExclExclCallFix
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.psi.KtCallableDeclaration
import org.jetbrains.kotlin.psi.psiUtil.getNextSiblingIgnoringWhitespaceAndComments
import org.jetbrains.kotlin.types.TypeUtils
import javax.swing.JComponent
class HasPlatformTypeInspection(
@JvmField var publicAPIOnly: Boolean = true,
@JvmField var reportPlatformArguments: Boolean = false
) : AbstractImplicitTypeInspection(
{ element, inspection ->
with(inspection as HasPlatformTypeInspection) {
SpecifyTypeExplicitlyIntention.dangerousFlexibleTypeOrNull(
element,
this.publicAPIOnly,
this.reportPlatformArguments
) != null
}
}
) {
override val problemText = KotlinBundle.message(
"declaration.has.type.inferred.from.a.platform.call.which.can.lead.to.unchecked.nullability.issues"
)
override fun additionalFixes(element: KtCallableDeclaration): List<LocalQuickFix>? {
val type = SpecifyTypeExplicitlyIntention.dangerousFlexibleTypeOrNull(
element, publicAPIOnly, reportPlatformArguments
) ?: return null
if (TypeUtils.isNullableType(type)) {
val expression = element.node.findChildByType(KtTokens.EQ)?.psi?.getNextSiblingIgnoringWhitespaceAndComments()
if (expression != null &&
(!reportPlatformArguments || !TypeUtils.makeNotNullable(type).isFlexibleRecursive())
) {
return listOf(IntentionWrapper(AddExclExclCallFix(expression), element.containingFile))
}
}
return null
}
override fun createOptionsPanel(): JComponent? {
val panel = MultipleCheckboxOptionsPanel(this)
panel.addCheckbox(KotlinBundle.message("apply.only.to.public.or.protected.members"), "publicAPIOnly")
panel.addCheckbox(KotlinBundle.message("report.for.types.with.platform.arguments"), "reportPlatformArguments")
return panel
}
} | apache-2.0 | b8ce8575f62b0514330ed648365e59db | 42.8 | 158 | 0.740769 | 5.061657 | false | false | false | false |
mseroczynski/CityBikes | app/src/main/kotlin/pl/ches/citybikes/domain/common/diagnostic/CrashlyticsTree.kt | 1 | 1015 | package pl.ches.citybikes.domain.common.diagnostic
import android.util.Log
import pl.ches.citybikes.di.scope.AppScope
import timber.log.Timber
import javax.inject.Inject
/**
* @author Michał Seroczyński <michal.seroczynski@gmail.com>
*/
@AppScope
class CrashlyticsTree
@Inject
constructor() : Timber.Tree() {
override fun log(priority: Int, tag: String?, message: String?, t: Throwable?) {
if (priority == Log.VERBOSE || priority == Log.DEBUG || priority == Log.INFO) {
return
}
// TODO Crashlytics
// Crashlytics.setInt(CRASHLYTICS_KEY_PRIORITY, priority)
// Crashlytics.setString(CRASHLYTICS_KEY_TAG, tag)
// Crashlytics.setString(CRASHLYTICS_KEY_MESSAGE, message)
if (t == null) {
// Crashlytics.logException(Exception(message))
} else {
// Crashlytics.logException(t)
}
}
companion object {
private val CRASHLYTICS_KEY_PRIORITY = "priority"
private val CRASHLYTICS_KEY_TAG = "tag"
private val CRASHLYTICS_KEY_MESSAGE = "message"
}
} | gpl-3.0 | 74996adda493778a3abd7764bb04b406 | 25.684211 | 83 | 0.698914 | 3.724265 | false | false | false | false |
JetBrains/xodus | environment/src/main/kotlin/jetbrains/exodus/log/BlockSet.kt | 1 | 4331 | /**
* 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.log
import jetbrains.exodus.core.dataStructures.hash.LongIterator
import jetbrains.exodus.core.dataStructures.persistent.PersistentBitTreeLongMap
import jetbrains.exodus.core.dataStructures.persistent.PersistentLongMap
import jetbrains.exodus.io.Block
// block key is aligned block address, i.e. block address divided by blockSize
sealed class BlockSet(val blockSize: Long, val set: PersistentLongMap<Block>) {
protected abstract val current: PersistentLongMap.ImmutableMap<Block>
fun size() = current.size()
val isEmpty get() = current.isEmpty
val minimum: Long? get() = current.iterator().let { if (it.hasNext()) it.next().key.keyToAddress else null }
val maximum: Long? get() = current.reverseIterator().let { if (it.hasNext()) it.next().key.keyToAddress else null }
/**
* Array of blocks' addresses in reverse order: the newer blocks first
*/
val array: LongArray
get() = getFiles(reversed = true)
@JvmOverloads
fun getFiles(reversed: Boolean = false): LongArray {
val current = current
val result = LongArray(current.size())
val it = if (reversed) {
current.reverseIterator()
} else {
current.iterator()
}
for (i in 0 until result.size) {
result[i] = it.next().key.keyToAddress
}
return result
}
fun contains(blockAddress: Long) = current.containsKey(blockAddress.addressToKey)
fun getBlock(blockAddress: Long): Block = current.get(blockAddress.addressToKey) ?: EmptyBlock(blockAddress)
// if address is inside of a block, the block containing it must be included as well if present
fun getFilesFrom(blockAddress: Long = 0L): LongIterator = object : LongIterator {
val it = if (blockAddress == 0L) current.iterator() else current.tailEntryIterator(blockAddress.addressToKey)
override fun next() = nextLong()
override fun hasNext() = it.hasNext()
override fun nextLong() = it.next().key.keyToAddress
override fun remove() = throw UnsupportedOperationException()
}
fun beginWrite() = Mutable(blockSize, set.clone)
protected val Long.keyToAddress: Long get() = this * blockSize
protected val Long.addressToKey: Long get() = this / blockSize
class Immutable @JvmOverloads constructor(
blockSize: Long,
map: PersistentLongMap<Block> = PersistentBitTreeLongMap()
) : BlockSet(blockSize, map) {
private val immutable: PersistentLongMap.ImmutableMap<Block> = map.beginRead()
public override val current: PersistentLongMap.ImmutableMap<Block>
get() = immutable
}
class Mutable(blockSize: Long, map: PersistentLongMap<Block>) : BlockSet(blockSize, map) {
private val mutable: PersistentLongMap.MutableMap<Block> = set.beginWrite()
override val current: PersistentLongMap.ImmutableMap<Block>
get() = mutable
fun clear() = mutable.clear()
fun add(blockAddress: Long, block: Block) = mutable.put(blockAddress.addressToKey, block)
fun remove(blockAddress: Long) = mutable.remove(blockAddress.addressToKey) != null
fun endWrite(): Immutable {
if (!mutable.endWrite()) {
throw IllegalStateException("File set can't be updated")
}
return Immutable(blockSize, set.clone)
}
}
private inner class EmptyBlock(private val address: Long) : Block {
override fun getAddress() = address
override fun length() = 0L
override fun read(output: ByteArray, position: Long, offset: Int, count: Int) = 0
override fun refresh() = this
}
}
| apache-2.0 | 8a69d5234f1a8751f6058e2d0f7ca6da | 35.70339 | 119 | 0.680905 | 4.497404 | false | false | false | false |
jwren/intellij-community | plugins/toml/json/src/main/kotlin/org/toml/ide/json/TomlJsonSchemaCompletionContributor.kt | 5 | 7804 | /*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.toml.ide.json
import com.intellij.codeInsight.completion.CompletionContributor
import com.intellij.codeInsight.completion.CompletionParameters
import com.intellij.codeInsight.completion.CompletionResultSet
import com.intellij.codeInsight.lookup.LookupElement
import com.intellij.codeInsight.lookup.LookupElementBuilder
import com.intellij.icons.AllIcons
import com.intellij.openapi.editor.EditorModificationUtil
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.text.StringUtil
import com.intellij.psi.PsiElement
import com.intellij.psi.util.parentOfType
import com.intellij.util.Consumer
import com.intellij.util.ThreeState
import com.jetbrains.jsonSchema.extension.JsonLikePsiWalker
import com.jetbrains.jsonSchema.extension.adapters.JsonPropertyAdapter
import com.jetbrains.jsonSchema.ide.JsonSchemaService
import com.jetbrains.jsonSchema.impl.JsonSchemaDocumentationProvider
import com.jetbrains.jsonSchema.impl.JsonSchemaObject
import com.jetbrains.jsonSchema.impl.JsonSchemaResolver
import com.jetbrains.jsonSchema.impl.JsonSchemaType
import org.toml.ide.experiments.TomlExperiments
import org.toml.lang.psi.TomlLiteral
import org.toml.lang.psi.TomlTableHeader
import org.toml.lang.psi.ext.TomlLiteralKind
import org.toml.lang.psi.ext.kind
class TomlJsonSchemaCompletionContributor : CompletionContributor() {
override fun fillCompletionVariants(parameters: CompletionParameters, result: CompletionResultSet) {
if (!TomlExperiments.isJsonSchemaEnabled) return
val position = parameters.position
val jsonSchemaService = JsonSchemaService.Impl.get(position.project)
val jsonSchemaObject = jsonSchemaService.getSchemaObject(parameters.originalFile)
if (jsonSchemaObject != null) {
val completionPosition = parameters.originalPosition ?: parameters.position
val worker = Worker(jsonSchemaObject, parameters.position, completionPosition, result)
worker.work()
}
}
private class Worker(
private val rootSchema: JsonSchemaObject,
private val position: PsiElement,
private val originalPosition: PsiElement,
private val resultConsumer: Consumer<LookupElement?>
) {
val variants: MutableSet<LookupElement> = mutableSetOf()
private val walker: JsonLikePsiWalker? = JsonLikePsiWalker.getWalker(position, rootSchema)
private val project: Project = originalPosition.project
fun work() {
val checkable = walker?.findElementToCheck(position) ?: return
val isName = walker.isName(checkable)
val pointerPosition = walker.findPosition(checkable, isName == ThreeState.NO)
if (pointerPosition == null || pointerPosition.isEmpty && isName == ThreeState.NO) return
val schemas = JsonSchemaResolver(project, rootSchema, pointerPosition).resolve()
val knownNames = hashSetOf<String>()
for (schema in schemas) {
if (isName != ThreeState.NO) {
val properties = walker.getPropertyNamesOfParentObject(originalPosition, position)
val adapter = walker.getParentPropertyAdapter(checkable)
val schemaProperties = schema.properties
addAllPropertyVariants(properties, adapter, schemaProperties, knownNames, originalPosition)
}
if (isName != ThreeState.YES) {
suggestValues(schema, isName == ThreeState.NO)
}
}
for (variant in variants) {
resultConsumer.consume(variant)
}
}
private fun addAllPropertyVariants(
properties: Collection<String>,
adapter: JsonPropertyAdapter?,
schemaProperties: Map<String, JsonSchemaObject>,
knownNames: MutableSet<String>,
originalPosition: PsiElement
) {
val variants = schemaProperties.keys.filter { name ->
!properties.contains(name) && !knownNames.contains(name) || name == adapter?.name
}
for (variant in variants) {
knownNames.add(variant)
val jsonSchemaObject = schemaProperties[variant]
if (jsonSchemaObject != null) {
// skip basic types keys as they can't be in the table header
val isTomlHeader = originalPosition.parentOfType<TomlTableHeader>() != null
if (isTomlHeader && jsonSchemaObject.guessType() !in JSON_COMPOUND_TYPES) continue
addPropertyVariant(variant, jsonSchemaObject)
}
}
}
@Suppress("NAME_SHADOWING")
private fun addPropertyVariant(key: String, jsonSchemaObject: JsonSchemaObject) {
val currentVariants = JsonSchemaResolver(project, jsonSchemaObject).resolve()
val jsonSchemaObject = currentVariants.firstOrNull() ?: jsonSchemaObject
var description = JsonSchemaDocumentationProvider.getBestDocumentation(true, jsonSchemaObject)
if (description.isNullOrBlank()) {
description = jsonSchemaObject.getTypeDescription(true).orEmpty()
}
val lookupElement = LookupElementBuilder.create(key)
.withTypeText(description)
.withIcon(getIconForType(jsonSchemaObject.guessType()))
variants.add(lookupElement)
}
private val isInsideStringLiteral: Boolean
get() = (position.parent as? TomlLiteral)?.kind is TomlLiteralKind.String
private fun suggestValues(schema: JsonSchemaObject, isSurelyValue: Boolean) {
val enumVariants = schema.enum
if (enumVariants != null) {
for (o in enumVariants) {
if (isInsideStringLiteral && o !is String) continue
val variant = if (isInsideStringLiteral) {
StringUtil.unquoteString(o.toString())
} else {
o.toString()
}
variants.add(LookupElementBuilder.create(variant))
}
} else if (isSurelyValue) {
variants.addAll(suggestValuesByType(schema.guessType()))
}
}
private fun suggestValuesByType(type: JsonSchemaType?): List<LookupElement> = when (type) {
JsonSchemaType._object -> listOf(buildPairLookupElement("{}"))
JsonSchemaType._array -> listOf(buildPairLookupElement("[]"))
JsonSchemaType._string -> if (isInsideStringLiteral) {
emptyList()
} else {
listOf(buildPairLookupElement("\"\""))
}
JsonSchemaType._boolean -> listOf("true", "false").map { LookupElementBuilder.create(it) }
else -> emptyList()
}
private fun buildPairLookupElement(element: String): LookupElementBuilder =
LookupElementBuilder.create(element)
.withInsertHandler { context, _ ->
EditorModificationUtil.moveCaretRelatively(context.editor, -1)
}
private fun getIconForType(type: JsonSchemaType?) = when (type) {
JsonSchemaType._object -> AllIcons.Json.Object
JsonSchemaType._array -> AllIcons.Json.Array
else -> AllIcons.Nodes.Property
}
}
companion object {
private val JSON_COMPOUND_TYPES = listOf(
JsonSchemaType._array, JsonSchemaType._object,
JsonSchemaType._any, null // type is uncertain
)
}
}
| apache-2.0 | 1a2ec714db3c6596f37ca2cbe3351b38 | 41.879121 | 111 | 0.653767 | 5.209613 | false | false | false | false |
jwren/intellij-community | platform/workspaceModel/jps/src/com/intellij/workspaceModel/ide/impl/jps/serialization/JpsProjectSerializersImpl.kt | 1 | 46220 | // 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.workspaceModel.ide.impl.jps.serialization
import com.intellij.diagnostic.AttachmentFactory
import com.intellij.openapi.components.ExpandMacroToPathMap
import com.intellij.openapi.components.PathMacroManager
import com.intellij.openapi.components.impl.ModulePathMacroManager
import com.intellij.openapi.components.impl.ProjectPathMacroManager
import com.intellij.openapi.diagnostic.Attachment
import com.intellij.openapi.diagnostic.debug
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.diagnostic.trace
import com.intellij.openapi.module.impl.ModulePath
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.io.FileUtil
import com.intellij.openapi.vfs.VfsUtilCore
import com.intellij.projectModel.ProjectModelBundle
import com.intellij.util.Function
import com.intellij.util.PathUtil
import com.intellij.util.containers.BidirectionalMap
import com.intellij.util.containers.BidirectionalMultiMap
import com.intellij.util.text.UniqueNameGenerator
import com.intellij.workspaceModel.ide.*
import com.intellij.workspaceModel.storage.*
import com.intellij.workspaceModel.storage.bridgeEntities.*
import com.intellij.workspaceModel.storage.impl.reportErrorAndAttachStorage
import com.intellij.workspaceModel.storage.url.VirtualFileUrl
import com.intellij.workspaceModel.storage.url.VirtualFileUrlManager
import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap
import org.jdom.Element
import org.jdom.JDOMException
import org.jetbrains.annotations.TestOnly
import org.jetbrains.jps.util.JpsPathUtil
import java.io.IOException
import java.nio.file.Files
import java.nio.file.Path
import java.nio.file.Paths
import java.util.*
import java.util.concurrent.Callable
import java.util.concurrent.ConcurrentHashMap
import java.util.concurrent.ForkJoinTask
import java.util.function.Supplier
import kotlin.streams.toList
class JpsProjectSerializersImpl(directorySerializersFactories: List<JpsDirectoryEntitiesSerializerFactory<*>>,
moduleListSerializers: List<JpsModuleListSerializer>,
reader: JpsFileContentReader,
private val entityTypeSerializers: List<JpsFileEntityTypeSerializer<*>>,
private val configLocation: JpsProjectConfigLocation,
private val externalStorageMapping: JpsExternalStorageMapping,
private val enableExternalStorage: Boolean,
private val virtualFileManager: VirtualFileUrlManager,
fileInDirectorySourceNames: FileInDirectorySourceNames) : JpsProjectSerializers {
private val lock = Any()
val moduleSerializers = BidirectionalMap<JpsFileEntitiesSerializer<*>, JpsModuleListSerializer>()
internal val serializerToDirectoryFactory = BidirectionalMap<JpsFileEntitiesSerializer<*>, JpsDirectoryEntitiesSerializerFactory<*>>()
private val internalSourceToExternal = HashMap<JpsFileEntitySource, JpsFileEntitySource>()
internal val fileSerializersByUrl = BidirectionalMultiMap<String, JpsFileEntitiesSerializer<*>>()
internal val fileIdToFileName = Int2ObjectOpenHashMap<String>()
// Map of module serializer to boolean that defines whenever modules.xml is external or not
private val moduleSerializerToExternalSourceBool = mutableMapOf<JpsFileEntitiesSerializer<*>, Boolean>()
init {
synchronized(lock) {
for (factory in directorySerializersFactories) {
createDirectorySerializers(factory, fileInDirectorySourceNames).associateWithTo(serializerToDirectoryFactory) { factory }
}
val enabledModuleListSerializers = moduleListSerializers.filter { enableExternalStorage || !it.isExternalStorage }
val moduleFiles = enabledModuleListSerializers.flatMap { ser ->
ser.loadFileList(reader, virtualFileManager).map {
Triple(it.first, it.second, ser.isExternalStorage)
}
}
for ((moduleFile, moduleGroup, isOriginallyExternal) in moduleFiles) {
val directoryUrl = virtualFileManager.getParentVirtualUrl(moduleFile)!!
val internalSource =
bindExistingSource(fileInDirectorySourceNames, ModuleEntity::class.java, moduleFile.fileName, directoryUrl) ?:
createFileInDirectorySource(directoryUrl, moduleFile.fileName)
for (moduleListSerializer in enabledModuleListSerializers) {
val moduleSerializer = moduleListSerializer.createSerializer(internalSource, moduleFile, moduleGroup)
moduleSerializers[moduleSerializer] = moduleListSerializer
moduleSerializerToExternalSourceBool[moduleSerializer] = isOriginallyExternal
}
}
val allFileSerializers = entityTypeSerializers.filter { enableExternalStorage || !it.isExternalStorage } +
serializerToDirectoryFactory.keys + moduleSerializers.keys
allFileSerializers.forEach {
fileSerializersByUrl.put(it.fileUrl.url, it)
}
}
}
internal val directorySerializerFactoriesByUrl = directorySerializersFactories.associateBy { it.directoryUrl }
val moduleListSerializersByUrl = moduleListSerializers.associateBy { it.fileUrl }
private fun createFileInDirectorySource(directoryUrl: VirtualFileUrl, fileName: String): JpsFileEntitySource.FileInDirectory {
val source = JpsFileEntitySource.FileInDirectory(directoryUrl, configLocation)
// Don't convert to links[key] = ... because it *may* became autoboxing
@Suppress("ReplacePutWithAssignment")
fileIdToFileName.put(source.fileNameId, fileName)
LOG.debug { "createFileInDirectorySource: ${source.fileNameId}=$fileName" }
return source
}
private fun createDirectorySerializers(factory: JpsDirectoryEntitiesSerializerFactory<*>,
fileInDirectorySourceNames: FileInDirectorySourceNames): List<JpsFileEntitiesSerializer<*>> {
val osPath = JpsPathUtil.urlToOsPath(factory.directoryUrl)
val libPath = Paths.get(osPath)
val files = when {
Files.isDirectory(libPath) -> Files.list(libPath).use { stream ->
stream.filter { path: Path -> PathUtil.getFileExtension(path.toString()) == "xml" && Files.isRegularFile(path) }
.toList()
}
else -> emptyList()
}
return files.map {
val fileName = it.fileName.toString()
val directoryUrl = virtualFileManager.fromUrl(factory.directoryUrl)
val entitySource =
bindExistingSource(fileInDirectorySourceNames, factory.entityClass, fileName, directoryUrl) ?:
createFileInDirectorySource(directoryUrl, fileName)
factory.createSerializer("${factory.directoryUrl}/$fileName", entitySource, virtualFileManager)
}
}
private fun bindExistingSource(fileInDirectorySourceNames: FileInDirectorySourceNames,
entityType: Class<out WorkspaceEntity>,
fileName: String,
directoryUrl: VirtualFileUrl): JpsFileEntitySource.FileInDirectory? {
val source = fileInDirectorySourceNames.findSource(entityType, fileName)
if (source == null || source.directory != directoryUrl) return null
@Suppress("ReplacePutWithAssignment")
fileIdToFileName.put(source.fileNameId, fileName)
LOG.debug { "bindExistingSource: ${source.fileNameId}=$fileName" }
return source
}
fun findModuleSerializer(modulePath: ModulePath): JpsFileEntitiesSerializer<*>? {
synchronized(lock) {
return fileSerializersByUrl.getValues(VfsUtilCore.pathToUrl(modulePath.path)).first()
}
}
override fun reloadFromChangedFiles(change: JpsConfigurationFilesChange,
reader: JpsFileContentReader,
errorReporter: ErrorReporter): Pair<Set<EntitySource>, WorkspaceEntityStorageBuilder> {
val obsoleteSerializers = ArrayList<JpsFileEntitiesSerializer<*>>()
val newFileSerializers = ArrayList<JpsFileEntitiesSerializer<*>>()
val addedFileUrls = change.addedFileUrls.flatMap {
val file = JpsPathUtil.urlToFile(it)
if (file.isDirectory) {
file.list()?.map { fileName -> "$it/$fileName" } ?: emptyList()
} else listOf(it)
}.toSet()
val affectedFileLoaders: LinkedHashSet<JpsFileEntitiesSerializer<*>>
val changedSources = HashSet<JpsFileEntitySource>()
synchronized(lock) {
for (addedFileUrl in addedFileUrls) {
// The file may already be processed during class initialization
if (fileSerializersByUrl.containsKey(addedFileUrl)) continue
val factory = directorySerializerFactoriesByUrl[PathUtil.getParentPath(addedFileUrl)]
val newFileSerializer = factory?.createSerializer(addedFileUrl, createFileInDirectorySource(
virtualFileManager.fromUrl(factory.directoryUrl), PathUtil.getFileName(addedFileUrl)), virtualFileManager)
if (newFileSerializer != null) {
newFileSerializers.add(newFileSerializer)
serializerToDirectoryFactory[newFileSerializer] = factory
}
}
for (changedUrl in change.changedFileUrls) {
val serializerFactory = moduleListSerializersByUrl[changedUrl]
if (serializerFactory != null) {
val newFileUrls = serializerFactory.loadFileList(reader, virtualFileManager)
val oldSerializers: List<JpsFileEntitiesSerializer<*>> = moduleSerializers.getKeysByValue(serializerFactory) ?: emptyList()
val oldFileUrls = oldSerializers.mapTo(HashSet()) { it.fileUrl }
val newFileUrlsSet = newFileUrls.mapTo(HashSet()) { it.first }
val obsoleteSerializersForFactory = oldSerializers.filter { it.fileUrl !in newFileUrlsSet }
obsoleteSerializersForFactory.forEach {
moduleSerializers.remove(it, serializerFactory)
moduleSerializerToExternalSourceBool.remove(it)
}
val newFileSerializersForFactory = newFileUrls.filter { it.first !in oldFileUrls }.map {
serializerFactory.createSerializer(createFileInDirectorySource(virtualFileManager.getParentVirtualUrl(it.first)!!,
it.first.fileName), it.first, it.second)
}
newFileSerializersForFactory.associateWithTo(moduleSerializerToExternalSourceBool) { serializerFactory.isExternalStorage }
newFileSerializersForFactory.associateWithTo(moduleSerializers) { serializerFactory }
obsoleteSerializers.addAll(obsoleteSerializersForFactory)
newFileSerializers.addAll(newFileSerializersForFactory)
}
}
for (newSerializer in newFileSerializers) {
fileSerializersByUrl.put(newSerializer.fileUrl.url, newSerializer)
}
for (obsoleteSerializer in obsoleteSerializers) {
fileSerializersByUrl.remove(obsoleteSerializer.fileUrl.url, obsoleteSerializer)
}
affectedFileLoaders = LinkedHashSet(newFileSerializers)
addedFileUrls.flatMapTo(affectedFileLoaders) { fileSerializersByUrl.getValues(it) }
change.changedFileUrls.flatMapTo(affectedFileLoaders) { fileSerializersByUrl.getValues(it) }
affectedFileLoaders.mapTo(changedSources) { it.internalEntitySource }
for (fileUrl in change.removedFileUrls) {
val directorySerializer = directorySerializerFactoriesByUrl[fileUrl]
if (directorySerializer != null) {
val serializers = serializerToDirectoryFactory.getKeysByValue(directorySerializer)?.toList() ?: emptyList()
for (serializer in serializers) {
fileSerializersByUrl.removeValue(serializer)
obsoleteSerializers.add(serializer)
serializerToDirectoryFactory.remove(serializer, directorySerializer)
}
} else {
val obsolete = fileSerializersByUrl.getValues(fileUrl)
fileSerializersByUrl.removeKey(fileUrl)
obsoleteSerializers.addAll(obsolete)
obsolete.forEach {
serializerToDirectoryFactory.remove(it)
}
}
}
obsoleteSerializers.mapTo(changedSources) { it.internalEntitySource }
obsoleteSerializers.asSequence().map { it.internalEntitySource }.filterIsInstance(JpsFileEntitySource.FileInDirectory::class.java).forEach {
fileIdToFileName.remove(it.fileNameId)
LOG.debug { "remove association for ${it.fileNameId}" }
}
}
val builder = WorkspaceEntityStorageBuilder.create()
affectedFileLoaders.forEach {
loadEntitiesAndReportExceptions(it, builder, reader, errorReporter)
}
return Pair(changedSources, builder)
}
override fun loadAll(reader: JpsFileContentReader,
builder: WorkspaceEntityStorageBuilder,
errorReporter: ErrorReporter,
project: Project?): List<EntitySource> {
val serializers = synchronized(lock) { fileSerializersByUrl.values.toList() }
val tasks = serializers.map { serializer ->
ForkJoinTask.adapt(Callable {
val myBuilder = WorkspaceEntityStorageBuilder.create()
loadEntitiesAndReportExceptions(serializer, myBuilder, reader, errorReporter)
myBuilder
})
}
ForkJoinTask.invokeAll(tasks)
val builders = tasks.mapNotNull { it.rawResult }
val sourcesToUpdate = removeDuplicatingEntities(builders, serializers, project)
val squashedBuilder = squash(builders)
builder.addDiff(squashedBuilder)
return sourcesToUpdate
}
private fun loadEntitiesAndReportExceptions(serializer: JpsFileEntitiesSerializer<*>,
builder: WorkspaceEntityStorageBuilder,
reader: JpsFileContentReader,
errorReporter: ErrorReporter) {
fun reportError(e: Exception, url: VirtualFileUrl) {
errorReporter.reportError(ProjectModelBundle.message("module.cannot.load.error", url.presentableUrl, e.localizedMessage), url)
}
try {
serializer.loadEntities(builder, reader, errorReporter, virtualFileManager)
}
catch (e: JDOMException) {
reportError(e, serializer.fileUrl)
}
catch (e: IOException) {
reportError(e, serializer.fileUrl)
}
}
// Check if the same module is loaded from different source. This may happen in case of two `modules.xml` with the same module.
// See IDEA-257175
// This code may be removed if we'll get rid of storing modules.xml and friends in external storage (cache/external_build_system)
private fun removeDuplicatingEntities(builders: List<WorkspaceEntityStorageBuilder>, serializers: List<JpsFileEntitiesSerializer<*>>, project: Project?): List<EntitySource> {
if (project == null) return emptyList()
val modules = mutableMapOf<String, MutableList<Triple<ModuleId, WorkspaceEntityStorageBuilder, JpsFileEntitiesSerializer<*>>>>()
val libraries = mutableMapOf<LibraryId, MutableList<Pair<WorkspaceEntityStorageBuilder, JpsFileEntitiesSerializer<*>>>>()
val artifacts = mutableMapOf<ArtifactId, MutableList<Pair<WorkspaceEntityStorageBuilder, JpsFileEntitiesSerializer<*>>>>()
builders.forEachIndexed { i, builder ->
if (enableExternalStorage) {
builder.entities(ModuleEntity::class.java).forEach { module ->
val moduleId = module.persistentId()
modules.getOrPut(moduleId.name.toLowerCase(Locale.US)) { ArrayList() }.add(Triple(moduleId, builder, serializers[i]))
}
}
builder.entities(LibraryEntity::class.java).filter { it.tableId == LibraryTableId.ProjectLibraryTableId }.forEach { library ->
libraries.getOrPut(library.persistentId()) { ArrayList() }.add(builder to serializers[i])
}
builder.entities(ArtifactEntity::class.java).forEach { artifact ->
artifacts.getOrPut(artifact.persistentId()) { ArrayList() }.add(builder to serializers[i])
}
}
val sourcesToUpdate = mutableListOf<EntitySource>()
for ((_, buildersWithModule) in modules) {
if (buildersWithModule.size <= 1) continue
var correctModuleFound = false
var leftModuleId = 0
// Leave only first module with "correct" entity source
// If there is no such module, leave the last one
buildersWithModule.forEachIndexed { index, (moduleId, builder, ser) ->
val originalExternal = moduleSerializerToExternalSourceBool[ser] ?: return@forEachIndexed
val moduleEntity = builder.resolve(moduleId)!!
if (index != buildersWithModule.lastIndex) {
if (!correctModuleFound && originalExternal) {
correctModuleFound = true
leftModuleId = index
}
else {
sourcesToUpdate += moduleEntity.entitySource
builder.removeEntity(moduleEntity)
}
}
else {
if (correctModuleFound) {
sourcesToUpdate += moduleEntity.entitySource
builder.removeEntity(moduleEntity)
}
else {
leftModuleId = index
}
}
}
reportIssue(project, buildersWithModule.mapTo(HashSet()) { it.first }, buildersWithModule.map { it.third }, leftModuleId)
}
for ((libraryId, buildersWithSerializers) in libraries) {
if (buildersWithSerializers.size <= 1) continue
val defaultFileName = FileUtil.sanitizeFileName(libraryId.name) + ".xml"
val hasImportedEntity = buildersWithSerializers.any { (builder, _) ->
builder.resolve(libraryId)!!.entitySource is JpsImportedEntitySource
}
val entitiesToRemove = buildersWithSerializers.mapNotNull { (builder, serializer) ->
val library = builder.resolve(libraryId)!!
val entitySource = library.entitySource
if (entitySource !is JpsFileEntitySource.FileInDirectory) return@mapNotNull null
val fileName = serializer.fileUrl.fileName
if (fileName != defaultFileName || enableExternalStorage && hasImportedEntity) Triple(builder, library, fileName) else null
}
LOG.warn("Multiple configuration files were found for '${libraryId.name}' library.")
if (entitiesToRemove.isNotEmpty() && entitiesToRemove.size < buildersWithSerializers.size) {
for ((builder, entity) in entitiesToRemove) {
sourcesToUpdate.add(entity.entitySource)
builder.removeEntity(entity)
}
LOG.warn("Libraries defined in ${entitiesToRemove.joinToString { it.third }} files will ignored and these files will be removed.")
}
else {
LOG.warn("Cannot determine which configuration file should be ignored: ${buildersWithSerializers.map { it.second }}")
}
}
for ((artifactId, buildersWithSerializers) in artifacts) {
if (buildersWithSerializers.size <= 1) continue
val defaultFileName = FileUtil.sanitizeFileName(artifactId.name) + ".xml"
val hasImportedEntity = buildersWithSerializers.any { (builder, _) ->
builder.resolve(artifactId)!!.entitySource is JpsImportedEntitySource
}
val entitiesToRemove = buildersWithSerializers.mapNotNull { (builder, serializer) ->
val artifact = builder.resolve(artifactId)!!
val entitySource = artifact.entitySource
if (entitySource !is JpsFileEntitySource.FileInDirectory) return@mapNotNull null
val fileName = serializer.fileUrl.fileName
if (fileName != defaultFileName || enableExternalStorage && hasImportedEntity) Triple(builder, artifact, fileName) else null
}
LOG.warn("Multiple configuration files were found for '${artifactId.name}' artifact.")
if (entitiesToRemove.isNotEmpty() && entitiesToRemove.size < buildersWithSerializers.size) {
for ((builder, entity) in entitiesToRemove) {
sourcesToUpdate.add(entity.entitySource)
builder.removeEntity(entity)
}
LOG.warn("Artifacts defined in ${entitiesToRemove.joinToString { it.third }} files will ignored and these files will be removed.")
}
else {
LOG.warn("Cannot determine which configuration file should be ignored: ${buildersWithSerializers.map { it.second }}")
}
}
return sourcesToUpdate
}
private fun reportIssue(project: Project, moduleIds: Set<ModuleId>, serializers: List<JpsFileEntitiesSerializer<*>>, leftModuleId: Int) {
var serializerCounter = -1
val attachments = mutableMapOf<String, Attachment>()
val serializersInfo = serializers.joinToString(separator = "\n\n") {
serializerCounter++
it as ModuleImlFileEntitiesSerializer
val externalFileUrl = it.let {
it.externalModuleListSerializer?.createSerializer(it.internalEntitySource, it.fileUrl, it.modulePath.group)
}?.fileUrl
val fileUrl = it.fileUrl
val internalModuleListSerializerUrl = it.internalModuleListSerializer?.fileUrl
val externalModuleListSerializerUrl = it.externalModuleListSerializer?.fileUrl
if (externalFileUrl != null && FileUtil.exists(JpsPathUtil.urlToPath(externalFileUrl.url))) {
attachments[externalFileUrl.url] = AttachmentFactory.createAttachment(externalFileUrl.toPath(), false)
}
if (FileUtil.exists(JpsPathUtil.urlToPath(fileUrl.url))) {
attachments[fileUrl.url] = AttachmentFactory.createAttachment(fileUrl.toPath(), false)
}
if (internalModuleListSerializerUrl != null && FileUtil.exists(JpsPathUtil.urlToPath(internalModuleListSerializerUrl))) {
attachments[internalModuleListSerializerUrl] = AttachmentFactory.createAttachment(
Path.of(JpsPathUtil.urlToPath(internalModuleListSerializerUrl)
), false)
}
if (externalModuleListSerializerUrl != null && FileUtil.exists(JpsPathUtil.urlToPath(externalModuleListSerializerUrl))) {
attachments[externalModuleListSerializerUrl] = AttachmentFactory.createAttachment(
Path.of(JpsPathUtil.urlToPath(externalModuleListSerializerUrl)), false
)
}
"""
Serializer info #$serializerCounter:
Is external: ${moduleSerializerToExternalSourceBool[it]}
fileUrl: ${fileUrl.presentableUrl}
externalFileUrl: ${externalFileUrl?.presentableUrl}
internal modules.xml: $internalModuleListSerializerUrl
external modules.xml: $externalModuleListSerializerUrl
""".trimIndent()
}
val text = """
|Trying to load multiple modules with the same name.
|
|Project: ${project.name}
|Module: ${moduleIds.map { it.name }}
|Amount of modules: ${serializers.size}
|Leave module of nth serializer: $leftModuleId
|
|$serializersInfo
""".trimMargin()
LOG.error(text, *attachments.values.toTypedArray())
}
private fun squash(builders: List<WorkspaceEntityStorageBuilder>): WorkspaceEntityStorageBuilder {
var result = builders
while (result.size > 1) {
result = result.chunked(2) { list ->
val res = list.first()
if (list.size == 2) res.addDiff(list.last())
res
}
}
return result.singleOrNull() ?: WorkspaceEntityStorageBuilder.create() }
@TestOnly
override fun saveAllEntities(storage: WorkspaceEntityStorage, writer: JpsFileContentWriter) {
moduleListSerializersByUrl.values.forEach {
saveModulesList(it, storage, writer)
}
val allSources = storage.entitiesBySource { true }.keys
saveEntities(storage, allSources, writer)
}
internal fun getActualFileUrl(source: EntitySource): String? {
val actualFileSource = getActualFileSource(source) ?: return null
return when (actualFileSource) {
is JpsFileEntitySource.ExactFile -> actualFileSource.file.url
is JpsFileEntitySource.FileInDirectory -> {
val fileName = fileIdToFileName.get(actualFileSource.fileNameId) ?: run {
// We have a situations when we don't have an association at for `fileIdToFileName` entity source returned from `getActualFileSource`
// but we have it for the original `JpsImportedEntitySource.internalFile` and base on it we try to calculate actual file url
if (source is JpsImportedEntitySource && source.internalFile is JpsFileEntitySource.FileInDirectory && source.storedExternally) {
fileIdToFileName.get((source.internalFile as JpsFileEntitySource.FileInDirectory).fileNameId)?.substringBeforeLast(".")?.let { "$it.xml" }
} else null
}
if (fileName != null) actualFileSource.directory.url + "/" + fileName else null
}
else -> error("Unexpected implementation of JpsFileEntitySource: ${actualFileSource.javaClass}")
}
}
private fun getActualFileSource(source: EntitySource): JpsFileEntitySource? {
return when (source) {
is JpsImportedEntitySource -> {
if (source.storedExternally) {
//todo remove obsolete entries
internalSourceToExternal.getOrPut(source.internalFile) { externalStorageMapping.getExternalSource(source.internalFile) }
}
else {
source.internalFile
}
}
else -> getInternalFileSource(source)
}
}
override fun getAllModulePaths(): List<ModulePath> {
synchronized(lock) {
return fileSerializersByUrl.values.filterIsInstance<ModuleImlFileEntitiesSerializer>().mapTo(LinkedHashSet()) { it.modulePath }.toList()
}
}
override fun saveEntities(storage: WorkspaceEntityStorage, affectedSources: Set<EntitySource>, writer: JpsFileContentWriter) {
val affectedModuleListSerializers = HashSet<JpsModuleListSerializer>()
val serializersToRun = HashMap<JpsFileEntitiesSerializer<*>, MutableMap<Class<out WorkspaceEntity>, MutableSet<WorkspaceEntity>>>()
synchronized(lock) {
if (LOG.isTraceEnabled) {
LOG.trace("save entities; current serializers (${fileSerializersByUrl.values.size}):")
fileSerializersByUrl.values.forEach {
LOG.trace(it.toString())
}
}
val affectedEntityTypeSerializers = HashSet<JpsFileEntityTypeSerializer<*>>()
fun processObsoleteSource(fileUrl: String, deleteModuleFile: Boolean) {
val obsoleteSerializers = fileSerializersByUrl.getValues(fileUrl)
fileSerializersByUrl.removeKey(fileUrl)
LOG.trace { "processing obsolete source $fileUrl: serializers = $obsoleteSerializers" }
obsoleteSerializers.forEach {
// Clean up module files content
val moduleListSerializer = moduleSerializers.remove(it)
if (moduleListSerializer != null) {
if (deleteModuleFile) {
moduleListSerializer.deleteObsoleteFile(fileUrl, writer)
}
LOG.trace { "affected module list: $moduleListSerializer" }
affectedModuleListSerializers.add(moduleListSerializer)
}
// Remove libraries under `.idea/libraries` folder
val directoryFactory = serializerToDirectoryFactory.remove(it)
if (directoryFactory != null) {
writer.saveComponent(fileUrl, directoryFactory.componentName, null)
}
// Remove libraries under `external_build_system/libraries` folder
if (it in entityTypeSerializers) {
if (getFilteredEntitiesForSerializer(it as JpsFileEntityTypeSerializer, storage).isEmpty()) {
it.deleteObsoleteFile(fileUrl, writer)
}
else {
affectedEntityTypeSerializers.add(it)
}
}
}
}
val sourcesStoredInternally = affectedSources.asSequence().filterIsInstance<JpsImportedEntitySource>()
.filter { !it.storedExternally }
.associateBy { it.internalFile }
val internalSourcesOfCustomModuleEntitySources = affectedSources.mapNotNullTo(HashSet()) { (it as? CustomModuleEntitySource)?.internalSource }
/* Entities added via JPS and imported entities stored in internal storage must be passed to serializers together, otherwise incomplete
data will be stored.
It isn't necessary to save entities stored in external storage when their internal parts are affected, but add them to the list
to ensure that obsolete *.iml files will be removed if their modules are stored in external storage.
*/
val entitiesToSave = storage.entitiesBySource { source ->
source in affectedSources
|| source in sourcesStoredInternally
|| source is JpsImportedEntitySource && source.internalFile in affectedSources
|| source in internalSourcesOfCustomModuleEntitySources
|| source is CustomModuleEntitySource && source.internalSource in affectedSources
}
if (LOG.isTraceEnabled) {
LOG.trace("Affected sources: $affectedSources")
LOG.trace("Entities to save:")
for ((source, entities) in entitiesToSave) {
LOG.trace(" $source: $entities")
}
}
val internalSourceConvertedToImported = affectedSources.filterIsInstance<JpsImportedEntitySource>().mapTo(HashSet()) {
it.internalFile
}
val sourcesStoredExternally = entitiesToSave.keys.asSequence().filterIsInstance<JpsImportedEntitySource>()
.filter { it.storedExternally }
.associateBy { it.internalFile }
val obsoleteSources = affectedSources - entitiesToSave.keys
LOG.trace { "Obsolete sources: $obsoleteSources" }
for (source in obsoleteSources) {
val fileUrl = getActualFileUrl(source)
if (fileUrl != null) {
val affectedImportedSourceStoredExternally = when {
source is JpsImportedEntitySource && source.storedExternally -> sourcesStoredInternally[source.internalFile]
source is JpsImportedEntitySource && !source.storedExternally -> sourcesStoredExternally[source.internalFile]
source is JpsFileEntitySource -> sourcesStoredExternally[source]
else -> null
}
// When user removes module from project we don't delete corresponding *.iml file located under project directory by default
// (because it may be included in other projects). However we do remove the module file if module actually wasn't removed, just
// its storage has been changed, e.g. if module was marked as imported from external system, or the place where module imported
// from external system was changed, or part of a module configuration is imported from external system and data stored in *.iml
// file was removed.
val deleteObsoleteFile = source in internalSourceConvertedToImported || (affectedImportedSourceStoredExternally != null &&
affectedImportedSourceStoredExternally !in obsoleteSources)
processObsoleteSource(fileUrl, deleteObsoleteFile)
val actualSource = if (source is JpsImportedEntitySource && !source.storedExternally) source.internalFile else source
if (actualSource is JpsFileEntitySource.FileInDirectory) {
fileIdToFileName.remove(actualSource.fileNameId)
LOG.debug { "remove association for obsolete source $actualSource" }
}
}
}
fun processNewlyAddedDirectoryEntities(entitiesMap: Map<Class<out WorkspaceEntity>, List<WorkspaceEntity>>) {
directorySerializerFactoriesByUrl.values.forEach { factory ->
val added = entitiesMap[factory.entityClass]
if (added != null) {
val newSerializers = createSerializersForDirectoryEntities(factory, added)
newSerializers.forEach {
serializerToDirectoryFactory[it.key] = factory
fileSerializersByUrl.put(it.key.fileUrl.url, it.key)
}
newSerializers.forEach { (serializer, entitiesMap) -> mergeSerializerEntitiesMap(serializersToRun, serializer, entitiesMap) }
}
}
}
entitiesToSave.forEach { (source, entities) ->
val actualFileSource = getActualFileSource(source)
if (actualFileSource is JpsFileEntitySource.FileInDirectory) {
val fileNameByEntity = calculateFileNameForEntity(actualFileSource, source, entities)
val oldFileName = fileIdToFileName.get(actualFileSource.fileNameId)
if (oldFileName != fileNameByEntity) {
// Don't convert to links[key] = ... because it *may* became autoboxing
@Suppress("ReplacePutWithAssignment")
fileIdToFileName.put(actualFileSource.fileNameId, fileNameByEntity)
LOG.debug { "update association for ${actualFileSource.fileNameId} to $fileNameByEntity (was $oldFileName)" }
if (oldFileName != null) {
processObsoleteSource("${actualFileSource.directory.url}/$oldFileName", true)
}
val existingSerializers = fileSerializersByUrl.getValues("${actualFileSource.directory.url}/$fileNameByEntity").filter {
it in serializerToDirectoryFactory
}
if (existingSerializers.isNotEmpty()) {
val existingSources = existingSerializers.map { it.internalEntitySource }
val entitiesWithOldSource = storage.entitiesBySource { it in existingSources }
val entitiesPersistentIds = entitiesWithOldSource.values
.flatMap { it.values }
.flatten()
.filterIsInstance<WorkspaceEntityWithPersistentId>()
.joinToString(separator = "||") { "$it (PersistentId: ${it.persistentId()})" }
//technically this is not an error, but cases when different entities have the same default file name are rare so let's report this
// as error for now to find real cause of IDEA-265327
val message = """
|Cannot save entities to $fileNameByEntity because it's already used for other entities;
|Current entity source: $actualFileSource
|Old file name: $oldFileName
|Existing serializers: $existingSerializers
|Their entity sources: $existingSources
|Entities with these sources in the storage: ${entitiesWithOldSource.mapValues { (_, value) -> value.values }}
|Entities with persistent ids: $entitiesPersistentIds
|Original entities to save: ${entities.values.flatten().joinToString(separator = "||") { "$it (Persistent Id: ${(it as? WorkspaceEntityWithPersistentId)?.persistentId()})" }}
""".trimMargin()
reportErrorAndAttachStorage(message, storage)
}
if (existingSerializers.isEmpty() || existingSerializers.any { it.internalEntitySource != actualFileSource }) {
processNewlyAddedDirectoryEntities(entities)
}
}
}
val url = getActualFileUrl(source)
val internalSource = getInternalFileSource(source)
if (url != null && internalSource != null
&& (ModuleEntity::class.java in entities || FacetEntity::class.java in entities || ModuleGroupPathEntity::class.java in entities)) {
val existingSerializers = fileSerializersByUrl.getValues(url)
val moduleGroup = (entities[ModuleGroupPathEntity::class.java]?.first() as? ModuleGroupPathEntity)?.path?.joinToString("/")
if (existingSerializers.isEmpty() || existingSerializers.any { it is ModuleImlFileEntitiesSerializer && it.modulePath.group != moduleGroup }) {
moduleListSerializersByUrl.values.forEach { moduleListSerializer ->
if (moduleListSerializer.entitySourceFilter(source)) {
if (existingSerializers.isNotEmpty()) {
existingSerializers.forEach {
if (it is ModuleImlFileEntitiesSerializer) {
moduleSerializers.remove(it)
fileSerializersByUrl.remove(url, it)
}
}
}
val newSerializer = moduleListSerializer.createSerializer(internalSource, virtualFileManager.fromUrl(url), moduleGroup)
fileSerializersByUrl.put(url, newSerializer)
moduleSerializers[newSerializer] = moduleListSerializer
affectedModuleListSerializers.add(moduleListSerializer)
}
}
}
for (serializer in existingSerializers) {
val moduleListSerializer = moduleSerializers[serializer]
val storedExternally = moduleSerializerToExternalSourceBool[serializer]
if (moduleListSerializer != null && storedExternally != null &&
(moduleListSerializer.isExternalStorage == storedExternally && !moduleListSerializer.entitySourceFilter(source)
|| moduleListSerializer.isExternalStorage != storedExternally && moduleListSerializer.entitySourceFilter(source))) {
moduleSerializerToExternalSourceBool[serializer] = !storedExternally
affectedModuleListSerializers.add(moduleListSerializer)
}
}
}
}
entitiesToSave.forEach { (source, entities) ->
val serializers = fileSerializersByUrl.getValues(getActualFileUrl(source))
serializers.filter { it !is JpsFileEntityTypeSerializer }.forEach { serializer ->
mergeSerializerEntitiesMap(serializersToRun, serializer, entities)
}
}
for (serializer in entityTypeSerializers) {
if (entitiesToSave.any { serializer.mainEntityClass in it.value } || serializer in affectedEntityTypeSerializers) {
val entitiesMap = mutableMapOf(serializer.mainEntityClass to getFilteredEntitiesForSerializer(serializer, storage))
serializer.additionalEntityTypes.associateWithTo(entitiesMap) {
storage.entities(it).toList()
}
fileSerializersByUrl.put(serializer.fileUrl.url, serializer)
mergeSerializerEntitiesMap(serializersToRun, serializer, entitiesMap)
}
}
}
if (affectedModuleListSerializers.isNotEmpty()) {
moduleListSerializersByUrl.values.forEach {
saveModulesList(it, storage, writer)
}
}
serializersToRun.forEach {
saveEntitiesBySerializer(it.key, it.value.mapValues { entitiesMapEntry -> entitiesMapEntry.value.toList() }, storage, writer)
}
}
override fun changeEntitySourcesToDirectoryBasedFormat(builder: WorkspaceEntityStorageBuilder) {
for (factory in directorySerializerFactoriesByUrl.values) {
factory.changeEntitySourcesToDirectoryBasedFormat(builder, configLocation)
}
}
private fun mergeSerializerEntitiesMap(existingSerializer2EntitiesMap: HashMap<JpsFileEntitiesSerializer<*>, MutableMap<Class<out WorkspaceEntity>, MutableSet<WorkspaceEntity>>>,
serializer: JpsFileEntitiesSerializer<*>,
entitiesMap: Map<Class<out WorkspaceEntity>, List<WorkspaceEntity>>) {
val existingEntitiesMap = existingSerializer2EntitiesMap.getOrPut(serializer) { HashMap() }
entitiesMap.forEach { (type, entity) ->
val existingEntities = existingEntitiesMap.getOrPut(type) { HashSet() }
existingEntities.addAll(entity)
}
}
private fun calculateFileNameForEntity(source: JpsFileEntitySource.FileInDirectory,
originalSource: EntitySource,
entities: Map<Class<out WorkspaceEntity>, List<WorkspaceEntity>>): String? {
val directoryFactory = directorySerializerFactoriesByUrl[source.directory.url]
if (directoryFactory != null) {
return getDefaultFileNameForEntity(directoryFactory, entities)
}
if (ModuleEntity::class.java in entities || FacetEntity::class.java in entities) {
val moduleListSerializer = moduleListSerializersByUrl.values.find {
it.entitySourceFilter(originalSource)
}
if (moduleListSerializer != null) {
return getFileNameForModuleEntity(moduleListSerializer, entities)
}
}
return null
}
private fun <E : WorkspaceEntity> getDefaultFileNameForEntity(directoryFactory: JpsDirectoryEntitiesSerializerFactory<E>,
entities: Map<Class<out WorkspaceEntity>, List<WorkspaceEntity>>): String? {
@Suppress("UNCHECKED_CAST") val entity = entities[directoryFactory.entityClass]?.singleOrNull() as? E ?: return null
return FileUtil.sanitizeFileName(directoryFactory.getDefaultFileName(entity)) + ".xml"
}
private fun getFileNameForModuleEntity(moduleListSerializer: JpsModuleListSerializer,
entities: Map<Class<out WorkspaceEntity>, List<WorkspaceEntity>>): String? {
val entity = entities[ModuleEntity::class.java]?.singleOrNull() as? ModuleEntity
if (entity != null) {
return moduleListSerializer.getFileName(entity)
}
val additionalEntity = entities[FacetEntity::class.java]?.firstOrNull() as? FacetEntity ?: return null
return moduleListSerializer.getFileName(additionalEntity.module)
}
private fun <E : WorkspaceEntity> getFilteredEntitiesForSerializer(serializer: JpsFileEntityTypeSerializer<E>,
storage: WorkspaceEntityStorage): List<E> {
return storage.entities(serializer.mainEntityClass).filter(serializer.entityFilter).toList()
}
private fun <E : WorkspaceEntity> saveEntitiesBySerializer(serializer: JpsFileEntitiesSerializer<E>,
entities: Map<Class<out WorkspaceEntity>, List<WorkspaceEntity>>,
storage: WorkspaceEntityStorage,
writer: JpsFileContentWriter) {
@Suppress("UNCHECKED_CAST")
serializer.saveEntities(entities[serializer.mainEntityClass] as? Collection<E> ?: emptyList(), entities, storage, writer)
}
private fun <E : WorkspaceEntity> createSerializersForDirectoryEntities(factory: JpsDirectoryEntitiesSerializerFactory<E>,
entities: List<WorkspaceEntity>)
: Map<JpsFileEntitiesSerializer<*>, Map<Class<out WorkspaceEntity>, List<WorkspaceEntity>>> {
val serializers = serializerToDirectoryFactory.getKeysByValue(factory) ?: emptyList()
val nameGenerator = UniqueNameGenerator(serializers, Function {
PathUtil.getFileName(it.fileUrl.url)
})
return entities.asSequence()
.filter { @Suppress("UNCHECKED_CAST") factory.entityFilter(it as E) }
.associate { entity ->
@Suppress("UNCHECKED_CAST")
val defaultFileName = FileUtil.sanitizeFileName(factory.getDefaultFileName(entity as E))
val fileName = nameGenerator.generateUniqueName(defaultFileName, "", ".xml")
val entityMap = mapOf<Class<out WorkspaceEntity>, List<WorkspaceEntity>>(factory.entityClass to listOf(entity))
val currentSource = entity.entitySource as? JpsFileEntitySource.FileInDirectory
val source =
if (currentSource != null && fileIdToFileName.get(currentSource.fileNameId) == fileName) currentSource
else createFileInDirectorySource(virtualFileManager.fromUrl(factory.directoryUrl), fileName)
factory.createSerializer("${factory.directoryUrl}/$fileName", source, virtualFileManager) to entityMap
}
}
private fun saveModulesList(it: JpsModuleListSerializer, storage: WorkspaceEntityStorage, writer: JpsFileContentWriter) {
LOG.trace("saving modules list")
it.saveEntitiesList(storage.entities(ModuleEntity::class.java), writer)
}
companion object {
private val LOG = logger<JpsProjectSerializersImpl>()
}
}
class CachingJpsFileContentReader(private val configLocation: JpsProjectConfigLocation) : JpsFileContentReader {
private val projectPathMacroManager = ProjectPathMacroManager.createInstance(
configLocation::projectFilePath,
{ JpsPathUtil.urlToPath(configLocation.baseDirectoryUrlString) },
null
)
private val fileContentCache = ConcurrentHashMap<String, Map<String, Element>>()
override fun loadComponent(fileUrl: String, componentName: String, customModuleFilePath: String?): Element? {
val content = fileContentCache.computeIfAbsent(fileUrl + customModuleFilePath) {
loadComponents(fileUrl, customModuleFilePath)
}
return content[componentName]
}
override fun getExpandMacroMap(fileUrl: String): ExpandMacroToPathMap {
return getMacroManager(fileUrl, null).expandMacroMap
}
private fun loadComponents(fileUrl: String, customModuleFilePath: String?): Map<String, Element> {
val macroManager = getMacroManager(fileUrl, customModuleFilePath)
val file = Paths.get(JpsPathUtil.urlToPath(fileUrl))
return if (Files.isRegularFile(file)) loadStorageFile(file, macroManager) else emptyMap()
}
private fun getMacroManager(fileUrl: String,
customModuleFilePath: String?): PathMacroManager {
val path = JpsPathUtil.urlToPath(fileUrl)
return if (FileUtil.extensionEquals(fileUrl, "iml") || isExternalModuleFile(path)) {
ModulePathMacroManager.createInstance(configLocation::projectFilePath, Supplier { customModuleFilePath ?: path })
}
else {
projectPathMacroManager
}
}
}
internal fun Element.getAttributeValueStrict(name: String): String =
getAttributeValue(name) ?: throw JDOMException("Expected attribute $name under ${this.name} element")
fun isExternalModuleFile(filePath: String): Boolean {
val parentPath = PathUtil.getParentPath(filePath)
return FileUtil.extensionEquals(filePath, "xml") && PathUtil.getFileName(parentPath) == "modules"
&& PathUtil.getFileName(PathUtil.getParentPath(parentPath)) != ".idea"
}
internal fun getInternalFileSource(source: EntitySource) = when (source) {
is JpsFileDependentEntitySource -> source.originalSource
is CustomModuleEntitySource -> source.internalSource
is JpsFileEntitySource -> source
else -> null
}
| apache-2.0 | feb8f6dc10e10fb0ede898d49531e7cb | 50.932584 | 187 | 0.700303 | 5.847672 | false | false | false | false |
dahlstrom-g/intellij-community | plugins/kotlin/frontend-independent/src/org/jetbrains/kotlin/idea/quickfix/RemoveRedundantSpreadOperatorFix.kt | 3 | 1568 | /*
* Copyright 2010-2021 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlin.idea.quickfix
import com.intellij.codeInsight.intention.IntentionAction
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiElement
import org.jetbrains.kotlin.idea.KotlinBundle
import org.jetbrains.kotlin.psi.KtExpression
import org.jetbrains.kotlin.psi.KtFile
import org.jetbrains.kotlin.psi.KtValueArgument
import org.jetbrains.kotlin.psi.psiUtil.getParentOfType
class RemoveRedundantSpreadOperatorFix(argument: KtExpression) : KotlinPsiOnlyQuickFixAction<KtExpression>(argument) {
override fun getText(): String = KotlinBundle.message("fix.remove.redundant.star.text")
override fun getFamilyName(): String = text
override fun invoke(project: Project, editor: Editor?, file: KtFile) {
val argument = element?.getParentOfType<KtValueArgument>(false) ?: return
val spreadElement = argument.getSpreadElement() ?: return
spreadElement.delete()
}
companion object : QuickFixesPsiBasedFactory<PsiElement>(PsiElement::class, PsiElementSuitabilityCheckers.ALWAYS_SUITABLE) {
override fun doCreateQuickFix(psiElement: PsiElement): List<IntentionAction> {
val element = psiElement as? KtExpression ?: return emptyList()
return listOf(RemoveRedundantSpreadOperatorFix(element))
}
}
} | apache-2.0 | ef7b0906b0924fd5fe840ca597df6a2d | 43.828571 | 128 | 0.772959 | 4.824615 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/base/fe10/analysis/src/org/jetbrains/kotlin/idea/caches/resolve/PerFileAnalysisCache.kt | 2 | 25924 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.kotlin.idea.caches.resolve
import com.google.common.collect.ImmutableMap
import com.intellij.openapi.diagnostic.ControlFlowException
import com.intellij.openapi.progress.ProcessCanceledException
import com.intellij.openapi.progress.ProgressIndicatorProvider
import com.intellij.openapi.project.DumbService
import com.intellij.openapi.project.IndexNotReadyException
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.ModificationTracker
import com.intellij.psi.PsiElement
import com.intellij.psi.util.findParentInFile
import com.intellij.psi.util.findTopmostParentInFile
import com.intellij.psi.util.findTopmostParentOfType
import org.jetbrains.kotlin.analyzer.AnalysisResult
import org.jetbrains.kotlin.cfg.ControlFlowInformationProviderImpl
import org.jetbrains.kotlin.container.ComponentProvider
import org.jetbrains.kotlin.container.get
import org.jetbrains.kotlin.context.GlobalContext
import org.jetbrains.kotlin.context.withModule
import org.jetbrains.kotlin.context.withProject
import org.jetbrains.kotlin.descriptors.InvalidModuleException
import org.jetbrains.kotlin.descriptors.ModuleDescriptor
import org.jetbrains.kotlin.diagnostics.Diagnostic
import org.jetbrains.kotlin.diagnostics.DiagnosticFactoryWithPsiElement
import org.jetbrains.kotlin.diagnostics.DiagnosticSink
import org.jetbrains.kotlin.diagnostics.DiagnosticUtils
import org.jetbrains.kotlin.diagnostics.PositioningStrategies.DECLARATION_WITH_BODY
import org.jetbrains.kotlin.frontend.di.createContainerForLazyBodyResolve
import org.jetbrains.kotlin.idea.base.projectStructure.compositeAnalysis.findAnalyzerServices
import org.jetbrains.kotlin.idea.base.projectStructure.languageVersionSettings
import org.jetbrains.kotlin.idea.base.projectStructure.moduleInfo
import org.jetbrains.kotlin.idea.caches.trackers.clearInBlockModifications
import org.jetbrains.kotlin.idea.caches.trackers.inBlockModifications
import org.jetbrains.kotlin.idea.compiler.IdeMainFunctionDetectorFactory
import org.jetbrains.kotlin.idea.compiler.IdeSealedClassInheritorsProvider
import org.jetbrains.kotlin.idea.project.IdeaModuleStructureOracle
import org.jetbrains.kotlin.idea.util.application.withPsiAttachment
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.parentsWithSelf
import org.jetbrains.kotlin.resolve.*
import org.jetbrains.kotlin.resolve.diagnostics.Diagnostics
import org.jetbrains.kotlin.resolve.diagnostics.DiagnosticsElementsCache
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
import org.jetbrains.kotlin.resolve.lazy.ResolveSession
import org.jetbrains.kotlin.storage.CancellableSimpleLock
import org.jetbrains.kotlin.storage.guarded
import org.jetbrains.kotlin.types.KotlinType
import org.jetbrains.kotlin.util.slicedMap.ReadOnlySlice
import org.jetbrains.kotlin.util.slicedMap.WritableSlice
import org.jetbrains.kotlin.utils.addToStdlib.safeAs
import org.jetbrains.kotlin.utils.checkWithAttachment
import java.util.concurrent.locks.ReentrantLock
internal class PerFileAnalysisCache(val file: KtFile, componentProvider: ComponentProvider) {
private val globalContext = componentProvider.get<GlobalContext>()
private val moduleDescriptor = componentProvider.get<ModuleDescriptor>()
private val resolveSession = componentProvider.get<ResolveSession>()
private val codeFragmentAnalyzer = componentProvider.get<CodeFragmentAnalyzer>()
private val bodyResolveCache = componentProvider.get<BodyResolveCache>()
private val cache = HashMap<PsiElement, AnalysisResult>()
private var fileResult: AnalysisResult? = null
private val lock = ReentrantLock()
private val guardLock = CancellableSimpleLock(lock,
checkCancelled = {
ProgressIndicatorProvider.checkCanceled()
},
interruptedExceptionHandler = { throw ProcessCanceledException(it) })
private fun check(element: KtElement) {
checkWithAttachment(element.containingFile == file, {
"Expected $file, but was ${element.containingFile} for ${if (element.isValid) "valid" else "invalid"} $element "
}) {
it.withPsiAttachment("element.kt", element)
it.withPsiAttachment("file.kt", element.containingFile)
it.withPsiAttachment("original.kt", file)
}
}
internal val isValid: Boolean get() = moduleDescriptor.isValid
internal fun fetchAnalysisResults(element: KtElement): AnalysisResult? {
check(element)
if (lock.tryLock()) {
try {
updateFileResultFromCache()
return fileResult?.takeIf { file.inBlockModifications.isEmpty() }
} finally {
lock.unlock()
}
}
return null
}
internal fun getAnalysisResults(element: KtElement, callback: DiagnosticSink.DiagnosticsCallback? = null): AnalysisResult {
check(element)
val analyzableParent = KotlinResolveDataProvider.findAnalyzableParent(element) ?: return AnalysisResult.EMPTY
fun handleResult(result: AnalysisResult, callback: DiagnosticSink.DiagnosticsCallback?): AnalysisResult {
callback?.let { result.bindingContext.diagnostics.forEach(it::callback) }
return result
}
return guardLock.guarded {
// step 1: perform incremental analysis IF it is applicable
getIncrementalAnalysisResult(callback)?.let {
return@guarded handleResult(it, callback)
}
// cache does not contain AnalysisResult per each kt/psi element
// instead it looks up analysis for its parents - see lookUp(analyzableElement)
// step 2: return result if it is cached
lookUp(analyzableParent)?.let {
return@guarded handleResult(it, callback)
}
val localDiagnostics = mutableSetOf<Diagnostic>()
val localCallback = if (callback != null) { d: Diagnostic ->
localDiagnostics.add(d)
callback.callback(d)
} else null
// step 3: perform analyze of analyzableParent as nothing has been cached yet
val result = try {
analyze(analyzableParent, null, localCallback)
} catch (e: Throwable) {
e.throwAsInvalidModuleException {
ProcessCanceledException(it)
}
throw e
}
// some diagnostics could be not handled with a callback - send out the rest
callback?.let { c ->
result.bindingContext.diagnostics.filterNot { it in localDiagnostics }.forEach(c::callback)
}
cache[analyzableParent] = result
return@guarded result
}
}
private fun getIncrementalAnalysisResult(callback: DiagnosticSink.DiagnosticsCallback?): AnalysisResult? {
updateFileResultFromCache()
val inBlockModifications = file.inBlockModifications
if (inBlockModifications.isNotEmpty()) {
try {
// IF there is a cached result for ktFile and there are inBlockModifications
fileResult = fileResult?.let { result ->
var analysisResult = result
// Force full analysis when existed is erroneous
if (analysisResult.isError()) return@let null
for (inBlockModification in inBlockModifications) {
val resultCtx = analysisResult.bindingContext
val stackedCtx =
if (resultCtx is StackedCompositeBindingContextTrace.StackedCompositeBindingContext) resultCtx else null
// no incremental analysis IF it is not applicable
if (stackedCtx?.isIncrementalAnalysisApplicable() == false) return@let null
val trace: StackedCompositeBindingContextTrace =
if (stackedCtx != null && stackedCtx.element() == inBlockModification) {
val trace = stackedCtx.bindingTrace()
trace.clear()
trace
} else {
// to reflect a depth of stacked binding context
val depth = (stackedCtx?.depth() ?: 0) + 1
StackedCompositeBindingContextTrace(
depth,
element = inBlockModification,
resolveContext = resolveSession.bindingContext,
parentContext = resultCtx
)
}
callback?.let { trace.parentDiagnosticsApartElement.forEach(it::callback) }
val newResult = analyze(inBlockModification, trace, callback)
analysisResult = wrapResult(result, newResult, trace)
}
file.clearInBlockModifications()
analysisResult
}
} catch (e: Throwable) {
e.throwAsInvalidModuleException {
clearFileResultCache()
ProcessCanceledException(it)
}
if (e !is ControlFlowException) {
clearFileResultCache()
}
throw e
}
}
if (fileResult == null) {
file.clearInBlockModifications()
}
return fileResult
}
private fun updateFileResultFromCache() {
// move fileResult from cache if it is stored there
if (fileResult == null && cache.containsKey(file)) {
fileResult = cache[file]
// drop existed results for entire cache:
// if incremental analysis is applicable it will produce a single value for file
// otherwise those results are potentially stale
cache.clear()
}
}
private fun lookUp(analyzableElement: KtElement): AnalysisResult? {
// Looking for parent elements that are already analyzed
// Also removing all elements whose parents are already analyzed, to guarantee consistency
val descendantsOfCurrent = arrayListOf<PsiElement>()
val toRemove = hashSetOf<PsiElement>()
var result: AnalysisResult? = null
for (current in analyzableElement.parentsWithSelf) {
val cached = cache[current]
if (cached != null) {
result = cached
toRemove.addAll(descendantsOfCurrent)
descendantsOfCurrent.clear()
}
descendantsOfCurrent.add(current)
}
cache.keys.removeAll(toRemove)
return result
}
private fun wrapResult(
oldResult: AnalysisResult,
newResult: AnalysisResult,
elementBindingTrace: StackedCompositeBindingContextTrace
): AnalysisResult {
val newBindingCtx = elementBindingTrace.stackedContext
return when {
oldResult.isError() -> {
oldResult.error.throwAsInvalidModuleException()
AnalysisResult.internalError(newBindingCtx, oldResult.error)
}
newResult.isError() -> {
newResult.error.throwAsInvalidModuleException()
AnalysisResult.internalError(newBindingCtx, newResult.error)
}
else -> {
AnalysisResult.success(
newBindingCtx,
oldResult.moduleDescriptor,
oldResult.shouldGenerateCode
)
}
}
}
private fun analyze(
analyzableElement: KtElement,
bindingTrace: BindingTrace?,
callback: DiagnosticSink.DiagnosticsCallback?
): AnalysisResult {
ProgressIndicatorProvider.checkCanceled()
val project = analyzableElement.project
if (DumbService.isDumb(project)) {
return AnalysisResult.EMPTY
}
moduleDescriptor.assertValid()
try {
return KotlinResolveDataProvider.analyze(
project,
globalContext,
moduleDescriptor,
resolveSession,
codeFragmentAnalyzer,
bodyResolveCache,
analyzableElement,
bindingTrace,
callback
)
} catch (e: ProcessCanceledException) {
throw e
} catch (e: IndexNotReadyException) {
throw e
} catch (e: Throwable) {
e.throwAsInvalidModuleException()
DiagnosticUtils.throwIfRunningOnServer(e)
LOG.warn(e)
return AnalysisResult.internalError(BindingContext.EMPTY, e)
}
}
private fun clearFileResultCache() {
file.clearInBlockModifications()
fileResult = null
}
}
private fun Throwable.asInvalidModuleException(): InvalidModuleException? {
return when (this) {
is InvalidModuleException -> this
is AssertionError ->
// temporary workaround till 1.6.0 / KT-48977
if (message?.contains("contained in his own dependencies, this is probably a misconfiguration") == true)
InvalidModuleException(message!!)
else null
else -> cause?.takeIf { it != this }?.asInvalidModuleException()
}
}
private inline fun Throwable.throwAsInvalidModuleException(crossinline action: (InvalidModuleException) -> Throwable = { it }) {
asInvalidModuleException()?.let {
throw action(it)
}
}
private class MergedDiagnostics(
val diagnostics: Collection<Diagnostic>,
val noSuppressionDiagnostics: Collection<Diagnostic>,
override val modificationTracker: ModificationTracker
) : Diagnostics {
private val elementsCache = DiagnosticsElementsCache(this) { true }
override fun all() = diagnostics
override fun forElement(psiElement: PsiElement): MutableCollection<Diagnostic> = elementsCache.getDiagnostics(psiElement)
override fun noSuppression() = if (noSuppressionDiagnostics.isEmpty()) {
this
} else {
MergedDiagnostics(noSuppressionDiagnostics, emptyList(), modificationTracker)
}
}
/**
* Keep in mind: trace fallbacks to [resolveContext] (is used during resolve) that does not have any
* traces of earlier resolve for this [element]
*
* When trace turned into [BindingContext] it fallbacks to [parentContext]:
* It is expected that all slices specific to [element] (and its descendants) are stored in this binding context
* and for the rest elements it falls back to [parentContext].
*/
private class StackedCompositeBindingContextTrace(
val depth: Int, // depth of stack over original ktFile bindingContext
val element: KtElement,
val resolveContext: BindingContext,
val parentContext: BindingContext
) : DelegatingBindingTrace(
resolveContext,
"Stacked trace for resolution of $element",
allowSliceRewrite = true
) {
/**
* Effectively StackedCompositeBindingContext holds up-to-date and partially outdated contexts (parentContext)
*
* The most up-to-date results for element are stored here (in a DelegatingBindingTrace#map)
*
* Note: It does not delete outdated results rather hide it therefore there is some extra memory footprint.
*
* Note: stackedContext differs from DelegatingBindingTrace#bindingContext:
* if result is not present in this context it goes to parentContext rather to resolveContext
* diagnostics are aggregated from this context and parentContext
*/
val stackedContext = StackedCompositeBindingContext()
/**
* All diagnostics from parentContext apart this diagnostics this belongs to the element or its descendants
*/
val parentDiagnosticsApartElement: Collection<Diagnostic> =
(resolveContext.diagnostics.all() + parentContext.diagnostics.all()).filterApartElement()
val parentDiagnosticsNoSuppressionApartElement: Collection<Diagnostic> =
(resolveContext.diagnostics.noSuppression() + parentContext.diagnostics.noSuppression()).filterApartElement()
private fun Collection<Diagnostic>.filterApartElement() =
toSet().let { s ->
s.filter { it.psiElement == element && selfDiagnosticToHold(it) } +
s.filter { it.psiElement.parentsWithSelf.none { e -> e == element } }
}
inner class StackedCompositeBindingContext : BindingContext {
var cachedDiagnostics: Diagnostics? = null
fun bindingTrace(): StackedCompositeBindingContextTrace = this@StackedCompositeBindingContextTrace
fun element(): KtElement = this@StackedCompositeBindingContextTrace.element
fun depth(): Int = this@StackedCompositeBindingContextTrace.depth
// to prevent too deep stacked binding context
fun isIncrementalAnalysisApplicable(): Boolean = this@StackedCompositeBindingContextTrace.depth < 16
override fun getDiagnostics(): Diagnostics {
if (cachedDiagnostics == null) {
val mergedDiagnostics = mutableSetOf<Diagnostic>()
mergedDiagnostics.addAll(parentDiagnosticsApartElement)
this@StackedCompositeBindingContextTrace.mutableDiagnostics?.all()?.let {
mergedDiagnostics.addAll(it)
}
val mergedNoSuppressionDiagnostics = mutableSetOf<Diagnostic>()
mergedNoSuppressionDiagnostics += parentDiagnosticsNoSuppressionApartElement
this@StackedCompositeBindingContextTrace.mutableDiagnostics?.noSuppression()?.let {
mergedNoSuppressionDiagnostics.addAll(it)
}
cachedDiagnostics = MergedDiagnostics(mergedDiagnostics, mergedNoSuppressionDiagnostics, parentContext.diagnostics.modificationTracker)
}
return cachedDiagnostics!!
}
override fun <K : Any?, V : Any?> get(slice: ReadOnlySlice<K, V>, key: K): V? {
return selfGet(slice, key) ?: parentContext.get(slice, key)
}
override fun getType(expression: KtExpression): KotlinType? {
val typeInfo = get(BindingContext.EXPRESSION_TYPE_INFO, expression)
return typeInfo?.type
}
override fun <K, V> getKeys(slice: WritableSlice<K, V>): Collection<K> {
val keys = map.getKeys(slice)
val fromParent = parentContext.getKeys(slice)
if (keys.isEmpty()) return fromParent
if (fromParent.isEmpty()) return keys
return keys + fromParent
}
override fun <K : Any?, V : Any?> getSliceContents(slice: ReadOnlySlice<K, V>): ImmutableMap<K, V> {
return ImmutableMap.copyOf(parentContext.getSliceContents(slice) + map.getSliceContents(slice))
}
override fun addOwnDataTo(trace: BindingTrace, commitDiagnostics: Boolean) = throw UnsupportedOperationException()
}
override fun <K : Any?, V : Any?> get(slice: ReadOnlySlice<K, V>, key: K): V? =
if (slice == BindingContext.ANNOTATION) {
selfGet(slice, key) ?: parentContext.get(slice, key)
} else {
super.get(slice, key)
}
override fun clear() {
super.clear()
stackedContext.cachedDiagnostics = null
}
companion object {
private fun selfDiagnosticToHold(d: Diagnostic): Boolean {
@Suppress("MoveVariableDeclarationIntoWhen")
val positioningStrategy = d.factory.safeAs<DiagnosticFactoryWithPsiElement<*, *>>()?.positioningStrategy
return when (positioningStrategy) {
DECLARATION_WITH_BODY -> false
else -> true
}
}
}
}
private object KotlinResolveDataProvider {
fun findAnalyzableParent(element: KtElement): KtElement? {
if (element is KtFile) return element
val topmostElement = element.findTopmostParentInFile {
it is KtNamedFunction ||
it is KtAnonymousInitializer ||
it is KtProperty ||
it is KtImportDirective ||
it is KtPackageDirective ||
it is KtCodeFragment ||
// TODO: Non-analyzable so far, add more granular analysis
it is KtAnnotationEntry ||
it is KtTypeConstraint ||
it is KtSuperTypeList ||
it is KtTypeParameter ||
it is KtParameter ||
it is KtTypeAlias
} as KtElement?
// parameters and supertype lists are not analyzable by themselves, but if we don't count them as topmost, we'll stop inside, say,
// object expressions inside arguments of super constructors of classes (note that classes themselves are not topmost elements)
val analyzableElement = when (topmostElement) {
is KtAnnotationEntry,
is KtTypeConstraint,
is KtSuperTypeList,
is KtTypeParameter,
is KtParameter -> topmostElement.findParentInFile { it is KtClassOrObject || it is KtCallableDeclaration } as? KtElement?
else -> topmostElement
}
// Primary constructor should never be returned
if (analyzableElement is KtPrimaryConstructor) return analyzableElement.getContainingClassOrObject()
// Class initializer should be replaced by containing class to provide full analysis
if (analyzableElement is KtClassInitializer) return analyzableElement.containingDeclaration
return analyzableElement
// if none of the above worked, take the outermost declaration
?: element.findTopmostParentOfType<KtDeclaration>()
// if even that didn't work, take the whole file
?: element.containingFile as? KtFile
}
fun analyze(
project: Project,
globalContext: GlobalContext,
moduleDescriptor: ModuleDescriptor,
resolveSession: ResolveSession,
codeFragmentAnalyzer: CodeFragmentAnalyzer,
bodyResolveCache: BodyResolveCache,
analyzableElement: KtElement,
bindingTrace: BindingTrace?,
callback: DiagnosticSink.DiagnosticsCallback?
): AnalysisResult {
try {
if (analyzableElement is KtCodeFragment) {
val bodyResolveMode = BodyResolveMode.PARTIAL_FOR_COMPLETION
val trace: BindingTrace = codeFragmentAnalyzer.analyzeCodeFragment(analyzableElement, bodyResolveMode)
val bindingContext = trace.bindingContext
return AnalysisResult.success(bindingContext, moduleDescriptor)
}
val trace = bindingTrace ?: BindingTraceForBodyResolve(
resolveSession.bindingContext,
"Trace for resolution of $analyzableElement"
)
val moduleInfo = analyzableElement.containingKtFile.moduleInfo
val targetPlatform = moduleInfo.platform
var callbackSet = false
try {
callbackSet = callback?.let(trace::setCallbackIfNotSet) ?: false
/*
Note that currently we *have* to re-create LazyTopDownAnalyzer with custom trace in order to disallow resolution of
bodies in top-level trace (trace from DI-container).
Resolving bodies in top-level trace may lead to memory leaks and incorrect resolution, because top-level
trace isn't invalidated on in-block modifications (while body resolution surely does)
Also note that for function bodies, we'll create DelegatingBindingTrace in ResolveElementCache anyways
(see 'functionAdditionalResolve'). However, this trace is still needed, because we have other
codepaths for other KtDeclarationWithBodies (like property accessors/secondary constructors/class initializers)
*/
val lazyTopDownAnalyzer = createContainerForLazyBodyResolve(
//TODO: should get ModuleContext
globalContext.withProject(project).withModule(moduleDescriptor),
resolveSession,
trace,
targetPlatform,
bodyResolveCache,
targetPlatform.findAnalyzerServices(project),
analyzableElement.languageVersionSettings,
IdeaModuleStructureOracle(),
IdeMainFunctionDetectorFactory(),
IdeSealedClassInheritorsProvider,
ControlFlowInformationProviderImpl.Factory,
).get<LazyTopDownAnalyzer>()
lazyTopDownAnalyzer.analyzeDeclarations(TopDownAnalysisMode.TopLevelDeclarations, listOf(analyzableElement))
} finally {
if (callbackSet) {
trace.resetCallback()
}
}
return AnalysisResult.success(trace.bindingContext, moduleDescriptor)
} catch (e: ProcessCanceledException) {
throw e
} catch (e: IndexNotReadyException) {
throw e
} catch (e: Throwable) {
e.throwAsInvalidModuleException()
DiagnosticUtils.throwIfRunningOnServer(e)
LOG.warn(e)
return AnalysisResult.internalError(BindingContext.EMPTY, e)
}
}
}
| apache-2.0 | 134f24d01565ce76d58180adc202da73 | 42.351171 | 151 | 0.6499 | 5.661498 | false | false | false | false |
siosio/intellij-community | plugins/kotlin/jvm-debugger/sequence/src/org/jetbrains/kotlin/idea/debugger/sequence/psi/impl/PackageBasedCallChecker.kt | 1 | 1733 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.debugger.sequence.psi.impl
import com.intellij.openapi.util.text.StringUtil
import org.jetbrains.kotlin.idea.debugger.sequence.psi.KotlinPsiUtil
import org.jetbrains.kotlin.idea.debugger.sequence.psi.StreamCallChecker
import org.jetbrains.kotlin.idea.core.receiverType
import org.jetbrains.kotlin.idea.core.resolveType
import org.jetbrains.kotlin.psi.KtCallExpression
import org.jetbrains.kotlin.types.KotlinType
class PackageBasedCallChecker(private val supportedPackage: String) : StreamCallChecker {
override fun isIntermediateCall(expression: KtCallExpression): Boolean {
return checkReceiverSupported(expression) && checkResultSupported(expression, true)
}
override fun isTerminationCall(expression: KtCallExpression): Boolean {
return checkReceiverSupported(expression) && checkResultSupported(expression, false)
}
private fun checkResultSupported(
expression: KtCallExpression,
shouldSupportResult: Boolean
): Boolean {
val resultType = expression.resolveType()
return shouldSupportResult == isSupportedType(resultType)
}
private fun checkReceiverSupported(expression: KtCallExpression): Boolean {
val receiverType = expression.receiverType()
return receiverType != null && isSupportedType(receiverType)
}
private fun isSupportedType(type: KotlinType): Boolean {
val typeName = KotlinPsiUtil.getTypeWithoutTypeParameters(type)
return StringUtil.getPackageName(typeName).startsWith(supportedPackage)
}
} | apache-2.0 | da7cf0cf14b958a154e02df6913fa7ad | 43.461538 | 158 | 0.776111 | 4.89548 | false | false | false | false |
zielu/GitToolBox | src/main/kotlin/zielu/intellij/util/ZDateFormatUtil.kt | 1 | 3298 | package zielu.intellij.util
import com.intellij.util.text.SyncDateFormat
import java.time.Duration
import java.time.Instant
import java.time.ZoneOffset
import java.time.ZonedDateTime
import java.time.temporal.ChronoUnit
import java.util.Date
internal object ZDateFormatUtil {
/**
* Formats relative date-time in following way:
* 1. under 1 minutes - moments ago
* 2. 1 minutes to 1 hour - x minutes, one hour ago
* 3. over 1 hour - today, yesterday, according to date format
*/
fun formatPrettyDateTime(
date: ZonedDateTime,
now: ZonedDateTime,
dateFormat: SyncDateFormat
): String {
if (now < date) {
return ZResBundle.na()
}
val nowInstant = now.toInstant()
val dateInstant = date.toInstant()
val duration = Duration.between(dateInstant, nowInstant)
return if (duration < HOUR_AND_MINUTE) {
formatPrettyUntilOneHour(duration)
} else {
formatOverOneHour(dateInstant, nowInstant, dateFormat)
}
}
private fun formatPrettyUntilOneHour(duration: Duration): String {
return if (duration < MINUTE) {
ZResBundle.message("date.format.minutes.ago", 0)
} else ZResBundle.message("date.format.minutes.ago", duration.dividedBy(60).seconds)
}
private fun formatOverOneHour(date: Instant, now: Instant, dateFormat: SyncDateFormat): String {
val nowDate = now.atZone(ZoneOffset.UTC).toLocalDate()
val referenceDate = date.atZone(ZoneOffset.UTC).toLocalDate()
return when {
nowDate == referenceDate -> {
ZResBundle.message("date.format.today")
}
nowDate.minusDays(1) == referenceDate -> {
ZResBundle.message("date.format.yesterday")
}
else -> {
dateFormat.format(Date.from(date))
}
}
}
fun formatBetweenDates(date1: ZonedDateTime, date2: ZonedDateTime): String {
val duration = Duration.between(date1, date2)
return if (duration.isNegative) {
// TODO: should handle future - in a x minutes
ZResBundle.na()
} else {
formatRelativePastDuration(duration)
}
}
private fun formatRelativePastDuration(duration: Duration): String {
return when {
duration < MINUTE -> {
ZResBundle.message("date.format.moments.ago")
}
duration < HOUR -> {
ZResBundle.message("date.format.n.minutes.ago", duration.dividedBy(MINUTE))
}
duration < DAY -> {
ZResBundle.message("date.format.n.hours.ago", duration.dividedBy(HOUR))
}
duration < WEEK -> {
ZResBundle.message("date.format.n.days.ago", duration.dividedBy(DAY))
}
duration < MONTH -> {
ZResBundle.message("date.format.n.weeks.ago", duration.dividedBy(WEEK))
}
duration < YEAR -> {
ZResBundle.message("date.format.n.months.ago", duration.dividedBy(MONTH))
}
else -> {
ZResBundle.message("date.format.n.years.ago", duration.dividedBy(YEAR))
}
}
}
}
private val MINUTE = Duration.ofSeconds(60)
private val HOUR = Duration.of(1, ChronoUnit.HOURS)
private val HOUR_AND_MINUTE = HOUR.plusSeconds(1)
private val DAY = Duration.of(1, ChronoUnit.DAYS)
private val WEEK = Duration.of(7, ChronoUnit.DAYS)
private val MONTH = Duration.of(30, ChronoUnit.DAYS)
private val YEAR = Duration.of(365, ChronoUnit.DAYS)
| apache-2.0 | da5bb40616c138c6c2c8f0d34e56aa04 | 31.333333 | 98 | 0.674651 | 3.848308 | false | false | false | false |
smmribeiro/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/MoveTypeAliasToTopLevelFix.kt | 5 | 1471 | // 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.diagnostics.Diagnostic
import org.jetbrains.kotlin.idea.KotlinBundle
import org.jetbrains.kotlin.psi.KtFile
import org.jetbrains.kotlin.psi.KtPsiFactory
import org.jetbrains.kotlin.psi.KtTypeAlias
import org.jetbrains.kotlin.psi.psiUtil.parents
class MoveTypeAliasToTopLevelFix(element: KtTypeAlias) : KotlinQuickFixAction<KtTypeAlias>(element) {
override fun getText() = KotlinBundle.message("fix.move.typealias.to.top.level")
override fun getFamilyName() = text
override fun invoke(project: Project, editor: Editor?, file: KtFile) {
val typeAlias = element ?: return
val parents = typeAlias.parents.toList().reversed()
val containingFile = parents.firstOrNull() as? KtFile ?: return
val target = parents.getOrNull(1) ?: return
containingFile.addAfter(typeAlias, target)
containingFile.addAfter(KtPsiFactory(typeAlias).createNewLine(2), target)
typeAlias.delete()
}
companion object : KotlinSingleIntentionActionFactory() {
override fun createAction(diagnostic: Diagnostic) = (diagnostic.psiElement as? KtTypeAlias)?.let { MoveTypeAliasToTopLevelFix(it) }
}
}
| apache-2.0 | c934ddfbbe53031402fc46e44f4cc830 | 44.96875 | 158 | 0.760027 | 4.526154 | false | false | false | false |
smmribeiro/intellij-community | plugins/kotlin/idea/tests/testData/inspections/naming/objectProperty/test.kt | 10 | 404 | val Foo: String = ""
var FOO_BAR: Int = 0
var _FOO: Int = 0
const val THREE = 3
val xyzzy = 1
fun foo() {
val XYZZY = 1
val BAR_BAZ = 2
}
object Foo {
val Foo: String = ""
var FOO_BAR: Int = 0
var _FOO: Int = 0
}
class D {
private val _foo: String
private val FOO_BAR: String
companion object {
val Foo: String = ""
var FOO_BAR: Int = 0
}
} | apache-2.0 | 61b2ec01e3094b7fec26ff4ce7e6b44b | 10.911765 | 31 | 0.529703 | 2.992593 | false | false | false | false |
LouisCAD/Splitties | modules/permissions/src/androidMain/kotlin/splitties/permissions/internal/PermissionRequestDialogFragment.kt | 1 | 3302 | /*
* Copyright 2019 Louis Cognault Ayeva Derman. Use of this source code is governed by the Apache 2.0 license.
*/
package splitties.permissions.internal
import android.content.Intent
import android.content.pm.PackageManager
import android.os.Bundle
import androidx.annotation.RequiresApi
import androidx.fragment.app.DialogFragment
import kotlinx.coroutines.CompletableDeferred
import splitties.experimental.ExperimentalSplittiesApi
import splitties.intents.intent
import splitties.lifecycle.coroutines.createJob
import splitties.permissions.PermissionRequestResult
@RequiresApi(23)
internal class PermissionRequestDialogFragment : DialogFragment() {
var permissionNames: Array<out String>? = null
suspend fun awaitResult(): PermissionRequestResult = try {
asyncGrant.await()
} finally {
runCatching { dismissAllowingStateLoss() } // Activity may be detached, so we catch.
}
@OptIn(ExperimentalSplittiesApi::class)
private val asyncGrant = CompletableDeferred<PermissionRequestResult>(lifecycle.createJob())
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
permissionNames?.also {
@Suppress("Deprecation") // We don't need the ActivityResultContract APIs.
requestPermissions(it, 1)
} ?: dismissAllowingStateLoss()
}
override fun onRequestPermissionsResult(
requestCode: Int,
permissions: Array<out String>,
grantResults: IntArray
) {
handleGrantResult(grantResults)
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
checkNotNull(data) // data is always provided from PermissionRequestFallbackActivity result.
val extras = data.extras!! // and its result always contains the grantResult extra.
handleGrantResult(extras.get(PermissionRequestFallbackActivity.GRANT_RESULT) as IntArray)
}
private fun handleGrantResult(grantResults: IntArray) {
val permissions = permissionNames ?: return
if (grantResults.isEmpty()) {
fallbackRequestFromTransparentActivity(permissions)
return
}
try {
val indexOfFirstNotGranted = grantResults.indexOfFirst {
it != PackageManager.PERMISSION_GRANTED
}
val result = if (indexOfFirstNotGranted == -1) {
PermissionRequestResult.Granted
} else permissions[indexOfFirstNotGranted].let { firstDeniedPermission ->
if (shouldShowRequestPermissionRationale(firstDeniedPermission)) {
PermissionRequestResult.Denied.MayAskAgain(firstDeniedPermission)
} else {
PermissionRequestResult.Denied.DoNotAskAgain(firstDeniedPermission)
}
}
asyncGrant.complete(result)
} finally {
dismissAllowingStateLoss()
}
}
private fun fallbackRequestFromTransparentActivity(permissions: Array<out String>) {
@Suppress("Deprecation") // We don't need the ActivityResultContract APIs.
startActivityForResult(PermissionRequestFallbackActivity.intent { _, extrasSpec ->
extrasSpec.permissionNames = permissions
}, 1)
}
}
| apache-2.0 | c57ade8f88aacda38ee474c44a2b91b6 | 37.847059 | 109 | 0.697456 | 5.625213 | false | false | false | false |
smmribeiro/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/createFromUsage/createClass/CreateClassFromReferenceExpressionActionFactory.kt | 2 | 6010 | // 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.createFromUsage.createClass
import com.intellij.psi.PsiClass
import com.intellij.psi.PsiElement
import org.jetbrains.kotlin.diagnostics.Diagnostic
import org.jetbrains.kotlin.idea.caches.resolve.analyzeAndGetResult
import org.jetbrains.kotlin.idea.quickfix.createFromUsage.callableBuilder.TypeInfo
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.*
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.calls.callUtil.getCall
import org.jetbrains.kotlin.utils.ifEmpty
import java.util.*
object CreateClassFromReferenceExpressionActionFactory : CreateClassFromUsageFactory<KtSimpleNameExpression>() {
override fun getElementOfInterest(diagnostic: Diagnostic): KtSimpleNameExpression? {
val refExpr = diagnostic.psiElement as? KtSimpleNameExpression ?: return null
if (refExpr.getNonStrictParentOfType<KtTypeReference>() != null) return null
return refExpr
}
private fun getFullCallExpression(element: KtSimpleNameExpression): KtExpression? {
return element.parent.let {
when {
it is KtCallExpression && it.calleeExpression == element -> return null
it is KtQualifiedExpression && it.selectorExpression == element -> it
else -> element
}
}
}
private fun isQualifierExpected(element: KtSimpleNameExpression) =
element.isDotReceiver() || ((element.parent as? KtDotQualifiedExpression)?.isDotReceiver() ?: false)
override fun getPossibleClassKinds(element: KtSimpleNameExpression, diagnostic: Diagnostic): List<ClassKind> {
fun isEnum(element: PsiElement): Boolean {
return when (element) {
is KtClass -> element.isEnum()
is PsiClass -> element.isEnum
else -> false
}
}
val name = element.getReferencedName()
val (context, moduleDescriptor) = element.analyzeAndGetResult()
val fullCallExpr = getFullCallExpression(element) ?: return Collections.emptyList()
val inImport = element.getNonStrictParentOfType<KtImportDirective>() != null
if (inImport || isQualifierExpected(element)) {
val receiverSelector =
(fullCallExpr as? KtQualifiedExpression)?.receiverExpression?.getQualifiedElementSelector() as? KtReferenceExpression
val qualifierDescriptor = receiverSelector?.let { context[BindingContext.REFERENCE_TARGET, it] }
val targetParents = getTargetParentsByQualifier(element, receiverSelector != null, qualifierDescriptor)
.ifEmpty { return emptyList() }
targetParents.forEach {
if (element.getCreatePackageFixIfApplicable(it) != null) return emptyList()
}
if (!name.checkClassName()) return emptyList()
return ClassKind.values().filter {
when (it) {
ClassKind.ANNOTATION_CLASS -> inImport
ClassKind.ENUM_ENTRY -> inImport && targetParents.any { isEnum(it) }
else -> true
}
}
}
val parent = element.parent
if (parent is KtClassLiteralExpression && parent.receiverExpression == element) {
return listOf(ClassKind.PLAIN_CLASS, ClassKind.ENUM_CLASS, ClassKind.INTERFACE, ClassKind.ANNOTATION_CLASS, ClassKind.OBJECT)
}
if (fullCallExpr.getAssignmentByLHS() != null) return Collections.emptyList()
val call = element.getCall(context) ?: return Collections.emptyList()
val targetParents = getTargetParentsByCall(call, context).ifEmpty { return emptyList() }
if (isInnerClassExpected(call)) return Collections.emptyList()
val allKinds = listOf(ClassKind.OBJECT, ClassKind.ENUM_ENTRY)
val expectedType = fullCallExpr.guessTypeForClass(context, moduleDescriptor)
return allKinds.filter { classKind ->
targetParents.any { targetParent ->
(expectedType == null || getClassKindFilter(expectedType, targetParent)(classKind)) && when (classKind) {
ClassKind.OBJECT -> expectedType == null || !isEnum(targetParent)
ClassKind.ENUM_ENTRY -> isEnum(targetParent)
else -> false
}
}
}
}
override fun extractFixData(element: KtSimpleNameExpression, diagnostic: Diagnostic): ClassInfo? {
val name = element.getReferencedName()
val (context, moduleDescriptor) = element.analyzeAndGetResult()
val fullCallExpr = getFullCallExpression(element) ?: return null
if (element.isInImportDirective() || isQualifierExpected(element)) {
val receiverSelector =
(fullCallExpr as? KtQualifiedExpression)?.receiverExpression?.getQualifiedElementSelector() as? KtReferenceExpression
val qualifierDescriptor = receiverSelector?.let { context[BindingContext.REFERENCE_TARGET, it] }
val targetParents = getTargetParentsByQualifier(element, receiverSelector != null, qualifierDescriptor)
.ifEmpty { return null }
return ClassInfo(
name = name,
targetParents = targetParents,
expectedTypeInfo = TypeInfo.Empty
)
}
val call = element.getCall(context) ?: return null
val targetParents = getTargetParentsByCall(call, context).ifEmpty { return null }
val expectedTypeInfo = fullCallExpr.guessTypeForClass(context, moduleDescriptor)?.toClassTypeInfo() ?: TypeInfo.Empty
return ClassInfo(
name = name,
targetParents = targetParents,
expectedTypeInfo = expectedTypeInfo
)
}
}
| apache-2.0 | c81e466f8e7334ebb26d34a47abc4061 | 43.850746 | 158 | 0.668719 | 5.696682 | false | false | false | false |
smmribeiro/intellij-community | plugins/kotlin/frontend-independent/src/org/jetbrains/kotlin/idea/references/KtIdeReferenceProviderService.kt | 2 | 4536 | // 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.references
import com.intellij.openapi.components.service
import com.intellij.openapi.project.IndexNotReadyException
import com.intellij.psi.ContributedReferenceHost
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiReference
import com.intellij.psi.PsiReferenceService
import com.intellij.psi.impl.source.resolve.reference.ReferenceProvidersRegistry
import com.intellij.psi.util.CachedValueProvider
import com.intellij.psi.util.CachedValuesManager
import com.intellij.psi.util.PsiModificationTracker
import com.intellij.util.containers.ConcurrentFactoryMap
import com.intellij.util.containers.ContainerUtil
import com.intellij.util.containers.MultiMap
import org.jetbrains.kotlin.psi.KotlinReferenceProvidersService
import org.jetbrains.kotlin.psi.KtElement
import org.jetbrains.kotlin.utils.SmartList
interface KotlinPsiReferenceProvider {
fun getReferencesByElement(element: PsiElement): Array<PsiReference>
}
interface KotlinReferenceProviderContributor {
fun registerReferenceProviders(registrar: KotlinPsiReferenceRegistrar)
companion object {
fun getInstance(): KotlinReferenceProviderContributor = service()
}
}
class KotlinPsiReferenceRegistrar {
val providers: MultiMap<Class<out PsiElement>, KotlinPsiReferenceProvider> = MultiMap.create()
inline fun <reified E : KtElement> registerProvider(crossinline factory: (E) -> PsiReference?) {
registerMultiProvider<E> { element ->
factory(element)?.let { reference -> arrayOf(reference) } ?: PsiReference.EMPTY_ARRAY
}
}
inline fun <reified E : KtElement> registerMultiProvider(crossinline factory: (E) -> Array<PsiReference>) {
val provider: KotlinPsiReferenceProvider = object : KotlinPsiReferenceProvider {
override fun getReferencesByElement(element: PsiElement): Array<PsiReference> {
return factory(element as E)
}
}
registerMultiProvider(E::class.java, provider)
}
fun registerMultiProvider(klass: Class<out PsiElement>, provider: KotlinPsiReferenceProvider) {
providers.putValue(klass, provider)
}
}
class KtIdeReferenceProviderService : KotlinReferenceProvidersService() {
private val originalProvidersBinding: MultiMap<Class<out PsiElement>, KotlinPsiReferenceProvider>
private val providersBindingCache: Map<Class<out PsiElement>, List<KotlinPsiReferenceProvider>>
init {
val registrar = KotlinPsiReferenceRegistrar()
KotlinReferenceProviderContributor.getInstance().registerReferenceProviders(registrar)
originalProvidersBinding = registrar.providers
providersBindingCache = ConcurrentFactoryMap.createMap<Class<out PsiElement>, List<KotlinPsiReferenceProvider>> { klass ->
val result = SmartList<KotlinPsiReferenceProvider>()
for (bindingClass in originalProvidersBinding.keySet()) {
if (bindingClass.isAssignableFrom(klass)) {
result.addAll(originalProvidersBinding.get(bindingClass))
}
}
result
}
}
private fun doGetKotlinReferencesFromProviders(context: PsiElement): Array<PsiReference> {
val providers: List<KotlinPsiReferenceProvider>? = providersBindingCache[context.javaClass]
if (providers.isNullOrEmpty()) return PsiReference.EMPTY_ARRAY
val result = SmartList<PsiReference>()
for (provider in providers) {
try {
result.addAll(provider.getReferencesByElement(context))
} catch (ignored: IndexNotReadyException) {
// Ignore and continue to next provider
}
}
if (result.isEmpty()) {
return PsiReference.EMPTY_ARRAY
}
return result.toTypedArray()
}
override fun getReferences(psiElement: PsiElement): Array<PsiReference> {
if (psiElement is ContributedReferenceHost) {
return ReferenceProvidersRegistry.getReferencesFromProviders(psiElement, PsiReferenceService.Hints.NO_HINTS)
}
return CachedValuesManager.getCachedValue(psiElement) {
CachedValueProvider.Result.create(
doGetKotlinReferencesFromProviders(psiElement),
PsiModificationTracker.MODIFICATION_COUNT
)
}
}
} | apache-2.0 | ab9e1518b1c4954eaef57715dfa460fa | 39.873874 | 158 | 0.727734 | 5.237875 | false | false | false | false |
smmribeiro/intellij-community | plugins/kotlin/idea/tests/testData/intentions/branched/ifWhen/ifToWhen/combinedIf.kt | 13 | 247 | fun bar(arg: Int): String {
<caret>if (arg == 1) return "One"
else if (arg == 2) return "Two"
if (arg == 0) return "Zero"
if (arg == -1) return "Minus One"
else if (arg == -2) return "Minus Two"
return "Something Complex"
} | apache-2.0 | 76cbe4032f5f230cfa14e7cb0441ba7e | 30 | 42 | 0.562753 | 3.049383 | false | false | false | false |
kerubistan/kerub | src/main/kotlin/com/github/kerubistan/kerub/model/dynamic/VirtualStorageFsAllocation.kt | 2 | 1307 | package com.github.kerubistan.kerub.model.dynamic
import com.fasterxml.jackson.annotation.JsonIgnore
import com.fasterxml.jackson.annotation.JsonTypeName
import com.github.kerubistan.kerub.model.FsStorageCapability
import com.github.kerubistan.kerub.model.io.VirtualDiskFormat
import com.github.kerubistan.kerub.utils.validateSize
import java.math.BigInteger
import java.util.UUID
@JsonTypeName("fs-allocation")
data class VirtualStorageFsAllocation(
override val hostId: UUID,
override val capabilityId: UUID,
override val actualSize: BigInteger,
val mountPoint: String,
override val type: VirtualDiskFormat,
val fileName: String,
val backingFile: String? = null
) : VirtualStorageAllocation {
init {
actualSize.validateSize("actualSize")
require(fileName.startsWith(mountPoint)) {
"The file name ($fileName) must be a full path starting with the mount point ($mountPoint)"
}
require(fileName.endsWith(type.name)) {
"the file name ($fileName) must be postfixed by the file type ($type)"
}
}
override fun getRedundancyLevel(): Byte = 0
@JsonIgnore
override fun requires() = FsStorageCapability::class
override fun resize(newSize: BigInteger): VirtualStorageAllocation = this.copy(actualSize = newSize)
override fun getPath(id: UUID) =
"$mountPoint/$id.$type"
} | apache-2.0 | fe55fc00ae3f0ca7ee9f0f8f1c302d9f | 30.902439 | 101 | 0.778883 | 3.984756 | false | false | false | false |
MaTriXy/gradle-play-publisher-1 | play/plugin/src/main/kotlin/com/github/triplet/gradle/play/internal/Plugins.kt | 1 | 3927 | package com.github.triplet.gradle.play.internal
import com.android.build.api.variant.ApplicationVariant
import com.android.build.api.variant.ApplicationVariantProperties
import com.github.triplet.gradle.common.utils.PLUGIN_GROUP
import com.github.triplet.gradle.common.utils.nullOrFull
import com.github.triplet.gradle.play.PlayPublisherExtension
import com.github.triplet.gradle.play.tasks.CommitEdit
import com.github.triplet.gradle.play.tasks.GenerateEdit
import com.github.triplet.gradle.play.tasks.internal.EditTaskBase
import org.gradle.api.InvalidUserDataException
import org.gradle.api.NamedDomainObjectContainer
import org.gradle.api.Project
import org.gradle.api.Task
import org.gradle.api.tasks.TaskProvider
import org.gradle.kotlin.dsl.register
internal val ApplicationVariantProperties.flavorNameOrDefault
get() = flavorName.nullOrFull() ?: "main"
internal val ApplicationVariantProperties.playPath get() = "$RESOURCES_OUTPUT_PATH/$name/$PLAY_PATH"
internal fun Project.newTask(
name: String,
description: String? = null,
block: Task.() -> Unit = {}
) = newTask(name, description, emptyArray(), block)
internal inline fun <reified T : Task> Project.newTask(
name: String,
description: String? = null,
constructorArgs: Array<Any> = emptyArray(),
noinline block: T.() -> Unit = {}
): TaskProvider<T> {
val config: T.() -> Unit = {
this.description = description
this.group = PLUGIN_GROUP.takeUnless { description.isNullOrBlank() }
block()
}
return tasks.register<T>(name, *constructorArgs).apply { configure(config) }
}
internal fun Project.getGenEditTask(
appId: String,
extension: PlayPublisherExtension
) = rootProject.getOrRegisterEditTask<GenerateEdit>("generateEditFor", extension, appId)
internal fun Project.getCommitEditTask(
appId: String,
extension: PlayPublisherExtension
) = rootProject.getOrRegisterEditTask<CommitEdit>("commitEditFor", extension, appId)
internal fun ApplicationVariant<ApplicationVariantProperties>.buildExtension(
extensionContainer: NamedDomainObjectContainer<PlayPublisherExtension>,
baseExtension: PlayPublisherExtension,
cliOptionsExtension: PlayPublisherExtension
): PlayPublisherExtension = buildExtensionInternal(
this,
extensionContainer,
baseExtension,
cliOptionsExtension
)
private fun buildExtensionInternal(
variant: ApplicationVariant<ApplicationVariantProperties>,
extensionContainer: NamedDomainObjectContainer<PlayPublisherExtension>,
baseExtension: PlayPublisherExtension,
cliOptionsExtension: PlayPublisherExtension
): PlayPublisherExtension {
val variantExtension = extensionContainer.findByName(variant.name)
val flavorExtension = variant.productFlavors.mapNotNull { (_, flavor) ->
extensionContainer.findByName(flavor)
}.singleOrNull()
val buildTypeExtension = variant.buildType?.let { extensionContainer.findByName(it) }
val extensions = listOfNotNull(
cliOptionsExtension,
variantExtension,
flavorExtension,
buildTypeExtension,
baseExtension
).distinctBy {
it.name
}
return mergeExtensions(extensions)
}
private inline fun <reified T : EditTaskBase> Project.getOrRegisterEditTask(
baseName: String,
extension: PlayPublisherExtension,
appId: String
): TaskProvider<T> {
val taskName = baseName + appId.split(".").joinToString("Dot") { it.capitalize() }
return try {
tasks.register<T>(taskName, extension).apply {
configure {
editIdFile.set(layout.buildDirectory.file("$OUTPUT_PATH/$appId.txt"))
}
}
} catch (e: InvalidUserDataException) {
@Suppress("UNCHECKED_CAST")
tasks.named(taskName) as TaskProvider<T>
}
}
| mit | fe2f1ea2ca982e091e197c93431b3982 | 36.04717 | 100 | 0.723453 | 4.714286 | false | false | false | false |
chiken88/passnotes | app/src/main/kotlin/com/ivanovsky/passnotes/domain/interactor/search/SearchInteractor.kt | 1 | 2841 | package com.ivanovsky.passnotes.domain.interactor.search
import com.ivanovsky.passnotes.data.entity.Group
import com.ivanovsky.passnotes.data.entity.Note
import com.ivanovsky.passnotes.data.entity.OperationResult
import com.ivanovsky.passnotes.data.repository.EncryptedDatabaseRepository
import com.ivanovsky.passnotes.domain.DispatcherProvider
import com.ivanovsky.passnotes.domain.usecases.GetDatabaseUseCase
import com.ivanovsky.passnotes.domain.usecases.LockDatabaseUseCase
import kotlinx.coroutines.withContext
class SearchInteractor(
private val dbRepo: EncryptedDatabaseRepository,
private val dispatchers: DispatcherProvider,
private val getDbUseCase: GetDatabaseUseCase,
private val lockUseCase: LockDatabaseUseCase
) {
suspend fun find(query: String): OperationResult<List<Item>> {
return withContext(dispatchers.IO) {
val dbResult = getDbUseCase.getDatabase()
if (dbResult.isFailed) {
return@withContext dbResult.takeError()
}
val db = dbResult.obj
val notesResult = db.noteRepository.find(query)
if (notesResult.isFailed) {
return@withContext notesResult.takeError()
}
val groupsResult = db.groupRepository.find(query)
if (groupsResult.isFailed) {
return@withContext groupsResult.takeError()
}
val notes = notesResult.obj
val groups = groupsResult.obj
val items = mutableListOf<Item>()
for (group in groups) {
val noteCountResult = dbRepo.noteRepository.getNoteCountByGroupUid(group.uid)
if (noteCountResult.isFailed) {
return@withContext noteCountResult.takeError()
}
val childGroupCountResult = dbRepo.groupRepository.getChildGroupsCount(group.uid)
if (childGroupCountResult.isFailed) {
return@withContext childGroupCountResult.takeError()
}
val noteCount = noteCountResult.obj
val childGroupCount = childGroupCountResult.obj
items.add(
Item.GroupItem(
group = group,
noteCount = noteCount,
childGroupCount = childGroupCount
)
)
}
items.addAll(notes.map { Item.NoteItem(it) })
OperationResult.success(items)
}
}
fun lockDatabase() {
lockUseCase.lockIfNeed()
}
sealed class Item {
data class NoteItem(val note: Note) : Item()
data class GroupItem(
val group: Group,
val noteCount: Int,
val childGroupCount: Int
) : Item()
}
} | gpl-2.0 | 7921091563c0aa94343443132df83f03 | 33.240964 | 97 | 0.617388 | 4.949477 | false | false | false | false |
EMResearch/EvoMaster | core/src/main/kotlin/org/evomaster/core/problem/rest/service/ResourceSampler.kt | 1 | 9891 | package org.evomaster.core.problem.rest.service
import com.google.inject.Inject
import org.evomaster.client.java.controller.api.dto.SutInfoDto
import org.evomaster.core.database.SqlInsertBuilder
import org.evomaster.core.problem.rest.*
import org.evomaster.core.problem.httpws.service.auth.NoAuth
import org.evomaster.core.problem.rest.resource.RestResourceCalls
import org.evomaster.core.problem.rest.resource.SamplerSpecification
import org.evomaster.core.search.ActionFilter
import org.evomaster.core.search.EvaluatedIndividual
import org.evomaster.core.search.service.Randomness
import org.evomaster.core.search.tracer.Traceable
import org.slf4j.Logger
import org.slf4j.LoggerFactory
/**
* resource-based sampler
* the sampler handles resource-based rest individual
*/
open class ResourceSampler : AbstractRestSampler() {
companion object {
val log: Logger = LoggerFactory.getLogger(ResourceSampler::class.java)
}
@Inject
private lateinit var ssc : ResourceSampleMethodController
@Inject
private lateinit var rm : ResourceManageService
@Inject
private lateinit var dm : ResourceDepManageService
override fun initSqlInfo(infoDto: SutInfoDto) {
//when ResourceDependency is enabled, SQL info is required to identify dependency
if (infoDto.sqlSchemaDto != null && (configuration.shouldGenerateSqlData() || config.isEnabledResourceDependency())) {
sqlInsertBuilder = SqlInsertBuilder(infoDto.sqlSchemaDto, rc)
existingSqlData = sqlInsertBuilder!!.extractExistingPKs()
}
}
override fun customizeAdHocInitialIndividuals() {
rm.initResourceNodes(actionCluster, sqlInsertBuilder)
rm.initExcludedResourceNode(getExcludedActions())
adHocInitialIndividuals.clear()
rm.createAdHocIndividuals(NoAuth(),adHocInitialIndividuals, getMaxTestSizeDuringSampler())
authentications.forEach { auth ->
rm.createAdHocIndividuals(auth, adHocInitialIndividuals, getMaxTestSizeDuringSampler())
}
}
override fun postInits() {
ssc.initialize()
}
override fun sampleAtRandom() : RestIndividual {
return sampleAtRandom(randomness.nextInt(1, getMaxTestSizeDuringSampler()))
}
private fun sampleAtRandom(size : Int): RestIndividual {
assert(size <= getMaxTestSizeDuringSampler())
val restCalls = mutableListOf<RestResourceCalls>()
val n = randomness.nextInt(1, getMaxTestSizeDuringSampler())
var left = n
while(left > 0){
val call = sampleRandomResourceAction(0.05, left)
left -= call.seeActionSize(ActionFilter.MAIN_EXECUTABLE)
restCalls.add(call)
}
val ind = RestIndividual(
resourceCalls = restCalls, sampleType = SampleType.RANDOM, dbInitialization = mutableListOf(), trackOperator = this, index = time.evaluatedIndividuals)
ind.doGlobalInitialize(searchGlobalState)
return ind
}
private fun sampleRandomResourceAction(noAuthP: Double, left: Int) : RestResourceCalls{
val r = randomness.choose(rm.getResourceCluster().filter { it.value.isAnyAction() })
val rc = if (randomness.nextBoolean()){
r.sampleOneAction(null, randomness)
} else{
r.randomRestResourceCalls(randomness,left)
}
rc.seeActions(ActionFilter.MAIN_EXECUTABLE).forEach {
(it as RestCallAction).auth = getRandomAuth(noAuthP)
}
return rc
}
override fun smartSample(): RestIndividual {
/*
At the beginning, sampleAll from this set, until it is empty
*/
val ind = if (adHocInitialIndividuals.isNotEmpty()) {
adHocInitialIndividuals.removeAt(0)
} else {
val withDependency = config.probOfEnablingResourceDependencyHeuristics > 0.0
&& dm.isDependencyNotEmpty()
&& randomness.nextBoolean(config.probOfEnablingResourceDependencyHeuristics)
val method = ssc.getSampleStrategy()
sampleWithMethodAndDependencyOption(method, withDependency)
?: return sampleAtRandom()
}
ind.doGlobalInitialize(searchGlobalState)
return ind
}
fun sampleWithMethodAndDependencyOption(sampleMethod : ResourceSamplingMethod, withDependency: Boolean) : RestIndividual?{
val restCalls = mutableListOf<RestResourceCalls>()
when(sampleMethod){
ResourceSamplingMethod.S1iR -> sampleIndependentAction(restCalls)
ResourceSamplingMethod.S1dR -> sampleOneResource(restCalls)
ResourceSamplingMethod.S2dR -> sampleComResource(restCalls, withDependency)
ResourceSamplingMethod.SMdR -> sampleManyResources(restCalls, withDependency)
}
//auth management
val auth = if(authentications.isNotEmpty()){
getRandomAuth(0.0)
}else{
NoAuth()
}
restCalls.flatMap { it.seeActions(ActionFilter.MAIN_EXECUTABLE) }.forEach {
(it as RestCallAction).auth = auth
}
if (restCalls.isNotEmpty()) {
val individual = RestIndividual(restCalls, SampleType.SMART_RESOURCE, sampleSpec = SamplerSpecification(sampleMethod.toString(), withDependency),
trackOperator = if(config.trackingEnabled()) this else null, index = if (config.trackingEnabled()) time.evaluatedIndividuals else -1)
if (withDependency)
dm.sampleResourceWithRelatedDbActions(individual, rm.getMaxNumOfResourceSizeHandling())
individual.cleanBrokenBindingReference()
return individual
}
return null
}
private fun sampleIndependentAction(resourceCalls: MutableList<RestResourceCalls>){
val key = randomness.choose(rm.getResourceCluster().filter { it.value.hasIndependentAction() }.keys)
rm.sampleCall(key, false, resourceCalls, getMaxTestSizeDuringSampler())
}
private fun sampleOneResource(resourceCalls: MutableList<RestResourceCalls>){
val key = selectAIndResourceHasNonInd(randomness)
rm.sampleCall(key, true, resourceCalls, getMaxTestSizeDuringSampler())
}
private fun sampleComResource(resourceCalls: MutableList<RestResourceCalls>, withDependency : Boolean){
if(withDependency){
dm.sampleRelatedResources(resourceCalls, 2, getMaxTestSizeDuringSampler())
}else{
sampleRandomComResource(resourceCalls)
}
}
private fun sampleManyResources(resourceCalls: MutableList<RestResourceCalls>, withDependency: Boolean){
if(withDependency){
val num = randomness.nextInt(3, getMaxTestSizeDuringSampler())
dm.sampleRelatedResources(resourceCalls, num, getMaxTestSizeDuringSampler())
}else{
sampleManyResources(resourceCalls)
}
}
private fun selectAIndResourceHasNonInd(randomness: Randomness) : String{
return randomness.choose(rm.getResourceCluster().filter { r -> r.value.isAnyAction() && !r.value.isIndependent() }.keys)
}
override fun feedback(evi : EvaluatedIndividual<RestIndividual>) {
if(config.resourceSampleStrategy.requiredArchive && evi.hasImprovement)
evi.individual.sampleSpec?.let { ssc.reportImprovement(it) }
}
private fun sampleRandomComResource(resourceCalls: MutableList<RestResourceCalls>){
val candidates = rm.getResourceCluster().filter { !it.value.isIndependent() }.keys
assert(candidates.size > 1)
val keys = randomness.choose(candidates, 2)
var size = getMaxTestSizeDuringSampler()
keys.forEach {
rm.sampleCall(it, true, resourceCalls, size)
size -= resourceCalls.last().seeActionSize(ActionFilter.NO_SQL)
}
}
private fun sampleManyResources(resourceCalls: MutableList<RestResourceCalls>){
val executed = mutableListOf<String>()
val depCand = rm.getResourceCluster().filter { r -> !r.value.isIndependent() }
var resourceSize = randomness.nextInt(3, if(config.maxResourceSize > 0) config.maxResourceSize else 5)
if(resourceSize > depCand.size) resourceSize = depCand.size + 1
var size = getMaxTestSizeDuringSampler()
val candR = rm.getResourceCluster().filter { r -> r.value.isAnyAction() }
while(size > 1 && executed.size < resourceSize){
val key = if(executed.size < resourceSize-1 && size > 2)
randomness.choose(depCand.keys.filter { !executed.contains(it) })
else if (candR.keys.any { !executed.contains(it) })
randomness.choose(candR.keys.filter { !executed.contains(it) })
else
randomness.choose(candR.keys)
rm.sampleCall(key, true, resourceCalls, size)
size -= resourceCalls.last().seeActionSize(ActionFilter.NO_SQL)
executed.add(key)
}
}
override fun createIndividual(restCalls: MutableList<RestCallAction>): RestIndividual {
val resourceCalls = restCalls.map {
val node = rm.getResourceNodeFromCluster(it.path.toString())
RestResourceCalls(
template = node.getTemplate(it.verb.toString()),
node = node,
actions = mutableListOf(it),
dbActions = listOf()
)
}.toMutableList()
val ind = RestIndividual(
resourceCalls=resourceCalls,
sampleType = SampleType.SMART_RESOURCE,
trackOperator = if (config.trackingEnabled()) this else null,
index = if (config.trackingEnabled()) time.evaluatedIndividuals else Traceable.DEFAULT_INDEX)
ind.doGlobalInitialize(searchGlobalState)
return ind
}
} | lgpl-3.0 | 10fb4f99a7a6dc0252f9bf13e83b216c | 39.707819 | 167 | 0.676979 | 4.757576 | false | false | false | false |
EMResearch/EvoMaster | core/src/main/kotlin/org/evomaster/core/problem/rest/RestIndividual.kt | 1 | 14070 | package org.evomaster.core.problem.rest
import org.evomaster.core.database.DbAction
import org.evomaster.core.database.DbActionUtils
import org.evomaster.core.problem.api.service.ApiWsIndividual
import org.evomaster.core.problem.external.service.ApiExternalServiceAction
import org.evomaster.core.problem.rest.resource.RestResourceCalls
import org.evomaster.core.problem.rest.resource.SamplerSpecification
import org.evomaster.core.search.*
import org.evomaster.core.search.ActionFilter.*
import org.evomaster.core.search.gene.*
import org.evomaster.core.search.tracer.Traceable
import org.evomaster.core.search.tracer.TraceableElementCopyFilter
import org.evomaster.core.search.tracer.TrackOperator
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import kotlin.math.max
/**
*
* @property trackOperator indicates which operator create this individual.
* @property index indicates when the individual is created, ie, using num of evaluated individual.
*/
class RestIndividual(
val sampleType: SampleType,
val sampleSpec: SamplerSpecification? = null,
trackOperator: TrackOperator? = null,
index : Int = -1,
allActions : MutableList<out ActionComponent>,
mainSize : Int = allActions.size,
dbSize: Int = 0,
groups : GroupsOfChildren<StructuralElement> = getEnterpriseTopGroups(allActions,mainSize,dbSize)
): ApiWsIndividual(trackOperator, index, allActions,
childTypeVerifier = {
RestResourceCalls::class.java.isAssignableFrom(it)
|| DbAction::class.java.isAssignableFrom(it)
}, groups) {
companion object{
private val log: Logger = LoggerFactory.getLogger(RestIndividual::class.java)
}
constructor(
resourceCalls: MutableList<RestResourceCalls>,
sampleType: SampleType,
sampleSpec: SamplerSpecification? = null,
dbInitialization: MutableList<DbAction> = mutableListOf(),
trackOperator: TrackOperator? = null,
index : Int = -1
) : this(sampleType, sampleSpec, trackOperator, index, mutableListOf<ActionComponent>().apply {
addAll(dbInitialization); addAll(resourceCalls)
}, resourceCalls.size, dbInitialization.size)
constructor(
actions: MutableList<out Action>,
sampleType: SampleType,
dbInitialization: MutableList<DbAction> = mutableListOf(),
trackOperator: TrackOperator? = null,
index : Int = Traceable.DEFAULT_INDEX
) : this(
actions.map {RestResourceCalls(actions= listOf(it as RestCallAction), dbActions = listOf())}.toMutableList(),
sampleType,
null,
dbInitialization,
trackOperator,
index
)
override fun copyContent(): Individual {
return RestIndividual(
sampleType,
sampleSpec?.copy(),
trackOperator,
index,
children.map { it.copy() }.toMutableList() as MutableList<out ActionComponent>,
mainSize = groupsView()!!.sizeOfGroup(GroupsOfChildren.MAIN),
dbSize = groupsView()!!.sizeOfGroup(GroupsOfChildren.INITIALIZATION_SQL)
)
}
override fun canMutateStructure(): Boolean {
return sampleType == SampleType.RANDOM ||
sampleType == SampleType.SMART_GET_COLLECTION ||
sampleType == SampleType.SMART_RESOURCE
}
/**
* Note that if resource-mio is enabled, [dbInitialization] of a RestIndividual is always empty, since DbActions are created
* for initializing an resource for a set of actions on the same resource.
* TODO is this no longer the case?
*
* This effects on a configuration with respect to [EMConfig.geneMutationStrategy] is ONE_OVER_N when resource-mio is enabled.
*
* In another word, if resource-mio is enabled, whatever [EMConfig.geneMutationStrategy] is, it always follows "GeneMutationStrategy.ONE_OVER_N_BIASED_SQL"
* strategy.
*
*/
override fun seeGenes(filter: GeneFilter): List<out Gene> {
return when (filter) {
GeneFilter.ALL -> seeAllActions().flatMap(Action::seeTopGenes)
GeneFilter.NO_SQL -> seeActions(ActionFilter.NO_SQL).flatMap(Action::seeTopGenes)
GeneFilter.ONLY_SQL -> seeDbActions().flatMap(DbAction::seeTopGenes)
GeneFilter.ONLY_EXTERNAL_SERVICE -> seeExternalServiceActions().flatMap(ApiExternalServiceAction::seeTopGenes)
}
}
enum class ResourceFilter { ALL, NO_SQL, ONLY_SQL, ONLY_SQL_INSERTION, ONLY_SQL_EXISTING }
/**
* @return involved resources in [this] RestIndividual
* for all [resourceCalls], we return their resource keys to represent the resource
* for dbActions, we employ their table names to represent the resource
*
* NOTE that for [RestResourceCalls], there might exist DbAction as well.
* But since the dbaction is to prepare resource for the endpoint whose goal is equivalent with POST here,
* we do not consider such dbactions as separated resources from the endpoint.
*/
fun seeResource(filter: ResourceFilter) : List<String>{
return when(filter){
ResourceFilter.ALL -> seeInitializingActions().filterIsInstance<DbAction>().map { it.table.name }.plus(
getResourceCalls().map { it.getResourceKey() }
)
ResourceFilter.NO_SQL -> getResourceCalls().map { it.getResourceKey() }
ResourceFilter.ONLY_SQL -> seeInitializingActions().filterIsInstance<DbAction>().map { it.table.name }
ResourceFilter.ONLY_SQL_EXISTING -> seeInitializingActions().filterIsInstance<DbAction>().filter { it.representExistingData }.map { it.table.name }
ResourceFilter.ONLY_SQL_INSERTION -> seeInitializingActions().filterIsInstance<DbAction>().filterNot { it.representExistingData }.map { it.table.name }
}
}
override fun size() = seeMainExecutableActions().size
//FIXME refactor
override fun verifyInitializationActions(): Boolean {
return DbActionUtils.verifyActions(seeInitializingActions().filterIsInstance<DbAction>())
}
override fun copy(copyFilter: TraceableElementCopyFilter): RestIndividual {
val copy = copy() as RestIndividual
when(copyFilter){
TraceableElementCopyFilter.NONE-> {}
TraceableElementCopyFilter.WITH_TRACK, TraceableElementCopyFilter.DEEP_TRACK ->{
copy.wrapWithTracking(null, tracking!!.copy())
}else -> throw IllegalStateException("${copyFilter.name} is not implemented!")
}
return copy
}
/**
* for each call, there exist db actions for preparing resources.
* however, the db action might refer to a db action which is not in the same call.
* In this case, we need to repair the fk of db actions among calls.
*
* Note: this is ignoring the DB Actions in the initialization of the individual, as we
* are building dependencies among resources here.
*
* TODO not sure whether build binding between fk and pk
*/
fun repairDbActionsInCalls(){
val previous = mutableListOf<DbAction>()
getResourceCalls().forEach { c->
c.repairFK(previous)
previous.addAll(c.seeActions(ONLY_SQL) as List<DbAction>)
}
}
/**
* @return all groups of actions for resource handling
*/
fun getResourceCalls() : List<RestResourceCalls> = children.filterIsInstance<RestResourceCalls>()
/**
* return all the resource calls in this individual, with their index in the children list
* @param isRelative indicates whether to return the relative index by only considering a list of resource calls
*/
fun getIndexedResourceCalls(isRelative: Boolean = true) : Map<Int,RestResourceCalls> = getIndexedChildren(RestResourceCalls::class.java).run {
if (isRelative)
this.map { it.key - getFirstIndexOfRestResourceCalls() to it.value }.toMap()
else
this
}
/****************************** manipulate resource call in an individual *******************************************/
/**
* remove the resource at [position]
*/
fun removeResourceCall(position : Int) {
if(!getIndexedResourceCalls().keys.contains(position))
throw IllegalArgumentException("position is out of range of list")
val removed = killChildByIndex(getFirstIndexOfRestResourceCalls() + position) as RestResourceCalls
removed.removeThisFromItsBindingGenes()
}
fun removeResourceCall(remove: List<RestResourceCalls>) {
if(!getResourceCalls().containsAll(remove))
throw IllegalArgumentException("specified rest calls are not part of this individual")
killChildren(remove)
remove.forEach { it.removeThisFromItsBindingGenes() }
}
/**
* add [restCalls] at [position], if [position] == -1, append the [restCalls] at the end
*/
fun addResourceCall(position: Int = -1, restCalls : RestResourceCalls) {
if (position == -1){
addChildToGroup(restCalls, GroupsOfChildren.MAIN)
}else{
if(position > children.size)
throw IllegalArgumentException("position is out of range of list")
addChildToGroup(getFirstIndexOfRestResourceCalls() + position, restCalls, GroupsOfChildren.MAIN)
}
}
private fun getFirstIndexOfRestResourceCalls() = max(0, max(children.indexOfLast { it is DbAction }+1, children.indexOfFirst { it is RestResourceCalls }))
/**
* replace the resourceCall at [position] with [resourceCalls]
*/
fun replaceResourceCall(position: Int, restCalls: RestResourceCalls){
if(!getIndexedResourceCalls().keys.contains(position))
throw IllegalArgumentException("position is out of range of list")
removeResourceCall(position)
addResourceCall(position, restCalls)
}
/**
* switch the resourceCall at [position1] and the resourceCall at [position2]
*/
fun swapResourceCall(position1: Int, position2: Int){
val valid = getIndexedResourceCalls().keys
if(!valid.contains(position1) || !valid.contains(position2))
throw IllegalArgumentException("position is out of range of list")
if(position1 == position2)
throw IllegalArgumentException("It is not necessary to swap two same position on the resource call list")
swapChildren(getFirstIndexOfRestResourceCalls() + position1, getFirstIndexOfRestResourceCalls() + position2)
}
fun getFixedActionIndexes(resourcePosition: Int)
= getIndexedResourceCalls()[resourcePosition]!!.seeActions(ALL).filter { seeMainExecutableActions().contains(it) }.map {
seeFixedMainActions().indexOf(it)
}
fun getDynamicActionLocalIds(resourcePosition: Int) =
getIndexedResourceCalls()[resourcePosition]!!.seeActions(ALL).filter { seeDynamicMainActions().contains(it) }.map { it.getLocalId() }
private fun validateSwap(first : Int, second : Int) : Boolean{
//TODO need update, although currently not in use
val position = getResourceCalls()[first].shouldBefore.map { r ->
getResourceCalls().indexOfFirst { it.getResourceNodeKey() == r }
}
if(!position.none { it > second }) return false
getResourceCalls().subList(0, second).find { it.shouldBefore.contains(getResourceCalls()[second].getResourceNodeKey()) }?.let {
return getResourceCalls().indexOf(it) < first
}
return true
}
/**
* @return movable position
*/
fun getMovablePosition(position: Int) : List<Int>{
return (getResourceCalls().indices)
.filter {
if(it < position) validateSwap(it, position) else if(it > position) validateSwap(position, it) else false
}
}
/**
* @return whether the call at the position is movable
*/
fun isMovable(position: Int) : Boolean{
return (getResourceCalls().indices)
.any {
if(it < position) validateSwap(it, position) else if(it > position) validateSwap(position, it) else false
}
}
/**
* @return possible swap positions of calls in this individual
*/
fun extractSwapCandidates(): Map<Int, Set<Int>>{
return getIndexedResourceCalls().map {
val range = handleSwapCandidates(this, it.key)
it.key to range
}.filterNot { it.second.isEmpty() }.toMap()
}
private fun handleSwapCandidates(ind: RestIndividual, indexToSwap: Int): Set<Int>{
val swapTo = handleSwapTo(ind, indexToSwap)
return swapTo.filter { t -> handleSwapTo(ind, t).contains(indexToSwap) }.toSet()
}
private fun handleSwapTo(ind: RestIndividual, indexToSwap: Int): Set<Int>{
val indexed = ind.getIndexedResourceCalls()
val toSwap = indexed[indexToSwap]!!
val before : Int = toSwap.shouldBefore.map { t ->
indexed.filter { it.value.getResourceNodeKey() == t }
.minByOrNull { it.key }?.key ?: (indexed.keys.maxOrNull()!! + 1)
}.minOrNull() ?: (indexed.keys.maxOrNull()!! + 1)
val after : Int = toSwap.depends.map { t->
indexed.filter { it.value.getResourceNodeKey() == t }
.maxByOrNull { it.key }?.key ?: 0
}.maxOrNull() ?: 0
if (after >= before) return emptySet()
return indexed.keys.filter { it >= after && it < before && it != indexToSwap }.toSet()
}
override fun getInsertTableNames(): List<String> {
return seeDbActions().filterNot { it.representExistingData }.map { it.table.name }
}
override fun seeMainExecutableActions(): List<RestCallAction> {
return super.seeMainExecutableActions() as List<RestCallAction>
}
} | lgpl-3.0 | 740c733d6a9e7163917ed43a3f06ebd4 | 41.255255 | 163 | 0.660128 | 4.740566 | false | false | false | false |
BlueBoxWare/LibGDXPlugin | src/test/testdata/annotators/colorAnnotator/KotlinToJava.kt | 1 | 270 | import com.badlogic.gdx.graphics.Color
import com.badlogic.gdx.graphics.Colors
const val constC = "#ffff00"
val s = "ff00ff"
val c1 = "#ff0000"
class C {
val c2 = Color(25667)
val c3 = Colors.get("RED")
fun f() {
Colors.put("foobar", Color.YELLOW)
}
}
| apache-2.0 | 8319dc25d8dd6370f74fd5092c2bd4f5 | 14 | 39 | 0.651852 | 2.727273 | false | false | false | false |
firebase/quickstart-android | firestore/app/src/main/java/com/google/firebase/example/fireeats/kotlin/RatingDialogFragment.kt | 1 | 2227 | package com.google.firebase.example.fireeats.kotlin
import android.content.Context
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.DialogFragment
import com.google.firebase.auth.ktx.auth
import com.google.firebase.example.fireeats.databinding.DialogRatingBinding
import com.google.firebase.example.fireeats.kotlin.model.Rating
import com.google.firebase.ktx.Firebase
/**
* Dialog Fragment containing rating form.
*/
class RatingDialogFragment : DialogFragment() {
private var _binding: DialogRatingBinding? = null
private val binding get() = _binding!!
private var ratingListener: RatingListener? = null
internal interface RatingListener {
fun onRating(rating: Rating)
}
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
_binding = DialogRatingBinding.inflate(inflater, container, false)
binding.restaurantFormButton.setOnClickListener { onSubmitClicked() }
binding.restaurantFormCancel.setOnClickListener { onCancelClicked() }
return binding.root
}
override fun onDestroyView() {
super.onDestroyView()
_binding = null
}
override fun onAttach(context: Context) {
super.onAttach(context)
if (parentFragment is RatingListener) {
ratingListener = parentFragment as RatingListener
}
}
override fun onResume() {
super.onResume()
dialog?.window?.setLayout(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.WRAP_CONTENT)
}
private fun onSubmitClicked() {
val user = Firebase.auth.currentUser
user?.let {
val rating = Rating(
it,
binding.restaurantFormRating.rating.toDouble(),
binding.restaurantFormText.text.toString())
ratingListener?.onRating(rating)
}
dismiss()
}
private fun onCancelClicked() {
dismiss()
}
companion object {
const val TAG = "RatingDialog"
}
}
| apache-2.0 | c58248940d3c266b1b427ea59889217b | 25.831325 | 77 | 0.66502 | 4.959911 | false | false | false | false |
google/private-compute-libraries | java/com/google/android/libraries/pcc/chronicle/util/TypedMap.kt | 1 | 3054 | /*
* Copyright 2022 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.libraries.pcc.chronicle.util
/**
* A [MutableTypedMap] is a mutable, type-safe map that allows for heterogeneously typed values.
*
* This map is keyed using implementations of the [Key] interface. A [Key] implementation will
* specify the class type of a corresponding value to be stored in the map.
*
* Example:
*
* ```kotlin
* object NameKey : Key<String>
* object IdKey : Key<Int>
*
* map[NameKey] = "First Last"
* map[IdKey] = 123
* ```
*/
class MutableTypedMap(val map: MutableMap<Key<Any>, Any> = mutableMapOf()) {
/** Set a value of type T for the given key */
operator fun <T : Any> set(key: Key<T>, value: T) {
@Suppress("UNCHECKED_CAST")
map[key as Key<Any>] = value
}
/** Get object of type T or null if not present */
operator fun <T> get(key: Key<T>): T? {
@Suppress("UNCHECKED_CAST") return map[key as Key<Any>] as T
}
/** Get immutable version of this [MutableTypedMap] */
fun toTypedMap() = TypedMap(this)
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other !is MutableTypedMap) return false
if (map != other.map) return false
return true
}
override fun hashCode(): Int {
return map.hashCode()
}
}
/**
* Keying structure for the [TypedMap] that can be associated with a value of type T, where T is a
* basic type (https://kotlinlang.org/docs/basic-types.html)
*
* Non-basic types are not recommended, since deep copies are currently not supported.
*
* Example usage of a [Key] for a String value:
* ```kotlin
* object Name : Key<String>
*
* // Set Name
* mutableTypedMap[Name] = "First Last"
* typedMap = TypedMap(mutableTypedMap)
*
* // Get Name
* val myName = typedMap[Name]
* ```
*/
interface Key<T>
/**
* A [TypedMap] is an immutable, type-safe map that allows for heterogeneously typed values. It
* copies in the current state of a provided [MutableTypedMap].
*/
class TypedMap(mutableTypedMap: MutableTypedMap = MutableTypedMap()) {
private val map: MutableTypedMap = MutableTypedMap(mutableTypedMap.map.toMutableMap())
/** Get object of type T or null if not present */
operator fun <T> get(key: Key<T>): T? = map[key]
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other !is TypedMap) return false
if (map != other.map) return false
return true
}
override fun hashCode(): Int {
return map.hashCode()
}
}
| apache-2.0 | 3e1ac5b9d8aba1506201334553f6e1c4 | 28.650485 | 98 | 0.682384 | 3.622776 | false | false | false | false |
Subsets and Splits