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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
nemerosa/ontrack | ontrack-job/src/main/java/net/nemerosa/ontrack/job/Schedule.kt | 1 | 1910 | package net.nemerosa.ontrack.job
import org.apache.commons.lang3.StringUtils
import java.time.Duration
import java.util.concurrent.TimeUnit
data class Schedule(
val initialPeriod: Long = 0,
val period: Long,
val unit: TimeUnit,
val cron: String? = null,
) {
val periodText: String
get() = when {
cron != null && cron.isNotBlank() -> cron
period <= 0 -> "Manually"
period == 1L -> "Every " + StringUtils.substringBeforeLast(unit.name.lowercase(), "s")
else -> "Every " + period + " " + unit.name.lowercase()
}
fun after(initial: Int): Schedule {
check(cron == null || cron.isBlank()) { "Setting an initial delay is not supported for cron schedules." }
return Schedule(
initial.toLong(),
period,
unit
)
}
fun after(initial: Duration): Schedule {
return after(initial.toMillis().toInt())
}
companion object {
fun cron(expression: String) = Schedule(
initialPeriod = 0,
period = 0,
unit = TimeUnit.MILLISECONDS,
cron = expression,
)
@JvmStatic
fun everySeconds(seconds: Long): Schedule {
return Schedule(0, seconds, TimeUnit.SECONDS)
}
@JvmStatic
fun everyMinutes(minutes: Long): Schedule {
return Schedule(0, minutes, TimeUnit.MINUTES)
}
@JvmField
val NONE = everySeconds(0)
@JvmField
val EVERY_SECOND = everySeconds(1)
@JvmField
val EVERY_MINUTE = everyMinutes(1)
@Suppress("unused")
@JvmField
val EVERY_HOUR = Schedule(0, 1, TimeUnit.HOURS)
@JvmField
val EVERY_DAY = Schedule(0, 1, TimeUnit.DAYS)
@JvmField
val EVERY_WEEK = Schedule(0, 7, TimeUnit.DAYS)
}
}
| mit | 3e91c7c50e99ac4c452b121211f4b623 | 27.507463 | 113 | 0.558115 | 4.370709 | false | false | false | false |
cbeust/kobalt | modules/kobalt-plugin-api/src/main/kotlin/com/beust/kobalt/IncludedFile.kt | 2 | 1707 | package com.beust.kobalt
import com.beust.kobalt.misc.KFiles
import com.beust.kobalt.misc.toString
import java.io.File
import java.nio.file.Paths
class IncludedFile(val fromOriginal: From, val toOriginal: To, val specs: List<IFileSpec>,
val expandJarFiles: Boolean = false) {
constructor(specs: List<IFileSpec>, expandJarFiles: Boolean = false) : this(From(""), To(""), specs, expandJarFiles)
fun from(s: String) = File(if (fromOriginal.isCurrentDir()) s else KFiles.joinDir(from, s))
val from: String get() = fromOriginal.path.replace("\\", "/")
fun to(s: String) = File(if (toOriginal.isCurrentDir()) s else KFiles.joinDir(to, s))
val to: String get() = toOriginal.path.replace("\\", "/")
override fun toString() = toString("IncludedFile",
"files - ", specs.map { it.toString() },
"from", from,
"to", to)
fun allFromFiles(directory: String? = null): List<File> {
val result = arrayListOf<File>()
specs.forEach { spec ->
// val fullDir = if (directory == null) from else KFiles.joinDir(directory, from)
spec.toFiles(directory, from).forEach { source ->
result.add(if (source.isAbsolute) source else File(source.path))
}
}
return result.map { Paths.get(it.path).normalize().toFile()}
}
}
open class Direction(open val p: String) {
override fun toString() = path
fun isCurrentDir() = path == "./"
val path: String get() =
if (p.isEmpty()) "./"
else if (p.startsWith("/") || p.endsWith("/")) p
else p + "/"
}
class From(override val p: String) : Direction(p)
class To(override val p: String) : Direction(p)
| apache-2.0 | 49919ab8493d6cb9da8bc2bad4f8dcbc | 37.795455 | 120 | 0.620387 | 3.835955 | false | false | false | false |
DankBots/Mega-Gnar | src/main/kotlin/gg/octave/bot/entities/framework/ExtendedMemberParser.kt | 1 | 694 | package gg.octave.bot.entities.framework
import me.devoxin.flight.api.Context
import me.devoxin.flight.internal.parsers.MemberParser
import me.devoxin.flight.internal.parsers.Parser
import net.dv8tion.jda.api.entities.Member
import java.util.*
class ExtendedMemberParser : Parser<Member> {
override fun parse(ctx: Context, param: String): Optional<Member> {
val parsed = defaultMemberParser.parse(ctx, param)
return parsed.or {
val mentioned = ctx.message.mentionedMembers.firstOrNull { it.asMention == param }
Optional.ofNullable(mentioned)
}
}
companion object {
private val defaultMemberParser = MemberParser()
}
}
| mit | 5a988ffff2b99e9f597e6e09b2a7b42c | 30.545455 | 94 | 0.716138 | 4.106509 | false | false | false | false |
d9n/intellij-rust | src/main/kotlin/org/rust/ide/intentions/SpecifyTypeExplicitlyIntention.kt | 1 | 1615 | package org.rust.ide.intentions
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiElement
import org.rust.lang.core.psi.RsLetDecl
import org.rust.lang.core.psi.RsPatIdent
import org.rust.lang.core.psi.RsPsiFactory
import org.rust.lang.core.psi.ext.parentOfType
import org.rust.lang.core.types.infer.inferDeclarationType
import org.rust.lang.core.types.ty.Ty
import org.rust.lang.core.types.ty.TyUnknown
class SpecifyTypeExplicitlyIntention : RsElementBaseIntentionAction<SpecifyTypeExplicitlyIntention.Context>() {
override fun getFamilyName() = "Specify type explicitly"
override fun getText() = "Specify type explicitly"
override fun findApplicableContext(project: Project, editor: Editor, element: PsiElement): Context? {
val letDecl = element.parentOfType<RsLetDecl>() ?: return null
if(letDecl.typeReference != null) {
return null
}
val ident = letDecl.pat as? RsPatIdent ?: return null
val type = inferDeclarationType(ident.patBinding)
if (type is TyUnknown) {
return null
}
return Context(type, letDecl)
}
override fun invoke(project: Project, editor: Editor, ctx: Context) {
val factory = RsPsiFactory(project)
val createdType = factory.createType(ctx.type.toString())
val letDecl = ctx.letDecl
val colon = letDecl.addAfter(factory.createColon(), letDecl.pat)
letDecl.addAfter(createdType, colon)
}
data class Context(
val type: Ty,
val letDecl: RsLetDecl
)
}
| mit | 377f3728a764820ccb50a66a558010b4 | 34.108696 | 111 | 0.710836 | 4.227749 | false | false | false | false |
soywiz/korge | korge-swf/src/commonMain/kotlin/com/soywiz/korfl/AbcUtil.kt | 1 | 522 | package com.soywiz.korfl
import com.soywiz.korio.stream.*
fun SyncStream.readU30(): Int {
var result = readU8()
if ((result and 0x80) == 0) return result
result = (result and 0x7f) or (readU8() shl 7)
if ((result and 0x4000) == 0) return result
result = (result and 0x3fff) or (readU8() shl 14)
if ((result and 0x200000) == 0) return result
result = (result and 0x1fffff) or (readU8() shl 21)
if ((result and 0x10000000) == 0) return result
result = (result and 0xfffffff) or (readU8() shl 28)
return result
}
| apache-2.0 | 2245a541108dc4c980e3ffbfd82ae95e | 31.625 | 53 | 0.687739 | 2.821622 | false | false | false | false |
Andr3Carvalh0/mGBA | app/src/main/java/io/mgba/data/local/model/Cheat.kt | 1 | 850 | package io.mgba.data.local.model
import java.io.File
import androidx.annotation.NonNull
import androidx.room.ColumnInfo
import androidx.room.Entity
import androidx.room.ForeignKey
import androidx.room.PrimaryKey
import androidx.room.ForeignKey.CASCADE
@Entity(tableName = "Cheats", foreignKeys = [ForeignKey(entity = Game::class, parentColumns = arrayOf("id"), childColumns = arrayOf("gameKey"), onDelete = CASCADE)])
class Cheat {
@PrimaryKey(autoGenerate = true)
var id: Int = 0
@ColumnInfo(name = "gameKey")
@NonNull
@get:NonNull
var gameKey: File? = null
@ColumnInfo(name = "cheatName")
var value: String? = null
@ColumnInfo(name = "codeType")
var type: Int = 0
@ColumnInfo(name = "codeState")
var enabled: Boolean = false
@ColumnInfo(name = "codeName")
var name: String? = null
}
| mpl-2.0 | fb0b0fc7f10e0225ecd66da6e4fc760e | 24 | 165 | 0.701176 | 3.863636 | false | false | false | false |
martin-nordberg/KatyDOM | Katydid-CSS-JS/src/main/kotlin/o/katydid/css/styles/builders/KatydidLineStyleBuilder.kt | 1 | 2066 | //
// (C) Copyright 2018-2019 Martin E. Nordberg III
// Apache 2.0 License
//
package o.katydid.css.styles.builders
import o.katydid.css.measurements.Length
import o.katydid.css.measurements.Percentage
import o.katydid.css.styles.KatydidStyle
import o.katydid.css.types.ENormal
import x.katydid.css.infrastructure.makeDecimalString
//---------------------------------------------------------------------------------------------------------------------
/**
* Builder class for setting line style properties of a given [style] from a nested block.
*/
@KatydidStyleBuilderDsl
class KatydidLineStyleBuilder(
private val style: KatydidStyle
) {
fun height(value: Length) =
style.lineHeight(value)
fun height(value: Percentage) =
style.lineHeight(value)
fun height(value: Float) =
style.lineHeight(value)
fun height(value: ENormal) =
style.lineHeight(value)
}
//---------------------------------------------------------------------------------------------------------------------
fun KatydidStyle.letterSpacing(value: Length) =
setProperty("letter-spacing", "$value")
fun KatydidStyle.letterSpacing(value: ENormal) =
setProperty("letter-spacing", "$value")
//---------------------------------------------------------------------------------------------------------------------
fun KatydidStyle.line(build: KatydidLineStyleBuilder.() -> Unit) =
KatydidLineStyleBuilder(this).build()
//---------------------------------------------------------------------------------------------------------------------
fun KatydidStyle.lineHeight(value: Length) =
setProperty("line-height", "$value")
fun KatydidStyle.lineHeight(value: Percentage) =
setProperty("line-height", "$value")
fun KatydidStyle.lineHeight(value: Float) =
setProperty("line-height", makeDecimalString(value))
fun KatydidStyle.lineHeight(value: ENormal) =
setProperty("line-height", "$value")
//---------------------------------------------------------------------------------------------------------------------
| apache-2.0 | 4f965f1f09c35e4d34f2bc58f65c24d9 | 30.784615 | 119 | 0.517425 | 5.352332 | false | false | false | false |
android/security-samples | FileLocker/app/src/main/java/com/android/example/filelocker/ListFragment.kt | 1 | 7019 | /*
* Copyright 2019 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.example.filelocker
import android.os.Bundle
import android.view.LayoutInflater
import android.view.MenuItem
import android.view.View
import android.view.ViewGroup
import android.widget.EditText
import androidx.annotation.StringRes
import androidx.appcompat.app.AlertDialog
import androidx.fragment.app.Fragment
import androidx.lifecycle.observe
import androidx.navigation.fragment.findNavController
import androidx.security.crypto.EncryptedSharedPreferences
import androidx.security.crypto.MasterKeys
import com.android.example.filelocker.databinding.FragmentListBinding
import com.google.android.material.dialog.MaterialAlertDialogBuilder
import com.google.android.material.snackbar.Snackbar
private const val ENCRYPTED_PREFS_FILE_NAME = "default_prefs"
private const val ENCRYPTED_PREFS_PASSWORD_KEY = "key_prefs_password"
class ListFragment : Fragment(), FileAdapter.FileAdapterListener {
private lateinit var binding: FragmentListBinding
private val sharedPreferences by lazy {
EncryptedSharedPreferences.create(
ENCRYPTED_PREFS_FILE_NAME,
MasterKeys.getOrCreate(MasterKeys.AES256_GCM_SPEC),
requireContext(),
EncryptedSharedPreferences.PrefKeyEncryptionScheme.AES256_SIV,
EncryptedSharedPreferences.PrefValueEncryptionScheme.AES256_GCM
)
}
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
binding = FragmentListBinding.inflate(inflater, container, false)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
val adapter = FileAdapter(this)
binding.toolbar.inflateMenu(R.menu.toolbar_list_menu)
binding.toolbar.setOnMenuItemClickListener { menuItem ->
onMenuItemClick(menuItem)
}
binding.recyclerView.adapter = adapter
// Observe this app's files directory to be displayed as a list.
DirectoryLiveData(requireContext().filesDir).observe(viewLifecycleOwner) { newList ->
adapter.submitList(newList)
}
}
override fun onFileClicked(file: FileEntity) {
onEncryptedFileClicked(file)
}
private fun onMenuItemClick(item: MenuItem?): Boolean {
return when (item?.itemId) {
R.id.menu_list_add_item -> {
findNavController().navigate(
ListFragmentDirections.actionListFragmentToEditFragment("")
)
true
}
R.id.menu_list_password -> {
if (getPassword() == null) showSetPasswordDialog() else showResetPasswordDialog()
true
}
else -> false
}
}
private fun showSetPasswordDialog() {
buildPasswordDialog(title = R.string.dialog_set_password_title) {
setPassword(getPassword(), it)
}.show()
}
private fun showResetPasswordDialog() {
buildResetPasswordDialog { current, new ->
setPassword(current, new)
}.show()
}
private fun getPassword(): String? {
return sharedPreferences.getString(
ENCRYPTED_PREFS_PASSWORD_KEY,
null
)
}
private fun setPassword(current: String?, new: String?) {
if (current != getPassword()) {
showSnackbar(R.string.error_current_password_incorrect)
return
}
if (new.isNullOrBlank()) {
sharedPreferences.edit().putString(ENCRYPTED_PREFS_PASSWORD_KEY, null).apply()
showSnackbar(R.string.message_password_cleared)
} else {
sharedPreferences.edit().putString(ENCRYPTED_PREFS_PASSWORD_KEY, new).apply()
showSnackbar(R.string.message_password_set)
}
}
private fun showSnackbar(@StringRes messageRes: Int) {
Snackbar.make(binding.coordinator, messageRes, Snackbar.LENGTH_LONG).show()
}
private fun onEncryptedFileClicked(file: FileEntity) {
if (getPassword() == null) {
editFile(file)
} else {
buildPasswordDialog {
if (it == getPassword()) {
editFile(file)
} else {
showSnackbar(R.string.error_incorrect_password)
}
}.show()
}
}
private fun editFile(file: FileEntity) {
findNavController().navigate(
ListFragmentDirections
.actionListFragmentToEditFragment(file.title)
)
}
private fun buildPasswordDialog(
@StringRes title: Int = R.string.dialog_password_title,
onPositiveClicked: (value: String) -> Unit
): AlertDialog {
val view = View.inflate(requireContext(), R.layout.alert_dialog_password_layout, null)
val editTextView: EditText = view.findViewById(R.id.password_input_edit_text)
return MaterialAlertDialogBuilder(requireContext())
.setTitle(title)
.setView(view)
.setPositiveButton(R.string.dialog_password_positive_button) { _, _ ->
onPositiveClicked(editTextView.text.toString())
}
.setNegativeButton(R.string.dialog_password_negative_button) { _, _ -> }
.create()
}
private fun buildResetPasswordDialog(
@StringRes title: Int = R.string.dialog_new_password_title,
onPositiveClicked: (current: String, new: String) -> Unit
): AlertDialog {
val view = View.inflate(requireContext(), R.layout.alert_dialog_reset_password_layout, null)
val passwordEditTextView: EditText = view.findViewById(R.id.password_input_edit_text)
val newPasswordEditTextView: EditText = view.findViewById(R.id.new_password_input_edit_text)
return MaterialAlertDialogBuilder(requireContext())
.setTitle(title)
.setView(view)
.setPositiveButton(R.string.dialog_new_password_positive_button) { _, _ ->
onPositiveClicked(
passwordEditTextView.text.toString(),
newPasswordEditTextView.text.toString()
)
}
.setNegativeButton(R.string.dialog_new_password_negative_button) { _, _ -> }
.create()
}
} | apache-2.0 | bce9598bbef413c5bbbac3bf4991546e | 34.816327 | 100 | 0.650662 | 4.857439 | false | false | false | false |
marcelgross90/Cineaste | app/src/main/kotlin/de/cineaste/android/entity/series/Series.kt | 1 | 1798 | package de.cineaste.android.entity.series
import com.google.gson.annotations.SerializedName
import java.util.Date
data class Series(
var id: Long = 0,
var name: String = "",
@SerializedName("vote_average")
var voteAverage: Double = 0.toDouble(),
@SerializedName("vote_count")
var voteCount: Int = 0,
@SerializedName("overview")
var description: String? = null,
@SerializedName("first_air_date")
var releaseDate: Date? = null,
@SerializedName("in_production")
var isInProduction: Boolean = false,
@SerializedName("number_of_episodes")
var numberOfEpisodes: Int = 0,
@SerializedName("number_of_seasons")
var numberOfSeasons: Int = 0,
@SerializedName("poster_path")
var posterPath: String? = null,
@SerializedName("backdrop_path")
var backdropPath: String? = null,
var seasons: List<Season> = listOf(),
var isWatched: Boolean = false,
var listPosition: Int = 0
) {
val currentNumberOfSeason: Int
get() {
var lastSeason = Season()
for (season in seasons) {
lastSeason = season
if (!season.isWatched) {
return season.seasonNumber
}
}
return lastSeason.seasonNumber
}
val currentNumberOfEpisode: Int
get() {
var lastSeason = Season()
for (season in seasons) {
lastSeason = season
if (!season.isWatched) {
for (episode in season.episodes) {
if (!episode.isWatched) {
return episode.episodeNumber
}
}
}
}
return lastSeason.episodeCount
}
}
| gpl-3.0 | aff5c222ed7288103c38706d3131edcc | 28.47541 | 56 | 0.556174 | 4.769231 | false | false | false | false |
slartus/4pdaClient-plus | app/src/main/java/org/softeg/slartus/forpdaplus/repositories/ForumsRepository.kt | 1 | 1984 | package org.softeg.slartus.forpdaplus.repositories
import io.reactivex.subjects.BehaviorSubject
import kotlinx.coroutines.CoroutineExceptionHandler
import kotlinx.coroutines.MainScope
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.flow.distinctUntilChanged
import kotlinx.coroutines.launch
import org.softeg.slartus.forpdaapi.Forum
import org.softeg.slartus.forpdaplus.common.AppLog
import ru.softeg.slartus.forum.api.ForumRepository
@Deprecated("use ru.softeg.slartus.forum.api.ForumRepository instead.")
class ForumsRepository private constructor() {
private object Holder {
val INSTANCE = ForumsRepository()
}
private val errorHandler = CoroutineExceptionHandler { _, ex ->
MainScope().launch {
AppLog.e(ex)
}
}
val forumsSubject: BehaviorSubject<List<Forum>> = BehaviorSubject.createDefault(emptyList())
fun init(forumRepository: ForumRepository) {
MainScope().launch(errorHandler) {
forumRepository.forum
.distinctUntilChanged()
.collect { rawItems ->
forumsSubject.onNext(rawItems.map {
Forum(it.id, it.title ?: "").apply {
description = it.description
isHasTopics = it.isHasTopics
isHasForums = it.isHasForums
iconUrl = it.iconUrl
parentId = it.parentId
}
})
}
}
InternetConnection.instance.loadDataOnInternetConnected({
MainScope().launch(errorHandler) {
forumRepository.load()
}
})
}
fun findById(
startForumId: String?
): Forum? {
return forumsSubject.value?.firstOrNull { it.id == startForumId }
}
companion object {
@JvmStatic
val instance by lazy { Holder.INSTANCE }
}
} | apache-2.0 | 6a46f545d555bdc29e6301800fa9e139 | 32.083333 | 96 | 0.608367 | 5.234828 | false | false | false | false |
stripe/stripe-android | link/src/main/java/com/stripe/android/link/account/LinkAccountManager.kt | 1 | 15178 | package com.stripe.android.link.account
import androidx.annotation.VisibleForTesting
import com.stripe.android.core.exception.AuthenticationException
import com.stripe.android.link.LinkPaymentDetails
import com.stripe.android.link.LinkPaymentLauncher
import com.stripe.android.link.analytics.LinkEventsReporter
import com.stripe.android.link.model.AccountStatus
import com.stripe.android.link.model.LinkAccount
import com.stripe.android.link.repositories.LinkRepository
import com.stripe.android.link.ui.inline.UserInput
import com.stripe.android.model.ConsumerPaymentDetailsUpdateParams
import com.stripe.android.model.ConsumerSession
import com.stripe.android.model.ConsumerSignUpConsentAction
import com.stripe.android.model.PaymentMethodCreateParams
import com.stripe.android.model.StripeIntent
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.transform
import kotlinx.coroutines.launch
import javax.inject.Inject
import javax.inject.Singleton
/**
* Manages the Link account for the current user, persisting it across app usages.
*/
@Singleton
internal class LinkAccountManager @Inject constructor(
private val config: LinkPaymentLauncher.Configuration,
private val linkRepository: LinkRepository,
private val cookieStore: CookieStore,
private val linkEventsReporter: LinkEventsReporter
) {
private val _linkAccount = MutableStateFlow<LinkAccount?>(null)
var linkAccount: StateFlow<LinkAccount?> = _linkAccount
/**
* The publishable key for the signed in Link account.
*/
var consumerPublishableKey: String? = null
val accountStatus = linkAccount.transform { value ->
emit(
// If we already fetched an account, return its status
value?.accountStatus
?: (
// If consumer has previously logged in, fetch their account
cookieStore.getAuthSessionCookie()?.let {
lookupConsumer(null).map {
it?.accountStatus
}.getOrElse {
AccountStatus.Error
}
}
// If the user recently signed up on this device, use their email
?: cookieStore.getNewUserEmail()?.let {
lookupConsumer(it).map {
it?.accountStatus
}.getOrElse {
AccountStatus.Error
}
}
// If a customer email was passed in, lookup the account,
// unless the user has logged out of this account
?: config.customerEmail?.let { customerEmail ->
if (hasUserLoggedOut(customerEmail)) {
AccountStatus.SignedOut
} else {
lookupConsumer(customerEmail).map {
it?.accountStatus
}.getOrElse {
AccountStatus.Error
}
}
} ?: AccountStatus.SignedOut
)
)
}
/**
* Keeps track of whether the user has logged out during this session. If that's the case, we
* want to ignore the email passed in by the merchant to avoid confusion.
*/
private var userHasLoggedOut = false
/**
* Retrieves the Link account associated with the email if it exists.
*
* Optionally starts a user session, by storing the cookie for the account and starting a
* verification if needed.
*
* When the [email] parameter is null, will try to fetch the account for the currently stored
* cookie.
*/
suspend fun lookupConsumer(
email: String?,
startSession: Boolean = true
): Result<LinkAccount?> =
linkRepository.lookupConsumer(email, cookie())
.also {
if (it.isFailure) {
linkEventsReporter.onAccountLookupFailure()
}
}.map { consumerSessionLookup ->
if (email == null && !consumerSessionLookup.exists) {
// Lookup with cookie-only failed, so cookie is invalid
cookieStore.updateAuthSessionCookie("")
}
consumerSessionLookup.consumerSession?.let { consumerSession ->
if (startSession) {
setAccountNullable(consumerSession)
} else {
LinkAccount(consumerSession)
}
}
}.mapCatching {
it?.let { account ->
if (startSession && !account.isVerified) {
setAccount(
linkRepository.startVerification(
account.clientSecret,
consumerPublishableKey,
cookie()
).getOrThrow()
)
} else {
account
}
}
}
/**
* Use the user input in memory to sign in to an existing account or sign up for a new Link
* account, starting verification if needed.
*/
suspend fun signInWithUserInput(userInput: UserInput): Result<LinkAccount> =
when (userInput) {
is UserInput.SignIn -> lookupConsumer(userInput.email).mapCatching {
requireNotNull(it) { "Error fetching user account" }
}
is UserInput.SignUp -> signUp(
email = userInput.email,
phone = userInput.phone,
country = userInput.country,
name = userInput.name,
consentAction = ConsumerSignUpConsentAction.Checkbox
).also {
if (it.isSuccess) {
linkEventsReporter.onSignupCompleted(true)
} else {
linkEventsReporter.onSignupFailure(true)
}
}
}
/**
* Registers the user for a new Link account and starts verification if needed.
*/
suspend fun signUp(
email: String,
phone: String,
country: String,
name: String?,
consentAction: ConsumerSignUpConsentAction
): Result<LinkAccount> =
linkRepository.consumerSignUp(email, phone, country, name, cookie(), consentAction)
.map { consumerSession ->
cookieStore.storeNewUserEmail(email)
setAccount(consumerSession)
}.mapCatching { account ->
if (account.isVerified) {
account
} else {
setAccount(
linkRepository.startVerification(
account.clientSecret,
consumerPublishableKey,
cookie()
).getOrThrow()
)
}
}
/**
* Triggers sending a verification code to the user.
*/
suspend fun startVerification(): Result<LinkAccount> = retryingOnAuthError { clientSecret ->
linkRepository.startVerification(clientSecret, consumerPublishableKey, cookie())
.also {
if (it.isFailure) {
linkEventsReporter.on2FAStartFailure()
}
}.map { consumerSession ->
setAccount(consumerSession)
}
}
/**
* Confirms a verification code sent to the user.
*/
suspend fun confirmVerification(code: String): Result<LinkAccount> =
retryingOnAuthError { clientSecret ->
linkRepository.confirmVerification(code, clientSecret, consumerPublishableKey, cookie())
.map { consumerSession ->
setAccount(consumerSession)
}
}
/**
* Fetch all saved payment methods for the signed in consumer.
*/
suspend fun listPaymentDetails() = retryingOnAuthError { clientSecret ->
linkRepository.listPaymentDetails(clientSecret, consumerPublishableKey)
}
/**
* Creates a new PaymentDetails.Card attached to the current account.
*
* @return The parameters needed to confirm the current Stripe Intent using the newly created
* Payment Details.
*/
suspend fun createCardPaymentDetails(
paymentMethodCreateParams: PaymentMethodCreateParams
): Result<LinkPaymentDetails.New> =
linkAccount.value?.let { account ->
createCardPaymentDetails(
paymentMethodCreateParams,
account.email,
config.stripeIntent
)
} ?: Result.failure(
IllegalStateException("A non-null Link account is needed to create payment details")
)
/**
* Create a session used to connect a bank account through Financial Connections.
*/
suspend fun createFinancialConnectionsSession() = retryingOnAuthError { clientSecret ->
linkRepository.createFinancialConnectionsSession(
clientSecret,
consumerPublishableKey
)
}
/**
* Create a new Bank Account payment method attached to the consumer account.
*/
suspend fun createBankAccountPaymentDetails(
financialConnectionsAccountId: String
) = retryingOnAuthError { clientSecret ->
linkRepository.createBankAccountPaymentDetails(
financialConnectionsAccountId,
clientSecret,
consumerPublishableKey
)
}
/**
* Create a new Card payment method attached to the consumer account.
*/
suspend fun createCardPaymentDetails(
paymentMethodCreateParams: PaymentMethodCreateParams,
userEmail: String,
stripeIntent: StripeIntent
) = retryingOnAuthError { clientSecret ->
linkRepository.createCardPaymentDetails(
paymentMethodCreateParams,
userEmail,
stripeIntent,
clientSecret,
consumerPublishableKey
)
}
/**
* Update an existing payment method in the signed in consumer account.
*/
suspend fun updatePaymentDetails(updateParams: ConsumerPaymentDetailsUpdateParams) =
retryingOnAuthError { clientSecret ->
linkRepository.updatePaymentDetails(updateParams, clientSecret, consumerPublishableKey)
}
/**
* Delete the payment method from the signed in consumer account.
*/
suspend fun deletePaymentDetails(paymentDetailsId: String) =
retryingOnAuthError { clientSecret ->
linkRepository.deletePaymentDetails(
paymentDetailsId,
clientSecret,
consumerPublishableKey
)
}
/**
* Make an API call with the client_secret for the currently signed in account, retrying once
* if the call fails because of an [AuthenticationException].
*/
private suspend fun <T> retryingOnAuthError(apiCall: suspend (String) -> Result<T>): Result<T> =
linkAccount.value?.let { account ->
apiCall(account.clientSecret).fold(
onSuccess = {
Result.success(it)
},
onFailure = {
if (it is AuthenticationException && cookie() != null) {
// Try fetching the user account with the stored cookie, then retry API call
lookupConsumer(null).fold(
onSuccess = {
it?.let { updatedAccount ->
apiCall(updatedAccount.clientSecret)
}
},
onFailure = {
Result.failure(it)
}
)
} else {
Result.failure(it)
}
}
)
} ?: Result.failure(
IllegalStateException("User not signed in")
)
/**
* Logs the current consumer out.
*
* Regardless of the result of the API call, the local cookie is deleted and the current account
* is cleared. This will effectively log the user out, so there's no need to wait for the result
* of this call to consider it done.
*/
fun logout() =
linkAccount.value?.let { account ->
val cookie = cookie()
cookieStore.logout(account.email)
userHasLoggedOut = true
_linkAccount.value = null
val publishableKey = consumerPublishableKey
consumerPublishableKey = null
GlobalScope.launch {
linkRepository.logout(account.clientSecret, publishableKey, cookie)
}
}
/**
* Whether the user has logged out from any account during this session, or the last logout was
* from the [email] passed as parameter, even if in a previous session.
*/
fun hasUserLoggedOut(email: String?) = userHasLoggedOut ||
(email?.let { cookieStore.isEmailLoggedOut(it) } ?: false)
private fun setAccount(consumerSession: ConsumerSession): LinkAccount {
maybeUpdateConsumerPublishableKey(consumerSession)
val newAccount = LinkAccount(consumerSession)
_linkAccount.value = newAccount
cookieStore.updateAuthSessionCookie(newAccount.getAuthSessionCookie())
if (cookieStore.isEmailLoggedOut(newAccount.email)) {
cookieStore.storeLoggedOutEmail("")
}
return newAccount
}
@VisibleForTesting
fun setAccountNullable(consumerSession: ConsumerSession?): LinkAccount? =
consumerSession?.let {
setAccount(it)
} ?: run {
_linkAccount.value = null
consumerPublishableKey = null
null
}
/**
* Update the [consumerPublishableKey] value if needed.
*
* Only calls to [lookupConsumer] and [signUp] return the publishable key. For other calls, we
* want to keep using the current key unless the user signed out.
*/
private fun maybeUpdateConsumerPublishableKey(newSession: ConsumerSession) {
newSession.publishableKey?.let {
// If the session has a key, start using it
consumerPublishableKey = it
} ?: run {
// Keep the current key if it's the same user, reset it if the user changed
if (_linkAccount.value?.email != newSession.emailAddress) {
consumerPublishableKey = null
}
}
}
private fun cookie() = cookieStore.getAuthSessionCookie()
}
| mit | 2e218cde22304e18105722bf32788adb | 37.328283 | 100 | 0.571749 | 5.72107 | false | false | false | false |
andimage/PCBridge | src/main/kotlin/com/projectcitybuild/repositories/BanRepository.kt | 1 | 2810 | package com.projectcitybuild.repositories
import com.projectcitybuild.core.infrastructure.network.APIClient
import com.projectcitybuild.core.infrastructure.network.APIRequestFactory
import com.projectcitybuild.entities.responses.GameBan
import java.util.Date
import java.util.UUID
import javax.inject.Inject
class BanRepository @Inject constructor(
private val apiRequestFactory: APIRequestFactory,
private val apiClient: APIClient,
) {
class PlayerAlreadyBannedException : Exception()
class PlayerNotBannedException : Exception()
@Throws(PlayerAlreadyBannedException::class)
suspend fun ban(
targetPlayerUUID: UUID,
targetPlayerName: String,
staffId: UUID?,
reason: String?
) {
try {
val banApi = apiRequestFactory.pcb.banApi
apiClient.execute {
banApi.storeBan(
playerId = targetPlayerUUID.toString(),
playerIdType = "minecraft_uuid",
playerAlias = targetPlayerName,
staffId = staffId.toString(),
staffIdType = "minecraft_uuid",
reason = if (reason != null && reason.isNotEmpty()) reason else null,
expiresAt = null,
isGlobalBan = 1
)
}
} catch (e: APIClient.HTTPError) {
if (e.errorBody?.id == "player_already_banned") {
throw PlayerAlreadyBannedException()
}
throw e
}
}
@Throws(PlayerNotBannedException::class)
suspend fun unban(targetPlayerUUID: UUID, staffId: UUID?) {
try {
val banApi = apiRequestFactory.pcb.banApi
apiClient.execute {
banApi.storeUnban(
playerId = targetPlayerUUID.toString(),
playerIdType = "minecraft_uuid",
staffId = staffId.toString(),
staffIdType = "minecraft_uuid"
)
}
} catch (e: APIClient.HTTPError) {
if (e.errorBody?.id == "player_not_banned") {
throw PlayerNotBannedException()
}
throw e
}
}
suspend fun get(targetPlayerUUID: UUID): GameBan? {
val banApi = apiRequestFactory.pcb.banApi
val response = apiClient.execute {
banApi.requestStatus(
playerId = targetPlayerUUID.toString(),
playerType = "minecraft_uuid"
)
}
val ban = response.data
if (ban != null) {
if (!ban.isActive) return null
val hasExpired = ban.expiresAt != null && ban.expiresAt <= Date().time
if (hasExpired) return null
}
return ban
}
}
| mit | 608636b9f83087e6e90554ff972ec07f | 32.855422 | 89 | 0.566192 | 4.929825 | false | false | false | false |
Studium-SG/neurals | src/main/java/sg/studium/neurals/dataset/InMemoryDataSetIterator.kt | 1 | 2687 | package sg.studium.neurals.dataset
import org.nd4j.linalg.dataset.DataSet
import org.nd4j.linalg.dataset.api.DataSetPreProcessor
import org.nd4j.linalg.factory.Nd4j
import java.lang.UnsupportedOperationException
/**
* In-memory iterator.
*/
class InMemoryDataSetIterator(
private val X: List<DoubleArray>,
private val Y: List<DoubleArray>,
private val header: Array<String>,
private val yCols: Array<String>,
private val batchSize: Int
) : DsIterator {
constructor(xy: XY, batchSize: Int) : this(xy.X, xy.Y, xy.allColumns, xy.yCols, batchSize)
private var cursor: Int = 0
private var gotAround: Boolean = false
private var _preProcessor: DataSetPreProcessor? = null
override fun resetSupported(): Boolean {
return true
}
override fun getAllColumns(): Array<String> {
return header
}
override fun getlYColumns(): Array<String> {
return yCols
}
override fun getLabels(): MutableList<String> {
throw UnsupportedOperationException()
}
override fun cursor(): Int {
return cursor
}
override fun remove() {
throw UnsupportedOperationException()
}
override fun inputColumns(): Int {
return X.first().size
}
override fun numExamples(): Int {
return X.size
}
override fun batch(): Int {
return batchSize
}
override fun next(num: Int): DataSet {
val avail = Math.min(num, X.size - cursor)
val x = Nd4j.create(avail, X[0].size)
val y = Nd4j.create(avail, Y[0].size)
for (i in 0..avail - 1) {
x.putRow(i, Nd4j.create(X[cursor]))
y.putRow(i, Nd4j.create(Y[cursor]))
cursor++
if (cursor == X.size) {
cursor = 0
gotAround = true
}
}
val ds = DataSet(x, y, null, null)
if (_preProcessor != null) {
_preProcessor!!.preProcess(ds)
}
return ds
}
override fun next(): DataSet {
return next(batchSize)
}
override fun totalOutcomes(): Int {
return Y.first().size
}
override fun totalExamples(): Int {
return numExamples()
}
override fun reset() {
cursor = 0
gotAround = false
}
override fun hasNext(): Boolean {
return !gotAround
}
override fun asyncSupported(): Boolean {
return false
}
override fun setPreProcessor(preProcessor: DataSetPreProcessor?) {
_preProcessor = preProcessor
}
override fun getPreProcessor(): DataSetPreProcessor? {
return _preProcessor
}
} | gpl-3.0 | 3184a3234914b19cb910f4ce60ae2eca | 22.578947 | 94 | 0.595087 | 4.23817 | false | false | false | false |
Undin/intellij-rust | src/main/kotlin/org/rust/lang/core/psi/ext/RsMethodOrPath.kt | 2 | 1200 | /*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.lang.core.psi.ext
import org.rust.lang.core.psi.RsAssocTypeBinding
import org.rust.lang.core.psi.RsLifetime
import org.rust.lang.core.psi.RsTypeArgumentList
import org.rust.lang.core.psi.RsTypeReference
val RsMethodOrPath.lifetimeArguments: List<RsLifetime> get() = typeArgumentList?.lifetimeArguments.orEmpty()
val RsMethodOrPath.typeArguments: List<RsTypeReference> get() = typeArgumentList?.typeArguments.orEmpty()
val RsMethodOrPath.constArguments: List<RsElement> get() = typeArgumentList?.constArguments.orEmpty()
val RsMethodOrPath.assocTypeBindings: List<RsAssocTypeBinding> get() = typeArgumentList?.assocTypeBindingList.orEmpty()
fun RsMethodOrPath.getGenericArguments(
includeLifetimes: Boolean = true,
includeTypes: Boolean = true,
includeConsts: Boolean = true,
includeAssocBindings: Boolean = true
): List<RsElement> = typeArgumentList?.getGenericArguments(
includeLifetimes,
includeTypes,
includeConsts,
includeAssocBindings
).orEmpty()
interface RsMethodOrPath : RsElement {
val typeArgumentList: RsTypeArgumentList?
}
| mit | 1279f3f8381a5e6b6051a4c59d7fe6c7 | 36.5 | 119 | 0.791667 | 4.081633 | false | false | false | false |
charleskorn/batect | app/src/main/kotlin/batect/ui/fancy/Utils.kt | 1 | 1313 | /*
Copyright 2017-2020 Charles Korn.
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 batect.ui.fancy
import batect.ui.text.Text
import batect.ui.text.TextRun
internal fun humanReadableList(list: Collection<Text>): TextRun {
return list.foldIndexed(TextRun()) { index, acc, current ->
val secondLastItem = index == list.size - 2
val beforeSecondLastItem = index < list.size - 2
val separator = when {
secondLastItem -> Text(" and ")
beforeSecondLastItem -> Text(", ")
else -> Text("")
}
acc + current + separator
}
}
internal fun pluralize(count: Int, singular: String, plural: String = singular + "s"): String =
if (count == 1) {
"$count $singular"
} else {
"$count $plural"
}
| apache-2.0 | bfaf40bf4f1d71c76c23173074b2fd9e | 30.261905 | 95 | 0.661081 | 4.347682 | false | false | false | false |
foreverigor/TumCampusApp | app/src/main/java/de/tum/in/tumcampusapp/service/WifiScanHandler.kt | 1 | 2172 | package de.tum.`in`.tumcampusapp.service
import android.content.Context
import android.net.wifi.WifiManager
import android.os.Handler
import de.tum.`in`.tumcampusapp.utils.Utils
import java.util.*
import java.util.concurrent.atomic.AtomicBoolean
/**
* This class is responsible for starting repeating wifi scans.
* Its next schedule will be called at random. The upper and lower bound
* for the next schedule are defined by MIN_ AND MAX_TIME_PASSED_IN_SECONDS.
* The generator then randomly picks a number in this range as input for postDelayed
*/
class WifiScanHandler : Handler() {
private var isRunning = AtomicBoolean(false)
private lateinit var wifiManager: WifiManager
private var wifiLock: WifiManager.WifiLock? = null
private val periodicalScan = Runnable {
wifiLock!!.acquire()
wifiManager.startScan()
Utils.log("WifiScanHandler started")
}
fun startRepetition(context: Context) {
if (!isRunning.compareAndSet(false, true)) {
return
}
wifiManager = context.applicationContext.getSystemService(Context.WIFI_SERVICE) as WifiManager
wifiLock = wifiManager.createWifiLock(WifiManager.WIFI_MODE_SCAN_ONLY, "WifiScanHandler")
val interval = generateRandomScanInterval(MIN_TIME_PASSED_IN_SECONDS, MAX_TIME_PASSED_IN_SECONDS - MIN_TIME_PASSED_IN_SECONDS)
postDelayed(periodicalScan, interval.toLong())
}
fun onScanFinished() {
wifiLock?.let {
if (it.isHeld) {
it.release()
}
}
}
companion object {
private val INSTANCE = WifiScanHandler()
//Big range advised, e.g. 10s to 420s (7min), since there's a possibility for battery drain
private const val MIN_TIME_PASSED_IN_SECONDS = 5
private const val MAX_TIME_PASSED_IN_SECONDS = 420
fun getInstance() = INSTANCE.apply {
removeCallbacksAndMessages(null)
}
private fun generateRandomScanInterval(minimumSeconds: Int, range: Int): Int {
val random = Random()
return 1000 * minimumSeconds + random.nextInt(range * 1000)
}
}
}
| gpl-3.0 | 31cb59b788782b5bb7d61d504f8d3225 | 32.9375 | 134 | 0.678637 | 4.432653 | false | false | false | false |
androidx/androidx | room/room-compiler-processing/src/main/java/androidx/room/compiler/processing/javac/JavacMethodParameter.kt | 3 | 2268 | /*
* Copyright (C) 2020 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.room.compiler.processing.javac
import androidx.room.compiler.processing.XExecutableParameterElement
import androidx.room.compiler.processing.XMemberContainer
import androidx.room.compiler.processing.javac.kotlin.KmType
import androidx.room.compiler.processing.javac.kotlin.KmValueParameter
import androidx.room.compiler.processing.util.sanitizeAsJavaParameterName
import javax.lang.model.element.VariableElement
internal class JavacMethodParameter(
env: JavacProcessingEnv,
override val enclosingElement: JavacExecutableElement,
element: VariableElement,
kotlinMetadataFactory: () -> KmValueParameter?,
val argIndex: Int
) : JavacVariableElement(env, element), XExecutableParameterElement {
private val kotlinMetadata by lazy { kotlinMetadataFactory() }
override val name: String
get() = (kotlinMetadata?.name ?: super.name).sanitizeAsJavaParameterName(
argIndex = argIndex
)
override val kotlinType: KmType?
get() = kotlinMetadata?.type
override val hasDefaultValue: Boolean
get() = kotlinMetadata?.hasDefault() ?: false
override val fallbackLocationText: String
get() = if (
enclosingElement is JavacMethodElement &&
enclosingElement.isSuspendFunction() &&
this === enclosingElement.parameters.last()
) {
"return type of ${enclosingElement.fallbackLocationText}"
} else {
"$name in ${enclosingElement.fallbackLocationText}"
}
override val closestMemberContainer: XMemberContainer by lazy {
enclosingElement.enclosingElement
}
}
| apache-2.0 | c7181ed699693dae1b5fb974f8aa88b6 | 36.180328 | 81 | 0.730159 | 4.866953 | false | false | false | false |
InfiniteSoul/ProxerAndroid | src/main/kotlin/me/proxer/app/chat/prv/sync/DirectReplyReceiver.kt | 1 | 2422 | package me.proxer.app.chat.prv.sync
import android.app.PendingIntent
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import androidx.core.app.RemoteInput
import io.reactivex.Completable
import io.reactivex.schedulers.Schedulers
import me.proxer.app.util.data.StorageHelper
import me.proxer.app.util.extension.getSafeCharSequence
import me.proxer.app.util.extension.safeInject
import me.proxer.app.util.extension.subscribeAndLogErrors
import org.koin.core.KoinComponent
/**
* @author Ruben Gees
*/
class DirectReplyReceiver : BroadcastReceiver(), KoinComponent {
companion object {
const val REMOTE_REPLY_EXTRA = "remote_reply"
private const val CONFERENCE_ID_EXTRA = "conference_id"
fun getPendingIntent(context: Context, conferenceId: Long): PendingIntent {
val intent = Intent(context, DirectReplyReceiver::class.java)
.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
.apply { putExtra(CONFERENCE_ID_EXTRA, conferenceId) }
return PendingIntent.getBroadcast(context, conferenceId.toInt(), intent, PendingIntent.FLAG_UPDATE_CURRENT)
}
}
private val messengerDao by safeInject<MessengerDao>()
private val storageHelper by safeInject<StorageHelper>()
override fun onReceive(context: Context, intent: Intent) {
val conferenceId = intent.getLongExtra(CONFERENCE_ID_EXTRA, -1)
Completable
.fromAction {
val safeUser = requireNotNull(storageHelper.user)
messengerDao.insertMessageToSend(safeUser, getMessageText(intent), conferenceId)
val unreadMap = messengerDao.getUnreadConferences()
.asSequence().associateWith {
messengerDao.getMostRecentMessagesForConference(it.id, it.unreadMessageAmount).asReversed()
}
.plus(messengerDao.getConference(conferenceId) to emptyList())
.toMap()
MessengerNotifications.showOrUpdate(context, unreadMap)
MessengerWorker.enqueueSynchronization()
}
.subscribeOn(Schedulers.io())
.subscribeAndLogErrors()
}
private fun getMessageText(intent: Intent) = RemoteInput.getResultsFromIntent(intent)
.getSafeCharSequence(REMOTE_REPLY_EXTRA)
.toString()
}
| gpl-3.0 | cc0f445e97d3e7c4b1094d7c085bff28 | 36.84375 | 119 | 0.692816 | 4.963115 | false | false | false | false |
handstandsam/ShoppingApp | mock-data/src/main/kotlin/com/handstandsam/shoppingapp/mockdata/ProduceMockAccount.kt | 1 | 3991 | package com.handstandsam.shoppingapp.mockdata
import com.handstandsam.shoppingapp.models.Category
import com.handstandsam.shoppingapp.models.Item
import com.handstandsam.shoppingapp.models.User
class ProduceMockAccount : MockAccount() {
internal val user: User = User("Sam", "Edwards")
internal val categories: MutableList<Category> = mutableListOf()
init {
val fruitCategory = Category("Fruits", IMAGE_BASE_URL + "fuji-apple.jpg")
val fruitItems = ArrayList<Item>()
fruitItems.add(Item("Granny Smith Apple", IMAGE_BASE_URL + "granny-smith-apple.jpg"))
fruitItems.add(Item("Gala Apple", IMAGE_BASE_URL + "gala-apple.jpg"))
fruitItems.add(Item("Pineapple", IMAGE_BASE_URL + "pineapple.jpg"))
fruitItems.add(Item("Red Delicious Apple", IMAGE_BASE_URL + "red-delicious-apple.jpg"))
fruitItems.add(Item("Fuji Apple", IMAGE_BASE_URL + "fuji-apple.jpg"))
fruitItems.add(Item("Lemon", IMAGE_BASE_URL + "lemons.jpg"))
fruitItems.add(Item("Grapefruit", IMAGE_BASE_URL + "grapefruit.jpg"))
fruitItems.add(Item("Lime", IMAGE_BASE_URL + "lime.jpg"))
fruitItems.add(Item("Orange", IMAGE_BASE_URL + "orange.jpg"))
itemsByCategory[fruitCategory.label] = fruitItems
val floralCategory =
Category("Floral", IMAGE_BASE_URL + "white-rose.jpg")
val floralItems = ArrayList<Item>()
floralItems.add(Item("White Rose", IMAGE_BASE_URL + "white-rose.jpg"))
floralItems.add(Item("Sunflower", IMAGE_BASE_URL + "sunflower.jpg"))
itemsByCategory[floralCategory.label] = floralItems
val seafoodCategory =
Category("Seafood", IMAGE_BASE_URL + "shrimp.jpg")
val seafoodItems = ArrayList<Item>()
seafoodItems.add(Item("Lobster Tail", IMAGE_BASE_URL + "lobster-tail.jpg"))
seafoodItems.add(Item("Shrimp", IMAGE_BASE_URL + "shrimp.jpg"))
seafoodItems.add(Item("Scallop", IMAGE_BASE_URL + "scallops.jpg"))
itemsByCategory[seafoodCategory.label] = seafoodItems
val vegetableCategory =
Category("Vegetables", IMAGE_BASE_URL + "kale.jpg")
val vegetableItems = ArrayList<Item>()
vegetableItems.add(Item("Carrot", IMAGE_BASE_URL + "carrots.jpg"))
vegetableItems.add(Item("Cucumber", IMAGE_BASE_URL + "cucumber.jpg"))
vegetableItems.add(Item("Kale", IMAGE_BASE_URL + "kale.jpg"))
vegetableItems.add(Item("Romaine Lettuce", IMAGE_BASE_URL + "romaine-lettuce.jpg"))
vegetableItems.add(Item("Artichoke", IMAGE_BASE_URL + "artichoke.jpg"))
vegetableItems.add(Item("Beet", IMAGE_BASE_URL + "beet.jpg"))
vegetableItems.add(Item("Radish", IMAGE_BASE_URL + "radish.jpg"))
vegetableItems.add(Item("Tomato", IMAGE_BASE_URL + "tomato.jpg"))
vegetableItems.add(Item("Broccoli", IMAGE_BASE_URL + "broccoli.jpg"))
vegetableItems.add(Item("Avocado", IMAGE_BASE_URL + "avocado.jpg"))
vegetableItems.add(Item("Red Bell Pepper", IMAGE_BASE_URL + "red-bell-pepper.jpg"))
vegetableItems.add(Item("Orange Bell Pepper", IMAGE_BASE_URL + "orange-bell-pepper.jpg"))
vegetableItems.add(Item("Yellow Bell Pepper", IMAGE_BASE_URL + "yellow-bell-pepper.jpg"))
itemsByCategory[vegetableCategory.label] = vegetableItems
categories.addAll(
listOf(
fruitCategory,
vegetableCategory,
seafoodCategory,
floralCategory
)
)
}
override fun getUsername(): String {
return "produce"
}
override fun getUser(): User {
return user
}
override fun getCategories(): List<Category> {
return categories
}
override fun getItemsForCategory(categoryLabel: String): List<Item>? {
return itemsByCategory[categoryLabel]
}
companion object {
val IMAGE_BASE_URL = "https://s3.amazonaws.com/shopping-app/produce/images/"
}
}
| apache-2.0 | a8c3941a7981786be623c619a2a1dccb | 42.380435 | 97 | 0.650714 | 3.479512 | false | false | false | false |
kenrube/Fantlab-client | app/src/main/kotlin/ru/fantlab/android/data/dao/model/SearchWork.kt | 2 | 3316 | package ru.fantlab.android.data.dao.model
import android.os.Parcelable
import androidx.annotation.Keep
import com.google.gson.annotations.SerializedName
import kotlinx.android.parcel.Parcelize
@Parcelize
@Keep
data class SearchWork(
@SerializedName("all_autor_name")
val allAutorName: String = "",
@SerializedName("all_autor_rusname")
val allAutorRusname: String = "",
@SerializedName("altname")
val altname: String = "",
@SerializedName("autor1_id")
val autor1Id: Int = 0,
@SerializedName("autor1_is_opened")
val autor1IsOpened: Int = 0,
@SerializedName("autor1_rusname")
val autor1Rusname: String = "",
@SerializedName("autor2_id")
val autor2Id: Int = 0,
@SerializedName("autor2_is_opened")
val autor2IsOpened: Int = 0,
@SerializedName("autor2_rusname")
val autor2Rusname: String = "",
@SerializedName("autor3_id")
val autor3Id: Int = 0,
@SerializedName("autor3_is_opened")
val autor3IsOpened: Int = 0,
@SerializedName("autor3_rusname")
val autor3Rusname: String = "",
@SerializedName("autor4_id")
val autor4Id: Int = 0,
@SerializedName("autor4_is_opened")
val autor4IsOpened: Int = 0,
@SerializedName("autor4_rusname")
val autor4Rusname: String = "",
@SerializedName("autor5_id")
val autor5Id: Int = 0,
@SerializedName("autor5_is_opened")
val autor5IsOpened: Int = 0,
@SerializedName("autor5_rusname")
val autor5Rusname: String = "",
@SerializedName("autor_id")
val autorId: Int = 0,
@SerializedName("autor_is_opened")
val autorIsOpened: Int = 0,
@SerializedName("autor_rusname")
val autorRusname: String = "",
@SerializedName("doc")
val doc: Int = 0,
@SerializedName("fullname")
val fullname: String = "",
@SerializedName("keywords")
val keywords: String = "",
@SerializedName("level")
val level: Int = 0,
@SerializedName("markcount")
val markcount: Int = 0,
@SerializedName("midmark")
val midmark: List<Double> = listOf(),
@SerializedName("name")
val name: String = "",
@SerializedName("name_eng")
val nameEng: String = "",
@SerializedName("name_show_im")
val nameShowIm: String = "",
@SerializedName("nearest_parent_work_id")
val nearestParentWorkId: Int = 0,
@SerializedName("parent_work_id")
val parentWorkId: Int = 0,
@SerializedName("parent_work_id_present")
val parentWorkIdPresent: Int = 0,
@SerializedName("pic_edition_id")
val picEditionId: Int = 0,
@SerializedName("pic_edition_id_auto")
val picEditionIdAuto: Int = 0,
@SerializedName("rating")
val rating: List<Double> = listOf(),
@SerializedName("rusname")
val rusname: String = "",
@SerializedName("weight")
val weight: Int = 0,
@SerializedName("work_id")
val workId: Int = 0,
@SerializedName("work_type_id")
val workTypeId: Int = 0,
@SerializedName("year")
val year: Int = 0
) : Parcelable | gpl-3.0 | 144dccf1e3d6b03f70a0476fa003fb0d | 34.666667 | 49 | 0.591677 | 4.150188 | false | false | false | false |
tasomaniac/OpenLinkWith | base/src/main/kotlin/com/tasomaniac/openwith/HeaderAdapter.kt | 1 | 2775 | package com.tasomaniac.openwith
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
open class HeaderAdapter<in T : RecyclerView.ViewHolder, H : RecyclerView.ViewHolder> @JvmOverloads constructor(
private val innerAdapter: RecyclerView.Adapter<T>,
private val createHeaderViewHolder: (parent: ViewGroup) -> H,
private val bindHeader: H.() -> Unit = {}
) : RecyclerView.Adapter<RecyclerView.ViewHolder>() {
init {
innerAdapter.registerAdapterDataObserver(ForwardingDataObserver())
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
return when (viewType) {
TYPE_HEADER -> createHeaderViewHolder(parent)
else -> innerAdapter.onCreateViewHolder(parent, viewType)
}
}
override fun onBindViewHolder(viewHolder: RecyclerView.ViewHolder, position: Int) =
throw UnsupportedOperationException()
@Suppress("UNCHECKED_CAST")
override fun onBindViewHolder(
holder: RecyclerView.ViewHolder,
position: Int,
payloads: List<Any>
) {
when (getItemViewType(position)) {
TYPE_HEADER -> (holder as H).bindHeader()
else -> innerAdapter.onBindViewHolder(holder as T, position - HEADER_COUNT, payloads)
}
}
override fun getItemCount() = innerAdapter.itemCount + HEADER_COUNT
override fun getItemViewType(position: Int) =
if (position < HEADER_COUNT) {
TYPE_HEADER
} else {
innerAdapter.getItemViewType(position - HEADER_COUNT)
}
private inner class ForwardingDataObserver : RecyclerView.AdapterDataObserver() {
override fun onChanged() {
notifyDataSetChanged()
}
override fun onItemRangeChanged(positionStart: Int, itemCount: Int) {
notifyItemRangeChanged(positionStart + 1, itemCount)
}
override fun onItemRangeChanged(positionStart: Int, itemCount: Int, payload: Any?) {
notifyItemRangeChanged(positionStart + 1, itemCount, payload)
}
override fun onItemRangeInserted(positionStart: Int, itemCount: Int) {
notifyItemRangeInserted(positionStart + 1, itemCount)
}
override fun onItemRangeRemoved(positionStart: Int, itemCount: Int) {
notifyItemRangeRemoved(positionStart + 1, itemCount)
}
override fun onItemRangeMoved(fromPosition: Int, toPosition: Int, itemCount: Int) {
if (itemCount == 1) {
notifyItemMoved(fromPosition + 1, toPosition + 1)
}
}
}
companion object {
private const val TYPE_HEADER = Integer.MAX_VALUE
private const val HEADER_COUNT = 1
}
}
| apache-2.0 | 399d47acbcb98d50d4cc59d7bc498313 | 33.6875 | 112 | 0.660541 | 5.377907 | false | false | false | false |
westnordost/StreetComplete | app/src/main/java/de/westnordost/streetcomplete/map/PointerPinView.kt | 1 | 6038 | package de.westnordost.streetcomplete.map
import android.content.Context
import android.graphics.Bitmap
import android.graphics.Canvas
import android.graphics.Outline
import android.graphics.Paint
import android.graphics.drawable.Drawable
import android.os.Build
import android.util.AttributeSet
import android.view.View
import android.view.View.MeasureSpec.getMode
import android.view.View.MeasureSpec.getSize
import android.view.ViewOutlineProvider
import androidx.core.content.withStyledAttributes
import androidx.core.graphics.withRotation
import de.westnordost.streetcomplete.R
import de.westnordost.streetcomplete.ktx.toPx
import kotlin.math.*
/** A view for the pointer pin that ought to be displayed at the edge of the screen.
* Can be rotated with the pinRotation field. As opposed to normal rotation, it ensures that the
* pin icon always stays upright */
class PointerPinView @JvmOverloads constructor(
context: Context,
attrs: AttributeSet? = null,
defStyleAttr: Int = 0
) : View(context, attrs, defStyleAttr) {
private val pointerPin: Drawable = context.resources.getDrawable(R.drawable.quest_pin_pointer)
private var pointerPinBitmap: Bitmap? = null
private val antiAliasPaint: Paint = Paint().apply {
isAntiAlias = true
isFilterBitmap = true
}
/** rotation of the pin in degrees. Similar to rotation, only that the pointy end of the pin
* is always located at the edge of the view */
var pinRotation: Float = 0f
set(value) {
field = value
invalidate()
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
invalidateOutline()
}
}
var pinIconDrawable: Drawable? = null
set(value) {
field = value
invalidate()
}
fun setPinIconResource(resId: Int) {
pinIconDrawable = context.resources.getDrawable(resId)
}
init {
context.withStyledAttributes(attrs, R.styleable.PointerPinView) {
pinRotation = getFloat(R.styleable.PointerPinView_pinRotation, 0f)
val resId = getResourceId(R.styleable.PointerPinView_iconSrc, 0)
if (resId != 0)
setPinIconResource(resId)
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
outlineProvider = object : ViewOutlineProvider() {
override fun getOutline(view: View, outline: Outline) {
val size = min(width, height)
val pinCircleSize = (size * (1 - PIN_CENTER_OFFSET_FRACTION*2)).toInt()
val arrowOffset = size * PIN_CENTER_OFFSET_FRACTION
val a = pinRotation.toDouble().normalizeAngle().toRadians()
val x = (-sin(a) * arrowOffset).toInt()
val y = (+cos(a) * arrowOffset).toInt()
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
outline.setOval(
width/2 - pinCircleSize/2 + x,
height/2 - pinCircleSize/2 + y,
width/2 + pinCircleSize/2 + x,
height/2 + pinCircleSize/2 + y)
}
}
}
}
}
override fun invalidateDrawable(drawable: Drawable) {
super.invalidateDrawable(drawable)
if (drawable == pinIconDrawable) {
invalidate()
}
}
override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
val desiredSize = DEFAULT_SIZE.toPx(context).toInt()
val width = reconcileSize(desiredSize, widthMeasureSpec)
val height = reconcileSize(desiredSize, heightMeasureSpec)
setMeasuredDimension(width, height)
}
override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
pointerPinBitmap?.recycle()
val size = min(width, height)
val bmp = Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888)
val canvas = Canvas(bmp)
pointerPin.setBounds(0,0, size, size)
pointerPin.draw(canvas)
pointerPinBitmap = bmp
}
override fun onDraw(canvas: Canvas?) {
val c = canvas ?: return
val size = min(width, height)
val r = pinRotation
c.withRotation(r, width/2f, height/2f) {
pointerPinBitmap?.let { canvas.drawBitmap(it, 0f, 0f, antiAliasPaint) }
}
val icon = pinIconDrawable
if (icon != null) {
val iconSize = (size * ICON_SIZE_FRACTION).toInt()
val arrowOffset = size * PIN_CENTER_OFFSET_FRACTION
val a = r.toDouble().normalizeAngle().toRadians()
val x = (-sin(a) * arrowOffset).toInt()
val y = (+cos(a) * arrowOffset).toInt()
icon.setBounds(
width/2 - iconSize/2 + x,
height/2 - iconSize/2 + y,
width/2 + iconSize/2 + x,
height/2 + iconSize/2 + y)
icon.draw(c)
}
}
private fun reconcileSize(contentSize: Int, measureSpec: Int): Int {
val mode = getMode(measureSpec)
val size = getSize(measureSpec)
return when (mode) {
MeasureSpec.EXACTLY -> size
MeasureSpec.AT_MOST -> min(contentSize, size)
else -> contentSize
}
}
companion object {
// half size of the sharp end of pin, depends on the pin drawable: using quest_pin_pointer
private const val PIN_CENTER_OFFSET_FRACTION = 14f / 124f
// size of the icon part of the pin, depends on the pin drawable: using quest_pin_pointer
private const val ICON_SIZE_FRACTION = 84f / 124f
// intrinsic/default size
private const val DEFAULT_SIZE = 64f // in dp
}
}
private fun Double.toRadians(): Double = this / 180.0 * PI
private fun Double.normalizeAngle(): Double {
var r = this % 360 // r is -360..360
r = (r + 360) % 360 // r is 0..360
return r
}
| gpl-3.0 | 49a3e5945134bc85f31725f7f0c9d3c0 | 35.817073 | 98 | 0.608811 | 4.340762 | false | false | false | false |
SirLYC/Android-Gank-Share | app/src/main/java/com/lyc/gank/discover/DiscoverFragment.kt | 1 | 4521 | package com.lyc.gank.discover
import android.arch.lifecycle.Observer
import android.content.Intent
import android.os.Bundle
import android.support.v7.widget.DividerItemDecoration
import android.support.v7.widget.LinearLayoutManager
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.ViewGroup.LayoutParams.WRAP_CONTENT
import android.view.ViewStub
import android.widget.ImageView
import android.widget.LinearLayout
import com.lyc.data.resp.GankItem
import com.lyc.gank.GankWithImgViewBinder
import com.lyc.gank.GankWithoutImgViewBinder
import com.lyc.gank.OnGankItemClickListener
import com.lyc.gank.R
import com.lyc.gank.article.ArticleActivity
import com.lyc.gank.base.BaseFragment
import com.lyc.gank.category.GirlItemViewBinder
import com.lyc.gank.photo.PhotoActivity
import com.lyc.gank.search.SearchActivity
import com.lyc.gank.utils.*
import com.lyc.gank.widget.LoadRetryView
import kotlinx.android.synthetic.main.fragment_discover.*
/**
* Created by Liu Yuchuan on 2018/2/24.
*/
class DiscoverFragment : BaseFragment(), View.OnClickListener, LoadRetryView.OnRetryClickListener, OnGankItemClickListener, LoadRetryView.OnInflateListener {
override fun onRetryViewInflate(stub: ViewStub, inflated: View) {
}
override fun onLoadViewInflate(stub: ViewStub, inflated: View) {
val param = inflated.layoutParams
param.width = WRAP_CONTENT
param.height = WRAP_CONTENT
inflated.layoutParams = param
}
private lateinit var discoverViewModel: DiscoverViewModel
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
discoverViewModel = provideViewModel()
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
return inflater.inflate(R.layout.fragment_discover, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
tv_search.setOnClickListener(this)
tv_refresh.setOnClickListener(this)
lrv_discover.onRetryClickListener = this
lrv_discover.setOnInflateListener(this)
rv_discover.layoutManager = LinearLayoutManager(activity)
rv_discover.addItemDecoration(DividerItemDecoration(activity, LinearLayout.VERTICAL))
rv_discover.adapter = ReactiveAdapter(discoverViewModel.discoverList).apply {
register(GankItem::class.java)
.to(GankWithImgViewBinder(this@DiscoverFragment),
GankWithoutImgViewBinder(this@DiscoverFragment),
GirlItemViewBinder(this@DiscoverFragment))
.withClassLinker { _, t ->
return@withClassLinker when {
t.type == "福利" -> GirlItemViewBinder::class.java
t.imgUrl != null -> GankWithImgViewBinder::class.java
else -> GankWithoutImgViewBinder::class.java
}
}
observe(this@DiscoverFragment)
}
discoverViewModel.refreshState.observe(this, Observer { state ->
when (state) {
is RefreshState.Refreshing -> lrv_discover.showLoadView()
is RefreshState.Error -> lrv_discover.showRetryView()
else -> lrv_discover.hideAll()
}
tv_refresh.isEnabled = state !is RefreshState.Refreshing
if (state === RefreshState.Empty) {
discoverViewModel.refresh()
}
})
discoverViewModel.refreshEvent.observe(this, Observer { event ->
if (event is RefreshState.Error) {
toast(event.msg)
}
})
}
override fun onClick(v: View) {
when (v.id) {
R.id.tv_search -> startActivity(Intent(activity(), SearchActivity::class.java))
R.id.tv_refresh -> {
loge("refresh","refresh")
discoverViewModel.refresh()
}
}
}
override fun onRetryClicked(v: View) {
discoverViewModel.refresh()
}
override fun onGirlItemClick(iv: ImageView, item: GankItem) {
PhotoActivity.start(activity!!, item)
}
override fun onArticleItemClick(item: GankItem) {
ArticleActivity.start(activity!!, item)
}
override fun onVideoItemClick(item: GankItem) {
openWebPage(item.url)
}
}
| apache-2.0 | a5a22edfb85e93872f8b061838c15701 | 35.136 | 157 | 0.667257 | 4.661507 | false | false | false | false |
square/wire | wire-library/wire-tests/src/commonTest/kotlin/com/squareup/wire/Asserts.kt | 1 | 1791 | /*
* Copyright 2019 Square Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.squareup.wire
import kotlin.math.abs
import kotlin.test.fail
fun assertFloatEquals(expected: Float, actual: Float, delta: Float = 0.01f) {
require(delta >= 0) { "delta can't be negative, was $delta." }
val diff = abs(expected - actual)
if (diff > delta) {
fail(
"Expected difference between <$expected> and <$actual> to not be greater than <$delta>," +
" but was <$diff>."
)
}
}
fun assertArrayEquals(expected: ByteArray, actual: ByteArray) {
if (expected === actual) return
if (actual.size != expected.size) {
fail("Expected array of length <${expected.size}> but was <${actual.size}>.")
}
for (i in expected.indices) {
if (actual[i] != expected[i]) {
fail("Expected element at position <$i> to be <${expected[i]}> but was <${actual[i]}>.")
}
}
}
fun assertArrayNotEquals(expected: ByteArray, actual: ByteArray) {
if (expected === actual) {
fail("Expected $actual to not be equal to $expected.")
}
if (actual.size != expected.size) return
for (i in expected.indices) {
if (actual[i] != expected[i]) return
}
fail("Expected ${actual.contentToString()} to not be equal to ${expected.contentToString()}.")
}
| apache-2.0 | e2a67a6dee54558b6fdc563a2680d2a8 | 32.792453 | 96 | 0.677275 | 3.762605 | false | false | false | false |
zzorn/mechaflow | src/main/kotlin/org/mechaflow2/standard/StandardMachineBase.kt | 1 | 1690 | package org.mechaflow2.standard
import org.mechaflow2.MachineBase
import org.mechaflow2.PortDirection
import org.mechaflow2.PortSize
import org.mechaflow2.standard.ports.SignalPort
import org.mechaflow2.standard.ports.SignalRange
/**
*
*/
abstract class StandardMachineBase : MachineBase() {
protected fun inputSignal(name: String,
desc: String? = null,
range: SignalRange = SignalRange.UNLIMITED,
size: PortSize = PortSize.MEDIUM): SignalPort =
inputSignal(name, 0.0, desc, range, size)
protected fun inputSignal(name: String,
defaultValue: Double = 0.0,
desc: String? = null,
range: SignalRange = SignalRange.UNLIMITED,
size: PortSize = PortSize.MEDIUM): SignalPort =
SignalPort(name, PortDirection.IN, defaultValue, range, desc, size)
protected fun outputSignal(name: String,
desc: String? = null,
range: SignalRange = SignalRange.UNLIMITED,
size: PortSize = PortSize.MEDIUM): SignalPort =
outputSignal(name, 0.0, desc, range, size)
protected fun outputSignal(name: String,
defaultValue: Double = 0.0,
desc: String? = null,
range: SignalRange = SignalRange.UNLIMITED,
size: PortSize = PortSize.MEDIUM): SignalPort =
SignalPort(name, PortDirection.OUT, defaultValue, range, desc, size)
} | gpl-3.0 | 8c0371079e7664ef6697cfb30fa00b42 | 40.243902 | 80 | 0.552071 | 4.694444 | false | false | false | false |
ingokegel/intellij-community | platform/core-impl/src/com/intellij/ide/plugins/IdeaPluginDescriptorImpl.kt | 1 | 21432 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
@file:Suppress("ReplaceGetOrSet", "ReplaceNegatedIsEmptyWithIsNotEmpty", "OVERRIDE_DEPRECATION")
package com.intellij.ide.plugins
import com.intellij.AbstractBundle
import com.intellij.DynamicBundle
import com.intellij.core.CoreBundle
import com.intellij.idea.AppMode
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.extensions.ExtensionDescriptor
import com.intellij.openapi.extensions.PluginId
import com.intellij.openapi.extensions.impl.ExtensionPointImpl
import org.jetbrains.annotations.ApiStatus
import org.jetbrains.annotations.NonNls
import org.jetbrains.annotations.PropertyKey
import org.jetbrains.annotations.VisibleForTesting
import java.io.File
import java.io.IOException
import java.nio.file.Path
import java.time.ZoneOffset
import java.util.*
private val LOG: Logger
get() = PluginManagerCore.getLogger()
fun Collection<String>.toPluginIds(): Set<PluginId> = PluginManagerCore.toPluginIds(this)
fun Iterable<IdeaPluginDescriptor>.toPluginIdSet(): Set<PluginId> = mapTo(LinkedHashSet()) { it.pluginId }
fun Iterable<PluginId>.toPluginDescriptors(): List<IdeaPluginDescriptorImpl> {
val pluginIdMap = PluginManagerCore.buildPluginIdMap()
return mapNotNull { pluginIdMap[it] }
}
internal fun Iterable<PluginId>.joinedPluginIds(operation: String): String {
return joinToString(
prefix = "Plugins to $operation: [",
postfix = "]",
) { it.idString }
}
@ApiStatus.Internal
class IdeaPluginDescriptorImpl(raw: RawPluginDescriptor,
@JvmField val path: Path,
private val isBundled: Boolean,
id: PluginId?,
@JvmField val moduleName: String?,
@JvmField val useCoreClassLoader: Boolean = false) : IdeaPluginDescriptor {
private val id: PluginId = id ?: PluginId.getId(raw.id ?: raw.name ?: throw RuntimeException("Neither id nor name are specified"))
private val name = raw.name ?: id?.idString ?: raw.id
@Suppress("EnumEntryName")
enum class OS {
mac, linux, windows, unix, freebsd
}
// only for sub descriptors
@JvmField internal var descriptorPath: String? = null
@Volatile private var description: String? = null
private val productCode = raw.productCode
private var releaseDate: Date? = raw.releaseDate?.let { Date.from(it.atStartOfDay(ZoneOffset.UTC).toInstant()) }
private val releaseVersion = raw.releaseVersion
private val isLicenseOptional = raw.isLicenseOptional
@NonNls private var resourceBundleBaseName: String? = null
private val changeNotes = raw.changeNotes
private var version: String? = raw.version
private var vendor = raw.vendor
private val vendorEmail = raw.vendorEmail
private val vendorUrl = raw.vendorUrl
private var category: String? = raw.category
@JvmField internal val url = raw.url
@JvmField val pluginDependencies: List<PluginDependency>
@JvmField val incompatibilities: List<PluginId> = raw.incompatibilities ?: Collections.emptyList()
init {
// https://youtrack.jetbrains.com/issue/IDEA-206274
val list = raw.depends
if (list != null) {
val iterator = list.iterator()
while (iterator.hasNext()) {
val item = iterator.next()
if (!item.isOptional) {
for (a in list) {
if (a.isOptional && a.pluginId == item.pluginId) {
a.isOptional = false
iterator.remove()
break
}
}
}
}
}
pluginDependencies = list ?: Collections.emptyList()
}
companion object {
@VisibleForTesting
const val ON_DEMAND_ENABLED_KEY = "idea.on.demand.plugins"
val isOnDemandEnabled
@ApiStatus.Experimental get() = java.lang.Boolean.getBoolean(ON_DEMAND_ENABLED_KEY)
}
@Transient @JvmField var jarFiles: List<Path>? = null
private var _pluginClassLoader: ClassLoader? = null
@JvmField val actions: List<RawPluginDescriptor.ActionDescriptor> = raw.actions ?: Collections.emptyList()
// extension point name -> list of extension descriptors
val epNameToExtensions: Map<String, MutableList<ExtensionDescriptor>>? = raw.epNameToExtensions
@JvmField val appContainerDescriptor = raw.appContainerDescriptor
@JvmField val projectContainerDescriptor = raw.projectContainerDescriptor
@JvmField val moduleContainerDescriptor = raw.moduleContainerDescriptor
@JvmField val content: PluginContentDescriptor = raw.contentModules?.let { PluginContentDescriptor(it) } ?: PluginContentDescriptor.EMPTY
@JvmField val dependencies = raw.dependencies
@JvmField val modules: List<PluginId> = raw.modules ?: Collections.emptyList()
private val descriptionChildText = raw.description
@JvmField val isUseIdeaClassLoader = raw.isUseIdeaClassLoader
@JvmField val isBundledUpdateAllowed = raw.isBundledUpdateAllowed
@JvmField internal val implementationDetail = raw.implementationDetail
@ApiStatus.Experimental @JvmField internal val onDemand = isOnDemandEnabled && raw.onDemand
@JvmField internal val isRestartRequired = raw.isRestartRequired
@JvmField val packagePrefix = raw.`package`
private val sinceBuild = raw.sinceBuild
private val untilBuild = raw.untilBuild
private var isEnabled = true
var isDeleted = false
@JvmField internal var isIncomplete: PluginLoadingError? = null
override fun getDescriptorPath() = descriptorPath
override fun getDependencies(): List<IdeaPluginDependency> {
return if (pluginDependencies.isEmpty()) Collections.emptyList() else Collections.unmodifiableList(pluginDependencies)
}
override fun getPluginPath() = path
private fun createSub(raw: RawPluginDescriptor,
descriptorPath: String,
pathResolver: PathResolver,
context: DescriptorListLoadingContext,
dataLoader: DataLoader,
moduleName: String?): IdeaPluginDescriptorImpl {
raw.name = name
val result = IdeaPluginDescriptorImpl(raw, path = path, isBundled = isBundled, id = id, moduleName = moduleName,
useCoreClassLoader = useCoreClassLoader)
result.descriptorPath = descriptorPath
result.vendor = vendor
result.version = version
result.resourceBundleBaseName = resourceBundleBaseName
result.readExternal(raw = raw, pathResolver = pathResolver, context = context, isSub = true, dataLoader = dataLoader)
return result
}
fun readExternal(raw: RawPluginDescriptor,
pathResolver: PathResolver,
context: DescriptorListLoadingContext,
isSub: Boolean,
dataLoader: DataLoader) {
// include module file descriptor if not specified as `depends` (old way - xi:include)
// must be first because merged into raw descriptor
if (!isSub) {
for (module in content.modules) {
val subDescriptorFile = module.configFile ?: "${module.name}.xml"
val subDescriptor = createSub(raw = pathResolver.resolveModuleFile(readContext = context,
dataLoader = dataLoader,
path = subDescriptorFile,
readInto = null),
descriptorPath = subDescriptorFile,
pathResolver = pathResolver,
context = context,
dataLoader = dataLoader,
moduleName = module.name)
module.descriptor = subDescriptor
}
}
if (raw.resourceBundleBaseName != null) {
if (id == PluginManagerCore.CORE_ID && !isSub) {
LOG.warn("<resource-bundle>${raw.resourceBundleBaseName}</resource-bundle> tag is found in an xml descriptor" +
" included into the platform part of the IDE but the platform part uses predefined bundles " +
"(e.g. ActionsBundle for actions) anyway; this tag must be replaced by a corresponding attribute in some inner tags " +
"(e.g. by 'resource-bundle' attribute in 'actions' tag)")
}
if (resourceBundleBaseName != null && resourceBundleBaseName != raw.resourceBundleBaseName) {
LOG.warn("Resource bundle redefinition for plugin $id. " +
"Old value: $resourceBundleBaseName, new value: ${raw.resourceBundleBaseName}")
}
resourceBundleBaseName = raw.resourceBundleBaseName
}
if (version == null) {
version = context.defaultVersion
}
if (!isSub) {
if (context.isPluginDisabled(id)) {
markAsIncomplete(disabledDependency = null, shortMessage = null)
}
else {
checkCompatibility(context)
if (isIncomplete != null) {
return
}
for (pluginDependency in dependencies.plugins) {
if (context.isPluginDisabled(pluginDependency.id)) {
markAsIncomplete(pluginDependency.id, shortMessage = "plugin.loading.error.short.depends.on.disabled.plugin")
}
}
}
}
if (isIncomplete == null && moduleName == null) {
processOldDependencies(descriptor = this,
context = context,
pathResolver = pathResolver,
dependencies = pluginDependencies,
dataLoader = dataLoader)
}
}
private fun processOldDependencies(descriptor: IdeaPluginDescriptorImpl,
context: DescriptorListLoadingContext,
pathResolver: PathResolver,
dependencies: List<PluginDependency>,
dataLoader: DataLoader) {
var visitedFiles: MutableList<String>? = null
for (dependency in dependencies) {
// context.isPluginIncomplete must be not checked here as another version of plugin maybe supplied later from another source
if (context.isPluginDisabled(dependency.pluginId)) {
if (!dependency.isOptional && isIncomplete == null) {
markAsIncomplete(dependency.pluginId, "plugin.loading.error.short.depends.on.disabled.plugin")
}
}
// because of https://youtrack.jetbrains.com/issue/IDEA-206274, configFile maybe not only for optional dependencies
val configFile = dependency.configFile ?: continue
if (pathResolver.isFlat && context.checkOptionalConfigShortName(configFile, descriptor)) {
continue
}
var resolveError: Exception? = null
val raw: RawPluginDescriptor? = try {
pathResolver.resolvePath(readContext = context, dataLoader = dataLoader, relativePath = configFile, readInto = null)
}
catch (e: IOException) {
resolveError = e
null
}
if (raw == null) {
val message = "Plugin $descriptor misses optional descriptor $configFile"
if (context.isMissingSubDescriptorIgnored) {
LOG.info(message)
if (resolveError != null) {
LOG.debug(resolveError)
}
}
else {
throw RuntimeException(message, resolveError)
}
continue
}
if (visitedFiles == null) {
visitedFiles = context.visitedFiles
}
checkCycle(descriptor, configFile, visitedFiles)
visitedFiles.add(configFile)
val subDescriptor = descriptor.createSub(raw = raw,
descriptorPath = configFile,
pathResolver = pathResolver,
context = context,
dataLoader = dataLoader,
moduleName = null)
dependency.subDescriptor = subDescriptor
visitedFiles.clear()
}
}
private fun checkCompatibility(context: DescriptorListLoadingContext) {
if (isBundled) {
return
}
fun markAsIncompatible(error: PluginLoadingError) {
if (isIncomplete != null) {
return
}
isIncomplete = error
isEnabled = false
}
if (AppMode.isDisableNonBundledPlugins()) {
markAsIncompatible(PluginLoadingError(
plugin = this,
detailedMessageSupplier = { CoreBundle.message("plugin.loading.error.long.custom.plugin.loading.disabled", getName()) },
shortMessageSupplier = { CoreBundle.message("plugin.loading.error.short.custom.plugin.loading.disabled") },
isNotifyUser = false
))
return
}
PluginManagerCore.checkBuildNumberCompatibility(this, context.productBuildNumber())?.let {
markAsIncompatible(it)
return
}
// "Show broken plugins in Settings | Plugins so that users can uninstall them and resolve "Plugin Error" (IDEA-232675)"
if (context.isBroken(this)) {
markAsIncompatible(PluginLoadingError(
plugin = this,
detailedMessageSupplier = { CoreBundle.message("plugin.loading.error.long.marked.as.broken", name, version) },
shortMessageSupplier = { CoreBundle.message("plugin.loading.error.short.marked.as.broken") }
))
}
}
private fun markAsIncomplete(disabledDependency: PluginId?,
@PropertyKey(resourceBundle = CoreBundle.BUNDLE) shortMessage: String?,
pluginId: PluginId? = disabledDependency) {
if (isIncomplete != null) {
return
}
if (shortMessage == null) {
isIncomplete = PluginLoadingError(plugin = this, detailedMessageSupplier = null, shortMessageSupplier = PluginLoadingError.DISABLED)
}
else {
isIncomplete = PluginLoadingError(plugin = this,
detailedMessageSupplier = null,
shortMessageSupplier = { CoreBundle.message(shortMessage, pluginId!!) },
isNotifyUser = false,
disabledDependency = disabledDependency)
}
isEnabled = false
}
@ApiStatus.Internal
fun registerExtensions(nameToPoint: Map<String, ExtensionPointImpl<*>>,
containerDescriptor: ContainerDescriptor,
listenerCallbacks: MutableList<in Runnable>?) {
containerDescriptor.extensions?.let {
if (!it.isEmpty()) {
@Suppress("JavaMapForEach")
it.forEach { name, list ->
nameToPoint.get(name)?.registerExtensions(list, this, listenerCallbacks)
}
}
return
}
val unsortedMap = epNameToExtensions ?: return
// app container: in most cases will be only app-level extensions - to reduce map copying, assume that all extensions are app-level and then filter out
// project container: rest of extensions wil be mostly project level
// module container: just use rest, area will not register unrelated extension anyway as no registered point
if (containerDescriptor == appContainerDescriptor) {
val registeredCount = doRegisterExtensions(unsortedMap, nameToPoint, listenerCallbacks)
containerDescriptor.distinctExtensionPointCount = registeredCount
if (registeredCount == unsortedMap.size) {
projectContainerDescriptor.extensions = Collections.emptyMap()
moduleContainerDescriptor.extensions = Collections.emptyMap()
}
}
else if (containerDescriptor == projectContainerDescriptor) {
val registeredCount = doRegisterExtensions(unsortedMap, nameToPoint, listenerCallbacks)
containerDescriptor.distinctExtensionPointCount = registeredCount
if (registeredCount == unsortedMap.size) {
containerDescriptor.extensions = unsortedMap
moduleContainerDescriptor.extensions = Collections.emptyMap()
}
else if (registeredCount == (unsortedMap.size - appContainerDescriptor.distinctExtensionPointCount)) {
moduleContainerDescriptor.extensions = Collections.emptyMap()
}
}
else {
val registeredCount = doRegisterExtensions(unsortedMap, nameToPoint, listenerCallbacks)
if (registeredCount == 0) {
moduleContainerDescriptor.extensions = Collections.emptyMap()
}
}
}
private fun doRegisterExtensions(unsortedMap: Map<String, MutableList<ExtensionDescriptor>>,
nameToPoint: Map<String, ExtensionPointImpl<*>>,
listenerCallbacks: MutableList<in Runnable>?): Int {
var registeredCount = 0
for (entry in unsortedMap) {
val point = nameToPoint.get(entry.key) ?: continue
point.registerExtensions(entry.value, this, listenerCallbacks)
registeredCount++
}
return registeredCount
}
@Suppress("HardCodedStringLiteral")
override fun getDescription(): String? {
var result = description
if (result != null) {
return result
}
result = (resourceBundleBaseName?.let { baseName ->
try {
AbstractBundle.messageOrDefault(
DynamicBundle.getResourceBundle(classLoader, baseName),
"plugin.$id.description",
descriptionChildText ?: "",
)
}
catch (_: MissingResourceException) {
LOG.info("Cannot find plugin $id resource-bundle: $baseName")
null
}
}) ?: descriptionChildText
description = result
return result
}
override fun getChangeNotes() = changeNotes
override fun getName(): String = name!!
override fun getProductCode() = productCode
override fun getReleaseDate() = releaseDate
override fun getReleaseVersion() = releaseVersion
override fun isLicenseOptional() = isLicenseOptional
override fun getOptionalDependentPluginIds(): Array<PluginId> {
val pluginDependencies = pluginDependencies
return if (pluginDependencies.isEmpty())
PluginId.EMPTY_ARRAY
else
pluginDependencies.asSequence()
.filter { it.isOptional }
.map { it.pluginId }
.toList()
.toTypedArray()
}
override fun getVendor() = vendor
override fun getVersion() = version
override fun getResourceBundleBaseName() = resourceBundleBaseName
override fun getCategory() = category
/*
This setter was explicitly defined to be able to set a category for a
descriptor outside its loading from the xml file.
Problem was that most commonly plugin authors do not publish the plugin's
category in its .xml file so to be consistent in plugins representation
(e.g. in the Plugins form) we have to set this value outside.
*/
fun setCategory(category: String?) {
this.category = category
}
val unsortedEpNameToExtensionElements: Map<String, List<ExtensionDescriptor>>
get() {
return Collections.unmodifiableMap(epNameToExtensions ?: return Collections.emptyMap())
}
override fun getVendorEmail() = vendorEmail
override fun getVendorUrl() = vendorUrl
override fun getUrl() = url
override fun getPluginId() = id
override fun getPluginClassLoader(): ClassLoader? = _pluginClassLoader
@ApiStatus.Internal
fun setPluginClassLoader(classLoader: ClassLoader?) {
_pluginClassLoader = classLoader
}
override fun isEnabled() = isEnabled
override fun setEnabled(enabled: Boolean) {
isEnabled = enabled
}
override fun getSinceBuild() = sinceBuild
override fun getUntilBuild() = untilBuild
override fun isBundled() = isBundled
override fun allowBundledUpdate() = isBundledUpdateAllowed
override fun isImplementationDetail() = implementationDetail
override fun isOnDemand() = onDemand
override fun isRequireRestart() = isRestartRequired
override fun equals(other: Any?): Boolean {
if (this === other) {
return true
}
if (other !is IdeaPluginDescriptorImpl) {
return false
}
return id == other.id && descriptorPath == other.descriptorPath
}
override fun hashCode(): Int {
return 31 * id.hashCode() + (descriptorPath?.hashCode() ?: 0)
}
override fun toString(): String {
return "PluginDescriptor(" +
"name=$name, " +
"id=$id, " +
(if (moduleName == null) "" else "moduleName=$moduleName, ") +
"descriptorPath=${descriptorPath ?: "plugin.xml"}, " +
"path=${pluginPathToUserString(path)}, " +
"version=$version, " +
"package=$packagePrefix, " +
"isBundled=$isBundled" +
")"
}
}
// don't expose user home in error messages
internal fun pluginPathToUserString(file: Path): String {
return file.toString().replace("${System.getProperty("user.home")}${File.separatorChar}", "~${File.separatorChar}")
}
private fun checkCycle(descriptor: IdeaPluginDescriptorImpl, configFile: String, visitedFiles: List<String>) {
var i = 0
val n = visitedFiles.size
while (i < n) {
if (configFile == visitedFiles[i]) {
val cycle = visitedFiles.subList(i, visitedFiles.size)
throw RuntimeException("Plugin $descriptor optional descriptors form a cycle: ${java.lang.String.join(", ", cycle)}")
}
i++
}
} | apache-2.0 | e9ddc7ca9c1968e48c57fc684307f341 | 36.934513 | 155 | 0.655702 | 5.254229 | false | false | false | false |
micolous/metrodroid | src/commonMain/kotlin/au/id/micolous/metrodroid/transit/china/NewShenzhenTransitData.kt | 1 | 4385 | /*
* NewShenzhenTransitData.kt
*
* Copyright 2018 Google
*
* 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.transit.china
import au.id.micolous.metrodroid.card.CardType
import au.id.micolous.metrodroid.card.china.ChinaCardTransitFactory
import au.id.micolous.metrodroid.card.china.ChinaCard
import au.id.micolous.metrodroid.card.iso7816.ISO7816TLV
import au.id.micolous.metrodroid.multi.Localizer
import au.id.micolous.metrodroid.multi.Parcelize
import au.id.micolous.metrodroid.multi.R
import au.id.micolous.metrodroid.transit.*
import au.id.micolous.metrodroid.util.NumberUtils
import au.id.micolous.metrodroid.util.ImmutableByteArray
// Reference: https://github.com/sinpolib/nfcard/blob/master/src/com/sinpo/xnfc/nfc/reader/pboc/ShenzhenTong.java
@Parcelize
class NewShenzhenTransitData (val validityStart: Int?,
val validityEnd: Int?,
private val mSerial: Int,
override val trips: List<NewShenzhenTrip>?,
val mBalance: Int?): TransitData() {
override val serialNumber: String?
get() = formatSerial(mSerial)
override val cardName: String
get() = Localizer.localizeString(R.string.card_name_szt)
public override val balance: TransitBalance?
get() = if (mBalance != null)
TransitBalanceStored(TransitCurrency.CNY(mBalance),
null,
ChinaTransitData.parseHexDate(validityStart),
ChinaTransitData.parseHexDate(validityEnd))
else
null
companion object {
private fun parse(card: ChinaCard) : NewShenzhenTransitData {
val szttag = getTagInfo(card)
return NewShenzhenTransitData(
validityStart = szttag?.byteArrayToInt(20, 4),
validityEnd = szttag?.byteArrayToInt(24, 4),
trips = ChinaTransitData.parseTrips(card) { data -> NewShenzhenTrip(data) },
mSerial = parseSerial(card),
mBalance = ChinaTransitData.parseBalance(card)
)
}
val CARD_INFO = CardInfo(
imageId = R.drawable.szt_card,
name = R.string.card_name_szt,
locationId = R.string.location_shenzhen,
cardType = CardType.FeliCa,
region = TransitRegion.CHINA,
preview = true)
val FACTORY: ChinaCardTransitFactory = object : ChinaCardTransitFactory {
override val appNames: List<ImmutableByteArray>
get() = listOf(ImmutableByteArray.fromASCII("PAY.SZT"))
override val allCards: List<CardInfo>
get() = listOf(CARD_INFO)
override fun parseTransitIdentity(card: ChinaCard) =
TransitIdentity(Localizer.localizeString(R.string.card_name_szt), formatSerial(parseSerial(card)))
override fun parseTransitData(card: ChinaCard) = parse(card)
}
private fun formatSerial(sn: Int): String {
val digsum = NumberUtils.getDigitSum(sn.toLong())
// Sum of digits must be divisible by 10
val lastDigit = (10 - digsum % 10) % 10
return "$sn($lastDigit)"
}
private fun getTagInfo(card: ChinaCard): ImmutableByteArray? {
val file15 = ChinaTransitData.getFile(card, 0x15)
if (file15 != null)
return file15.binaryData
val szttag = card.appProprietaryBerTlv ?: return null
return ISO7816TLV.findBERTLV(szttag, "8c", false)
}
private fun parseSerial(card: ChinaCard) = getTagInfo(card)?.byteArrayToIntReversed(16, 4) ?: 0
}
}
| gpl-3.0 | 5a400ad621a3e9d760d6688992b77f71 | 39.981308 | 118 | 0.643101 | 4.358847 | false | false | false | false |
icela/FriceEngine | src/org/frice/obj/AttachedObjects.kt | 1 | 1851 | package org.frice.obj
/**
* This is just an attacher, add objects inside.
*
* @author ice1000
* @since v1.7.2
*/
class AttachedObjects(val objs: MutableList<FObject>) : MutableList<FObject> by objs {
constructor(vararg fObject: FObject) : this(fObject.toMutableList())
/** scale all objects */
fun scale(x: Double, y: Double) = forEach { it.scale(x, y) }
/** move all objects */
fun move(x: Double, y: Double) = forEach { it.move(x, y) }
/** set all objects' `died` to true */
fun die() = forEach { it.died = true }
/** set all objects' `isVisible` to false */
fun hide() = forEach { it.isVisible = false }
/** rotate all objects */
fun rotate(angle: Double) = forEach { it.rotate(angle) }
/** stop all objects' anims */
fun stopAnims() = forEach(FObject::stopAnims)
fun clearDied() = removeIf(FObject::died)
fun addObject(vararg objects: FObject) = objects.forEach { add(it) }
fun removeObject(vararg objects: FObject) = objects.forEach { remove(it) }
}
/**
* This is just an attacher, add objects inside.
*
* @author ice1000
* @since v1.7.2
* @see AttachedObjects
*/
class AttachedAbstractObjects(val objs: MutableList<AbstractObject>) : MutableList<AbstractObject> by objs {
constructor(vararg fObject: AbstractObject) : this(fObject.toMutableList())
/** move all objects */
fun move(x: Double, y: Double) = forEach { it.move(x, y) }
/** set all objects' `died` to true */
fun die() = forEach { it.died = true }
/** set all objects' `isVisible` to false */
fun hide() = forEach { it.isVisible = false }
/** rotate all objects */
fun rotate(angle: Double) = forEach { it.rotate(angle) }
fun addObject(vararg objects: AbstractObject) = objects.forEach { add(it) }
fun clearDied() = removeIf(AbstractObject::died)
fun removeObject(vararg objects: AbstractObject) = objects.forEach { remove(it) }
}
| agpl-3.0 | 7a1895208ea1de46d5ab0facfb11132d | 29.85 | 108 | 0.679092 | 3.207972 | false | false | false | false |
GunoH/intellij-community | platform/lang-impl/src/com/intellij/codeInsight/hints/presentation/TextInlayPresentation.kt | 8 | 2426 | // 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.codeInsight.hints.presentation
import com.intellij.ide.ui.AntialiasingType
import com.intellij.openapi.editor.markup.EffectType
import com.intellij.openapi.editor.markup.TextAttributes
import com.intellij.ui.paint.EffectPainter
import org.jetbrains.annotations.ApiStatus
import java.awt.Graphics2D
import java.awt.RenderingHints
/**
* Draws text.
*/
@ApiStatus.Internal
class TextInlayPresentation(
private val metricsStorage: InlayTextMetricsStorage,
val isSmall: Boolean,
var text: String
) : BasePresentation() {
override val width: Int
get() = getMetrics().getStringWidth(text)
override val height: Int
get() = getMetrics().fontHeight
private fun getMetrics() = metricsStorage.getFontMetrics(isSmall)
override fun paint(g: Graphics2D, attributes: TextAttributes) {
val savedHint = g.getRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING)
try {
val foreground = attributes.foregroundColor
if (foreground != null) {
val metrics = getMetrics()
val font = metrics.font
g.font = font
g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, AntialiasingType.getKeyForCurrentScope(false))
g.color = foreground
g.drawString(text, 0, metrics.fontBaseline)
val effectColor = attributes.effectColor
if (effectColor != null) {
g.color = effectColor
when (attributes.effectType) {
EffectType.LINE_UNDERSCORE -> EffectPainter.LINE_UNDERSCORE.paint(g, 0, metrics.ascent, width, metrics.descent, font)
EffectType.BOLD_LINE_UNDERSCORE -> EffectPainter.BOLD_LINE_UNDERSCORE.paint(g, 0, metrics.ascent, width, metrics.descent, font)
EffectType.STRIKEOUT -> EffectPainter.STRIKE_THROUGH.paint(g, 0, metrics.fontBaseline, width, height, font)
EffectType.WAVE_UNDERSCORE -> EffectPainter.WAVE_UNDERSCORE.paint(g, 0, metrics.ascent, width, metrics.descent, font)
EffectType.BOLD_DOTTED_LINE -> EffectPainter.BOLD_DOTTED_UNDERSCORE.paint(g, 0, metrics.ascent, width, metrics.descent, font)
else -> {}
}
}
}
}
finally {
g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, savedHint)
}
}
override fun toString(): String = text
} | apache-2.0 | 9c58246a32e23c596fee1f82ea1f5624 | 39.45 | 140 | 0.714757 | 4.27866 | false | false | false | false |
jk1/intellij-community | plugins/stats-collector/src/com/intellij/stats/experiment/WebServiceStatusProvider.kt | 3 | 4215 | /*
* Copyright 2000-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.stats.experiment
import com.google.gson.Gson
import com.google.gson.JsonSyntaxException
import com.google.gson.internal.LinkedTreeMap
import com.intellij.ide.util.PropertiesComponent
import com.intellij.stats.network.assertNotEDT
import com.intellij.stats.network.service.RequestService
class WebServiceStatusProvider(
private val requestSender: RequestService,
private val experimentDecision: ExperimentDecision
): WebServiceStatus {
companion object {
val STATUS_URL: String = "https://www.jetbrains.com/config/features-service-status.json"
private val GSON = Gson()
private val SALT = "completion.stats.experiment.salt"
private val EXPERIMENT_VERSION_KEY = "completion.stats.experiment.version"
private val PERFORM_EXPERIMENT_KEY = "completion.ml.perform.experiment"
}
@Volatile private var info: ExperimentInfo = loadInfo()
@Volatile private var serverStatus = ""
@Volatile private var dataServerUrl = ""
override fun experimentVersion(): Int = info.experimentVersion
override fun dataServerUrl(): String = dataServerUrl
override fun isExperimentGoingOnNow(): Boolean = info.performExperiment
override fun isServerOk(): Boolean = serverStatus.equals("ok", ignoreCase = true)
override fun isExperimentOnCurrentIDE(): Boolean {
if (!info.performExperiment) {
return false
}
return experimentDecision.isPerformExperiment(info.salt)
}
override fun updateStatus() {
serverStatus = ""
dataServerUrl = ""
assertNotEDT()
val response = requestSender.get(STATUS_URL)
if (response != null && response.isOK()) {
val map = parseServerResponse(response.text)
val salt = map["salt"]?.toString()
val experimentVersion = map["experimentVersion"]?.toString()
val performExperiment = map["performExperiment"]?.toString() ?: "false"
if (salt != null && experimentVersion != null) {
//should be Int always
val floatVersion = experimentVersion.toFloat()
info = ExperimentInfo(floatVersion.toInt(), salt, performExperiment.toBoolean())
saveInfo(info)
}
serverStatus = map["status"]?.toString() ?: ""
dataServerUrl = map["urlForZipBase64Content"]?.toString() ?: ""
}
}
private fun parseServerResponse(responseText: String): LinkedTreeMap<*, *> {
try {
return GSON.fromJson(responseText, LinkedTreeMap::class.java)
}
catch (e: JsonSyntaxException) {
throw JsonSyntaxException("Expected valid JSON object, but received: $responseText", e)
}
}
private fun loadInfo(): ExperimentInfo {
return with (PropertiesComponent.getInstance()) {
val salt = getValue(SALT, "")
val experimentVersion = getInt(EXPERIMENT_VERSION_KEY, 0)
val performExperiment = getBoolean(PERFORM_EXPERIMENT_KEY, false)
ExperimentInfo(experimentVersion, salt, performExperiment)
}
}
private fun saveInfo(info: ExperimentInfo) {
with (PropertiesComponent.getInstance()) {
setValue(SALT, info.salt)
setValue(EXPERIMENT_VERSION_KEY, info.experimentVersion.toString())
setValue(PERFORM_EXPERIMENT_KEY, info.performExperiment)
}
}
}
data class ExperimentInfo(var experimentVersion: Int, var salt: String, var performExperiment: Boolean) | apache-2.0 | efe966cfe18f566c72d8825cfdaf394e | 35.982456 | 103 | 0.66809 | 4.795222 | false | false | false | false |
ktorio/ktor | ktor-io/jvm/src/io/ktor/utils/io/internal/ObjectPool.kt | 1 | 1164 | package io.ktor.utils.io.internal
import io.ktor.utils.io.pool.*
import java.nio.*
internal val BUFFER_SIZE = getIOIntProperty("BufferSize", 4096)
private val BUFFER_POOL_SIZE = getIOIntProperty("BufferPoolSize", 2048)
private val BUFFER_OBJECT_POOL_SIZE = getIOIntProperty("BufferObjectPoolSize", 1024)
// ------------- standard shared pool objects -------------
internal val BufferPool: ObjectPool<ByteBuffer> = DirectByteBufferPool(BUFFER_POOL_SIZE, BUFFER_SIZE)
internal val BufferObjectPool: ObjectPool<ReadWriteBufferState.Initial> =
object : DefaultPool<ReadWriteBufferState.Initial>(BUFFER_OBJECT_POOL_SIZE) {
override fun produceInstance() =
ReadWriteBufferState.Initial(BufferPool.borrow())
override fun disposeInstance(instance: ReadWriteBufferState.Initial) {
BufferPool.recycle(instance.backingBuffer)
}
}
internal val BufferObjectNoPool: ObjectPool<ReadWriteBufferState.Initial> =
object : NoPoolImpl<ReadWriteBufferState.Initial>() {
override fun borrow(): ReadWriteBufferState.Initial =
ReadWriteBufferState.Initial(ByteBuffer.allocateDirect(BUFFER_SIZE))
}
| apache-2.0 | b65278449f525211c4a9b63519b3c1ce | 42.111111 | 101 | 0.741409 | 4.494208 | false | false | false | false |
MiniMineCraft/MiniBus | src/main/kotlin/me/camdenorrb/minibus/type/TypeHolder.kt | 1 | 3760 | package me.camdenorrb.minibus.type
abstract class TypeHolder<T : Any> {
val type by lazy {
this::class.supertypes.first().arguments.first().type!!
}
}
/*
abstract class TypeHolder<T : Any> {
val raw: KClass<in T>
lateinit var type: Type
private set
constructor(raw: KClass<in T>) {
this.raw = raw
}
constructor(type: Type, raw: KClass<in T>) : this(raw) {
this.type = type
}
init {
if (!::type.isInitialized) {
//this::class.supertypes.first()
type = (javaClass.genericSuperclass as ParameterizedType).actualTypeArguments[0]
}
}
fun isAssignableFrom(clazz: KClass<T>): Boolean {
if (clazz != raw) return false
return isAssignableFrom(TypeHolder.of(clazz))
}
fun isAssignableFrom(typeHolder: TypeHolder<*>): Boolean {
println("${type} ${typeHolder.type}")
if (typeHolder.raw != raw) return false
return isAssignableFrom(typeHolder.type)
}
fun isAssignableFrom(fromType: ParameterizedType, toType: Type): Boolean {
if (toType !is ParameterizedType) {
return false
}
val fromTypes = fromType.actualTypeArguments
val toTypes = toType.actualTypeArguments
if (fromTypes.size != toTypes.size) {
return false
}
return (0 until fromTypes.size).all {
isAssignableFrom(fromTypes[it], toTypes[it])
}
}
fun isAssignableFrom(fromType: GenericArrayType, toType: Type): Boolean {
if (toType !is GenericArrayType) {
return false
}
return isAssignableFrom(fromType.genericComponentType, toType.genericComponentType)
}
fun isAssignableFrom(fromType: TypeVariable<*>, toType: Type): Boolean {
if (toType !is TypeVariable<*>) {
return false
}
val fromBounds = fromType.bounds
val toBounds = toType.bounds
if (fromBounds.size != toBounds.size) {
return false
}
return (0 until fromBounds.size).all {
isAssignableFrom(fromBounds[it], toBounds[it])
}
}
fun isAssignableFrom(fromType: WildcardType, toType: Type): Boolean {
if (toType !is WildcardType) {
return false
}
val toUpperBounds = toType.upperBounds
val fromUpperBounds = fromType.upperBounds
if (toUpperBounds.size != fromUpperBounds.size) {
return false
}
/*val toUpperBounds = toType.upperBounds
val fromUpperBounds = fromType.upperBounds
if (toUpperBounds.size != fromUpperBounds.size) {
return false
}
*/
val isUpperValid = (0 until toUpperBounds.size).all {
isAssignableFrom(fromUpperBounds[it], toUpperBounds[it])
}
return isUpperValid
/*
val isUpperValid = (0 until toUpperBounds.size).all {
println("${fromUpperBounds[it]} ${toUpperBounds[it]}")
isAssignableFrom(fromUpperBounds[it], toUpperBounds[it])
}
if (!isUpperValid) {
return false
}*/
}
fun isAssignableFrom(fromType: Type): Boolean {
return isAssignableFrom(fromType, type)
}
private fun isAssignableFrom(fromType: Type, toType: Type): Boolean {
return when (fromType) {
is Class<*> -> {
if (toType is Class<*>) fromType.isAssignableFrom(toType)
else false
}
is ParameterizedType -> isAssignableFrom(fromType, toType)
is GenericArrayType -> isAssignableFrom(fromType, toType)
is WildcardType -> isAssignableFrom(fromType, toType)
is TypeVariable<*> -> isAssignableFrom(fromType, toType)
else -> error("Couldn't handle $fromType")
}
}
companion object {
inline fun <reified T : Any> of(): TypeHolder<T> {
return object : TypeHolder<T>(T::class) {}
}
inline fun <reified T : Any> of(type: Type): TypeHolder<T> {
return object : TypeHolder<T>(type, T::class) {}
}
fun <T : Any> of(clazz: KClass<T>): TypeHolder<T> {
return object : TypeHolder<T>(clazz) {}
}
fun <T : Any> of(type: Type, clazz: KClass<T>): TypeHolder<T> {
return object : TypeHolder<T>(type, clazz) {}
}
}
}*/ | apache-2.0 | 73fae06009a3a9e644119208b93601b9 | 20.614943 | 85 | 0.691223 | 3.475046 | false | false | false | false |
KDE/kdeconnect-android | src/org/kde/kdeconnect/UserInterface/About/LicensesActivity.kt | 1 | 2657 | /*
* SPDX-FileCopyrightText: 2021 Maxim Leshchenko <[email protected]>
*
* SPDX-License-Identifier: GPL-2.0-only OR GPL-3.0-only OR LicenseRef-KDE-Accepted-GPL
*/
package org.kde.kdeconnect.UserInterface.About
import android.os.Bundle
import android.util.DisplayMetrics
import android.view.Menu
import android.view.MenuItem
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.LinearSmoothScroller
import org.apache.commons.io.IOUtils
import org.kde.kdeconnect.UserInterface.ThemeUtil
import org.kde.kdeconnect_tp.R
import org.kde.kdeconnect_tp.databinding.ActivityLicensesBinding
import java.nio.charset.Charset
class LicensesActivity : AppCompatActivity() {
private lateinit var binding: ActivityLicensesBinding
override fun onCreate(savedInstanceState: Bundle?) {
ThemeUtil.setUserPreferredTheme(this)
super.onCreate(savedInstanceState)
binding = ActivityLicensesBinding.inflate(layoutInflater)
setContentView(binding.root)
setSupportActionBar(binding.toolbarLayout.toolbar)
supportActionBar!!.setDisplayHomeAsUpEnabled(true)
supportActionBar!!.setDisplayShowHomeEnabled(true)
binding.licensesText.layoutManager = LinearLayoutManager(this)
binding.licensesText.adapter = StringListAdapter(getLicenses().split("\n\n"))
}
private fun getLicenses(): String = resources.openRawResource(R.raw.license).use { inputStream -> IOUtils.toString(inputStream, Charset.defaultCharset()) }
override fun onCreateOptionsMenu(menu: Menu): Boolean {
menuInflater.inflate(R.menu.menu_licenses, menu)
return super.onCreateOptionsMenu(menu)
}
private fun smoothScrollToPosition(position: Int) {
val linearSmoothScroller: LinearSmoothScroller = object : LinearSmoothScroller(this) {
override fun calculateSpeedPerPixel(displayMetrics: DisplayMetrics): Float = 2.5F / displayMetrics.densityDpi
}
linearSmoothScroller.targetPosition = position
binding.licensesText.layoutManager?.startSmoothScroll(linearSmoothScroller)
}
override fun onOptionsItemSelected(item: MenuItem): Boolean = when (item.itemId) {
R.id.menu_rise_up -> {
smoothScrollToPosition(0)
true
}
R.id.menu_rise_down -> {
smoothScrollToPosition(binding.licensesText.adapter!!.itemCount - 1)
true
}
else -> super.onOptionsItemSelected(item)
}
override fun onSupportNavigateUp(): Boolean {
super.onBackPressed()
return true
}
} | gpl-2.0 | 0a050e47a3b691e4e95b31aa69f8a273 | 35.916667 | 159 | 0.736921 | 4.753131 | false | false | false | false |
JonathanxD/CodeAPI | src/main/kotlin/com/github/jonathanxd/kores/ArrayInstructions.kt | 1 | 5698 | /*
* Kores - Java source and Bytecode generation framework <https://github.com/JonathanxD/Kores>
*
* The MIT License (MIT)
*
* Copyright (c) 2020 TheRealBuggy/JonathanxD (https://github.com/JonathanxD/) <[email protected]>
* Copyright (c) contributors
*
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.github.jonathanxd.kores
import java.util.*
import java.util.function.Consumer
import java.util.stream.Stream
import java.util.stream.StreamSupport
/**
* Backed by an [Array] of [Instruction].
*
* @see MutableInstructions
*/
class ArrayInstructions(private val parts: Array<Instruction> = emptyArray()) : Instructions() {
constructor() : this(emptyArray())
override val size: Int get() = this.parts.size
override fun getAtIndex(index: Int): Instruction =
this.parts[index]
override operator fun contains(o: Any): Boolean = this.parts.any { equals(it, o) }
override operator fun plus(other: Instruction): Instructions =
ArrayInstructions(this.parts + other)
override operator fun minus(other: Instruction): Instructions =
ArrayInstructions((this.parts.toList() - other).toTypedArray())
override operator fun plus(other: Iterable<Instruction>): Instructions =
ArrayInstructions((this.toList() + other).toTypedArray())
override operator fun minus(other: Iterable<Instruction>): Instructions =
ArrayInstructions(this.parts.filter { it in other }.toTypedArray())
override fun indexOf(o: Any): Int =
this.parts.indices.firstOrNull { equals(this.parts[it], o) } ?: -1
override fun lastIndexOf(o: Any): Int =
this.parts.indices.lastOrNull { Companion.equals(this.parts[it], o) } ?: -1
override fun forEach(action: Consumer<in Instruction>) {
for (part in this.parts) {
action.accept(part)
}
}
override fun toArray(): Array<Instruction> = this.parts.clone()
override fun spliterator(): Spliterator<Instruction> =
Spliterators.spliterator(this.parts.clone(), Spliterator.ORDERED)
override fun iterator(): Iterator<Instruction> = Iterat()
override fun subSource(fromIndex: Int, toIndex: Int): Instructions {
if (fromIndex < 0 || toIndex > this.size || fromIndex > toIndex)
throw IndexOutOfBoundsException("fromIndex: $fromIndex, toIndex: $toIndex")
return InstructionsView(this, fromIndex, toIndex)
}
override fun listIterator(): ListIterator<Instruction> = this.listIterator(0)
override fun listIterator(index: Int): ListIterator<Instruction> = ListIterat(index)
override fun stream(): Stream<Instruction> = StreamSupport.stream(this.spliterator(), false)
override fun parallelStream(): Stream<Instruction> =
StreamSupport.stream(this.spliterator(), true)
override fun toString(): String = if (this.isEmpty) "CodeSource[]" else "CodeSource[...]"
private inner class Iterat : Iterator<Instruction> {
private var index = 0
override fun hasNext(): Boolean = this.index < [email protected]
override fun next(): Instruction {
if (!this.hasNext())
throw java.util.NoSuchElementException()
return this@ArrayInstructions[this.index++]
}
}
private inner class ListIterat internal constructor(index: Int) :
ListIterator<Instruction> {
private var index = 0
init {
this.index = index
}
override fun hasNext(): Boolean = this.index < [email protected]
override fun next(): Instruction {
if (!this.hasNext())
throw java.util.NoSuchElementException()
return this@ArrayInstructions[this.index++]
}
override fun hasPrevious(): Boolean = this.index - 1 >= 0
override fun previous(): Instruction {
if (!this.hasPrevious())
throw java.util.NoSuchElementException()
return this@ArrayInstructions[--this.index]
}
override fun nextIndex(): Int = this.index
override fun previousIndex(): Int = this.index - 1
}
companion object {
@JvmStatic
inline fun ArrayInstructions(size: Int, init: (index: Int) -> Instruction): Instructions =
ArrayInstructions(Array(size, { init(it) }))
/**
* Helper method.
*/
private fun equals(a: Any?, b: Any?): Boolean =
a == null && b == null || a === b || a != null && b != null && a == b
}
}
| mit | 99b6bd92d8fa8044ca59d8cf2b087e12 | 34.17284 | 118 | 0.658828 | 4.625 | false | false | false | false |
dahlstrom-g/intellij-community | plugins/markdown/core/src/org/intellij/plugins/markdown/ui/actions/MarkdownActionUtil.kt | 1 | 4457 | // Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.intellij.plugins.markdown.ui.actions
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.actionSystem.CommonDataKeys
import com.intellij.openapi.actionSystem.PlatformCoreDataKeys
import com.intellij.openapi.editor.Caret
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.fileEditor.FileEditor
import com.intellij.openapi.util.Condition
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiFile
import com.intellij.psi.tree.IElementType
import com.intellij.psi.tree.TokenSet
import com.intellij.psi.util.PsiTreeUtil
import com.intellij.psi.util.PsiUtilBase
import com.intellij.util.concurrency.annotations.RequiresEdt
import org.intellij.plugins.markdown.lang.MarkdownLanguage
import org.intellij.plugins.markdown.lang.MarkdownLanguageUtils.isMarkdownLanguage
import org.intellij.plugins.markdown.ui.preview.MarkdownEditorWithPreview
import org.intellij.plugins.markdown.ui.preview.MarkdownPreviewFileEditor
internal object MarkdownActionUtil {
@RequiresEdt
@JvmStatic
fun findSplitEditor(event: AnActionEvent): MarkdownEditorWithPreview? {
val editor = event.getData(PlatformCoreDataKeys.FILE_EDITOR)
return findSplitEditor(editor)
}
@RequiresEdt
@JvmStatic
fun findSplitEditor(editor: FileEditor?): MarkdownEditorWithPreview? {
return when (editor) {
is MarkdownEditorWithPreview -> editor
else -> editor?.getUserData(MarkdownEditorWithPreview.PARENT_SPLIT_EDITOR_KEY)
}
}
@RequiresEdt
@JvmStatic
fun findMarkdownPreviewEditor(event: AnActionEvent): MarkdownPreviewFileEditor? {
val splitEditor = findSplitEditor(event) ?: return null
val editor = splitEditor.previewEditor
return when {
editor !is MarkdownPreviewFileEditor || !editor.getComponent().isVisible -> null
else -> editor
}
}
@JvmStatic
fun findMarkdownTextEditor(event: AnActionEvent): Editor? {
val splitEditor = findSplitEditor(event)
if (splitEditor == null) {
val psiFile = event.getData(CommonDataKeys.PSI_FILE) ?: return null
return when (psiFile.language) {
MarkdownLanguage.INSTANCE -> event.getData(CommonDataKeys.EDITOR)
else -> null
}
}
val mainEditor = splitEditor.textEditor
return when {
!mainEditor.component.isVisible -> null
else -> mainEditor.editor
}
}
fun findMarkdownTextEditorByPsiFile(event: AnActionEvent): Editor? {
val psiFile = event.getData(CommonDataKeys.PSI_FILE) ?: return null
return when {
psiFile.language.isMarkdownLanguage() -> event.getData(CommonDataKeys.EDITOR)
else -> null
}
}
@JvmStatic
fun getElementsUnderCaretOrSelection(file: PsiFile, caret: Caret): Pair<PsiElement, PsiElement> {
if (caret.selectionStart == caret.selectionEnd) {
val element = PsiUtilBase.getElementAtOffset(file, caret.selectionStart)
return element to element
}
val startElement = PsiUtilBase.getElementAtOffset(file, caret.selectionStart)
val endElement = PsiUtilBase.getElementAtOffset(file, caret.selectionEnd)
return startElement to endElement
}
@JvmStatic
fun getCommonParentOfType(left: PsiElement, right: PsiElement, elementType: IElementType): PsiElement? {
return getCommonParentOfTypes(left, right, TokenSet.create(elementType))
}
@JvmStatic
fun getCommonTopmostParentOfTypes(left: PsiElement, right: PsiElement, tokenSet: TokenSet): PsiElement? {
val base = PsiTreeUtil.findCommonParent(left, right)
return getTopmostParentOfType(base, Condition {
val node = it.node
node != null && tokenSet.contains(node.elementType)
})
}
@JvmStatic
fun getTopmostParentOfType(element: PsiElement?, condition: Condition<in PsiElement>): PsiElement? {
var answer = PsiTreeUtil.findFirstParent(element, false, condition)
do {
val next = PsiTreeUtil.findFirstParent(answer, true, condition) ?: break
answer = next
} while (true)
return answer
}
@JvmStatic
fun getCommonParentOfTypes(left: PsiElement, right: PsiElement, tokenSet: TokenSet): PsiElement? {
val base = PsiTreeUtil.findCommonParent(left, right)
return PsiTreeUtil.findFirstParent(base, false) {
val node = it.node
node != null && tokenSet.contains(node.elementType)
}
}
}
| apache-2.0 | 4584c1ace841c93c4b43d8dbae893a83 | 36.453782 | 140 | 0.754992 | 4.623444 | false | false | false | false |
dahlstrom-g/intellij-community | plugins/gradle/tooling-proxy/src/org/jetbrains/plugins/gradle/tooling/proxy/InetAddresses.kt | 12 | 2647 | // 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 org.jetbrains.plugins.gradle.tooling.proxy
import org.slf4j.LoggerFactory
import java.net.InetAddress
import java.net.SocketException
import java.lang.RuntimeException
import java.net.NetworkInterface
import java.util.*
internal class InetAddresses {
private val loopback: MutableList<InetAddress> = mutableListOf()
val remote: MutableList<InetAddress> = mutableListOf()
@Throws(SocketException::class)
private fun analyzeNetworkInterfaces() {
val interfaces = NetworkInterface.getNetworkInterfaces()
if (interfaces != null) {
while (interfaces.hasMoreElements()) {
analyzeNetworkInterface(interfaces.nextElement() as NetworkInterface)
}
}
}
private fun analyzeNetworkInterface(networkInterface: NetworkInterface) {
logger.debug("Adding IP addresses for network interface {}", networkInterface.displayName)
try {
val isLoopbackInterface = networkInterface.isLoopback
logger.debug("Is this a loopback interface? {}", isLoopbackInterface)
val candidates: Enumeration<*> = networkInterface.inetAddresses
while (candidates.hasMoreElements()) {
val candidate = candidates.nextElement() as InetAddress
if (isLoopbackInterface) {
if (candidate.isLoopbackAddress) {
if (candidate.isReachable(REACHABLE_TIMEOUT_MS)) {
logger.debug("Adding loopback address {}", candidate)
loopback.add(candidate)
}
else {
logger.debug("Ignoring unreachable local address on loopback interface {}", candidate)
}
}
else {
logger.debug("Ignoring remote address on loopback interface {}", candidate)
}
}
else if (candidate.isLoopbackAddress) {
logger.debug("Ignoring loopback address on remote interface {}", candidate)
}
else {
logger.debug("Adding remote address {}", candidate)
remote.add(candidate)
}
}
}
catch (e: SocketException) {
logger.debug("Error while querying interface {} for IP addresses", networkInterface, e)
}
catch (t: Throwable) {
throw RuntimeException(String.format("Could not determine the IP addresses for network interface %s", networkInterface.name), t)
}
}
companion object {
private val logger = LoggerFactory.getLogger(InetAddresses::class.java)
private const val REACHABLE_TIMEOUT_MS = 50
}
init {
analyzeNetworkInterfaces()
}
} | apache-2.0 | 1737ac73de686d6e47a08e66734f4964 | 35.777778 | 140 | 0.682282 | 5.090385 | false | false | false | false |
cdietze/klay | tripleklay/src/main/kotlin/tripleklay/ui/util/BoxPoint.kt | 1 | 4347 | package tripleklay.ui.util
import klay.scene.LayerUtil
import euklid.f.IDimension
import euklid.f.Point
import tripleklay.ui.Element
import tripleklay.ui.Style.HAlign
import tripleklay.ui.Style.VAlign
/** Defines a point relative to a box. */
class BoxPoint
/** Creates a new box point that will resolve to the given normalized coordinates plus
* the given absolute coordinates. */
constructor(
/** Normalized x, y coordinates. For example, nx = 1 is the right edge. */
val nx: Float, val ny: Float,
/** Absolute x, y offsets. */
val ox: Float = 0f, val oy: Float = 0f) {
/** Creates a new box point that is equivalent to this one except with an x coordinate that
* will resolve to the left edge of the box. */
fun left(): BoxPoint {
return nx(0f)
}
/** Creates a new box point that is equivalent to this one except with an x coordinate that
* will resolve to the right edge of the box. */
fun right(): BoxPoint {
return nx(1f)
}
/** Creates a new box point that is equivalent to this one except with a y coordinate that
* will resolve to the top edge of the box. */
fun top(): BoxPoint {
return ny(0f)
}
/** Creates a new box point that is equivalent to this one except with a y coordinate that
* will resolve to the top bottom of the box. */
fun bottom(): BoxPoint {
return ny(1f)
}
/** Creates a new box point that is equivalent to this one except with x, y coordinates that
* will resolve to the center of the box. */
fun center(): BoxPoint {
return BoxPoint(.5f, .5f, ox, oy)
}
/** Creates a new box point that is equivalent to this one except with given offset
* coordinates. */
fun offset(x: Float, y: Float): BoxPoint {
return BoxPoint(nx, ny, x, y)
}
/** Creates a new box point that is equivalent to this one except with the given normalized
* y coordinate. */
fun ny(ny: Float): BoxPoint {
return BoxPoint(nx, ny, ox, oy)
}
/** Creates a new box point that is equivalent to this one except with the given horizontal
* and vertical alignment. */
fun align(halign: HAlign, valign: VAlign): BoxPoint {
return BoxPoint(halign.offset(0f, 1f), valign.offset(0f, 1f), ox, oy)
}
/** Creates a new box point that is equivalent to this one except with the given y alignment.
* This is a shortcut for calling [.ny] with 0, .5, or 1. */
fun valign(valign: VAlign): BoxPoint {
return ny(valign.offset(0f, 1f))
}
/** Creates a new box point that is equivalent to this one except with the given normalized
* x coordinate. */
fun nx(nx: Float): BoxPoint {
return BoxPoint(nx, ny, ox, oy)
}
/** Creates a new box point that is equivalent to this one except with the given x alignment.
* This is a shortcut for calling [.nx] with 0, .5, or 1. */
fun halign(halign: HAlign): BoxPoint {
return nx(halign.offset(0f, 1f))
}
/** Finds the screen coordinates of the point, using the given element as the box. */
fun resolve(elem: Element<*>, dest: Point): Point {
LayerUtil.layerToScreen(elem.layer, dest.set(0f, 0f), dest)
return resolve(dest.x, dest.y, elem.size().width, elem.size().height, dest)
}
/** Finds the coordinates of the point, using the box defined by the given coordinates. */
fun resolve(x: Float, y: Float, width: Float, height: Float, dest: Point): Point {
return dest.set(x + ox + nx * width, y + oy + ny * height)
}
/** Finds the coordinates of the point, using the box with top left of 0, 0 and the given
* dimension. */
fun resolve(size: IDimension, dest: Point): Point {
return resolve(0f, 0f, size.width, size.height, dest)
}
companion object {
/** The top left corner. */
val TL = BoxPoint(0f, 0f)
/** The bottom left corner. */
val BL = BoxPoint(0f, 1f)
/** The top right corner. */
val TR = BoxPoint(1f, 0f)
/** The bottom right corner. */
val BR = BoxPoint(1f, 1f)
/** The center of the box. */
val CENTER = BoxPoint(.5f, .5f)
}
}
/** Creates a new box point that will resolve to the given normalized coordinates. */
| apache-2.0 | f25873fa3d9ed236a20f967ba18f0bb7 | 35.225 | 97 | 0.627789 | 3.744186 | false | false | false | false |
pflammertsma/cryptogram | app/src/main/java/com/pixplicity/cryptogram/utils/NotificationPublisher.kt | 1 | 4460 | package com.pixplicity.cryptogram.utils
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.os.Build
import androidx.core.app.NotificationCompat
import androidx.core.app.NotificationManagerCompat
import androidx.core.app.TaskStackBuilder
import com.pixplicity.cryptogram.R
import com.pixplicity.cryptogram.activities.CryptogramActivity
class NotificationPublisher : BroadcastReceiver() {
companion object {
/**
* Previously used for April Fools'.
*/
@Suppress("unused")
@Deprecated("Notification is removed, but do not use this ID")
const val NOTIFICATION_APRIL_SPECIAL = 2001
const val NOTIFICATION_NEW_PUZZLES = 2002
private const val NOTIFICATION_TYPE = "type"
private const val NOTIFICATION_TEXT = "text"
private const val CHANNEL_SPECIAL_EVENTS = "special_events"
private const val CHANNEL_NEW_PUZZLES = "new_puzzles"
fun getIntent(context: Context, type: Int, text: String?) =
Intent().apply {
putExtra(NOTIFICATION_TYPE, type)
putExtra(NOTIFICATION_TEXT, text)
}
fun clear(context: Context, type: Int) {
val notificationManager = NotificationManagerCompat.from(context)
notificationManager.cancel(type)
}
fun notify(context: Context, type: Int, text: String?) {
if (text == null) {
throw NullPointerException("No text provided for notification")
}
val channelId = when (type) {
NOTIFICATION_APRIL_SPECIAL -> CHANNEL_SPECIAL_EVENTS
NOTIFICATION_NEW_PUZZLES -> CHANNEL_NEW_PUZZLES
else -> throw IllegalStateException("Unexpected notification type $type")
}
val notificationManager = NotificationManagerCompat.from(context)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
context.apply {
// Create the NotificationChannel
val channel = when (channelId) {
CHANNEL_SPECIAL_EVENTS -> NotificationChannel(channelId,
getString(R.string.notification_channel_special_events_name),
NotificationManager.IMPORTANCE_DEFAULT).apply {
description = getString(R.string.notification_channel_special_events_description)
}
CHANNEL_NEW_PUZZLES -> NotificationChannel(channelId,
getString(R.string.notification_channel_new_puzzles_name),
NotificationManager.IMPORTANCE_DEFAULT).apply {
description = getString(R.string.notification_channel_new_puzzles_description)
}
else -> throw IllegalStateException("Unexpected notification channel $channelId")
}
// Register the channel with the system; you can't change the importance
// or other notification behaviors after this
notificationManager.createNotificationChannel(channel)
}
}
// Some defaults
val notification = NotificationCompat.Builder(context, channelId).apply {
setContentTitle(context.getString(R.string.app_name))
setContentText(text)
setSmallIcon(R.drawable.ic_notification)
setAutoCancel(true)
setContentIntent(TaskStackBuilder.create(context).run {
// Add the intent, which inflates the back stack
addNextIntentWithParentStack(Intent(context, CryptogramActivity::class.java))
// Get the PendingIntent containing the entire back stack
getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT)
})
}.build()
notificationManager.notify(type, notification)
}
}
override fun onReceive(context: Context, intent: Intent) {
intent.apply {
notify(context, getIntExtra(NOTIFICATION_TYPE, 0), getStringExtra(NOTIFICATION_TEXT))
}
}
}
| mit | e814e4b86528fd12e72a74b7361ef074 | 43.158416 | 109 | 0.609193 | 5.581977 | false | false | false | false |
sreich/ore-infinium | core/src/com/ore/infinium/util/KotlinExtensions.kt | 1 | 4016 | /**
MIT License
Copyright (c) 2016 Shaun Reich <[email protected]>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
package com.ore.infinium.util
import com.badlogic.gdx.math.MathUtils
import com.badlogic.gdx.utils.TimeUtils
/**
* Returns a new mutable list of @param n items,
* each having the value of @param value
*
* To be more similar to Array.fill()
*/
fun <T> mutableListOfNulls(n: Int) =
mutableListOf<T?>().apply {
repeat(n) {
add(null)
}
}
/**
*
* returns result of lambda, so we can e.g. return an element outward, by doing
*
* list.mapFirstNotNull { it.mapFirstNotNull { it.firstOrNull { it.predicate() } } }
*
* allowing us to get the element that matches that predicate, outside of the nesting
* lambdas.
* @author sreich
*/
inline fun <T, R : Any> Iterable<T>.firstNotNull(selector: (T) -> R?): R? {
forEach { selector(it)?.let { return it } }
return null
}
fun Int.isNegative(): Boolean {
return Math.abs(this) != this
}
fun profilerStart(name: String = ""): Long {
return TimeUtils.nanoTime()
}
fun profilerStopAndPrintMs(prevTimeNs: Long) {
val ns = TimeUtils.timeSinceNanos(prevTimeNs)
val ms = TimeUtils.nanosToMillis(ns)
println("PROFILER measured time: $ms ms")
}
/**
* profile time taken, execute a function, print result in ms
* and return result of function call
*/
fun <T> printMeasureTimeMs(block: () -> T, customString: String = ""): T {
val start = System.currentTimeMillis()
val result = block()
val time = System.currentTimeMillis() - start
println("PROFILER measured time: $time ms $customString")
return result
}
/**
* format to 2 decimals by default, or whatever you specify.
*/
fun Float.format(format: String = "%.4f") = String.format(format, this)
/**
* converts a multiline (\n)string into a single line one,
* also trims the margin, delimited by '|'.
*
* this is for allowing to use the multiline string syntax
* but still keep it on one actual line. string concatenation
* is what I hate, but I also hate huge length statements
*/
fun String.toSingleLine(): String {
return this.trimMargin().filterNot { it -> it == '\n' }
}
/**
* @return string indicating "enabled" or "disabled,
* based on true/false
* @author sreich
*/
fun Boolean.enabled() = if (this) {
"enabled"
} else {
"disabled"
}
/**
* @return string indicating "On" or "Off,
* based on true/false
* @author sreich
*/
fun Boolean.onOffString() = if (this) {
"On"
} else {
"Off"
}
/**
* @return true if negative
* @author sreich
*/
fun Float.isNegative(): Boolean {
return Math.abs(this) != this
}
/**
* @author sreich
*/
fun Float.abs(): Float {
return Math.abs(this)
}
/**
* @author sreich
*/
fun Float.floor(): Int {
return MathUtils.floor(this)
}
fun Float.floorf(): Float {
return MathUtils.floor(this).toFloat()
}
fun Float.ceil(): Int {
return MathUtils.ceil(this)
}
fun Float.round(): Int {
return Math.round(this)
}
| mit | 9b419cdea88d5e3a862e08f4abf3b1ae | 24.417722 | 85 | 0.689243 | 3.732342 | false | false | false | false |
github/codeql | java/ql/test/kotlin/library-tests/reflection/reflection.kt | 1 | 3800 | import java.awt.Rectangle
import kotlin.reflect.*
class Reflection {
fun fn() {
val ref: KFunction2<Ccc, Int, Double> = Ccc::m
println(ref.name)
val x0: KProperty1<C, Int> = C::p0
val x1: Int = x0.get(C())
val x2: String = x0.name
val x3: KProperty1.Getter<C, Int> = x0.getter
val x4: KFunction1<C, Int> = x0::get
val x5: KProperty0<Int> = C()::p0
val y0: KMutableProperty1<C, Int> = C::p1
val y1: Unit = y0.set(C(), 5)
val y2: String = y0.name
val y3: KMutableProperty1.Setter<C, Int> = y0.setter
val y4: KFunction2<C, Int, Unit> = y0::set
val y5: KMutableProperty0<Int> = C()::p1
val prop = (C::class).members.single { it.name == "p3" } as KProperty2<C, Int, Int>
val z0 = prop.get(C(), 5)
}
class Ccc {
fun m(i:Int):Double = 5.0
}
class C {
val p0: Int = 1
var p1: Int = 2
var p2: Int
get() = 1
set(value) = Unit
var Int.p3: Int // this can't be referenced through a property reference
get() = 1
set(value) = Unit
}
}
val String.lastChar: Char
get() = this[length - 1]
fun fn2() {
println(String::lastChar.get("abc"))
println("abcd"::lastChar.get())
}
fun <T2> Class1.Generic<T2>.ext1() = this.toString()
fun Class1.Generic<Int>.ext2() = this.toString()
class Class1 {
fun fn() {
println(Generic<Int>::m1)
println(Generic<Int>()::m1)
println(Generic<Int>::ext1)
println(Generic<Int>()::ext1)
println(Generic<Int>::ext2)
println(Generic<Int>()::ext2)
println(Generic<Int>::p2)
println(Generic<Int>()::p2)
println(Int::MAX_VALUE) // Companion object and property getter
println(Integer::MAX_VALUE) // Static field access, no getter
println(Rectangle()::height) // Field access, no getter, with dispatch receiver
}
class Generic<T1> {
fun m1(i:T1) = this.toString()
var p2: T1?
get() = null
set(value) = Unit
}
}
class Class2<T>(val value: T) {
inner class Inner<T1> {
constructor(t: T1) { }
}
fun test() {
fn11("", ::Inner)
}
}
fun <T> fn(value: T) { }
fun test() {
fn11("", ::Class2)
fn11("", ::fn)
fn12("", Class2(5)::Inner)
}
fun <T, R> fn11(l: T, transform: (T) -> R) { }
fun <T1, R> fn12(l: T1, l2: (T1) -> R) { }
open class Base1(var prop1: Int) {}
class Derived1(prop1: Int) : Base1(prop1) {
fun fn() {
println(this::prop1)
}
}
class LocalFn {
fun fn() {
fun fn1(i: Int) { }
val x: KFunction1<Int, Unit> = ::fn1
}
}
fun fn1() = 5
fun fn2(f: () -> Unit) = f()
fun adapted() {
fn2(::fn1)
}
fun expectsOneParam(f: (Int) -> Int) = f(0)
fun takesOptionalParam(x: Int, y: Int = 0) = x + y
fun adaptedParams() {
expectsOneParam(::takesOptionalParam)
}
fun expectsOneParamAndReceiver(f: (MemberOptionalsTest, Int) -> Int) { }
class MemberOptionalsTest {
fun takesOptionalParam(x: Int, y: Int = 0) = x + y
}
fun memberAdaptedParams(m: MemberOptionalsTest) {
expectsOneParam(m::takesOptionalParam)
expectsOneParamAndReceiver(MemberOptionalsTest::takesOptionalParam)
}
fun expectsOneParamAndExtension(f: (String, Int) -> Int) { }
fun String.extTakesOptionalParam(x: Int, y: Int = 0) = x + y
fun extensionAdaptedParams(s: String) {
expectsOneParam(s::extTakesOptionalParam)
expectsOneParamAndExtension(String::extTakesOptionalParam)
}
class ConstructorOptional(x: Int, y: Int = 0) { }
fun expectsOneParamCons(f: (Int) -> ConstructorOptional) = f(0)
fun constructorAdaptedParams() {
expectsOneParamCons(::ConstructorOptional)
}
| mit | 4bc70ad4cc436701508ffc812fbe7396 | 22.312883 | 91 | 0.577368 | 3.062047 | false | false | false | false |
audit4j/audit4j-demo | audit4j-kotlin-demo-springboot/src/main/kotlin/org/springframework/samples/petclinic/owner/VisitController.kt | 1 | 2039 | package org.springframework.samples.petclinic.owner
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.samples.petclinic.visit.Visit;
import org.springframework.samples.petclinic.visit.VisitRepository;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;
import javax.validation.Valid;
@Controller
class VisitController(val visits: VisitRepository, val pets: PetRepository) {
@InitBinder
fun setAllowedFields(dataBinder: WebDataBinder) {
dataBinder.setDisallowedFields("id")
}
/**
* Called before each and every @RequestMapping annotated method.
* 2 goals:
* - Make sure we always have fresh data
* - Since we do not use the session scope, make sure that Pet object always has an id
* (Even though id is not part of the form fields)
*
* @param petId
* @return Pet
*/
@ModelAttribute("visit")
fun loadPetWithVisit(@PathVariable("petId") petId: Int, model: MutableMap<String, Any>): Visit {
val pet = pets.findById(petId)
model.put("pet", pet)
val visit = Visit()
pet.addVisit(visit)
return visit
}
// Spring MVC calls method loadPetWithVisit(...) before initNewVisitForm is called
@GetMapping(value = "/owners/*/pets/{petId}/visits/new")
fun initNewVisitForm(@PathVariable("petId") petId: Int, model: Map<String, Any>): String
= "pets/createOrUpdateVisitForm"
// Spring MVC calls method loadPetWithVisit(...) before processNewVisitForm is called
@PostMapping(value = "/owners/{ownerId}/pets/{petId}/visits/new")
fun processNewVisitForm(@Valid visit: Visit, result: BindingResult): String {
return if (result.hasErrors()) {
"pets/createOrUpdateVisitForm"
} else {
visits.save(visit)
"redirect:/owners/{ownerId}"
}
}
} | apache-2.0 | 4c183a95c382d19c52463c0c25e86938 | 34.172414 | 100 | 0.692987 | 4.21281 | false | false | false | false |
paplorinc/intellij-community | platform/configuration-store-impl/src/schemeManager/SchemeManagerBase.kt | 3 | 1767 | // Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.configurationStore.schemeManager
import com.intellij.openapi.options.SchemeProcessor
import com.intellij.openapi.options.SchemesManager
abstract class SchemeManagerBase<T : Any, in MUTABLE_SCHEME : T>(internal val processor: SchemeProcessor<T, MUTABLE_SCHEME>) : SchemesManager<T>() {
/**
* Schemes can be lazy loaded, so, client should be able to set current scheme by name, not only by instance.
*/
@Volatile
internal var currentPendingSchemeName: String? = null
override var activeScheme: T? = null
internal set
override var currentSchemeName: String?
get() = activeScheme?.let { processor.getSchemeKey(it) } ?: currentPendingSchemeName
set(schemeName) = setCurrentSchemeName(schemeName, true)
internal fun processPendingCurrentSchemeName(newScheme: T): Boolean {
if (processor.getSchemeKey(newScheme) == currentPendingSchemeName) {
setCurrent(newScheme, false)
return true
}
return false
}
override fun setCurrent(scheme: T?, notify: Boolean) {
currentPendingSchemeName = null
val oldCurrent = activeScheme
activeScheme = scheme
if (notify && oldCurrent !== scheme) {
processor.onCurrentSchemeSwitched(oldCurrent, scheme)
}
}
override fun setCurrentSchemeName(schemeName: String?, notify: Boolean) {
currentPendingSchemeName = schemeName
val scheme = schemeName?.let { findSchemeByName(it) }
// don't set current scheme if no scheme by name - pending resolution (see currentSchemeName field comment)
if (scheme != null || schemeName == null) {
setCurrent(scheme, notify)
}
}
} | apache-2.0 | 3a4cf968ea7bc771f08cdbd6ac91b688 | 35.833333 | 148 | 0.732315 | 4.507653 | false | false | false | false |
kmagiera/react-native-gesture-handler | android/src/main/java/com/swmansion/gesturehandler/react/RNGestureHandlerRegistry.kt | 1 | 2921 | package com.swmansion.gesturehandler.react
import android.util.SparseArray
import android.view.View
import com.facebook.react.bridge.UiThreadUtil
import com.swmansion.gesturehandler.GestureHandler
import com.swmansion.gesturehandler.GestureHandlerRegistry
import java.util.*
class RNGestureHandlerRegistry : GestureHandlerRegistry {
private val handlers = SparseArray<GestureHandler<*>>()
private val attachedTo = SparseArray<Int?>()
private val handlersForView = SparseArray<ArrayList<GestureHandler<*>>>()
@Synchronized
fun registerHandler(handler: GestureHandler<*>) {
handlers.put(handler.tag, handler)
}
@Synchronized
fun getHandler(handlerTag: Int): GestureHandler<*>? {
return handlers[handlerTag]
}
@Synchronized
fun attachHandlerToView(handlerTag: Int, viewTag: Int, useDeviceEvents: Boolean = false): Boolean {
val handler = handlers[handlerTag]
return handler?.let {
detachHandler(handler)
handler.usesDeviceEvents = useDeviceEvents
registerHandlerForViewWithTag(viewTag, handler)
true
} ?: false
}
@Synchronized
private fun registerHandlerForViewWithTag(viewTag: Int, handler: GestureHandler<*>) {
check(attachedTo[handler.tag] == null) { "Handler $handler already attached" }
attachedTo.put(handler.tag, viewTag)
var listToAdd = handlersForView[viewTag]
if (listToAdd == null) {
listToAdd = ArrayList(1)
listToAdd.add(handler)
handlersForView.put(viewTag, listToAdd)
} else {
listToAdd.add(handler)
}
}
@Synchronized
private fun detachHandler(handler: GestureHandler<*>) {
val attachedToView = attachedTo[handler.tag]
if (attachedToView != null) {
attachedTo.remove(handler.tag)
val attachedHandlers = handlersForView[attachedToView]
if (attachedHandlers != null) {
attachedHandlers.remove(handler)
if (attachedHandlers.size == 0) {
handlersForView.remove(attachedToView)
}
}
}
if (handler.view != null) {
// Handler is in "prepared" state which means it is registered in the orchestrator and can
// receive touch events. This means that before we remove it from the registry we need to
// "cancel" it so that orchestrator does no longer keep a reference to it.
UiThreadUtil.runOnUiThread { handler.cancel() }
}
}
@Synchronized
fun dropHandler(handlerTag: Int) {
handlers[handlerTag]?.let {
detachHandler(it)
handlers.remove(handlerTag)
}
}
@Synchronized
fun dropAllHandlers() {
handlers.clear()
attachedTo.clear()
handlersForView.clear()
}
@Synchronized
fun getHandlersForViewWithTag(viewTag: Int): ArrayList<GestureHandler<*>>? {
return handlersForView[viewTag]
}
@Synchronized
override fun getHandlersForView(view: View): ArrayList<GestureHandler<*>>? {
return getHandlersForViewWithTag(view.id)
}
}
| mit | 76ca0d4c0a9c90b0b94baf783f318ac5 | 29.747368 | 101 | 0.711058 | 4.486943 | false | false | false | false |
vladmm/intellij-community | platform/configuration-store-impl/testSrc/DefaultProjectStoreTest.kt | 5 | 3869 | package com.intellij.configurationStore
import com.intellij.externalDependencies.DependencyOnPlugin
import com.intellij.externalDependencies.ExternalDependenciesManager
import com.intellij.externalDependencies.ProjectExternalDependency
import com.intellij.openapi.application.ex.ApplicationManagerEx
import com.intellij.openapi.application.runWriteAction
import com.intellij.openapi.components.*
import com.intellij.openapi.project.ProjectManager
import com.intellij.openapi.util.JDOMUtil
import com.intellij.openapi.vfs.LocalFileSystem
import com.intellij.testFramework.*
import org.assertj.core.api.Assertions.assertThat
import org.jdom.Element
import org.junit.ClassRule
import org.junit.Rule
import org.junit.Test
import java.nio.file.Paths
internal class DefaultProjectStoreTest {
companion object {
@ClassRule val projectRule = ProjectRule()
private const val TEST_COMPONENT_NAME = "Foo"
@State(name = TEST_COMPONENT_NAME, storages = arrayOf(
Storage(file = StoragePathMacros.PROJECT_FILE),
Storage(file = "${StoragePathMacros.PROJECT_CONFIG_DIR}/testSchemes", scheme = StorageScheme.DIRECTORY_BASED, stateSplitter = TestStateSplitter::class))
)
private class TestComponent: PersistentStateComponent<Element> {
private var element = Element("state")
override fun getState() = element.clone()
override fun loadState(state: Element) {
element = state.clone()
}
}
}
private val tempDirManager = TemporaryDirectory()
private val requiredPlugins = listOf<ProjectExternalDependency>(DependencyOnPlugin("fake", "0", "1"))
private val ruleChain = RuleChain(
tempDirManager,
WrapRule {
val app = ApplicationManagerEx.getApplicationEx()
val path = Paths.get(app.stateStore.stateStorageManager.expandMacros(StoragePathMacros.APP_CONFIG))
// dream about using in memory fs per test as ICS partially does and avoid such hacks
path.refreshVfs()
val isDoNotSave = app.isDoNotSave
app.doNotSave(false);
{
try {
app.doNotSave(isDoNotSave)
}
finally {
path.deleteRecursively()
val virtualFile = LocalFileSystem.getInstance().findFileByPathIfCached(path.systemIndependentPath)
runInEdtAndWait { runWriteAction { virtualFile?.delete(null) } }
}
}
}
)
@Rule fun getChain() = ruleChain
@Test fun `new project from default - file-based storage`() {
val externalDependenciesManager = ProjectManager.getInstance().defaultProject.service<ExternalDependenciesManager>()
externalDependenciesManager.allDependencies = requiredPlugins
try {
createProjectAndUseInLoadComponentStateMode(tempDirManager) {
assertThat(it.service<ExternalDependenciesManager>().allDependencies).isEqualTo(requiredPlugins)
}
}
finally {
externalDependenciesManager.allDependencies = emptyList()
}
}
@Test fun `new project from default - directory-based storage`() {
val defaultProject = ProjectManager.getInstance().defaultProject
val defaultTestComponent = TestComponent()
defaultTestComponent.loadState(JDOMUtil.load("""<component><main name="$TEST_COMPONENT_NAME"/><sub name="foo" /><sub name="bar" /></component>""".reader()))
val stateStore = defaultProject.stateStore as ComponentStoreImpl
stateStore.initComponent(defaultTestComponent, true)
try {
// obviously, project must be directory-based also
createProjectAndUseInLoadComponentStateMode(tempDirManager, directoryBased = true) {
val component = TestComponent()
it.stateStore.initComponent(component, true)
assertThat(JDOMUtil.writeElement(component.state)).isEqualTo(JDOMUtil.writeElement(defaultTestComponent.state))
}
}
finally {
stateStore.removeComponent(TEST_COMPONENT_NAME)
}
}
} | apache-2.0 | c8cdc0ef96dd2b5d2a245c444983b319 | 37.316832 | 160 | 0.742311 | 5.104222 | false | true | false | false |
google/intellij-community | plugins/gradle/src/org/jetbrains/plugins/gradle/frameworkSupport/script/ScriptTreeBuilder.kt | 5 | 4051 | // 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 org.jetbrains.plugins.gradle.frameworkSupport.script
import com.intellij.openapi.diagnostic.Logger
import org.jetbrains.plugins.gradle.frameworkSupport.script.ScriptElement.ArgumentElement
import org.jetbrains.plugins.gradle.frameworkSupport.script.ScriptElement.Statement
import org.jetbrains.plugins.gradle.frameworkSupport.script.ScriptElement.Statement.Expression
import org.jetbrains.plugins.gradle.frameworkSupport.script.ScriptElement.Statement.Expression.BlockElement
import org.jetbrains.plugins.gradle.frameworkSupport.script.ScriptElement.Statement.NewLineElement
@Suppress("MemberVisibilityCanBePrivate", "unused")
class ScriptTreeBuilder : AbstractScriptElementBuilder() {
private val roots = ArrayList<ScriptElement>()
fun join(builder: ScriptTreeBuilder) = builder.generate().also(::addElements)
fun addElements(block: BlockElement) = addElements(block) { true }
fun addElements(builder: ScriptTreeBuilder) = addElements(builder.generate())
fun addElements(configure: ScriptTreeBuilder.() -> Unit) = addElements(ScriptTreeBuilder(configure))
fun addNonExistedElements(block: BlockElement) = addElements(block) { it !in roots }
fun addNonExistedElements(builder: ScriptTreeBuilder) = addNonExistedElements(builder.generate())
fun addNonExistedElements(configure: ScriptTreeBuilder.() -> Unit) = addNonExistedElements(ScriptTreeBuilder(configure))
fun addElements(block: BlockElement, filter: (ScriptElement) -> Boolean) = apply {
block.statements.filterTo(roots, filter)
}
private fun <E : ScriptElement> process(vararg children: ScriptElement, element: () -> E) = process(children.toList(), element)
private fun <E : ScriptElement> process(children: List<ScriptElement>, createElement: () -> E): E {
for (child in children) {
roots.removeIf { it === child }
}
val element = createElement()
roots.add(element)
return element
}
override fun newLine() = process { super.newLine() }
override fun int(value: Int) = process { super.int(value) }
override fun boolean(value: Boolean) = process { super.boolean(value) }
override fun string(value: String) = process { super.string(value) }
override fun list(elements: List<Expression>) = process(elements) { super.list(elements) }
override fun code(text: List<String>) = process { super.code(text) }
override fun assign(name: String, value: Expression) = process(value) { super.assign(name, value) }
override fun plusAssign(name: String, value: Expression) = process(value) { super.plusAssign(name, value) }
override fun property(name: String, value: Expression) = process(value) { super.property(name, value) }
override fun call(name: Expression, arguments: List<ArgumentElement>) = process(arguments + name) { super.call(name, arguments) }
override fun infixCall(left: Expression, name: String, right: Expression) = process(left, right) { super.infixCall(left, name, right) }
override fun argument(name: String?, value: Expression) = process(value) { super.argument(name, value) }
override fun block(configure: ScriptTreeBuilder.() -> Unit) = process { super.block(configure) }
fun generate(): BlockElement {
val statements = roots.filterIsInstance<Statement>()
if (statements.size != roots.size) {
LOG.error("Found non complete script tree. Orphan elements: " +
roots.filterNot { it is Statement })
}
return BlockElement(statements.dropLastWhile { it == NewLineElement })
}
companion object {
private val LOG = Logger.getInstance(ScriptTreeBuilder::class.java)
operator fun invoke(configure: ScriptTreeBuilder.() -> Unit) =
ScriptTreeBuilder().apply(configure)
fun tree(configure: ScriptTreeBuilder.() -> Unit) =
ScriptTreeBuilder(configure).generate()
fun script(builder: ScriptBuilder, configure: ScriptTreeBuilder.() -> Unit) =
builder.generate(tree(configure))
}
} | apache-2.0 | 6ea136de2509945ba66fea277e7d0e49 | 53.026667 | 140 | 0.748704 | 4.365302 | false | true | false | false |
JetBrains/intellij-community | plugins/grazie/src/main/kotlin/com/intellij/grazie/ide/notification/GrazieToastNotifications.kt | 1 | 2543 | // 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.notification
import com.intellij.grazie.GrazieConfig
import com.intellij.grazie.ide.ui.components.dsl.msg
import com.intellij.grazie.remote.GrazieRemote
import com.intellij.notification.Notification
import com.intellij.notification.NotificationAction
import com.intellij.notification.NotificationGroupManager
import com.intellij.notification.NotificationType
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.project.Project
import com.intellij.util.containers.MultiMap
import java.lang.ref.WeakReference
object GrazieToastNotifications {
private enum class Group {
LANGUAGES
}
private val shownNotifications = MultiMap.createConcurrent<Group, WeakReference<Notification>>()
internal val MISSED_LANGUAGES_GROUP = NotificationGroupManager.getInstance()
.getNotificationGroup("Proofreading missing languages information")
internal val GENERAL_GROUP
get() = NotificationGroupManager.getInstance().getNotificationGroup("Grazie notifications")
fun showMissedLanguages(project: Project) {
val langs = GrazieConfig.get().missedLanguages
MISSED_LANGUAGES_GROUP
.createNotification(msg("grazie.notification.missing-languages.title"),
msg("grazie.notification.missing-languages.body", langs.joinToString()),
NotificationType.WARNING)
.addAction(object : NotificationAction(msg("grazie.notification.missing-languages.action.download")) {
override fun actionPerformed(e: AnActionEvent, notification: Notification) {
GrazieRemote.downloadMissing(project)
notification.expire()
}
})
.addAction(object : NotificationAction(msg("grazie.notification.missing-languages.action.disable")) {
override fun actionPerformed(e: AnActionEvent, notification: Notification) {
GrazieConfig.update { state ->
state.copy(enabledLanguages = state.enabledLanguages - state.missedLanguages)
}
notification.expire()
}
})
.setSuggestionType(true)
.expireAll(Group.LANGUAGES)
.notify(project)
}
private fun Notification.expireAll(group: Group): Notification {
whenExpired {
shownNotifications.remove(group)?.forEach { it.get()?.expire() }
}
shownNotifications.putValue(group, WeakReference(this))
return this
}
}
| apache-2.0 | 9dc3846f1e57a84a55136113149d67b3 | 40.688525 | 140 | 0.74361 | 4.976517 | false | false | false | false |
square/okhttp | okhttp/src/jvmTest/java/okhttp3/internal/idn/stringprep.kt | 3 | 3292 | /*
* Copyright (C) 2022 Square, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package okhttp3.internal.idn
import okio.Buffer
import okio.BufferedSource
/**
* An implementation of Stringprep ([RFC 3454]) intended for use with Nameprep ([RFC 3491]).
*
* [RFC 3454]: https://datatracker.ietf.org/doc/html/rfc3454
* [RFC 3491]: https://datatracker.ietf.org/doc/html/rfc3491
*/
class Stringprep(
/** Unassigned code points. */
val unassigned: CodePointSet,
/** Mappings. Note table B.3 is not used in RFC 3491. */
val mapping: CodePointMapping,
/** Prohibited code points. */
val prohibitSet: CodePointSet,
/** RandALCat code points; bidi category is "R" or "AL". */
val randalcatSet: CodePointSet,
/** LCat code points; bidi category is "L". */
val lcatSet: CodePointSet,
) {
/**
* Returns [input] in canonical form according to these rules, or null if no such canonical form
* exists for it.
*/
operator fun invoke(input: String): String? = invoke(Buffer().writeUtf8(input))
internal operator fun invoke(input: BufferedSource): String? {
// 1. Map.
val mapResult = Buffer()
while (!input.exhausted()) {
val codePoint = input.readUtf8CodePoint()
when (val mappedCodePoint = mapping[codePoint]) {
null -> mapResult.writeUtf8CodePoint(codePoint)
else -> mapResult.writeUtf8(mappedCodePoint)
}
}
// 2. Normalize
// TODO.
// 3 and 4. Check prohibited characters and bidi.
val validateBuffer = mapResult.copy()
var firstIsRandalcat = false
while (!validateBuffer.exhausted()) {
val first = validateBuffer.size == mapResult.size
val codePoint = validateBuffer.readUtf8CodePoint()
if (codePoint in prohibitSet) return null
if (first) {
firstIsRandalcat = codePoint in randalcatSet
} else if (firstIsRandalcat) {
// 'If a string contains any RandALCat character, the string MUST NOT contain any LCat
// character.'
if (codePoint in lcatSet) return null
// 'If a string contains any RandALCat character, a RandALCat character MUST be the last
// character of the string.'
if (validateBuffer.exhausted() && codePoint !in randalcatSet) return null
} else {
// 'If a string contains any RandALCat character, a RandALCat character MUST be the first
// character of the string'
if (codePoint in randalcatSet) return null
}
}
return mapResult.readUtf8()
}
}
interface CodePointMapping {
/**
* Returns a (possibly-empty) string that [codePoint] maps to, or null if [codePoint] is not
* mapped.
*/
operator fun get(codePoint: Int): String?
}
interface CodePointSet {
operator fun contains(codePoint: Int): Boolean
}
| apache-2.0 | 00513f5c13f9657efbe84644fd15f52c | 31.92 | 98 | 0.68226 | 3.937799 | false | false | false | false |
allotria/intellij-community | uast/uast-java/src/org/jetbrains/uast/java/declarations/JavaUVariable.kt | 3 | 6509 | // Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.uast.java
import com.intellij.psi.*
import com.intellij.psi.impl.source.PsiParameterImpl
import com.intellij.psi.impl.source.tree.java.PsiLocalVariableImpl
import com.intellij.psi.util.PsiTypesUtil
import com.intellij.psi.util.parentOfType
import org.jetbrains.uast.*
import org.jetbrains.uast.java.internal.JavaUElementWithComments
abstract class AbstractJavaUVariable(givenParent: UElement?) : JavaAbstractUElement(
givenParent), PsiVariable, UVariableEx, JavaUElementWithComments, UAnchorOwner {
abstract override val javaPsi: PsiVariable
@Suppress("OverridingDeprecatedMember")
override val psi
get() = javaPsi
override val uastInitializer: UExpression? by lz {
val initializer = javaPsi.initializer ?: return@lz null
UastFacade.findPlugin(initializer)?.convertElement(initializer, this) as? UExpression
}
override val uAnnotations: List<JavaUAnnotation> by lz { javaPsi.annotations.map { JavaUAnnotation(it, this) } }
override val typeReference: UTypeReferenceExpression? by lz {
javaPsi.typeElement?.let { UastFacade.findPlugin(it)?.convertOpt<UTypeReferenceExpression>(javaPsi.typeElement, this) }
}
abstract override val sourcePsi: PsiVariable?
override val uastAnchor: UIdentifier?
get() = sourcePsi?.let { UIdentifier(it.nameIdentifier, this) }
override fun equals(other: Any?): Boolean = other is AbstractJavaUVariable && javaPsi == other.javaPsi
override fun hashCode(): Int = javaPsi.hashCode()
}
class JavaUVariable(
override val javaPsi: PsiVariable,
givenParent: UElement?
) : AbstractJavaUVariable(givenParent), UVariableEx, PsiVariable by javaPsi {
@Suppress("OverridingDeprecatedMember")
override val psi: PsiVariable
get() = javaPsi
override val sourcePsi: PsiVariable? get() = javaPsi.takeIf { it.isPhysical || it is PsiLocalVariableImpl}
companion object {
fun create(psi: PsiVariable, containingElement: UElement?): UVariable {
return when (psi) {
is PsiEnumConstant -> JavaUEnumConstant(psi, containingElement)
is PsiLocalVariable -> JavaULocalVariable(psi, containingElement)
is PsiParameter -> JavaUParameter(psi, containingElement)
is PsiField -> JavaUField(psi, containingElement)
else -> JavaUVariable(psi, containingElement)
}
}
}
override fun getOriginalElement(): PsiElement? = javaPsi.originalElement
}
class JavaUParameter(
override val javaPsi: PsiParameter,
givenParent: UElement?
) : AbstractJavaUVariable(givenParent), UParameterEx, PsiParameter by javaPsi {
@Suppress("OverridingDeprecatedMember")
override val psi: PsiParameter
get() = javaPsi
override val sourcePsi: PsiParameter?
get() = javaPsi.takeIf { it.isPhysical || (it is PsiParameterImpl && it.parentOfType<PsiMethod>()?.let { canBeSourcePsi(it) } == true) }
override fun getOriginalElement(): PsiElement? = javaPsi.originalElement
}
class JavaUField(
override val sourcePsi: PsiField,
givenParent: UElement?
) : AbstractJavaUVariable(givenParent), UFieldEx, PsiField by sourcePsi {
@Suppress("OverridingDeprecatedMember")
override val psi: PsiField
get() = javaPsi
override val javaPsi: PsiField = unwrap<UField, PsiField>(sourcePsi)
override fun getOriginalElement(): PsiElement? = sourcePsi.originalElement
}
class JavaULocalVariable(
override val sourcePsi: PsiLocalVariable,
givenParent: UElement?
) : AbstractJavaUVariable(givenParent), ULocalVariableEx, PsiLocalVariable by sourcePsi {
@Suppress("OverridingDeprecatedMember")
override val psi: PsiLocalVariable
get() = javaPsi
override val javaPsi: PsiLocalVariable = unwrap<ULocalVariable, PsiLocalVariable>(sourcePsi)
override fun getPsiParentForLazyConversion(): PsiElement? = super.getPsiParentForLazyConversion()?.let {
when (it) {
is PsiResourceList -> it.parent
else -> it
}
}
override fun getOriginalElement(): PsiElement? = sourcePsi.originalElement
}
class JavaUEnumConstant(
override val sourcePsi: PsiEnumConstant,
givenParent: UElement?
) : AbstractJavaUVariable(givenParent), UEnumConstantEx, UCallExpressionEx, PsiEnumConstant by sourcePsi, UMultiResolvable {
override val initializingClass: UClass? by lz { UastFacade.findPlugin(sourcePsi)?.convertOpt<UClass>(sourcePsi.initializingClass, this) }
@Suppress("OverridingDeprecatedMember")
override val psi: PsiEnumConstant
get() = javaPsi
override val javaPsi: PsiEnumConstant get() = sourcePsi
override val kind: UastCallKind
get() = UastCallKind.CONSTRUCTOR_CALL
override val receiver: UExpression?
get() = null
override val receiverType: PsiType?
get() = null
override val methodIdentifier: UIdentifier?
get() = null
override val classReference: UReferenceExpression?
get() = JavaEnumConstantClassReference(sourcePsi, this)
override val typeArgumentCount: Int
get() = 0
override val typeArguments: List<PsiType>
get() = emptyList()
override val valueArgumentCount: Int
get() = sourcePsi.argumentList?.expressions?.size ?: 0
override val valueArguments: List<UExpression> by lz {
sourcePsi.argumentList?.expressions?.map {
UastFacade.findPlugin(it)?.convertElement(it, this) as? UExpression ?: UastEmptyExpression(this)
} ?: emptyList()
}
override fun getArgumentForParameter(i: Int): UExpression? = valueArguments.getOrNull(i)
override val returnType: PsiType?
get() = sourcePsi.type
override fun resolve(): PsiMethod? = sourcePsi.resolveMethod()
override fun multiResolve(): Iterable<ResolveResult> =
listOfNotNull(sourcePsi.resolveMethodGenerics())
override val methodName: String?
get() = null
private class JavaEnumConstantClassReference(
override val sourcePsi: PsiEnumConstant,
givenParent: UElement?
) : JavaAbstractUExpression(givenParent), USimpleNameReferenceExpression, UMultiResolvable {
override fun resolve() = sourcePsi.containingClass
override fun multiResolve(): Iterable<ResolveResult> =
listOfNotNull(resolve()?.let { PsiTypesUtil.getClassType(it).resolveGenerics() })
override val resolvedName: String?
get() = sourcePsi.containingClass?.name
override val identifier: String
get() = sourcePsi.containingClass?.name ?: "<error>"
}
override fun getOriginalElement(): PsiElement? = sourcePsi.originalElement
} | apache-2.0 | 49c5f5d92d0a062aafb44bfad15855d9 | 35.573034 | 140 | 0.756952 | 5.121164 | false | false | false | false |
allotria/intellij-community | platform/vcs-log/impl/src/com/intellij/vcs/log/ui/details/commit/CommitDetailsPanel.kt | 3 | 8391 | // 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.vcs.log.ui.details.commit
import com.intellij.ide.IdeTooltipManager
import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.VerticalFlowLayout
import com.intellij.openapi.ui.popup.Balloon
import com.intellij.openapi.util.text.HtmlChunk
import com.intellij.openapi.vcs.ui.FontUtil
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.ui.BrowserHyperlinkListener
import com.intellij.ui.components.panels.Wrapper
import com.intellij.ui.scale.JBUIScale
import com.intellij.util.ui.ColorIcon
import com.intellij.util.ui.HtmlPanel
import com.intellij.util.ui.JBUI
import com.intellij.util.ui.UIUtil
import com.intellij.util.ui.components.BorderLayoutPanel
import com.intellij.vcs.log.CommitId
import com.intellij.vcs.log.VcsCommitMetadata
import com.intellij.vcs.log.VcsRef
import com.intellij.vcs.log.ui.frame.CommitPresentationUtil.*
import com.intellij.vcs.log.util.VcsLogUiUtil
import java.awt.*
import java.awt.event.MouseAdapter
import java.awt.event.MouseEvent
import javax.swing.JPanel
import javax.swing.event.HyperlinkEvent
open class CommitDetailsPanel(private val project: Project, navigate: (CommitId) -> Unit) : JPanel() {
companion object {
const val SIDE_BORDER = 14
const val INTERNAL_BORDER = 10
const val EXTERNAL_BORDER = 14
}
data class RootColor(val root: VirtualFile, val color: Color)
private val hashAndAuthorPanel = HashAndAuthorPanel()
private val messagePanel = CommitMessagePanel(navigate)
private val branchesPanel = ReferencesPanel()
private val tagsPanel = ReferencesPanel()
private val rootPanel = RootColorPanel(hashAndAuthorPanel)
private val containingBranchesPanel = ContainingBranchesPanel()
init {
layout = VerticalFlowLayout(VerticalFlowLayout.TOP, 0, 0, true, false)
isOpaque = false
val metadataPanel = BorderLayoutPanel().apply {
isOpaque = false
border = JBUI.Borders.empty(INTERNAL_BORDER, SIDE_BORDER)
addToLeft(rootPanel)
addToCenter(hashAndAuthorPanel)
}
add(messagePanel)
add(metadataPanel)
add(branchesPanel)
add(tagsPanel)
add(containingBranchesPanel)
}
final override fun add(comp: Component?): Component = super.add(comp)
open fun setCommit(commit: CommitId, presentation: CommitPresentation) {
messagePanel.updateMessage(presentation)
hashAndAuthorPanel.updateHashAndAuthor(presentation)
}
fun setCommit(commit: VcsCommitMetadata) {
val presentation = buildPresentation(project, commit, mutableSetOf())
setCommit(CommitId(commit.id, commit.root), presentation)
}
fun setRefs(references: List<VcsRef>?) {
references ?: return
branchesPanel.setReferences(references.filter { it.type.isBranch })
tagsPanel.setReferences(references.filter { !it.type.isBranch })
if (tagsPanel.isVisible) {
branchesPanel.border = JBUI.Borders.empty(0, SIDE_BORDER - ReferencesPanel.H_GAP, 0, SIDE_BORDER)
tagsPanel.border = JBUI.Borders.empty(0, SIDE_BORDER - ReferencesPanel.H_GAP, INTERNAL_BORDER, SIDE_BORDER)
}
else if (branchesPanel.isVisible) {
branchesPanel.border = JBUI.Borders.empty(0, SIDE_BORDER - ReferencesPanel.H_GAP, INTERNAL_BORDER, SIDE_BORDER)
}
update()
}
fun setRoot(rootColor: RootColor?) {
rootPanel.setRoot(rootColor)
}
fun setBranches(branches: List<String>?) {
containingBranchesPanel.setBranches(branches)
}
fun update() {
messagePanel.update()
rootPanel.update()
hashAndAuthorPanel.update()
branchesPanel.update()
tagsPanel.update()
containingBranchesPanel.update()
}
override fun getBackground(): Color = getCommitDetailsBackground()
}
private class CommitMessagePanel(private val navigate: (CommitId) -> Unit) : HtmlPanel() {
private var presentation: CommitPresentation? = null
override fun hyperlinkUpdate(e: HyperlinkEvent) {
presentation?.let { presentation ->
if (e.eventType == HyperlinkEvent.EventType.ACTIVATED && isGoToHash(e)) {
val commitId = presentation.parseTargetCommit(e) ?: return
navigate(commitId)
}
else {
BrowserHyperlinkListener.INSTANCE.hyperlinkUpdate(e)
}
}
}
init {
border = JBUI.Borders.empty(CommitDetailsPanel.EXTERNAL_BORDER, CommitDetailsPanel.SIDE_BORDER, CommitDetailsPanel.INTERNAL_BORDER,
CommitDetailsPanel.SIDE_BORDER)
}
fun updateMessage(message: CommitPresentation?) {
presentation = message
update()
}
override fun getBody() = presentation?.text ?: ""
override fun getBackground(): Color = getCommitDetailsBackground()
override fun update() {
isVisible = presentation != null
super.update()
}
}
private class ContainingBranchesPanel : HtmlPanel() {
private var branches: List<String>? = null
private var expanded = false
init {
border = JBUI.Borders.empty(0, CommitDetailsPanel.SIDE_BORDER, CommitDetailsPanel.EXTERNAL_BORDER, CommitDetailsPanel.SIDE_BORDER)
isVisible = false
}
override fun setBounds(x: Int, y: Int, w: Int, h: Int) {
val oldWidth = width
super.setBounds(x, y, w, h)
if (w != oldWidth) {
update()
}
}
override fun hyperlinkUpdate(e: HyperlinkEvent) {
if (e.eventType == HyperlinkEvent.EventType.ACTIVATED && isShowHideBranches(e)) {
expanded = !expanded
update()
}
}
fun setBranches(branches: List<String>?) {
this.branches = branches
expanded = false
isVisible = true
update()
}
override fun getBody(): String {
val insets = insets
val text = getBranchesText(branches, expanded, width - insets.left - insets.right, getFontMetrics(bodyFont))
return if (expanded) text else HtmlChunk.raw(text).wrapWith("nobr").toString()
}
override fun getBackground(): Color = getCommitDetailsBackground()
override fun getBodyFont(): Font = FontUtil.getCommitMetadataFont()
}
private class HashAndAuthorPanel : HtmlPanel() {
private var presentation: CommitPresentation? = null
override fun getBody(): String = presentation?.hashAndAuthor ?: ""
init {
border = JBUI.Borders.empty()
}
fun updateHashAndAuthor(commitAndAuthorPresentation: CommitPresentation?) {
presentation = commitAndAuthorPresentation
update()
}
public override fun getBodyFont(): Font = FontUtil.getCommitMetadataFont()
override fun update() {
isVisible = presentation != null
super.update()
}
}
private class RootColorPanel(private val parent: HashAndAuthorPanel) : Wrapper(parent) {
companion object {
private const val ROOT_ICON_SIZE = 13
private const val ROOT_GAP = 4
}
private var icon: ColorIcon? = null
private var tooltipText: String? = null
private val mouseMotionListener = object : MouseAdapter() {
override fun mouseMoved(e: MouseEvent?) {
if (IdeTooltipManager.getInstance().hasCurrent()) {
IdeTooltipManager.getInstance().hideCurrent(e)
return
}
icon?.let { icon ->
tooltipText?.let { tooltipText ->
VcsLogUiUtil.showTooltip(this@RootColorPanel, Point(icon.iconWidth / 2, 0), Balloon.Position.above, tooltipText)
}
}
}
}
init {
setVerticalSizeReferent(parent)
addMouseMotionListener(mouseMotionListener)
}
override fun getPreferredSize(): Dimension = icon?.let { icon ->
val size = super.getPreferredSize()
Dimension(icon.iconWidth + JBUIScale.scale(ROOT_GAP), size.height)
} ?: Dimension(0, 0)
fun setRoot(rootColor: CommitDetailsPanel.RootColor?) {
if (rootColor != null) {
icon = JBUI.scale(ColorIcon(ROOT_ICON_SIZE, rootColor.color))
tooltipText = rootColor.root.path
}
else {
icon = null
tooltipText = null
}
}
fun update() {
isVisible = icon != null
revalidate()
repaint()
}
override fun getBackground(): Color = getCommitDetailsBackground()
override fun paintComponent(g: Graphics) {
icon?.let { icon ->
val h = FontUtil.getStandardAscent(parent.bodyFont, g)
val metrics = getFontMetrics(parent.bodyFont)
icon.paintIcon(this, g, 0, metrics.maxAscent - h + (h - icon.iconHeight - 1) / 2)
}
}
}
fun getCommitDetailsBackground(): Color = UIUtil.getTreeBackground() | apache-2.0 | eec14431092e3284136ca696500ba170 | 30.197026 | 140 | 0.718627 | 4.349922 | false | false | false | false |
allotria/intellij-community | platform/platform-api/src/com/intellij/openapi/ui/DialogPanel.kt | 2 | 3036 | // 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.openapi.ui
import com.intellij.openapi.Disposable
import com.intellij.ui.components.JBPanel
import java.awt.LayoutManager
import java.util.function.Supplier
import javax.swing.JComponent
import javax.swing.text.JTextComponent
/**
* @author yole
*/
class DialogPanel : JBPanel<DialogPanel> {
var preferredFocusedComponent: JComponent? = null
var validateCallbacks: List<() -> ValidationInfo?> = emptyList()
var componentValidateCallbacks: Map<JComponent, () -> ValidationInfo?> = emptyMap()
var customValidationRequestors: Map<JComponent, List<(() -> Unit) -> Unit>> = emptyMap()
var applyCallbacks: Map<JComponent?, List<() -> Unit>> = emptyMap()
var resetCallbacks: Map<JComponent?, List<() -> Unit>> = emptyMap()
var isModifiedCallbacks: Map<JComponent?, List<() -> Boolean>> = emptyMap()
private val componentValidationStatus = hashMapOf<JComponent, ValidationInfo>()
constructor() : super()
constructor(layout: LayoutManager?) : super(layout)
fun registerValidators(parentDisposable: Disposable, componentValidityChangedCallback: ((Map<JComponent, ValidationInfo>) -> Unit)? = null) {
for ((component, callback) in componentValidateCallbacks) {
val validator = ComponentValidator(parentDisposable).withValidator(Supplier {
val infoForComponent = callback()
if (componentValidationStatus[component] != infoForComponent) {
if (infoForComponent != null) {
componentValidationStatus[component] = infoForComponent
}
else {
componentValidationStatus.remove(component)
}
componentValidityChangedCallback?.invoke(componentValidationStatus)
}
infoForComponent
})
if (component is JTextComponent) {
validator.andRegisterOnDocumentListener(component)
}
registerCustomValidationRequestors(component, validator)
validator.installOn(component)
}
}
fun apply() {
for ((component, callbacks) in applyCallbacks.entries) {
if (component == null) continue
val modifiedCallbacks = isModifiedCallbacks.get(component)
if (modifiedCallbacks.isNullOrEmpty() || modifiedCallbacks.any { it() }) {
callbacks.forEach { it() }
}
}
applyCallbacks.get(null)?.forEach { it() }
}
fun reset() {
for ((component, callbacks) in resetCallbacks.entries) {
if (component == null) continue
callbacks.forEach { it() }
}
resetCallbacks.get(null)?.forEach { it() }
}
fun isModified(): Boolean {
return isModifiedCallbacks.values.any { list -> list.any { it() } }
}
private fun registerCustomValidationRequestors(component: JComponent, validator: ComponentValidator) {
for (onCustomValidationRequest in customValidationRequestors.get(component) ?: return) {
onCustomValidationRequest { validator.revalidate() }
}
}
}
| apache-2.0 | 88ea121e40129a95f784dd8c7fe943fd | 36.481481 | 143 | 0.702569 | 4.692427 | false | false | false | false |
Kotlin/kotlinx.coroutines | kotlinx-coroutines-core/common/src/internal/Scopes.kt | 1 | 1558 | /*
* 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 kotlinx.coroutines.*
import kotlin.coroutines.*
import kotlin.coroutines.intrinsics.*
import kotlin.jvm.*
/**
* This is a coroutine instance that is created by [coroutineScope] builder.
*/
internal open class ScopeCoroutine<in T>(
context: CoroutineContext,
@JvmField val uCont: Continuation<T> // unintercepted continuation
) : AbstractCoroutine<T>(context, true, true), CoroutineStackFrame {
final override val callerFrame: CoroutineStackFrame? get() = uCont as? CoroutineStackFrame
final override fun getStackTraceElement(): StackTraceElement? = null
final override val isScopedCoroutine: Boolean get() = true
internal val parent: Job? get() = parentHandle?.parent
override fun afterCompletion(state: Any?) {
// Resume in a cancellable way by default when resuming from another context
uCont.intercepted().resumeCancellableWith(recoverResult(state, uCont))
}
override fun afterResume(state: Any?) {
// Resume direct because scope is already in the correct context
uCont.resumeWith(recoverResult(state, uCont))
}
}
internal class ContextScope(context: CoroutineContext) : CoroutineScope {
override val coroutineContext: CoroutineContext = context
// CoroutineScope is used intentionally for user-friendly representation
override fun toString(): String = "CoroutineScope(coroutineContext=$coroutineContext)"
}
| apache-2.0 | 98cf99c944626989f753c4d8621e1db2 | 37 | 102 | 0.748395 | 4.899371 | false | false | false | false |
leafclick/intellij-community | platform/vcs-impl/src/com/intellij/openapi/vcs/impl/RepositoryBrowser.kt | 1 | 7002 | // 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.openapi.vcs.impl
import com.intellij.ide.impl.ContentManagerWatcher
import com.intellij.openapi.Disposable
import com.intellij.openapi.actionSystem.*
import com.intellij.openapi.fileChooser.FileChooserDescriptor
import com.intellij.openapi.fileChooser.ex.FileSystemTreeImpl
import com.intellij.openapi.fileEditor.FileEditorManager
import com.intellij.openapi.fileEditor.OpenFileDescriptor
import com.intellij.openapi.fileEditor.impl.LoadTextUtil
import com.intellij.openapi.fileTypes.FileTypeManager
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.Disposer
import com.intellij.openapi.vcs.FilePath
import com.intellij.openapi.vcs.RemoteFilePath
import com.intellij.openapi.vcs.VcsActions
import com.intellij.openapi.vcs.actions.VcsContextFactory
import com.intellij.openapi.vcs.changes.ByteBackedContentRevision
import com.intellij.openapi.vcs.changes.Change
import com.intellij.openapi.vcs.changes.ContentRevision
import com.intellij.openapi.vcs.changes.CurrentContentRevision
import com.intellij.openapi.vcs.changes.actions.diff.ShowDiffAction
import com.intellij.openapi.vcs.history.VcsRevisionNumber
import com.intellij.openapi.vcs.vfs.AbstractVcsVirtualFile
import com.intellij.openapi.vcs.vfs.VcsVirtualFile
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.openapi.wm.ToolWindow
import com.intellij.openapi.wm.ToolWindowAnchor
import com.intellij.openapi.wm.ToolWindowManager
import com.intellij.ui.ScrollPaneFactory
import com.intellij.ui.content.ContentFactory
import com.intellij.util.PlatformIcons
import java.awt.BorderLayout
import java.io.File
import javax.swing.Icon
import javax.swing.JPanel
const val TOOLWINDOW_ID = "Repositories"
fun showRepositoryBrowser(project: Project, root: AbstractVcsVirtualFile, localRoot: VirtualFile, title: String) {
val toolWindowManager = ToolWindowManager.getInstance(project)
val repoToolWindow = toolWindowManager.getToolWindow(TOOLWINDOW_ID) ?: registerRepositoriesToolWindow(toolWindowManager, project)
for (content in repoToolWindow.contentManager.contents) {
val component = content.component as? RepositoryBrowserPanel ?: continue
if (component.root == root) {
repoToolWindow.contentManager.setSelectedContent(content)
return
}
}
val contentPanel = RepositoryBrowserPanel(project, root, localRoot)
val content = ContentFactory.SERVICE.getInstance().createContent(contentPanel, title, true)
repoToolWindow.contentManager.addContent(content)
repoToolWindow.contentManager.setSelectedContent(content, true)
repoToolWindow.activate(null)
}
private fun registerRepositoriesToolWindow(toolWindowManager: ToolWindowManager, project: Project): ToolWindow {
val toolWindow = toolWindowManager.registerToolWindow(TOOLWINDOW_ID, true, ToolWindowAnchor.LEFT, project, true)
ContentManagerWatcher.watchContentManager(toolWindow, toolWindow.contentManager)
return toolWindow
}
val REPOSITORY_BROWSER_DATA_KEY = DataKey.create<RepositoryBrowserPanel>("com.intellij.openapi.vcs.impl.RepositoryBrowserPanel")
class RepositoryBrowserPanel(
val project: Project,
val root: AbstractVcsVirtualFile,
val localRoot: VirtualFile
) : JPanel(BorderLayout()), DataProvider, Disposable {
private val fileSystemTree: FileSystemTreeImpl
init {
val fileChooserDescriptor = object : FileChooserDescriptor(true, false, false, false, false, true) {
override fun getRoots(): List<VirtualFile> = listOf(root)
override fun getIcon(file: VirtualFile): Icon? {
if (file.isDirectory) {
return PlatformIcons.FOLDER_ICON
}
return FileTypeManager.getInstance().getFileTypeByFileName(file.nameSequence).icon
}
}
fileSystemTree = object : FileSystemTreeImpl(project, fileChooserDescriptor) {
@Suppress("OverridingDeprecatedMember")
override fun useNewAsyncModel() = true
}
fileSystemTree.addOkAction {
val files = fileSystemTree.selectedFiles
for (file in files) {
FileEditorManager.getInstance(project).openFile(file, true)
}
}
val actionGroup = DefaultActionGroup()
actionGroup.add(ActionManager.getInstance().getAction(IdeActions.ACTION_EDIT_SOURCE))
actionGroup.add(ActionManager.getInstance().getAction(VcsActions.DIFF_AFTER_WITH_LOCAL))
fileSystemTree.registerMouseListener(actionGroup)
val scrollPane = ScrollPaneFactory.createScrollPane(fileSystemTree.tree)
add(scrollPane, BorderLayout.CENTER)
}
override fun getData(dataId: String): Any? {
return when {
CommonDataKeys.VIRTUAL_FILE_ARRAY.`is`(dataId) -> fileSystemTree.selectedFiles
CommonDataKeys.NAVIGATABLE_ARRAY.`is`(dataId) ->
fileSystemTree.selectedFiles
.filter { !it.isDirectory }
.map { OpenFileDescriptor(project, it) }
.toTypedArray()
REPOSITORY_BROWSER_DATA_KEY.`is`(dataId) -> this
else -> null
}
}
override fun dispose() {
Disposer.dispose(fileSystemTree)
}
fun hasSelectedFiles() = fileSystemTree.selectedFiles.any { it is VcsVirtualFile }
fun getSelectionAsChanges(): List<Change> {
return fileSystemTree.selectedFiles
.filterIsInstance<VcsVirtualFile>()
.map { createChangeVsLocal(it) }
}
private fun createChangeVsLocal(file: VcsVirtualFile): Change {
val repoRevision = VcsVirtualFileContentRevision(file)
val localPath = File(localRoot.path, file.path)
val localRevision = CurrentContentRevision(VcsContextFactory.SERVICE.getInstance().createFilePathOn(localPath))
return Change(repoRevision, localRevision)
}
}
class DiffRepoWithLocalAction : AnActionExtensionProvider {
override fun isActive(e: AnActionEvent): Boolean {
return e.getData(REPOSITORY_BROWSER_DATA_KEY) != null
}
override fun update(e: AnActionEvent) {
val repoBrowser = e.getData(REPOSITORY_BROWSER_DATA_KEY) ?: return
e.presentation.isEnabled = repoBrowser.hasSelectedFiles()
}
override fun actionPerformed(e: AnActionEvent) {
val repoBrowser = e.getData(REPOSITORY_BROWSER_DATA_KEY) ?: return
val changes = repoBrowser.getSelectionAsChanges()
ShowDiffAction.showDiffForChange(repoBrowser.project, changes)
}
}
class VcsVirtualFileContentRevision(private val vcsVirtualFile: VcsVirtualFile) : ContentRevision, ByteBackedContentRevision {
override fun getContent(): String? {
return contentAsBytes?.let { LoadTextUtil.getTextByBinaryPresentation(it, vcsVirtualFile).toString() }
}
override fun getContentAsBytes(): ByteArray? {
return vcsVirtualFile.fileRevision?.loadContent()
}
override fun getFile(): FilePath {
return RemoteFilePath(vcsVirtualFile.path, vcsVirtualFile.isDirectory)
}
override fun getRevisionNumber(): VcsRevisionNumber {
return vcsVirtualFile.fileRevision?.revisionNumber ?: VcsRevisionNumber.NULL
}
} | apache-2.0 | 7e15c1227c1d7c731808e3cb1f81e675 | 39.247126 | 140 | 0.783776 | 4.766508 | false | false | false | false |
romannurik/muzei | android-client-common/src/main/java/com/google/android/apps/muzei/room/MuzeiDatabase.kt | 1 | 19866 | /*
* Copyright 2017 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.apps.muzei.room
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.database.sqlite.SQLiteConstraintException
import androidx.room.AutoMigration
import androidx.room.Database
import androidx.room.InvalidationTracker
import androidx.room.Room
import androidx.room.RoomDatabase
import androidx.room.migration.Migration
import androidx.sqlite.db.SupportSQLiteDatabase
import com.google.android.apps.muzei.api.MuzeiContract
import com.google.android.apps.muzei.provider.DirectBootCache
import java.io.File
/**
* Room Database for Muzei
*/
@Database(
entities = [(Artwork::class), (Provider::class)],
autoMigrations = [
AutoMigration(from = 4, to = 5)
],
version = 9
)
abstract class MuzeiDatabase : RoomDatabase() {
abstract fun providerDao(): ProviderDao
abstract fun artworkDao(): ArtworkDao
companion object {
@Volatile
private var instance: MuzeiDatabase? = null
fun getInstance(context: Context): MuzeiDatabase {
val applicationContext = context.applicationContext
return instance ?: synchronized(this) {
instance ?: Room.databaseBuilder(applicationContext,
MuzeiDatabase::class.java, "muzei.db")
.addMigrations(
MIGRATION_1_2,
MIGRATION_2_3,
MIGRATION_3_4,
MIGRATION_5_6,
Migration6to8(applicationContext),
Migration7to8(applicationContext),
MIGRATION_8_9)
.build().also { database ->
database.invalidationTracker.addObserver(
object : InvalidationTracker.Observer("artwork") {
@Suppress("DEPRECATION")
override fun onInvalidated(tables: Set<String>) {
DirectBootCache.onArtworkChanged(applicationContext)
applicationContext.contentResolver
.notifyChange(MuzeiContract.Artwork.CONTENT_URI, null)
applicationContext.sendBroadcast(
Intent(MuzeiContract.Artwork.ACTION_ARTWORK_CHANGED))
}
}
)
database.invalidationTracker.addObserver(
object : InvalidationTracker.Observer("provider") {
@Suppress("DEPRECATION")
override fun onInvalidated(tables: Set<String>) {
applicationContext.contentResolver
.notifyChange(MuzeiContract.Sources.CONTENT_URI, null)
// First send a targeted broadcast just to ourselves
applicationContext.sendBroadcast(
Intent(MuzeiContract.Sources.ACTION_SOURCE_CHANGED).apply {
`package` = applicationContext.packageName
})
// Now send another broadcast to other apps listening
// (it is expected that our own listener filters
// these second calls out)
applicationContext.sendBroadcast(
Intent(MuzeiContract.Sources.ACTION_SOURCE_CHANGED))
}
}
)
instance = database
}
}
}
private val MIGRATION_1_2 = object : Migration(1, 2) {
override fun migrate(database: SupportSQLiteDatabase) {
// NO-OP
}
}
private val MIGRATION_2_3 = object : Migration(2, 3) {
override fun migrate(database: SupportSQLiteDatabase) {
// We can't ALTER TABLE to add a foreign key and we wouldn't know what the FK should be
// at this point anyways so we'll wipe and recreate the artwork table
database.execSQL("DROP TABLE artwork")
database.execSQL("CREATE TABLE sources ("
+ "_id INTEGER PRIMARY KEY AUTOINCREMENT,"
+ "component_name TEXT,"
+ "selected INTEGER,"
+ "description TEXT,"
+ "network INTEGER,"
+ "supports_next_artwork INTEGER,"
+ "commands TEXT);")
database.execSQL("CREATE TABLE artwork ("
+ "_id INTEGER PRIMARY KEY AUTOINCREMENT,"
+ "sourceComponentName TEXT,"
+ "imageUri TEXT,"
+ "title TEXT,"
+ "byline TEXT,"
+ "attribution TEXT,"
+ "token TEXT,"
+ "metaFont TEXT,"
+ "date_added INTEGER,"
+ "viewIntent TEXT,"
+ " CONSTRAINT fk_source_artwork FOREIGN KEY "
+ "(sourceComponentName) REFERENCES "
+ "sources (component_name) ON DELETE CASCADE);")
}
}
private val MIGRATION_3_4 = object : Migration(3, 4) {
override fun migrate(database: SupportSQLiteDatabase) {
// Handle Sources
database.execSQL("UPDATE sources "
+ "SET network = 0 "
+ "WHERE network IS NULL")
database.execSQL("UPDATE sources "
+ "SET supports_next_artwork = 0 "
+ "WHERE supports_next_artwork IS NULL")
database.execSQL("UPDATE sources "
+ "SET commands = \"\" "
+ "WHERE commands IS NULL")
database.execSQL("CREATE TABLE sources2 ("
+ "_id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,"
+ "component_name TEXT UNIQUE NOT NULL,"
+ "selected INTEGER NOT NULL,"
+ "description TEXT,"
+ "network INTEGER NOT NULL,"
+ "supports_next_artwork INTEGER NOT NULL,"
+ "commands TEXT NOT NULL);")
try {
database.execSQL("INSERT INTO sources2 SELECT * FROM sources")
} catch (e: SQLiteConstraintException) {
// Wtf, multiple sources with the same component_name? Mkay
// Just move over the component_name and selected flag then
database.execSQL("INSERT INTO sources2 " +
"(component_name, selected, network, supports_next_artwork, commands) "
+ "SELECT component_name, MAX(selected), "
+ "0 AS network, 0 AS supports_next_artwork, '' as commands "
+ "FROM sources GROUP BY component_name")
}
database.execSQL("DROP TABLE sources")
database.execSQL("ALTER TABLE sources2 RENAME TO sources")
database.execSQL("CREATE UNIQUE INDEX index_sources_component_name " + "ON sources (component_name)")
// Handle Artwork
database.execSQL("UPDATE artwork "
+ "SET metaFont = \"\" "
+ "WHERE metaFont IS NULL")
database.execSQL("CREATE TABLE artwork2 ("
+ "_id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,"
+ "sourceComponentName TEXT,"
+ "imageUri TEXT,"
+ "title TEXT,"
+ "byline TEXT,"
+ "attribution TEXT,"
+ "token TEXT,"
+ "metaFont TEXT NOT NULL,"
+ "date_added INTEGER NOT NULL,"
+ "viewIntent TEXT,"
+ " CONSTRAINT fk_source_artwork FOREIGN KEY "
+ "(sourceComponentName) REFERENCES "
+ "sources (component_name) ON DELETE CASCADE);")
database.execSQL("INSERT INTO artwork2 " + "SELECT * FROM artwork")
database.execSQL("DROP TABLE artwork")
database.execSQL("ALTER TABLE artwork2 RENAME TO artwork")
database.execSQL("CREATE INDEX index_Artwork_sourceComponentName " + "ON artwork (sourceComponentName)")
}
}
private val MIGRATION_5_6 = object : Migration(5, 6) {
override fun migrate(database: SupportSQLiteDatabase) {
// Handle Source
database.execSQL("CREATE TABLE sources2 ("
+ "component_name TEXT PRIMARY KEY NOT NULL,"
+ "label TEXT,"
+ "defaultDescription TEXT,"
+ "description TEXT,"
+ "color INTEGER NOT NULL,"
+ "targetSdkVersion INTEGER NOT NULL,"
+ "settingsActivity TEXT, "
+ "setupActivity TEXT,"
+ "selected INTEGER NOT NULL,"
+ "wantsNetworkAvailable INTEGER NOT NULL,"
+ "supportsNextArtwork INTEGER NOT NULL,"
+ "commands TEXT NOT NULL)")
database.execSQL("INSERT INTO sources2"
+ "(component_name, description, color, targetSdkVersion, selected, "
+ "wantsNetworkAvailable, supportsNextArtwork, commands) "
+ "SELECT component_name, description, 0, 0, selected, "
+ "network, supports_next_artwork, commands "
+ "FROM sources")
database.execSQL("DROP TABLE sources")
database.execSQL("ALTER TABLE sources2 RENAME TO sources")
}
}
/**
* Skip directly from version 6 to 8, avoiding the intermediate database version
* 7 which used the provider's ComponentName as the key.
*/
private class Migration6to8(private val context: Context) : Migration(6, 8) {
override fun migrate(database: SupportSQLiteDatabase) {
// Handle Provider
database.execSQL("CREATE TABLE provider ("
+ "authority TEXT PRIMARY KEY NOT NULL,"
+ "supportsNextArtwork INTEGER NOT NULL)")
// Try to populate the provider table with an initial provider
// by seeing if the current source has a replacement provider available
try {
database.query("SELECT component_name FROM sources WHERE selected=1").use { selectedSource ->
if (selectedSource.moveToFirst()) {
val componentName = ComponentName.unflattenFromString(
selectedSource.getString(0))!!
@Suppress("DEPRECATION")
val info = context.packageManager.getServiceInfo(componentName,
PackageManager.GET_META_DATA)
val metadata = info.metaData
if (metadata != null) {
val replacement = metadata.getString("replacement")
if (replacement != null && replacement.isNotEmpty()) {
@Suppress("DEPRECATION")
val providerInfo = context.packageManager
.resolveContentProvider(replacement, 0) ?: run {
ComponentName.unflattenFromString(
"${info.packageName}/$replacement")?.run {
context.packageManager
.getProviderInfo(this, 0)
}
}
if (providerInfo != null) {
database.execSQL("INSERT INTO provider " +
"(authority, supportsNextArtwork) "
+ "VALUES (?, ?)",
arrayOf(providerInfo.authority, false))
}
}
}
}
}
} catch (e: PackageManager.NameNotFoundException) {
// Couldn't find the selected source, so there's nothing more to do
}
// Handle Artwork
database.execSQL("DROP TABLE artwork")
database.execSQL("CREATE TABLE artwork ("
+ "_id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,"
+ "providerAuthority TEXT NOT NULL,"
+ "imageUri TEXT NOT NULL,"
+ "title TEXT,"
+ "byline TEXT,"
+ "attribution TEXT,"
+ "metaFont TEXT NOT NULL,"
+ "date_added INTEGER NOT NULL)")
database.execSQL("CREATE INDEX index_Artwork_providerAuthority " + "ON artwork (providerAuthority)")
// Delete previously cached artwork - providers now cache their own artwork
val artworkDirectory = File(context.filesDir, "artwork")
artworkDirectory.delete()
}
}
/**
* Handle the migration from the intermediate database version 7, which
* used the ComponentName of the provider as the unique key
*/
private class Migration7to8(private val context: Context) :
Migration(7, 8) {
override fun migrate(database: SupportSQLiteDatabase) {
// Handle Provider
database.execSQL("CREATE TABLE provider2 ("
+ "authority TEXT PRIMARY KEY NOT NULL,"
+ "supportsNextArtwork INTEGER NOT NULL)")
try {
database.query("SELECT componentName, supportsNextArtwork FROM provider").use {
selectedProvider ->
if (selectedProvider.moveToFirst()) {
val componentName = ComponentName.unflattenFromString(
selectedProvider.getString(0))!!
val supportsNextArtwork = selectedProvider.getInt(1)
@Suppress("DEPRECATION")
val info = context.packageManager.getProviderInfo(componentName, 0)
database.execSQL("INSERT INTO provider2 " +
"(authority, supportsNextArtwork) "
+ "VALUES (?, ?)",
arrayOf(info.authority, supportsNextArtwork))
}
}
} catch (e: PackageManager.NameNotFoundException) {
// Couldn't find the selected provider, so there's nothing more to do
}
database.execSQL("DROP TABLE provider")
database.execSQL("ALTER TABLE provider2 RENAME TO provider")
// Handle Artwork
database.execSQL("CREATE TABLE artwork2 ("
+ "_id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,"
+ "providerAuthority TEXT NOT NULL,"
+ "imageUri TEXT NOT NULL,"
+ "title TEXT,"
+ "byline TEXT,"
+ "attribution TEXT,"
+ "metaFont TEXT NOT NULL,"
+ "date_added INTEGER NOT NULL)")
database.query("SELECT _id, providerComponentName, imageUri, " +
"title, byline, attribution, metaFont, date_added FROM artwork").use{ artwork ->
while (artwork.moveToNext()) {
val id = artwork.getLong(0)
val componentName = ComponentName.unflattenFromString(
artwork.getString(1))!!
val imageUri = artwork.getString(2)
val title = artwork.getString(3)
val byline = artwork.getString(4)
val attribution = artwork.getString(5)
val metaFont = artwork.getString(6)
val dateAdded = artwork.getLong(7)
try {
@Suppress("DEPRECATION")
val info = context.packageManager.getProviderInfo(componentName, 0)
database.execSQL("INSERT INTO artwork2 " +
"(_id, providerAuthority, imageUri, " +
"title, byline, attribution, metaFont, date_added) "
+ "VALUES (?, ?, ?, ?, ?, ?, ?, ?)",
arrayOf(id, info.authority, imageUri, title,
byline, attribution, metaFont, dateAdded))
} catch (e: PackageManager.NameNotFoundException) {
// Couldn't find the provider, so there's nothing more to do
}
}
}
database.execSQL("DROP TABLE artwork")
database.execSQL("ALTER TABLE artwork2 RENAME TO artwork")
database.execSQL("CREATE INDEX index_Artwork_providerAuthority " + "ON artwork (providerAuthority)")
}
}
private val MIGRATION_8_9 = object : Migration(8, 9) {
override fun migrate(database: SupportSQLiteDatabase) {
// Drop the legacy source table
database.execSQL("DROP TABLE sources")
}
}
}
} | apache-2.0 | 5efb5cd70fae25f25c6e99506e3cf463 | 51.697613 | 120 | 0.474328 | 6.458388 | false | false | false | false |
TheAnonymous/Redo | app/src/main/java/com/redo/redo/MainList.kt | 1 | 10116 | package com.redo.redo
import android.app.ActionBar
import android.app.Activity
import android.app.AlertDialog
import android.content.DialogInterface
import android.content.Intent
import android.os.Bundle
import android.os.Environment
import android.util.Log
import android.view.Menu
import android.view.MenuItem
import android.view.View
import android.view.ViewGroup
import android.widget.*
import java.io.File
import java.io.FileInputStream
import java.io.FileOutputStream
import java.io.IOException
import java.io.ObjectInputStream
import java.io.ObjectOutputStream
import java.util.ArrayList
import java.util.Calendar
import java.util.Date
public class MainList : Activity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main_list)
val intent = getIntent()
val app = getApplicationContext() as MyApp
if (app.reminders != null)
for (i in app.reminders.indices) {
val tmp = app.reminders.get(i)
addItem(tmp.name, tmp.type, tmp.delay, tmp.lastTimeDone)
}
else {
app.reminders = ArrayList<Reminder>()
}
if (intent.getExtras() != null) {
val bundle = intent.getExtras()
if (bundle.getString("delay") != null) {
Log.i("BUNDLE", bundle.toString())
val delay = Integer.parseInt(bundle.getString("delay"))
Log.i("Delay", bundle.getString("delay"))
val name = bundle.getString("name")
Log.i("Name", name)
val type = bundle.getString("type")
Log.i("Type", type)
val r = Reminder()
r.delay = delay
r.lastTimeDone = Calendar.getInstance().getTime().getTime()
r.name = name
r.type = type
app.reminders.add(r)
addItem(name, type, delay, Calendar.getInstance().getTime().getTime())
saveState(app.reminders)
} else {
Log.i("GOING_TO_LOADING", "-------->bundle.getString(\"delay\") != null")
val tablelayout = findViewById(R.id.tableLayout) as TableLayout
tablelayout.removeAllViews()
app.reminders = loadReminders()
for (i in app.reminders.indices) {
val tmp = app.reminders.get(i)
addItem(tmp.name, tmp.type, tmp.delay, tmp.lastTimeDone)
}
}
} else {
Log.i("GOING_TO_LOADING", "-------->intent.getExtras() != null")
val tablelayout = findViewById(R.id.tableLayout) as TableLayout
tablelayout.removeAllViews()
app.reminders = loadReminders()
if (app.reminders == null) {
app.reminders = ArrayList<Reminder>()
}
for (i in app.reminders.indices) {
val tmp = app.reminders.get(i)
addItem(tmp.name, tmp.type, tmp.delay, tmp.lastTimeDone)
}
}
}
public fun loadReminders(): ArrayList<Reminder> {
Log.i("INSIDE_LOADING", "<===>")
val sdcard = Environment.getExternalStorageDirectory()
val f = File(sdcard, "reminders.ser")
var ois: ObjectInputStream? = null
try {
ois = ObjectInputStream(FileInputStream(f))
} catch (e: IOException) {
e.printStackTrace()
}
try {
if (ois != null) {
val o = ois.readObject() as ArrayList<Reminder>
if (o != null) {
Log.i("ARRAYSIZE", Integer.toString(o.size()))
} else {
Log.i("ARRAYSIZE", "--------->NULL")
}
return o
}
} catch (e: ClassNotFoundException) {
e.printStackTrace()
} catch (e: IOException) {
e.printStackTrace()
}
return ArrayList<Reminder>()
}
public fun saveState(reminders: ArrayList<Reminder>) {
try {
val sdcard = Environment.getExternalStorageDirectory()
val file = File(sdcard, "reminders.ser")
val fileOut = FileOutputStream(file)
val out = ObjectOutputStream(fileOut)
out.writeObject(reminders)
out.close()
fileOut.close()
Log.i("saveState", "Serialized data is saved in /tmp/employee.ser")
} catch (i: IOException) {
i.printStackTrace()
}
}
public fun removeItemDialog(pb: ProgressBar, tv1: TextView, tv2: TextView, tl: TableLayout, id: Int) {
val dialogClickListener = object : DialogInterface.OnClickListener {
override fun onClick(dialog: DialogInterface, which: Int) {
val app = getApplicationContext() as MyApp
when (which) {
DialogInterface.BUTTON_POSITIVE -> {
//Done button clicked
app.reminders = loadReminders()
val rem = app.reminders.get(id)
app.reminders.set(id, Reminder(rem.name, rem.type, rem.delay, Date().getTime()))
saveState(app.reminders)
tl.removeAllViews()
app.reminders = loadReminders()
for (i in app.reminders.indices) {
val tmp = app.reminders.get(i)
addItem(tmp.name, tmp.type, tmp.delay, tmp.lastTimeDone)
}
}
DialogInterface.BUTTON_NEGATIVE -> {
//Remove button clicked
tl.removeView(pb)
tl.removeView(tv1)
tl.removeView(tv2)
app.reminders.remove(id)
saveState(app.reminders)
tl.removeAllViews()
app.reminders = loadReminders()
for (i in app.reminders.indices) {
val tmp = app.reminders.get(i)
addItem(tmp.name, tmp.type, tmp.delay, tmp.lastTimeDone)
}
}
}
}
}
val builder = AlertDialog.Builder(this)
builder.setMessage("Done task or remove reminder?").setPositiveButton("Done", dialogClickListener).setNegativeButton("Remove", dialogClickListener).show()
}
public fun addItem(name: String, type: String, delay: Int?, date: Long) {
//Debug
Log.d("TimePassedInPercentage", Integer.toString(TimeCalculator.TimePassedInPercentage(date, delay!!, type)))
Log.d("TimeLeftSentence", TimeCalculator.TimeLeftSentence(date, delay, type))
//Initaliaize
val tablelayout = findViewById(R.id.tableLayout) as TableLayout
val tvlabel = TextView(this)
val tvtime = TextView(this)
val pbprogress = ProgressBar(this, null, android.R.attr.progressBarStyleHorizontal)
val app = getApplicationContext() as MyApp
val id = app.reminders.size() - 1
LinearLayout.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)
val trparams = TableRow.LayoutParams(-1, -2)
//Set First Labe with name etc.
tvlabel.setText(name + " - every " + delay.toString() + " " + type)
tvlabel.setTextAppearance(this, android.R.style.TextAppearance_DeviceDefault_Medium)
tvlabel.setLayoutParams( trparams)
tvlabel.setOnLongClickListener(object : View.OnLongClickListener {
override fun onLongClick(v: View): Boolean {
removeItemDialog(pbprogress, tvlabel, tvtime, tablelayout, id)
return false
}
})
//SetProgressbar
pbprogress.setProgress(TimeCalculator.TimePassedInPercentage(date, delay, type))
pbprogress.setLayoutParams(trparams)
pbprogress.setOnLongClickListener(object : View.OnLongClickListener {
override fun onLongClick(v: View): Boolean {
removeItemDialog(pbprogress, tvlabel, tvtime, tablelayout, id)
return true
}
})
//Set Time left
tvtime.setTextAppearance(this, android.R.style.TextAppearance_DeviceDefault_Small)
tvtime.setLayoutParams(trparams)
tvtime.setText(TimeCalculator.TimeLeftSentence(date, delay, type))
tvtime.setOnLongClickListener(object : View.OnLongClickListener {
override fun onLongClick(v: View): Boolean {
removeItemDialog(pbprogress, tvlabel, tvtime, tablelayout, id)
return false
}
})
//Add to List
tablelayout.addView(tvlabel)
tablelayout.addView(pbprogress)
tablelayout.addView(tvtime)
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main_list, menu)
return true
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
val id = item.getItemId()
//noinspection SimplifiableIfStatement
if (id == R.id.action_add) {
AddReminder()
return true
}
// Handle presses on the action bar items
when (item.getItemId()) {
R.id.action_add -> {
AddReminder()
return true
}
else -> return super.onOptionsItemSelected(item)
}
}
public fun AddReminder() {
val myIntent = Intent(this, javaClass<Add>())
startActivity(myIntent)
}
}
| gpl-3.0 | 6a7944b87ba110a016fb759735775cf2 | 36.328413 | 162 | 0.566331 | 4.837877 | false | false | false | false |
JuliusKunze/kotlin-native | backend.native/tests/external/codegen/box/properties/substituteJavaSuperField.kt | 2 | 491 | // TODO: muted automatically, investigate should it be ran for JS or not
// IGNORE_BACKEND: JS, NATIVE
// FILE: Test.java
public abstract class Test<F> {
protected final F value = null;
}
// FILE: test.kt
// See KT-5445: Bad access to protected data in getfield
class A : Test<String>() {
fun foo(): String? = value
fun bar(): String? = this.value
}
fun box(): String {
if (A().foo() != null) return "Fail 1"
if (A().bar() != null) return "Fail 2"
return "OK"
}
| apache-2.0 | e22059638d3b1e9300cbf57fdddf73d5 | 21.318182 | 72 | 0.623218 | 3.251656 | false | true | false | false |
deeplearning4j/deeplearning4j | platform-tests/src/test/kotlin/org/eclipse/deeplearning4j/frameworkimport/frameworkimport/onnx/TestOnnxIR.kt | 1 | 94080 | /*
* ******************************************************************************
* *
* *
* * This program and the accompanying materials are made available under the
* * terms of the Apache License, Version 2.0 which is available at
* * https://www.apache.org/licenses/LICENSE-2.0.
* *
* * See the NOTICE file distributed with this work for additional
* * information regarding copyright ownership.
* * Unless required by applicable law or agreed to in writing, software
* * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* * License for the specific language governing permissions and limitations
* * under the License.
* *
* * SPDX-License-Identifier: Apache-2.0
* *****************************************************************************
*/
package org.eclipse.deeplearning4j.frameworkimport.frameworkimport.onnx
import onnx.Onnx
import org.eclipse.deeplearning4j.modelimport.onnx.OnnxTestUtils
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.Disabled
import org.junit.jupiter.api.Tag
import org.junit.jupiter.api.Test
import org.nd4j.autodiff.samediff.SameDiff
import org.nd4j.autodiff.samediff.config.SDValue
import org.nd4j.common.tests.tags.TagNames
import org.nd4j.common.util.ArrayUtil
import org.nd4j.linalg.api.buffer.DataType
import org.nd4j.linalg.api.ndarray.INDArray
import org.nd4j.linalg.factory.Nd4j
import org.nd4j.linalg.factory.ops.NDBitwise
import org.nd4j.samediff.frameworkimport.ImportGraph
import org.nd4j.samediff.frameworkimport.onnx.*
import org.nd4j.samediff.frameworkimport.onnx.definitions.OnnxOpDeclarations
import org.nd4j.samediff.frameworkimport.onnx.definitions.registry
import org.nd4j.samediff.frameworkimport.onnx.ir.OnnxIRGraph
import org.nd4j.samediff.frameworkimport.onnx.ir.OnnxIRGraphRunner
import kotlin.test.assertTrue
data class OnnxGraphInput(val graphDef: Onnx.GraphProto, val inputNames: List<String>, val outputNames: List<String>,
val inputArrays: Map<String, INDArray>, val dynamicArrays: Map<String, INDArray>)
@Tag(TagNames.ONNX)
@Disabled
class TestOnnxIR {
val declarations = OnnxOpDeclarations
@Test
fun testSequenceConstruct() {
Nd4j.getExecutioner().enableVerboseMode(true)
Nd4j.getExecutioner().enableDebugMode(true)
val onnxOpRegistry = registry()
val importGraph = ImportGraph<Onnx.GraphProto,Onnx.NodeProto,Onnx.NodeProto,Onnx.TensorProto,Onnx.AttributeProto,Onnx.AttributeProto,Onnx.TensorProto.DataType>()
val inputTensor = Nd4j.linspace(0,25,25).reshape(1,1,5,5).castTo(DataType.FLOAT)
val w = Nd4j.ones(1,1,3,3).castTo(DataType.FLOAT)
val graphToRun = GraphProto {
Input(createValueInfoFromTensor(inputTensor,"x",true))
Input(createValueInfoFromTensor(w,"W",true))
//Initializer(convertedTensor)
Node(NodeProto {
Input("x")
Input("W")
Output("y")
name = "y"
opType = "SequenceConstruct"
})
Output(createSequenceValueInfoFromTensors(arrayOf(inputTensor),"y",false))
}
val onnxIRGraph = OnnxIRGraph(graphToRun,onnxOpRegistry)
val onnxGraphRunner = OnnxIRGraphRunner(onnxIRGraph,listOf("x","W"),listOf("y"))
val importedGraph = importGraph.importGraph(onnxIRGraph,null,null, convertToOnnxTensors(mutableMapOf("W" to w,"x" to inputTensor)),onnxOpRegistry)
val inputs = mapOf("x" to arrayOf(inputTensor),"W" to arrayOf(w))
val inputs2 = mapOf("x" to SDValue.create(inputTensor),"W" to SDValue.create(w))
val assertion = onnxGraphRunner.runSequence(inputs2)
val result = importedGraph.outputValues(inputs2,listOf("y"))
//assert equals doesn't know how to deal with arrays within maps
assertEquals(assertion["y"],result["y"])
}
@Test
fun testSequenceErase() {
Nd4j.getExecutioner().enableVerboseMode(true)
Nd4j.getExecutioner().enableDebugMode(true)
val onnxOpRegistry = registry()
val importGraph = ImportGraph<Onnx.GraphProto,Onnx.NodeProto,Onnx.NodeProto,Onnx.TensorProto,Onnx.AttributeProto,Onnx.AttributeProto,Onnx.TensorProto.DataType>()
val inputTensor = Nd4j.linspace(0,25,25).reshape(1,1,5,5).castTo(DataType.FLOAT)
val insert = Nd4j.ones(DataType.FLOAT,1)
val w = Nd4j.ones(1,1,3,3).castTo(DataType.FLOAT)
val index = Nd4j.ones(1).castTo(DataType.INT32)
val indexTwo = Nd4j.ones(1).castTo(DataType.INT32)
val graphToRun = GraphProto {
Input(createValueInfoFromTensor(inputTensor,"x",true))
Input(createValueInfoFromTensor(w,"W",true))
Input(createValueInfoFromTensor(insert,"insert",true))
Input(createValueInfoFromTensor(index,"index",true))
Input(createValueInfoFromTensor(indexTwo,"indexTwo",true))
Node(NodeProto {
Input("x")
Input("W")
Output("y")
name = "y"
opType = "SequenceConstruct"
})
Node(NodeProto {
Input("y")
Input("indexTwo")
Output("sequenceInsert")
name = "sequenceInsert"
opType = "SequenceErase"
})
Node(NodeProto {
Input("y")
Input("index")
Output("sequenceAt")
name = "sequenceAt"
opType = "SequenceAt"
})
Output(createValueInfoFromTensor(inputTensor,"sequenceAt",false))
}
val onnxIRGraph = OnnxIRGraph(graphToRun,onnxOpRegistry)
val onnxGraphRunner = OnnxIRGraphRunner(onnxIRGraph,listOf("x","W","index","indexTwo","insert"),listOf("sequenceAt"))
val importedGraph = importGraph.importGraph(onnxIRGraph,null,null, convertToOnnxTensors(mutableMapOf(
"W" to w,"x" to inputTensor,"index" to index,"indexTwo" to indexTwo,"insert" to insert)),onnxOpRegistry)
println(importedGraph.summary())
val inputs = mapOf("x" to arrayOf(inputTensor),"W" to arrayOf(w),"index" to arrayOf(index),"indexTwo" to arrayOf(indexTwo),"insert" to arrayOf(insert))
val inputs2 = mapOf("x" to SDValue.create(inputTensor)
,"W" to SDValue.create(w),
"index" to SDValue.create(index),
"indexTwo" to SDValue.create(indexTwo),"insert" to SDValue.create(insert))
val assertion = onnxGraphRunner.runSequence(inputs2)
val result = importedGraph.outputValues(inputs2,listOf("sequenceAt"))
//assert equals doesn't know how to deal with arrays within maps
assertEquals(assertion["sequenceAt"],result["sequenceAt"])
}
@Test
fun testSequenceInsert() {
Nd4j.getExecutioner().enableVerboseMode(true)
Nd4j.getExecutioner().enableDebugMode(true)
val onnxOpRegistry = registry()
val importGraph = ImportGraph<Onnx.GraphProto,Onnx.NodeProto,Onnx.NodeProto,Onnx.TensorProto,Onnx.AttributeProto,Onnx.AttributeProto,Onnx.TensorProto.DataType>()
val inputTensor = Nd4j.linspace(0,25,25).reshape(1,1,5,5).castTo(DataType.FLOAT)
val insert = Nd4j.ones(DataType.FLOAT,1)
val w = Nd4j.ones(1,1,3,3).castTo(DataType.FLOAT)
val index = Nd4j.ones(1).castTo(DataType.INT32)
val indexTwo = Nd4j.ones(1).castTo(DataType.INT32).addi(1)
val graphToRun = GraphProto {
Input(createValueInfoFromTensor(inputTensor,"x",true))
Input(createValueInfoFromTensor(w,"W",true))
Input(createValueInfoFromTensor(insert,"insert",true))
Input(createValueInfoFromTensor(index,"index",true))
Input(createValueInfoFromTensor(indexTwo,"indexTwo",true))
Node(NodeProto {
Input("x")
Input("W")
Output("y")
name = "y"
opType = "SequenceConstruct"
})
Node(NodeProto {
Input("y")
Input("insert")
Input("indexTwo")
Output("sequenceInsert")
name = "sequenceInsert"
opType = "SequenceInsert"
})
Node(NodeProto {
Input("y")
Input("index")
Output("sequenceAt")
name = "sequenceAt"
opType = "SequenceAt"
})
Output(createValueInfoFromTensor(inputTensor,"sequenceAt",false))
}
val onnxIRGraph = OnnxIRGraph(graphToRun,onnxOpRegistry)
val onnxGraphRunner = OnnxIRGraphRunner(onnxIRGraph,listOf("x","W","index","indexTwo","insert"),listOf("sequenceAt"))
val importedGraph = importGraph.importGraph(onnxIRGraph,null,null, convertToOnnxTensors(mutableMapOf(
"W" to w,"x" to inputTensor,"index" to index,"indexTwo" to indexTwo,"insert" to insert)),onnxOpRegistry)
println(importedGraph.summary())
val inputs = mapOf("x" to arrayOf(inputTensor),"W" to arrayOf(w),"index" to arrayOf(index),"indexTwo" to arrayOf(indexTwo),"insert" to arrayOf(insert))
val inputs2 = mapOf("x" to SDValue.create(inputTensor),"W" to
SDValue.create(w),"index" to SDValue.create(index),"indexTwo" to SDValue.create(indexTwo),
"insert" to SDValue.create(insert))
val assertion = onnxGraphRunner.runSequence(inputs2)
val result = importedGraph.outputValues(inputs2,listOf("sequenceAt"))
//assert equals doesn't know how to deal with arrays within maps
assertEquals(assertion["sequenceAt"],result["sequenceAt"])
}
@Test
fun testSequenceLength() {
Nd4j.getExecutioner().enableVerboseMode(true)
Nd4j.getExecutioner().enableDebugMode(true)
val onnxOpRegistry = registry()
val importGraph = ImportGraph<Onnx.GraphProto,Onnx.NodeProto,Onnx.NodeProto,Onnx.TensorProto,Onnx.AttributeProto,Onnx.AttributeProto,Onnx.TensorProto.DataType>()
val inputTensor = Nd4j.linspace(0,25,25).reshape(1,1,5,5).castTo(DataType.FLOAT)
val w = Nd4j.ones(1,1,3,3).castTo(DataType.FLOAT)
val graphToRun = GraphProto {
Input(createValueInfoFromTensor(inputTensor,"x",true))
Input(createValueInfoFromTensor(w,"W",true))
Node(NodeProto {
Input("x")
Input("W")
Output("y")
name = "y"
opType = "SequenceConstruct"
})
Node(NodeProto {
Input("y")
Output("sequenceLength")
name = "sequenceLength"
opType = "SequenceLength"
})
Output(createValueInfoFromTensor(inputTensor.castTo(DataType.INT64),"sequenceLength",false))
}
val onnxIRGraph = OnnxIRGraph(graphToRun,onnxOpRegistry)
val onnxGraphRunner = OnnxIRGraphRunner(onnxIRGraph,listOf("x","W"),listOf("sequenceLength"))
val importedGraph = importGraph.importGraph(onnxIRGraph,null,null, convertToOnnxTensors(mutableMapOf(
"W" to w,"x" to inputTensor)),onnxOpRegistry)
println(importedGraph.summary())
val inputs = mapOf("x" to arrayOf(inputTensor),"W" to arrayOf(w))
val inputs2 = mapOf("x" to SDValue.create(inputTensor),"W" to SDValue.create(w))
val assertion = onnxGraphRunner.runSequence(inputs2)
val result = importedGraph.outputValues(inputs2,listOf("sequenceLength"))
val assertionArr = assertion["sequenceLength"]!!
val resultArr = assertion["sequenceLength"]!!
//assert equals doesn't know how to deal with arrays within maps
assertEquals(assertionArr,resultArr)
}
@Test
fun testSequenceAt() {
Nd4j.getExecutioner().enableVerboseMode(true)
Nd4j.getExecutioner().enableDebugMode(true)
val onnxOpRegistry = registry()
val importGraph = ImportGraph<Onnx.GraphProto,Onnx.NodeProto,Onnx.NodeProto,Onnx.TensorProto,Onnx.AttributeProto,Onnx.AttributeProto,Onnx.TensorProto.DataType>()
val inputTensor = Nd4j.linspace(0,25,25).reshape(1,1,5,5).castTo(DataType.FLOAT)
val w = Nd4j.ones(1,1,3,3).castTo(DataType.FLOAT)
val index = Nd4j.ones(1).castTo(DataType.INT32)
val graphToRun = GraphProto {
Input(createValueInfoFromTensor(inputTensor,"x",true))
Input(createValueInfoFromTensor(w,"W",true))
Input(createValueInfoFromTensor(index,"index",true))
Node(NodeProto {
Input("x")
Input("W")
Output("y")
name = "y"
opType = "SequenceConstruct"
})
Node(NodeProto {
Input("y")
Input("index")
Output("sequenceAt")
name = "sequenceAt"
opType = "SequenceAt"
})
Output(createValueInfoFromTensor(inputTensor,"sequenceAt",false))
}
val onnxIRGraph = OnnxIRGraph(graphToRun,onnxOpRegistry)
val onnxGraphRunner = OnnxIRGraphRunner(onnxIRGraph,listOf("x","W"),listOf("sequenceAt"))
val importedGraph = importGraph.importGraph(onnxIRGraph,null,null, convertToOnnxTensors(mutableMapOf("W" to w,"x" to inputTensor,"index" to index)),onnxOpRegistry)
println(importedGraph.summary())
val inputs = mapOf("x" to arrayOf(inputTensor),"W" to arrayOf(w),"index" to arrayOf(index))
val inputs2 = mapOf("x" to SDValue.create(inputTensor),"W" to SDValue.create(w),"index" to SDValue.create(index))
val assertion = onnxGraphRunner.runSequence(inputs2)
val result = importedGraph.outputValues(inputs2,listOf("sequenceAt"))
//assert equals doesn't know how to deal with arrays within maps
assertEquals(assertion["sequenceAt"],result["sequenceAt"])
}
@Test
fun testSequenceRemove() {
Nd4j.getExecutioner().enableVerboseMode(true)
Nd4j.getExecutioner().enableDebugMode(true)
val onnxOpRegistry = registry()
val importGraph = ImportGraph<Onnx.GraphProto,Onnx.NodeProto,Onnx.NodeProto,Onnx.TensorProto,Onnx.AttributeProto,Onnx.AttributeProto,Onnx.TensorProto.DataType>()
val inputTensor = Nd4j.linspace(0,25,25).reshape(1,1,5,5).castTo(DataType.FLOAT)
val w = Nd4j.ones(1,1,3,3).castTo(DataType.FLOAT)
val index = Nd4j.ones(1).castTo(DataType.INT32)
val graphToRun = GraphProto {
Input(createValueInfoFromTensor(inputTensor,"x",true))
Input(createValueInfoFromTensor(w,"W",true))
Input(createValueInfoFromTensor(index,"index",true))
Node(NodeProto {
Input("x")
Input("W")
Output("y")
name = "y"
opType = "SequenceConstruct"
})
Node(NodeProto {
Input("y")
Input("index")
Output("sequenceRemove")
name = "sequenceRemove"
opType = "SequenceErase"
})
Output(createEmptySequence(convertToOnnxDataType( inputTensor.dataType()),"sequenceRemove"))
}
val onnxIRGraph = OnnxIRGraph(graphToRun,onnxOpRegistry)
val onnxGraphRunner = OnnxIRGraphRunner(onnxIRGraph,listOf("x","W"),listOf("sequenceRemove"))
val importedGraph = importGraph.importGraph(onnxIRGraph,null,null, convertToOnnxTensors(mutableMapOf("W" to w,"x" to inputTensor,"index" to index)),onnxOpRegistry)
println(importedGraph.summary())
val inputs = mapOf("x" to arrayOf(inputTensor),"W" to arrayOf(w),"index" to arrayOf(index))
val inputs2 = mapOf("x" to SDValue.create(inputTensor),"W" to SDValue.create(w),"index" to SDValue.create(index))
val assertion = onnxGraphRunner.runSequence(inputs2)
val result = importedGraph.outputValues(inputs2 ,listOf("sequenceRemove"))
//assert equals doesn't know how to deal with arrays within maps
assertEquals(assertion["sequenceRemove"],result["sequenceRemove"])
}
@Test
fun testConvPaddingSame() {
Nd4j.getExecutioner().enableVerboseMode(true)
Nd4j.getExecutioner().enableDebugMode(true)
val onnxOpRegistry = registry()
val importGraph = ImportGraph<Onnx.GraphProto,Onnx.NodeProto,Onnx.NodeProto,Onnx.TensorProto,Onnx.AttributeProto,Onnx.AttributeProto,Onnx.TensorProto.DataType>()
val inputTensor = Nd4j.linspace(0,25,25).reshape(1,1,5,5).castTo(DataType.FLOAT)
val w = Nd4j.ones(1,1,3,3).castTo(DataType.FLOAT)
val graphToRun = GraphProto {
Input(createValueInfoFromTensor(inputTensor,"x",true))
Input(createValueInfoFromTensor(w,"W",true))
//Initializer(convertedTensor)
Node(NodeProto {
Input("x")
Input("W")
Output("y")
name = "y"
opType = "Conv"
Attribute(AttributeProto {
type = Onnx.AttributeProto.AttributeType.INTS
name = "kernel_shape"
ListInts(listOf(3,3))
})
Attribute(AttributeProto {
type = Onnx.AttributeProto.AttributeType.INTS
name = "pads"
ListInts(listOf(1,1,1,1))
})
Attribute(AttributeProto {
type = Onnx.AttributeProto.AttributeType.INTS
name = "strides"
ListInts(listOf(1,1))
})
Attribute(AttributeProto {
type = Onnx.AttributeProto.AttributeType.INTS
name = "dilations"
ListInts(listOf(1,1))
})
Attribute(AttributeProto {
type = Onnx.AttributeProto.AttributeType.INT
name = "group"
IntValue(1)
})
})
Output(createValueInfoFromTensor(inputTensor,"y",false))
}
val onnxIRGraph = OnnxIRGraph(graphToRun,onnxOpRegistry)
val onnxGraphRunner = OnnxIRGraphRunner(onnxIRGraph,listOf("x","W"),listOf("y"))
val importedGraph = importGraph.importGraph(onnxIRGraph,null,null, convertToOnnxTensors(mutableMapOf("W" to w,"x" to inputTensor)),onnxOpRegistry)
val inputs = mapOf("x" to inputTensor,"W" to w)
val assertion = onnxGraphRunner.run(inputs)
val result = importedGraph.output(inputs,"y")
assertEquals(assertion,result)
}
@Test
fun testLoop() {
Nd4j.getExecutioner().enableDebugMode(true)
Nd4j.getExecutioner().enableVerboseMode(true)
val bitWise = NDBitwise()
val and = bitWise.and(Nd4j.ones(DataType.INT64,1),Nd4j.ones(DataType.INT64,1))
val axes = Nd4j.createFromArray(0L)
val inputArr = Nd4j.create(floatArrayOf(1.0f,2.0f,3.0f,4.0f,5.0f))
val y = Nd4j.create(floatArrayOf(-2.0f))
val onnxOpRegistry = registry()
val tripCount = Nd4j.createFromArray(2).castTo(DataType.INT64)
val resY = Nd4j.createFromArray(13f)
val cond = Nd4j.createFromArray(true)
val resScan = Nd4j.createFromArray(-1,1,4,8,13).castTo(DataType.FLOAT).reshape(5,1)
val modelLoad = """
ir_version: 8
producer_name: "backend-test"
graph {
node {
input: "trip_count"
input: "cond"
input: "seq_empty"
output: "seq_res"
op_type: "Loop"
name: "loop_body"
attribute {
name: "body"
g {
node {
name: "cond_out"
input: "cond_in"
output: "cond_out"
op_type: "Identity"
}
node {
name: "x"
output: "x"
op_type: "Constant"
attribute {
name: "value"
t {
dims: 5
data_type: 1
float_data: 1.0
float_data: 2.0
float_data: 3.0
float_data: 4.0
float_data: 5.0
name: "const_tensor_x"
}
type: TENSOR
}
}
node {
name: "one"
output: "one"
op_type: "Constant"
attribute {
name: "value"
t {
data_type: 7
int64_data: 1
name: "const_tensor_one"
}
type: TENSOR
}
}
node {
name: "slice_start"
output: "slice_start"
op_type: "Constant"
attribute {
name: "value"
t {
dims: 1
data_type: 7
int64_data: 0
name: "const_tensor_zero"
}
type: TENSOR
}
}
node {
name: "add"
input: "iter_count"
input: "one"
output: "end"
op_type: "Add"
}
node {
name: "axes"
output: "axes"
op_type: "Constant"
attribute {
name: "value"
t {
data_type: 7
int64_data: 0
name: "const_tensor_axes"
}
type: TENSOR
}
}
node {
name: "slice_end"
input: "end"
input: "axes"
output: "slice_end"
op_type: "Unsqueeze"
}
node {
name: "slice_out"
input: "x"
input: "slice_start"
input: "slice_end"
output: "slice_out"
op_type: "Slice"
}
node {
name: "seq_out"
input: "seq_in"
input: "slice_out"
output: "seq_out"
op_type: "SequenceInsert"
}
name: "loop_body"
input {
name: "iter_count"
type {
tensor_type {
elem_type: 7
shape {
}
}
}
}
input {
name: "cond_in"
type {
tensor_type {
elem_type: 9
shape {
}
}
}
}
input {
name: "seq_in"
type {
sequence_type {
elem_type {
tensor_type {
elem_type: 1
}
}
}
}
}
output {
name: "cond_out"
type {
tensor_type {
elem_type: 9
shape {
}
}
}
}
output {
name: "seq_out"
type {
sequence_type {
elem_type {
tensor_type {
elem_type: 1
}
}
}
}
}
}
type: GRAPH
}
}
name: "test_loop13_seq"
input {
name: "trip_count"
type {
tensor_type {
elem_type: 7
shape {
}
}
}
}
input {
name: "cond"
type {
tensor_type {
elem_type: 9
shape {
}
}
}
}
input {
name: "seq_empty"
type {
sequence_type {
elem_type {
tensor_type {
elem_type: 1
shape {
}
}
}
}
}
}
output {
name: "seq_res"
type {
sequence_type {
elem_type {
tensor_type {
elem_type: 1
}
}
}
}
}
}
opset_import {
domain: ""
version: 13
}
""".trimIndent()
val graph = OnnxTestUtils.loadFromString(modelLoad)
val onnxIRGraph = OnnxIRGraph(graph.graph,onnxOpRegistry)
val onnxGraphRunner = OnnxIRGraphRunner(onnxIRGraph,listOf("trip_count","cond","seq_empty"),listOf("res_y","res_scan"))
val inputs = mapOf("trip_count" to tripCount,"cond" to cond,"y" to y,"begin_axes" to axes,"end_axes" to axes,"iter_count" to Nd4j.create(Nd4j.createBuffer(longArrayOf(1))))
val sequenceInputValues = mapOf("trip_count" to SDValue.create(tripCount),
"cond" to SDValue.create(cond),
"y" to SDValue.create(y),
"begin_axes" to SDValue.create(axes),"end_axes" to SDValue.create(axes),
"seq_empty" to SDValue.create(mutableListOf(Nd4j.ones(DataType.FLOAT,1))))
val inputsOnnx = convertToOnnxTensors(inputs)
val importGraph = ImportGraph<Onnx.GraphProto,Onnx.NodeProto,Onnx.NodeProto,Onnx.TensorProto,Onnx.AttributeProto,Onnx.AttributeProto,Onnx.TensorProto.DataType>()
val importedGraph = importGraph.importGraph(onnxIRGraph,null,null,inputsOnnx,onnxOpRegistry)
val assertion = onnxGraphRunner.runSequence(sequenceInputValues)
println(importedGraph.summary())
val result = importedGraph.outputValues(sequenceInputValues,mutableListOf("seq_res"))
assertEquals(assertion,result)
}
@Test
fun testEager() {
val sd = SameDiff.create()
sd.isEagerMode = true
val result = sd.math().add(sd.constant(Nd4j.ones(1)),sd.constant(Nd4j.ones(1)))
val result2 = sd.math().add(result,1.0)
sd.outputAll(emptyMap())
println(result2)
}
@Test
fun testConvPaddingGroups() {
Nd4j.getExecutioner().enableVerboseMode(true)
Nd4j.getExecutioner().enableDebugMode(true)
val onnxOpRegistry = registry()
val importGraph = ImportGraph<Onnx.GraphProto,Onnx.NodeProto,Onnx.NodeProto,Onnx.TensorProto,Onnx.AttributeProto,Onnx.AttributeProto,Onnx.TensorProto.DataType>()
val inputTensor = Nd4j.ones(1,32,224,224).castTo(DataType.FLOAT)
val w = Nd4j.ones(32,1,3,3).castTo(DataType.FLOAT)
val graphToRun = GraphProto {
Input(createValueInfoFromTensor(inputTensor,"x",true))
Input(createValueInfoFromTensor(w,"W",true))
//Initializer(convertedTensor)
Node(NodeProto {
Input("x")
Input("W")
Output("y")
name = "y"
opType = "Conv"
Attribute(AttributeProto {
type = Onnx.AttributeProto.AttributeType.INTS
name = "kernel_shape"
ListInts(listOf(3,3))
})
Attribute(AttributeProto {
type = Onnx.AttributeProto.AttributeType.INTS
name = "pads"
ListInts(listOf(1,1,1,1))
})
Attribute(AttributeProto {
type = Onnx.AttributeProto.AttributeType.INTS
name = "strides"
ListInts(listOf(1,1))
})
Attribute(AttributeProto {
type = Onnx.AttributeProto.AttributeType.INTS
name = "dilations"
ListInts(listOf(1,1))
})
Attribute(AttributeProto {
type = Onnx.AttributeProto.AttributeType.INT
name = "group"
IntValue(32)
})
})
Output(createValueInfoFromTensor(inputTensor,"y",false))
}
val onnxIRGraph = OnnxIRGraph(graphToRun,onnxOpRegistry)
val onnxGraphRunner = OnnxIRGraphRunner(onnxIRGraph,listOf("x","W"),listOf("y"))
val inputs = mapOf("x" to inputTensor,"W" to w)
val inputsOnnx = mutableMapOf("x" to convertToOnnxTensor(inputTensor,"x"),"W" to convertToOnnxTensor(w,"W"))
val importedGraph = importGraph.importGraph(onnxIRGraph,null,null,inputsOnnx,onnxOpRegistry)
val assertion = onnxGraphRunner.run(inputs)
val result = importedGraph.output(inputs,"y")
assertEquals(assertion,result)
}
@Test
fun testConvPadding() {
Nd4j.getExecutioner().enableVerboseMode(true)
Nd4j.getExecutioner().enableDebugMode(true)
val onnxOpRegistry = registry()
val importGraph = ImportGraph<Onnx.GraphProto,Onnx.NodeProto,Onnx.NodeProto,Onnx.TensorProto,Onnx.AttributeProto,Onnx.AttributeProto,Onnx.TensorProto.DataType>()
val inputTensor = Nd4j.linspace(0,25,25).reshape(1,1,5,5).castTo(DataType.FLOAT)
val w = Nd4j.ones(1,1,3,3).castTo(DataType.FLOAT)
val graphToRun = GraphProto {
Input(createValueInfoFromTensor(inputTensor,"x",true))
Input(createValueInfoFromTensor(w,"W",true))
//Initializer(convertedTensor)
Node(NodeProto {
Input("x")
Input("W")
Output("y")
name = "y"
opType = "Conv"
Attribute(AttributeProto {
type = Onnx.AttributeProto.AttributeType.INTS
name = "kernel_shape"
ListInts(listOf(3,3))
})
Attribute(AttributeProto {
type = Onnx.AttributeProto.AttributeType.INTS
name = "pads"
ListInts(listOf(1,1,1,1))
})
Attribute(AttributeProto {
type = Onnx.AttributeProto.AttributeType.INTS
name = "strides"
ListInts(listOf(1,1))
})
Attribute(AttributeProto {
type = Onnx.AttributeProto.AttributeType.INTS
name = "dilations"
ListInts(listOf(1,1))
})
Attribute(AttributeProto {
type = Onnx.AttributeProto.AttributeType.INT
name = "group"
IntValue(1)
})
})
Output(createValueInfoFromTensor(inputTensor,"y",false))
}
val onnxIRGraph = OnnxIRGraph(graphToRun,onnxOpRegistry)
val onnxGraphRunner = OnnxIRGraphRunner(onnxIRGraph,listOf("x","W"),listOf("y"))
val importedGraph = importGraph.importGraph(onnxIRGraph,null,null, convertToOnnxTensors(mutableMapOf("x" to inputTensor,"W" to w)),onnxOpRegistry)
val inputs = mapOf("x" to inputTensor,"W" to w)
val assertion = onnxGraphRunner.run(inputs)
val result = importedGraph.output(inputs,"y")
assertEquals(assertion,result)
}
@Test
fun testConvNoPadding() {
val onnxOpRegistry = registry()
val importGraph = ImportGraph<Onnx.GraphProto,Onnx.NodeProto,Onnx.NodeProto,Onnx.TensorProto,Onnx.AttributeProto,Onnx.AttributeProto,Onnx.TensorProto.DataType>()
val inputTensor = Nd4j.linspace(0,25,25).reshape(1,1,5,5)
val w = Nd4j.ones(1,1,3,3)
val graphToRun = GraphProto {
Input(createValueInfoFromTensor(inputTensor,"x",true))
Input(createValueInfoFromTensor(w,"W",true))
//Initializer(convertedTensor)
Node(NodeProto {
Input("x")
Input("W")
Output("y")
name = "y"
opType = "Conv"
Attribute(AttributeProto {
type = Onnx.AttributeProto.AttributeType.INTS
name = "kernel_shape"
ListInts(listOf(3,3))
})
Attribute(AttributeProto {
type = Onnx.AttributeProto.AttributeType.INTS
name = "pads"
ListInts(listOf(0,0,0,0))
})
Attribute(AttributeProto {
type = Onnx.AttributeProto.AttributeType.INTS
name = "strides"
ListInts(listOf(1,1))
})
Attribute(AttributeProto {
type = Onnx.AttributeProto.AttributeType.INTS
name = "dilations"
ListInts(listOf(1,1))
})
Attribute(AttributeProto {
type = Onnx.AttributeProto.AttributeType.INT
name = "group"
IntValue(1)
})
})
Output(createValueInfoFromTensor(inputTensor,"y",false))
}
val onnxIRGraph = OnnxIRGraph(graphToRun,onnxOpRegistry)
val onnxGraphRunner = OnnxIRGraphRunner(onnxIRGraph,listOf("x","W"),listOf("y"))
val importedGraph = importGraph.importGraph(onnxIRGraph,null,null,
convertToOnnxTensors(mutableMapOf("x" to inputTensor,"W" to w)),onnxOpRegistry)
val inputs = mapOf("x" to inputTensor,"W" to w)
val assertion = onnxGraphRunner.run(inputs)
val result = importedGraph.output(inputs,"y")
assertEquals(assertion,result)
}
@Test
fun testConvStridesPadding() {
val onnxOpRegistry = registry()
val importGraph = ImportGraph<Onnx.GraphProto,Onnx.NodeProto,Onnx.NodeProto,Onnx.TensorProto,Onnx.AttributeProto,Onnx.AttributeProto,Onnx.TensorProto.DataType>()
val inputTensor = Nd4j.linspace(0,34,35).reshape(1,1,7,5)
val w = Nd4j.ones(1,1,3,3)
val graphToRun = GraphProto {
Input(createValueInfoFromTensor(inputTensor,"x",true))
Input(createValueInfoFromTensor(w,"W",true))
//Initializer(convertedTensor)
Node(NodeProto {
Input("x")
Input("W")
Output("y")
name = "y"
opType = "Conv"
Attribute(AttributeProto {
type = Onnx.AttributeProto.AttributeType.INTS
name = "kernel_shape"
ListInts(listOf(3,3))
})
Attribute(AttributeProto {
type = Onnx.AttributeProto.AttributeType.INTS
name = "pads"
ListInts(listOf(1,1,1,1))
})
Attribute(AttributeProto {
type = Onnx.AttributeProto.AttributeType.INTS
name = "strides"
ListInts(listOf(2,2))
})
Attribute(AttributeProto {
type = Onnx.AttributeProto.AttributeType.INTS
name = "dilations"
ListInts(listOf(1,1))
})
Attribute(AttributeProto {
type = Onnx.AttributeProto.AttributeType.INT
name = "group"
IntValue(1)
})
})
Output(createValueInfoFromTensor(inputTensor,"y",false))
}
val onnxIRGraph = OnnxIRGraph(graphToRun,onnxOpRegistry)
val onnxGraphRunner = OnnxIRGraphRunner(onnxIRGraph,listOf("x","W"),listOf("y"))
val importedGraph = importGraph.importGraph(onnxIRGraph,null,null,
convertToOnnxTensors(mutableMapOf("x" to inputTensor,"W" to w)),onnxOpRegistry)
val inputs = mapOf("x" to inputTensor,"W" to w)
val assertion = onnxGraphRunner.run(inputs)
val result = importedGraph.output(inputs,"y")
assertEquals(assertion,result)
}
@Test
@Disabled("See: https://github.com/eclipse/deeplearning4j/issues/9525 we need to support asymmetrics padding")
fun testConvStridesAsymmetricPadding() {
val onnxOpRegistry = registry()
val importGraph = ImportGraph<Onnx.GraphProto,Onnx.NodeProto,Onnx.NodeProto,Onnx.TensorProto,Onnx.AttributeProto,Onnx.AttributeProto,Onnx.TensorProto.DataType>()
val inputTensor = Nd4j.linspace(0,34,35).reshape(1,1,7,5)
val w = Nd4j.ones(1,1,3,3)
val graphToRun = GraphProto {
Input(createValueInfoFromTensor(inputTensor,"x",true))
Input(createValueInfoFromTensor(w,"W",true))
//Initializer(convertedTensor)
Node(NodeProto {
Input("x")
Input("W")
Output("y")
name = "y"
opType = "Conv"
Attribute(AttributeProto {
type = Onnx.AttributeProto.AttributeType.INTS
name = "kernel_shape"
ListInts(listOf(3,3))
})
Attribute(AttributeProto {
type = Onnx.AttributeProto.AttributeType.INTS
name = "pads"
ListInts(listOf(1,0,1,0))
})
Attribute(AttributeProto {
type = Onnx.AttributeProto.AttributeType.INTS
name = "strides"
ListInts(listOf(2,2))
})
Attribute(AttributeProto {
type = Onnx.AttributeProto.AttributeType.INTS
name = "dilations"
ListInts(listOf(1,1))
})
Attribute(AttributeProto {
type = Onnx.AttributeProto.AttributeType.INT
name = "group"
IntValue(1)
})
})
Output(createValueInfoFromTensor(inputTensor,"y",false))
}
val onnxIRGraph = OnnxIRGraph(graphToRun,onnxOpRegistry)
val onnxGraphRunner = OnnxIRGraphRunner(onnxIRGraph,listOf("x","W"),listOf("y"))
val importedGraph = importGraph.importGraph(onnxIRGraph,null,null,HashMap(),onnxOpRegistry)
val inputs = mapOf("x" to inputTensor,"W" to w)
val assertion = onnxGraphRunner.run(inputs)
val result = importedGraph.output(inputs,"y")
assertEquals(assertion,result)
}
@Test
fun testOpExecutionHooks() {
val onnxOpRegistry = registry()
val importGraph = ImportGraph<Onnx.GraphProto,Onnx.NodeProto,Onnx.NodeProto,Onnx.TensorProto,Onnx.AttributeProto,Onnx.AttributeProto,Onnx.TensorProto.DataType>()
val inputTensor = Nd4j.ones(1,3,5,5)
val graphToRun = GraphProto {
Input(createValueInfoFromTensor(inputTensor,"x",true))
//Initializer(convertedTensor)
Node(NodeProto {
Input("x")
Output("y")
name = "y"
opType = "GlobalAveragePool"
})
Output(createValueInfoFromTensor(inputTensor,"y",false))
}
val onnxIRGraph = OnnxIRGraph(graphToRun,onnxOpRegistry)
val onnxGraphRunner = OnnxIRGraphRunner(onnxIRGraph,listOf("x"),listOf("y"))
val importedGraph = importGraph.importGraph(onnxIRGraph,null,null,
convertToOnnxTensors(mutableMapOf("x" to inputTensor)),onnxOpRegistry)
val inputs = mapOf("x" to inputTensor)
val assertion = onnxGraphRunner.run(inputs)
val result = importedGraph.output(inputs,"y")
assertEquals(assertion,result)
}
@Test
fun testExpand() {
val declarations = OnnxOpDeclarations
val onnxOpRegistry = registry()
val shape = longArrayOf(3,1)
val newShape = longArrayOf(2,1,6)
val inputNewShape = Nd4j.create(Nd4j.createBuffer(newShape))
val inputs = mapOf("data" to Nd4j.arange(1.0, ArrayUtil.prod(*shape).toDouble() + 1.0).reshape(*shape),
"newShape" to inputNewShape)
val inputNames = listOf("data","newShape")
val outputs = listOf("expanded")
val graph = createSingleNodeGraph(op = "Expand",inputs = inputs, attributes = emptyMap(),outputs = outputs,inputNames = inputNames)
runAssertion(graph,inputs,outputs)
}
@Test
fun testSlice() {
/**
* Note that this test case is manual due to subtle differences in
* how onnxruntime and tensorflow appear to interpret their nearest neighbor results.
* In our test case here, we are verifying against tensorflow-onnx as the implementation.
*
*/
Nd4j.getExecutioner().enableDebugMode(true)
Nd4j.getExecutioner().enableVerboseMode(true)
val x = Nd4j.linspace(1,1000,1000).reshape(20,10,5)
val starts = Nd4j.zeros(2).castTo(DataType.INT64)
val ends = Nd4j.create(Nd4j.createBuffer(longArrayOf(3,10))).reshape(2)
val axes = Nd4j.create(Nd4j.createBuffer(longArrayOf(0,1))).reshape(2)
val steps = Nd4j.ones(2).castTo(DataType.INT64).reshape(2)
val input = mapOf("x" to x,"starts" to starts,"ends" to ends,"axes" to axes,"steps" to steps)
val outputs = listOf("y")
val attributes = emptyMap<String,Any>()
val inputs = listOf("x","starts","ends","axes","steps")
val graph = createSingleNodeGraph(input,"Slice",attributes,outputs,inputs)
assertEquals(input.size,graph.inputCount)
assertEquals(1,graph.outputCount)
runAssertion(graph,input,outputs)
}
@Test
fun testClip() {
val declarations = OnnxOpDeclarations
val inputs = mutableMapOf("input" to Nd4j.linspace(1,4,4).castTo(DataType.DOUBLE),
"min" to Nd4j.scalar(1.0).castTo(DataType.DOUBLE), "max" to Nd4j.scalar(2.0).castTo(DataType.DOUBLE))
val output = listOf("output")
val createdGraph = createSingleNodeGraph(inputs,"Clip",emptyMap(),output,inputs.keys.toList())
runAssertion(createdGraph,inputs,output)
}
@Test
fun testNonZero() {
val declarations = OnnxOpDeclarations
val inputs = mutableMapOf("input" to Nd4j.linspace(1,4,4).castTo(DataType.DOUBLE))
val onnxOpRegistry = registry()
val output = listOf("output")
val createdGraph = createSingleNodeGraph(inputs,"NonZero",emptyMap(),output,inputs.keys.toList(),templateTensor = Nd4j.ones(DataType.INT64))
val importGraph = ImportGraph<Onnx.GraphProto,Onnx.NodeProto,Onnx.NodeProto,Onnx.TensorProto,Onnx.AttributeProto,Onnx.AttributeProto,Onnx.TensorProto.DataType>()
val onnxIRGraph = OnnxIRGraph(createdGraph,onnxOpRegistry)
val importedGraph = importGraph.importGraph(onnxIRGraph,null,null, convertToOnnxTensors(inputs),onnxOpRegistry)
val result = importedGraph.output(inputs,output)
//runAssertion(createdGraph,inputs,output)
}
@Test
fun testIf() {
val thenOut = convertToOnnxTensor(Nd4j.ones(DataType.FLOAT,5),"then_out")
val elseOut = convertToOnnxTensor(Nd4j.ones(DataType.FLOAT,5),"else_out")
val x = Nd4j.linspace(1,5,5).castTo(DataType.FLOAT)
val y = Nd4j.create(floatArrayOf(5.0f,4.0f,3.0f,2.0f,1.0f))
val elseGraph = createSingleNodeGraph(emptyMap(),"Constant",mapOf("value" to elseOut),listOf("else_out"),listOf(),x)
val thenGraph = createSingleNodeGraph(emptyMap(),"Constant",mapOf("value" to thenOut),listOf("then_out"),listOf(),x)
val thenGraphAttr = AttributeProto {
name = "then_branch"
g = thenGraph
type = Onnx.AttributeProto.AttributeType.GRAPH
}
val elseAttr = AttributeProto {
name = "else_branch"
g = elseGraph
type = Onnx.AttributeProto.AttributeType.GRAPH
}
val ifNode = NodeProto {
opType = "If"
name = "ifNode"
Input("cond")
Output("res")
Attribute(thenGraphAttr)
Attribute(elseAttr)
}
val graph = GraphProto {
name = "ifGraph"
Input(createValueInfoFromTensor(Nd4j.ones(1).castTo(DataType.BOOL),"cond",true))
Node(ifNode)
Output(createValueInfoFromTensor(y,"res",true))
}
runAssertion(graph,mapOf("cond" to (Nd4j.ones(1).castTo(DataType.BOOL))),listOf("res"))
}
@Test
fun testRoiAligned() {
val xArr = arrayOf(
doubleArrayOf(
0.2764,
0.7150,
0.1958,
0.3416,
0.4638,
0.0259,
0.2963,
0.6518,
0.4856,
0.7250,
),
doubleArrayOf(
0.9637,
0.0895,
0.2919,
0.6753,
0.0234,
0.6132,
0.8085,
0.5324,
0.8992,
0.4467,
),
doubleArrayOf(
0.3265,
0.8479,
0.9698,
0.2471,
0.9336,
0.1878,
0.4766,
0.4308,
0.3400,
0.2162,
),
doubleArrayOf(
0.0206,
0.1720,
0.2155,
0.4394,
0.0653,
0.3406,
0.7724,
0.3921,
0.2541,
0.5799,
),
doubleArrayOf(
0.4062,
0.2194,
0.4473,
0.4687,
0.7109,
0.9327,
0.9815,
0.6320,
0.1728,
0.6119,
),
doubleArrayOf(
0.3097,
0.1283,
0.4984,
0.5068,
0.4279,
0.0173,
0.4388,
0.0430,
0.4671,
0.7119,
),
doubleArrayOf(
0.1011,
0.8477,
0.4726,
0.1777,
0.9923,
0.4042,
0.1869,
0.7795,
0.9946,
0.9689,
),
doubleArrayOf(
0.1366,
0.3671,
0.7011,
0.6234,
0.9867,
0.5585,
0.6985,
0.5609,
0.8788,
0.9928,
),
doubleArrayOf(
0.5697,
0.8511,
0.6711,
0.9406,
0.8751,
0.7496,
0.1650,
0.1049,
0.1559,
0.2514,
),
doubleArrayOf(
0.7012,
0.4056,
0.7879,
0.3461,
0.0415,
0.2998,
0.5094,
0.3727,
0.5482,
0.0502,
))
val roiX = Nd4j.create(xArr).reshape(1,1,10,10).castTo(DataType.FLOAT)
val rois = Nd4j.create(Nd4j.createBuffer(longArrayOf(0,0,9,9,0,5,4,9,5,5,9,9))).reshape(3,4).castTo(DataType.FLOAT)
val batchIndices = Nd4j.create(Nd4j.createBuffer(longArrayOf(0,0,0))).reshape(3)
val y = Nd4j.create(Nd4j.createBuffer(doubleArrayOf(0.4664,0.4466,0.3405,0.5688,0.6068,0.3714,0.4296,0.3835,0.5562,0.351
,0.2768,0.4883,0.5222,0.5528,0.4171,0.4713,0.4844,0.6904,0.492,0.8774
,0.6239,0.7125,0.6289,0.3355,0.3495,0.3022,0.4305,0.4696,0.3978,0.5423
,0.3656,0.705,0.5165,0.3172,0.7015,0.2912,0.5059,0.6476,0.6235,0.8299
,0.5916,0.7389,0.7048,0.8372,0.8893,0.6227,0.6153,0.7097,0.6154,0.4585
,0.2384,0.3379,0.3717,0.61,0.7601,0.3767,0.3785,0.7147,0.9243,0.9727
,0.5749,0.5826,0.5709,0.7619,0.877,0.5355,0.2566,0.2141,0.2796,0.36
,0.4365,0.3504,0.2887,0.3661,0.2349))).reshape(3,1,5,5)
val outputs = listOf("y")
val inputs = mapOf("X" to roiX,"rois" to rois,"batch_indices" to batchIndices)
val attributes = mapOf("spatial_scale" to 1.0f,"output_height" to 5,"output_width" to 5,"sampling_ratio" to 2)
val createdGraph = createSingleNodeGraph(inputs,"RoiAlign",attributes,outputs,inputs.keys.toList())
runAssertion(createdGraph,inputs,outputs)
}
@Test
fun testMaximum() {
val declarations = OnnxOpDeclarations
val inputs = mutableMapOf<String,INDArray>()
for(i in 0 until 5) {
inputs["$i"] = Nd4j.zeros(2).addi(i)
}
val output = listOf("output")
val createdGraph = createSingleNodeGraph(inputs,"Max",emptyMap(),output,inputs.keys.toList())
runAssertion(createdGraph,inputs,output)
}
@Test
fun testMinimum() {
val declarations = OnnxOpDeclarations
val inputs = mutableMapOf<String,INDArray>()
for(i in 0 until 5) {
inputs["$i"] = Nd4j.zeros(2).addi(i)
}
val output = listOf("output")
val createdGraph = createSingleNodeGraph(inputs,"Min",emptyMap(),output,inputs.keys.toList())
runAssertion(createdGraph,inputs,output)
}
@Test
fun testUnsqueeze() {
val declarations = OnnxOpDeclarations
/**
* Note that this test case is manual due to subtle differences in
* how onnxruntime and tensorflow appear to interpret their nearest neighbor results.
* In our test case here, we are verifying against tensorflow-onnx as the implementation.
*
*/
val onnxOpRegistry = registry()
val inputData = Nd4j.linspace(1,15,15).reshape(1,3,1,5)
val axes = Nd4j.create(floatArrayOf(-2.0f)).castTo(DataType.INT64)
val input = mapOf("x" to inputData,"axes" to axes)
val outputs = listOf("y")
val attributes = emptyMap<String,Any>()
val inputs = listOf("x","axes")
val graph = createSingleNodeGraph(input,"Unsqueeze",attributes,outputs,inputs)
assertEquals(input.size,graph.inputCount)
assertEquals(1,graph.outputCount)
val onnxIRGraph = OnnxIRGraph(graph,onnxOpRegistry)
val onnxGraphRunner = OnnxIRGraphRunner(onnxIRGraph,input.keys.toList(),outputs)
val assertion = onnxGraphRunner.run(input)
val importGraph = ImportGraph<Onnx.GraphProto,Onnx.NodeProto,Onnx.NodeProto,Onnx.TensorProto,Onnx.AttributeProto,Onnx.AttributeProto,Onnx.TensorProto.DataType>()
val importedGraph = importGraph.importGraph(onnxIRGraph,null,null, convertToOnnxTensors(input),onnxOpRegistry)
val result = importedGraph.output(input,outputs)
//TODO: add coefficients for better eps comparison, see: https://github.com/eclipse/deeplearning4j/issues/9467
assertTrue(assertion["y"]!!.equalsWithEps(result["y"],1e-1))
}
@Test
fun testCast() {
val declarations = OnnxOpDeclarations
/**
* Note that this test case is manual due to subtle differences in
* how onnxruntime and tensorflow appear to interpret their nearest neighbor results.
* In our test case here, we are verifying against tensorflow-onnx as the implementation.
*
*/
val onnxOpRegistry = registry()
val startInput = Nd4j.ones(2).castTo(DataType.DOUBLE)
val inputData = mapOf("x" to startInput)
val outputs = listOf("y")
val attributes = mapOf("to" to Onnx.TensorProto.DataType.FLOAT.ordinal)
val graph = createSingleNodeGraph(inputData,"Cast",attributes,outputs,listOf("x"),Nd4j.ones(2).castTo(DataType.FLOAT))
runAssertion(graph,inputData,outputs)
}
@Test
fun testResize() {
val declarations = OnnxOpDeclarations
/**
* Note that this test case is manual due to subtle differences in
* how onnxruntime and tensorflow appear to interpret their nearest neighbor results.
* In our test case here, we are verifying against tensorflow-onnx as the implementation.
*
*/
val onnxOpRegistry = registry()
val inputData = Nd4j.linspace(1,16,16).reshape(1,1,4,4)
val scales = Nd4j.create(floatArrayOf(1.0f,1.0f,0.8f,0.8f))
val input = mapOf("x" to inputData,"scales" to scales,"roi-empty" to Nd4j.zeros(1,1,1,1))
val outputs = listOf("y")
val attributes = mapOf("mode" to "cubic")
val inputs = listOf("x","roi-empty","scales")
val graph = createSingleNodeGraph(input,"Resize",attributes,outputs,inputs)
assertEquals(input.size,graph.inputCount)
assertEquals(1,graph.outputCount)
val onnxIRGraph = OnnxIRGraph(graph,onnxOpRegistry)
val onnxGraphRunner = OnnxIRGraphRunner(onnxIRGraph,input.keys.toList(),outputs)
val assertion = onnxGraphRunner.run(input)
val importGraph = ImportGraph<Onnx.GraphProto,Onnx.NodeProto,Onnx.NodeProto,Onnx.TensorProto,Onnx.AttributeProto,Onnx.AttributeProto,Onnx.TensorProto.DataType>()
val importedGraph = importGraph.importGraph(onnxIRGraph,null,null, convertToOnnxTensors(input),onnxOpRegistry)
val result = importedGraph.output(input,outputs)
//TODO: add coefficients for better eps comparison, see: https://github.com/eclipse/deeplearning4j/issues/9467
assertTrue(assertion["y"]!!.equalsWithEps(result["y"],1e-1))
}
@Test
fun testOpExecution() {
val onnxOpRegistry = registry()
val scalarInputs = mapOf(
"abs" to -1.0,
"copy" to 1.0,
"erfc" to 1.0,
"exp" to 1.0,
"identity" to 1.0,
"neg" to 1.0,
"ones_as" to 1.0,
"relu6" to 1.0,
"round" to 1.0,
"sign" to 1.0,
"sin" to 1.0,
"square" to 1.0,
"sqrt" to 1.0)
val scalarFloatOps = mapOf(
"acos" to 1.0f,
"asin" to 1.0f,
"acosh" to 1.0f,
"asinh" to 1.0f,
"atan" to 1.0f,
"atanh" to 0.5f,
"ceil" to 1.0f,
"cosh" to 1.0f,
"cos" to 1.0f,
"erf" to 1.0f,
"hard_sigmoid" to 1.0f,
"floor" to 1.0f,
"log" to 1.0f,
"round" to 1.0f,
"relu" to 1.0f,
"selu" to 1.0f,
"sinh" to 1.0f,
"sigmoid" to 1.0f,
"softplus" to 1.0f,
"softsign" to 1.0f,
"tan" to 1.0f,
"tanh" to 1.0f
)
val singleInputOps = scalarInputs.keys
val singleInputBooleanOps = mapOf(
"not" to false
)
val singleOutputBooleanOps = mapOf(
"isfinite" to 1.0f,
"isinf" to 1.0f,
"isnan" to 1.0f,
)
val pairWiseBooleanOps = mapOf(
"min" to listOf(1.0,2.0),
"max" to listOf(1.0,2.0),
"equals" to listOf(2.0,2.0),
"greater" to listOf(2.0,1.0),
"greater_equal" to listOf(2.0,1.0),
"less" to listOf(2.0,1.0),
"less_equal" to listOf(2.0,1.0))
val singleInputIntOutput = mapOf(
"size" to Nd4j.linspace(1,4,4).reshape(2,2),
"shape_of" to Nd4j.linspace(1,4,4).reshape(2,2)
)
val pairWiseBooleanInputs = mapOf(
"or" to listOf(true,false),
"and" to listOf(false,false),
"xor" to listOf(false,true)
)
val singleReduceOps = mapOf(
"reduce_sum" to Nd4j.linspace(1,4,4).reshape(2,2),
// "reduce_logsumexp" to Nd4j.linspace(1,4,4).reshape(2,2)
)
val pairwise = mapOf(
"add" to listOf(1.0,1.0),
"subtract" to listOf(2.0,1.0),
"multiply" to listOf(2.0,1.0),
"divide" to listOf(2.0,1.0),
"pow" to listOf(2.0,1.0)
)
val mappedOps = setOf("elu","transpose","argmin","argmax","leakyrelu","prelu","flatten_2d")//,"top_k")
/**
* NOTE WHEN WRITING TESTS, IF YOU SEE AN ERROR like:
* java.lang.RuntimeException: Could not find an implementation for the node output:Cos(7)
*
* Check the supported data types for each op here:
* https://github.com/microsoft/onnxruntime/blob/master/docs/OperatorKernels.md
*/
val importGraph = ImportGraph<Onnx.GraphProto,Onnx.NodeProto,Onnx.NodeProto,Onnx.TensorProto,Onnx.AttributeProto,Onnx.AttributeProto,Onnx.TensorProto.DataType>()
val finishedOps = HashSet<String>()
onnxOpRegistry.mappingProcessNames()
.filter { onnxOpRegistry.hasMappingOpProcess(it) }
.map { onnxOpRegistry.lookupOpMappingProcess(it) }.forEach { mappingProcess ->
val nd4jOpDef = onnxOpRegistry.lookupNd4jOpDef(mappingProcess.opName())
val onnxOpDef = onnxOpRegistry.lookupInputFrameworkOpDef(mappingProcess.inputFrameworkOpName())
if(scalarInputs.containsKey(nd4jOpDef.name)) {
print("Running op $nd4jOpDef.name")
val input = Nd4j.scalar(scalarInputs[mappingProcess.opName()]).castTo(org.nd4j.linalg.api.buffer.DataType.DOUBLE)
val graphToRun = GraphProto {
Input(createValueInfoFromTensor(input,"input"))
//Initializer(convertedTensor)
Node(NodeProto {
name = "output"
opType = onnxOpDef.opType
Input("input")
Output("output")
})
Output(createValueInfoFromTensor(input,"output"))
}
val inputs = mapOf("input" to input)
val onnxInputs = convertToOnnxTensors(inputs)
val onnxIRGraph = OnnxIRGraph(graphToRun,onnxOpRegistry)
val onnxGraphRunner = OnnxIRGraphRunner(onnxIRGraph,listOf("input"),listOf("output"))
val importedGraph = importGraph.importGraph(onnxIRGraph,null,null,onnxInputs,onnxOpRegistry)
val assertion = onnxGraphRunner.run(inputs)
val result = importedGraph.output(inputs,"output")
assertEquals(assertion["output"]!!.reshape(1,1),result["output"]!!.reshape(1,1),"Function ${nd4jOpDef.name} failed with input $input")
finishedOps.add(nd4jOpDef.name)
} else if(scalarFloatOps.containsKey(nd4jOpDef.name)) {
print("Running op $nd4jOpDef.name")
val input = Nd4j.scalar(scalarFloatOps[mappingProcess.opName()]).castTo(DataType.FLOAT)
val graphToRun = GraphProto {
Input(createValueInfoFromTensor(input,"input"))
//Initializer(convertedTensor)
Node(NodeProto {
name = "output"
opType = onnxOpDef.opType
Input("input")
Output("output")
})
Output(createValueInfoFromTensor(input,"output"))
}
val inputs = mapOf("input" to input)
val dynamicVariables = convertToOnnxTensors(inputs)
val onnxIRGraph = OnnxIRGraph(graphToRun,onnxOpRegistry)
val onnxGraphRunner = OnnxIRGraphRunner(onnxIRGraph,listOf("input"),listOf("output"))
val importedGraph = importGraph.importGraph(onnxIRGraph,null,null,dynamicVariables,onnxOpRegistry)
val assertion = onnxGraphRunner.run(inputs)
val result = importedGraph.output(inputs,"output")
assertEquals(assertion["output"]!!.reshape(1,1),result["output"]!!.reshape(1,1),"Function ${nd4jOpDef.name} failed with input $input")
finishedOps.add(nd4jOpDef.name)
}
else if(singleOutputBooleanOps.containsKey(nd4jOpDef.name)) {
print("Running op $nd4jOpDef.name")
val input = Nd4j.scalar(singleOutputBooleanOps[mappingProcess.opName()]).castTo(DataType.FLOAT)
val convertedTensor = convertToOnnxTensor(input,"input")
val convertedOutputTensor = convertToOnnxTensor(input,"output")
val graphToRun = GraphProto {
Input(createValueInfoFromTensor(input,"input"))
//Initializer(convertedTensor)
Node(NodeProto {
name = "output"
opType = onnxOpDef.opType
Input("input")
Output("output")
})
Output(createValueInfoFromTensor(Nd4j.create(booleanArrayOf(true)).reshape(),"output"))
}
val inputs = mapOf("input" to input)
val convertedTensors = convertToOnnxTensors(inputs)
val onnxIRGraph = OnnxIRGraph(graphToRun,onnxOpRegistry)
val onnxGraphRunner = OnnxIRGraphRunner(onnxIRGraph,listOf("input"),listOf("output"))
val importedGraph = importGraph.importGraph(onnxIRGraph,null,null,convertedTensors,onnxOpRegistry)
val assertion = onnxGraphRunner.run(inputs)
val result = importedGraph.output(inputs,"output")
assertEquals(assertion["output"]!!.reshape(1,1),result["output"]!!.reshape(1,1),"Function ${nd4jOpDef.name} failed with input $input")
finishedOps.add(nd4jOpDef.name)
}
else if(pairwise.containsKey(nd4jOpDef.name)) {
print("Running op def $nd4jOpDef.name")
val x = Nd4j.scalar(pairwise[mappingProcess.opName()]!![0]!!).castTo(org.nd4j.linalg.api.buffer.DataType.DOUBLE)
val y = Nd4j.scalar(pairwise[mappingProcess.opName()]!![1]!!).castTo(org.nd4j.linalg.api.buffer.DataType.DOUBLE)
val graphToRun = GraphProto {
Input(createValueInfoFromTensor(x,"x"))
Input(createValueInfoFromTensor(y,"y"))
//Initializer(convertedTensor)
Node(NodeProto {
name = "output"
opType = onnxOpDef.opType
Input("x")
Input("y")
Output("output")
})
Output(createValueInfoFromTensor(x,"output"))
}
val onnxIRGraph = OnnxIRGraph(graphToRun,onnxOpRegistry)
val onnxGraphRunner = OnnxIRGraphRunner(onnxIRGraph,listOf("x","y"),listOf("output"))
val importedGraph = importGraph.importGraph(onnxIRGraph,null,null,
hashMapOf("x" to convertToOnnxTensor(x,"x"),"y" to convertToOnnxTensor(y,"y")),onnxOpRegistry)
val inputs = mapOf("x" to x,"y" to y)
val result = importedGraph.output(inputs,"output")
val assertion = onnxGraphRunner.run(inputs)
assertEquals(assertion["output"]!!.getDouble(0),result["output"]!!.getDouble(0),"Function ${nd4jOpDef.name} failed with input $x $y")
finishedOps.add(nd4jOpDef.name)
} else if(pairWiseBooleanInputs.containsKey(nd4jOpDef.name)) {
print("Running op def $nd4jOpDef.name")
val x = Nd4j.scalar(pairWiseBooleanInputs[mappingProcess.opName()]!![0]!!).castTo(org.nd4j.linalg.api.buffer.DataType.BOOL)
val y = Nd4j.scalar(pairWiseBooleanInputs[mappingProcess.opName()]!![1]!!).castTo(org.nd4j.linalg.api.buffer.DataType.BOOL)
val graphToRun = GraphProto {
Input(createValueInfoFromTensor(x,"x"))
Input(createValueInfoFromTensor(y,"y"))
Node(NodeProto {
name = "output"
opType = onnxOpDef.opType
Input("x")
Input("y")
Output("output")
})
Output(createValueInfoFromTensor(x,"output"))
}
val onnxIRGraph = OnnxIRGraph(graphToRun,onnxOpRegistry)
val onnxGraphRunner = OnnxIRGraphRunner(onnxIRGraph,listOf("x","y"),listOf("output"))
val importedGraph = importGraph.importGraph(onnxIRGraph,null,null,
hashMapOf("x" to convertToOnnxTensor(x,"x"),"y" to convertToOnnxTensor(y,"y")),onnxOpRegistry)
val inputs = mapOf("x" to x,"y" to y)
val assertion = onnxGraphRunner.run(inputs)
val result = importedGraph.output(inputs,"output")
assertEquals(assertion["output"]!!.getDouble(0),result["output"]!!.getDouble(0),"Function ${nd4jOpDef.name} failed with input $x $y")
finishedOps.add(nd4jOpDef.name)
} else if(pairWiseBooleanOps.containsKey(nd4jOpDef.name)) {
print("Running op def $nd4jOpDef.name")
val x = Nd4j.scalar(pairWiseBooleanOps[mappingProcess.opName()]!![0]!!).castTo(DataType.FLOAT)
val y = Nd4j.scalar(pairWiseBooleanOps[mappingProcess.opName()]!![1]!!).castTo(DataType.FLOAT)
val output = Nd4j.scalar(pairWiseBooleanOps[mappingProcess.opName()]!![1]!!).castTo(org.nd4j.linalg.api.buffer.DataType.BOOL)
val graphToRun = GraphProto {
Input(createValueInfoFromTensor(x,"x"))
Input(createValueInfoFromTensor(y,"y"))
//Initializer(convertedTensor)
Node(NodeProto {
name = "output"
opType = onnxOpDef.opType
Input("x")
Input("y")
Output("output")
})
Output(createValueInfoFromTensor(output,"output"))
}
val onnxIRGraph = OnnxIRGraph(graphToRun,onnxOpRegistry)
val onnxGraphRunner = OnnxIRGraphRunner(onnxIRGraph,listOf("x","y"),listOf("output"))
val importedGraph = importGraph.importGraph(onnxIRGraph,null,null,
hashMapOf("x" to convertToOnnxTensor(x,"x"),"y" to convertToOnnxTensor(y,"y")),onnxOpRegistry)
val inputs = mapOf("x" to x,"y" to y)
val assertion = onnxGraphRunner.run(inputs)
val result = importedGraph.output(inputs,"output")
assertEquals(assertion["output"]!!.getDouble(0),result["output"]!!.getDouble(0),"Function ${nd4jOpDef.name} failed with input $x $y")
finishedOps.add(nd4jOpDef.name)
}
else if(singleInputBooleanOps.containsKey(nd4jOpDef.name)) {
print("Running op def $nd4jOpDef.name")
val x = Nd4j.create(booleanArrayOf(singleInputBooleanOps[mappingProcess.opName()]!!)).castTo(org.nd4j.linalg.api.buffer.DataType.BOOL)
val output = Nd4j.create(booleanArrayOf(singleInputBooleanOps[mappingProcess.opName()]!!)).castTo(org.nd4j.linalg.api.buffer.DataType.BOOL)
val graphToRun = GraphProto {
Input(createValueInfoFromTensor(x,"x"))
//Initializer(convertedTensor)
Node(NodeProto {
name = "output"
opType = onnxOpDef.opType
Input("x")
Output("output")
})
Output(createValueInfoFromTensor(output,"output"))
}
val onnxIRGraph = OnnxIRGraph(graphToRun,onnxOpRegistry)
val onnxGraphRunner = OnnxIRGraphRunner(onnxIRGraph,listOf("x"),listOf("output"))
val importedGraph = importGraph.importGraph(onnxIRGraph,null,null,hashMapOf("x" to convertToOnnxTensor(x,"x")),onnxOpRegistry)
val inputs = mapOf("x" to x)
val assertion = onnxGraphRunner.run(inputs)
val result = importedGraph.output(inputs,"output")
finishedOps.add(nd4jOpDef.name)
//assertEquals("Function ${nd4jOpDef.name} failed with input $x",assertion["output"]!!.reshape(1,1),result["output"]!!.reshape(1,1))
}
else if(singleReduceOps.containsKey(nd4jOpDef.name)) {
print("Running op def $nd4jOpDef.name")
val x = singleReduceOps[mappingProcess.opName()]!!.castTo(DataType.FLOAT)
val axes = Nd4j.zeros(1).castTo(DataType.INT64)
val output = x.mean(0).reshape(2)
.castTo(DataType.FLOAT)
val graphToRun = GraphProto {
Input(createValueInfoFromTensor(x,"x"))
Input(createValueInfoFromTensor(axes,"axes",true))
//Initializer(convertedTensor)
Node(NodeProto {
name = "output"
opType = onnxOpDef.opType
Input("x")
Input("axes")
Output("output")
Attribute(Onnx.AttributeProto.newBuilder()
.setType(Onnx.AttributeProto.AttributeType.INT)
.setI(0)
.setName("keepdims").build())
})
Output(createValueInfoFromTensor(output,"output",false))
}
val onnxIRGraph = OnnxIRGraph(graphToRun,onnxOpRegistry)
val inputs = mapOf("x" to x,"axes" to axes)
val importedGraph = importGraph.importGraph(onnxIRGraph,null,null,
hashMapOf("x" to convertToOnnxTensor(x,"x"),"axes" to convertToOnnxTensor(axes,"axes")),onnxOpRegistry)
val result = importedGraph.output(inputs,"output")
val onnxGraphRunner = OnnxIRGraphRunner(onnxIRGraph,listOf("x","axes"),listOf("output"))
val assertion = onnxGraphRunner.run(inputs)
assertEquals(assertion["output"]!!.reshape(1,2),result["output"]!!.reshape(1,2),"Function ${nd4jOpDef.name} failed with input $x")
finishedOps.add(nd4jOpDef.name)
} else if(mappedOps.contains(nd4jOpDef.name)){
val graphForOp = graphForOp(nd4jOpDef.name)
graphForOp.forEach { graph ->
val onnxIRGraph = OnnxIRGraph(graph.graphDef,onnxOpRegistry)
val inputs =graph.inputArrays
val convertedArrays = HashMap<String,Onnx.TensorProto>()
graph.inputArrays.forEach { name, arr ->
convertedArrays[name] = convertToOnnxTensor(arr,name)
}
val importedGraph = importGraph.importGraph(onnxIRGraph,null,null,convertedArrays,onnxOpRegistry)
val onnxGraphRunner = OnnxIRGraphRunner(onnxIRGraph,graph.inputNames,graph.outputNames)
val assertion = onnxGraphRunner.run(inputs)
val result = importedGraph.output(inputs,graph.outputNames)
assertEquals(assertion.keys,result.keys)
result.forEach { name,arr ->
if(arr.length().toInt() == 1) {
assertEquals(assertion[name]!!.getDouble(0),arr.getDouble(0),1e-3,"Function ${nd4jOpDef.name} failed with input ${graph.inputNames}")
}
else {
assertEquals(assertion[name],arr,"Function ${nd4jOpDef.name} failed with input ${graph.inputNames}")
}
}
finishedOps.add(nd4jOpDef.name)
}
} else if(singleInputIntOutput.containsKey(nd4jOpDef.name)) {
print("Running op $nd4jOpDef.name")
val input = singleInputIntOutput[mappingProcess.opName()]!!.castTo(org.nd4j.linalg.api.buffer.DataType.INT64)
val graphToRun = GraphProto {
Input(createValueInfoFromTensor(input,"input"))
//Initializer(convertedTensor)
Node(NodeProto {
name = "output"
opType = onnxOpDef.opType
Input("input")
Output("output")
})
Output(createValueInfoFromTensor(input,"output",false ))
}
val onnxIRGraph = OnnxIRGraph(graphToRun,onnxOpRegistry)
val onnxGraphRunner = OnnxIRGraphRunner(onnxIRGraph,listOf("input"),listOf("output"))
val importedGraph = importGraph.importGraph(onnxIRGraph,null,null,HashMap(),onnxOpRegistry)
val inputs = mapOf("input" to input)
val assertion = onnxGraphRunner.run(inputs)
val result = importedGraph.output(inputs,"output")
if(assertion["output"]!!.length() == 1L)
assertEquals(assertion["output"]!!.reshape(1,1),result["output"]!!.reshape(1,1),"Function ${nd4jOpDef.name} failed with input $input")
else
assertEquals(assertion["output"]!!.ravel(),result["output"]!!.ravel(),"Function ${nd4jOpDef.name} failed with input $input")
finishedOps.add(nd4jOpDef.name)
}
}
println("Finished ops totaling ${finishedOps.size} out of ${onnxOpRegistry.mappedNd4jOpNames().size}")
}
fun graphForOp(opName: String): List<OnnxGraphInput> {
when(opName) {
"non_max_suppression_v3" -> {
/**
* TODO: Add pre and post processing for each node.
* Our NMS requires 2d, but onnx is 3d. Attempt to see
* if generalized pre/post processing node additions as part of a mapping process can work.
*
*/
print("Running op def $opName")
val boxesVal = Nd4j.create(arrayOf(
floatArrayOf(0f,0f,1f,1f),
floatArrayOf(0f,0.1f,1f,1.1f),
floatArrayOf(0f,-0.1f,1f,0.9f),
floatArrayOf(0f,10f,1f,11f)
)).reshape(1,4,4).castTo(DataType.FLOAT)
val scoresVal = Nd4j.create(listOf(0.9f,0.75f,0.6f,0.95f).toFloatArray())
.reshape(1,1,4)
.castTo(DataType.FLOAT)
val maxOutputSize = Nd4j.scalar(4.0).castTo(DataType.INT64)
val iouThreshold = Nd4j.scalar(0.5).castTo(DataType.FLOAT)
val scoreThreshold = Nd4j.scalar(0.0).castTo(DataType.FLOAT)
val inputs = mapOf("boxes" to boxesVal,"scores" to scoresVal,"max_output_boxes_per_class" to maxOutputSize,
"iou_threshold" to iouThreshold,"score_threshold" to scoreThreshold)
val output = Nd4j.scalar(1)
.castTo(org.nd4j.linalg.api.buffer.DataType.INT64)
val graphToRun = GraphProto {
Input(createValueInfoFromTensor(boxesVal,"boxes",false))
Input(createValueInfoFromTensor(scoresVal,"scores",false))
Input(createValueInfoFromTensor(maxOutputSize,"max_output_boxes_per_class",false))
Input(createValueInfoFromTensor(iouThreshold,"iou_threshold",false))
Input(createValueInfoFromTensor(scoreThreshold,"score_threshold",false))
//Initializer(convertedTensor)
Node(NodeProto {
Input("boxes")
Input("scores")
Input("max_output_boxes_per_class")
Input("iou_threshold")
Input("score_threshold")
Output("output")
name = "output"
opType = "NonMaxSuppression"
})
Output(createValueInfoFromTensor(output,"output",false))
}
return listOf(OnnxGraphInput(graphToRun,listOf("boxes","scores","max_output_boxes_per_class","iou_threshold","score_threshold"),listOf("output"),inputs,inputs))
}
"argmin","argmax" -> {
print("Running op def $opName")
val x = Nd4j.linspace(1,4,4).reshape(2,2).castTo(DataType.FLOAT)
val output = x.mean(0).reshape(2)
.castTo(org.nd4j.linalg.api.buffer.DataType.INT64)
val graphToRun = GraphProto {
Input(createValueInfoFromTensor(x,"x"))
//Initializer(convertedTensor)
Node(NodeProto {
name = "output"
opType = if(opName == "argmin") "ArgMin" else "ArgMax"
Input("x")
Output("output")
Attribute(Onnx.AttributeProto.newBuilder()
.setType(Onnx.AttributeProto.AttributeType.INT)
.setName("axis").setI(0).build())
Attribute(Onnx.AttributeProto.newBuilder()
.setType(Onnx.AttributeProto.AttributeType.INT)
.setI(0)
.setName("keepdims").build())
Attribute(Onnx.AttributeProto.newBuilder()
.setType(Onnx.AttributeProto.AttributeType.INT)
.setI(1)
.setName("select_last_index").build())
})
Output(createValueInfoFromTensor(output,"output",false))
}
val inputMap = mapOf("x" to x)
return listOf(OnnxGraphInput(graphToRun,listOf("x"),listOf("output"),inputMap,inputMap))
}
"top_k" -> {
val input = Nd4j.linspace(1,4,4).reshape(2,2).castTo(DataType.FLOAT)
val k = Nd4j.scalar(2.0).castTo(DataType.INT64).reshape(1)
val output = Nd4j.linspace(1,4,4).reshape(2,2).castTo(org.nd4j.linalg.api.buffer.DataType.INT64)
val graphToRun = GraphProto {
Input(createValueInfoFromTensor(input,"input"))
Input(createValueInfoFromTensor(k,"k"))
Node(NodeProto {
name = "output"
opType = "TopK"
Input("input")
Input("k")
Output("output")
Output("indices")
Attribute(Onnx.AttributeProto.newBuilder()
.setType(Onnx.AttributeProto.AttributeType.INT)
.setI(0)
.setName("axis").build())
Attribute(Onnx.AttributeProto.newBuilder()
.setType(Onnx.AttributeProto.AttributeType.INT)
.setI(1)
.setName("sorted").build())
Attribute(Onnx.AttributeProto.newBuilder()
.setType(Onnx.AttributeProto.AttributeType.INT)
.setI(1)
.setName("largest").build())
})
Output(createValueInfoFromTensor(input,"output",false))
Output(createValueInfoFromTensor(output,"indices",false))
}
val inputMap = mapOf("input" to input,"k" to k)
return listOf(OnnxGraphInput(graphToRun,listOf("input","k"),listOf("output","indices"),inputMap,inputMap))
}
"transpose" -> {
val input = Nd4j.linspace(1,6,6).reshape(3,2).castTo(DataType.FLOAT)
val output = Nd4j.linspace(1,6,6).reshape(2,3).castTo(DataType.FLOAT)
val graphToRun = GraphProto {
Input(createValueInfoFromTensor(input,"input"))
//Initializer(convertedTensor)
Node(NodeProto {
name = "output"
opType = "Transpose"
Input("input")
Output("output")
Attribute(Onnx.AttributeProto.newBuilder()
.setType(Onnx.AttributeProto.AttributeType.INTS)
.addInts(1).addInts(0)
.setName("perm").build())
})
Output(createValueInfoFromTensor(output,"output"))
}
val inputMap = mapOf("input" to input)
return listOf(OnnxGraphInput(graphToRun,listOf("input"),listOf("output"),inputMap,inputMap))
}
"prelu" -> {
val input = Nd4j.randn(3,4,5).castTo(DataType.FLOAT)
val alpha = Nd4j.zeros(1,1,5).addi(0.1).castTo(DataType.FLOAT)
val graphToRun = GraphProto {
Input(createValueInfoFromTensor(input,"input",false))
Input(createValueInfoFromTensor(input,"slope",false))
//Initializer(convertedTensor)
Node(NodeProto {
name = "output"
opType = "PRelu"
Input("input")
Input("slope")
Output("output")
})
Output(createValueInfoFromTensor(input,"output",false))
}
val inputMap = mapOf("input" to input,"slope" to alpha)
return listOf(OnnxGraphInput(graphToRun,listOf("input","slope"),listOf("output"),inputMap,inputMap))
}
"reduce_norm1" -> {
val input = Nd4j.linspace(1,4,4).reshape(2,2).castTo(DataType.FLOAT)
val graphToRun = GraphProto {
Input(createValueInfoFromTensor(input,"input"))
//Initializer(convertedTensor)
Node(NodeProto {
name = "output"
opType = "ReduceL1"
Input("input")
Output("output")
Attribute(Onnx.AttributeProto.newBuilder()
.setType(Onnx.AttributeProto.AttributeType.INTS)
.setInts(0,0)
.setName("axes").build())
})
Output(createValueInfoFromTensor(input,"output"))
}
val inputMap = mapOf("input" to input)
return listOf(OnnxGraphInput(graphToRun,listOf("input"),listOf("output"),inputMap,inputMap))
}
"reduce_prod" -> {
val input = Nd4j.linspace(1,4,4).reshape(2,2).castTo(DataType.FLOAT)
val graphToRun = GraphProto {
Input(createValueInfoFromTensor(input,"input"))
//Initializer(convertedTensor)
Node(NodeProto {
name = "output"
opType = "ReduceProd"
Input("input")
Output("output")
Attribute(Onnx.AttributeProto.newBuilder()
.setType(Onnx.AttributeProto.AttributeType.INTS)
.setInts(0,0)
.setName("axes").build())
})
Output(createValueInfoFromTensor(input,"output"))
}
val inputMap = mapOf("input" to input)
return listOf(OnnxGraphInput(graphToRun,listOf("input"),listOf("output"),inputMap,inputMap))
}
"reduce_norm2" -> {
val input = Nd4j.linspace(1,4,4).reshape(2,2).castTo(DataType.FLOAT)
val graphToRun = GraphProto {
Input(createValueInfoFromTensor(input,"input"))
//Initializer(convertedTensor)
Node(NodeProto {
name = "output"
opType = "ReduceL2"
Input("input")
Output("output")
Attribute(Onnx.AttributeProto.newBuilder()
.setType(Onnx.AttributeProto.AttributeType.INTS)
.setInts(0,0)
.setName("axes").build())
})
Output(createValueInfoFromTensor(input,"output"))
}
val inputMap = mapOf("input" to input)
return listOf(OnnxGraphInput(graphToRun,listOf("input"),listOf("output"),inputMap,inputMap))
}
"reduce_mean" -> {
val input = Nd4j.linspace(1,4,4).reshape(2,2).castTo(DataType.FLOAT)
val graphToRun = GraphProto {
Input(createValueInfoFromTensor(input,"input"))
//Initializer(convertedTensor)
Node(NodeProto {
name = "output"
opType = "ReduceMean"
Input("input")
Output("output")
Attribute(Onnx.AttributeProto.newBuilder()
.setType(Onnx.AttributeProto.AttributeType.INTS)
.setInts(0,0)
.setName("axes").build())
})
Output(createValueInfoFromTensor(input,"output"))
}
val inputMap = mapOf("input" to input)
return listOf(OnnxGraphInput(graphToRun,listOf("input"),listOf("output"),inputMap,inputMap))
}
"reduce_max" -> {
val input = Nd4j.linspace(1,4,4).reshape(2,2).castTo(DataType.FLOAT)
val graphToRun = GraphProto {
Input(createValueInfoFromTensor(input,"input"))
//Initializer(convertedTensor)
Node(NodeProto {
name = "output"
opType = "ReduceMax"
Input("input")
Output("output")
Attribute(Onnx.AttributeProto.newBuilder()
.setType(Onnx.AttributeProto.AttributeType.INTS)
.setInts(0,0)
.setName("axes").build())
})
Output(createValueInfoFromTensor(input,"output"))
}
val inputMap = mapOf("input" to input)
return listOf(OnnxGraphInput(graphToRun,listOf("input"),listOf("output"),inputMap,inputMap))
}
"elu","leakyrelu" -> {
val input = Nd4j.scalar(1.0f).castTo(DataType.FLOAT)
val graphToRun = GraphProto {
Input(createValueInfoFromTensor(input,"input"))
//Initializer(convertedTensor)
Node(NodeProto {
name = "output"
opType = if(name == "elu") "Elu" else "LeakyRelu"
Input("input")
Output("output")
Attribute(Onnx.AttributeProto.newBuilder()
.setType(Onnx.AttributeProto.AttributeType.FLOAT)
.setF(1.0f)
.setName("alpha").build())
})
Output(createValueInfoFromTensor(input,"output"))
}
val inputMap = mapOf("input" to input)
return listOf(OnnxGraphInput(graphToRun,listOf("input"),listOf("output"),inputMap,inputMap))
}
"flatten_2d" -> {
val x = Nd4j.randn(2,3,4).castTo(org.nd4j.linalg.api.buffer.DataType.DOUBLE)
val graphToRun = GraphProto {
Input(createValueInfoFromTensor(x,"x"))
//Initializer(convertedTensor)
Node(NodeProto {
name = "output"
opType = "Flatten"
Input("x")
Output("output")
Attribute(Onnx.AttributeProto.newBuilder()
.setType(Onnx.AttributeProto.AttributeType.INT)
.setI(1)
.setName("axis").build())
})
Output(createValueInfoFromTensor(x,"output",false))
}
val inputMap = mapOf("x" to x)
return listOf(OnnxGraphInput(graphToRun,listOf("x"),listOf("output"),inputMap,inputMap))
}
"mod" -> {
val x = Nd4j.scalar(2.0).castTo(org.nd4j.linalg.api.buffer.DataType.DOUBLE)
val y = Nd4j.scalar(2.0).castTo(org.nd4j.linalg.api.buffer.DataType.DOUBLE)
val graphToRun = GraphProto {
Input(createValueInfoFromTensor(x,"x"))
Input(createValueInfoFromTensor(y,"y"))
//Initializer(convertedTensor)
Node(NodeProto {
name = "output"
opType = "Mod"
Input("x")
Input("y")
Output("output")
Attribute(Onnx.AttributeProto.newBuilder()
.setType(Onnx.AttributeProto.AttributeType.INT)
.setI(1)
.setName("fmod").build())
})
Output(createValueInfoFromTensor(x,"output"))
}
val inputMap = mapOf("x" to x,"y" to y)
return listOf(OnnxGraphInput(graphToRun,listOf("x","y"),listOf("output"),inputMap,inputMap))
}
else -> {
throw IllegalArgumentException("Illegal op name $opName")
}
}
}
} | apache-2.0 | a097fea8a60c6ab416dad7a5611887b6 | 40.500221 | 180 | 0.523544 | 4.467449 | false | false | false | false |
smmribeiro/intellij-community | plugins/kotlin/project-wizard/core/src/org/jetbrains/kotlin/tools/projectWizard/plugins/templates/TemplatesPlugin.kt | 5 | 9814 | // 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.tools.projectWizard.plugins.templates
import org.jetbrains.kotlin.tools.projectWizard.core.*
import org.jetbrains.kotlin.tools.projectWizard.core.Defaults.SRC_DIR
import org.jetbrains.kotlin.tools.projectWizard.core.entity.PipelineTask
import org.jetbrains.kotlin.tools.projectWizard.core.entity.properties.Property
import org.jetbrains.kotlin.tools.projectWizard.core.entity.settings.PluginSetting
import org.jetbrains.kotlin.tools.projectWizard.core.service.TemplateEngineService
import org.jetbrains.kotlin.tools.projectWizard.ir.buildsystem.*
import org.jetbrains.kotlin.tools.projectWizard.moduleConfigurators.JvmModuleConfigurator
import org.jetbrains.kotlin.tools.projectWizard.moduleConfigurators.KotlinTestFramework
import org.jetbrains.kotlin.tools.projectWizard.moduleConfigurators.settingValue
import org.jetbrains.kotlin.tools.projectWizard.phases.GenerationPhase
import org.jetbrains.kotlin.tools.projectWizard.plugins.buildSystem.BuildSystemPlugin
import org.jetbrains.kotlin.tools.projectWizard.plugins.kotlin.KotlinPlugin
import org.jetbrains.kotlin.tools.projectWizard.plugins.pomIR
import org.jetbrains.kotlin.tools.projectWizard.plugins.projectName
import org.jetbrains.kotlin.tools.projectWizard.settings.buildsystem.SourcesetType
import org.jetbrains.kotlin.tools.projectWizard.settings.buildsystem.updateBuildFiles
import org.jetbrains.kotlin.tools.projectWizard.settings.javaPackage
import org.jetbrains.kotlin.tools.projectWizard.templates.*
import org.jetbrains.kotlin.tools.projectWizard.transformers.interceptors.InterceptionPoint
import org.jetbrains.kotlin.tools.projectWizard.transformers.interceptors.TemplateInterceptionApplicationState
import org.jetbrains.kotlin.tools.projectWizard.transformers.interceptors.applyAll
import java.nio.file.Path
import java.util.*
class TemplatesPlugin(context: Context) : Plugin(context) {
override val path = pluginPath
companion object : PluginSettingsOwner() {
override val pluginPath = "templates"
val templates by property<Map<String, Template>>(emptyMap())
val addTemplate by task1<Template, Unit> {
withAction { template ->
templates.update { success(it + (template.id to template)) }
}
}
val fileTemplatesToRender by property<List<FileTemplate>>(emptyList())
val addFileTemplate by task1<FileTemplate, Unit> {
withAction { template ->
fileTemplatesToRender.update { success(it + template) }
}
}
val addFileTemplates by task1<List<FileTemplate>, Unit> {
withAction { templates ->
fileTemplatesToRender.addValues(templates)
}
}
val renderFileTemplates by pipelineTask(GenerationPhase.PROJECT_GENERATION) {
runAfter(KotlinPlugin.createModules)
withAction {
val templateEngine = service<TemplateEngineService>()
fileTemplatesToRender.propertyValue.mapSequenceIgnore { template ->
with(templateEngine) { writeTemplate(template) }
}
}
}
val addTemplatesToModules by pipelineTask(GenerationPhase.PROJECT_GENERATION) {
runBefore(BuildSystemPlugin.createModules)
runAfter(KotlinPlugin.createModules)
withAction {
updateBuildFiles { buildFile ->
val moduleStructure = buildFile.modules
val moduleIRs = buildList<ModuleIR> {
if (moduleStructure is MultiplatformModulesStructureIR) {
+moduleStructure.multiplatformModule
}
+moduleStructure.modules
}
moduleIRs.mapSequence { module ->
applyTemplateToModule(
module.template,
module
).map { result -> result.updateModuleIR(module.withIrs(result.librariesToAdd)) to result }
}.map {
val (moduleIrs, results) = it.unzip()
val foldedResults = results.fold()
buildFile.copy(
modules = buildFile.modules.withModules(moduleIrs.filterNot { it is FakeMultiplatformModuleIR })
).withIrs(foldedResults.irsToAddToBuildFile).let { buildFile ->
when (val structure = buildFile.modules) {
is MultiplatformModulesStructureIR ->
buildFile.copy(
modules = structure
.updateTargets(foldedResults.updateTarget)
.updateSourceSets(foldedResults.updateModuleIR)
)
else -> buildFile
}
}
}
}
}
}
val postApplyTemplatesToModules by pipelineTask(GenerationPhase.PROJECT_GENERATION) {
runBefore(BuildSystemPlugin.createModules)
runAfter(KotlinPlugin.createModules)
runAfter(TemplatesPlugin.addTemplatesToModules)
withAction {
updateBuildFiles { buildFile ->
val modules = buildFile.modules.modules
val applicationState = modules.mapNotNull { module ->
module.template?.let {
with(it) {
createInterceptors(module)
}
}
}.flatten()
.applyAll(TemplateInterceptionApplicationState(buildFile, emptyMap()))
val templateEngine = service<TemplateEngineService>()
val templatesApplicationResult = modules.map { module ->
val settings = applicationState.moduleToSettings[module.originalModule.identificator].orEmpty()
applyFileTemplatesFromSourceset(module, templateEngine, settings)
}.sequenceIgnore()
templatesApplicationResult andThen applicationState.buildFileIR.asSuccess()
}
}
}
private fun Writer.applyFileTemplatesFromSourceset(
module: ModuleIR,
templateEngine: TemplateEngineService,
interceptionPointSettings: Map<InterceptionPoint<Any>, Any>
): TaskResult<Unit> {
val template = module.template ?: return UNIT_SUCCESS
val settings = with(template) { settingsAsMap(module.originalModule) }
val allSettings: Map<String, Any> = mutableMapOf<String, Any>().apply {
putAll(settings)
putAll(interceptionPointSettings.mapKeys { it.key.name })
putAll(defaultSettings(module))
}
return with(template) { getFileTemplates(module) }.mapNotNull { (fileTemplateDescriptor, filePath, settings) ->
val path = generatePathForFileTemplate(module, filePath) ?: return@mapNotNull null
val fileTemplate = FileTemplate(
fileTemplateDescriptor,
module.path / path,
allSettings + settings
)
with(templateEngine) { writeTemplate(fileTemplate) }
}.sequenceIgnore()
}
private fun Reader.defaultSettings(moduleIR: ModuleIR) = mapOf(
"projectName" to projectName,
"moduleName" to moduleIR.name,
"package" to moduleIR.originalModule.javaPackage(pomIR()).asCodePackage()
)
private fun Reader.generatePathForFileTemplate(module: ModuleIR, filePath: FilePath): Path? {
if (filePath is SrcFilePath
&& filePath.sourcesetType == SourcesetType.test
&& settingValue(module.originalModule, JvmModuleConfigurator.testFramework) == KotlinTestFramework.NONE
) return null
val moduleConfigurator = module.originalModule.configurator
return when (module) {
is SingleplatformModuleIR -> {
when (filePath) {
is SrcFilePath -> SRC_DIR / filePath.sourcesetType.toString() / moduleConfigurator.kotlinDirectoryName
is ResourcesFilePath -> SRC_DIR / filePath.sourcesetType.toString() / moduleConfigurator.resourcesDirectoryName
}
}
is MultiplatformModuleIR -> {
val directory = when (filePath) {
is SrcFilePath -> moduleConfigurator.kotlinDirectoryName
is ResourcesFilePath -> moduleConfigurator.resourcesDirectoryName
}
SRC_DIR / "${module.name}${filePath.sourcesetType.name.capitalize(Locale.US)}" / directory
}
else -> error("Not supported for ${module.javaClass}")
}
}
}
override val settings: List<PluginSetting<*, *>> = listOf()
override val pipelineTasks: List<PipelineTask> =
listOf(
renderFileTemplates,
addTemplatesToModules,
postApplyTemplatesToModules
)
override val properties: List<Property<*>> =
listOf(
templates,
fileTemplatesToRender
)
}
| apache-2.0 | 7db1713b1f8b9ad3603b2cdc66692145 | 47.107843 | 158 | 0.611473 | 5.852117 | false | true | false | false |
smmribeiro/intellij-community | plugins/stream-debugger/src/com/intellij/debugger/streams/ui/impl/ValueWithPositionImpl.kt | 16 | 1873 | // Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.debugger.streams.ui.impl
import com.intellij.debugger.streams.trace.TraceElement
import com.intellij.debugger.streams.ui.ValueWithPosition
/**
* @author Vitaliy.Bibaev
*/
data class ValueWithPositionImpl(override val traceElement: TraceElement) : ValueWithPosition {
companion object {
const val INVALID_POSITION: Int = Int.MIN_VALUE
const val DEFAULT_VISIBLE_VALUE: Boolean = false
const val DEFAULT_HIGHLIGHTING_VALUE: Boolean = false
}
private var myPosition: Int = INVALID_POSITION
private var myIsVisible: Boolean = DEFAULT_VISIBLE_VALUE
private var myIsHighlighted: Boolean = DEFAULT_HIGHLIGHTING_VALUE
override fun equals(other: Any?): Boolean {
return other != null && other is ValueWithPosition && traceElement == other.traceElement
}
override fun hashCode(): Int = traceElement.hashCode()
override val isVisible: Boolean
get() = myIsVisible
override val position: Int
get() = myPosition
override val isHighlighted: Boolean
get() = myIsHighlighted
fun updateToInvalid(): Boolean =
updateProperties(INVALID_POSITION, DEFAULT_VISIBLE_VALUE, DEFAULT_HIGHLIGHTING_VALUE)
fun setInvalid(): Unit =
setProperties(INVALID_POSITION, DEFAULT_VISIBLE_VALUE, DEFAULT_HIGHLIGHTING_VALUE)
fun updateProperties(position: Int, isVisible: Boolean, isHighlighted: Boolean): Boolean {
val changed = myPosition != position || myIsVisible != isVisible || myIsHighlighted != isHighlighted
setProperties(position, isVisible, isHighlighted)
return changed
}
fun setProperties(position: Int, isVisible: Boolean, isHighlighted: Boolean) {
myPosition = position
myIsHighlighted = isHighlighted
myIsVisible = isVisible
}
} | apache-2.0 | 93bb68cc61cf1d0346b408dfcda4da82 | 34.358491 | 140 | 0.753871 | 4.579462 | false | false | false | false |
smmribeiro/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/goto/KotlinSearchEverywherePsiRenderer.kt | 6 | 1808 | // 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.goto
import com.intellij.ide.actions.SearchEverywherePsiRenderer
import com.intellij.openapi.components.Service
import com.intellij.openapi.components.service
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiElement
import org.jetbrains.kotlin.idea.caches.resolve.resolveToDescriptorIfAny
import org.jetbrains.kotlin.idea.core.KotlinPluginDisposable
import org.jetbrains.kotlin.idea.util.IdeDescriptorRenderers
import org.jetbrains.kotlin.psi.KtNamedFunction
import org.jetbrains.kotlin.renderer.ParameterNameRenderingPolicy
@Service
internal class KotlinSearchEverywherePsiRenderer(project: Project) :
SearchEverywherePsiRenderer(KotlinPluginDisposable.getInstance(project)) {
companion object {
private val RENDERER = IdeDescriptorRenderers.SOURCE_CODE_SHORT_NAMES_NO_ANNOTATIONS.withOptions {
parameterNameRenderingPolicy = ParameterNameRenderingPolicy.NONE
modifiers = emptySet()
startFromName = false
}
fun getInstance(project: Project): KotlinSearchEverywherePsiRenderer = project.service()
}
override fun getElementText(element: PsiElement?): String {
if (element !is KtNamedFunction) return super.getElementText(element)
val descriptor = element.resolveToDescriptorIfAny() ?: return ""
return buildString {
descriptor.extensionReceiverParameter?.let { append(RENDERER.renderType(it.type)).append('.') }
append(element.name)
descriptor.valueParameters.joinTo(this, prefix = "(", postfix = ")") { RENDERER.renderType(it.type) }
}
}
}
| apache-2.0 | 613d73f3b6446192d779c22dc64af176 | 46.578947 | 158 | 0.760509 | 4.980716 | false | false | false | false |
kohesive/kohesive-iac | cloudtrail-tool/src/main/kotlin/uy/kohesive/iac/model/aws/cloudtrail/Model.kt | 1 | 4453 | package uy.kohesive.iac.model.aws.cloudtrail
import com.amazonaws.codegen.model.intermediate.ListModel
import com.amazonaws.codegen.model.intermediate.MapModel
import com.amazonaws.codegen.model.intermediate.MemberModel
import com.amazonaws.codegen.model.intermediate.ShapeModel
import com.amazonaws.util.DateUtils
import org.apache.commons.lang3.StringEscapeUtils
import uy.kohesive.iac.model.aws.cloudtrail.utils.DateTime
import java.util.*
typealias RequestMap = Map<String, Any?>
data class CloudTrailEvent(
val eventId: String,
val eventSourceUri: String?,
val eventSource: String,
val eventName: String,
val apiVersion: String?,
val eventTime: Date,
val request: RequestMap?
) {
override fun toString(): String {
return "id=$eventId, type=$eventName, time=${DateUtils.formatISO8601Date(eventTime)}"
}
}
data class RequestMapNode(
val shape: ShapeModel? = null,
val members: MutableList<RequestMapNodeMember> = mutableListOf(),
val constructorArgs: MutableList<RequestMapNodeMember> = mutableListOf(),
var simpleType: String? = null,
var simpleValue: Any? = null,
var listModel: ListModel? = null,
var vararg: Boolean = false,
val mapModel: MapModel? = null,
var enumValue: String? = null,
val dateValue: DateTime? = null
) {
companion object {
fun simple(type: String, value: Any?) = RequestMapNode(
simpleType = type,
simpleValue = value
)
fun date(dateValue: String) = RequestMapNode(
dateValue = DateTime.parse(dateValue)
)
fun complex(shape: ShapeModel, members: List<RequestMapNodeMember>) = RequestMapNode(
shape = shape,
members = members.toMutableList()
)
fun list(listModel: ListModel, items: List<RequestMapNodeMember>) = RequestMapNode(
listModel = listModel,
members = items.toMutableList()
)
fun map(mapModel: MapModel, items: List<RequestMapNodeMember>) = RequestMapNode(
mapModel = mapModel,
members = items.toMutableList()
)
fun enum(enumValue: String, shape: ShapeModel) = RequestMapNode(
shape = shape,
enumValue = enumValue
)
}
val simpleValueLiteral: Any? by lazy { getSimpleValueLiteral_() }
fun isEmpty(): Boolean =
((isStructure() || isList() || isMap()) && members.isEmpty()) ||
(isSimple() && simpleValueLiteral == null) ||
(isEnum() && enumValue == null)
fun isEnum() = enumValue != null
fun isList() = listModel != null
fun isMap() = mapModel != null
fun isSimple() = simpleValue != null
fun isStructure() = shape != null && enumValue == null
fun isDate() = dateValue != null
fun getDateFormatted(): String = dateValue?.getISO8601Date() ?: "(unknown date)"
private fun getSimpleValueLiteral_(): Any? {
if (!isSimple()) throw IllegalStateException("Not a simple value")
val capturedSimpleValue = simpleValue
val extractedSimpleValue = (if (capturedSimpleValue is Map<*, *>) {
capturedSimpleValue.keys.firstOrNull()?.let { firstKey ->
capturedSimpleValue[firstKey]
}
} else {
capturedSimpleValue
}) ?: return null
if (simpleType == "Integer") {
if (simpleValue is Int) {
return simpleValue
} else {
return simpleValue?.toString()?.toInt()
}
} else if (simpleType == "Long") {
if (simpleValue is Long) {
return simpleValue
} else {
return simpleValue?.toString()?.toLong()
}
}
if (extractedSimpleValue is String) {
return "\"${StringEscapeUtils.escapeJava(extractedSimpleValue.toString())}\"".replace("$", "\\$")
} else if (extractedSimpleValue is Number) {
return extractedSimpleValue.toString()
} else if (extractedSimpleValue is Boolean) {
return extractedSimpleValue.toString()
} else {
throw IllegalStateException("Unsupported simple value: ${simpleValue?.javaClass?.simpleName}")
}
}
}
data class RequestMapNodeMember(
var memberModel: MemberModel,
val value: RequestMapNode?,
val key: String? = null // for maps
)
| mit | 686d841b0d783b7c98b3efd775b23e9a | 31.268116 | 109 | 0.62093 | 4.609731 | false | false | false | false |
cout970/Modeler | src/main/kotlin/com/cout970/modeler/core/export/glTF/GLTFBuilder.kt | 1 | 23812 | package com.cout970.modeler.core.export.glTF
import com.cout970.glutilities.texture.Texture
import com.cout970.matrix.api.IMatrix2
import com.cout970.matrix.api.IMatrix3
import com.cout970.matrix.api.IMatrix4
import com.cout970.modeler.NAME
import com.cout970.vector.api.IQuaternion
import com.cout970.vector.api.IVector2
import com.cout970.vector.api.IVector3
import com.cout970.vector.api.IVector4
import com.cout970.vector.extensions.Vector3
import com.cout970.vector.extensions.Vector4
import com.cout970.vector.extensions.vec3Of
import java.nio.ByteBuffer
import java.nio.ByteOrder
import java.util.*
fun testExporter() = glftModel {
useExtensions("myExtension")
requireExtensions("myExtrensionLoader")
asset {
copyright = "GNU GPL v3"
}
var rootNodeId: UUID? = null
scene {
node {
name = "root"
rootNodeId = id
transformation {
translation = Vector3.ZERO
scale = Vector3.ONE
}
node {
name = "child1"
cubeMesh(this)
}
}
}
animation {
name = "Translation to (1,1,1)"
channel {
node = rootNodeId
interpolation = LINEAR
transformType = TRANSLATION
timeValues = buffer(FLOAT, listOf(1f, 2f, 3f, 4f))
transformValues = buffer(FLOAT, listOf(vec3Of(0), vec3Of(1), vec3Of(1), vec3Of(0)))
}
}
}
private fun GLTFBuilder.cubeMesh(node: GLTFBuilder.Node) = node.apply {
mesh {
name = "Cube"
primitive {
mode = TRIANGLES
attributes[POSITION] = buffer(FLOAT, listOf(
vec3Of(-1.0f, 1.0f, 1.0f),
vec3Of(1.0f, 1.0f, 1.0f),
vec3Of(-1.0f, -1.0f, 1.0f),
vec3Of(1.0f, -1.0f, 1.0f),
vec3Of(-1.0f, 1.0f, -1.0f),
vec3Of(1.0f, 1.0f, -1.0f),
vec3Of(-1.0f, -1.0f, -1.0f),
vec3Of(1.0f, -1.0f, -1.0f)
))
indices = buffer(UNSIGNED_INT, listOf(
0, 1, 2, // 0
1, 3, 2,
4, 6, 5, // 2
5, 6, 7,
0, 2, 4, // 4
4, 2, 6,
1, 5, 3, // 6
5, 7, 3,
0, 4, 1, // 8
4, 5, 1,
2, 3, 6, // 10
6, 3, 7
))
}
}
}
fun glftModel(func: GLTFBuilder.() -> Unit): Pair<GltfFile, ByteArray> {
val builder = GLTFBuilder()
builder.func()
return builder.build()
}
fun main(args: Array<String>) {
println(testExporter().first)
}
class GLTFBuilder {
private val extensionsUsed = mutableListOf<String>()
private val extensionsRequired = mutableListOf<String>()
private val asset = Asset()
private val scenes = mutableListOf<Scene>()
private val bakedMaterials = mutableListOf<GltfMaterial>()
private val materialsMap = mutableMapOf<UUID, Int>()
private val bakedImages = mutableListOf<GltfImage>()
private val bakedSamplers = mutableListOf<GltfSampler>()
private val bakedTextures = mutableListOf<GltfTexture>()
private val bakedNodes = mutableListOf<GltfNode>()
private val nodeIdToIndex = mutableMapOf<UUID, Int>()
private val bakedMeshes = mutableListOf<GltfMesh>()
private var buffer = ByteBuffer.allocate(16).order(ByteOrder.LITTLE_ENDIAN)
private val bakedBufferViews = mutableListOf<GltfBufferView>()
private val bakedAccessors = mutableListOf<GltfAccessor>()
private val animations = mutableListOf<Animation>()
private val meshToId = mutableMapOf<Mesh, Int>()
private val bufferToId = mutableMapOf<UUID, Int>()
var bufferName = "model.bin"
fun useExtensions(vararg extensionsUsed: String) {
this.extensionsUsed.addAll(extensionsUsed)
}
fun requireExtensions(vararg extensionsRequired: String) {
this.extensionsRequired.addAll(extensionsRequired)
}
fun build(): Pair<GltfFile, ByteArray> {
val scenes = scenes.build()
val animations = animations.map { it.build() }
val binary = buffer.toArray()
return GltfFile(
asset = asset.build(),
nodes = bakedNodes,
meshes = bakedMeshes,
bufferViews = bakedBufferViews,
accessors = bakedAccessors,
scene = 0,
scenes = scenes,
buffers = listOf(GltfBuffer(uri = bufferName, byteLength = binary.size)),
materials = bakedMaterials,
animations = animations,
images = bakedImages,
textures = bakedTextures,
samplers = bakedSamplers
) to binary
}
data class Asset(
var copyright: String? = null
)
fun asset(func: Asset.() -> Unit) {
this.asset.func()
}
fun Asset.build(): JsObject {
val map = mutableMapOf(
"generator" to "$NAME glTF v2 Exporter",
"version" to "2.0"
)
copyright?.let { map["copyright"] = it }
return map
}
data class Scene(
val nodes: MutableList<Node> = mutableListOf(),
var name: String? = null,
var extras: Any? = null
)
fun scene(func: Scene.() -> Unit) {
scenes.add(Scene().apply(func))
}
@JvmName("buildScenes")
private fun List<Scene>.build(): List<GltfScene> {
return map { it.build() }
}
fun Scene.build(): GltfScene {
val indices = nodes.map {
it.build()
bakedNodes.size - 1
}
return GltfScene(
nodes = indices,
name = name,
extras = extras
)
}
data class Node(
val id: UUID = UUID.randomUUID(),
var transformation: Transformation? = null,
var name: String? = null,
var children: MutableList<Node>? = null,
var mesh: Mesh? = null,
var extras: Any? = null
)
sealed class Transformation {
data class Matrix(var matrix: IMatrix4) : Transformation()
data class TRS(
var translation: IVector3? = null,
var rotation: IQuaternion? = null,
var scale: IVector3? = null
) : Transformation()
}
fun Scene.node(func: Node.() -> Unit) {
nodes.add(Node().apply(func))
}
fun Node.node(func: Node.() -> Unit) {
val list = children ?: mutableListOf()
list.add(Node().apply(func))
children = list
}
fun Node.transformation(mat: IMatrix4) {
transformation = Transformation.Matrix(mat)
}
fun Node.transformation(func: Transformation.TRS.() -> Unit) {
transformation = Transformation.TRS().apply(func)
}
@JvmName("buildNodes")
private fun List<Node>.build(): List<GltfNode> {
bakedNodes.clear()
forEach { it.build() }
return bakedNodes
}
fun Node.build(): GltfNode {
val bakedChildren = children?.map { it.build() }
val t = transformation
val m = mesh?.build()
val node = GltfNode(
name = name,
matrix = (t as? Transformation.Matrix)?.matrix,
translation = (t as? Transformation.TRS)?.translation,
rotation = (t as? Transformation.TRS)?.rotation,
scale = (t as? Transformation.TRS)?.scale,
children = bakedChildren?.map { bakedNodes.indexOf(it) } ?: emptyList(),
mesh = m,
extras = extras
)
nodeIdToIndex[id] = bakedNodes.size
bakedNodes.add(node)
return node
}
data class Mesh(
var name: String? = null,
var primitives: MutableList<Primitive> = mutableListOf(),
var weights: MutableList<Double> = mutableListOf()
)
fun Node.mesh(func: Mesh.() -> Unit) {
mesh = Mesh().apply(func)
}
fun Mesh.build(): Int? {
if (this in meshToId) {
return meshToId[this]
}
val mesh = GltfMesh(primitives.map { it.build() }, weights, name)
bakedMeshes.add(mesh)
meshToId[this] = bakedMeshes.size - 1
return bakedMeshes.size - 1
}
@Suppress("PropertyName", "unused")
data class Primitive(
val attributes: MutableMap<String, UnpackedBuffer> = mutableMapOf(),
var indices: UnpackedBuffer? = null,
var material: Material? = null,
var mode: GltfMode = GltfMode.TRIANGLES,
val targets: MutableMap<String, Int> = mutableMapOf()
) {
// this avoids having to import ComponentType.*
inline val BYTE: GltfComponentType get() = GltfComponentType.BYTE
inline val UNSIGNED_BYTE: GltfComponentType get() = GltfComponentType.UNSIGNED_BYTE
inline val SHORT: GltfComponentType get() = GltfComponentType.SHORT
inline val UNSIGNED_SHORT: GltfComponentType get() = GltfComponentType.UNSIGNED_SHORT
inline val UNSIGNED_INT: GltfComponentType get() = GltfComponentType.UNSIGNED_INT
inline val FLOAT: GltfComponentType get() = GltfComponentType.FLOAT
// this avoids having to import Attribute.*
inline val POSITION: String get() = GltfAttribute.POSITION.name
inline val NORMAL: String get() = GltfAttribute.NORMAL.name
inline val TANGEN: String get() = GltfAttribute.TANGENT.name
inline val TEXCOORD_0: String get() = GltfAttribute.TEXCOORD_0.name
inline val TEXCOORD_1: String get() = GltfAttribute.TEXCOORD_1.name
inline val COLOR_0: String get() = GltfAttribute.COLOR_0.name
inline val JOINTS_0: String get() = GltfAttribute.JOINTS_0.name
inline val WEIGHTS_0: String get() = GltfAttribute.WEIGHTS_0.name
// this avoids having to import GLMode.*
inline val POINTS: GltfMode get() = GltfMode.POINTS
inline val LINES: GltfMode get() = GltfMode.LINES
inline val LINE_LOOP: GltfMode get() = GltfMode.LINE_LOOP
inline val LINE_STRIP: GltfMode get() = GltfMode.LINE_STRIP
inline val TRIANGLES: GltfMode get() = GltfMode.TRIANGLES
inline val TRIANGLE_STRIP: GltfMode get() = GltfMode.TRIANGLE_STRIP
inline val TRIANGLE_FAN: GltfMode get() = GltfMode.TRIANGLE_FAN
inline val QUADS: GltfMode get() = GltfMode.QUADS
inline val QUAD_STRIP: GltfMode get() = GltfMode.QUAD_STRIP
inline val POLYGON: GltfMode get() = GltfMode.POLYGON
}
fun Mesh.primitive(func: Primitive.() -> Unit) {
primitives.add(Primitive().apply(func))
}
inline fun <reified T> buffer(type: GltfComponentType, data: List<T>, indices: Boolean = false): UnpackedBuffer {
val container: GltfType = when {
Number::class.java.isAssignableFrom(T::class.java) -> GltfType.SCALAR
IVector2::class.java.isAssignableFrom(T::class.java) -> GltfType.VEC2
IVector3::class.java.isAssignableFrom(T::class.java) -> GltfType.VEC3
IVector4::class.java.isAssignableFrom(T::class.java) -> GltfType.VEC4
IMatrix2::class.java.isAssignableFrom(T::class.java) -> GltfType.MAT2
IMatrix3::class.java.isAssignableFrom(T::class.java) -> GltfType.MAT3
IMatrix4::class.java.isAssignableFrom(T::class.java) -> GltfType.MAT4
else -> {
error("Invalid buffer type")
}
}
return UnpackedBuffer(container, type, data, indices)
}
fun Primitive.build(): GltfPrimitive {
val matIndex: Int? = material?.build()
return GltfPrimitive(
attributes = attributes.mapValues { it.value.build() },
indices = indices?.build(),
material = matIndex,
mode = mode.code,
targets = targets
)
}
fun Primitive.material(func: Material.() -> Unit) {
material = Material().apply(func)
}
fun Material.build(): Int {
require(id != null) { "Material doesn't have ID" }
if (id in materialsMap) {
return materialsMap[id!!]!!
}
materialsMap[id!!] = bakedMaterials.size
bakedMaterials.add(GltfMaterial(
pbrMetallicRoughness = pbrMetallicRoughness?.build(),
normalTexture = normalTexture,
occlusionTexture = occlusionTexture,
emissiveTexture = emissiveTexture,
emissiveFactor = emissiveFactor,
alphaMode = alphaMode ?: GltfAlphaMode.MASK,
alphaCutoff = alphaCutoff ?: 0.5,
doubleSided = doubleSided
))
return bakedMaterials.size - 1
}
data class UnpackedBuffer(
val containerType: GltfType,
val elementType: GltfComponentType,
val data: List<*>,
val indices: Boolean,
val uuid: UUID = UUID.randomUUID()
) {
init {
require(data.isNotEmpty()) { "Unable to build an empty Buffer" }
val size = elementType.size * containerType.numComponents * data.size
require(size != 0) { "Unable to build a Buffer of size 0" }
}
}
@Suppress("UNCHECKED_CAST")
fun UnpackedBuffer.build(animation: Boolean = false): Int {
if (this.uuid in bufferToId) {
return bufferToId[this.uuid]!!
}
val size = elementType.size * containerType.numComponents * data.size
val index = bakedBufferViews.size
val view = GltfBufferView(
buffer = 0,
name = null,
byteLength = size,
byteOffset = buffer.position(),
byteStride = null,
target = if (animation) null else if (indices) 34963 else 34962
)
val accessor = GltfAccessor(
bufferView = index,
byteOffset = 0,
componentType = elementType.id,
normalized = false,
count = data.size,
type = containerType,
min = getMin(this),
max = getMax(this),
name = null
)
val put = { n: Number ->
if (buffer.capacity() < buffer.position() + 16 * 4) {
buffer = buffer.expand(buffer.capacity() * 2)
}
when (elementType) {
GltfComponentType.BYTE, GltfComponentType.UNSIGNED_BYTE -> buffer.put(n.toByte())
GltfComponentType.SHORT, GltfComponentType.UNSIGNED_SHORT -> buffer.putShort(n.toShort())
GltfComponentType.UNSIGNED_INT -> buffer.putInt(n.toInt())
GltfComponentType.FLOAT -> buffer.putFloat(n.toFloat())
}
Unit
}
when (containerType) {
GltfType.SCALAR -> (data as List<Number>).forEach(put)
GltfType.VEC2 -> (data as List<IVector2>).forEach { put(it.x); put(it.y) }
GltfType.VEC3 -> (data as List<IVector3>).forEach { put(it.x); put(it.y); put(it.z) }
GltfType.VEC4 -> (data as List<IVector4>).forEach { put(it.x); put(it.y); put(it.z); put(it.w) }
GltfType.MAT2, GltfType.MAT3, GltfType.MAT4 -> error("Matrix storage not supported")
}
bakedBufferViews.add(view)
bakedAccessors.add(accessor)
bufferToId[this.uuid] = index
return index
}
private fun getMin(buff: UnpackedBuffer): List<Double> {
val numbers = mutableListOf<List<Double>>()
when (buff.containerType) {
GltfType.SCALAR -> {
numbers += buff.data.map { (it as Number).toDouble() }
}
GltfType.VEC2 -> {
val vecs = buff.data.map { it as IVector2 }
numbers += vecs.map { it.xd }
numbers += vecs.map { it.yd }
}
GltfType.VEC3 -> {
val vecs = buff.data.map { it as IVector3 }
numbers += vecs.map { it.xd }
numbers += vecs.map { it.yd }
numbers += vecs.map { it.zd }
}
GltfType.VEC4 -> {
val vecs = buff.data.map { it as IVector4 }
numbers += vecs.map { it.xd }
numbers += vecs.map { it.yd }
numbers += vecs.map { it.zd }
numbers += vecs.map { it.wd }
}
GltfType.MAT2, GltfType.MAT3, GltfType.MAT4 -> error("Not supported")
}
return numbers.map { it.min() ?: 0.0 }
}
private fun getMax(buff: UnpackedBuffer): List<Double> {
val numbers = mutableListOf<List<Double>>()
when (buff.containerType) {
GltfType.SCALAR -> {
numbers += buff.data.map { (it as Number).toDouble() }
}
GltfType.VEC2 -> {
val vecs = buff.data.map { it as IVector2 }
numbers += vecs.map { it.xd }
numbers += vecs.map { it.yd }
}
GltfType.VEC3 -> {
val vecs = buff.data.map { it as IVector3 }
numbers += vecs.map { it.xd }
numbers += vecs.map { it.yd }
numbers += vecs.map { it.zd }
}
GltfType.VEC4 -> {
val vecs = buff.data.map { it as IVector4 }
numbers += vecs.map { it.xd }
numbers += vecs.map { it.yd }
numbers += vecs.map { it.zd }
numbers += vecs.map { it.wd }
}
GltfType.MAT2, GltfType.MAT3, GltfType.MAT4 -> error("Not supported")
}
return numbers.map { it.max() ?: 0.0 }
}
fun ByteBuffer.toArray(): ByteArray {
val array = ByteArray(position())
flip()
repeat(array.size) {
array[it] = get()
}
return array
}
fun ByteBuffer.expand(newSize: Int): ByteBuffer {
this.flip()
return ByteBuffer.allocate(newSize).put(this).order(ByteOrder.LITTLE_ENDIAN)
}
data class Material(
var id: UUID? = null,
var pbrMetallicRoughness: PbrMetallicRoughness? = null,
var normalTexture: GltfNormalTextureInfo? = null,
var occlusionTexture: GltfOcclusionTextureInfo? = null,
var emissiveTexture: GltfTextureInfo? = null,
var emissiveFactor: IVector3? = null,
var alphaMode: GltfAlphaMode? = null,
var alphaCutoff: Double? = null,
var doubleSided: Boolean = false
)
data class PbrMetallicRoughness(
var baseColorFactor: IVector4? = null,
var baseColorTexture: TextureInfo? = null,
var metallicFactor: Double? = null,
var roughnessFactor: Double? = null,
var metallicRoughnessTexture: TextureInfo? = null
)
data class TextureInfo(
var image: Image? = null,
var texCoord: Int = 0
)
data class Image(
var uri: String? = null,
var mimeType: String? = null,
var name: String? = null
)
fun Material.pbrMetallicRoughness(func: PbrMetallicRoughness.() -> Unit) {
val data = PbrMetallicRoughness()
func(data)
pbrMetallicRoughness = data
}
fun PbrMetallicRoughness.baseColor(func: Image.() -> Unit) {
baseColorTexture = TextureInfo(Image().apply(func))
}
fun PbrMetallicRoughness.build(): GltfPbrMetallicRoughness {
return GltfPbrMetallicRoughness(
baseColorFactor = baseColorFactor ?: Vector4.ONE,
baseColorTexture = baseColorTexture?.build(),
metallicFactor = metallicFactor ?: 1.0,
roughnessFactor = roughnessFactor ?: 1.0,
metallicRoughnessTexture = metallicRoughnessTexture?.build()
)
}
fun TextureInfo.build(): GltfTextureInfo {
return GltfTextureInfo(
index = image!!.build(),
texCoord = texCoord
)
}
fun Image.build(): Int {
if (bakedSamplers.isEmpty()) {
bakedSamplers.add(GltfSampler(
magFilter = Texture.PIXELATED,
minFilter = Texture.PIXELATED,
wrapS = Texture.REPEAT,
wrapT = Texture.REPEAT,
name = "pixelated"
))
}
bakedImages.add(GltfImage(
uri = uri
))
bakedTextures.add(GltfTexture(
sampler = 0,
source = bakedImages.size - 1,
name = name
))
return bakedTextures.size - 1
}
fun animation(func: Animation.() -> Unit) {
val anim = Animation()
anim.func()
animations.add(anim)
}
fun Animation.channel(func: Channel.() -> Unit) {
val chan = Channel()
chan.func()
channels.add(chan)
}
private fun Animation.build(): GltfAnimation {
val channels = mutableListOf<GltfAnimationChannel>()
val samplers = mutableListOf<GltfAnimationSampler>()
this.channels.forEach { chan ->
val node = nodeIdToIndex[chan.node] ?: return@forEach
channels += GltfAnimationChannel(
target = GltfChannelTarget(node = node, path = chan.transformType.toString()),
sampler = samplers.size
)
samplers += GltfAnimationSampler(
input = chan.timeValues!!.build(true),
interpolation = chan.interpolation,
output = chan.transformValues!!.build(true)
)
}
return GltfAnimation(
name = name,
channels = channels,
samplers = samplers
)
}
data class Animation(
var name: String? = null,
val channels: MutableList<Channel> = mutableListOf()
)
data class Channel(
var node: UUID? = null,
var interpolation: GltfInterpolation = GltfInterpolation.LINEAR,
var transformType: GltfChannelPath = GltfChannelPath.translation,
var timeValues: UnpackedBuffer? = null,
var transformValues: UnpackedBuffer? = null
) {
// this avoids having to import GltfInterpolation.*
inline val LINEAR: GltfInterpolation get() = GltfInterpolation.LINEAR
inline val STEP: GltfInterpolation get() = GltfInterpolation.STEP
inline val CUBICSPLINE: GltfInterpolation get() = GltfInterpolation.CUBICSPLINE
// this avoids having to import GltfChannelPath.*
inline val TRANSLATION: GltfChannelPath get() = GltfChannelPath.translation
inline val ROTATION: GltfChannelPath get() = GltfChannelPath.rotation
inline val SCALE: GltfChannelPath get() = GltfChannelPath.scale
inline val WEIGHTS: GltfChannelPath get() = GltfChannelPath.weights
// this avoids having to import ComponentType.*
inline val BYTE: GltfComponentType get() = GltfComponentType.BYTE
inline val UNSIGNED_BYTE: GltfComponentType get() = GltfComponentType.UNSIGNED_BYTE
inline val SHORT: GltfComponentType get() = GltfComponentType.SHORT
inline val UNSIGNED_SHORT: GltfComponentType get() = GltfComponentType.UNSIGNED_SHORT
inline val UNSIGNED_INT: GltfComponentType get() = GltfComponentType.UNSIGNED_INT
inline val FLOAT: GltfComponentType get() = GltfComponentType.FLOAT
}
// val cameras: List<Camera> = emptyList(), // An array of cameras. A camera defines a projection matrix.
// val images: List<Image> = emptyList(), // An array of images. An image defines data used to create a texture.
// val samplers: List<Sampler> = emptyList(), // An array of samplers. A sampler contains properties for texture filtering and wrapping modes.
// val skins: List<Skin> = emptyList(), // An array of skins. A skin is defined by joints and matrices.
// val textures: List<Texture> = emptyList(), // An array of textures.
} | gpl-3.0 | eb1ce78e2dac8c94c4245f49b2a85acd | 33.46165 | 146 | 0.581765 | 4.221986 | false | false | false | false |
tensorflow/examples | lite/examples/bert_qa/android/app/src/main/java/org/tensorflow/lite/examples/bertqa/dataset/LoadDataSetClient.kt | 1 | 1637 | /*
* Copyright 2022 The TensorFlow Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.tensorflow.lite.examples.bertqa.dataset
import android.content.Context
import android.util.Log
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import java.io.IOException
import java.io.InputStream
class LoadDataSetClient(private val context: Context) {
private companion object {
private const val TAG = "BertAppDemo"
private const val JSON_DIR = "qa.json"
}
// Load json file into a data object.
fun loadJson(): DataSet? {
var dataSet: DataSet? = null
try {
val inputStream: InputStream = context.assets.open(JSON_DIR)
val bufferReader = inputStream.bufferedReader()
val stringJson: String = bufferReader.use { it.readText() }
val datasetType = object : TypeToken<DataSet>() {}.type
dataSet = Gson().fromJson(stringJson, datasetType)
} catch (e: IOException) {
Log.e(TAG, e.message.toString())
}
return dataSet
}
}
| apache-2.0 | 4f0fc299e23372f3889463911b3b1830 | 34.586957 | 75 | 0.6854 | 4.274151 | false | false | false | false |
mdaniel/intellij-community | platform/platform-impl/src/com/intellij/toolWindow/ToolWindowPaneNewButtonManager.kt | 2 | 5484 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.toolWindow
import com.intellij.openapi.wm.RegisterToolWindowTask
import com.intellij.openapi.wm.ToolWindowAnchor
import com.intellij.openapi.wm.WindowInfo
import com.intellij.openapi.wm.impl.AbstractDroppableStripe
import com.intellij.openapi.wm.impl.SquareStripeButton
import com.intellij.openapi.wm.impl.ToolWindowImpl
import com.intellij.ui.awt.DevicePoint
import java.awt.BorderLayout
import java.awt.Dimension
import javax.swing.Icon
import javax.swing.JComponent
internal class ToolWindowPaneNewButtonManager(paneId: String, isPrimary: Boolean) : ToolWindowButtonManager {
constructor(paneId: String) : this(paneId, true)
private val left = ToolWindowLeftToolbar(paneId, isPrimary)
private val right = ToolWindowRightToolbar(paneId)
override val isNewUi: Boolean
get() = true
override fun add(pane: JComponent) {
pane.add(left, BorderLayout.WEST)
pane.add(right, BorderLayout.EAST)
}
override fun updateToolStripesVisibility(showButtons: Boolean, state: ToolWindowPaneState): Boolean {
val oldSquareVisible = left.isVisible && right.isVisible
val visible = showButtons || state.isStripesOverlaid
left.isVisible = visible
right.isVisible = visible
return oldSquareVisible != visible
}
override fun initMoreButton() {
left.initMoreButton()
}
override fun layout(size: Dimension, layeredPane: JComponent) {
layeredPane.setBounds(0, 0, size.width, size.height)
}
override fun validateAndRepaint() {
}
override fun revalidateNotEmptyStripes() {
}
override fun getBottomHeight() = 0
override fun getStripeFor(anchor: ToolWindowAnchor, isSplit: Boolean?): AbstractDroppableStripe {
return when (anchor) {
ToolWindowAnchor.LEFT -> left.getStripeFor(anchor)
ToolWindowAnchor.BOTTOM -> isSplit?.let { if (it) right.getStripeFor(anchor) else left.getStripeFor(anchor) }
?: throw IllegalArgumentException("Split mode isn't expected to be used here, anchor: " + anchor.displayName)
ToolWindowAnchor.RIGHT -> right.getStripeFor(anchor)
else -> throw IllegalArgumentException("Anchor=$anchor")
}
}
override fun getStripeFor(devicePoint: DevicePoint, preferred: AbstractDroppableStripe, pane: JComponent): AbstractDroppableStripe? {
val screenPoint = devicePoint.getLocationOnScreen(pane)
return if (preferred.containsPoint(screenPoint)) {
preferred
}
else {
left.getStripeFor(screenPoint) ?: right.getStripeFor(screenPoint)
}
}
override fun getStripeWidth(anchor: ToolWindowAnchor): Int {
if (anchor == ToolWindowAnchor.BOTTOM || anchor == ToolWindowAnchor.TOP) return 0
val stripe = getStripeFor(anchor, null)
return if (stripe.isVisible && stripe.isShowing) stripe.width else 0
}
override fun getStripeHeight(anchor: ToolWindowAnchor): Int {
// New UI only shows stripes on the LEFT + RIGHT. There is no TOP, and while BOTTOM is used, it is shown on the left, so has no height
return 0
}
fun getSquareStripeFor(anchor: ToolWindowAnchor): ToolWindowToolbar {
return when (anchor) {
ToolWindowAnchor.TOP, ToolWindowAnchor.RIGHT -> right
ToolWindowAnchor.BOTTOM, ToolWindowAnchor.LEFT -> left
else -> throw java.lang.IllegalArgumentException("Anchor=$anchor")
}
}
override fun startDrag() {
if (right.isVisible) {
right.startDrag()
}
if (left.isVisible) {
left.startDrag()
}
}
override fun stopDrag() {
if (right.isVisible) {
right.stopDrag()
}
if (left.isVisible) {
left.stopDrag()
}
}
override fun reset() {
left.reset()
right.reset()
}
fun refreshUi() {
left.repaint()
right.repaint()
}
private fun findToolbar(anchor: ToolWindowAnchor, isSplit: Boolean) =
when (anchor) {
ToolWindowAnchor.LEFT -> left
ToolWindowAnchor.BOTTOM -> if (isSplit) right else left
ToolWindowAnchor.RIGHT -> right
else -> throw IllegalArgumentException("Anchor=$anchor")
}
override fun createStripeButton(toolWindow: ToolWindowImpl, info: WindowInfo, task: RegisterToolWindowTask?): StripeButtonManager {
val squareStripeButton = SquareStripeButton(toolWindow)
val manager = object : StripeButtonManager {
override val id: String = toolWindow.id
override val toolWindow: ToolWindowImpl = toolWindow
override val windowDescriptor: WindowInfo
get() = toolWindow.windowInfo
override fun updateState(toolWindow: ToolWindowImpl) {
squareStripeButton.updateIcon()
}
override fun updatePresentation() {
squareStripeButton.updatePresentation()
}
override fun updateIcon(icon: Icon?) {
squareStripeButton.updatePresentation()
}
override fun remove() {
findToolbar(toolWindow.anchor, toolWindow.isSplitMode).getStripeFor(toolWindow.windowInfo.anchor).removeButton(this)
}
override fun getComponent() = squareStripeButton
override fun toString(): String {
return "SquareStripeButtonManager(windowInfo=${toolWindow.windowInfo})"
}
}
findToolbar(toolWindow.anchor, toolWindow.isSplitMode).getStripeFor(toolWindow.windowInfo.anchor).addButton(manager)
return manager
}
override fun hasButtons() = left.hasButtons() || right.hasButtons()
} | apache-2.0 | 4f2e79c92a47e33c9fec9157ed9030c5 | 32.042169 | 142 | 0.720095 | 4.719449 | false | false | false | false |
leafclick/intellij-community | uast/uast-java/src/org/jetbrains/uast/java/declarations/JavaUFile.kt | 1 | 1460 | // Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.uast.java
import com.intellij.psi.PsiComment
import com.intellij.psi.PsiJavaFile
import com.intellij.psi.PsiRecursiveElementWalkingVisitor
import org.jetbrains.uast.*
import java.util.*
class JavaUFile(override val sourcePsi: PsiJavaFile, override val languagePlugin: UastLanguagePlugin) : UFile, UElement {
override val packageName: String
get() = sourcePsi.packageName
override val imports: List<JavaUImportStatement> by lz {
sourcePsi.importList?.allImportStatements?.map { JavaUImportStatement(it, this) } ?: listOf()
}
override val uAnnotations: List<UAnnotation>
get() = sourcePsi.packageStatement?.annotationList?.annotations?.map { JavaUAnnotation(it, this) } ?: emptyList()
override val classes: List<UClass> by lz { sourcePsi.classes.map { JavaUClass.create(it, this) } }
override val allCommentsInFile: ArrayList<UComment> by lz {
val comments = ArrayList<UComment>(0)
sourcePsi.accept(object : PsiRecursiveElementWalkingVisitor() {
override fun visitComment(comment: PsiComment) {
comments += UComment(comment, this@JavaUFile)
}
})
comments
}
override fun equals(other: Any?): Boolean = (other as? JavaUFile)?.sourcePsi == sourcePsi
@Suppress("OverridingDeprecatedMember")
override val psi get() = sourcePsi
} | apache-2.0 | ffa2c434c4a2c8eb586330731d2c440c | 38.486486 | 140 | 0.75 | 4.520124 | false | false | false | false |
kivensolo/UiUsingListView | app/src/main/java/com/kingz/ipcdemo/Book.kt | 1 | 2061 | package com.kingz.ipcdemo
import android.os.Parcel
import android.os.Parcelable
/**
* author: King.Z <br></br>
* date: 2016/10/17 16:21 <br></br>
* description: 实现Parcelable接口 执行序列化操作 <br></br>
* 这里有一个坑: 默认生成的模板类的对象只支持为 in 的定向 tag 。
* 为什么呢?因为默认生成的类里面只有 writeToParcel() 方法,
* 而如果要支持为 out 或者 inout 的定向 tag 的话,
* 还需要实现 readFromParcel() 方法——而这个方法其实并没有在 Parcelable 接口里面,
* 所以需要从头写。具体为什么可以去看:
* http://www.open-open.com/lib/view/open1469494342021.html
*/
class Book : Parcelable {
constructor()
constructor(income: Parcel) {
name = income.readString()
price = income.readInt()
}
companion object {
@JvmField
val CREATOR: Parcelable.Creator<Book?> = object : Parcelable.Creator<Book?> {
override fun createFromParcel(income: Parcel): Book? {
return Book(income)
}
override fun newArray(size: Int): Array<Book?> {
return arrayOfNulls(size)
}
}
}
var name: String? = null
var price = 0
override fun describeContents(): Int { return 0}
override fun writeToParcel(dest: Parcel, flags: Int) {
dest.writeString(name)
dest.writeInt(price)
}
/**
* @param dest 用来存储和传输数据
* 添加了 readFromParcel() 方法之后,
* 我们的 Book 类的对象在AIDL文件里就可以用 out 或者 inout 来作为它的定向 tag 了。
*/
fun readFromParcel(dest: Parcel) {
//注意,此处的读值顺序应当是和writeToParcel()方法中一致的
name = dest.readString()
price = dest.readInt()
//至此,关于AIDL中非默认支持数据类型的序列化操作就完成了。
}
override fun toString(): String {
return "name : $name , price : $price"
}
} | gpl-2.0 | 75dd6a16c376565ca91a5e2af01366c0 | 25.253968 | 85 | 0.61343 | 3.325956 | false | false | false | false |
Zhouzhouzhou/AndroidDemo | app/src/main/java/com/zhou/android/ui/RippleView.kt | 1 | 4283 | package com.zhou.android.ui
import android.animation.ValueAnimator
import android.content.Context
import android.graphics.*
import android.util.AttributeSet
import android.util.Log
import android.view.View
import android.view.animation.LinearInterpolator
import kotlin.math.ceil
/**
* 模拟波纹涟漪
* 正常涟漪扩散应越来越慢,这里简化为匀速扩散
* Created by mxz on 2020/9/21.
*/
class RippleView @JvmOverloads constructor(context: Context, attributeSet: AttributeSet? = null, def: Int = 0)
: View(context, attributeSet, def) {
private var center = 0f
private var startRadius = 5f
private var viewRadius = 10f
private val rippleCount = 8
private var rippleDiff = 10f//间距
private var maxLimit = 1f
private val circlePaint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
style = Paint.Style.STROKE
color = Color.parseColor("#FF83B0FF")
strokeWidth = resources.displayMetrics.density * 2f + 0.5f
}
//渐变遮罩,使外层透明
private val shapeGradient: RadialGradient by lazy {
RadialGradient(center, center, viewRadius, intArrayOf(Color.TRANSPARENT, Color.TRANSPARENT, Color.BLACK), floatArrayOf(0f, 0.68f, 1f), Shader.TileMode.CLAMP)
}
private val shapePaint: Paint by lazy {
Paint().apply {
style = Paint.Style.FILL
shader = shapeGradient
}
}
//扩散刷新
private val spreadAnimator: ValueAnimator by lazy {
ValueAnimator.ofFloat(0f, rippleDiff).apply {
repeatCount = ValueAnimator.INFINITE
duration = 1500
interpolator = LinearInterpolator()
addUpdateListener {
curSpread = it.animatedValue as Float
postInvalidate()
}
}
}
private var curSpread = 5f //当前偏移量
private var maxSpread = 1f //最大偏移量
override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
val ws = MeasureSpec.getSize(widthMeasureSpec)
val wm = MeasureSpec.getMode(widthMeasureSpec)
val hs = MeasureSpec.getSize(heightMeasureSpec)
val hm = MeasureSpec.getMode(heightMeasureSpec)
var w: Int
var h: Int
if (wm == MeasureSpec.EXACTLY && hm == MeasureSpec.EXACTLY) {
w = ws.coerceAtMost(hs).also {
h = it
}
} else if (wm == MeasureSpec.EXACTLY) {
w = ws.also {
h = it
}
} else if (hm == MeasureSpec.EXACTLY) {
h = hs.also {
w = it
}
} else {
w = 300
h = 300
}
//获取中心位置
center = (w / 2f).also {
startRadius = it * 0.58f
}
//最大扩散距离 = 视图宽度一半 - 内圆半径
maxSpread = center - startRadius
//圆间距
rippleDiff = ceil((center - startRadius - 4.0) / rippleCount).toFloat()
viewRadius = center + rippleDiff + 6f//设置大一点的空间,避免最外面的圈闪烁
//最大圆的半径
maxLimit = center + rippleDiff + 4f
Log.d("ripple", "center = $center, startRadius = $startRadius, viewRadius = $viewRadius, maxSpread = $maxSpread, rippleDif = $rippleDiff")
setMeasuredDimension(w, h)
}
override fun onDraw(canvas: Canvas) {
for (i in rippleCount.downTo(0)) {
var r = startRadius + i * rippleDiff + curSpread
if (r > maxLimit) {//将超出的距离的圆圈重置为靠近中心的圈
r -= maxSpread
}
canvas.drawCircle(center, center, r, circlePaint)
}
canvas.drawCircle(center, center, viewRadius, shapePaint)
canvas.drawCircle(center, center, startRadius, circlePaint)
}
override fun onAttachedToWindow() {
super.onAttachedToWindow()
start()
}
override fun onDetachedFromWindow() {
stop()
super.onDetachedFromWindow()
}
private fun start() {
postDelayed({
spreadAnimator.start()
}, 800)
}
private fun stop() {
if (spreadAnimator.isRunning) {
spreadAnimator.cancel()
}
}
} | mit | 179231a94bc260bdbefab5dc5cffe001 | 28.518248 | 165 | 0.59535 | 4.071501 | false | false | false | false |
siosio/intellij-community | platform/collaboration-tools/src/com/intellij/collaboration/ui/codereview/diff/MutableDiffRequestChainProcessor.kt | 1 | 3719 | // 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.collaboration.ui.codereview.diff
import com.intellij.diff.chains.AsyncDiffRequestChain
import com.intellij.diff.chains.DiffRequestChain
import com.intellij.diff.chains.DiffRequestProducer
import com.intellij.diff.impl.CacheDiffRequestProcessor
import com.intellij.diff.util.DiffUserDataKeysEx.ScrollToPolicy
import com.intellij.openapi.actionSystem.AnAction
import com.intellij.openapi.project.Project
import com.intellij.openapi.vcs.FilePath
import com.intellij.openapi.vcs.changes.actions.diff.SelectionAwareGoToChangePopupActionProvider
import com.intellij.openapi.vcs.changes.ui.ChangeDiffRequestChain
import com.intellij.openapi.vcs.changes.ui.PresentableChange
import kotlin.properties.Delegates
open class MutableDiffRequestChainProcessor(project: Project, chain: DiffRequestChain?) : CacheDiffRequestProcessor.Simple(project) {
private val asyncChangeListener = AsyncDiffRequestChain.Listener {
dropCaches()
currentIndex = (this.chain?.index ?: 0)
updateRequest(true)
}
var chain: DiffRequestChain? by Delegates.observable(null) { _, oldValue, newValue ->
if (oldValue is AsyncDiffRequestChain) {
oldValue.onAssigned(false)
oldValue.removeListener(asyncChangeListener)
}
if (newValue is AsyncDiffRequestChain) {
newValue.onAssigned(true)
// listener should be added after `onAssigned` call to avoid notification about synchronously loaded requests
newValue.addListener(asyncChangeListener, this)
}
currentIndex = newValue?.index ?: 0
updateRequest()
}
private var currentIndex: Int = 0
init {
this.chain = chain
}
override fun onDispose() {
val chain = chain
if (chain is AsyncDiffRequestChain) chain.onAssigned(false)
super.onDispose()
}
override fun getCurrentRequestProvider(): DiffRequestProducer? {
val requests = chain?.requests ?: return null
return if (currentIndex < 0 || currentIndex >= requests.size) null else requests[currentIndex]
}
override fun hasNextChange(fromUpdate: Boolean): Boolean {
val chain = chain ?: return false
return currentIndex < chain.requests.lastIndex
}
override fun hasPrevChange(fromUpdate: Boolean): Boolean {
val chain = chain ?: return false
return currentIndex > 0 && chain.requests.size > 1
}
override fun goToNextChange(fromDifferences: Boolean) {
currentIndex += 1
updateRequest(false, if (fromDifferences) ScrollToPolicy.FIRST_CHANGE else null)
}
override fun goToPrevChange(fromDifferences: Boolean) {
currentIndex -= 1
updateRequest(false, if (fromDifferences) ScrollToPolicy.LAST_CHANGE else null)
}
override fun isNavigationEnabled(): Boolean {
val chain = chain ?: return false
return chain.requests.size > 1
}
override fun createGoToChangeAction(): AnAction? {
return MyGoToChangePopupProvider().createGoToChangeAction()
}
open fun selectFilePath(filePath: FilePath) {}
private inner class MyGoToChangePopupProvider : SelectionAwareGoToChangePopupActionProvider() {
override fun getChanges(): List<PresentableChange> {
return chain?.requests?.mapNotNull { it as? ChangeDiffRequestChain.Producer } ?: emptyList()
}
override fun getSelectedChange(): PresentableChange? {
val producer = chain?.requests?.getOrNull(currentIndex)
return if (producer is ChangeDiffRequestChain.Producer) producer else null
}
override fun select(change: PresentableChange) {
[email protected](change.filePath)
}
}
}
| apache-2.0 | f920a170758b16385e2bc755e14c62a0 | 35.460784 | 158 | 0.760419 | 4.666248 | false | false | false | false |
jwren/intellij-community | plugins/kotlin/j2k/services/src/org/jetbrains/kotlin/nj2k/postProcessing/diagnosticBasedPostProcessing.kt | 2 | 4335 | // 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.nj2k.postProcessing
import com.intellij.openapi.editor.RangeMarker
import com.intellij.psi.PsiElement
import org.jetbrains.kotlin.caches.resolve.KotlinCacheService
import org.jetbrains.kotlin.diagnostics.Diagnostic
import org.jetbrains.kotlin.diagnostics.DiagnosticFactory
import org.jetbrains.kotlin.idea.core.util.range
import org.jetbrains.kotlin.idea.quickfix.QuickFixFactory
import org.jetbrains.kotlin.idea.quickfix.asKotlinIntentionActionsFactory
import org.jetbrains.kotlin.idea.resolve.ResolutionFacade
import org.jetbrains.kotlin.idea.util.application.runReadAction
import org.jetbrains.kotlin.nj2k.NewJ2kConverterContext
import org.jetbrains.kotlin.psi.KtElement
import org.jetbrains.kotlin.psi.KtFile
import org.jetbrains.kotlin.psi.psiUtil.elementsInRange
import org.jetbrains.kotlin.resolve.diagnostics.Diagnostics
class DiagnosticBasedPostProcessingGroup(diagnosticBasedProcessings: List<DiagnosticBasedProcessing>) : FileBasedPostProcessing() {
constructor(vararg diagnosticBasedProcessings: DiagnosticBasedProcessing) : this(diagnosticBasedProcessings.toList())
private val diagnosticToFix =
diagnosticBasedProcessings.asSequence().flatMap { processing ->
processing.diagnosticFactories.asSequence().map { it to processing::fix }
}.groupBy { it.first }.mapValues { (_, list) ->
list.map { it.second }
}
override fun runProcessing(file: KtFile, allFiles: List<KtFile>, rangeMarker: RangeMarker?, converterContext: NewJ2kConverterContext) {
val diagnostics = runReadAction {
val resolutionFacade = KotlinCacheService.getInstance(converterContext.project).getResolutionFacade(allFiles)
analyzeFileRange(file, rangeMarker, resolutionFacade).all()
}
for (diagnostic in diagnostics) {
val elementIsInRange = runReadAction {
val range = rangeMarker?.range ?: file.textRange
diagnostic.psiElement.isInRange(range)
}
if (!elementIsInRange) continue
diagnosticToFix[diagnostic.factory]?.forEach { fix ->
val elementIsValid = runReadAction { diagnostic.psiElement.isValid }
if (elementIsValid) {
fix(diagnostic)
}
}
}
}
private fun analyzeFileRange(file: KtFile, rangeMarker: RangeMarker?, resolutionFacade: ResolutionFacade): Diagnostics {
val elements = when {
rangeMarker == null -> listOf(file)
rangeMarker.isValid -> file.elementsInRange(rangeMarker.range!!).filterIsInstance<KtElement>()
else -> emptyList()
}
return if (elements.isNotEmpty())
resolutionFacade.analyzeWithAllCompilerChecks(elements).bindingContext.diagnostics
else Diagnostics.EMPTY
}
}
interface DiagnosticBasedProcessing {
val diagnosticFactories: List<DiagnosticFactory<*>>
fun fix(diagnostic: Diagnostic)
}
inline fun <reified T : PsiElement> diagnosticBasedProcessing(
vararg diagnosticFactory: DiagnosticFactory<*>,
crossinline fix: (T, Diagnostic) -> Unit
) =
object : DiagnosticBasedProcessing {
override val diagnosticFactories = diagnosticFactory.toList()
override fun fix(diagnostic: Diagnostic) {
val element = diagnostic.psiElement as? T
if (element != null) runUndoTransparentActionInEdt(inWriteAction = true) {
fix(element, diagnostic)
}
}
}
fun diagnosticBasedProcessing(fixFactory: QuickFixFactory, vararg diagnosticFactory: DiagnosticFactory<*>) =
object : DiagnosticBasedProcessing {
override val diagnosticFactories = diagnosticFactory.toList()
override fun fix(diagnostic: Diagnostic) {
val actionFactory = fixFactory.asKotlinIntentionActionsFactory()
val fix = runReadAction { actionFactory.createActions(diagnostic).singleOrNull() } ?: return
runUndoTransparentActionInEdt(inWriteAction = true) {
fix.invoke(diagnostic.psiElement.project, null, diagnostic.psiFile)
}
}
}
| apache-2.0 | 9d0fed91f5133289f9748aef3cc33879 | 45.612903 | 158 | 0.714879 | 5.351852 | false | false | false | false |
dahlstrom-g/intellij-community | platform/platform-tests/testSrc/com/intellij/formatting/engine/testModel/TestFormattingModel.kt | 19 | 2752 | /*
* Copyright 2000-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.formatting.engine.testModel
import com.intellij.formatting.Block
import com.intellij.formatting.FormattingDocumentModel
import com.intellij.formatting.FormattingModel
import com.intellij.lang.ASTNode
import com.intellij.openapi.command.WriteCommandAction
import com.intellij.openapi.editor.Document
import com.intellij.openapi.util.TextRange
import com.intellij.util.text.CharArrayUtil
class TestFormattingModel(private val rootBlock: Block,
private val document: Document) : FormattingModel, FormattingDocumentModel {
override fun getRootBlock(): Block = rootBlock
override fun getDocumentModel(): TestFormattingModel = this
override fun replaceWhiteSpace(textRange: TextRange, whiteSpace: String): TextRange {
WriteCommandAction.runWriteCommandAction(null) {
document.replaceString(textRange.startOffset, textRange.endOffset, whiteSpace)
}
return TextRange(textRange.startOffset, textRange.startOffset + whiteSpace.length)
}
override fun shiftIndentInsideRange(node: ASTNode, range: TextRange, indent: Int): TextRange {
throw UnsupportedOperationException()
}
override fun commitChanges() {
}
override fun getLineNumber(offset: Int): Int = document.getLineNumber(offset)
override fun getLineStartOffset(line: Int): Int = document.getLineStartOffset(line)
override fun getText(textRange: TextRange): String = document.getText(textRange)
override fun getTextLength(): Int = document.textLength
override fun getDocument(): Document = document
override fun containsWhiteSpaceSymbolsOnly(startOffset: Int, endOffset: Int): Boolean {
return CharArrayUtil.containsOnlyWhiteSpaces(document.getText(TextRange(startOffset, endOffset)))
}
override fun adjustWhiteSpaceIfNecessary(whiteSpaceText: CharSequence,
startOffset: Int,
endOffset: Int,
nodeAfter: ASTNode?,
changedViaPsi: Boolean): CharSequence {
throw UnsupportedOperationException("not implemented")
}
} | apache-2.0 | 2904314fcb213310f9d1e7df440ae5a5 | 38.898551 | 102 | 0.732195 | 5.086876 | false | false | false | false |
allotria/intellij-community | python/testSrc/com/jetbrains/python/packaging/PyRequirementsGenerationTest.kt | 3 | 5762 | // 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.jetbrains.python.packaging
import com.intellij.openapi.actionSystem.ActionManager
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.actionSystem.LangDataKeys
import com.intellij.openapi.actionSystem.impl.SimpleDataContext
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.editor.ex.EditorEx
import com.intellij.openapi.project.Project
import com.intellij.openapi.projectRoots.Sdk
import com.intellij.testFramework.registerServiceInstance
import com.jetbrains.python.fixtures.PyTestCase
import org.easymock.EasyMock
class PyRequirementsGenerationTest : PyTestCase() {
private var oldPackageManagers: PyPackageManagers? = null
private val installedPackages = mapOf("Django" to "3.0.0",
"requests" to "2.22.0",
"Jinja2" to "2.11.1",
"pandas" to "1.0.1" ,
"cookiecutter" to "1.7.0",
"numpy" to "1.18.1",
"tox" to "3.14.4",
"docker-py" to "1.10.6")
fun testNewFileGeneration() = doTest()
fun testNewFileWithoutVersion() = doTest(PyRequirementsVersionSpecifierType.NO_VERSION)
fun testAddMissingPackages() = doTest()
fun testAddMissingVersion() = doTest()
fun testStripVersion() = doTest(PyRequirementsVersionSpecifierType.NO_VERSION)
fun testAddVersionWithSpecifier() = doTest(PyRequirementsVersionSpecifierType.COMPATIBLE)
fun testKeepComments() = doTest(removeUnused = true)
fun testKeepMatchingVersion() = doTest()
fun testKeepFileInstallOptions() = doTest()
fun testKeepPackageInstallOptions() = doTest()
fun testKeepEditableFromVCS() = doTest()
fun testKeepEditableForSelf() = doTest()
fun testRemoveUnused() = doTest(removeUnused = true)
fun testUpdateVersionKeepInstallOptions() = doTest()
fun testCompatibleFileReference() = doTest()
fun testDifferentTopLevelImport() = doTest()
fun testDifferentTopLevelImportWithOriginalPackage() = doTest(packages = installedPackages + mapOf("docker" to "3.7.0"))
fun testBaseFileUnchanged() = doTest()
fun testBaseFileUpdate() = doTest(modifyBaseFiles = true)
fun testBaseFileCleanup() = doTest(modifyBaseFiles = true, removeUnused = true)
private fun doTest(versionSpecifier: PyRequirementsVersionSpecifierType = PyRequirementsVersionSpecifierType.STRONG_EQ,
removeUnused: Boolean = false,
modifyBaseFiles: Boolean = false,
packages: Map<String, String> = installedPackages) {
val settings = PyPackageRequirementsSettings.getInstance(myFixture.module)
val oldRequirementsPath = settings.requirementsPath
val oldVersionSpecifier = settings.versionSpecifier
val oldRemoveUnused = settings.removeUnused
val oldModifyBaseFiles = settings.modifyBaseFiles
try {
overrideInstalledPackages(packages)
settings.requirementsPath = "requirements.txt"
settings.versionSpecifier = versionSpecifier
settings.removeUnused = removeUnused
settings.modifyBaseFiles = modifyBaseFiles
val testName = getTestName(true)
myFixture.copyDirectoryToProject(testName, "")
myFixture.configureFromTempProjectFile(settings.requirementsPath)
val action = ActionManager.getInstance().getAction("PySyncPythonRequirements")
val context = SimpleDataContext.getSimpleContext(LangDataKeys.MODULE, myFixture.module, (myFixture.editor as EditorEx).dataContext)
val event = AnActionEvent.createFromAnAction(action, null, "", context)
action.actionPerformed(event)
myFixture.checkResultByFile("$testName/new_${settings.requirementsPath}", true)
if (modifyBaseFiles) {
myFixture.checkResultByFile("base_${settings.requirementsPath}", "$testName/new_base_${settings.requirementsPath}", true)
}
assertProjectFilesNotParsed(myFixture.file)
}
finally {
settings.requirementsPath = oldRequirementsPath
settings.versionSpecifier = oldVersionSpecifier
settings.removeUnused = oldRemoveUnused
settings.modifyBaseFiles = oldModifyBaseFiles
}
}
override fun setUp() {
super.setUp()
oldPackageManagers = PyPackageManagers.getInstance()
}
override fun tearDown() {
try {
ApplicationManager.getApplication().registerServiceInstance(PyPackageManagers::class.java, oldPackageManagers!!)
}
catch (e: Throwable) {
addSuppressedException(e)
}
finally {
super.tearDown()
}
}
override fun getTestDataPath(): String = super.getTestDataPath() + "/requirement/generation"
private fun overrideInstalledPackages(packages: Map<String, String>) {
ApplicationManager.getApplication().registerServiceInstance(PyPackageManagers::class.java, MockPyPackageManagers(packages))
}
private class MockPyPackageManagers(val packages: Map<String, String>) : PyPackageManagers() {
override fun forSdk(sdk: Sdk): PyPackageManager {
val packageManager = EasyMock.createMock<PyPackageManager>(PyPackageManager::class.java)
EasyMock
.expect(packageManager.refreshAndGetPackages(false))
.andReturn(packages.map { PyPackage(it.key, it.value) })
EasyMock.replay(packageManager)
return packageManager
}
override fun getManagementService(project: Project?, sdk: Sdk?) = throw UnsupportedOperationException()
override fun clearCache(sdk: Sdk): Unit = throw UnsupportedOperationException()
}
} | apache-2.0 | 644f813c565d2a0d8fca22afe64aca2c | 44.738095 | 140 | 0.720236 | 4.858347 | false | true | false | false |
androidx/androidx | activity/activity/src/androidTest/java/androidx/activity/OnBackPressedDispatcherInvokerTest.kt | 3 | 5283 | /*
* 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.activity
import android.os.Build
import android.window.OnBackInvokedCallback
import android.window.OnBackInvokedDispatcher
import androidx.annotation.RequiresApi
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.filters.SdkSuppress
import androidx.test.filters.SmallTest
import com.google.common.truth.Truth.assertThat
import leakcanary.DetectLeaksAfterTestSuccess
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
@SmallTest
@RunWith(AndroidJUnit4::class)
@RequiresApi(Build.VERSION_CODES.TIRAMISU)
@SdkSuppress(minSdkVersion = Build.VERSION_CODES.S_V2)
class OnBackPressedDispatcherInvokerTest {
@get:Rule
val rule = DetectLeaksAfterTestSuccess()
@Test
fun testSimpleInvoker() {
var registerCount = 0
var unregisterCount = 0
val invoker = object : OnBackInvokedDispatcher {
override fun registerOnBackInvokedCallback(p0: Int, p1: OnBackInvokedCallback) {
registerCount++
}
override fun unregisterOnBackInvokedCallback(p0: OnBackInvokedCallback) {
unregisterCount++
}
}
val dispatcher = OnBackPressedDispatcher()
dispatcher.setOnBackInvokedDispatcher(invoker)
val callback = object : OnBackPressedCallback(true) {
override fun handleOnBackPressed() { }
}
dispatcher.addCallback(callback)
assertThat(registerCount).isEqualTo(1)
callback.remove()
assertThat(unregisterCount).isEqualTo(1)
}
@Test
fun testInvokerEnableDisable() {
var registerCount = 0
var unregisterCount = 0
val invoker = object : OnBackInvokedDispatcher {
override fun registerOnBackInvokedCallback(p0: Int, p1: OnBackInvokedCallback) {
registerCount++
}
override fun unregisterOnBackInvokedCallback(p0: OnBackInvokedCallback) {
unregisterCount++
}
}
val dispatcher = OnBackPressedDispatcher()
dispatcher.setOnBackInvokedDispatcher(invoker)
val callback = object : OnBackPressedCallback(true) {
override fun handleOnBackPressed() { }
}
dispatcher.addCallback(callback)
assertThat(registerCount).isEqualTo(1)
callback.isEnabled = false
assertThat(unregisterCount).isEqualTo(1)
callback.isEnabled = true
assertThat(registerCount).isEqualTo(2)
}
@Test
fun testCallbackEnabledDisabled() {
val callback = object : OnBackPressedCallback(false) {
override fun handleOnBackPressed() {
TODO("Not yet implemented")
}
}
callback.isEnabled = true
callback.isEnabled = false
}
@Test
fun testInvokerAddDisabledCallback() {
var registerCount = 0
var unregisterCount = 0
val invoker = object : OnBackInvokedDispatcher {
override fun registerOnBackInvokedCallback(p0: Int, p1: OnBackInvokedCallback) {
registerCount++
}
override fun unregisterOnBackInvokedCallback(p0: OnBackInvokedCallback) {
unregisterCount++
}
}
val callback = object : OnBackPressedCallback(false) {
override fun handleOnBackPressed() { }
}
val dispatcher = OnBackPressedDispatcher()
dispatcher.setOnBackInvokedDispatcher(invoker)
dispatcher.addCallback(callback)
assertThat(registerCount).isEqualTo(0)
callback.isEnabled = true
assertThat(registerCount).isEqualTo(1)
callback.isEnabled = false
assertThat(unregisterCount).isEqualTo(1)
}
@Test
fun testInvokerAddEnabledCallbackBeforeSet() {
var registerCount = 0
var unregisterCount = 0
val invoker = object : OnBackInvokedDispatcher {
override fun registerOnBackInvokedCallback(p0: Int, p1: OnBackInvokedCallback) {
registerCount++
}
override fun unregisterOnBackInvokedCallback(p0: OnBackInvokedCallback) {
unregisterCount++
}
}
val callback = object : OnBackPressedCallback(true) {
override fun handleOnBackPressed() { }
}
val dispatcher = OnBackPressedDispatcher()
dispatcher.addCallback(callback)
dispatcher.setOnBackInvokedDispatcher(invoker)
assertThat(registerCount).isEqualTo(1)
callback.isEnabled = false
assertThat(unregisterCount).isEqualTo(1)
}
}
| apache-2.0 | 8df18855d5a46fabae210d8fa2cd56b0 | 27.868852 | 92 | 0.663638 | 5.021863 | false | true | false | false |
androidx/androidx | compose/material/material/benchmark/src/androidTest/java/androidx/compose/material/benchmark/view/AndroidCheckboxesInLinearLayoutTestCase.kt | 3 | 2779 | /*
* 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.benchmark.view
import android.app.Activity
import android.view.View
import android.view.ViewGroup
import android.widget.CheckBox
import android.widget.LinearLayout
import android.widget.TextView
import androidx.compose.testutils.benchmark.android.AndroidTestCase
/**
* Version of [CheckboxesInRowsTestCase] using Android views.
*/
class AndroidCheckboxesInLinearLayoutTestCase(
private val amountOfCheckboxes: Int
) : AndroidTestCase {
private val checkboxes = mutableListOf<CheckBox>()
override fun getContent(activity: Activity): ViewGroup {
val column = LinearLayout(activity)
column.orientation = LinearLayout.VERTICAL
column.layoutParams = ViewGroup.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.WRAP_CONTENT
)
repeat(amountOfCheckboxes) {
val row = LinearLayout(activity)
row.orientation = LinearLayout.HORIZONTAL
row.layoutParams = LinearLayout.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.WRAP_CONTENT
)
val text = TextView(activity)
text.text = "Check Me!"
text.layoutParams = LinearLayout.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT
)
val checkbox = CheckBox(activity)
checkbox.isChecked = false
checkbox.layoutParams = LinearLayout.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT
)
val space = View(activity)
val layoutParams = LinearLayout.LayoutParams(0, 1)
layoutParams.weight = 1f
space.layoutParams = layoutParams
row.addView(text)
row.addView(space)
row.addView(checkbox)
column.addView(row)
}
return column
}
fun toggleState() {
val checkbox = checkboxes.first()
checkbox.isChecked = !checkbox.isChecked
}
} | apache-2.0 | 3b9782bf313eb4f0a75c06e751e5c46a | 34.189873 | 75 | 0.668946 | 5.071168 | false | true | false | false |
GunoH/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/ReplaceGuardClauseWithFunctionCallInspection.kt | 1 | 8407 | // 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
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import org.jetbrains.kotlin.builtins.KotlinBuiltIns
import org.jetbrains.kotlin.config.LanguageFeature
import org.jetbrains.kotlin.idea.base.projectStructure.languageVersionSettings
import org.jetbrains.kotlin.idea.base.psi.replaced
import org.jetbrains.kotlin.idea.base.psi.textRangeIn
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.caches.resolve.analyze
import org.jetbrains.kotlin.idea.codeinsight.api.classic.inspections.AbstractApplicabilityBasedInspection
import org.jetbrains.kotlin.idea.codeinsight.utils.NegatedBinaryExpressionSimplificationUtils
import org.jetbrains.kotlin.idea.core.ShortenReferences
import org.jetbrains.kotlin.idea.intentions.callExpression
import org.jetbrains.kotlin.idea.util.CommentSaver
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.name.parentOrNull
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.startOffset
import org.jetbrains.kotlin.resolve.bindingContextUtil.isUsedAsExpression
import org.jetbrains.kotlin.resolve.calls.util.getResolvedCall
import org.jetbrains.kotlin.resolve.calls.util.getType
import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameSafe
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
class ReplaceGuardClauseWithFunctionCallInspection : AbstractApplicabilityBasedInspection<KtIfExpression>(
KtIfExpression::class.java
) {
companion object {
private const val ILLEGAL_STATE_EXCEPTION = "IllegalStateException"
private const val ILLEGAL_ARGUMENT_EXCEPTION = "IllegalArgumentException"
}
private enum class KotlinFunction(val functionName: String) {
CHECK("check"), CHECK_NOT_NULL("checkNotNull"), REQUIRE("require"), REQUIRE_NOT_NULL("requireNotNull");
val fqName: String
get() = "kotlin.$functionName"
}
override fun inspectionText(element: KtIfExpression) = KotlinBundle.message("replace.guard.clause.with.kotlin.s.function.call")
override val defaultFixText get() = KotlinBundle.message("replace.with.kotlin.s.function.call")
override fun fixText(element: KtIfExpression) =
element.getKotlinFunction()?.let { KotlinBundle.message("replace.with.0.call", it.functionName) } ?: defaultFixText
override fun inspectionHighlightRangeInElement(element: KtIfExpression) = element.ifKeyword.textRangeIn(element)
override fun isApplicable(element: KtIfExpression): Boolean {
val languageVersionSettings = element.languageVersionSettings
if (!languageVersionSettings.supportsFeature(LanguageFeature.UseReturnsEffect)) return false
if (element.condition == null) return false
val call = element.getCallExpression() ?: return false
val calleeText = call.calleeExpression?.text ?: return false
val valueArguments = call.valueArguments
if (valueArguments.size > 1) return false
if (calleeText != ILLEGAL_STATE_EXCEPTION && calleeText != ILLEGAL_ARGUMENT_EXCEPTION) return false
val context = call.analyze(BodyResolveMode.PARTIAL_WITH_CFA)
val argumentType = valueArguments.firstOrNull()?.getArgumentExpression()?.getType(context)
if (argumentType != null && !KotlinBuiltIns.isStringOrNullableString(argumentType)) return false
if (element.isUsedAsExpression(context)) return false
val fqName = call.getResolvedCall(context)?.resultingDescriptor?.fqNameSafe?.parentOrNull()
return fqName == FqName("kotlin.$calleeText") || fqName == FqName("java.lang.$calleeText")
}
override fun applyTo(element: KtIfExpression, project: Project, editor: Editor?) {
val condition = element.condition ?: return
val call = element.getCallExpression() ?: return
val argument = call.valueArguments.firstOrNull()?.getArgumentExpression()
val commentSaver = CommentSaver(element)
val psiFactory = KtPsiFactory(element)
val replaced = when (val kotlinFunction = element.getKotlinFunction(call)) {
KotlinFunction.CHECK, KotlinFunction.REQUIRE -> {
val (excl, newCondition) = if (condition is KtPrefixExpression && condition.operationToken == KtTokens.EXCL) {
"" to (condition.baseExpression ?: return)
} else {
"!" to condition
}
val newExpression = if (argument == null) {
psiFactory.createExpressionByPattern("${kotlinFunction.fqName}($excl$0)", newCondition)
} else {
psiFactory.createExpressionByPattern("${kotlinFunction.fqName}($excl$0) { $1 }", newCondition, argument)
}
val replaced = element.replaceWith(newExpression, psiFactory)
val newCall = (replaced as? KtDotQualifiedExpression)?.callExpression
val negatedExpression = newCall?.valueArguments?.firstOrNull()?.getArgumentExpression() as? KtPrefixExpression
if (negatedExpression != null) {
NegatedBinaryExpressionSimplificationUtils.simplifyNegatedBinaryExpressionIfNeeded(negatedExpression)
}
replaced
}
KotlinFunction.CHECK_NOT_NULL, KotlinFunction.REQUIRE_NOT_NULL -> {
val nullCheckedExpression = condition.notNullCheckExpression() ?: return
val newExpression = if (argument == null) {
psiFactory.createExpressionByPattern("${kotlinFunction.fqName}($0)", nullCheckedExpression)
} else {
psiFactory.createExpressionByPattern("${kotlinFunction.fqName}($0) { $1 }", nullCheckedExpression, argument)
}
element.replaceWith(newExpression, psiFactory)
}
else -> return
}
commentSaver.restore(replaced)
editor?.caretModel?.moveToOffset(replaced.startOffset)
ShortenReferences.DEFAULT.process(replaced)
}
private fun KtIfExpression.replaceWith(newExpression: KtExpression, psiFactory: KtPsiFactory): KtExpression {
val parent = parent
val elseBranch = `else`
return if (elseBranch != null) {
val added = parent.addBefore(newExpression, this) as KtExpression
parent.addBefore(psiFactory.createNewLine(), this)
replaceWithBranch(elseBranch, isUsedAsExpression = false, keepBraces = false)
added
} else {
replaced(newExpression)
}
}
private fun KtIfExpression.getCallExpression(): KtCallExpression? {
val throwExpression = this.then?.let {
it as? KtThrowExpression ?: (it as? KtBlockExpression)?.statements?.singleOrNull() as? KtThrowExpression
} ?: return null
return throwExpression.thrownExpression?.let {
it as? KtCallExpression ?: (it as? KtQualifiedExpression)?.callExpression
}
}
private fun KtIfExpression.getKotlinFunction(call: KtCallExpression? = getCallExpression()): KotlinFunction? {
val calleeText = call?.calleeExpression?.text ?: return null
val isNotNullCheck = condition.notNullCheckExpression() != null
return when (calleeText) {
ILLEGAL_STATE_EXCEPTION -> if (isNotNullCheck) KotlinFunction.CHECK_NOT_NULL else KotlinFunction.CHECK
ILLEGAL_ARGUMENT_EXCEPTION -> if (isNotNullCheck) KotlinFunction.REQUIRE_NOT_NULL else KotlinFunction.REQUIRE
else -> null
}
}
private fun KtExpression?.notNullCheckExpression(): KtExpression? {
if (this == null) return null
if (this !is KtBinaryExpression) return null
if (this.operationToken != KtTokens.EQEQ) return null
val left = this.left ?: return null
val right = this.right ?: return null
return when {
right.isNullConstant() -> left
left.isNullConstant() -> right
else -> null
}
}
private fun KtExpression.isNullConstant(): Boolean {
return (this as? KtConstantExpression)?.text == KtTokens.NULL_KEYWORD.value
}
}
| apache-2.0 | 10c9512e9bb1cf9bc2f25e4969bbb496 | 51.217391 | 131 | 0.701439 | 5.45201 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/base/platforms/src/org/jetbrains/kotlin/idea/base/platforms/KLibUtils.kt | 6 | 3552 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
@file:JvmName("KLibUtils")
package org.jetbrains.kotlin.idea.base.platforms
import com.intellij.ide.highlighter.ArchiveFileType
import com.intellij.openapi.vfs.InvalidVirtualFileAccessException
import com.intellij.openapi.vfs.VirtualFile
import org.jetbrains.annotations.ApiStatus
import org.jetbrains.kotlin.library.*
import org.jetbrains.kotlin.library.impl.BuiltInsPlatform
import org.jetbrains.kotlin.platform.TargetPlatform
import org.jetbrains.kotlin.platform.isCommon
import org.jetbrains.kotlin.platform.js.isJs
import org.jetbrains.kotlin.platform.jvm.isJvm
import org.jetbrains.kotlin.platform.konan.isNative
import java.io.IOException
import java.util.*
@ApiStatus.Internal
fun VirtualFile.isKlibLibraryRootForPlatform(targetPlatform: TargetPlatform): Boolean {
// The virtual file for a library packed in a ZIP file will have path like "/some/path/to/the/file.klib!/",
// and therefore will be recognized by VFS as a directory (isDirectory == true).
// So, first, let's check the file type and file extension.
if ((fileType == ArchiveFileType.INSTANCE && extension != KLIB_FILE_EXTENSION) || !isDirectory)
return false
// run check for library root too
// this is necessary to recognize old style KLIBs that do not have components, and report tem to user appropriately
// (relevant only for Kotlin/Native KLIBs)
val requestedBuiltInsPlatform = targetPlatform.toBuiltInsPlatform()
if (requestedBuiltInsPlatform == BuiltInsPlatform.NATIVE && checkKlibComponent(this, requestedBuiltInsPlatform)) {
return true
}
try {
return children?.any { checkKlibComponent(it, requestedBuiltInsPlatform) } == true
} catch (e: InvalidVirtualFileAccessException) {
return false
}
}
private fun checkKlibComponent(componentFile: VirtualFile, requestedBuiltInsPlatform: BuiltInsPlatform): Boolean {
val manifestFile = componentFile.findChild(KLIB_MANIFEST_FILE_NAME)?.takeIf { !it.isDirectory } ?: return false
val manifestProperties = try {
manifestFile.inputStream.use { Properties().apply { load(it) } }
} catch (_: IOException) {
return false
}
if (!manifestProperties.containsKey(KLIB_PROPERTY_UNIQUE_NAME)) return false
val builtInsPlatformProperty = manifestProperties.getProperty(KLIB_PROPERTY_BUILTINS_PLATFORM)
// No builtins_platform property => either a new common klib (we don't write builtins_platform for common) or old Native klib
?: return when (requestedBuiltInsPlatform) {
BuiltInsPlatform.NATIVE -> componentFile.isLegacyNativeKlibComponent // TODO(dsavvinov): drop additional legacy check after 1.4
BuiltInsPlatform.COMMON -> !componentFile.isLegacyNativeKlibComponent
else -> false
}
val builtInsPlatform = BuiltInsPlatform.parseFromString(builtInsPlatformProperty) ?: return false
return builtInsPlatform == requestedBuiltInsPlatform
}
private fun TargetPlatform.toBuiltInsPlatform() = when {
isCommon() -> BuiltInsPlatform.COMMON
isNative() -> BuiltInsPlatform.NATIVE
isJvm() -> BuiltInsPlatform.JVM
isJs() -> BuiltInsPlatform.JS
else -> throw IllegalArgumentException("Unknown platform $this")
}
private val VirtualFile.isLegacyNativeKlibComponent: Boolean
get() {
val irFolder = findChild(KLIB_IR_FOLDER_NAME)
return irFolder != null && irFolder.children.isNotEmpty()
} | apache-2.0 | 50c93f452b8c130ec384fee5882e31a0 | 44.551282 | 139 | 0.752534 | 4.536398 | false | false | false | false |
GunoH/intellij-community | java/java-tests/testSrc/com/intellij/java/propertyBased/ProjectProblemsViewPropertyTest.kt | 7 | 20722 | // 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.java.propertyBased
import com.intellij.codeInsight.daemon.impl.HighlightInfo
import com.intellij.codeInsight.daemon.problems.MemberCollector
import com.intellij.codeInsight.daemon.problems.MemberUsageCollector
import com.intellij.codeInsight.daemon.problems.Problem
import com.intellij.codeInsight.daemon.problems.pass.ProjectProblemUtils
import com.intellij.codeInsight.javadoc.JavaDocUtil
import com.intellij.lang.annotation.HighlightSeverity
import com.intellij.openapi.command.WriteCommandAction
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.fileEditor.FileEditorManager
import com.intellij.openapi.fileEditor.OpenFileDescriptor
import com.intellij.openapi.fileEditor.TextEditor
import com.intellij.openapi.module.ModuleUtilCore
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.RecursionManager
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.psi.*
import com.intellij.psi.impl.search.JavaOverridingMethodsSearcher
import com.intellij.psi.impl.source.resolve.JavaResolveUtil
import com.intellij.psi.search.GlobalSearchScope
import com.intellij.psi.search.PsiSearchHelper
import com.intellij.psi.search.PsiSearchHelper.SearchCostResult.TOO_MANY_OCCURRENCES
import com.intellij.psi.search.SearchScope
import com.intellij.psi.search.searches.ReferencesSearch
import com.intellij.psi.util.PsiTreeUtil
import com.intellij.psi.util.PsiUtil
import com.intellij.testFramework.SkipSlowTestLocally
import com.intellij.testFramework.TestModeFlags
import com.intellij.testFramework.fixtures.impl.CodeInsightTestFixtureImpl
import com.intellij.testFramework.propertyBased.MadTestingUtil
import com.intellij.util.ArrayUtilRt
import com.siyeh.ig.psiutils.TypeUtils
import junit.framework.TestCase
import org.jetbrains.jetCheck.Generator
import org.jetbrains.jetCheck.ImperativeCommand
import org.jetbrains.jetCheck.PropertyChecker
import kotlin.math.absoluteValue
@SkipSlowTestLocally
class ProjectProblemsViewPropertyTest : BaseUnivocityTest() {
override fun setUp() {
TestModeFlags.set(ProjectProblemUtils.ourTestingProjectProblems, true, testRootDisposable)
super.setUp()
}
fun testAllFilesWithMemberNameReported() {
RecursionManager.disableMissedCacheAssertions(testRootDisposable)
PropertyChecker.customized()
.withIterationCount(50)
.checkScenarios { ImperativeCommand(this::doTestAllFilesWithMemberNameReported) }
}
private fun doTestAllFilesWithMemberNameReported(env: ImperativeCommand.Environment) {
val changedFiles = mutableMapOf<VirtualFile, Set<VirtualFile>>()
MadTestingUtil.changeAndRevert(myProject) {
val nFilesToChange = env.generateValue(Generator.integers(1, 3), "Files to change: %s")
var i = 0
while (i < nFilesToChange) {
val fileToChange = env.generateValue(psiJavaFiles(), null)
val relatedFiles = findRelatedFiles(fileToChange)
if (relatedFiles.isEmpty()) continue
val members = findMembers(fileToChange)
if (members.isEmpty()) continue
val editor = openEditor(fileToChange.virtualFile)
rehighlight(fileToChange, editor)
if (getFilesReportedByProblemSearch(editor).isNotEmpty()) continue
env.logMessage("Selected file: ${fileToChange.name}")
val actual = changeSelectedFile(env, members, fileToChange)
if (actual == null) break
changedFiles[fileToChange.virtualFile] = relatedFiles
val expected = findFilesWithProblems(relatedFiles, members)
assertContainsElements(actual, expected)
i++
}
}
// check that all problems disappeared after revert
val psiManager = PsiManager.getInstance(myProject)
for ((changedFile, relatedFiles) in changedFiles) {
val psiFile = psiManager.findFile(changedFile)!!
val editor = openEditor(changedFile)
rehighlight(psiFile, editor)
val problems: Map<PsiMember, Set<Problem>> = ProjectProblemUtils.getReportedProblems(editor)
if (problems.isNotEmpty()) {
val relatedProblems = findRelatedProblems(problems, relatedFiles)
if (relatedProblems.isNotEmpty()) {
TestCase.fail("""
Problems are still reported even after the fix.
File: ${changedFile.name},
${relatedProblems.map { (member, memberProblems) -> extractMemberProblems(member, memberProblems) }}
""".trimIndent())
}
}
}
}
private data class ScopedMember(val psiMember: PsiMember, var scope: SearchScope)
private fun changeSelectedFile(env: ImperativeCommand.Environment,
members: List<ScopedMember>,
fileToChange: PsiJavaFile): Set<VirtualFile>? {
val reportedFiles = mutableSetOf<VirtualFile>()
val nChanges = env.generateValue(Generator.integers(1, 5), "Changes to make: %s")
for (j in 0 until nChanges) {
val editor = (FileEditorManager.getInstance(myProject).selectedEditor as TextEditor).editor
val member = env.generateValue(Generator.sampledFrom(members), null)
val psiMember = member.psiMember
val prevScope = psiMember.useScope
env.logMessage("Changing member: ${JavaDocUtil.getReferenceText(myProject, psiMember)}")
val usages = findUsages(psiMember)
if (usages.isNullOrEmpty()) {
env.logMessage("Member has no usages (or too many). Skipping.")
continue
}
env.logMessage("Found ${usages.size} usages of member and its parents")
val modifications = Modification.getPossibleModifications(psiMember, env)
if (modifications.isEmpty()) {
env.logMessage("Don't know how to modify this member, skipping it.")
continue
}
val modification = env.generateValue(Generator.sampledFrom(modifications), "Applying modification: %s")
val membersToSearch = getMembersToSearch(member, modification, members)
if (membersToSearch == null) {
env.logMessage("Too costly to analyse change, skipping")
continue
}
rehighlight(fileToChange, editor)
WriteCommandAction.runWriteCommandAction(myProject) { modification.apply(myProject) }
env.logMessage("Modification applied")
rehighlight(fileToChange, editor)
if (!isCheapToSearch(psiMember)) {
env.logMessage("Too costly to analyze element after change, skipping all iteration")
return null
}
reportedFiles.addAll(getFilesReportedByProblemSearch(editor))
val curScope = psiMember.useScope
member.scope = prevScope.union(curScope)
}
return reportedFiles
}
private fun getMembersToSearch(member: ScopedMember, modification: Modification, members: List<ScopedMember>): List<ScopedMember>? {
if (!modification.searchAllMembers()) return listOf(member)
if (members.any { !isCheapToSearch(it.psiMember) }) return null
return members
}
private fun rehighlight(psiFile: PsiFile, editor: Editor): List<HighlightInfo> {
PsiDocumentManager.getInstance(myProject).commitAllDocuments()
return CodeInsightTestFixtureImpl.instantiateAndRun(psiFile, editor, ArrayUtilRt.EMPTY_INT_ARRAY, true)
}
private fun openEditor(virtualFile: VirtualFile) =
FileEditorManager.getInstance(myProject).openTextEditor(OpenFileDescriptor(myProject, virtualFile), true)!!
private fun findRelatedFiles(psiFile: PsiFile): Set<VirtualFile> {
val targetFile = psiFile.virtualFile
if (psiFile !is PsiClassOwner) return mutableSetOf()
return psiFile.classes.asSequence()
.flatMap { ReferencesSearch.search(it).findAll().asSequence() }
.map { it.element }
.filter { !JavaResolveUtil.isInJavaDoc(it) }
.mapNotNull { it.containingFile }
.distinctBy { it.virtualFile }
.mapNotNullTo(mutableSetOf()) {
val virtualFile = it.virtualFile
if (virtualFile == targetFile || hasErrors(it)) null else virtualFile
}
}
private fun findMembers(psiFile: PsiClassOwner): List<ScopedMember> {
return MemberCollector.collectMembers(psiFile) { member ->
if (member is PsiMethod && member.isConstructor) return@collectMembers false
val modifiers = member.modifierList ?: return@collectMembers true
return@collectMembers !modifiers.hasExplicitModifier(PsiModifier.PRIVATE)
}.map { ScopedMember(it, it.useScope) }
}
private fun findUsages(target: PsiMember): List<PsiElement>? {
if (!isCheapToSearch(target)) return null
val members = PsiTreeUtil.collectParents(target, PsiMember::class.java, true) { false }
val usages = mutableListOf<PsiElement>()
for (member in members) {
val name = member.name ?: return null
val scope = member.useScope as? GlobalSearchScope ?: return null
val usageExtractor: (PsiFile, Int) -> PsiElement? = lambda@{ psiFile, index ->
val identifier = psiFile.findElementAt(index) as? PsiIdentifier ?: return@lambda null
return@lambda when (val parent = identifier.parent) {
is PsiReference -> if (parent.isReferenceTo(member)) parent else null
is PsiMethod -> if (isOverride(parent, member)) parent else null
else -> null
}
}
val memberUsages = MemberUsageCollector.collect(name, member.containingFile, scope, usageExtractor) ?: return null
usages.addAll(memberUsages)
}
return usages
}
private fun isCheapToSearch(member: PsiMember): Boolean {
val name = member.name ?: return false
val module = ModuleUtilCore.findModuleForPsiElement(member) ?: return false
val scope = GlobalSearchScope.moduleScope(module)
val memberFile = member.containingFile
return PsiSearchHelper.getInstance(myProject).isCheapEnoughToSearch(name, scope, memberFile, null) != TOO_MANY_OCCURRENCES
}
private fun isOverride(possibleOverride: PsiMethod, target: PsiMember): Boolean {
val targetMethod = target as? PsiMethod ?: return false
val overrideClass = possibleOverride.containingClass ?: return false
val targetClass = targetMethod.containingClass ?: return false
if (!overrideClass.isInheritor(targetClass, true)) return false
return possibleOverride == JavaOverridingMethodsSearcher.findOverridingMethod(overrideClass, target, targetClass)
}
private fun findFilesWithProblems(relatedFiles: Set<VirtualFile>, members: List<ScopedMember>): Set<VirtualFile> {
val psiManager = PsiManager.getInstance(myProject)
val filesWithErrors = mutableSetOf<VirtualFile>()
for (file in relatedFiles) {
val psiFile = psiManager.findFile(file) ?: continue
if (hasErrors(psiFile, members)) filesWithErrors.add(file)
}
return filesWithErrors
}
private fun hasErrors(psiFile: PsiFile, members: List<ScopedMember>? = null): Boolean {
val infos = rehighlight(psiFile, openEditor(psiFile.virtualFile))
return infos.any { info ->
if (info.severity != HighlightSeverity.ERROR) return@any false
if (members == null) return@any true
val startElement = psiFile.findElementAt(info.actualStartOffset) ?: return@any false
val endElement = psiFile.findElementAt(info.actualEndOffset - 1) ?: return@any false
val reported = PsiTreeUtil.findCommonParent(startElement, endElement) ?: return@any false
if (JavaResolveUtil.isInJavaDoc(reported)) return@any false
val context = PsiTreeUtil.getNonStrictParentOfType(reported,
PsiStatement::class.java, PsiClass::class.java,
PsiMethod::class.java, PsiField::class.java,
PsiReferenceList::class.java) ?: return@any false
return@any PsiTreeUtil.collectElements(context, { r -> true })
.any { el -> el is PsiReference && members.any { m -> el.isReferenceTo(m.psiMember) && inScope(el.containingFile, m.scope) } }
}
}
private fun inScope(psiFile: PsiFile, scope: SearchScope): Boolean = scope.contains(psiFile.virtualFile)
private fun findRelatedProblems(problems: Map<PsiMember, Set<Problem>>, relatedFiles: Set<VirtualFile>): Map<PsiMember, Set<Problem>> {
val relatedProblems = mutableMapOf<PsiMember, Set<Problem>>()
for ((member, memberProblems) in problems) {
val memberRelatedProblems = mutableSetOf<Problem>()
for (memberProblem in memberProblems) {
val problemFile = memberProblem.reportedElement.containingFile
if (problemFile.virtualFile in relatedFiles) memberRelatedProblems.add(memberProblem)
}
if (memberRelatedProblems.isNotEmpty()) relatedProblems[member] = memberRelatedProblems
}
return relatedProblems
}
private fun extractMemberProblems(member: PsiMember, memberProblems: Set<Problem>): String {
data class ProblemData(val fileName: String, val offset: Int, val reportedElement: String,
val context: String?, val fileErrors: List<HighlightInfo>)
fun getProblemData(problem: Problem): ProblemData {
val context = problem.context
val reportedElement = problem.reportedElement
val psiFile = reportedElement.containingFile
val fileName = psiFile.name
val offset = reportedElement.textOffset
val textEditor = FileEditorManager.getInstance(myProject).openFile(psiFile.virtualFile, true)[0] as TextEditor
val fileErrors = rehighlight(psiFile, textEditor.editor).filter { it.severity == HighlightSeverity.ERROR }
return ProblemData(fileName, offset, reportedElement.text, context.text, fileErrors)
}
return "Member: ${JavaDocUtil.getReferenceText(member.project, member)}," +
" Problems: ${memberProblems.map { getProblemData(it) }}\n"
}
private fun getFilesReportedByProblemSearch(editor: Editor): Set<VirtualFile> =
ProjectProblemUtils.getReportedProblems(editor).asSequence()
.flatMap { it.value.asSequence() }
.map { it.reportedElement.containingFile }
.mapTo(mutableSetOf()) { it.virtualFile }
private sealed class Modification(protected val member: PsiMember, env: ImperativeCommand.Environment) {
abstract fun apply(project: Project)
abstract override fun toString(): String
open fun searchAllMembers(): Boolean = false
companion object {
val classModifications = arrayOf(::ChangeName, ::ExplicitModifierModification, ::ChangeExtendsList, ::MakeClassInterface)
val methodModifications = arrayOf(::ChangeName, ::ExplicitModifierModification, ::ChangeType, ::AddParam)
val fieldModifications = arrayOf(::ChangeName, ::ExplicitModifierModification, ::ChangeType)
fun getPossibleModifications(member: PsiMember, env: ImperativeCommand.Environment) = when (member) {
is PsiClass -> classModifications.map { it(member, env) }
is PsiMethod -> methodModifications.map { it(member, env) }
is PsiField -> if (member is PsiEnumConstant) emptyList() else fieldModifications.map { it(member, env) }
else -> emptyList()
}
private fun String.absHash(): Int {
val hash = hashCode()
return if (hash == Int.MIN_VALUE) Int.MAX_VALUE else hash.absoluteValue
}
}
private class ChangeName(member: PsiMember, env: ImperativeCommand.Environment) : Modification(member, env) {
private val newName: String
init {
val namedMember = member as PsiNameIdentifierOwner
val identifier = namedMember.nameIdentifier!!
val oldName = identifier.text
newName = oldName + oldName.absHash()
}
override fun apply(project: Project) {
val factory = JavaPsiFacade.getElementFactory(project)
(member as PsiNameIdentifierOwner).nameIdentifier!!.replace(factory.createIdentifier(newName))
}
override fun toString(): String = "ChangeName: new name is '$newName'"
}
private class ExplicitModifierModification(member: PsiMember, env: ImperativeCommand.Environment) : Modification(member, env) {
private val modifier: String = env.generateValue(Generator.sampledFrom(*MODIFIERS), null)
override fun apply(project: Project) {
val modifiers = member.modifierList ?: return
val hasModifier = modifiers.hasExplicitModifier(modifier)
if (!hasModifier && isAccessModifier(modifier)) {
val curAccessModifier = getAccessModifier(modifiers)
if (curAccessModifier != null) modifiers.setModifierProperty(curAccessModifier, false)
}
modifiers.setModifierProperty(modifier, !hasModifier)
}
companion object {
private val MODIFIERS = arrayOf(PsiModifier.PUBLIC, PsiModifier.PROTECTED,
PsiModifier.PRIVATE, PsiModifier.STATIC,
PsiModifier.ABSTRACT, PsiModifier.FINAL)
private val ACCESS_MODIFIERS = arrayOf(PsiModifier.PRIVATE, PsiModifier.PUBLIC, PsiModifier.PROTECTED)
private fun isAccessModifier(modifier: String) = modifier in ACCESS_MODIFIERS
private fun getAccessModifier(modifiers: PsiModifierList): String? =
sequenceOf(*ACCESS_MODIFIERS).firstOrNull { modifiers.hasExplicitModifier(it) }
}
override fun toString(): String = "ExplicitModifierModification: tweaking modifier '$modifier'"
}
private class ChangeType(member: PsiMember, env: ImperativeCommand.Environment) : Modification(member, env) {
private val typeElement = env.generateValue(Generator.sampledFrom(findTypeElements(member)), null)
private val newType = if (typeElement.type == PsiPrimitiveType.INT) TypeUtils.getStringType(typeElement) else PsiPrimitiveType.INT
override fun apply(project: Project) {
val factory = JavaPsiFacade.getElementFactory(project)
typeElement.replace(factory.createTypeElement(newType))
}
private fun findTypeElements(member: PsiMember): List<PsiTypeElement> {
val elements: Collection<PsiTypeElement> = PsiTreeUtil.findChildrenOfAnyType(member, false, PsiTypeElement::class.java)
return elements.toMutableList()
}
override fun toString(): String =
"ChangeType: '${typeElement.type.canonicalText}' is changed to '${newType.canonicalText}'"
}
private class AddParam(method: PsiMethod, env: ImperativeCommand.Environment) : Modification(method, env) {
val paramName: String
init {
val methodName = method.name
paramName = methodName + methodName.absHash()
}
override fun apply(project: Project) {
val factory = JavaPsiFacade.getElementFactory(project)
val param = factory.createParameter(paramName, PsiType.INT)
(member as PsiMethod).parameterList.add(param)
}
override fun toString(): String = "AddParam: param '$paramName' added"
}
private class ChangeExtendsList(psiClass: PsiClass, env: ImperativeCommand.Environment) : Modification(psiClass, env) {
private val parentRef: PsiElement?
init {
val refs = psiClass.extendsList?.referenceElements
parentRef = if (refs == null || refs.size != 1) null else refs[0].element
}
override fun apply(project: Project) {
if (parentRef == null) return
val factory = JavaPsiFacade.getElementFactory(project)
parentRef.replace(factory.createTypeElement(TypeUtils.getObjectType(parentRef)))
}
override fun searchAllMembers() = true
override fun toString(): String =
if (parentRef != null) "ChangeExtendsList: change '${parentRef.text}' to 'java.lang.Object'"
else "ChangeExtendsList: class doesn't extend anything, do nothing"
}
private class MakeClassInterface(psiClass: PsiClass, env: ImperativeCommand.Environment) : Modification(psiClass, env) {
override fun apply(project: Project) {
val psiClass = member as PsiClass
if (psiClass.isEnum || psiClass.isInterface || psiClass.isAnnotationType) return
val classKeyword = PsiTreeUtil.getPrevSiblingOfType(psiClass.nameIdentifier!!, PsiKeyword::class.java) ?: return
val factory = JavaPsiFacade.getElementFactory(project)
val newTypeKeyword = factory.createKeyword(PsiKeyword.INTERFACE)
PsiUtil.setModifierProperty(psiClass, PsiModifier.ABSTRACT, false)
PsiUtil.setModifierProperty(psiClass, PsiModifier.FINAL, false)
classKeyword.replace(newTypeKeyword)
}
override fun searchAllMembers() = true
override fun toString(): String = "MakeClassInterface: type changed to 'interface'"
}
}
} | apache-2.0 | 0a7570a314e6c9346c475291e8fb2f66 | 44.949002 | 140 | 0.720104 | 4.929115 | false | false | false | false |
siosio/intellij-community | platform/statistics/src/com/intellij/internal/statistic/eventLog/StatisticsEventLogWriter.kt | 1 | 2361 | // 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.internal.statistic.eventLog
import com.intellij.openapi.Disposable
import org.apache.log4j.Level
import org.apache.log4j.Logger
import org.apache.log4j.PatternLayout
import java.io.File
import java.io.IOException
import java.nio.file.Path
interface StatisticsEventLogWriter: Disposable {
fun log(logEvent: LogEvent)
fun getActiveFile(): EventLogFile?
fun getLogFilesProvider(): EventLogFilesProvider
fun cleanup()
fun rollOver()
}
class StatisticsEventLogFileWriter(private val recorderId: String,
private val maxFileSize: String,
isEap: Boolean,
prefix: String) : StatisticsEventLogWriter {
private var fileAppender: StatisticsEventLogFileAppender? = null
@Suppress("SSBasedInspection")
private val eventLogger: Logger = Logger.getLogger("event.logger.$recorderId")
init {
eventLogger.level = Level.INFO
eventLogger.additivity = false
val pattern = PatternLayout("%m\n")
try {
val dir = getEventLogDir()
fileAppender = StatisticsEventLogFileAppender.create(pattern, dir, prefix, isEap)
fileAppender?.let { appender ->
appender.setMaxFileSize(maxFileSize)
eventLogger.addAppender(appender)
}
}
catch (e: IOException) {
System.err.println("Unable to initialize logging for feature usage: " + e.localizedMessage)
}
}
private fun getEventLogDir(): Path {
return EventLogConfiguration.getInstance().getEventLogDataPath().resolve("logs").resolve(recorderId)
}
override fun log(logEvent: LogEvent) {
eventLogger.info(LogEventSerializer.toString(logEvent))
}
override fun getActiveFile(): EventLogFile? {
val activeLog = fileAppender?.activeLogName ?: return null
return EventLogFile(File(File(getEventLogDir().toUri()), activeLog))
}
override fun getLogFilesProvider(): EventLogFilesProvider {
return DefaultEventLogFilesProvider(getEventLogDir()) { fileAppender?.activeLogName }
}
override fun cleanup() {
fileAppender?.cleanUp()
}
override fun rollOver() {
fileAppender?.rollOver()
}
override fun dispose() = Unit
} | apache-2.0 | f010245c610881464332671985d5b565 | 29.675325 | 158 | 0.710716 | 4.647638 | false | false | false | false |
jwren/intellij-community | platform/external-system-impl/src/com/intellij/openapi/externalSystem/dependency/analyzer/DependencyAnalyzerEditorTab.kt | 2 | 1676 | // 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.externalSystem.dependency.analyzer
import com.intellij.icons.AllIcons
import com.intellij.ide.actions.SplitAction
import com.intellij.ide.plugins.UIComponentVirtualFile
import com.intellij.openapi.Disposable
import com.intellij.openapi.externalSystem.model.ProjectSystemId
import com.intellij.openapi.externalSystem.util.ExternalSystemBundle
import com.intellij.openapi.fileEditor.FileEditorManager
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.Disposer
import com.intellij.openapi.vfs.VirtualFile
import org.jetbrains.annotations.ApiStatus
@ApiStatus.Internal
class DependencyAnalyzerEditorTab(private val project: Project, systemId: ProjectSystemId) : Disposable {
val view = DependencyAnalyzerViewImpl(project, systemId, this)
private val file: VirtualFile by lazy {
val name = ExternalSystemBundle.message("external.system.dependency.analyzer.editor.tab.name")
UIComponentVirtualFile(name, object : UIComponentVirtualFile.Content {
override fun getIcon() = AllIcons.Actions.DependencyAnalyzer
override fun createComponent() = view.createComponent()
override fun getPreferredFocusedComponent() = null
}).apply {
putUserData(SplitAction.FORBID_TAB_SPLIT, true)
}
}
fun show() {
val editorManager = FileEditorManager.getInstance(project)
val editors = editorManager.openFile(file, true)
for (editor in editors) {
Disposer.register(editor, this)
}
}
override fun dispose() {}
} | apache-2.0 | da5fb3240a2f4f2bf83ee6de7a608ac0 | 39.902439 | 158 | 0.789976 | 4.668524 | false | false | false | false |
jwren/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/blockingCallsDetection/CoroutineNonBlockingContextChecker.kt | 1 | 11131 | // 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.blockingCallsDetection
import com.intellij.codeInspection.blockingCallsDetection.ContextType
import com.intellij.codeInspection.blockingCallsDetection.ContextType.*
import com.intellij.codeInspection.blockingCallsDetection.ElementContext
import com.intellij.codeInspection.blockingCallsDetection.NonBlockingContextChecker
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiFile
import com.intellij.psi.PsiRecursiveElementVisitor
import com.intellij.psi.util.parentsOfType
import com.intellij.util.castSafelyTo
import org.jetbrains.kotlin.builtins.getReceiverTypeFromFunctionType
import org.jetbrains.kotlin.builtins.isBuiltinFunctionalType
import org.jetbrains.kotlin.builtins.isSuspendFunctionType
import org.jetbrains.kotlin.config.LanguageFeature
import org.jetbrains.kotlin.config.LanguageVersionSettings
import org.jetbrains.kotlin.descriptors.*
import org.jetbrains.kotlin.idea.caches.resolve.resolveToCall
import org.jetbrains.kotlin.idea.core.receiverValue
import org.jetbrains.kotlin.idea.inspections.blockingCallsDetection.CoroutineBlockingCallInspectionUtils.BLOCKING_EXECUTOR_ANNOTATION
import org.jetbrains.kotlin.idea.inspections.blockingCallsDetection.CoroutineBlockingCallInspectionUtils.COROUTINE_CONTEXT
import org.jetbrains.kotlin.idea.inspections.blockingCallsDetection.CoroutineBlockingCallInspectionUtils.COROUTINE_SCOPE
import org.jetbrains.kotlin.idea.inspections.blockingCallsDetection.CoroutineBlockingCallInspectionUtils.DEFAULT_DISPATCHER_FQN
import org.jetbrains.kotlin.idea.inspections.blockingCallsDetection.CoroutineBlockingCallInspectionUtils.FLOW_PACKAGE_FQN
import org.jetbrains.kotlin.idea.inspections.blockingCallsDetection.CoroutineBlockingCallInspectionUtils.IO_DISPATCHER_FQN
import org.jetbrains.kotlin.idea.inspections.blockingCallsDetection.CoroutineBlockingCallInspectionUtils.MAIN_DISPATCHER_FQN
import org.jetbrains.kotlin.idea.inspections.blockingCallsDetection.CoroutineBlockingCallInspectionUtils.NONBLOCKING_EXECUTOR_ANNOTATION
import org.jetbrains.kotlin.idea.inspections.blockingCallsDetection.CoroutineBlockingCallInspectionUtils.findFlowOnCall
import org.jetbrains.kotlin.idea.intentions.getCallableDescriptor
import org.jetbrains.kotlin.idea.project.getLanguageVersionSettings
import org.jetbrains.kotlin.idea.project.languageVersionSettings
import org.jetbrains.kotlin.idea.refactoring.fqName.fqName
import org.jetbrains.kotlin.idea.util.projectStructure.module
import org.jetbrains.kotlin.js.resolve.diagnostics.findPsi
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.getParentOfType
import org.jetbrains.kotlin.psi.psiUtil.getParentOfTypes
import org.jetbrains.kotlin.psi.psiUtil.getStrictParentOfType
import org.jetbrains.kotlin.psi.psiUtil.parents
import org.jetbrains.kotlin.resolve.calls.util.getParameterForArgument
import org.jetbrains.kotlin.resolve.calls.checkers.isRestrictsSuspensionReceiver
import org.jetbrains.kotlin.resolve.calls.model.ResolvedCall
import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameOrNull
import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameSafe
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
import org.jetbrains.kotlin.resolve.scopes.DescriptorKindFilter
import org.jetbrains.kotlin.resolve.scopes.receivers.ImplicitClassReceiver
import org.jetbrains.kotlin.types.KotlinType
class CoroutineNonBlockingContextChecker : NonBlockingContextChecker {
override fun isApplicable(file: PsiFile): Boolean {
if (file !is KtFile) return false
val languageVersionSettings = getLanguageVersionSettings(file)
return languageVersionSettings.supportsFeature(LanguageFeature.ReleaseCoroutines)
}
override fun computeContextType(elementContext: ElementContext): ContextType {
val element = elementContext.element
if (element !is KtCallExpression) return Unsure
val containingLambda = element.parents
.filterIsInstance<KtLambdaExpression>()
.firstOrNull()
val containingArgument = containingLambda?.getParentOfType<KtValueArgument>(true, KtCallableDeclaration::class.java)
if (containingArgument != null) {
val callExpression = containingArgument.getStrictParentOfType<KtCallExpression>() ?: return Blocking
val call = callExpression.resolveToCall(BodyResolveMode.PARTIAL) ?: return Blocking
val blockingFriendlyDispatcherUsed = checkBlockingFriendlyDispatcherUsed(call, callExpression)
if (blockingFriendlyDispatcherUsed.isDefinitelyKnown) return blockingFriendlyDispatcherUsed
val parameterForArgument = call.getParameterForArgument(containingArgument) ?: return Blocking
val type = parameterForArgument.returnType ?: return Blocking
if (type.isBuiltinFunctionalType) {
val hasRestrictSuspensionAnnotation = type.getReceiverTypeFromFunctionType()?.isRestrictsSuspensionReceiver() ?: false
return if (!hasRestrictSuspensionAnnotation && type.isSuspendFunctionType) NonBlocking.INSTANCE else Blocking
}
}
if (containingLambda == null) {
val isInSuspendFunctionBody = element.parentsOfType<KtNamedFunction>()
.take(2)
.firstOrNull { function -> function.nameIdentifier != null }
?.hasModifier(KtTokens.SUSPEND_KEYWORD) ?: false
return if (isInSuspendFunctionBody) NonBlocking.INSTANCE else Blocking
}
val containingPropertyOrFunction: KtCallableDeclaration? =
containingLambda.getParentOfTypes(true, KtProperty::class.java, KtNamedFunction::class.java)
if (containingPropertyOrFunction?.typeReference?.hasModifier(KtTokens.SUSPEND_KEYWORD) == true) return NonBlocking.INSTANCE
return if (containingPropertyOrFunction?.hasModifier(KtTokens.SUSPEND_KEYWORD) == true) NonBlocking.INSTANCE else Blocking
}
private fun checkBlockingFriendlyDispatcherUsed(
call: ResolvedCall<out CallableDescriptor>,
callExpression: KtCallExpression
): ContextType {
return union(
{ checkBlockFriendlyDispatcherParameter(call) },
{ checkFunctionWithDefaultDispatcher(callExpression) },
{ checkFlowChainElementWithIODispatcher(call, callExpression) }
)
}
private fun getLanguageVersionSettings(psiElement: PsiElement): LanguageVersionSettings =
psiElement.module?.languageVersionSettings ?: psiElement.project.getLanguageVersionSettings()
private fun ResolvedCall<*>.getFirstArgument(): KtExpression? =
valueArgumentsByIndex?.firstOrNull()?.arguments?.firstOrNull()?.getArgumentExpression()
private fun KotlinType.isCoroutineContext(): Boolean =
(this.constructor.supertypes + this).any { it.fqName?.asString() == COROUTINE_CONTEXT }
private fun checkBlockFriendlyDispatcherParameter(call: ResolvedCall<*>): ContextType {
val argumentDescriptor = call.getFirstArgument()?.resolveToCall()?.resultingDescriptor ?: return Unsure
return argumentDescriptor.isBlockFriendlyDispatcher()
}
private fun checkFunctionWithDefaultDispatcher(callExpression: KtCallExpression): ContextType {
val classDescriptor =
callExpression.receiverValue().castSafelyTo<ImplicitClassReceiver>()?.classDescriptor ?: return Unsure
if (classDescriptor.typeConstructor.supertypes.none { it.fqName?.asString() == COROUTINE_SCOPE }) return Unsure
val propertyDescriptor = classDescriptor
.unsubstitutedMemberScope
.getContributedDescriptors(DescriptorKindFilter.VARIABLES)
.filterIsInstance<PropertyDescriptor>()
.singleOrNull { it.isOverridableOrOverrides && it.type.isCoroutineContext() }
?: return Unsure
val initializer = propertyDescriptor.findPsi().castSafelyTo<KtProperty>()?.initializer ?: return Unsure
return initializer.hasBlockFriendlyDispatcher()
}
private fun checkFlowChainElementWithIODispatcher(
call: ResolvedCall<out CallableDescriptor>,
callExpression: KtCallExpression
): ContextType {
val isInsideFlow = call.resultingDescriptor.fqNameSafe.asString().startsWith(FLOW_PACKAGE_FQN)
if (!isInsideFlow) return Unsure
val flowOnCall = callExpression.findFlowOnCall() ?: return NonBlocking.INSTANCE
return checkBlockFriendlyDispatcherParameter(flowOnCall)
}
private fun KtExpression.hasBlockFriendlyDispatcher(): ContextType {
class RecursiveExpressionVisitor : PsiRecursiveElementVisitor() {
var allowsBlocking: ContextType = Unsure
override fun visitElement(element: PsiElement) {
if (element is KtExpression) {
val callableDescriptor = element.getCallableDescriptor()
val allowsBlocking = callableDescriptor.castSafelyTo<DeclarationDescriptor>()
?.isBlockFriendlyDispatcher()
if (allowsBlocking != null && allowsBlocking != Unsure) {
this.allowsBlocking = allowsBlocking
return
}
}
super.visitElement(element)
}
}
return RecursiveExpressionVisitor().also(this::accept).allowsBlocking
}
private fun DeclarationDescriptor?.isBlockFriendlyDispatcher(): ContextType {
if (this == null) return Unsure
val returnTypeDescriptor = this.castSafelyTo<CallableDescriptor>()?.returnType
val typeConstructor = returnTypeDescriptor?.constructor?.declarationDescriptor
if (isTypeOrUsageAnnotatedWith(returnTypeDescriptor, typeConstructor, BLOCKING_EXECUTOR_ANNOTATION)) return Blocking
if (isTypeOrUsageAnnotatedWith(returnTypeDescriptor, typeConstructor, NONBLOCKING_EXECUTOR_ANNOTATION)) return NonBlocking.INSTANCE
val fqnOrNull = fqNameOrNull()?.asString() ?: return NonBlocking.INSTANCE
return when(fqnOrNull) {
IO_DISPATCHER_FQN -> Blocking
MAIN_DISPATCHER_FQN, DEFAULT_DISPATCHER_FQN -> NonBlocking.INSTANCE
else -> Unsure
}
}
private fun isTypeOrUsageAnnotatedWith(type: KotlinType?, typeConstructor: ClassifierDescriptor?, annotationFqn: String): Boolean {
val fqName = FqName(annotationFqn)
return when {
type?.annotations?.hasAnnotation(fqName) == true -> true
typeConstructor?.annotations?.hasAnnotation(fqName) == true -> true
else -> false
}
}
private fun union(vararg checks: () -> ContextType): ContextType {
for (check in checks) {
val iterationResult = check()
if (iterationResult != Unsure) return iterationResult
}
return Unsure
}
} | apache-2.0 | 98361ff6969bd81008dc883e3e7379a2 | 53.568627 | 158 | 0.75977 | 5.870781 | false | false | false | false |
GunoH/intellij-community | plugins/settings-sync/src/com/intellij/settingsSync/SettingsSnapshotZipSerializer.kt | 2 | 4822 | package com.intellij.settingsSync
import com.fasterxml.jackson.databind.DeserializationFeature
import com.fasterxml.jackson.databind.ObjectMapper
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.util.io.FileUtil
import com.intellij.settingsSync.plugins.SettingsSyncPluginsState
import com.intellij.util.io.*
import kotlinx.serialization.decodeFromString
import kotlinx.serialization.encodeToString
import kotlinx.serialization.json.Json
import java.io.OutputStream
import java.nio.file.Files
import java.nio.file.Path
import java.time.Instant
import java.time.format.DateTimeFormatter
import java.util.*
import java.util.stream.Collectors
import kotlin.io.path.div
internal object SettingsSnapshotZipSerializer {
private const val METAINFO = ".metainfo"
private const val INFO = "info.json"
private const val PLUGINS = "plugins.json"
private val LOG = logger<SettingsSnapshotZipSerializer>()
private val json = Json { prettyPrint = true }
fun serializeToZip(snapshot: SettingsSnapshot): Path {
val file = FileUtil.createTempFile(SETTINGS_SYNC_SNAPSHOT_ZIP, null)
serialize(snapshot, Compressor.Zip(file))
return file.toPath()
}
fun serializeToStream(snapshot: SettingsSnapshot, stream: OutputStream) {
serialize(snapshot, Compressor.Zip(stream))
}
private fun serialize(snapshot: SettingsSnapshot, zipCompressor: Compressor.Zip) {
zipCompressor.use { zip ->
zip.addFile("$METAINFO/$INFO", serializeMetaInfo(snapshot.metaInfo))
if (snapshot.plugins != null) {
zip.addFile("$METAINFO/$PLUGINS", serializePlugins(snapshot.plugins).toByteArray())
}
for (fileState in snapshot.fileStates) {
val content = if (fileState is FileState.Modified) fileState.content else DELETED_FILE_MARKER.toByteArray()
zip.addFile(fileState.file, content)
}
}
}
private fun serializePlugins(plugins: SettingsSyncPluginsState): String {
return json.encodeToString(plugins)
}
fun extractFromZip(zipFile: Path): SettingsSnapshot {
val tempDir = FileUtil.createTempDirectory("settings.sync.updates", null).toPath()
Decompressor.Zip(zipFile).extract(tempDir)
val metaInfoFolder = tempDir / METAINFO
val metaInfo = parseMetaInfo(metaInfoFolder)
val fileStates = Files.walk(tempDir)
.filter { it.isFile() && !metaInfoFolder.isAncestor(it) }
.map { getFileStateFromFileWithDeletedMarker(it, tempDir) }
.collect(Collectors.toSet())
val plugins = deserializePlugins(metaInfoFolder)
return SettingsSnapshot(metaInfo, fileStates, plugins)
}
private fun deserializePlugins(metaInfoFolder: Path): SettingsSyncPluginsState {
val pluginsFile = metaInfoFolder / PLUGINS
try {
if (pluginsFile.exists()) {
return json.decodeFromString(pluginsFile.readText())
}
}
catch (e: Throwable) {
LOG.error("Failed to read $pluginsFile", e)
}
return SettingsSyncPluginsState(emptyMap())
}
private fun serializeMetaInfo(snapshotMetaInfo: SettingsSnapshot.MetaInfo): ByteArray {
val formattedDate = DateTimeFormatter.ISO_INSTANT.format(snapshotMetaInfo.dateCreated)
val metaInfo = MetaInfo().apply {
date = formattedDate
applicationId = snapshotMetaInfo.appInfo?.applicationId.toString()
userName = snapshotMetaInfo.appInfo?.userName.toString()
hostName = snapshotMetaInfo.appInfo?.hostName.toString()
configFolder = snapshotMetaInfo.appInfo?.configFolder.toString()
isDeleted = snapshotMetaInfo.isDeleted
}
return ObjectMapper().writerWithDefaultPrettyPrinter().writeValueAsBytes(metaInfo)
}
private fun parseMetaInfo(path: Path): SettingsSnapshot.MetaInfo {
try {
val infoFile = path / INFO
if (infoFile.exists()) {
val metaInfo = ObjectMapper()
.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
.readValue(infoFile.readText(), MetaInfo::class.java)
val date = DateTimeFormatter.ISO_INSTANT.parse(metaInfo.date, Instant::from)
val appInfo = SettingsSnapshot.AppInfo(UUID.fromString(metaInfo.applicationId),
metaInfo.userName, metaInfo.hostName, metaInfo.configFolder)
return SettingsSnapshot.MetaInfo(date, appInfo, metaInfo.isDeleted)
}
else {
LOG.warn("Timestamp file doesn't exist")
}
}
catch (e: Throwable) {
LOG.error("Couldn't read .metainfo from $SETTINGS_SYNC_SNAPSHOT_ZIP", e)
}
return SettingsSnapshot.MetaInfo(Instant.now(), appInfo = null)
}
private class MetaInfo {
lateinit var date: String
lateinit var applicationId: String
var userName: String = ""
var hostName: String = ""
var configFolder: String = ""
var isDeleted: Boolean = false
}
} | apache-2.0 | 30a4c914e97700cbd239e5fe7ce2e930 | 36.976378 | 115 | 0.727292 | 4.65444 | false | false | false | false |
GunoH/intellij-community | plugins/markdown/core/src/org/intellij/plugins/markdown/ui/actions/styling/BaseToggleStateAction.kt | 2 | 6433 | package org.intellij.plugins.markdown.ui.actions.styling
import com.intellij.openapi.actionSystem.ActionUpdateThread
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.actionSystem.CommonDataKeys
import com.intellij.openapi.actionSystem.ToggleAction
import com.intellij.openapi.application.runWriteAction
import com.intellij.openapi.command.executeCommand
import com.intellij.openapi.diagnostic.thisLogger
import com.intellij.openapi.editor.Caret
import com.intellij.openapi.editor.Document
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.DumbAware
import com.intellij.openapi.util.TextRange
import com.intellij.psi.PsiFile
import com.intellij.psi.tree.IElementType
import com.intellij.psi.util.PsiTreeUtil
import com.intellij.psi.util.elementType
import org.intellij.plugins.markdown.editor.runForEachCaret
import org.intellij.plugins.markdown.lang.MarkdownElementTypes
import org.intellij.plugins.markdown.lang.MarkdownTokenTypes
import org.intellij.plugins.markdown.ui.actions.MarkdownActionUtil
import org.intellij.plugins.markdown.ui.actions.MarkdownActionUtil.getCommonParentOfType
import org.intellij.plugins.markdown.ui.actions.MarkdownActionUtil.getElementsUnderCaretOrSelection
abstract class BaseToggleStateAction: ToggleAction(), DumbAware {
protected abstract fun getBoundString(text: CharSequence, selectionStart: Int, selectionEnd: Int): String
protected open fun getExistingBoundString(text: CharSequence, startOffset: Int): String? {
return text[startOffset].toString()
}
protected abstract fun shouldMoveToWordBounds(): Boolean
protected abstract val targetNodeType: IElementType
override fun update(event: AnActionEvent) {
val editor = MarkdownActionUtil.findMarkdownEditor(event)
event.presentation.isEnabled = editor != null
super.update(event)
}
override fun getActionUpdateThread(): ActionUpdateThread {
return ActionUpdateThread.BGT
}
override fun isSelected(event: AnActionEvent): Boolean {
if (MarkdownActionUtil.findMarkdownEditor(event) == null) {
return false
}
val file = event.getData(CommonDataKeys.PSI_FILE) ?: return false
val caretSnapshots = SelectionUtil.obtainCaretSnapshots(this, event)?.asSequence() ?: return false
val selectionElements = caretSnapshots.map { getElementsUnderCaretOrSelection(file, it.selectionStart, it.selectionEnd) }
val commonParents = selectionElements.map { (left, right) -> getCommonParentOfType(left, right, targetNodeType) }
val hasMissingParents = commonParents.any { it == null }
val hasValidParents = commonParents.any { it != null }
if (hasMissingParents && hasValidParents) {
event.presentation.isEnabled = false
return false
}
event.presentation.isEnabled = true
return !hasMissingParents
}
override fun setSelected(event: AnActionEvent, state: Boolean) {
val editor = MarkdownActionUtil.findMarkdownEditor(event) ?: return
val file = event.getData(CommonDataKeys.PSI_FILE) ?: return
runWriteAction {
executeCommand(file.project, templatePresentation.text) {
editor.caretModel.runForEachCaret(reverseOrder = true) { caret ->
processCaret(file, editor, caret, state)
}
}
}
}
private fun processCaret(file: PsiFile, editor: Editor, caret: Caret, state: Boolean) {
val (first, second) = getElementsUnderCaretOrSelection(file, caret)
if (!state) {
val parent = getCommonParentOfType(first, second, targetNodeType)
if (parent == null) {
thisLogger().warn("Could not find enclosing element on its destruction")
return
}
removeEmphasisFromSelection(editor.document, caret, parent.textRange)
return
}
val parent = PsiTreeUtil.findCommonParent(first, second)
if (parent.elementType !in elementsToIgnore) {
addEmphasisToSelection(editor.document, caret)
}
}
private fun removeEmphasisFromSelection(document: Document, caret: Caret, nodeRange: TextRange) {
val text = document.charsSequence
val boundString = getExistingBoundString(text, nodeRange.startOffset)
if (boundString == null) {
thisLogger().warn("Could not fetch bound string from found node")
return
}
val boundLength = boundString.length
// Easy case --- selection corresponds to some emph
if (nodeRange.startOffset + boundLength == caret.selectionStart
&& nodeRange.endOffset - boundLength == caret.selectionEnd) {
document.deleteString(nodeRange.endOffset - boundLength, nodeRange.endOffset)
document.deleteString(nodeRange.startOffset, nodeRange.startOffset + boundLength)
return
}
var from = caret.selectionStart
var to = caret.selectionEnd
if (shouldMoveToWordBounds()) {
while (from - boundLength > nodeRange.startOffset && Character.isWhitespace(text[from - 1])) {
from--
}
while (to + boundLength < nodeRange.endOffset && Character.isWhitespace(text[to])) {
to++
}
}
if (to + boundLength == nodeRange.endOffset) {
document.deleteString(nodeRange.endOffset - boundLength, nodeRange.endOffset)
}
else {
document.insertString(to, boundString)
}
if (from - boundLength == nodeRange.startOffset) {
document.deleteString(nodeRange.startOffset, nodeRange.startOffset + boundLength)
}
else {
document.insertString(from, boundString)
}
}
private fun addEmphasisToSelection(document: Document, caret: Caret) {
var from = caret.selectionStart
var to = caret.selectionEnd
val text = document.charsSequence
if (shouldMoveToWordBounds()) {
while (from < to && Character.isWhitespace(text[from])) {
from++
}
while (to > from && Character.isWhitespace(text[to - 1])) {
to--
}
if (from == to) {
from = caret.selectionStart
to = caret.selectionEnd
}
}
val boundString = getBoundString(text, from, to)
document.insertString(to, boundString)
document.insertString(from, boundString)
if (caret.selectionStart == caret.selectionEnd) {
caret.moveCaretRelatively(boundString.length, 0, false, false)
}
}
companion object {
private val elementsToIgnore = setOf(
MarkdownElementTypes.LINK_DESTINATION,
MarkdownElementTypes.AUTOLINK,
MarkdownTokenTypes.GFM_AUTOLINK
)
}
}
| apache-2.0 | 0abfea28418668c1a315e5fa6ddb4d15 | 37.987879 | 125 | 0.734028 | 4.54629 | false | false | false | false |
GunoH/intellij-community | platform/lang-impl/src/com/intellij/ide/navigationToolbar/experimental/NewToolbarBorderLayout.kt | 2 | 1911 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.ide.navigationToolbar.experimental
import java.awt.BorderLayout
import java.awt.Component
import java.awt.Container
internal class NewToolbarBorderLayout : BorderLayout() {
private var lastTarget: Container? = null
override fun layoutContainer(target: Container?) {
synchronized(target!!.treeLock) {
lastTarget = target
val insets = target.insets
val top = insets.top
val bottom = target.height - insets.bottom
var left = insets.left
var right = target.width - insets.right
var c: Component?
if (getLayoutComponent(EAST).also { c = it } != null) {
val d = c!!.preferredSize
var heightDiff = 0
if (target.height > 0 && d.height > 0) {
heightDiff = (target.height - d.height) / 2
}
c!!.setSize(c!!.width, bottom - top)
c!!.setBounds(right - d.width, top + heightDiff, d.width, bottom - top)
right -= d.width + hgap
}
if (getLayoutComponent(CENTER).also { c = it } != null) {
val d = c!!.preferredSize
var heightDiff = 0
if (target.height > 0 && d.height > 0) {
heightDiff = (target.height - d.height) / 2
}
c!!.setBounds(right - c!!.preferredSize.width, top + heightDiff, c!!.preferredSize.width, bottom - top)
right -= d.width + hgap
}
if (getLayoutComponent(WEST).also { c = it } != null) {
val d = c!!.preferredSize
var heightDiff = 0
if (target.height > 0 && d.height > 0) {
heightDiff = (target.height - d.height) / 2
}
if(right < d.width) {
left -= d.width - right
}
c!!.setBounds(left, top + heightDiff, d.width, bottom - top)
left += d.width + hgap
}
}
}
} | apache-2.0 | 7fd18c673b277b5dbaa8cfadf0c42489 | 32.54386 | 120 | 0.589744 | 3.940206 | false | false | false | false |
smmribeiro/intellij-community | plugins/ml-local-models/src/com/intellij/ml/local/models/LocalModelsManager.kt | 11 | 1320 | package com.intellij.ml.local.models
import com.intellij.ml.local.models.api.LocalModel
import com.intellij.lang.Language
import com.intellij.ml.local.models.api.LocalModelFactory
import com.intellij.openapi.project.Project
import org.jetbrains.annotations.ApiStatus
@ApiStatus.Internal
class LocalModelsManager private constructor(private val project: Project) {
companion object {
fun getInstance(project: Project): LocalModelsManager = project.getService(LocalModelsManager::class.java)
}
private val models = mutableMapOf<String, MutableMap<String, LocalModel?>>()
fun getModels(language: Language): List<LocalModel> {
val id2model = models.getOrPut(language.id) { mutableMapOf() }
for (factory in LocalModelFactory.forLanguage(language)) {
if (factory.id !in id2model) {
id2model[factory.id] = factory.modelBuilder(project, language).build()
}
}
return id2model.values.filterNotNull()
}
fun registerModel(language: Language, model: LocalModel) {
models.getOrPut(language.id, { mutableMapOf() })[model.id] = model
}
fun unregisterModel(language: Language, modelId: String) {
models[language.id]?.remove(modelId)
}
inline fun <reified T : LocalModel> getModel(language: Language): T? = getModels(language).filterIsInstance<T>().firstOrNull()
} | apache-2.0 | 01470d78e836cc162e761b7edc3604d5 | 36.742857 | 128 | 0.750758 | 4.02439 | false | false | false | false |
smmribeiro/intellij-community | platform/lang-impl/src/com/intellij/openapi/projectRoots/impl/jdkDownloader/JdkDownloadDialog.kt | 1 | 15350 | // 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.openapi.projectRoots.impl.jdkDownloader
import com.intellij.execution.wsl.WSLDistribution
import com.intellij.execution.wsl.WslDistributionManager
import com.intellij.openapi.fileChooser.FileChooserDescriptorFactory
import com.intellij.openapi.project.Project
import com.intellij.openapi.project.ProjectBundle
import com.intellij.openapi.projectRoots.SdkTypeId
import com.intellij.openapi.ui.*
import com.intellij.openapi.util.NlsSafe
import com.intellij.openapi.util.io.FileUtil
import com.intellij.ui.*
import com.intellij.ui.components.textFieldWithBrowseButton
import com.intellij.ui.layout.*
import com.intellij.util.text.VersionComparatorUtil
import java.awt.Component
import java.awt.event.ItemEvent
import java.nio.file.Path
import java.util.function.Function
import javax.swing.*
import javax.swing.event.DocumentEvent
class JdkDownloaderModel(
val versionGroups: List<JdkVersionItem>,
val defaultItem: JdkItem,
val defaultVersion: JdkVersionItem,
val defaultVersionVendor: JdkVersionVendorItem,
)
class JdkVersionItem(
@NlsSafe
val jdkVersion: String,
/* we should prefer the default selected item from the JDKs.json feed,
* the list below is sorted by vendor, and default item is not necessarily first
*/
val defaultSelectedItem: JdkVersionVendorItem,
val includedItems: List<JdkVersionVendorItem>,
val excludedItems: List<JdkVersionVendorItem>
) {
//we reuse model to keep selected element in-memory!
val model: ComboBoxModel<JdkVersionVendorElement> by lazy {
require(this.includedItems.isNotEmpty()) { "No included items for $jdkVersion" }
require(this.defaultSelectedItem in this.includedItems) { "Default selected item must be in the list of items for $jdkVersion" }
val allItems = when {
this.excludedItems.isNotEmpty() -> this.includedItems + JdkVersionVendorGroupSeparator + this.excludedItems
else -> this.includedItems
}
DefaultComboBoxModel(allItems.toTypedArray()).also {
it.selectedItem = defaultSelectedItem
}
}
}
sealed class JdkVersionVendorElement
object JdkVersionVendorGroupSeparator : JdkVersionVendorElement()
class JdkVersionVendorItem(
val item: JdkItem
) : JdkVersionVendorElement() {
var parent: JdkVersionItem? = null
val selectItem get() = parent?.includedItems?.find { it.item == item } ?: this
val canBeSelected: Boolean get() = parent == null
}
private class JdkVersionVendorCombobox: ComboBox<JdkVersionVendorElement>() {
private val myActionItemSelectedListeners = mutableListOf<(item: JdkVersionVendorItem) -> Unit>()
override fun setSelectedItem(anObject: Any?) {
if (anObject !is JdkVersionVendorItem || selectedItem === anObject) return
if (anObject.canBeSelected) {
super.setSelectedItem(anObject)
} else {
myActionItemSelectedListeners.forEach { it(anObject) }
}
}
// the listener is called for all JdkVersionVendorItem, event for non-selectable ones
fun onActionItemSelected(action: (item: JdkVersionVendorItem) -> Unit) {
myActionItemSelectedListeners += action
}
override fun setModel(aModel: ComboBoxModel<JdkVersionVendorElement>?) {
if (model === aModel) return
super.setModel(aModel)
//change of data model does not file selected item change, which we'd like to receive
selectedItemChanged()
}
init {
isSwingPopup = false
renderer = object: ColoredListCellRenderer<JdkVersionVendorElement>() {
override fun getListCellRendererComponent(list: JList<out JdkVersionVendorElement>?,
value: JdkVersionVendorElement?,
index: Int,
selected: Boolean,
hasFocus: Boolean): Component {
if (value === JdkVersionVendorGroupSeparator ) {
return SeparatorWithText().apply { caption = ProjectBundle.message("dialog.row.jdk.other.versions") }
}
return super.getListCellRendererComponent(list, value, index, selected, hasFocus)
}
override fun customizeCellRenderer(list: JList<out JdkVersionVendorElement>, value: JdkVersionVendorElement?, index: Int, selected: Boolean, hasFocus: Boolean) {
if (value !is JdkVersionVendorItem) {
append("???")
return
}
append(value.item.product.packagePresentationText, SimpleTextAttributes.REGULAR_ATTRIBUTES)
val jdkVersion = value.item.jdkVersion
if (jdkVersion != value.parent?.jdkVersion) {
append(" $jdkVersion", SimpleTextAttributes.GRAYED_ATTRIBUTES, false)
}
value.item.presentableArchIfNeeded?.let { archIfNeeded ->
append(" $archIfNeeded", SimpleTextAttributes.GRAYED_ATTRIBUTES, false)
}
}
}
}
}
private fun List<JdkVersionVendorItem>.sortedForUI() = this.sortedBy { it.item.product.packagePresentationText.toLowerCase() }
fun buildJdkDownloaderModel(allItems: List<JdkItem>): JdkDownloaderModel {
@NlsSafe
fun JdkItem.versionGroupId() = this.presentableMajorVersionString
val groups = allItems
.groupBy { it.versionGroupId() }
.mapValues { (jdkVersion, groupItems) ->
val majorVersion = groupItems.first().jdkMajorVersion
val includedItems = groupItems
.map { JdkVersionVendorItem(item = it) }
val includedProducts = groupItems.map { it.product }.toHashSet()
val excludedItems = allItems
.asSequence()
.filter { it.product !in includedProducts }
.filter { it !in groupItems }
.groupBy { it.product }
.mapValues { (_, jdkItems) ->
val comparator = Comparator.comparing(Function<JdkItem, String> { it.jdkVersion }, VersionComparatorUtil.COMPARATOR)
//first try to find closest newer version
jdkItems
.filter { it.jdkMajorVersion >= majorVersion }
.minWithOrNull(comparator)
// if not, let's try an older version too
?: jdkItems
.filter { it.jdkMajorVersion < majorVersion }
.maxWithOrNull(comparator)
}
//we assume the initial order of feed items contains vendors in the right order
.mapNotNull { it.value }
.map { JdkVersionVendorItem(item = it) }
JdkVersionItem(jdkVersion,
includedItems.firstOrNull() ?: error("Empty group of includeItems for $jdkVersion"),
includedItems.sortedForUI(),
excludedItems.sortedForUI())
}
//assign parent relation
groups.values.forEach { parent -> parent.excludedItems.forEach { it.parent = groups.getValue(it.item.versionGroupId()) } }
val versionItems = groups.values
.sortedWith(Comparator.comparing(Function<JdkVersionItem, String> { it.jdkVersion }, VersionComparatorUtil.COMPARATOR).reversed())
val defaultItem = allItems.firstOrNull { it.isDefaultItem } /*pick the newest default JDK */
?: allItems.firstOrNull() /* pick just the newest JDK is no default was set (aka the JSON is broken) */
?: error("There must be at least one JDK to install") /* totally broken JSON */
val defaultJdkVersionItem = versionItems.firstOrNull { group -> group.includedItems.any { it.item == defaultItem } }
?: error("Default item is not found in the list")
val defaultVersionVendor = defaultJdkVersionItem.includedItems.find { it.item == defaultItem }
?: defaultJdkVersionItem.includedItems.first()
return JdkDownloaderModel(
versionGroups = versionItems,
defaultItem = defaultItem,
defaultVersion = defaultJdkVersionItem,
defaultVersionVendor = defaultVersionVendor,
)
}
private val jdkVersionItemRenderer = object: ColoredListCellRenderer<JdkVersionItem>() {
override fun customizeCellRenderer(list: JList<out JdkVersionItem>,
value: JdkVersionItem?,
index: Int,
selected: Boolean,
hasFocus: Boolean) {
append(value?.jdkVersion ?: return, SimpleTextAttributes.REGULAR_ATTRIBUTES)
}
}
internal class JdkDownloaderMergedModel(
private val mainModel: JdkDownloaderModel,
private val wslModel: JdkDownloaderModel?,
val wslDistributions: List<WSLDistribution>,
val projectWSLDistribution: WSLDistribution?
) {
val hasWsl get() = wslModel != null
fun selectModel(wsl: Boolean): JdkDownloaderModel = when {
wsl && wslModel != null -> wslModel
else -> mainModel
}
}
internal class JdkDownloadDialog(
val project: Project?,
val parentComponent: Component?,
val sdkType: SdkTypeId,
val mergedModel: JdkDownloaderMergedModel,
) : DialogWrapper(project, parentComponent, false, IdeModalityType.PROJECT) {
private val panel: JComponent
private val versionComboBox : ComboBox<JdkVersionItem>
private val vendorComboBox: JdkVersionVendorCombobox
private val installDirTextField: TextFieldWithBrowseButton?
private val installDirCombo: ComboBox<String>?
private val installDirComponent: JComponent
private var currentModel : JdkDownloaderModel? = null
private lateinit var selectedItem: JdkItem
private lateinit var selectedPath: String
init {
title = ProjectBundle.message("dialog.title.download.jdk")
setResizable(false)
versionComboBox = ComboBox()
versionComboBox.renderer = jdkVersionItemRenderer
versionComboBox.isSwingPopup = false
vendorComboBox = JdkVersionVendorCombobox()
if (mergedModel.hasWsl) {
installDirCombo = ComboBox<String>()
installDirCombo.isEditable = true
installDirCombo.initBrowsableEditor(
BrowseFolderRunnable(
ProjectBundle.message("dialog.title.select.path.to.install.jdk"),
null,
project,
FileChooserDescriptorFactory.createSingleFolderDescriptor(),
installDirCombo,
TextComponentAccessor.STRING_COMBOBOX_WHOLE_TEXT
), disposable)
installDirCombo.addActionListener {
onTargetPathChanged(installDirCombo.editor.item as String)
}
installDirTextField = null
installDirComponent = installDirCombo
}
else {
installDirTextField = textFieldWithBrowseButton(
project = project,
browseDialogTitle = ProjectBundle.message("dialog.title.select.path.to.install.jdk"),
fileChooserDescriptor = FileChooserDescriptorFactory.createSingleFolderDescriptor()
)
installDirTextField.onTextChange {
onTargetPathChanged(it)
}
installDirCombo = null
installDirComponent = installDirTextField
}
vendorComboBox.onActionItemSelected(::onVendorActionItemSelected)
vendorComboBox.onSelectionChange(::onVendorSelectionChange)
versionComboBox.onSelectionChange(::onVersionSelectionChange)
panel = panel {
row(ProjectBundle.message("dialog.row.jdk.version")) { versionComboBox.invoke().sizeGroup("combo") }
row(ProjectBundle.message("dialog.row.jdk.vendor")) { vendorComboBox.invoke().sizeGroup("combo").focused() }
row(ProjectBundle.message("dialog.row.jdk.location")) { installDirComponent.invoke() }
}
myOKAction.putValue(Action.NAME, ProjectBundle.message("dialog.button.download.jdk"))
setModel(mergedModel.projectWSLDistribution != null)
init()
}
private fun setModel(forWsl: Boolean) {
val model = mergedModel.selectModel(forWsl)
if (currentModel === model) return
val prevSelectedVersion = versionComboBox.selectedItem as? JdkVersionItem
val prevSelectedJdk = (vendorComboBox.selectedItem as? JdkVersionVendorItem)?.takeIf { it.canBeSelected }
currentModel = model
versionComboBox.model = DefaultComboBoxModel(model.versionGroups.toTypedArray())
val newVersionItem = if (prevSelectedVersion != null) {
model.versionGroups.singleOrNull { it.jdkVersion == prevSelectedVersion.jdkVersion }
} else null
val newVendorItem = if (newVersionItem != null && prevSelectedJdk != null) {
(newVersionItem.includedItems + newVersionItem.excludedItems).singleOrNull {
it.canBeSelected && it.item.suggestedSdkName == prevSelectedJdk.item.suggestedSdkName
}
} else null
onVersionSelectionChange(newVersionItem ?: model.defaultVersion)
onVendorSelectionChange(newVendorItem ?: model.defaultVersionVendor)
}
private fun onTargetPathChanged(path: String) {
@Suppress("NAME_SHADOWING")
val path = FileUtil.expandUserHome(path)
selectedPath = path
setModel(WslDistributionManager.isWslPath(path))
}
private fun onVendorActionItemSelected(it: JdkVersionVendorElement?) {
if (it !is JdkVersionVendorItem) return
val parent = it.parent ?: return
onVersionSelectionChange(parent)
vendorComboBox.selectedItem = it.selectItem
}
private fun onVendorSelectionChange(it: JdkVersionVendorElement?) {
if (it !is JdkVersionVendorItem || !it.canBeSelected) return
vendorComboBox.selectedItem = it.selectItem
val newVersion = it.item
val path = JdkInstaller.getInstance().defaultInstallDir(newVersion, mergedModel.projectWSLDistribution).toString()
val relativePath = FileUtil.getLocationRelativeToUserHome(path)
if (installDirTextField != null) {
installDirTextField.text = relativePath
}
else {
installDirCombo!!.model = CollectionComboBoxModel(getSuggestedInstallDirs(newVersion), relativePath)
}
selectedPath = path
selectedItem = newVersion
}
private fun getSuggestedInstallDirs(newVersion: JdkItem): List<String> {
return (listOf(null) + mergedModel.wslDistributions).mapTo(LinkedHashSet()) {
JdkInstaller.getInstance().defaultInstallDir(newVersion, it).toString()
}.map {
FileUtil.getLocationRelativeToUserHome(it)
}
}
private fun onVersionSelectionChange(it: JdkVersionItem?) {
if (it == null) return
versionComboBox.selectedItem = it
vendorComboBox.model = it.model
}
override fun doValidate(): ValidationInfo? {
super.doValidate()?.let { return it }
val (_, error) = JdkInstaller.getInstance().validateInstallDir(selectedPath)
return error?.let { ValidationInfo(error, installDirComponent) }
}
override fun createCenterPanel() = panel
fun selectJdkAndPath(): Pair<JdkItem, Path>? {
if (!showAndGet()) {
return null
}
val (selectedFile) = JdkInstaller.getInstance().validateInstallDir(selectedPath)
if (selectedFile == null) {
return null
}
JdkDownloaderLogger.logSelected(selectedItem)
return selectedItem to selectedFile
}
private inline fun TextFieldWithBrowseButton.onTextChange(crossinline action: (String) -> Unit) {
textField.document.addDocumentListener(object : DocumentAdapter() {
override fun textChanged(e: DocumentEvent) {
action(text)
}
})
}
private inline fun <reified T> ComboBox<T>.onSelectionChange(crossinline action: (T) -> Unit) {
this.addItemListener { e ->
if (e.stateChange == ItemEvent.SELECTED) action(e.item as T)
}
}
}
| apache-2.0 | 1a785865c184133b033b2432afedc4a1 | 36.807882 | 167 | 0.708274 | 4.765601 | false | false | false | false |
Cypher121/MC-ExtLib | src/main/kotlin/coffee/cypher/mcextlib/extensions/worlds/Worlds.kt | 1 | 827 | package coffee.cypher.mcextlib.extensions.worlds
import coffee.cypher.mcextlib.extensions.blocks.get
import net.minecraft.block.Block
import net.minecraft.tileentity.TileEntity
import net.minecraft.util.math.BlockPos
import net.minecraft.world.IBlockAccess
import net.minecraft.world.World
import net.minecraftforge.fml.relauncher.Side
inline fun <reified T : Block> IBlockAccess.getBlock(pos: BlockPos): T? = getBlockState(pos).get<T>()
inline fun <reified T : TileEntity> IBlockAccess.getTile(pos: BlockPos) = getTileEntity(pos) as? T
inline fun World.side(side: Side, op: () -> Unit) {
if ((side == Side.CLIENT) == isRemote) {
op()
}
}
inline fun World.client(op: () -> Unit) {
if (isRemote) {
op()
}
}
inline fun World.server(op: () -> Unit) {
if (!isRemote) {
op()
}
} | mit | f3f25e882f7de5f06960e98683c06b1a | 25.709677 | 101 | 0.695284 | 3.460251 | false | false | false | false |
saksmt/karaf-runner | src/main/java/run/smt/karafrunner/logic/provider/KarProvider.kt | 1 | 1342 | package run.smt.karafrunner.logic.provider
import run.smt.karafrunner.io.exception.UserErrorException
import run.smt.karafrunner.io.input.choose
import run.smt.karafrunner.io.output.hightlight
import run.smt.karafrunner.io.output.info
import run.smt.karafrunner.logic.util.PathRegistry.pwd
import java.io.File
class KarProvider : DeploymentFileProvider {
override fun provideDeploymentFilesFor(path: File): List<File> {
val preChosen = path.walkTopDown()
.filter { it.isFile }
.filter { it.absolutePath.endsWith(".kar") }
.filter { it.absolutePath.contains("target") }
.asIterable()
;
val show: (File) -> String = when (true) {
pwd.absolutePath == path.absolutePath -> { { it.relativeTo(pwd).path } }
!path.isAbsolute -> { { it.path } }
else -> { { it.absoluteFile.absolutePath } }
}
if (preChosen.count() == 1) {
info("Found ${show(preChosen.first()).hightlight()}")
return preChosen.toList()
} else if (preChosen.count() == 0) {
throw UserErrorException("No ${".kar".hightlight()} files found!")
}
info("Found ${".kar".hightlight()} files:")
return choose("Choose ${".kar".hightlight()} file to use:", preChosen, show)
}
} | mit | 2550270fa2c9fd47e0c428579f1c4fd1 | 40.96875 | 84 | 0.610283 | 4.079027 | false | false | false | false |
npryce/snodge | platform/jvm/src/test/com/natpryce/xmlk/XmlTextRoundTripTest.kt | 1 | 1623 | package com.natpryce.xmlk
import kotlin.test.Test
import org.xml.sax.InputSource
import java.io.StringReader
import java.io.StringWriter
import javax.xml.parsers.DocumentBuilderFactory
import javax.xml.stream.XMLOutputFactory
import javax.xml.transform.TransformerFactory
import javax.xml.transform.dom.DOMSource
import javax.xml.transform.stax.StAXResult
import kotlin.test.assertEquals
class XmlTextRoundTripTest {
@Test
fun `round_trips_XML`() {
ExampleXmlFiles.forEachText { exampleName, originalXml ->
val original = originalXml.toXmlDocument()
val roundTrippedXml = original.toXmlString()
assertEquals(normaliseXmlText(xmlText = originalXml), normaliseXmlText(roundTrippedXml), message=exampleName)
}
}
companion object {
private val outputFactory = XMLOutputFactory.newFactory().apply { setProperty(XMLOutputFactory.IS_REPAIRING_NAMESPACES, true) }
private var documentBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder()
private val transformer = TransformerFactory.newInstance().newTransformer()
fun normaliseXmlText(xmlText: String) =
documentBuilder.parse(InputSource(StringReader(xmlText)))
.let { doc ->
doc.normalize()
val writer = StringWriter()
transformer.transform(
DOMSource(doc),
StAXResult(outputFactory.createXMLStreamWriter(writer)))
writer.toString()
}
}
}
| apache-2.0 | 8fb4e5c3f48fc3cdc3cfed8f87e8d030 | 36.744186 | 135 | 0.661738 | 5.071875 | false | true | false | false |
quran/quran_android | feature/qarilist/src/main/kotlin/com/quran/mobile/feature/qarilist/presenter/QariListPresenter.kt | 2 | 2483 | package com.quran.mobile.feature.qarilist.presenter
import com.quran.data.di.ActivityScope
import com.quran.data.model.SuraAyah
import com.quran.data.model.audio.Qari
import com.quran.labs.androidquran.common.audio.cache.QariDownloadInfoManager
import com.quran.labs.androidquran.common.audio.extension.isRangeDownloaded
import com.quran.labs.androidquran.common.audio.model.QariDownloadInfo
import com.quran.labs.androidquran.common.audio.model.QariItem
import com.quran.mobile.feature.qarilist.R
import com.quran.mobile.feature.qarilist.model.QariUiModel
import javax.inject.Inject
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.map
@ActivityScope
class QariListPresenter @Inject constructor(private val qariDownloadInfoManager: QariDownloadInfoManager) {
fun qariList(start: SuraAyah, end: SuraAyah, qariTranslationLambda: ((Qari) -> QariItem)): Flow<List<QariUiModel>> {
return qariDownloadInfoManager.downloadedQariInfo().map { list ->
list.filter { qariDownloadInfo ->
val qari = qariDownloadInfo.qari
val gappedItem = qariDownloadInfo as? QariDownloadInfo.GappedQariDownloadInfo
qari.isGapless ||
(qari.hasGaplessAlternative && qariDownloadInfo.fullyDownloadedSuras.isEmpty() &&
(gappedItem?.partiallyDownloadedSuras?.isEmpty() ?: false)
)
}
}
.map { unsortedQariList ->
val readyToPlay = unsortedQariList.filter { it.isRangeDownloaded(start, end) }
.toSortedQariItemList(qariTranslationLambda)
val qarisWithDownloads = unsortedQariList.filter { it.fullyDownloadedSuras.isNotEmpty() }
.toSortedQariItemList(qariTranslationLambda)
.filter { it !in readyToPlay }
val gapless = unsortedQariList.filter { it.qari.isGapless }.toSortedQariItemList(qariTranslationLambda)
val gapped = unsortedQariList.filter { !it.qari.isGapless }.toSortedQariItemList(qariTranslationLambda)
readyToPlay.map { QariUiModel(it, R.string.qarilist_ready_to_play) } +
qarisWithDownloads.map { QariUiModel(it, R.string.qarilist_qaris_with_downloads) } +
gapless.map { QariUiModel(it, R.string.qarilist_gapless) } +
gapped.map { QariUiModel(it, R.string.qarilist_gapped) }
}
}
private fun List<QariDownloadInfo>.toSortedQariItemList(lambda: ((Qari) -> QariItem)): List<QariItem> {
return this.map { lambda(it.qari) }
.sortedBy { it.name }
}
}
| gpl-3.0 | 1db9b4846b80f6a38c263408b8b4d3de | 48.66 | 118 | 0.734595 | 4.011309 | false | false | false | false |
seventhroot/elysium | bukkit/rpk-payments-bukkit/src/main/kotlin/com/rpkit/payments/bukkit/command/payment/PaymentInviteCommand.kt | 1 | 4774 | /*
* Copyright 2016 Ross Binden
*
* 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.rpkit.payments.bukkit.command.payment
import com.rpkit.characters.bukkit.character.RPKCharacterProvider
import com.rpkit.payments.bukkit.RPKPaymentsBukkit
import com.rpkit.payments.bukkit.group.RPKPaymentGroupProvider
import com.rpkit.payments.bukkit.notification.RPKPaymentNotificationImpl
import com.rpkit.payments.bukkit.notification.RPKPaymentNotificationProvider
import com.rpkit.players.bukkit.profile.RPKMinecraftProfileProvider
import org.bukkit.command.Command
import org.bukkit.command.CommandExecutor
import org.bukkit.command.CommandSender
import java.text.SimpleDateFormat
import java.util.*
/**
* Payment invite command.
* Invites a character to a payment group.
*/
class PaymentInviteCommand(private val plugin: RPKPaymentsBukkit): CommandExecutor {
val dateFormat = SimpleDateFormat("yyyy-MM-dd HH:mm:ss zzz")
override fun onCommand(sender: CommandSender, command: Command, label: String, args: Array<out String>): Boolean {
if (sender.hasPermission("rpkit.payments.command.payment.invite")) {
if (args.size > 1) {
val paymentGroupProvider = plugin.core.serviceManager.getServiceProvider(RPKPaymentGroupProvider::class)
val paymentGroup = paymentGroupProvider.getPaymentGroup(args.dropLast(1).joinToString(" "))
if (paymentGroup != null) {
val minecraftProfileProvider = plugin.core.serviceManager.getServiceProvider(RPKMinecraftProfileProvider::class)
val characterProvider = plugin.core.serviceManager.getServiceProvider(RPKCharacterProvider::class)
val bukkitPlayer = plugin.server.getOfflinePlayer(args.last())
val minecraftProfile = minecraftProfileProvider.getMinecraftProfile(bukkitPlayer)
if (minecraftProfile != null) {
val character = characterProvider.getActiveCharacter(minecraftProfile)
if (character != null) {
paymentGroup.addInvite(character)
sender.sendMessage(plugin.messages["payment-invite-valid"])
val paymentNotificationProvider = plugin.core.serviceManager.getServiceProvider(RPKPaymentNotificationProvider::class)
val now = System.currentTimeMillis()
val notificationMessage = plugin.messages["payment-notification-invite", mapOf(
Pair("member", character.name),
Pair("group", paymentGroup.name),
Pair("date", dateFormat.format(Date(now)))
)]
if (!minecraftProfile.isOnline) { // If offline
paymentNotificationProvider.addPaymentNotification(
RPKPaymentNotificationImpl(
group = paymentGroup,
to = character,
character = character,
date = now,
text = notificationMessage
)
)
} else { // If online
minecraftProfile.sendMessage(notificationMessage)
}
} else {
sender.sendMessage(plugin.messages["payment-invite-invalid-character"])
}
} else {
sender.sendMessage(plugin.messages["no-minecraft-profile"])
}
} else {
sender.sendMessage(plugin.messages["payment-invite-invalid-group"])
}
} else {
sender.sendMessage(plugin.messages["payment-invite-usage"])
}
} else {
sender.sendMessage(plugin.messages["no-permission-payment-invite"])
}
return true
}
} | apache-2.0 | 91a6a1f297018342f3f7a0200c7eb2a8 | 51.472527 | 146 | 0.589024 | 5.937811 | false | false | false | false |
hazuki0x0/YuzuBrowser | module/search/src/main/java/jp/hazuki/yuzubrowser/search/presentation/search/SearchSuggestAdapter.kt | 1 | 3914 | /*
* Copyright (C) 2017-2019 Hazuki
*
* 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 jp.hazuki.yuzubrowser.search.presentation.search
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.databinding.DataBindingUtil
import androidx.databinding.ViewDataBinding
import androidx.recyclerview.widget.RecyclerView
import jp.hazuki.yuzubrowser.search.R
import jp.hazuki.yuzubrowser.search.databinding.SearchActivitySuggestHistoryBinding
import jp.hazuki.yuzubrowser.search.databinding.SearchActivtySuggestSuggestBinding
import jp.hazuki.yuzubrowser.search.model.SearchSuggestModel
class SearchSuggestAdapter : RecyclerView.Adapter<SearchSuggestAdapter.SuggestHolder>() {
val list: MutableList<SearchSuggestModel> = mutableListOf()
var listener: OnSearchSelectedListener? = null
override fun getItemCount() = list.size
override fun getItemViewType(position: Int): Int {
return when (list[position]) {
is SearchSuggestModel.SuggestModel -> TYPE_SUGGEST
is SearchSuggestModel.HistoryModel -> TYPE_HISTORY
}
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int) =
SuggestHolder(LayoutInflater.from(parent.context).inflate(getLayoutId(viewType), parent, false))
override fun onBindViewHolder(holder: SuggestHolder, position: Int) {
when (val item = list[position]) {
is SearchSuggestModel.SuggestModel -> {
(holder.binding as SearchActivtySuggestSuggestBinding).model = item
holder.binding.textView.setOnClickListener {
listener?.onSelectedQuery(item.suggest)
}
holder.binding.imageButton.setOnClickListener {
listener?.onInputQuery(item.suggest)
}
if (item.suggestHistory) {
holder.binding.textView.setOnLongClickListener {
if (item.suggestHistory) listener?.onDeleteQuery(item.suggest)
true
}
} else {
holder.binding.textView.setOnLongClickListener(null)
}
}
is SearchSuggestModel.HistoryModel -> {
(holder.binding as SearchActivitySuggestHistoryBinding).model = item
holder.binding.background.setOnClickListener {
listener?.onSelectedQuery(item.url)
}
holder.binding.inputImageButton.setOnClickListener {
listener?.onInputQuery(item.url)
}
}
}
}
private fun getLayoutId(type: Int): Int {
return when (type) {
TYPE_SUGGEST -> R.layout.search_activty_suggest_suggest
TYPE_HISTORY -> R.layout.search_activity_suggest_history
else -> throw IllegalArgumentException("Unknown viewType $type")
}
}
inner class SuggestHolder(v: View) : RecyclerView.ViewHolder(v) {
val binding: ViewDataBinding = DataBindingUtil.bind(v)!!
}
companion object {
private const val TYPE_SUGGEST = 0
private const val TYPE_HISTORY = 1
}
interface OnSearchSelectedListener {
fun onSelectedQuery(query: String)
fun onInputQuery(query: String)
fun onDeleteQuery(query: String)
}
}
| apache-2.0 | 08cb33dbb8b9378c3ae2f50f174b00f9 | 37.372549 | 104 | 0.664538 | 5.043814 | false | false | false | false |
kpspemu/kpspemu | src/commonMain/kotlin/com/soywiz/kpspemu/cpu/GlobalCpuState.kt | 1 | 486 | package com.soywiz.kpspemu.cpu
import com.soywiz.korge.util.*
import com.soywiz.kpspemu.cpu.dynarec.*
import com.soywiz.kpspemu.mem.*
class GlobalCpuState(val mem: Memory) {
var insideInterrupt = false
var interruptFlags = -1
val mcache = MethodCache(mem)
@NativeThreadLocal
companion object {
val dummy = GlobalCpuState(MemoryInfo.DUMMY)
}
fun reset() {
mcache.reset()
insideInterrupt = false
interruptFlags = -1
}
}
| mit | ea8e6609ff6fd3f91df609d83b519821 | 21.090909 | 52 | 0.668724 | 3.857143 | false | false | false | false |
EMResearch/EvoMaster | core/src/test/kotlin/org/evomaster/core/database/extract/mysql/ExtractTestBaseMySQL.kt | 1 | 2153 | package org.evomaster.core.database.extract.mysql
import org.evomaster.client.java.controller.api.dto.database.schema.DatabaseType
import org.evomaster.client.java.controller.db.DbCleaner
import org.evomaster.client.java.controller.db.SqlScriptRunner
import org.evomaster.core.KGenericContainer
import org.junit.jupiter.api.AfterAll
import org.junit.jupiter.api.AfterEach
import org.junit.jupiter.api.BeforeAll
import org.junit.jupiter.api.BeforeEach
import java.sql.Connection
import java.sql.DriverManager
abstract class ExtractTestBaseMySQL {
companion object {
@JvmStatic
protected lateinit var connection: Connection
private var sqlSchemaCommand : String? = null
private const val MYSQL_DB_NAME = "test"
private const val MYSQL_PORT = 3306
private const val MYSQL_VERSION = "8.0.27";
private val mysql = KGenericContainer("mysql:$MYSQL_VERSION")
.withEnv(
mutableMapOf(
"MYSQL_ROOT_PASSWORD" to "root",
"MYSQL_DATABASE" to MYSQL_DB_NAME,
"MYSQL_USER" to "test",
"MYSQL_PASSWORD" to "test"
)
)
.withExposedPorts(MYSQL_PORT)
@BeforeAll
@JvmStatic
fun initClass() {
mysql.start()
val host = mysql.containerIpAddress
val port = mysql.getMappedPort(MYSQL_PORT)
val url = "jdbc:mysql://$host:$port/$MYSQL_DB_NAME"
connection = DriverManager.getConnection(url, "test", "test")
}
@AfterAll
@JvmStatic
fun clean(){
sqlSchemaCommand = null
connection.close()
mysql.stop()
}
}
@BeforeEach
fun initTest() {
if(sqlSchemaCommand == null){
sqlSchemaCommand = this::class.java.getResource(getSchemaLocation()).readText()
}
SqlScriptRunner.execScript(connection, sqlSchemaCommand)
}
@AfterEach
fun afterTest(){
DbCleaner.dropDatabaseTables(connection, MYSQL_DB_NAME, null, DatabaseType.MYSQL)
}
abstract fun getSchemaLocation() : String
} | lgpl-3.0 | a125158deebe4bc693c89a2bfa0026f1 | 26.615385 | 91 | 0.63725 | 4.3583 | false | true | false | false |
square/sqldelight | sqldelight-idea-plugin/src/main/kotlin/com/squareup/sqldelight/intellij/SqlDelightParameterInfoHandler.kt | 1 | 4304 | package com.squareup.sqldelight.intellij
import com.alecstrong.sql.psi.core.psi.SqlBindExpr
import com.alecstrong.sql.psi.core.psi.SqlColumnDef
import com.alecstrong.sql.psi.core.psi.SqlInsertStmt
import com.alecstrong.sql.psi.core.psi.SqlInsertStmtValues
import com.alecstrong.sql.psi.core.psi.SqlTypes
import com.alecstrong.sql.psi.core.psi.SqlValuesExpression
import com.intellij.codeInsight.lookup.LookupElement
import com.intellij.lang.parameterInfo.CreateParameterInfoContext
import com.intellij.lang.parameterInfo.ParameterInfoContext
import com.intellij.lang.parameterInfo.ParameterInfoHandlerWithTabActionSupport
import com.intellij.lang.parameterInfo.ParameterInfoUIContext
import com.intellij.lang.parameterInfo.ParameterInfoUtils
import com.intellij.lang.parameterInfo.UpdateParameterInfoContext
import com.intellij.psi.tree.IElementType
import com.intellij.psi.util.PsiTreeUtil
import com.intellij.psi.util.parentOfType
import com.squareup.sqldelight.core.psi.SqlDelightColumnType
class SqlDelightParameterInfoHandler : ParameterInfoHandlerWithTabActionSupport<SqlValuesExpression, List<String>, SqlBindExpr> {
override fun couldShowInLookup(): Boolean {
return false
}
override fun getParametersForLookup(
item: LookupElement,
context: ParameterInfoContext
): Array<Any> {
return emptyArray()
}
override fun findElementForParameterInfo(context: CreateParameterInfoContext): SqlValuesExpression? {
val element = context.file.findElementAt(context.offset)
val valuesExpr = element?.parentOfType<SqlValuesExpression>() ?: return null
if (valuesExpr.parent !is SqlInsertStmtValues) {
return null
}
val columns = element.parentOfType<SqlInsertStmt>()?.columnNameList.orEmpty()
.mapNotNull { it.reference?.resolve()?.parent as? SqlColumnDef }
.mapNotNull { columnDef ->
val columnType = PsiTreeUtil.getChildOfType(columnDef, SqlDelightColumnType::class.java) ?: return@mapNotNull null
val annotations = columnType.annotationList.joinToString(", ") { "@${it.text}" }
val columnName = columnDef.columnName.text
val type = columnType.javaTypeName?.text ?: columnType.typeName.text
buildString {
if (annotations.isNotBlank()) {
append(annotations)
append(" ")
}
append("$columnName: $type")
}
}
context.itemsToShow = arrayOf(columns)
return valuesExpr
}
override fun findElementForUpdatingParameterInfo(context: UpdateParameterInfoContext): SqlValuesExpression? {
return context.file.findElementAt(context.offset)?.parentOfType()
}
override fun showParameterInfo(
element: SqlValuesExpression,
context: CreateParameterInfoContext
) {
context.showHint(element, element.textRange.startOffset, this)
}
override fun updateParameterInfo(
parameterOwner: SqlValuesExpression,
context: UpdateParameterInfoContext
) {
val offset = context.offset
val index = ParameterInfoUtils.getCurrentParameterIndex(parameterOwner.node, offset, SqlTypes.COMMA)
context.setCurrentParameter(index)
}
override fun updateUI(p: List<String>, context: ParameterInfoUIContext) {
val text = p.joinToString(", ")
val index = context.currentParameterIndex
val s = p.getOrNull(index)
var startIndex = -1
var endIndex = -1
if (s != null) {
startIndex = text.indexOf(s)
endIndex = startIndex + s.length
}
context.setupUIComponentPresentation(
text,
startIndex,
endIndex,
!context.isUIComponentEnabled,
false,
false,
context.defaultParameterColor
)
}
override fun getActualParameters(o: SqlValuesExpression): Array<SqlBindExpr> {
return o.exprList
.filterIsInstance<SqlBindExpr>()
.toTypedArray()
}
override fun getActualParameterDelimiterType(): IElementType {
return SqlTypes.COMMA
}
override fun getActualParametersRBraceType(): IElementType = SqlTypes.RP
override fun getArgumentListAllowedParentClasses(): Set<Class<*>> {
return emptySet()
}
override fun getArgListStopSearchClasses(): Set<Class<*>> {
return emptySet()
}
override fun getArgumentListClass(): Class<SqlValuesExpression> {
return SqlValuesExpression::class.java
}
}
| apache-2.0 | 3f6d5aed50844471920a16704ccb85dd | 33.709677 | 129 | 0.747677 | 4.72967 | false | false | false | false |
theostanton/LFGSS | app/src/main/java/com/theostanton/lfgss/listitem/viewholder/HuddleViewHolder.kt | 1 | 1925 | package com.theostanton.lfgss.listitem.viewholder
import android.view.View
import android.widget.TextView
import com.theostanton.lfgss.R
import com.theostanton.lfgss.api.get.Huddle
import com.theostanton.lfgss.global.ago
import com.theostanton.lfgss.huddle.HuddleActivity
import com.theostanton.lfgss.listitem.ListItem
import org.jetbrains.anko.onClick
import org.jetbrains.anko.startActivity
/**
* Created by theostanton on 28/02/16.
*/
class HuddleViewHolder(itemView: View) : ListItemViewHolder(itemView){
val root = itemView.findViewById(R.id.root)
val titleTextView = itemView.findViewById(R.id.title_textView) as TextView
val postedByTextView = itemView.findViewById(R.id.posted_by_textView) as TextView
val postedAgoTextView = itemView.findViewById(R.id.posted_ago_textView) as TextView
val repliedByTextView = itemView.findViewById(R.id.replied_by_textView) as TextView
val repliedAgoTextView = itemView.findViewById(R.id.replied_ago_textView) as TextView
val commentsCountTextView = itemView.findViewById(R.id.comments_count_textView) as TextView
override fun setItem(listItem: ListItem) {
super.setItem(listItem)
if(listItem is Huddle){
titleTextView.text = listItem.title
postedByTextView.text = listItem.meta.createdBy?.profileName
postedAgoTextView.text = listItem.meta.created?.ago()
// repliedAgoTextView.text = listItem.lastComment.created?.ago()
// repliedByTextView.text = listItem.lastComment.createdBy?.profileName
commentsCountTextView.text = listItem.totalComments.toString()
root.onClick {
root.context.startActivity<HuddleActivity>(
"id" to listItem.id,
"totalComments" to listItem.totalComments,
"title" to listItem.title
)
}
}
}
} | mit | a975940e8841ebcb4db4b8665df32173 | 38.306122 | 95 | 0.707013 | 4.335586 | false | false | false | false |
bvic23/storybook-intellij-plugin | src/org/bvic23/intellij/plugin/storybook/main/StorybookPanelController.kt | 1 | 5656 | package org.bvic23.intellij.plugin.storybook.main
import com.intellij.openapi.options.ShowSettingsUtil
import com.intellij.openapi.project.Project
import com.intellij.ui.content.ContentFactory
import org.bvic23.intellij.plugin.storybook.main.State.WAITING_FOR_CONNECTION
import org.bvic23.intellij.plugin.storybook.notifications.NotificationManager
import org.bvic23.intellij.plugin.storybook.notifications.SettingsChangeNotifier
import org.bvic23.intellij.plugin.storybook.settings.SettingsController
import org.bvic23.intellij.plugin.storybook.settings.SettingsManager
import org.bvic23.intellij.plugin.storybook.socket.SocketClient
import java.util.*
import javax.websocket.CloseReason
import kotlin.concurrent.timerTask
import org.bvic23.intellij.plugin.storybook.main.State.*
import org.bvic23.intellij.plugin.storybook.models.*
import java.awt.event.KeyEvent
import java.awt.event.KeyListener
import sun.jvm.hotspot.HelloWorld.e
import javafx.scene.input.KeyCode.getKeyCode
class StorybookPanelController(project: Project) : SettingsChangeNotifier {
private val panel = StorybookPanel()
private val notificationManager = NotificationManager()
private val getStoriesMessage = GeneralMessage<StoriesArg>("getStories")
private val settingsManager = SettingsManager(project.name)
private val socketClient = SocketClient(notificationManager)
private var showFailedMessage = false
private var tree = Tree.empty
private val treeController = TreeController(panel.storyTree, settingsManager, project) { storySelection ->
setCurrentStory(storySelection)
}
private val filterController = FilterController(panel.filterField, settingsManager) {
updateTree()
}
private val stateManager = StateManager(panel.statusField, panel.subStatusField) { state ->
panel.treePanel.isVisible = state == READY
panel.statusPanel.isVisible = state != READY
}
val content
get() = ContentFactory.SERVICE.getInstance().createContent(panel.contentPane, "", false)
init {
setupSettingsAndMessageBus(project)
setupListeners(project)
connect()
}
private fun setupListeners(project: Project) {
panel.settingsButton.addActionListener {
ShowSettingsUtil.getInstance().showSettingsDialog(project, "Storybook")
}
panel.filterField.addKeyListener(object: KeyListener{
override fun keyTyped(e: KeyEvent?) {}
override fun keyPressed(e: KeyEvent?) {}
override fun keyReleased(e: KeyEvent) {
val code = e.keyCode
when (code) {
KeyEvent.VK_DOWN -> {
panel.storyTree.requestFocus()
}
KeyEvent.VK_LEFT -> {}
KeyEvent.VK_RIGHT -> {}
}
}
})
socketClient.onClose { reason ->
if (reason.closeCode == CloseReason.CloseCodes.CLOSED_ABNORMALLY) {
notificationManager.info("lost connection, waiting for restart storybook")
stateManager.state = WAITING_FOR_CONNECTION
connect()
} else {
notificationManager.info("connection got close with reason: $reason")
}
}
socketClient.onError { e ->
notificationManager.error("error: $e")
}
socketClient.on("setStories") { args ->
if (args[0] is StoriesArg) {
tree = (args[0] as StoriesArg).toTree()
updateTree()
}
stateManager.state = READY
Timer().schedule(timerTask {
setCurrentStory(treeController.selectedStory, true)
}, 500)
}
socketClient.on("setCurrentStory") { args ->
if (args[0] is Story) {
setCurrentStory((args[0] as Story))
}
stateManager.state = READY
}
socketClient.on("getCurrentStory") { _ -> setCurrentStory(treeController.selectedStory) }
socketClient.onOpen {
notificationManager.info("connected")
showFailedMessage = false
stateManager.state = WAITING_FOR_STORIES
socketClient.send(getStoriesMessage)
}
}
private fun connect() {
try {
socketClient.connect(settingsManager.host, settingsManager.port)
} catch (e: Throwable) {
if (!showFailedMessage) {
showFailedMessage = true
notificationManager.error("failed to connect, please check your settings or start storybook!")
}
Timer().schedule(timerTask {
connect()
}, 1000)
}
}
private fun setupSettingsAndMessageBus(project: Project) {
SettingsController.messageBus = project.messageBus
SettingsController.settingsManager = settingsManager
project.messageBus.connect().subscribe(SettingsChangeNotifier.SETTINGS_CHANGE_TOPIC, this)
}
override fun onSettingsChange() {
notificationManager.info("settings has changed, try to reconnect...")
connect()
}
private fun setCurrentStory(story: Story, force: Boolean = false) {
if (treeController.selectedStory == story && !force) return
treeController.selectedStory = story
socketClient.send(story.toMessage())
}
private fun updateTree() {
val filterString = filterController.filterString
treeController.model = if (filterString.isEmpty()) tree
else tree.filteredTree(filterString)
}
}
| mit | 9f58775652ca0e9b713bbc97c5602acd | 35.025478 | 110 | 0.652758 | 4.922541 | false | false | false | false |
premnirmal/StockTicker | app/src/main/kotlin/com/github/premnirmal/ticker/widget/WidgetDataProvider.kt | 1 | 3616 | package com.github.premnirmal.ticker.widget
import android.appwidget.AppWidgetManager
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import dagger.hilt.android.qualifiers.ApplicationContext
import javax.inject.Inject
import javax.inject.Singleton
@Singleton
class WidgetDataProvider @Inject constructor(
@ApplicationContext private val context: Context,
private val widgetManager: AppWidgetManager
) {
companion object {
const val INVALID_WIDGET_ID = AppWidgetManager.INVALID_APPWIDGET_ID
}
private val widgets: MutableMap<Int, WidgetData> by lazy {
HashMap()
}
fun getAppWidgetIds(): IntArray =
widgetManager.getAppWidgetIds(ComponentName(context, StockWidget::class.java))
fun widgetDataList(): List<WidgetData> {
val appWidgetIds = getAppWidgetIds().toMutableSet()
if (appWidgetIds.isEmpty()) {
appWidgetIds.add(INVALID_WIDGET_ID)
}
return appWidgetIds.map {
dataForWidgetId(it)
}
}
fun dataForWidgetId(widgetId: Int): WidgetData {
synchronized(widgets) {
return if (widgets.containsKey(widgetId)) {
val widgetData = widgets[widgetId]!!
if (widgetId == AppWidgetManager.INVALID_APPWIDGET_ID && widgetData.getTickers().isEmpty()) {
widgetData.addAllFromStocksProvider()
}
widgetData
} else {
val appWidgetIds = getAppWidgetIds()
// check if size is 1 because the first widget just got added
val position = appWidgetIds.indexOf(widgetId) + 1
val widgetData: WidgetData = if (appWidgetIds.size == 1) {
WidgetData(position, widgetId, true)
} else {
WidgetData(position, widgetId)
}
if (widgetId == AppWidgetManager.INVALID_APPWIDGET_ID && widgetData.getTickers().isEmpty()) {
widgetData.addAllFromStocksProvider()
}
widgets[widgetId] = widgetData
widgetData
}
}
}
fun removeWidget(widgetId: Int): WidgetData? {
return synchronized(widgets) {
val removed = widgets.remove(widgetId)
removed?.let {
if (widgetCount == 0) {
val widget = dataForWidgetId(AppWidgetManager.INVALID_APPWIDGET_ID)
widget.addAllFromStocksProvider()
}
it.onWidgetRemoved()
}
return@synchronized removed
}
}
fun broadcastUpdateWidget(widgetId: Int) {
val intent = Intent(context, StockWidget::class.java)
intent.action = AppWidgetManager.ACTION_APPWIDGET_UPDATE
val ids = arrayOf(widgetId).toIntArray()
intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, ids)
context.sendBroadcast(intent)
}
fun broadcastUpdateAllWidgets() {
val intent = Intent(context, StockWidget::class.java)
intent.action = AppWidgetManager.ACTION_APPWIDGET_UPDATE
val ids = widgetManager.getAppWidgetIds(ComponentName(context, StockWidget::class.java))
intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, ids)
context.sendBroadcast(intent)
}
fun hasWidget(): Boolean = getAppWidgetIds().isNotEmpty()
val widgetCount: Int
get() = getAppWidgetIds().size
fun containsTicker(ticker: String): Boolean = widgets.any { it.value.hasTicker(ticker) }
fun widgetDataWithStock(ticker: String) =
widgets.filter { it.value.hasTicker(ticker) }.values.toList()
fun updateWidgets(tickerList: List<String>) {
if (hasWidget()) {
dataForWidgetId(getAppWidgetIds()[0])
.addTickers(tickerList)
} else {
dataForWidgetId(AppWidgetManager.INVALID_APPWIDGET_ID)
.addTickers(tickerList)
}
}
} | gpl-3.0 | 767e9ab0d9876e64cc7c9a68ae9b312d | 31.00885 | 101 | 0.697179 | 4.41514 | false | false | false | false |
nsnikhil/Notes | app/src/main/java/com/nrs/nsnik/notes/viewmodel/NoteViewModel.kt | 1 | 3680 | /*
* Notes Copyright (C) 2018 Nikhil Soni
* This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
* This is free software, and you are welcome to redistribute it
* under certain conditions; type `show c' for details.
*
* The hypothetical commands `show w' and `show c' should show the appropriate
* parts of the General Public License. Of course, your program's commands
* might be different; for a GUI interface, you would use an "about box".
*
* You should also get your employer (if you work as a programmer) or school,
* if any, to sign a "copyright disclaimer" for the program, if necessary.
* For more information on this, and how to apply and follow the GNU GPL, see
* <http://www.gnu.org/licenses/>.
*
* The GNU General Public License does not permit incorporating your program
* into proprietary programs. If your program is a subroutine library, you
* may consider it more useful to permit linking proprietary applications with
* the library. If this is what you want to do, use the GNU Lesser General
* Public License instead of this License. But first, please read
* <http://www.gnu.org/philosophy/why-not-lgpl.html>.
*/
package com.nrs.nsnik.notes.viewmodel
import android.app.Application
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.LiveData
import com.nrs.nsnik.notes.MyApplication
import com.nrs.nsnik.notes.data.NoteEntity
import com.nrs.nsnik.notes.util.DbUtil
class NoteViewModel(application: Application) : AndroidViewModel(application) {
private val mDbUtil: DbUtil = (application as MyApplication).dbUtil
fun insertNote(vararg noteEntities: NoteEntity) = mDbUtil.insertNote(*noteEntities)
fun updateNote(vararg noteEntities: NoteEntity) = mDbUtil.updateNote(*noteEntities)
fun deleteNote(vararg noteEntities: NoteEntity) = mDbUtil.deleteNote(*noteEntities)
fun deleteNoteByFolderName(folderName: String) = mDbUtil.deleteNoteByFolderName(folderName)
fun getNoteById(id: Int): LiveData<NoteEntity> = mDbUtil.getNoteById(id)
fun getNoteByFolderName(folderName: String): LiveData<List<NoteEntity>> = mDbUtil.getNoteByFolderName(folderName)
fun getNoteByFolderNameNoPinNoLock(folderName: String): LiveData<List<NoteEntity>> = mDbUtil.getNoteByFolderNameNoPinNoLock(folderName)
fun getNoteByFolderNamePinNoLock(folderName: String): LiveData<List<NoteEntity>> = mDbUtil.getNoteByFolderNamePinNoLock(folderName)
fun getNoteByFolderNameNoPinLock(folderName: String): LiveData<List<NoteEntity>> = mDbUtil.getNoteByFolderNameNoPinLock(folderName)
fun getNoteByFolderNamePinLock(folderName: String): LiveData<List<NoteEntity>> = mDbUtil.getNoteByFolderNamePinLock(folderName)
fun getNoteByFolderNameOrdered(folderName: String): LiveData<List<NoteEntity>> = mDbUtil.getNoteByFolderNameOrdered(folderName)
fun getNoteByFolderNameOrderedLock(folderName: String): LiveData<List<NoteEntity>> = mDbUtil.getNoteByFolderNameOrderedLock(folderName)
fun searchNote(query: String): LiveData<List<NoteEntity>> = mDbUtil.searchNote(query)
fun getNoteByPin(isPinned: Int): LiveData<List<NoteEntity>> = mDbUtil.getNotesByPin(isPinned)
fun getNoteByLock(isLocked: Int): LiveData<List<NoteEntity>> = mDbUtil.getNotesByLock(isLocked)
fun getNoteByColor(color: String): LiveData<List<NoteEntity>> = mDbUtil.getNotesByColor(color)
fun changeNotePinStatus(id: Int, pin: Int) = mDbUtil.changeNotePinStatus(id, pin)
fun changeNoteLockStatus(id: Int, lock: Int) = mDbUtil.changeNoteLockStatus(id, lock)
fun changeNoteFolder(id: Int, folderName: String) = mDbUtil.changeNoteFolder(id, folderName)
} | gpl-3.0 | c68931ec98345faaf882af1bac3c8b0c | 47.434211 | 139 | 0.776902 | 3.991323 | false | false | false | false |
premnirmal/StockTicker | app/src/main/kotlin/com/github/premnirmal/ticker/portfolio/search/SearchFragment.kt | 1 | 8920 | package com.github.premnirmal.ticker.portfolio.search
import android.appwidget.AppWidgetManager
import android.content.Intent
import android.graphics.PorterDuff
import android.os.Bundle
import android.text.Editable
import android.text.TextWatcher
import android.view.View
import android.view.ViewGroup
import androidx.appcompat.app.AlertDialog
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import androidx.core.view.isVisible
import androidx.core.view.updateLayoutParams
import androidx.fragment.app.viewModels
import androidx.recyclerview.widget.DividerItemDecoration
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import com.github.premnirmal.ticker.analytics.ClickEvent
import com.github.premnirmal.ticker.base.BaseFragment
import com.github.premnirmal.ticker.components.InAppMessage
import com.github.premnirmal.ticker.home.ChildFragment
import com.github.premnirmal.ticker.isNetworkOnline
import com.github.premnirmal.ticker.network.data.Suggestion
import com.github.premnirmal.ticker.news.QuoteDetailActivity
import com.github.premnirmal.ticker.portfolio.search.SuggestionsAdapter.SuggestionClickListener
import com.github.premnirmal.ticker.showDialog
import com.github.premnirmal.ticker.ui.SpacingDecoration
import com.github.premnirmal.ticker.viewBinding
import com.github.premnirmal.ticker.widget.WidgetDataProvider
import com.github.premnirmal.tickerwidget.R
import com.github.premnirmal.tickerwidget.R.dimen
import com.github.premnirmal.tickerwidget.databinding.FragmentSearchBinding
import com.google.android.material.color.MaterialColors
import dagger.hilt.android.AndroidEntryPoint
@AndroidEntryPoint
class SearchFragment : BaseFragment<FragmentSearchBinding>(), ChildFragment, SuggestionClickListener, TextWatcher {
override val binding: (FragmentSearchBinding) by viewBinding(FragmentSearchBinding::inflate)
companion object {
private const val ARG_WIDGET_ID = AppWidgetManager.EXTRA_APPWIDGET_ID
private const val ARG_SHOW_NAV_ICON = "SHOW_NAV_ICON"
fun newInstance(
widgetId: Int,
showNavIcon: Boolean = false
): SearchFragment {
val fragment = SearchFragment()
val args = Bundle()
args.putInt(ARG_WIDGET_ID, widgetId)
args.putBoolean(ARG_SHOW_NAV_ICON, showNavIcon)
fragment.arguments = args
return fragment
}
}
private val viewModel: SearchViewModel by viewModels()
private lateinit var suggestionsAdapter: SuggestionsAdapter
private lateinit var trendingAdapter: TrendingStocksAdapter
override val simpleName: String = "SearchFragment"
private var selectedWidgetId: Int = -1
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
arguments?.let {
setData(it)
}
}
override fun onViewCreated(
view: View,
savedInstanceState: Bundle?
) {
super.onViewCreated(view, savedInstanceState)
if (arguments?.getBoolean(ARG_SHOW_NAV_ICON) == true) {
binding.toolbar.setNavigationIcon(R.drawable.ic_back)
val tint = MaterialColors.getColor(binding.toolbar, com.google.android.material.R.attr.colorOnSurfaceVariant)
binding.toolbar.navigationIcon?.setTint(tint)
binding.toolbar.navigationIcon?.setTintMode(PorterDuff.Mode.SRC_IN)
binding.toolbar.setNavigationOnClickListener { requireActivity().finish() }
} else {
// Inset toolbar from window top inset
ViewCompat.setOnApplyWindowInsetsListener(view) { _, insets ->
binding.toolbar.updateLayoutParams<ViewGroup.MarginLayoutParams> {
this.topMargin = insets.getInsets(WindowInsetsCompat.Type.systemBars()).top
}
insets
}
}
trendingAdapter = TrendingStocksAdapter { quote ->
analytics.trackClickEvent(ClickEvent("InstrumentClick"))
val intent = Intent(requireContext(), QuoteDetailActivity::class.java)
intent.putExtra(QuoteDetailActivity.TICKER, quote.symbol)
startActivity(intent)
}
binding.trendingRecyclerView?.layoutManager = GridLayoutManager(activity, 3)
binding.trendingRecyclerView?.addItemDecoration(
SpacingDecoration(requireContext().resources.getDimensionPixelSize(dimen.list_spacing_double))
)
binding.trendingRecyclerView?.adapter = trendingAdapter
suggestionsAdapter = SuggestionsAdapter(this)
binding.searchResultsRecyclerView?.layoutManager = LinearLayoutManager(activity)
binding.searchResultsRecyclerView?.addItemDecoration(DividerItemDecoration(activity, DividerItemDecoration.VERTICAL))
binding.searchResultsRecyclerView?.adapter = suggestionsAdapter
binding.searchView.addTextChangedListener(this)
savedInstanceState?.let { selectedWidgetId = it.getInt(ARG_WIDGET_ID, -1) }
if (viewModel.searchResult.value?.wasSuccessful == true) {
suggestionsAdapter.setData(viewModel.searchResult.value!!.data)
}
viewModel.fetchTrendingStocks().observe(viewLifecycleOwner) { quotes ->
if (quotes.isNotEmpty()) trendingAdapter.setData(quotes)
}
viewModel.searchResult.observe(viewLifecycleOwner) {
if (it.wasSuccessful) {
suggestionsAdapter.setData(it.data)
} else {
suggestionsAdapter.setData(
listOf(
Suggestion(
binding.searchView.text?.toString()
.orEmpty()
)
)
)
InAppMessage.showToast(requireActivity(), R.string.error_fetching_suggestions)
}
}
}
override fun onSaveInstanceState(outState: Bundle) {
outState.putInt(ARG_WIDGET_ID, selectedWidgetId)
super.onSaveInstanceState(outState)
}
private fun addTickerToWidget(
ticker: String,
widgetId: Int
) {
if (viewModel.addTickerToWidget(ticker, widgetId)) {
InAppMessage.showToast(requireActivity(), getString(R.string.added_to_list, ticker))
} else {
requireActivity().showDialog(getString(R.string.already_in_portfolio, ticker))
}
}
override fun beforeTextChanged(
s: CharSequence,
start: Int,
count: Int,
after: Int
) {
// Do nothing.
}
override fun onTextChanged(
s: CharSequence,
start: Int,
before: Int,
count: Int
) {
// Do nothing.
}
override fun afterTextChanged(s: Editable) {
val query = s.toString()
.trim { it <= ' ' }
.replace(" ".toRegex(), "")
if (query.isNotEmpty()) {
binding.searchResultsRecyclerView?.isVisible = true
binding.trendingHolder?.isVisible = false
if (requireActivity().isNetworkOnline()) {
viewModel.fetchResults(query)
} else {
InAppMessage.showToast(requireActivity(), R.string.no_network_message)
}
} else {
binding.searchResultsRecyclerView?.isVisible = false
binding.trendingHolder?.isVisible = true
}
}
override fun onSuggestionClick(suggestion: Suggestion): Boolean {
val ticker = suggestion.symbol
if (selectedWidgetId > 0) {
addTickerToWidget(ticker, selectedWidgetId)
return true
}
val intent = Intent(requireContext(), QuoteDetailActivity::class.java)
intent.putExtra(QuoteDetailActivity.TICKER, ticker)
startActivity(intent)
return false
}
override fun onAddRemoveClick(suggestion: Suggestion): Boolean {
val ticker = suggestion.symbol
if (!suggestion.exists) {
if (selectedWidgetId > 0) {
addTickerToWidget(ticker, selectedWidgetId)
return true
} else {
if (viewModel.hasWidget()) {
val widgetDatas = viewModel.getWidgetDatas()
if (widgetDatas.size > 1) {
val widgetNames = widgetDatas.map { it.widgetName() }
.toTypedArray()
AlertDialog.Builder(requireActivity())
.setTitle(R.string.select_widget)
.setItems(widgetNames) { dialog, which ->
val id = widgetDatas[which].widgetId
addTickerToWidget(ticker, id)
suggestion.exists = viewModel.doesSuggestionExist(suggestion)
suggestionsAdapter.notifyDataSetChanged()
dialog.dismiss()
}
.create()
.show()
return false
} else {
addTickerToWidget(ticker, widgetDatas.first().widgetId)
return true
}
} else {
addTickerToWidget(ticker, WidgetDataProvider.INVALID_WIDGET_ID)
return true
}
}
} else {
viewModel.removeStock(ticker, selectedWidgetId)
return true
}
}
// ChildFragment
override fun setData(bundle: Bundle) {
selectedWidgetId = bundle.getInt(ARG_WIDGET_ID, -1)
}
override fun scrollToTop() {
binding.searchResultsRecyclerView?.smoothScrollToPosition(0)
binding.trendingRecyclerView?.smoothScrollToPosition(0)
}
} | gpl-3.0 | 05a370e33f11d4353f0dd3221edf100f | 34.827309 | 121 | 0.713453 | 4.813815 | false | false | false | false |
wayfair/gists | android/anko_blogpost/UserlistAnko/app/src/main/java/com/wayfair/userlistanko/data/UsersListDataModel.kt | 1 | 457 | package com.wayfair.userlistanko.data
data class UsersListDataModel(
val usersList: MutableList<UserDataModel>
) {
data class UserDataModel(
val login: String = "",
val id: Int = 0,
val node_id: String = "",
val avatar_url: String = "",
val url: String = "",
val html_url: String = "",
val type: String = "",
val site_admin: Boolean = false
)
} | mit | c4f30ad96d183e08cdce54c914f1dd8f | 27.625 | 49 | 0.522976 | 4.394231 | false | false | false | false |
MaTriXy/fresco | samples/kotlin/src/main/kotlin/com/facebook/samples/kotlin/ImageAdapter.kt | 2 | 3067 | /*
* This file provided by Facebook is for non-commercial testing and evaluation
* purposes only. Facebook reserves all rights not expressly granted.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* FACEBOOK BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
* ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package com.facebook.samples.kotlin
import android.graphics.drawable.Drawable
import android.net.Uri
import android.support.v7.widget.RecyclerView
import android.view.View
import android.view.ViewGroup
import com.facebook.drawee.backends.pipeline.Fresco
import com.facebook.drawee.drawable.ProgressBarDrawable
import com.facebook.drawee.drawable.ScalingUtils
import com.facebook.drawee.generic.GenericDraweeHierarchyBuilder
import com.facebook.drawee.view.SimpleDraweeView
import com.facebook.imagepipeline.common.ResizeOptions
import com.facebook.imagepipeline.request.ImageRequestBuilder
data class ImageHolder(private val view: View,
private val resizeOptions: ResizeOptions?) : RecyclerView.ViewHolder(view) {
companion object {
private const val DEFAULT_IMAGE_SIZE = 360
}
init {
val width = resizeOptions?.width ?: DEFAULT_IMAGE_SIZE
val height = resizeOptions?.height ?: DEFAULT_IMAGE_SIZE
itemView.layoutParams = ViewGroup.LayoutParams(width, height)
}
fun bind(uri: Uri) {
itemView as? SimpleDraweeView ?: return
itemView.controller = Fresco.newDraweeControllerBuilder()
.setImageRequest(
ImageRequestBuilder.newBuilderWithSource(uri)
.setResizeOptions(resizeOptions)
.build())
.setOldController(itemView.controller)
.setAutoPlayAnimations(true)
.build()
}
}
class ImageAdapter(private val placeholderDrawable: Drawable,
private val failureDrawable: Drawable,
squareDim: Int) : RecyclerView.Adapter<ImageHolder>() {
private var uris = listOf<Uri>()
private val imageResizeOptions = ResizeOptions.forSquareSize(squareDim)
fun setUris(uris: List<Uri>) {
this.uris = uris
notifyDataSetChanged()
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ImageHolder {
val context = parent.context
val hierarchy = GenericDraweeHierarchyBuilder(context.resources)
.setPlaceholderImage(placeholderDrawable)
.setFailureImage(failureDrawable)
.setProgressBarImage(ProgressBarDrawable())
.setActualImageScaleType(ScalingUtils.ScaleType.CENTER_CROP)
.build()
return ImageHolder(SimpleDraweeView(context, hierarchy), imageResizeOptions)
}
override fun onBindViewHolder(holder: ImageHolder, position: Int) {
holder.bind(uris[position])
}
override fun getItemCount() = uris.size
}
| bsd-3-clause | 35ab6fc51397bed37e396a870f35f564 | 37.3375 | 99 | 0.745354 | 4.618976 | false | false | false | false |
ujpv/intellij-rust | src/main/kotlin/org/rust/cargo/runconfig/RustBacktraceFilter.kt | 1 | 5541 | package org.rust.cargo.runconfig
import com.intellij.execution.filters.Filter
import com.intellij.execution.filters.OpenFileHyperlinkInfo
import com.intellij.execution.filters.RegexpFilter
import com.intellij.openapi.editor.colors.EditorColorsManager
import com.intellij.openapi.editor.colors.TextAttributesKey
import com.intellij.openapi.editor.markup.EffectType
import com.intellij.openapi.editor.markup.TextAttributes
import com.intellij.openapi.module.Module
import com.intellij.openapi.project.Project
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.psi.PsiDocumentManager
import org.rust.lang.core.resolve.RustResolveEngine
import java.awt.Color
import java.awt.Font
import java.util.*
import java.util.regex.Pattern
/**
* Adds features to stack backtraces:
* - Wrap function calls into hyperlinks to source code.
* - Turn source code links into hyperlinks.
* - Dims function hash codes to reduce noise.
*/
class RustBacktraceFilter(
project: Project,
cargoProjectDir: VirtualFile,
module: Module
) : Filter {
private val sourceLinkFilter = RegexpFileLinkFilter(project, cargoProjectDir, "^\\s+at ${RegexpFilter.FILE_PATH_MACROS}:${RegexpFilter.LINE_MACROS}$")
private val backtraceItemFilter = RustBacktraceItemFilter(project, module)
override fun applyFilter(line: String, entireLength: Int): Filter.Result? {
return backtraceItemFilter.applyFilter(line, entireLength)
?: sourceLinkFilter.applyFilter(line, entireLength)
}
}
/**
* Adds hyperlinks to function names in backtraces
*/
private class RustBacktraceItemFilter(
val project: Project,
val module: Module
) : Filter {
private val pattern = Pattern.compile("^(\\s*\\d+:\\s+0x[a-f0-9]+ - )(.+)(::h[0-9a-f]+)$")!!
private val docManager = PsiDocumentManager.getInstance(project)
override fun applyFilter(line: String, entireLength: Int): Filter.Result? {
val matcher = pattern.matcher(line)
if (!matcher.find()) return null
val header = matcher.group(1)
val funcName = matcher.group(2)
val funcHash = matcher.group(3)
val normFuncName = funcName.normalize()
val resultItems = ArrayList<Filter.ResultItem>(2)
// Add hyperlink to the function name
val funcStart = entireLength - line.length + header.length
val funcEnd = funcStart + funcName.length
if (SKIP_PREFIXES.none { normFuncName.startsWith(it) }) {
extractFnHyperlink(normFuncName, funcStart, funcEnd)?.let { resultItems.add(it) }
}
// Dim the hashcode
resultItems.add(Filter.ResultItem(funcEnd, funcEnd + funcHash.length, null, DIMMED_TEXT))
return Filter.Result(resultItems)
}
private fun extractFnHyperlink(funcName: String, start: Int, end: Int): Filter.ResultItem? {
val func = RustResolveEngine.resolve(funcName, module) ?: return null
val funcFile = func.element.containingFile
val doc = docManager.getDocument(funcFile) ?: return null
val link = OpenFileHyperlinkInfo(project, funcFile.virtualFile, doc.getLineNumber(func.element.textOffset))
val linkAttr = if (!func.pkg.isWorkspaceMember) GRAYED_LINK else null
return Filter.ResultItem(start, end, link, linkAttr)
}
/**
* Normalizes function path:
* - Removes angle brackets from the element path, including enclosed contents when necessary.
* - Removes closure markers.
* Examples:
* - <core::option::Option<T>>::unwrap -> core::option::Option::unwrap
* - std::panicking::default_hook::{{closure}} -> std::panicking::default_hook
*/
private fun String.normalize(): String {
var str = this
while (str.endsWith("::{{closure}}")) {
str = str.substringBeforeLast("::")
}
while (true) {
val range = str.findAngleBrackets() ?: break
val idx = str.indexOf("::", range.start + 1)
if (idx < 0 || idx > range.endInclusive) {
str = str.removeRange(range)
} else {
str = str.removeRange(IntRange(range.endInclusive, range.endInclusive))
.removeRange(IntRange(range.start, range.start))
}
}
return str
}
/**
* Finds the range of the first matching angle brackets within the string.
*/
private fun String.findAngleBrackets(): IntRange? {
var start = -1
var counter = 0
loop@ for ((index, char) in this.withIndex()) {
when (char) {
'<' -> {
if (start < 0) {
start = index
}
counter += 1
}
'>' -> counter -= 1
else -> continue@loop
}
if (counter == 0) {
val range = IntRange(start, index)
return range
}
}
return null
}
private companion object {
val DIMMED_TEXT = EditorColorsManager.getInstance().globalScheme
.getAttributes(TextAttributesKey.createTextAttributesKey("org.rust.DIMMED_TEXT"))!!
val GRAYED_LINK_COLOR = Color(135, 135, 135)
val GRAYED_LINK = TextAttributes(GRAYED_LINK_COLOR, null, GRAYED_LINK_COLOR, EffectType.LINE_UNDERSCORE, Font.PLAIN)
val SKIP_PREFIXES = arrayOf(
"std::rt::lang_start",
"std::panicking",
"std::sys::backtrace",
"core::panicking")
}
}
| mit | 45803a02b6293c7c57a84041458e896e | 37.748252 | 154 | 0.640498 | 4.318784 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.