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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
BOINC/boinc | android/BOINC/app/src/main/java/edu/berkeley/boinc/rpc/ProjectAttachReplyParser.kt | 2 | 3222 | /*
* This file is part of BOINC.
* http://boinc.berkeley.edu
* Copyright (C) 2021 University of California
*
* BOINC is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License
* as published by the Free Software Foundation,
* either version 3 of the License, or (at your option) any later version.
*
* BOINC is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with BOINC. If not, see <http://www.gnu.org/licenses/>.
*/
package edu.berkeley.boinc.rpc
import android.util.Xml
import edu.berkeley.boinc.utils.Logging
import org.xml.sax.Attributes
import org.xml.sax.SAXException
class ProjectAttachReplyParser : BaseParser() {
lateinit var projectAttachReply: ProjectAttachReply
private set
@Throws(SAXException::class)
override fun startElement(uri: String?, localName: String, qName: String?, attributes: Attributes?) {
super.startElement(uri, localName, qName, attributes)
if (localName.equals(PROJECT_ATTACH_REPLY_TAG, ignoreCase = true)) {
projectAttachReply = ProjectAttachReply()
} else {
// Another element, hopefully primitive and not constructor
// (although unknown constructor does not hurt, because there will be primitive start anyway)
mElementStarted = true
mCurrentElement.setLength(0)
}
}
@Throws(SAXException::class)
override fun endElement(uri: String?, localName: String, qName: String?) {
super.endElement(uri, localName, qName)
try {
if (!localName.equals(PROJECT_ATTACH_REPLY_TAG, ignoreCase = true)) {
// Not the closing tag - we decode possible inner tags
trimEnd()
if (localName.equals(ERROR_NUM_TAG, ignoreCase = true)) {
projectAttachReply.errorNum = mCurrentElement.toInt()
} else if (localName.equals(MESSAGE, ignoreCase = true)) {
projectAttachReply.messages.add(mCurrentElement.toString())
}
}
} catch (e: Exception) {
Logging.logException(Logging.Category.XML, "ProjectAttachReplyParser.endElement error: ", e)
}
mElementStarted = false
}
companion object {
const val PROJECT_ATTACH_REPLY_TAG = "project_attach_reply"
const val ERROR_NUM_TAG = "error_num"
@JvmStatic
fun parse(rpcResult: String?): ProjectAttachReply? {
return try {
val parser = ProjectAttachReplyParser()
Xml.parse(rpcResult, parser)
parser.projectAttachReply
} catch (e: SAXException) {
Logging.logException(Logging.Category.RPC, "ProjectAttachReplyParser: malformed XML ", e)
Logging.logDebug(Logging.Category.XML, "ProjectAttachReplyParser: $rpcResult")
null
}
}
}
}
| lgpl-3.0 | cb7f588e369154c0c877f7ed7d24bfae | 39.275 | 105 | 0.649907 | 4.589744 | false | false | false | false |
xiaojinzi123/Component | ComponentImpl/src/main/java/com/xiaojinzi/component/impl/interceptor/OpenOnceInterceptor.kt | 1 | 2315 | package com.xiaojinzi.component.impl.interceptor
import com.xiaojinzi.component.Component.requiredConfig
import com.xiaojinzi.component.impl.RouterInterceptor
import com.xiaojinzi.component.impl.interceptor.OpenOnceInterceptor
import com.xiaojinzi.component.error.ignore.NavigationFailException
import java.lang.Exception
import java.util.ArrayList
import java.util.HashMap
/**
* 这个拦截器必须在其他任何一个拦截器之前执行
* 从根本上限制同一个界面在一秒钟内只能打开一次,这个拦截器会被框架最先执行
* note: 这个拦截器没有连同 [Uri.getScheme] 一起判断,其实应该一起的,
* 但是现实中应该也不会出现一秒钟 host 和 path 都相同的两次路由了
*
*
* time : 2019/01/23
*
* @author : xiaojinzi
*/
object OpenOnceInterceptor : RouterInterceptor {
private val map: MutableMap<String, Long> = HashMap()
@Throws(Exception::class)
override fun intercept(chain: RouterInterceptor.Chain) {
val uri = chain.request().uri
val hostAndPath = StringBuffer()
.append(uri.host)
// .append("/")
.append(uri.path)
.toString()
// 调试的情况下可能会失效,因为你断点打到这里慢慢的往下走那么可能时间已经过了一秒,就失去了限制的作用
val currentTime = System.currentTimeMillis()
// 如果之前有了并且时间少于一定的时间
if (map.containsKey(hostAndPath) && currentTime - map[hostAndPath]!! < requiredConfig().routeRepeatCheckDuration) {
chain.callback()
.onError(NavigationFailException("same request can't launch twice in a second, target uri is:$uri"))
} else {
map[hostAndPath] = currentTime
// 放过执行
chain.proceed(chain.request())
}
// 清理过期的
cleanOverdue()
}
private fun cleanOverdue() {
val currentTime = System.currentTimeMillis()
val keys: MutableList<String> = ArrayList()
for (key in map.keys) {
if (currentTime - map[key]!! >= requiredConfig().routeRepeatCheckDuration) {
keys.add(key)
}
}
for (key in keys) {
map.remove(key)
}
}
} | apache-2.0 | 1d25f0b3111db4ca30e52a6c722b4bc7 | 30.709677 | 123 | 0.647837 | 3.679775 | false | false | false | false |
groupdocs-comparison/GroupDocs.Comparison-for-Java | Demos/Javalin/src/main/kotlin/com/groupdocs/ui/modules/compare/CompareController.kt | 1 | 5830 | package com.groupdocs.ui.modules.compare
import com.groupdocs.ui.manager.PathManager
import com.groupdocs.ui.model.*
import com.groupdocs.ui.modules.BaseController
import com.groupdocs.ui.usecase.AreFilesSupportedUseCase
import com.groupdocs.ui.usecase.CompareDocumentsUseCase
import com.groupdocs.ui.usecase.RetrieveLocalFilePagesStreamUseCase
import com.groupdocs.ui.util.InternalServerException
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import org.koin.core.component.KoinComponent
import java.io.BufferedInputStream
import java.io.BufferedOutputStream
import java.io.FileInputStream
import java.io.FileOutputStream
import java.nio.file.Files
import java.util.*
import kotlin.io.path.extension
class CompareControllerImpl(
private val checkAreFilesSupported: AreFilesSupportedUseCase,
private val compareDocuments: CompareDocumentsUseCase,
private val retrieveLocalFilePagesStream: RetrieveLocalFilePagesStreamUseCase,
private val pathManager: PathManager
) : BaseController(), CompareController, KoinComponent {
override suspend fun compare(request: CompareRequest): CompareResponse {
val (sourceDocument, targetDocument) = request.guids
val sourceFile = sourceDocument.guid
val targetFile = targetDocument.guid
val sourceFilePath = pathManager.assertPathIsInsideFilesDirectory(sourceFile)
val targetFilePath = pathManager.assertPathIsInsideFilesDirectory(targetFile)
if (!checkAreFilesSupported(sourceFilePath.fileName.toString(), targetFilePath.fileName.toString())) {
throw InternalServerException("File's types are different or are not supported") // TODO: Need another exception type
}
val sourcePassword = sourceDocument.password
val targetPassword = targetDocument.password
val resultExtension = sourceFilePath.fileName.extension
val resultPath = pathManager.createPathForResultFile(
sourceName = sourceFilePath.fileName.toString(),
targetName = targetFilePath.fileName.toString(),
extension = resultExtension
)
if (Files.notExists(resultPath.parent)) {
throw InternalServerException("Result directory does not exist") // TODO: Need another exception type
}
val changeInfos = withContext(Dispatchers.IO) {
BufferedOutputStream(FileOutputStream(resultPath.toFile())).use { outputStream ->
return@withContext compareDocuments(
sourcePath = sourceFilePath,
sourcePassword = sourcePassword,
targetPath = targetFilePath,
targetPassword = targetPassword,
outputStream = outputStream
)
}
}
val pages = withContext(Dispatchers.IO) {
val pages = mutableListOf<ComparePage>()
val previewPageWidth = appConfig.comparison.previewPageWidthOrDefault
val previewPageRatio = appConfig.comparison.previewPageRatioOrDefault
BufferedInputStream(FileInputStream(resultPath.toFile())).use { inputStream ->
retrieveLocalFilePagesStream(
inputStream = inputStream,
previewWidth = previewPageWidth,
previewRatio = previewPageRatio
) { pageNumber, pageInputStream ->
val data = Base64.getEncoder().encodeToString(pageInputStream.readAllBytes())
pages.add(
ComparePage(
number = pageNumber - 1,
width = previewPageWidth,
height = (previewPageWidth * previewPageRatio).toInt(),
data = data
)
)
}
}
pages
}
val changes = changeInfos.map { changeInfo ->
DocumentChange(
id = changeInfo.id,
type = changeInfo.type,
comparisonAction = changeInfo.comparisonAction,
sourceText = changeInfo.sourceText,
targetText = changeInfo.targetText,
text = changeInfo.text ?: "",
componentType = changeInfo.componentType,
box = ChangeBox(
x = changeInfo.box.x,
y = changeInfo.box.y,
width = changeInfo.box.width,
height = changeInfo.box.height
),
authors = changeInfo.authors ?: emptyList(),
pageInfo = PageInfo(
pageNumber = changeInfo.pageInfo.pageNumber,
width = changeInfo.pageInfo.width,
height = changeInfo.pageInfo.height
),
styleChanges = (changeInfo.styleChanges ?: emptyList()).map { styleChangeInfo ->
StyleChange(
propertyName = styleChangeInfo.propertyName,
oldValue = styleChangeInfo.oldValue,
newValue = styleChangeInfo.newValue
)
}
)
}
val filesDirectory = pathManager.filesDirectory
val resultDirectory = pathManager.resultDirectory
val guid = if (resultDirectory.startsWith(filesDirectory)) {
filesDirectory.relativize(resultPath)
} else resultDirectory.relativize(resultPath)
return CompareResponse(
guid = guid.toString(),
changes = changes,
pages = pages,
extension = resultExtension
)
}
}
interface CompareController {
suspend fun compare(request: CompareRequest): CompareResponse
} | mit | 9fabbe6a62505915ae31c009fa96488c | 41.562044 | 129 | 0.624014 | 5.882947 | false | false | false | false |
material-components/material-components-android-examples | Reply/app/src/main/java/com/materialstudies/reply/data/EmailStore.kt | 1 | 10755 | /*
* 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.materialstudies.reply.data
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.Transformations
import com.materialstudies.reply.R
import com.materialstudies.reply.ui.home.Mailbox
/**
* A static data store of [Email]s.
*/
object EmailStore {
private val allEmails = mutableListOf(
Email(
0L,
AccountStore.getContactAccountById(9L),
listOf(AccountStore.getDefaultUserAccount()),
"Package shipped!",
"""
Cucumber Mask Facial has shipped.
Keep an eye out for a package to arrive between this Thursday and next Tuesday. If for any reason you don't receive your package before the end of next week, please reach out to us for details on your shipment.
As always, thank you for shopping with us and we hope you love our specially formulated Cucumber Mask!
""".trimIndent(),
isStarred = true
),
Email(
1L,
AccountStore.getContactAccountById(6L),
listOf(AccountStore.getDefaultUserAccount()),
"Brunch this weekend?",
"""
I'll be in your neighborhood doing errands and was hoping to catch you for a coffee this Saturday. If you don't have anything scheduled, it would be great to see you! It feels like its been forever.
If we do get a chance to get together, remind me to tell you about Kim. She stopped over at the house to say hey to the kids and told me all about her trip to Mexico.
Talk to you soon,
Ali
""".trimIndent()
),
Email(
2L,
AccountStore.getContactAccountById(5L),
listOf(AccountStore.getDefaultUserAccount()),
"Bonjour from Paris",
"Here are some great shots from my trip...",
listOf(
EmailAttachment(R.drawable.paris_1, "Bridge in Paris"),
EmailAttachment(R.drawable.paris_2, "Bridge in Paris at night"),
EmailAttachment(R.drawable.paris_3, "City street in Paris"),
EmailAttachment(R.drawable.paris_4, "Street with bike in Paris")
),
true
),
Email(
3L,
AccountStore.getContactAccountById(8L),
listOf(AccountStore.getDefaultUserAccount()),
"High school reunion?",
"""
Hi friends,
I was at the grocery store on Sunday night.. when I ran into Genie Williams! I almost didn't recognize her afer 20 years!
Anyway, it turns out she is on the organizing committee for the high school reunion this fall. I don't know if you were planning on going or not, but she could definitely use our help in trying to track down lots of missing alums. If you can make it, we're doing a little phone-tree party at her place next Saturday, hoping that if we can find one person, thee more will...
""".trimIndent(),
mailbox = Mailbox.SENT
),
Email(
4L,
AccountStore.getContactAccountById(11L),
listOf(
AccountStore.getDefaultUserAccount(),
AccountStore.getContactAccountById(8L),
AccountStore.getContactAccountById(5L)
),
"Brazil trip",
"""
Thought we might be able to go over some details about our upcoming vacation.
I've been doing a bit of research and have come across a few paces in Northern Brazil that I think we should check out. One, the north has some of the most predictable wind on the planet. I'd love to get out on the ocean and kitesurf for a couple of days if we're going to be anywhere near or around Taiba. I hear it's beautiful there and if you're up for it, I'd love to go. Other than that, I haven't spent too much time looking into places along our road trip route. I'm assuming we can find places to stay and things to do as we drive and find places we think look interesting. But... I know you're more of a planner, so if you have ideas or places in mind, lets jot some ideas down!
Maybe we can jump on the phone later today if you have a second.
""".trimIndent(),
isStarred = true
),
Email(
5L,
AccountStore.getContactAccountById(13L),
listOf(AccountStore.getDefaultUserAccount()),
"Update to Your Itinerary",
""
),
Email(
6L,
AccountStore.getContactAccountById(10L),
listOf(AccountStore.getDefaultUserAccount()),
"Recipe to try",
"Raspberry Pie: We should make this pie recipe tonight! The filling is " +
"very quick to put together.",
mailbox = Mailbox.SENT
),
Email(
7L,
AccountStore.getContactAccountById(9L),
listOf(AccountStore.getDefaultUserAccount()),
"Delivered",
"Your shoes should be waiting for you at home!"
),
Email(
8L,
AccountStore.getContactAccountById(13L),
listOf(AccountStore.getDefaultUserAccount()),
"Your update on Google Play Store is live!",
"""
Your update, 0.1.1, is now live on the Play Store and available for your alpha users to start testing.
Your alpha testers will be automatically notified. If you'd rather send them a link directly, go to your Google Play Console and follow the instructions for obtaining an open alpha testing link.
""".trimIndent(),
mailbox = Mailbox.TRASH
),
Email(
9L,
AccountStore.getContactAccountById(10L),
listOf(AccountStore.getDefaultUserAccount()),
"(No subject)",
"""
Hey,
Wanted to email and see what you thought of
""".trimIndent(),
mailbox = Mailbox.DRAFTS
),
Email(
10L,
AccountStore.getContactAccountById(5L),
listOf(AccountStore.getDefaultUserAccount()),
"Try a free TrailGo account",
"""
Looking for the best hiking trails in your area? TrailGo gets you on the path to the outdoors faster than you can pack a sandwich.
Whether you're an experienced hiker or just looking to get outside for the afternoon, there's a segment that suits you.
""".trimIndent(),
mailbox = Mailbox.TRASH
),
Email(
10L,
AccountStore.getContactAccountById(5L),
listOf(AccountStore.getDefaultUserAccount()),
"Free money",
"""
You've been selected as a winner in our latest raffle! To claim your prize, click on the link.
""".trimIndent(),
mailbox = Mailbox.SPAM
)
)
private val _emails: MutableLiveData<List<Email>> = MutableLiveData()
private val inbox: LiveData<List<Email>>
get() = Transformations.map(_emails) { emails ->
emails.filter { it.mailbox == Mailbox.INBOX }
}
private val starred: LiveData<List<Email>>
get() = Transformations.map(_emails) { emails ->
emails.filter { it.isStarred }
}
private val sent: LiveData<List<Email>>
get() = Transformations.map(_emails) { emails ->
emails.filter { it.mailbox == Mailbox.SENT }
}
private val trash: LiveData<List<Email>>
get() = Transformations.map(_emails) { emails ->
emails.filter { it.mailbox == Mailbox.TRASH }
}
private val spam: LiveData<List<Email>>
get() = Transformations.map(_emails) { emails ->
emails.filter { it.mailbox == Mailbox.SPAM }
}
private val drafts: LiveData<List<Email>>
get() = Transformations.map(_emails) { emails ->
emails.filter { it.mailbox == Mailbox.DRAFTS }
}
init {
_emails.value = allEmails
}
fun getEmails(mailbox: Mailbox): LiveData<List<Email>> {
return when (mailbox) {
Mailbox.INBOX -> inbox
Mailbox.STARRED -> starred
Mailbox.SENT -> sent
Mailbox.TRASH -> trash
Mailbox.SPAM -> spam
Mailbox.DRAFTS -> drafts
}
}
/**
* Get an [Email] with the given [id].
*/
fun get(id: Long): Email? {
return allEmails.firstOrNull { it.id == id }
}
/**
* Create a new, blank [Email].
*/
fun create(): Email {
return Email(
System.nanoTime(), // Unique ID generation.
AccountStore.getDefaultUserAccount()
)
}
/**
* Create a new [Email] that is a reply to the email with the given [replyToId].
*/
fun createReplyTo(replyToId: Long): Email {
val replyTo = get(replyToId) ?: return create()
return Email(
id = System.nanoTime(),
sender = replyTo.recipients.firstOrNull() ?: AccountStore.getDefaultUserAccount(),
recipients = listOf(replyTo.sender) + replyTo.recipients,
subject = replyTo.subject,
isStarred = replyTo.isStarred,
isImportant = replyTo.isImportant
)
}
/**
* Delete the [Email] with the given [id].
*/
fun delete(id: Long) {
update(id) { mailbox = Mailbox.TRASH }
}
/**
* Update the [Email] with the given [id] by applying all mutations from [with].
*/
fun update(id: Long, with: Email.() -> Unit) {
allEmails.find { it.id == id }?.let {
it.with()
_emails.value = allEmails
}
}
/**
* Get a list of [EmailFolder]s by which [Email]s can be categorized.
*/
fun getAllFolders() = listOf(
"Receipts",
"Pine Elementary",
"Taxes",
"Vacation",
"Mortgage",
"Grocery coupons"
)
}
| apache-2.0 | db91ceb51af1cece437d879d5dc03fa0 | 36.736842 | 703 | 0.591539 | 4.698558 | false | false | false | false |
austinv11/OpenPlanner | Core/src/main/kotlin/com/austinv11/planner/core/util/Security.kt | 1 | 2812 | package com.austinv11.planner.core.util
import io.jsonwebtoken.Jwts
import io.jsonwebtoken.SignatureAlgorithm
import java.security.Key
import java.security.MessageDigest
import java.security.SecureRandom
import java.util.*
/**
* This object contains various security-related utilities.
*/
object Security {
val SHA1 = SecureRandom.getInstance("SHA1PRNG")
val SHA256 = MessageDigest.getInstance("SHA-256")
val SHA512 = MessageDigest.getInstance("SHA-512")
const val SALT_LENGTH = 64
/**
* This generates a random salt via [generateSalt] and then hashes the provided string via [hash].
* @return A pair, firstValue=salt, secondValue=hash.
*/
fun hash(password: String): Pair<ByteArray, ByteArray> {
val salt = generateSalt()
return salt to hash(password, salt)
}
/**
* This hashes a password with a given salt by first hashing the password with the SHA-256 algorithm, it then
* combines the initial hash with the salt and hashes that product with the SHA-512 algorithm.
* @return The salted hash.
*/
fun hash(password: String, salt: ByteArray): ByteArray {
val initialHash = SHA256.digest(password.toByteArray())
val finalHash = SHA512.digest(initialHash + salt)
return finalHash
}
/**
* This performs a hash operation on the provided string and salt in order to compare it to the supposed value of
* the salted hash.
* @return True if the hashes match, false if otherwise.
*/
fun verify(hash: ByteArray, password: String, salt: ByteArray): Boolean {
return Arrays.equals(hash(password, salt), hash)
}
/**
* This generates a securely random salt that is [SALT_LENGTH] bytes long using the SHA-1 algorithm.
* @return The random salt.
*/
fun generateSalt(): ByteArray {
val array = ByteArray(SALT_LENGTH)
SHA1.nextBytes(array)
return array
}
/**
* This generates a SHA-512 signed JWS string.
* @param key The key to sign with (must be SHA-512 encoded).
* @param claims The claims designated as the payload.
* @return The JWS string.
*/
fun generateJWS(key: Key, claims: Map<String, Any?>): String {
return Jwts.builder()
.signWith(SignatureAlgorithm.HS512, key)
.setClaims(claims)
.compact()
}
/**
* This attempts to parse a signed JWS string.
* @param key The key used to sign the string.
* @param jws The JWS string to parse.
* @return The claims (body) of the jws string.
*/
fun parseJWS(key: Key, jws: String): Map<String, Any?> {
return Jwts.parser()
.setSigningKey(key)
.parseClaimsJws(jws)
.body
}
}
| gpl-3.0 | 9f7175b7f98562ccaac10504f8bb5416 | 32.47619 | 118 | 0.643314 | 4.165926 | false | false | false | false |
vanita5/twittnuker | twittnuker/src/main/kotlin/de/vanita5/twittnuker/loader/users/UserFriendsLoader.kt | 1 | 4903 | /*
* Twittnuker - Twitter client for Android
*
* Copyright (C) 2013-2017 vanita5 <[email protected]>
*
* This program incorporates a modified version of Twidere.
* Copyright (C) 2012-2017 Mariotaku Lee <[email protected]>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package de.vanita5.twittnuker.loader.users
import android.content.Context
import de.vanita5.microblog.library.MicroBlog
import de.vanita5.microblog.library.MicroBlogException
import de.vanita5.microblog.library.mastodon.Mastodon
import de.vanita5.microblog.library.twitter.model.Paging
import de.vanita5.twittnuker.annotation.AccountType
import de.vanita5.twittnuker.extension.model.api.mastodon.mapToPaginated
import de.vanita5.twittnuker.extension.model.api.mastodon.toParcelable
import de.vanita5.twittnuker.extension.model.api.microblog.mapToPaginated
import de.vanita5.twittnuker.extension.model.api.toParcelable
import de.vanita5.twittnuker.extension.model.newMicroBlogInstance
import de.vanita5.twittnuker.model.AccountDetails
import de.vanita5.twittnuker.model.ParcelableUser
import de.vanita5.twittnuker.model.UserKey
import de.vanita5.twittnuker.model.pagination.PaginatedList
class UserFriendsLoader(
context: Context,
accountKey: UserKey?,
userKey: UserKey?,
screenName: String?,
data: List<ParcelableUser>?,
fromUser: Boolean
) : UserRelatedUsersLoader(context, accountKey, userKey, screenName, data, fromUser) {
@Throws(MicroBlogException::class)
override fun getUsersByKey(details: AccountDetails, paging: Paging, userKey: UserKey): PaginatedList<ParcelableUser> {
when (details.type) {
AccountType.MASTODON -> {
val mastodon = details.newMicroBlogInstance(context, Mastodon::class.java)
return mastodon.getFollowing(userKey.id, paging).mapToPaginated {
it.toParcelable(details)
}
}
AccountType.STATUSNET -> {
val microBlog = details.newMicroBlogInstance(context, MicroBlog::class.java)
return microBlog.getStatusesFriendsList(userKey.id, paging).mapToPaginated {
it.toParcelable(details, profileImageSize = profileImageSize)
}
}
AccountType.FANFOU -> {
val microBlog = details.newMicroBlogInstance(context, MicroBlog::class.java)
return microBlog.getUsersFriends(userKey.id, paging).mapToPaginated(pagination) {
it.toParcelable(details, profileImageSize = profileImageSize)
}
}
else -> {
val microBlog = details.newMicroBlogInstance(context, MicroBlog::class.java)
return microBlog.getFriendsList(userKey.id, paging).mapToPaginated {
it.toParcelable(details, profileImageSize = profileImageSize)
}
}
}
}
@Throws(MicroBlogException::class)
override fun getUsersByScreenName(details: AccountDetails, paging: Paging, screenName: String): PaginatedList<ParcelableUser> {
when (details.type) {
AccountType.MASTODON -> {
throw MicroBlogException("Only ID supported")
}
AccountType.STATUSNET -> {
val microBlog = details.newMicroBlogInstance(context, MicroBlog::class.java)
return microBlog.getStatusesFriendsListByScreenName(screenName, paging).mapToPaginated {
it.toParcelable(details, profileImageSize = profileImageSize)
}
}
AccountType.FANFOU -> {
val microBlog = details.newMicroBlogInstance(context, MicroBlog::class.java)
return microBlog.getUsersFriends(screenName, paging).mapToPaginated(pagination) {
it.toParcelable(details, profileImageSize = profileImageSize)
}
}
else -> {
val microBlog = details.newMicroBlogInstance(context, MicroBlog::class.java)
return microBlog.getFriendsListByScreenName(screenName, paging).mapToPaginated {
it.toParcelable(details, profileImageSize = profileImageSize)
}
}
}
}
} | gpl-3.0 | 18590e174d9cc8d351ec9b09910c9be1 | 44.831776 | 131 | 0.677544 | 5.065083 | false | false | false | false |
stripe/stripe-android | paymentsheet/src/test/java/com/stripe/android/paymentsheet/paymentdatacollection/polling/PollingTestUtils.kt | 1 | 1346 | package com.stripe.android.paymentsheet.paymentdatacollection.polling
import com.stripe.android.model.StripeIntent
import com.stripe.android.polling.IntentStatusPoller
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
internal class FakeIntentStatusPoller : IntentStatusPoller {
private val _state = MutableStateFlow<StripeIntent.Status?>(null)
override val state: StateFlow<StripeIntent.Status?> = _state
private val forcePollChannel = Channel<StripeIntent.Status?>(capacity = 1)
var isActive: Boolean = false
private set
override fun startPolling(scope: CoroutineScope) {
isActive = true
}
override suspend fun forcePoll(): StripeIntent.Status? {
return forcePollChannel.receive()
}
override fun stopPolling() {
isActive = false
}
fun enqueueForcePollResult(status: StripeIntent.Status?) {
forcePollChannel.trySend(status)
}
fun emitNextPollResult(status: StripeIntent.Status?) {
_state.value = status
}
}
internal class FakeTimeProvider(
private val timeInMillis: Long = System.currentTimeMillis(),
) : TimeProvider {
override fun currentTimeInMillis(): Long {
return timeInMillis
}
}
| mit | 9d3fafbd0e3734ada40be36f27c77b32 | 27.638298 | 78 | 0.738484 | 4.706294 | false | false | false | false |
mwudka/aftflight-alexa | src/main/kotlin/com/mwudka/aftflight/core/generateWeatherBriefing.kt | 1 | 5837 | package com.mwudka.aftflight.core
import org.joda.time.DateTime
import org.joda.time.DateTimeZone
import org.joda.time.Hours
import org.joda.time.Minutes
import java.text.DecimalFormat
internal fun generateWindClause(weatherInfo: WeatherInfo): String {
var ret = "Wind"
if (weatherInfo.wind_speed_kt == 0 && weatherInfo.wind_gust_kt == 0) {
return "$ret calm"
}
if (weatherInfo.wind_dir_degrees == 0) {
ret = "$ret variable"
} else {
ret = "$ret from <say-as interpret-as=\"digits\">${weatherInfo.wind_dir_degrees}</say-as>"
}
if (weatherInfo.wind_speed_kt > 0) {
ret = "$ret @ ${weatherInfo.wind_speed_kt}"
}
if (weatherInfo.wind_gust_kt > 0) {
ret = "$ret gusting ${weatherInfo.wind_gust_kt}"
}
ret = "$ret knots"
return ret
}
internal fun generateSkyCoverClause(skyConditions: List<SkyCondition>): String {
if (skyConditions.isEmpty()) {
return "Sky condition unknown"
}
if (skyConditions.any { it.skyCover == SkyCover.CLR || it.skyCover == SkyCover.SKC }) {
return "Sky clear"
}
if (skyConditions.any { it.skyCover == SkyCover.CAVOK }) {
return "No clouds below 5,000 feet"
}
if (skyConditions.any { it.skyCover == SkyCover.NSC }) {
return "No significant clouds"
}
return "Sky " + skyConditions
.sortedBy { it.cloudBaseFTAGL }
.map {
val skyCoverType = when (it.skyCover) {
SkyCover.FEW -> "few"
SkyCover.SCT -> "scattered"
SkyCover.BKN -> "broken"
SkyCover.OVC -> "overcast"
SkyCover.OVX -> "foggy"
SkyCover.SKC, SkyCover.CLR, SkyCover.CAVOK, SkyCover.NSC -> throw IllegalStateException("Should return early if any sky conditions are clear")
}
if (it.cloudBaseFTAGL != null && it.cloudBaseFTAGL > 0) {
skyCoverType + " " + DecimalFormat("#,###").format(it.cloudBaseFTAGL)
} else {
skyCoverType
}
}.joinToString("; ")
}
internal fun generateVerticalVisibilityClause(weatherInfo: WeatherInfo): String {
if (weatherInfo.verticalVisibilityFt == null) {
return ""
} else {
val formattedVerticalVisibility = DecimalFormat("#,###").format(weatherInfo.verticalVisibilityFt)
return "Vertical visibility $formattedVerticalVisibility feet"
}
}
internal fun generateVisibilityClause(weatherInfo: WeatherInfo): String {
val ret = "Visibility"
if (weatherInfo.visibility_statute_mi <= 0) {
return "$ret unknown"
} else {
val formattedVisibility = DecimalFormat("#.#").format(weatherInfo.visibility_statute_mi)
return "$ret $formattedVisibility miles"
}
}
internal fun normalizeStationName(stationName: String): String {
return stationName.replace('/', ' ')
}
internal fun generateMETAROverviewClause(currentTime: DateTime, metarDatabaseEntry: METARDatabaseEntry): String {
val observationAge = Minutes.minutesBetween(metarDatabaseEntry.metar.observationTime, currentTime)
val observationAgeMinutes: Int
if (observationAge.minutes < 0) {
observationAgeMinutes = 0
} else {
observationAgeMinutes = observationAge.minutes
}
val minutesString = if (observationAgeMinutes == 1) {
"minute"
} else {
"minutes"
}
val normalizedStationName = normalizeStationName(metarDatabaseEntry.station.site)
return "Weather at $normalizedStationName from $observationAgeMinutes $minutesString ago"
}
fun generateMETARWeatherBriefing(currentTime: DateTime, metarDatabaseEntry: METARDatabaseEntry): String {
val metar = metarDatabaseEntry.metar
val response: String
if (Hours.hoursBetween(metar.observationTime, currentTime).hours > 3) {
response = "No current weather available for ${normalizeStationName(metarDatabaseEntry.station.site)}."
} else {
response = listOf(
generateMETAROverviewClause(currentTime, metarDatabaseEntry),
generateWindClause(metar),
generateVisibilityClause(metar),
generateSkyCoverClause(metar.sky_condition.orEmpty()),
generateVerticalVisibilityClause(metar)
).filter(String::isNotBlank).joinToString(". ")
}
return "<speak>$response</speak>"
}
fun generateTAFOverviewClause(tafDatabaseEntry: TAFDatabaseEntry): String {
val normalizedStationName = normalizeStationName(tafDatabaseEntry.station.site)
return "Forecast for $normalizedStationName; eastern timezone"
}
fun generateTAFWeatherBriefing(tafDatabaseEntry: TAFDatabaseEntry): String {
val response = listOf(
generateTAFOverviewClause(tafDatabaseEntry),
*tafDatabaseEntry.taf.forecasts.orEmpty().map(::generateTAFForecastClause).toTypedArray()
).joinToString(". ")
return "<speak>$response</speak>"
}
fun generateTAFForecastTimeRangeClause(forecast: Forecast): String {
val localFrom = forecast.timeFrom.withZone(DateTimeZone.forID("EST"))
val localTo = forecast.timeTo.withZone(DateTimeZone.forID("EST"))
val formatString = "'<say-as interpret-as=\"date\">????'MMdd'</say-as> 'h:mma"
return "From ${localFrom.toString(formatString)} to ${localTo.toString(formatString)}"
}
fun generateTAFForecastClause(forecast: Forecast): String {
return listOf(
generateTAFForecastTimeRangeClause(forecast),
generateWindClause(forecast),
generateVisibilityClause(forecast),
generateSkyCoverClause(forecast.sky_condition.orEmpty()),
generateVerticalVisibilityClause(forecast)
).filter(String::isNotBlank).joinToString(". ")
}
| mit | 3f356740db28a5cb67b9489d43d1896a | 34.375758 | 162 | 0.660785 | 4.128006 | false | false | false | false |
pyamsoft/padlock | padlock-service/src/main/java/com/pyamsoft/padlock/service/device/UsageEventProviderImpl.kt | 1 | 3928 | /*
* Copyright 2019 Peter Kenji Yamanaka
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.pyamsoft.padlock.service.device
import android.app.AppOpsManager
import android.app.AppOpsManager.OnOpChangedListener
import android.app.usage.UsageEvents
import android.app.usage.UsageStatsManager
import android.content.Context
import com.pyamsoft.padlock.api.preferences.PreferenceWatcher
import com.pyamsoft.padlock.api.service.LockServiceInteractor.ForegroundEvent
import com.pyamsoft.padlock.api.service.UsageEventProvider
import timber.log.Timber
import java.util.concurrent.atomic.AtomicBoolean
import javax.inject.Inject
import javax.inject.Singleton
import kotlin.LazyThreadSafetyMode.NONE
@Singleton
internal class UsageEventProviderImpl @Inject internal constructor(
private val context: Context
) : UsageEventProvider {
private val usage by lazy(NONE) {
context.getSystemService(Context.USAGE_STATS_SERVICE) as UsageStatsManager
}
private val internalWatchers = LinkedHashSet<(Boolean) -> Unit>()
private val watcher = AppUsagePreferenceWatcher(context) {
for (watcher in internalWatchers) {
watcher(it)
}
}
override fun queryEvents(
begin: Long,
end: Long
): UsageEventProvider.EventQueryResult = EventQueryResultImpl(usage.queryEvents(begin, end))
override fun watchPermission(func: (Boolean) -> Unit): PreferenceWatcher {
internalWatchers.add(func)
watcher.watch()
return object : PreferenceWatcher {
override fun stopWatching() {
Timber.d("Stop watching usage permission")
internalWatchers.remove(func)
}
}
}
private class AppUsagePreferenceWatcher internal constructor(
private val context: Context,
func: (Boolean) -> Unit
) : PreferenceWatcher {
private var isWatching = AtomicBoolean(false)
private val appOps = context.getSystemService(Context.APP_OPS_SERVICE) as AppOpsManager
private val callback = OnOpChangedListener { op, packageName ->
if (op == AppOpsManager.OPSTR_GET_USAGE_STATS) {
if (packageName == context.packageName) {
func(UsagePermissionChecker.hasPermission(context))
}
}
}
fun watch() {
if (isWatching.compareAndSet(false, true)) {
appOps.startWatchingMode(AppOpsManager.OPSTR_GET_USAGE_STATS, context.packageName, callback)
}
}
override fun stopWatching() {
// We register this onto the singleton instance because stopWatchingMode does not seem
// to actually unregister the callback, thus leading to memory leaks
appOps.stopWatchingMode(callback)
}
}
private data class EventQueryResultImpl(private val events: UsageEvents) : UsageEventProvider.EventQueryResult {
private val event: UsageEvents.Event? by lazy {
if (events.hasNextEvent()) {
val event = UsageEvents.Event()
events.getNextEvent(event)
while (events.hasNextEvent()) {
events.getNextEvent(event)
}
return@lazy event
} else {
return@lazy null
}
}
override fun createForegroundEvent(func: (String, String) -> ForegroundEvent): ForegroundEvent {
if ((event?.eventType ?: UsageEvents.Event.NONE) == UsageEvents.Event.MOVE_TO_FOREGROUND) {
return func(event?.packageName.orEmpty(), event?.className.orEmpty())
} else {
return func("", "")
}
}
}
}
| apache-2.0 | d50e9c7eea9493958b2d8a2b2f642838 | 30.677419 | 114 | 0.71945 | 4.463636 | false | false | false | false |
exponent/exponent | android/versioned-abis/expoview-abi44_0_0/src/main/java/abi44_0_0/expo/modules/imagepicker/exporters/RawImageExporter.kt | 2 | 1915 | package abi44_0_0.expo.modules.imagepicker.exporters
import android.content.ContentResolver
import android.graphics.BitmapFactory
import android.net.Uri
import abi44_0_0.expo.modules.imagepicker.exporters.ImageExporter.Listener
import org.apache.commons.io.IOUtils
import java.io.ByteArrayOutputStream
import java.io.File
import java.io.FileOutputStream
import java.io.IOException
class RawImageExporter(
private val contentResolver: ContentResolver,
private val mBase64: Boolean
) : ImageExporter {
override fun export(source: Uri, output: File, exporterListener: Listener) {
val base64Stream = if (mBase64) ByteArrayOutputStream() else null
base64Stream.use {
try {
copyImage(source, output, base64Stream)
val options = BitmapFactory.Options().apply { inJustDecodeBounds = true }
BitmapFactory.decodeFile(output.absolutePath, options)
exporterListener.onResult(base64Stream, options.outWidth, options.outHeight)
} catch (e: IOException) {
exporterListener.onFailure(e)
}
}
}
/**
* Copy the image file from `originalUri` to `file`, optionally saving it in
* `out` if base64 is requested.
*
* @param originalUri uri to the file to copy the data from
* @param file file to save the image to
* @param out if not null, the stream to save the image to
*/
@Throws(IOException::class)
private fun copyImage(originalUri: Uri, file: File, out: ByteArrayOutputStream?) {
contentResolver.openInputStream(originalUri)?.use { input ->
if (out != null) {
IOUtils.copy(input, out)
}
if (originalUri.compareTo(Uri.fromFile(file)) != 0) { // do not copy file over the same file
FileOutputStream(file).use { fos ->
if (out != null) {
fos.write(out.toByteArray())
} else {
IOUtils.copy(input, fos)
}
}
}
}
}
}
| bsd-3-clause | be791cbbb51449630c536f24485e8e94 | 31.457627 | 98 | 0.684595 | 4.145022 | false | false | false | false |
Gh0u1L5/WechatMagician | app/src/main/kotlin/com/gh0u1l5/wechatmagician/frontend/wechat/ConversationAdapter.kt | 1 | 4515 | package com.gh0u1l5.wechatmagician.frontend.wechat
import android.content.Context
import android.graphics.Color
import android.view.Gravity
import android.view.View
import android.view.ViewGroup
import android.widget.ArrayAdapter
import android.widget.LinearLayout
import android.widget.TextView
import com.gh0u1l5.wechatmagician.R
import com.gh0u1l5.wechatmagician.backend.plugins.ChatroomHider
import com.gh0u1l5.wechatmagician.backend.storage.Strings
import com.gh0u1l5.wechatmagician.backend.storage.database.MainDatabase
import com.gh0u1l5.wechatmagician.backend.storage.list.ChatroomHideList
import com.gh0u1l5.wechatmagician.util.ViewUtil.dp2px
import de.robv.android.xposed.XposedHelpers
class ConversationAdapter(context: Context, val conversations: MutableList<ConversationAdapter.Conversation> = getConversationList()) :
ArrayAdapter<ConversationAdapter.Conversation>(context, 0, conversations) {
data class Conversation(
val username: String,
val nickname: String,
val digest: String,
val digestUser: String,
val atCount: Int,
val unreadCount: Int
)
companion object {
fun getConversationList(): MutableList<Conversation> {
return ChatroomHideList.toList().mapNotNull {
val contact = MainDatabase.getContactByUsername(username = it)
val conversation = MainDatabase.getConversationByUsername(username = it)
if (contact != null && conversation != null) {
ConversationAdapter.Conversation(
username = contact.username,
nickname = contact.nickname,
digest = conversation.digest,
digestUser = conversation.digestUser,
atCount = conversation.atCount,
unreadCount = conversation.unreadCount
)
} else null
}.toMutableList()
}
}
override fun getView(position: Int, convertView: View?, parent: ViewGroup?): View {
var view = convertView as LinearLayout?
if (view == null) {
val containerLayout = XposedHelpers.callMethod(parent, "generateDefaultLayoutParams")
XposedHelpers.setIntField(containerLayout, "height", context.dp2px(60))
view = LinearLayout(context).apply {
orientation = LinearLayout.VERTICAL
if (containerLayout is ViewGroup.LayoutParams) {
layoutParams = containerLayout
}
setBackgroundColor(Color.WHITE)
val textLayout = LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.MATCH_PARENT)
textLayout.leftMargin = context.dp2px(15)
textLayout.rightMargin = context.dp2px(15)
textLayout.topMargin = context.dp2px(3)
textLayout.weight = 1F
// Add nickname row
addView(TextView(context).apply {
textSize = 16F
gravity = Gravity.CENTER_VERTICAL
setSingleLine()
setTextColor(Color.BLACK)
}, textLayout)
// Add digest row
addView(TextView(context).apply {
textSize = 12F
gravity = Gravity.TOP
setSingleLine()
setTextColor(Color.GRAY)
}, textLayout)
}
}
return view.apply {
val conversation = getItem(position)
val nickname = getChildAt(0) as TextView?
val digest = getChildAt(1) as TextView?
if (conversation.nickname.isEmpty()) {
nickname?.text = Strings.getString(R.string.label_unnamed)
} else {
nickname?.text = conversation.nickname
}
digest?.text = conversation.digest
.format(conversation.digestUser)
.replace("\n", "")
setOnClickListener { view ->
ChatroomHider.onChatroomHiderConversationClick(view, conversation.username)
}
setOnLongClickListener { view ->
ChatroomHider.onChatroomHiderConversationLongClick(view, this@ConversationAdapter, conversation.username)
}
}
}
} | gpl-3.0 | 82c390f79d05b8cf520a30c71cef8e4e | 42.009524 | 138 | 0.600886 | 5.262238 | false | false | false | false |
ioc1778/incubator | incubator-etc/src/main/java/com/riaektiv/guice/GatewayMain.kt | 2 | 988 | package com.riaektiv.guice
import com.netflix.governator.guice.LifecycleInjector
import com.netflix.governator.lifecycle.LifecycleManager
import org.slf4j.LoggerFactory
/**
* Coding With Passion Since 1991
* Created: 4/30/2017, 8:19 PM Eastern Time
* @author Sergey Chuykov
*/
class GatewayMain {
val l = LoggerFactory.getLogger(javaClass)
fun execute() {
val injector = LifecycleInjector.builder().withModules(
GatewayModule()
).build().createInjector()
val dao = injector.getInstance(QuoteEventDao::class.java)
l.info("{}", dao)
val handler = injector.getInstance(QuoteEventHandler::class.java)
l.info("{}", handler)
val manager = injector.getInstance(LifecycleManager::class.java)
manager.start()
Thread.sleep(1000)
manager.close()
}
companion object {
@JvmStatic fun main(args: Array<String>) {
GatewayMain().execute()
}
}
} | bsd-3-clause | e0c16f2aaf59afd62706ec5a56b3c29f | 22.547619 | 73 | 0.649798 | 4.31441 | false | false | false | false |
TeamWizardry/LibrarianLib | modules/courier/src/main/kotlin/com/teamwizardry/librarianlib/courier/CourierBuffer.kt | 1 | 1456 | package com.teamwizardry.librarianlib.courier
import io.netty.buffer.ByteBuf
import io.netty.buffer.Unpooled
import io.netty.handler.codec.DecoderException
import net.minecraft.network.PacketByteBuf
import net.minecraft.util.math.ChunkSectionPos
public class CourierBuffer(parent: ByteBuf) : PacketByteBuf(parent) {
//@Environment(EnvType.CLIENT)
override fun readLongArray(ls: LongArray?): LongArray {
return this.readLongArray(ls, readableBytes() / 8)
}
//@Environment(EnvType.CLIENT)
override fun readLongArray(toArray: LongArray?, maxCount: Int): LongArray {
val count = readVarInt()
val outArray = if(toArray?.size == count) {
toArray
} else {
if (count > maxCount) {
throw DecoderException("LongArray with size $count is bigger than allowed $maxCount")
}
LongArray(count)
}
for (k in outArray.indices) {
outArray[k] = readLong()
}
return outArray
}
//@Environment(EnvType.CLIENT)
override fun readChunkSectionPos(): ChunkSectionPos {
return ChunkSectionPos.from(readLong())
}
//@Environment(EnvType.CLIENT)
override fun readString(): String {
return this.readString(32767)
}
public companion object {
@JvmStatic
public fun create(): CourierBuffer {
return CourierBuffer(Unpooled.buffer())
}
}
} | lgpl-3.0 | 3cdd0617b28d2047ae14f7d802274051 | 28.14 | 101 | 0.644918 | 4.48 | false | false | false | false |
mvarnagiris/expensius | models/src/test/kotlin/com/mvcoding/expensius/model/CurrencyFormatTest.kt | 1 | 4110 | /*
* Copyright (C) 2016 Mantas Varnagiris.
*
* 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.
*/
package com.mvcoding.expensius.model
import com.mvcoding.expensius.model.CurrencyFormat.DecimalSeparator
import com.mvcoding.expensius.model.CurrencyFormat.GroupSeparator
import com.mvcoding.expensius.model.CurrencyFormat.SymbolDistance
import com.mvcoding.expensius.model.CurrencyFormat.SymbolPosition
import org.hamcrest.CoreMatchers.equalTo
import org.junit.Assert.assertThat
import org.junit.Test
import java.math.BigDecimal
class CurrencyFormatTest {
val currencyFormat = CurrencyFormat("$", SymbolPosition.START, SymbolDistance.FAR, DecimalSeparator.DOT, GroupSeparator.COMMA, 2, 2)
val value = BigDecimal("1234.567")
@Test
fun `symbol is at the right position`() {
assertThat(currencyFormat.copy(
symbol = "$",
symbolPosition = SymbolPosition.START,
symbolDistance = SymbolDistance.FAR).format(value), equalTo("$ 1,234.57"))
assertThat(currencyFormat.copy(
symbol = "USD",
symbolPosition = SymbolPosition.START,
symbolDistance = SymbolDistance.CLOSE).format(value), equalTo("USD1,234.57"))
assertThat(currencyFormat.copy(
symbol = "AnyThing",
symbolPosition = SymbolPosition.END,
symbolDistance = SymbolDistance.FAR).format(value), equalTo("1,234.57 AnyThing"))
assertThat(currencyFormat.copy(
symbol = "$",
symbolPosition = SymbolPosition.END,
symbolDistance = SymbolDistance.CLOSE).format(value), equalTo("1,234.57$"))
}
@Test
fun `uses correct decimal separator`() {
assertThat(currencyFormat.copy(decimalSeparator = DecimalSeparator.DOT).format(value), equalTo("$ 1,234.57"))
assertThat(currencyFormat.copy(decimalSeparator = DecimalSeparator.COMMA).format(value), equalTo("$ 1,234,57"))
assertThat(currencyFormat.copy(decimalSeparator = DecimalSeparator.SPACE).format(value), equalTo("$ 1,234 57"))
}
@Test
fun `uses correct group separator`() {
assertThat(currencyFormat.copy(groupSeparator = GroupSeparator.COMMA).format(value), equalTo("$ 1,234.57"))
assertThat(currencyFormat.copy(groupSeparator = GroupSeparator.DOT).format(value), equalTo("$ 1.234.57"))
assertThat(currencyFormat.copy(groupSeparator = GroupSeparator.SPACE).format(value), equalTo("$ 1 234.57"))
assertThat(currencyFormat.copy(groupSeparator = GroupSeparator.NONE).format(value), equalTo("$ 1\u0000234.57"))
}
@Test
fun `uses correct min fraction digits`() {
val value = BigDecimal("1234")
assertThat(currencyFormat.copy(minFractionDigits = 0).format(value), equalTo("$ 1,234"))
assertThat(currencyFormat.copy(minFractionDigits = 1).format(value), equalTo("$ 1,234.0"))
assertThat(currencyFormat.copy(minFractionDigits = 2).format(value), equalTo("$ 1,234.00"))
assertThat(currencyFormat.copy(minFractionDigits = 3, maxFractionDigits = 3).format(value), equalTo("$ 1,234.000"))
}
@Test
fun `uses correct max fraction digits`() {
val value = BigDecimal("1234.5678")
assertThat(currencyFormat.copy(maxFractionDigits = 0).format(value), equalTo("$ 1,235"))
assertThat(currencyFormat.copy(maxFractionDigits = 1).format(value), equalTo("$ 1,234.6"))
assertThat(currencyFormat.copy(maxFractionDigits = 2).format(value), equalTo("$ 1,234.57"))
assertThat(currencyFormat.copy(maxFractionDigits = 3).format(value), equalTo("$ 1,234.568"))
}
} | gpl-3.0 | 686c186f8be0ef210c309bc6599e7b68 | 46.252874 | 136 | 0.694404 | 4.409871 | false | true | false | false |
nrizzio/Signal-Android | app/src/main/java/org/thoughtcrime/securesms/badges/view/ViewBadgeViewModel.kt | 2 | 1811 | package org.thoughtcrime.securesms.badges.view
import androidx.lifecycle.LiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import io.reactivex.rxjava3.disposables.CompositeDisposable
import org.thoughtcrime.securesms.badges.BadgeRepository
import org.thoughtcrime.securesms.badges.models.Badge
import org.thoughtcrime.securesms.recipients.Recipient
import org.thoughtcrime.securesms.recipients.RecipientId
import org.thoughtcrime.securesms.util.livedata.Store
class ViewBadgeViewModel(
private val startBadge: Badge?,
private val recipientId: RecipientId,
private val repository: BadgeRepository
) : ViewModel() {
private val disposables = CompositeDisposable()
private val store = Store(ViewBadgeState())
val state: LiveData<ViewBadgeState> = store.stateLiveData
init {
store.update(Recipient.live(recipientId).liveData) { recipient, state ->
state.copy(
recipient = recipient,
allBadgesVisibleOnProfile = recipient.badges,
selectedBadge = startBadge ?: recipient.badges.firstOrNull(),
badgeLoadState = ViewBadgeState.LoadState.LOADED
)
}
}
override fun onCleared() {
disposables.clear()
}
fun onPageSelected(position: Int) {
if (position > store.state.allBadgesVisibleOnProfile.size - 1 || position < 0) {
return
}
store.update {
it.copy(selectedBadge = it.allBadgesVisibleOnProfile[position])
}
}
class Factory(
private val startBadge: Badge?,
private val recipientId: RecipientId,
private val repository: BadgeRepository
) : ViewModelProvider.Factory {
override fun <T : ViewModel> create(modelClass: Class<T>): T {
return requireNotNull(modelClass.cast(ViewBadgeViewModel(startBadge, recipientId, repository)))
}
}
}
| gpl-3.0 | c539c9d43cc5fd4addedbf6bd76b5485 | 29.694915 | 101 | 0.749862 | 4.561713 | false | false | false | false |
MaTriXy/android-topeka | app/src/main/java/com/google/samples/apps/topeka/activity/QuizActivity.kt | 1 | 16662 | /*
* 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.samples.apps.topeka.activity
import android.animation.Animator
import android.animation.AnimatorListenerAdapter
import android.animation.AnimatorSet
import android.animation.ArgbEvaluator
import android.animation.ObjectAnimator
import android.annotation.SuppressLint
import android.annotation.TargetApi
import android.content.Context
import android.content.Intent
import android.graphics.Color
import android.os.Build
import android.os.Bundle
import android.support.annotation.RequiresApi
import android.support.annotation.VisibleForTesting
import android.support.design.widget.FloatingActionButton
import android.support.test.espresso.idling.CountingIdlingResource
import android.support.v4.app.ActivityCompat
import android.support.v4.content.ContextCompat
import android.support.v4.view.ViewCompat
import android.support.v4.view.ViewPropertyAnimatorListenerAdapter
import android.support.v4.view.animation.FastOutLinearInInterpolator
import android.support.v4.view.animation.FastOutSlowInInterpolator
import android.support.v7.app.AppCompatActivity
import android.view.View
import android.view.ViewAnimationUtils
import android.view.animation.Interpolator
import android.widget.FrameLayout
import android.widget.ImageView
import android.widget.ListView
import android.widget.TextView
import com.google.samples.apps.topeka.R
import com.google.samples.apps.topeka.fragment.QuizFragment
import com.google.samples.apps.topeka.helper.ApiLevelHelper
import com.google.samples.apps.topeka.helper.FOREGROUND_COLOR
import com.google.samples.apps.topeka.helper.database
import com.google.samples.apps.topeka.helper.findFragmentById
import com.google.samples.apps.topeka.helper.findFragmentByTag
import com.google.samples.apps.topeka.model.Category
import com.google.samples.apps.topeka.model.JsonAttributes
import com.google.samples.apps.topeka.widget.TextSharedElementCallback
@get:VisibleForTesting
val countingIdlingResource = CountingIdlingResource("Quiz")
class QuizActivity : AppCompatActivity() {
private val interpolator: Interpolator = FastOutSlowInInterpolator()
private lateinit var category: Category
private var quizFab: FloatingActionButton? = null
private var icon: ImageView? = null
private var toolbarBack: View? = null
private lateinit var circularReveal: Animator
private lateinit var colorChange: ObjectAnimator
private var savedStateIsPlaying = false
private var quizFragment: QuizFragment? = null
private val onClickListener = View.OnClickListener {
when (it.id) {
R.id.fab_quiz -> startQuizFromClickOn(it)
R.id.submitAnswer -> submitAnswer()
R.id.quiz_done -> ActivityCompat.finishAfterTransition(this@QuizActivity)
R.id.back -> onBackPressed()
else -> throw UnsupportedOperationException(
"OnClick has not been implemented for " + resources.getResourceName(it.id))
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
if (null != savedInstanceState) {
savedStateIsPlaying = savedInstanceState.getBoolean(STATE_IS_PLAYING)
}
populate(intent.getStringExtra(Category.TAG))
val categoryNameTextSize = resources
.getDimensionPixelSize(R.dimen.category_item_text_size)
val paddingStart = resources.getDimensionPixelSize(R.dimen.spacing_double)
val startDelay = resources.getInteger(R.integer.toolbar_transition_duration).toLong()
ActivityCompat.setEnterSharedElementCallback(this,
object : TextSharedElementCallback(categoryNameTextSize.toFloat(), paddingStart) {
override fun onSharedElementStart(sharedElementNames: List<String>?,
sharedElements: List<View>,
sharedElementSnapshots: List<View>?) {
super.onSharedElementStart(sharedElementNames,
sharedElements,
sharedElementSnapshots)
toolbarBack?.let {
it.scaleX = 0f
it.scaleY = 0f
}
}
override fun onSharedElementEnd(sharedElementNames: List<String>?,
sharedElements: List<View>,
sharedElementSnapshots: List<View>?) {
super.onSharedElementEnd(sharedElementNames,
sharedElements,
sharedElementSnapshots)
// Make sure to perform this animation after the transition has ended.
ViewCompat.animate(toolbarBack)
.setStartDelay(startDelay)
.scaleX(1f)
.scaleY(1f)
.alpha(1f)
}
})
}
@SuppressLint("NewApi")
private fun populate(categoryId: String) {
category = database().getCategoryWith(categoryId).also {
setTheme(it.theme.styleId)
if (ApiLevelHelper.isAtLeast(Build.VERSION_CODES.LOLLIPOP)) {
window.statusBarColor = ContextCompat.getColor(this, it.theme.primaryDarkColor)
}
initLayout(it.id)
initToolbar(it)
}
}
private fun initLayout(categoryId: String) {
setContentView(R.layout.activity_quiz)
icon = (findViewById<ImageView>(R.id.icon)).apply {
val resId = resources.getIdentifier("$IMAGE_CATEGORY$categoryId",
"drawable",
applicationContext.packageName)
setImageResource(resId)
ViewCompat.animate(this)
.scaleX(1f)
.scaleY(1f)
.alpha(1f)
.setInterpolator(interpolator)
.setStartDelay(300L)
.start()
}
quizFab = (findViewById<FloatingActionButton>(R.id.fab_quiz)).apply {
setImageResource(R.drawable.ic_play)
if (savedStateIsPlaying) hide() else show()
setOnClickListener(onClickListener)
}
toolbarBack = findViewById<View>(R.id.back).apply { setOnClickListener(onClickListener) }
}
private fun initToolbar(category: Category) {
with(findViewById<TextView>(R.id.category_title)) {
text = category.name
setTextColor(ContextCompat.getColor(this@QuizActivity, category.theme.textPrimaryColor))
}
if (savedStateIsPlaying) {
// the toolbar should not have more elevation than the content while playing
setToolbarElevation(false)
}
}
override fun onResume() {
if (savedStateIsPlaying) {
with(findFragmentByTag(FRAGMENT_TAG) as QuizFragment) {
if (!hasSolvedStateListener()) setSolvedStateListener(solvedStateListener)
}
findViewById<View>(R.id.quiz_fragment_container).visibility = View.VISIBLE
quizFab?.hide()
icon?.visibility = View.GONE
} else {
initQuizFragment()
}
super.onResume()
}
private fun initQuizFragment() {
if (quizFragment != null) return
quizFragment = QuizFragment.newInstance(category.id, solvedStateListener)
// the toolbar should not have more elevation than the content while playing
setToolbarElevation(false)
}
public override fun onSaveInstanceState(outState: Bundle) {
outState.putBoolean(STATE_IS_PLAYING, quizFab?.visibility == View.GONE)
super.onSaveInstanceState(outState)
}
override fun onBackPressed() {
ViewCompat.animate(toolbarBack)
.scaleX(0f)
.scaleY(0f)
.alpha(0f)
.setDuration(100L)
.start()
// Scale the icon and fab to 0 size before calling onBackPressed if it exists.
ViewCompat.animate(icon)
.scaleX(.7f)
.scaleY(.7f)
.alpha(0f)
.setInterpolator(interpolator)
.start()
ViewCompat.animate(quizFab)
.scaleX(0f)
.scaleY(0f)
.setInterpolator(interpolator)
.setStartDelay(100L)
.setListener(object : ViewPropertyAnimatorListenerAdapter() {
@SuppressLint("NewApi")
override fun onAnimationEnd(view: View?) {
if (isFinishing ||
ApiLevelHelper.isAtLeast(Build.VERSION_CODES.JELLY_BEAN_MR1) &&
isDestroyed) return
[email protected]()
}
})
.start()
}
private fun startQuizFromClickOn(clickedView: View) {
initQuizFragment()
supportFragmentManager
.beginTransaction()
.replace(R.id.quiz_fragment_container, quizFragment, FRAGMENT_TAG)
.commit()
val container = (findViewById<FrameLayout>(R.id.quiz_fragment_container)).apply {
setBackgroundColor(ContextCompat.getColor(
this@QuizActivity,
category.theme.windowBackgroundColor))
}
revealFragmentContainer(clickedView, container)
// the toolbar should not have more elevation than the content while playing
setToolbarElevation(false)
}
@SuppressLint("NewApi")
private fun revealFragmentContainer(clickedView: View,
fragmentContainer: FrameLayout) {
if (ApiLevelHelper.isAtLeast(Build.VERSION_CODES.LOLLIPOP)) {
revealFragmentContainerLollipop(clickedView, fragmentContainer)
} else {
fragmentContainer.visibility = View.VISIBLE
clickedView.visibility = View.GONE
icon?.visibility = View.GONE
}
}
@RequiresApi(Build.VERSION_CODES.LOLLIPOP)
private fun revealFragmentContainerLollipop(clickedView: View,
fragmentContainer: FrameLayout) {
prepareCircularReveal(clickedView, fragmentContainer)
ViewCompat.animate(clickedView)
.scaleX(0f)
.scaleY(0f)
.alpha(0f)
.setInterpolator(interpolator)
.setListener(object : ViewPropertyAnimatorListenerAdapter() {
override fun onAnimationEnd(view: View?) {
fragmentContainer.visibility = View.VISIBLE
clickedView.visibility = View.GONE
}
})
.start()
fragmentContainer.visibility = View.VISIBLE
with(AnimatorSet()) {
play(circularReveal).with(colorChange)
start()
}
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
private fun prepareCircularReveal(startView: View, targetView: FrameLayout) {
val centerX = (startView.left + startView.right) / 2
// Subtract the start view's height to adjust for relative coordinates on screen.
val centerY = (startView.top + startView.bottom) / 2 - startView.height
val endRadius = Math.hypot(centerX.toDouble(), centerY.toDouble()).toFloat()
circularReveal = ViewAnimationUtils.createCircularReveal(
targetView, centerX, centerY, startView.width.toFloat(), endRadius)
.apply {
interpolator = FastOutLinearInInterpolator()
addListener(object : AnimatorListenerAdapter() {
override fun onAnimationEnd(animation: Animator) {
icon?.visibility = View.GONE
removeListener(this)
}
})
}
// Adding a color animation from the FAB's color to transparent creates a dissolve like
// effect to the circular reveal.
val accentColor = ContextCompat.getColor(this, category.theme.accentColor)
colorChange = ObjectAnimator.ofInt(targetView,
targetView.FOREGROUND_COLOR, accentColor, Color.TRANSPARENT)
.apply {
setEvaluator(ArgbEvaluator())
interpolator = [email protected]
}
}
@SuppressLint("NewApi")
fun setToolbarElevation(shouldElevate: Boolean) {
if (ApiLevelHelper.isAtLeast(Build.VERSION_CODES.LOLLIPOP)) {
toolbarBack?.elevation = if (shouldElevate)
resources.getDimension(R.dimen.elevation_header)
else
0f
}
}
private fun setResultSolved() {
setResult(R.id.solved, Intent().apply { putExtra(JsonAttributes.ID, category.id) })
}
private val solvedStateListener get() = object : QuizFragment.SolvedStateListener {
override fun onCategorySolved() {
setResultSolved()
setToolbarElevation(true)
displayDoneFab()
}
/*
* We're re-using the already existing fab and give it some
* new values. This has to run delayed due to the queued animation
* to hide the fab initially.
*/
private fun displayDoneFab() {
with(circularReveal) {
if (isRunning) {
addListener(object : AnimatorListenerAdapter() {
override fun onAnimationEnd(animation: Animator) {
showQuizFabWithDoneIcon()
removeListener(this)
}
})
} else {
showQuizFabWithDoneIcon()
}
}
}
private fun showQuizFabWithDoneIcon() {
with(quizFab ?: return) {
setImageResource(R.drawable.ic_tick)
id = R.id.quiz_done
visibility = View.VISIBLE
scaleX = 0f
scaleY = 0f
}
ViewCompat.animate(quizFab)
.scaleX(1f)
.scaleY(1f)
.setInterpolator(interpolator)
.setListener(null)
.start()
}
}
private fun submitAnswer() {
if (!countingIdlingResource.isIdleNow) countingIdlingResource.decrement()
if (quizFragment == null) {
quizFragment = findFragmentById(R.id.quiz_fragment_container) as QuizFragment
}
with(quizFragment ?: return) {
if (!showNextPage()) {
view?.let {
with(it.findViewById<ListView>(R.id.scorecard)) {
adapter = scoreAdapter
visibility = View.VISIBLE
}
quizView?.visibility = View.GONE
}
setResultSolved()
return
}
}
}
/**
* Proceeds the quiz to it's next state.
*/
fun proceed() = submitAnswer()
/**
* Solely exists for testing purposes and makes sure Espresso does not get confused.
*/
fun lockIdlingResource() = countingIdlingResource.increment()
companion object {
private val IMAGE_CATEGORY = "image_category_"
private val STATE_IS_PLAYING = "isPlaying"
private val FRAGMENT_TAG = "Quiz"
fun getStartIntent(context: Context, category: Category): Intent {
return Intent(context, QuizActivity::class.java)
.apply { putExtra(Category.TAG, category.id) }
}
}
} | apache-2.0 | 4f7aaaaae9e9a6e0886783d320275687 | 38.863636 | 100 | 0.599148 | 5.393979 | false | false | false | false |
inorichi/tachiyomi-extensions | src/ar/gmanga/src/eu/kanade/tachiyomi/extension/ar/gmanga/GmangaFilters.kt | 1 | 13359 | package eu.kanade.tachiyomi.extension.ar.gmanga
import android.annotation.SuppressLint
import com.github.salomonbrys.kotson.addAll
import com.github.salomonbrys.kotson.addProperty
import com.google.gson.JsonArray
import com.google.gson.JsonNull
import com.google.gson.JsonObject
import eu.kanade.tachiyomi.source.model.Filter
import eu.kanade.tachiyomi.source.model.FilterList
import java.lang.Exception
import java.text.ParseException
import java.text.SimpleDateFormat
class GmangaFilters() {
companion object {
fun getFilterList() = FilterList(
MangaTypeFilter(),
OneShotFilter(),
StoryStatusFilter(),
TranslationStatusFilter(),
ChapterCountFilter(),
DateRangeFilter(),
CategoryFilter()
)
fun buildSearchPayload(page: Int, query: String = "", filters: FilterList): JsonObject {
val mangaTypeFilter = filters.findInstance<MangaTypeFilter>()!!
val oneShotFilter = filters.findInstance<OneShotFilter>()!!
val storyStatusFilter = filters.findInstance<StoryStatusFilter>()!!
val translationStatusFilter = filters.findInstance<TranslationStatusFilter>()!!
val chapterCountFilter = filters.findInstance<ChapterCountFilter>()!!
val dateRangeFilter = filters.findInstance<DateRangeFilter>()!!
val categoryFilter = filters.findInstance<CategoryFilter>()!!
return JsonObject().apply {
oneShotFilter.state.first().let {
when {
it.isIncluded() -> addProperty("oneshot", true)
it.isExcluded() -> addProperty("oneshot", false)
else -> addProperty("oneshot", JsonNull.INSTANCE)
}
}
addProperty("title", query)
addProperty("page", page)
addProperty(
"manga_types",
JsonObject().apply {
addProperty(
"include",
JsonArray().apply {
addAll(mangaTypeFilter.state.filter { it.isIncluded() }.map { it.id })
}
)
addProperty(
"exclude",
JsonArray().apply {
addAll(mangaTypeFilter.state.filter { it.isExcluded() }.map { it.id })
}
)
}
)
addProperty(
"story_status",
JsonObject().apply {
addProperty(
"include",
JsonArray().apply {
addAll(storyStatusFilter.state.filter { it.isIncluded() }.map { it.id })
}
)
addProperty(
"exclude",
JsonArray().apply {
addAll(storyStatusFilter.state.filter { it.isExcluded() }.map { it.id })
}
)
}
)
addProperty(
"translation_status",
JsonObject().apply {
addProperty(
"include",
JsonArray().apply {
addAll(translationStatusFilter.state.filter { it.isIncluded() }.map { it.id })
}
)
addProperty(
"exclude",
JsonArray().apply {
addAll(translationStatusFilter.state.filter { it.isExcluded() }.map { it.id })
}
)
}
)
addProperty(
"categories",
JsonObject().apply {
addProperty(
"include",
JsonArray().apply {
add(JsonNull.INSTANCE) // always included, maybe to avoid shifting index in the backend
addAll(categoryFilter.state.filter { it.isIncluded() }.map { it.id })
}
)
addProperty(
"exclude",
JsonArray().apply {
addAll(categoryFilter.state.filter { it.isExcluded() }.map { it.id })
}
)
}
)
addProperty(
"chapters",
JsonObject().apply {
addPropertyFromValidatingTextFilter(
chapterCountFilter.state.first {
it.id == FILTER_ID_MIN_CHAPTER_COUNT
},
"min",
ERROR_INVALID_MIN_CHAPTER_COUNT,
""
)
addPropertyFromValidatingTextFilter(
chapterCountFilter.state.first {
it.id == FILTER_ID_MAX_CHAPTER_COUNT
},
"max",
ERROR_INVALID_MAX_CHAPTER_COUNT,
""
)
}
)
addProperty(
"dates",
JsonObject().apply {
addPropertyFromValidatingTextFilter(
dateRangeFilter.state.first {
it.id == FILTER_ID_START_DATE
},
"start",
ERROR_INVALID_START_DATE
)
addPropertyFromValidatingTextFilter(
dateRangeFilter.state.first {
it.id == FILTER_ID_END_DATE
},
"end",
ERROR_INVALID_END_DATE
)
}
)
}
}
// filter IDs
private const val FILTER_ID_ONE_SHOT = "oneshot"
private const val FILTER_ID_START_DATE = "start"
private const val FILTER_ID_END_DATE = "end"
private const val FILTER_ID_MIN_CHAPTER_COUNT = "min"
private const val FILTER_ID_MAX_CHAPTER_COUNT = "max"
// error messages
private const val ERROR_INVALID_START_DATE = "تاريخ بداية غير صالح"
private const val ERROR_INVALID_END_DATE = " تاريخ نهاية غير صالح"
private const val ERROR_INVALID_MIN_CHAPTER_COUNT = "الحد الأدنى لعدد الفصول غير صالح"
private const val ERROR_INVALID_MAX_CHAPTER_COUNT = "الحد الأقصى لعدد الفصول غير صالح"
private class MangaTypeFilter() : Filter.Group<TagFilter>(
"الأصل",
listOf(
TagFilter("1", "يابانية", TriState.STATE_INCLUDE),
TagFilter("2", "كورية", TriState.STATE_INCLUDE),
TagFilter("3", "صينية", TriState.STATE_INCLUDE),
TagFilter("4", "عربية", TriState.STATE_INCLUDE),
TagFilter("5", "كوميك", TriState.STATE_INCLUDE),
TagFilter("6", "هواة", TriState.STATE_INCLUDE),
TagFilter("7", "إندونيسية", TriState.STATE_INCLUDE),
TagFilter("8", "روسية", TriState.STATE_INCLUDE),
)
)
private class OneShotFilter() : Filter.Group<TagFilter>(
"ونشوت؟",
listOf(
TagFilter(FILTER_ID_ONE_SHOT, "نعم", TriState.STATE_EXCLUDE)
)
)
private class StoryStatusFilter() : Filter.Group<TagFilter>(
"حالة القصة",
listOf(
TagFilter("2", "مستمرة"),
TagFilter("3", "منتهية")
)
)
private class TranslationStatusFilter() : Filter.Group<TagFilter>(
"حالة الترجمة",
listOf(
TagFilter("0", "منتهية"),
TagFilter("1", "مستمرة"),
TagFilter("2", "متوقفة"),
TagFilter("3", "غير مترجمة", TriState.STATE_EXCLUDE),
)
)
private class ChapterCountFilter() : Filter.Group<IntFilter>(
"عدد الفصول",
listOf(
IntFilter(FILTER_ID_MIN_CHAPTER_COUNT, "على الأقل"),
IntFilter(FILTER_ID_MAX_CHAPTER_COUNT, "على الأكثر")
)
)
private class DateRangeFilter() : Filter.Group<DateFilter>(
"تاريخ النشر",
listOf(
DateFilter(FILTER_ID_START_DATE, "تاريخ النشر"),
DateFilter(FILTER_ID_END_DATE, "تاريخ الإنتهاء")
)
)
private class CategoryFilter() : Filter.Group<TagFilter>(
"التصنيفات",
listOf(
TagFilter("1", "إثارة"),
TagFilter("2", "أكشن"),
TagFilter("3", "الحياة المدرسية"),
TagFilter("4", "الحياة اليومية"),
TagFilter("5", "آليات"),
TagFilter("6", "تاريخي"),
TagFilter("7", "تراجيدي"),
TagFilter("8", "جوسيه"),
TagFilter("9", "حربي"),
TagFilter("10", "خيال"),
TagFilter("11", "خيال علمي"),
TagFilter("12", "دراما"),
TagFilter("13", "رعب"),
TagFilter("14", "رومانسي"),
TagFilter("15", "رياضة"),
TagFilter("16", "ساموراي"),
TagFilter("17", "سحر"),
TagFilter("18", "سينين"),
TagFilter("19", "شوجو"),
TagFilter("20", "شونين"),
TagFilter("21", "عنف"),
TagFilter("22", "غموض"),
TagFilter("23", "فنون قتال"),
TagFilter("24", "قوى خارقة"),
TagFilter("25", "كوميدي"),
TagFilter("26", "لعبة"),
TagFilter("27", "مسابقة"),
TagFilter("28", "مصاصي الدماء"),
TagFilter("29", "مغامرات"),
TagFilter("30", "موسيقى"),
TagFilter("31", "نفسي"),
TagFilter("32", "نينجا"),
TagFilter("33", "وحوش"),
TagFilter("34", "حريم"),
TagFilter("35", "راشد"),
TagFilter("38", "ويب-تون"),
TagFilter("39", "زمنكاني")
)
)
private const val DATE_FILTER_PATTERN = "yyyy/MM/dd"
@SuppressLint("SimpleDateFormat")
private val DATE_FITLER_FORMAT = SimpleDateFormat(DATE_FILTER_PATTERN).apply {
isLenient = false
}
private fun SimpleDateFormat.isValid(date: String): Boolean {
return try {
this.parse(date)
true
} catch (e: ParseException) {
false
}
}
private fun JsonObject.addPropertyFromValidatingTextFilter(
filter: ValidatingTextFilter,
property: String,
invalidErrorMessage: String,
default: String? = null
) {
filter.let {
when {
it.state == "" -> if (default == null) {
addProperty(property, JsonNull.INSTANCE)
} else addProperty(property, default)
it.isValid() -> addProperty(property, it.state)
else -> throw Exception(invalidErrorMessage)
}
}
}
private inline fun <reified T> Iterable<*>.findInstance() = find { it is T } as? T
private class TagFilter(val id: String, name: String, state: Int = STATE_IGNORE) : Filter.TriState(name, state)
private abstract class ValidatingTextFilter(name: String) : Filter.Text(name) {
abstract fun isValid(): Boolean
}
private class DateFilter(val id: String, name: String) : ValidatingTextFilter("($DATE_FILTER_PATTERN) $name)") {
override fun isValid(): Boolean = DATE_FITLER_FORMAT.isValid(this.state)
}
private class IntFilter(val id: String, name: String) : ValidatingTextFilter(name) {
override fun isValid(): Boolean = state.toIntOrNull() != null
}
}
}
| apache-2.0 | 4a26502aee53736f8bff9ed859e11a65 | 37.52994 | 120 | 0.450229 | 4.460659 | false | false | false | false |
WillowChat/Hopper | src/main/kotlin/chat/willow/hopper/routes/connection/ConnectionsPostRouteHandler.kt | 1 | 2402 | package chat.willow.hopper.routes.connection
import chat.willow.hopper.connections.HopperConnection
import chat.willow.hopper.connections.IHopperConnections
import chat.willow.hopper.db.IConnectionsDataSink
import chat.willow.hopper.logging.loggerFor
import chat.willow.hopper.routes.*
import chat.willow.hopper.routes.shared.ErrorResponseBody
import chat.willow.hopper.websocket.IWebSocketUserTracker
import chat.willow.hopper.websocket.messages.NewConnection
import com.google.common.net.HostSpecifier
import com.squareup.moshi.Moshi
data class ConnectionsPostRequestBody(val host: String, val port: Int, val tls: Boolean, val nick: String)
data class ConnectionsPostResponseBody(val connection: HopperConnection)
class ConnectionsPostRouteHandler(moshi: Moshi, private val connections: IHopperConnections, private val tracker: IWebSocketUserTracker, private val connectionSink: IConnectionsDataSink) :
JsonRouteHandler<ConnectionsPostRequestBody, ConnectionsPostResponseBody, AuthenticatedContext>(
moshi.stringParser(),
moshi.stringSerialiser(),
moshi.stringSerialiser(),
AuthenticatedContext.Builder
) {
private val LOGGER = loggerFor<ConnectionsPostRouteHandler>()
override fun handle(request: ConnectionsPostRequestBody, context: AuthenticatedContext): RouteResult<ConnectionsPostResponseBody, ErrorResponseBody> {
LOGGER.info("handling POST /connections: $request")
val hostValid = HostSpecifier.isValid(request.host)
if (!hostValid) {
return jsonFailure(400, "host failed validation")
}
val portValid = request.port in 1..65535
if (!portValid) {
return jsonFailure(400, "port failed validation")
}
// todo: validate nickname?
val connection = connections.create(request.host, request.port, request.tls, request.nick) ?: return jsonFailure(500, "failed to create connection")
val didPersistConnection = connectionSink.addConnection(context.user, connection)
if (!didPersistConnection) {
return jsonFailure(500, "failed to persist connection")
}
connections.track(connection)
tracker.send(NewConnection.Payload(id = connection.id), user = context.user)
return RouteResult.success(value = ConnectionsPostResponseBody(connection))
}
} | isc | d601d3e78c4fcc4b224c77a71ecc4edc | 41.157895 | 188 | 0.741882 | 4.682261 | false | false | false | false |
westnordost/StreetComplete | app/src/main/java/de/westnordost/streetcomplete/quests/baby_changing_table/AddBabyChangingTable.kt | 1 | 1475 | package de.westnordost.streetcomplete.quests.baby_changing_table
import de.westnordost.streetcomplete.R
import de.westnordost.streetcomplete.data.osm.osmquest.OsmFilterQuestType
import de.westnordost.streetcomplete.data.osm.changes.StringMapChangesBuilder
import de.westnordost.streetcomplete.ktx.toYesNo
import de.westnordost.streetcomplete.quests.YesNoQuestAnswerFragment
class AddBabyChangingTable : OsmFilterQuestType<Boolean>() {
override val elementFilter = """
nodes, ways with
(
(
(amenity ~ restaurant|cafe|fuel|fast_food or shop ~ mall|department_store)
and name
and toilets = yes
)
or amenity = toilets
)
and !diaper and !changing_table
"""
override val commitMessage = "Add baby changing table"
override val wikiLink = "Key:changing_table"
override val defaultDisabledMessage = R.string.default_disabled_msg_go_inside
override val isReplaceShopEnabled = true
override val icon = R.drawable.ic_quest_baby
override fun getTitle(tags: Map<String, String>) =
if (tags.containsKey("name"))
R.string.quest_baby_changing_table_title
else
R.string.quest_baby_changing_table_toilets_title
override fun createForm() = YesNoQuestAnswerFragment()
override fun applyAnswerTo(answer: Boolean, changes: StringMapChangesBuilder) {
changes.add("changing_table", answer.toYesNo())
}
}
| gpl-3.0 | 1181dbe0aea9b4327a57118c94020028 | 35.875 | 86 | 0.705085 | 4.623824 | false | false | false | false |
StepicOrg/stepic-android | app/src/main/java/org/stepic/droid/ui/adapters/StepFragmentAdapter.kt | 2 | 2117 | package org.stepic.droid.ui.adapters
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentManager
import androidx.fragment.app.FragmentStatePagerAdapter
import org.stepic.droid.util.resolvers.StepTypeResolver
import org.stepik.android.domain.lesson.model.LessonData
import org.stepik.android.domain.lesson.model.StepItem
import org.stepik.android.view.fragment_pager.ActiveFragmentPagerAdapter
import org.stepik.android.view.step.ui.fragment.StepFragment
class StepFragmentAdapter(
fm: FragmentManager,
private val stepTypeResolver: StepTypeResolver
) : FragmentStatePagerAdapter(fm, BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT),
ActiveFragmentPagerAdapter {
var items: List<StepItem> = emptyList()
set(value) {
val oldIds = field.map { it.stepWrapper.step.id }
val newIds = value.map { it.stepWrapper.step.id }
field = value
if (oldIds != newIds) {
notifyDataSetChanged()
}
}
lateinit var lessonData: LessonData
private val _activeFragments = mutableMapOf<Int, Fragment>()
override val activeFragments: Map<Int, Fragment>
get() = _activeFragments
override fun getItem(position: Int): Fragment =
StepFragment.newInstance(items[position].stepWrapper, lessonData)
override fun getCount(): Int =
items.size
override fun instantiateItem(container: ViewGroup, position: Int): Any =
super
.instantiateItem(container, position)
.also {
(it as? Fragment)?.let { fragment -> _activeFragments[position] = fragment }
}
override fun destroyItem(container: ViewGroup, position: Int, `object`: Any) {
_activeFragments.remove(position)
super.destroyItem(container, position, `object`)
}
fun getTabDrawable(position: Int): Pair<Int, Int> {
val step = items.getOrNull(position)?.stepWrapper?.step
return stepTypeResolver.getDrawableForType(step?.block?.name, step?.actions?.doReview != null)
}
}
| apache-2.0 | ce9767cf78f56623712a4dcea7440b13 | 35.5 | 102 | 0.692017 | 4.572354 | false | false | false | false |
StepicOrg/stepic-android | app/src/main/java/org/stepik/android/view/course_list/ui/delegate/CoursePropertiesDelegate.kt | 1 | 4693 | package org.stepik.android.view.course_list.ui.delegate
import android.view.View
import android.view.ViewGroup
import androidx.core.view.children
import androidx.core.view.isVisible
import kotlinx.android.synthetic.main.item_course.view.*
import kotlinx.android.synthetic.main.layout_course_properties.view.*
import org.stepic.droid.R
import org.stepic.droid.util.TextUtil
import org.stepic.droid.util.safeDiv
import org.stepic.droid.util.toFixed
import org.stepik.android.domain.course.model.CourseStats
import org.stepik.android.domain.course.model.EnrollmentState
import org.stepik.android.domain.course_list.model.CourseListItem
import org.stepik.android.domain.user_courses.model.UserCourse
import org.stepik.android.model.Course
import ru.nobird.android.core.model.safeCast
import java.util.Locale
class CoursePropertiesDelegate(
root: View,
private val view: ViewGroup
) {
private val learnersCountImage = view.learnersCountImage
private val learnersCountText = view.learnersCountText
private val courseItemProgress = view.courseItemProgressView
private val courseItemProgressTitle = view.courseItemProgressTitle
private val courseRatingImage = view.courseRatingImage
private val courseRatingText = view.courseRatingText
private val courseCertificateImage = view.courseCertificateImage
private val courseCertificateText = view.courseCertificateText
private val courseArchiveImage = view.courseArchiveImage
private val courseArchiveText = view.courseArchiveText
private val courseFavoriteImage = root.courseListFavorite
private val courseWishlistImage = root.courseListWishlist
fun setStats(courseListItem: CourseListItem.Data) {
setLearnersCount(courseListItem.course.learnersCount, courseListItem.course.enrollment > 0L)
setProgress(courseListItem.courseStats)
setRating(courseListItem.courseStats)
setCertificate(courseListItem.course)
setUserCourse(courseListItem.courseStats.enrollmentState.safeCast<EnrollmentState.Enrolled>()?.userCourse)
setWishlist(courseListItem.course.enrollment > 0L, courseListItem.courseStats.isWishlisted)
view.isVisible = view.children.any(View::isVisible)
}
private fun setLearnersCount(learnersCount: Long, isEnrolled: Boolean) {
val needShowLearners = learnersCount > 0 && !isEnrolled
if (needShowLearners) {
learnersCountText.text = TextUtil.formatNumbers(learnersCount)
}
learnersCountImage.isVisible = needShowLearners
learnersCountText.isVisible = needShowLearners
}
private fun setProgress(courseStats: CourseStats) {
val progress = courseStats.progress
val needShow = if (
progress != null &&
progress.cost > 0 &&
courseStats.enrollmentState.safeCast<EnrollmentState.Enrolled>()?.userCourse?.isArchived != true
) {
val score = progress
.score
?.toFloatOrNull()
?: 0f
prepareViewForProgress(score, progress.cost)
true
} else {
false
}
courseItemProgress.isVisible = needShow
courseItemProgressTitle.isVisible = needShow
}
private fun prepareViewForProgress(score: Float, cost: Long) {
courseItemProgress.progress = (score * 100 safeDiv cost) / 100f
courseItemProgressTitle.text = view
.resources
.getString(R.string.course_content_text_progress, score.toFixed(view.resources.getInteger(R.integer.score_decimal_count)), cost)
}
private fun setRating(courseStats: CourseStats) {
val needShow = courseStats.review > 0
if (needShow) {
courseRatingText.text = String.format(Locale.ROOT, view.resources.getString(R.string.course_rating_value), courseStats.review)
}
courseRatingImage.isVisible = needShow
courseRatingText.isVisible = needShow
}
private fun setCertificate(course: Course) {
val isEnrolled = course.enrollment > 0L
val needShow = course.withCertificate && !isEnrolled
courseCertificateImage.isVisible = needShow
courseCertificateText.isVisible = needShow
}
private fun setUserCourse(userCourse: UserCourse?) {
courseFavoriteImage.isVisible = userCourse?.isFavorite == true
val isArchived = userCourse?.isArchived == true
courseArchiveImage.isVisible = isArchived
courseArchiveText.isVisible = isArchived
}
private fun setWishlist(isEnrolled: Boolean, isWishlisted: Boolean) {
courseWishlistImage.isVisible = !isEnrolled && isWishlisted
}
} | apache-2.0 | 071ebde080df27f636505decb5d0a55b | 38.779661 | 140 | 0.72768 | 4.80348 | false | false | false | false |
NerdNumber9/TachiyomiEH | app/src/main/java/eu/kanade/tachiyomi/widget/preference/TrackLoginDialog.kt | 1 | 2088 | package eu.kanade.tachiyomi.widget.preference
import android.os.Bundle
import android.view.View
import eu.kanade.tachiyomi.R
import eu.kanade.tachiyomi.data.track.TrackManager
import eu.kanade.tachiyomi.data.track.TrackService
import eu.kanade.tachiyomi.util.toast
import kotlinx.android.synthetic.main.pref_account_login.view.*
import rx.android.schedulers.AndroidSchedulers
import rx.schedulers.Schedulers
import uy.kohesive.injekt.Injekt
import uy.kohesive.injekt.api.get
class TrackLoginDialog(bundle: Bundle? = null) : LoginDialogPreference(bundle) {
private val service = Injekt.get<TrackManager>().getService(args.getInt("key"))!!
constructor(service: TrackService) : this(Bundle().apply { putInt("key", service.id) })
override fun setCredentialsOnView(view: View) = with(view) {
dialog_title.text = context.getString(R.string.login_title, service.name)
username.setText(service.getUsername())
password.setText(service.getPassword())
}
override fun checkLogin() {
requestSubscription?.unsubscribe()
v?.apply {
if (username.text.isEmpty() || password.text.isEmpty())
return
login.progress = 1
val user = username.text.toString()
val pass = password.text.toString()
requestSubscription = service.login(user, pass)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe({
dialog?.dismiss()
context.toast(R.string.login_success)
}, { error ->
login.progress = -1
login.setText(R.string.unknown_error)
error.message?.let { context.toast(it) }
})
}
}
override fun onDialogClosed() {
super.onDialogClosed()
(targetController as? Listener)?.trackDialogClosed(service)
}
interface Listener {
fun trackDialogClosed(service: TrackService)
}
}
| apache-2.0 | 2ae0726d42822a8d5e7bc05d72083738 | 33.229508 | 91 | 0.630268 | 4.629712 | false | false | false | false |
exponentjs/exponent | packages/expo-image/android/src/main/java/expo/modules/image/drawing/OutlineProvider.kt | 2 | 6195 | package expo.modules.image.drawing
import android.content.Context
import android.graphics.Canvas
import android.graphics.Outline
import android.graphics.Path
import android.graphics.RectF
import android.view.View
import android.view.ViewOutlineProvider
import com.facebook.react.modules.i18nmanager.I18nUtil
import com.facebook.react.uimanager.FloatUtil
import com.facebook.react.uimanager.PixelUtil
import com.facebook.yoga.YogaConstants
import expo.modules.image.ifYogaUndefinedUse
import java.util.*
class OutlineProvider(private val mContext: Context) : ViewOutlineProvider() {
enum class BorderRadiusConfig {
ALL, TOP_LEFT, TOP_RIGHT, BOTTOM_RIGHT, BOTTOM_LEFT, TOP_START, TOP_END, BOTTOM_START, BOTTOM_END
}
enum class CornerRadius {
TOP_LEFT, TOP_RIGHT, BOTTOM_RIGHT, BOTTOM_LEFT
}
private var mLayoutDirection = View.LAYOUT_DIRECTION_LTR
private val mBounds = RectF()
val borderRadiiConfig = FloatArray(9)
private val mCornerRadii = FloatArray(4)
private var mCornerRadiiInvalidated = true
private val mConvexPath = Path()
private var mConvexPathInvalidated = true
init {
Arrays.fill(borderRadiiConfig, YogaConstants.UNDEFINED)
updateCornerRadiiIfNeeded()
}
private fun updateCornerRadiiIfNeeded() {
if (!mCornerRadiiInvalidated) {
return
}
val isRTL = mLayoutDirection == View.LAYOUT_DIRECTION_RTL
val isRTLSwap = I18nUtil.getInstance().doLeftAndRightSwapInRTL(mContext)
updateCornerRadius(
CornerRadius.TOP_LEFT,
BorderRadiusConfig.TOP_LEFT,
BorderRadiusConfig.TOP_RIGHT,
BorderRadiusConfig.TOP_START,
BorderRadiusConfig.TOP_END,
isRTL,
isRTLSwap
)
updateCornerRadius(
CornerRadius.TOP_RIGHT,
BorderRadiusConfig.TOP_RIGHT,
BorderRadiusConfig.TOP_LEFT,
BorderRadiusConfig.TOP_END,
BorderRadiusConfig.TOP_START,
isRTL,
isRTLSwap
)
updateCornerRadius(
CornerRadius.BOTTOM_LEFT,
BorderRadiusConfig.BOTTOM_LEFT,
BorderRadiusConfig.BOTTOM_RIGHT,
BorderRadiusConfig.BOTTOM_START,
BorderRadiusConfig.BOTTOM_END,
isRTL,
isRTLSwap
)
updateCornerRadius(
CornerRadius.BOTTOM_RIGHT,
BorderRadiusConfig.BOTTOM_RIGHT,
BorderRadiusConfig.BOTTOM_LEFT,
BorderRadiusConfig.BOTTOM_END,
BorderRadiusConfig.BOTTOM_START,
isRTL,
isRTLSwap
)
mCornerRadiiInvalidated = false
mConvexPathInvalidated = true
}
private fun updateCornerRadius(
outputPosition: CornerRadius,
inputPosition: BorderRadiusConfig,
oppositePosition: BorderRadiusConfig,
startPosition: BorderRadiusConfig,
endPosition: BorderRadiusConfig,
isRTL: Boolean,
isRTLSwap: Boolean
) {
var radius = borderRadiiConfig[inputPosition.ordinal]
if (isRTL) {
if (isRTLSwap) {
radius = borderRadiiConfig[oppositePosition.ordinal]
}
if (YogaConstants.isUndefined(radius)) {
radius = borderRadiiConfig[endPosition.ordinal]
}
} else {
if (YogaConstants.isUndefined(radius)) {
radius = borderRadiiConfig[startPosition.ordinal]
}
}
radius = radius
.ifYogaUndefinedUse(borderRadiiConfig[BorderRadiusConfig.ALL.ordinal])
.ifYogaUndefinedUse(0f)
mCornerRadii[outputPosition.ordinal] = PixelUtil.toPixelFromDIP(radius)
}
private fun updateConvexPathIfNeeded() {
if (!mConvexPathInvalidated) {
return
}
mConvexPath.reset()
mConvexPath.addRoundRect(
mBounds, floatArrayOf(
mCornerRadii[CornerRadius.TOP_LEFT.ordinal],
mCornerRadii[CornerRadius.TOP_LEFT.ordinal],
mCornerRadii[CornerRadius.TOP_RIGHT.ordinal],
mCornerRadii[CornerRadius.TOP_RIGHT.ordinal],
mCornerRadii[CornerRadius.BOTTOM_RIGHT.ordinal],
mCornerRadii[CornerRadius.BOTTOM_RIGHT.ordinal],
mCornerRadii[CornerRadius.BOTTOM_LEFT.ordinal],
mCornerRadii[CornerRadius.BOTTOM_LEFT.ordinal]
), Path.Direction.CW)
mConvexPathInvalidated = false
}
fun hasEqualCorners(): Boolean {
updateCornerRadiiIfNeeded()
val initialCornerRadius = mCornerRadii[0]
return mCornerRadii.all { initialCornerRadius == it }
}
fun setBorderRadius(radius: Float, position: Int): Boolean {
if (!FloatUtil.floatsEqual(borderRadiiConfig[position], radius)) {
borderRadiiConfig[position] = radius
mCornerRadiiInvalidated = true
return true
}
return false
}
private fun updateBoundsAndLayoutDirection(view: View) {
// Update layout direction
val layoutDirection = view.layoutDirection
if (mLayoutDirection != layoutDirection) {
mLayoutDirection = layoutDirection
mCornerRadiiInvalidated = true
}
// Update size
val left = 0
val top = 0
val right = view.width
val bottom = view.height
if (mBounds.left != left.toFloat() ||
mBounds.top != top.toFloat() ||
mBounds.right != right.toFloat() ||
mBounds.bottom != bottom.toFloat()) {
mBounds[left.toFloat(), top.toFloat(), right.toFloat()] = bottom.toFloat()
mCornerRadiiInvalidated = true
}
}
override fun getOutline(view: View, outline: Outline) {
updateBoundsAndLayoutDirection(view)
// Calculate outline
updateCornerRadiiIfNeeded()
if (hasEqualCorners()) {
val cornerRadius = mCornerRadii[0]
if (cornerRadius > 0) {
outline.setRoundRect(0, 0, mBounds.width().toInt(), mBounds.height().toInt(), cornerRadius)
} else {
outline.setRect(0, 0, mBounds.width().toInt(), mBounds.height().toInt())
}
} else {
// Clipping is not supported when using a convex path, but drawing the elevation
// shadow is. For the particular case, we fallback to canvas clipping in the view
// which is supposed to call `clipCanvasIfNeeded` in its `draw` method.
updateConvexPathIfNeeded()
outline.setConvexPath(mConvexPath)
}
}
fun clipCanvasIfNeeded(canvas: Canvas, view: View) {
updateBoundsAndLayoutDirection(view)
updateCornerRadiiIfNeeded()
if (!hasEqualCorners()) {
updateConvexPathIfNeeded()
canvas.clipPath(mConvexPath)
}
}
}
| bsd-3-clause | e302a17d43fc92da572b38784064c1bc | 30.130653 | 101 | 0.708636 | 3.996774 | false | true | false | false |
Heiner1/AndroidAPS | database/src/main/java/info/nightscout/androidaps/database/daos/ProfileSwitchDao.kt | 1 | 4494 | package info.nightscout.androidaps.database.daos
import androidx.room.Dao
import androidx.room.Query
import info.nightscout.androidaps.database.TABLE_PROFILE_SWITCHES
import info.nightscout.androidaps.database.daos.workaround.ProfileSwitchDaoWorkaround
import info.nightscout.androidaps.database.data.checkSanity
import info.nightscout.androidaps.database.entities.ProfileSwitch
import io.reactivex.rxjava3.core.Maybe
import io.reactivex.rxjava3.core.Single
@Suppress("FunctionName")
@Dao
internal interface ProfileSwitchDao : ProfileSwitchDaoWorkaround {
@Query("SELECT * FROM $TABLE_PROFILE_SWITCHES WHERE id = :id")
override fun findById(id: Long): ProfileSwitch?
@Query("DELETE FROM $TABLE_PROFILE_SWITCHES")
override fun deleteAllEntries()
@Query("SELECT id FROM $TABLE_PROFILE_SWITCHES ORDER BY id DESC limit 1")
fun getLastId(): Maybe<Long>
@Query("SELECT * FROM $TABLE_PROFILE_SWITCHES WHERE timestamp = :timestamp AND referenceId IS NULL")
fun findByTimestamp(timestamp: Long): ProfileSwitch?
@Query("SELECT * FROM $TABLE_PROFILE_SWITCHES WHERE nightscoutId = :nsId AND referenceId IS NULL")
fun findByNSId(nsId: String): ProfileSwitch?
@Query("SELECT * FROM $TABLE_PROFILE_SWITCHES WHERE timestamp <= :timestamp AND (timestamp + duration) > :timestamp AND referenceId IS NULL AND isValid = 1 ORDER BY timestamp DESC LIMIT 1")
fun getTemporaryProfileSwitchActiveAt(timestamp: Long): Maybe<ProfileSwitch>
@Query("SELECT * FROM $TABLE_PROFILE_SWITCHES WHERE timestamp <= :timestamp AND duration = 0 AND referenceId IS NULL AND isValid = 1 ORDER BY timestamp DESC LIMIT 1")
fun getPermanentProfileSwitchActiveAt(timestamp: Long): Maybe<ProfileSwitch>
@Query("SELECT * FROM $TABLE_PROFILE_SWITCHES WHERE referenceId IS NULL AND isValid = 1 ORDER BY timestamp DESC LIMIT 1")
fun getAllProfileSwitches(): Single<List<ProfileSwitch>>
@Query("SELECT * FROM $TABLE_PROFILE_SWITCHES WHERE timestamp >= :timestamp AND referenceId IS NULL ORDER BY timestamp ASC")
fun getProfileSwitchDataIncludingInvalidFromTime(timestamp: Long): Single<List<ProfileSwitch>>
@Query("SELECT * FROM $TABLE_PROFILE_SWITCHES WHERE timestamp >= :timestamp AND isValid = 1 AND referenceId IS NULL ORDER BY timestamp ASC")
fun getProfileSwitchDataFromTime(timestamp: Long): Single<List<ProfileSwitch>>
// This query will be used with v3 to get all changed records
@Query("SELECT * FROM $TABLE_PROFILE_SWITCHES WHERE id > :id AND referenceId IS NULL OR id IN (SELECT DISTINCT referenceId FROM $TABLE_PROFILE_SWITCHES WHERE id > :id) ORDER BY id ASC")
fun getModifiedFrom(id: Long): Single<List<ProfileSwitch>>
// for WS we need 1 record only
@Query("SELECT * FROM $TABLE_PROFILE_SWITCHES WHERE id > :id ORDER BY id ASC limit 1")
fun getNextModifiedOrNewAfter(id: Long): Maybe<ProfileSwitch>
@Query("SELECT * FROM $TABLE_PROFILE_SWITCHES WHERE id = :referenceId")
fun getCurrentFromHistoric(referenceId: Long): Maybe<ProfileSwitch>
@Query("SELECT * FROM $TABLE_PROFILE_SWITCHES WHERE dateCreated > :since AND dateCreated <= :until LIMIT :limit OFFSET :offset")
suspend fun getNewEntriesSince(since: Long, until: Long, limit: Int, offset: Int): List<ProfileSwitch>
}
internal fun ProfileSwitchDao.insertNewEntryImpl(entry: ProfileSwitch): Long {
if (!entry.basalBlocks.checkSanity()) throw IllegalArgumentException("Sanity check failed for basal blocks.")
if (!entry.icBlocks.checkSanity()) throw IllegalArgumentException("Sanity check failed for IC blocks.")
if (!entry.isfBlocks.checkSanity()) throw IllegalArgumentException("Sanity check failed for ISF blocks.")
if (!entry.targetBlocks.checkSanity()) throw IllegalArgumentException("Sanity check failed for target blocks.")
return (this as TraceableDao<ProfileSwitch>).insertNewEntryImpl(entry)
}
internal fun ProfileSwitchDao.updateExistingEntryImpl(entry: ProfileSwitch): Long {
if (!entry.basalBlocks.checkSanity()) throw IllegalArgumentException("Sanity check failed for basal blocks.")
if (!entry.icBlocks.checkSanity()) throw IllegalArgumentException("Sanity check failed for IC blocks.")
if (!entry.isfBlocks.checkSanity()) throw IllegalArgumentException("Sanity check failed for ISF blocks.")
if (!entry.targetBlocks.checkSanity()) throw IllegalArgumentException("Sanity check failed for target blocks.")
return (this as TraceableDao<ProfileSwitch>).updateExistingEntryImpl(entry)
} | agpl-3.0 | 24e71959ab1e001c77d6637a930d91e3 | 58.933333 | 193 | 0.76947 | 4.585714 | false | false | false | false |
auth0/Auth0.Android | auth0/src/test/java/com/auth0/android/request/internal/CredentialsGsonTest.kt | 1 | 7791 | package com.auth0.android.request.internal
import com.auth0.android.request.internal.GsonProvider.formatDate
import com.auth0.android.result.Credentials
import com.auth0.android.result.CredentialsMock
import com.google.gson.JsonParseException
import org.hamcrest.CoreMatchers
import org.hamcrest.MatcherAssert
import org.hamcrest.Matchers
import org.junit.Assert
import org.junit.Before
import org.junit.Test
import java.io.IOException
import java.io.Reader
import java.io.StringReader
import java.util.*
public class CredentialsGsonTest : GsonBaseTest() {
@Before
public fun setUp() {
gson = GsonProvider.gson
}
@Test
@Throws(Exception::class)
public fun shouldFailWithInvalidJson() {
Assert.assertThrows(JsonParseException::class.java) {
buildCredentialsFrom(json(INVALID))
}
}
@Test
@Throws(Exception::class)
public fun shouldFailWithEmptyJson() {
Assert.assertThrows(JsonParseException::class.java) {
buildCredentialsFrom(json(EMPTY_OBJECT))
}
}
@Test
@Throws(Exception::class)
public fun shouldNotRequireRefreshToken() {
buildCredentialsFrom(
StringReader(
"""{
"access_token": "s6GS5FGJN2jfd4l6",
"id_token": "s6GS5FGJN2jfd4l6",
"token_type": "bearer",
"expires_in": 86000,
"scope": "openid"
}""".trimIndent()
)
)
}
@Test
@Throws(Exception::class)
public fun shouldNotRequireScope() {
buildCredentialsFrom(
StringReader(
"""{
"access_token": "s6GS5FGJN2jfd4l6",
"id_token": "s6GS5FGJN2jfd4l6",
"token_type": "bearer",
"expires_in": 86000,
"refresh_token": "openid"
}""".trimIndent()
)
)
}
@Test
@Throws(Exception::class)
public fun shouldReturnBasic() {
val credentials = buildCredentialsFrom(json(OPENID_CREDENTIALS))
MatcherAssert.assertThat(credentials, Matchers.`is`(Matchers.notNullValue()))
MatcherAssert.assertThat(credentials.accessToken, Matchers.`is`(Matchers.notNullValue()))
MatcherAssert.assertThat(credentials.idToken, Matchers.`is`(Matchers.notNullValue()))
MatcherAssert.assertThat(credentials.type, Matchers.equalTo("bearer"))
MatcherAssert.assertThat(credentials.refreshToken, Matchers.`is`(Matchers.nullValue()))
MatcherAssert.assertThat(credentials.expiresAt, Matchers.`is`(Matchers.notNullValue()))
MatcherAssert.assertThat(credentials.scope, Matchers.`is`(Matchers.nullValue()))
}
@Test
@Throws(Exception::class)
public fun shouldReturnWithExpiresAt() {
val cal = Calendar.getInstance()
cal.add(Calendar.DAY_OF_YEAR, 1)
val exp = cal.time
val credentialsJSON = generateJSONWithExpiresAt(exp)
val credentials = buildCredentialsFrom(StringReader(credentialsJSON))
MatcherAssert.assertThat(credentials, Matchers.`is`(Matchers.notNullValue()))
MatcherAssert.assertThat(credentials.accessToken, Matchers.`is`(Matchers.notNullValue()))
MatcherAssert.assertThat(credentials.type, Matchers.equalTo("bearer"))
//The hardcoded value comes from the JSON file
MatcherAssert.assertThat(credentials.expiresAt, Matchers.`is`(Matchers.notNullValue()))
val expiresAt = credentials.expiresAt.time.toDouble()
MatcherAssert.assertThat(
expiresAt,
Matchers.`is`(Matchers.closeTo(exp.time.toDouble(), 1.0))
)
}
@Test
@Throws(Exception::class)
public fun shouldReturnWithRefreshToken() {
val credentials = buildCredentialsFrom(json(OPENID_OFFLINE_ACCESS_CREDENTIALS))
MatcherAssert.assertThat(credentials, Matchers.`is`(Matchers.notNullValue()))
MatcherAssert.assertThat(credentials.accessToken, Matchers.`is`(Matchers.notNullValue()))
MatcherAssert.assertThat(credentials.idToken, Matchers.`is`(Matchers.notNullValue()))
MatcherAssert.assertThat(credentials.type, Matchers.equalTo("bearer"))
MatcherAssert.assertThat(credentials.refreshToken, Matchers.`is`(Matchers.notNullValue()))
MatcherAssert.assertThat(credentials.expiresAt, Matchers.`is`(Matchers.notNullValue()))
MatcherAssert.assertThat(credentials.scope, Matchers.`is`("openid profile"))
}
@Test
public fun shouldSerializeCredentials() {
val expiresAt = Date(CredentialsMock.CURRENT_TIME_MS + 123456 * 1000)
val expectedExpiresAt = formatDate(expiresAt)
val expiresInCredentials: Credentials =
CredentialsMock("id", "access", "ty", "refresh", expiresAt, null)
val expiresInJson = gson.toJson(expiresInCredentials)
MatcherAssert.assertThat(expiresInJson, CoreMatchers.containsString("\"id_token\":\"id\""))
MatcherAssert.assertThat(
expiresInJson,
CoreMatchers.containsString("\"access_token\":\"access\"")
)
MatcherAssert.assertThat(
expiresInJson,
CoreMatchers.containsString("\"token_type\":\"ty\"")
)
MatcherAssert.assertThat(
expiresInJson,
CoreMatchers.containsString("\"refresh_token\":\"refresh\"")
)
MatcherAssert.assertThat(
expiresInJson,
CoreMatchers.not(CoreMatchers.containsString("\"expires_in\""))
)
MatcherAssert.assertThat(
expiresInJson, CoreMatchers.containsString(
"\"expires_at\":\"$expectedExpiresAt\""
)
)
MatcherAssert.assertThat(
expiresInJson,
CoreMatchers.not(CoreMatchers.containsString("\"scope\""))
)
val expiresAtCredentials: Credentials =
CredentialsMock("id", "access", "ty", "refresh", expiresAt, "openid")
val expiresAtJson = gson.toJson(expiresAtCredentials)
MatcherAssert.assertThat(expiresAtJson, CoreMatchers.containsString("\"id_token\":\"id\""))
MatcherAssert.assertThat(
expiresAtJson,
CoreMatchers.containsString("\"access_token\":\"access\"")
)
MatcherAssert.assertThat(
expiresAtJson,
CoreMatchers.containsString("\"token_type\":\"ty\"")
)
MatcherAssert.assertThat(
expiresAtJson,
CoreMatchers.containsString("\"refresh_token\":\"refresh\"")
)
MatcherAssert.assertThat(
expiresAtJson,
CoreMatchers.not(CoreMatchers.containsString("\"expires_in\""))
)
MatcherAssert.assertThat(
expiresInJson, CoreMatchers.containsString(
"\"expires_at\":\"$expectedExpiresAt\""
)
)
MatcherAssert.assertThat(expiresAtJson, CoreMatchers.containsString("\"scope\":\"openid\""))
}
@Throws(IOException::class)
private fun buildCredentialsFrom(json: Reader): Credentials {
return pojoFrom(json, Credentials::class.java)
}
private fun generateJSONWithExpiresAt(expiresAt: Date): String {
return """
{
"access_token": "s6GS5FGJN2jfd4l6",
"id_token": "s6GS5FGJN2jfd4l6",
"token_type": "bearer",
"expires_in": 86000,
"expires_at": "${formatDate(expiresAt)}"
}
""".trimIndent()
}
private companion object {
private const val OPENID_OFFLINE_ACCESS_CREDENTIALS =
"src/test/resources/credentials_openid_refresh_token.json"
private const val OPENID_CREDENTIALS = "src/test/resources/credentials_openid.json"
}
} | mit | a8164f832a13387ee9e3afd9440d2df6 | 37.766169 | 100 | 0.640098 | 4.909263 | false | true | false | false |
Adventech/sabbath-school-android-2 | common/design-compose/src/main/kotlin/app/ss/design/compose/widget/list/SnappingLazyRow.kt | 1 | 2531 | /*
* Copyright (c) 2022. Adventech <[email protected]>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
@file:OptIn(ExperimentalSnapperApi::class)
package app.ss.design.compose.widget.list
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.lazy.LazyListScope
import androidx.compose.foundation.lazy.LazyListState
import androidx.compose.foundation.lazy.LazyRow
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import dev.chrisbanes.snapper.ExperimentalSnapperApi
import dev.chrisbanes.snapper.SnapOffsets
import dev.chrisbanes.snapper.rememberSnapperFlingBehavior
@Composable
fun SnappingLazyRow(
modifier: Modifier = Modifier,
state: LazyListState = rememberLazyListState(),
contentPadding: PaddingValues = PaddingValues(0.dp),
reverseLayout: Boolean = false,
horizontalArrangement: Arrangement.Horizontal = if (reverseLayout) Arrangement.End else Arrangement.Start,
content: LazyListScope.() -> Unit
) {
LazyRow(
state = state,
flingBehavior = rememberSnapperFlingBehavior(
lazyListState = state,
snapOffsetForItem = SnapOffsets.Start
),
contentPadding = contentPadding,
horizontalArrangement = horizontalArrangement,
modifier = modifier,
content = content
)
}
| mit | fbb1677f1a70c35a22586618431fe07a | 41.183333 | 110 | 0.769261 | 4.757519 | false | false | false | false |
Maccimo/intellij-community | plugins/markdown/core/src/org/intellij/plugins/markdown/lang/psi/MarkdownAstFactory.kt | 2 | 1477 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.intellij.plugins.markdown.lang.psi
import com.intellij.lang.ASTFactory
import com.intellij.psi.impl.source.tree.CompositeElement
import com.intellij.psi.impl.source.tree.LeafElement
import com.intellij.psi.tree.IElementType
import org.intellij.plugins.markdown.lang.MarkdownElementTypes
import org.intellij.plugins.markdown.lang.MarkdownTokenTypes
import org.intellij.plugins.markdown.lang.psi.impl.*
import org.jetbrains.annotations.ApiStatus
@ApiStatus.Internal
class MarkdownAstFactory: ASTFactory() {
override fun createComposite(type: IElementType): CompositeElement? {
return when (type) {
MarkdownElementTypes.CODE_FENCE -> MarkdownCodeFence(type)
MarkdownElementTypes.FRONT_MATTER_HEADER -> MarkdownFrontMatterHeader(type)
else -> super.createComposite(type)
}
}
override fun createLeaf(type: IElementType, text: CharSequence): LeafElement? {
return when {
type == MarkdownTokenTypes.LIST_NUMBER -> MarkdownListNumber(type, text)
type == MarkdownTokenTypes.CODE_FENCE_CONTENT -> MarkdownCodeFenceContent(type, text)
type == MarkdownElementTypes.FRONT_MATTER_HEADER_CONTENT -> MarkdownFrontMatterHeaderContent(type, text)
type == MarkdownTokenTypes.TABLE_SEPARATOR && text.length > 1 -> MarkdownTableSeparatorRow(text)
else -> super.createLeaf(type, text)
}
}
}
| apache-2.0 | ce1d8f91e7e907de03fb49a49f1eeb27 | 45.15625 | 120 | 0.77522 | 4.408955 | false | false | false | false |
PolymerLabs/arcs | java/arcs/core/policy/PolicyConstraints.kt | 1 | 6038 | package arcs.core.policy
import arcs.core.data.AccessPath
import arcs.core.data.Check
import arcs.core.data.Claim
import arcs.core.data.InformationFlowLabel.Predicate
import arcs.core.data.InformationFlowLabel.SemanticTag
import arcs.core.data.ParticleSpec
import arcs.core.data.Recipe
/**
* Additional checks and claims that should be added to the particles in a recipe, which together
* are used to enforce that it complies with a policy.
*/
data class PolicyConstraints(
val policy: Policy,
val egressCheck: Predicate,
/** Maps from schema name to a list of claims to apply to stores of that type. */
val claims: Map<String, List<SelectorClaim>>
)
/** Equivalent to a [Claim.Assume] object, but without an [AccessPath.Root]. */
data class SelectorClaim(val selectors: List<AccessPath.Selector>, val predicate: Predicate) {
/** Converts the [SelectorClaim] to a [Claim] rooted at the given [handle]. */
fun inflate(handle: Recipe.Handle): Claim {
return Claim.Assume(AccessPath(handle, selectors), predicate)
}
}
/**
* Translates the given [policy] into dataflow analysis checks and claims, which are to be added to
* the particles from the given [recipe].
*
* @return additional checks and claims for the particles as a [PolicyConstraints] object
* @throws PolicyViolation if the [particles] violate the [policy]
*/
fun translatePolicy(policy: Policy): PolicyConstraints {
// Compute the predicate that will enforce the policy at an egress.
val egressCheckPredicate = createEgressCheckPredicate(policy)
// Add claim statements for stores.
val claims = policy.targets.associate { target -> target.schemaName to target.createClaims() }
return PolicyConstraints(policy, egressCheckPredicate, claims)
}
/** Returns a list of store [Claim]s for the given [handle] and corresponding [target]. */
private fun PolicyTarget.createClaims(): List<SelectorClaim> {
return fields.flatMap { field -> field.createClaims() }
}
/**
* Returns a list of claims for the given [field] (and all subfields), using the given [handle]
* as the root for the claims.
*/
private fun PolicyField.createClaims(): List<SelectorClaim> {
val claims = mutableListOf<SelectorClaim>()
// Create claim for this field.
createStoreClaimPredicate()?.let { predicate ->
val selectors = fieldPath.map { AccessPath.Selector.Field(it) }
claims.add(SelectorClaim(selectors, predicate))
}
// Add claims for subfields.
subfields.flatMapTo(claims) { subfield -> subfield.createClaims() }
return claims
}
/**
* Constructs the [Predicate] for the given [field] in a [Policy], to be used in constructing
* [Claim]s on the corresponding handles for the field in a recipe.
*/
private fun PolicyField.createStoreClaimPredicate(): Predicate? {
val predicates = mutableListOf<Predicate>()
if (rawUsages.canEgress()) {
predicates.add(labelPredicate(ALLOWED_FOR_EGRESS_LABEL))
}
val egressRedactionLabels = redactedUsages.filterValues { it.canEgress() }.keys
egressRedactionLabels.forEach { label ->
predicates.add(labelPredicate("${ALLOWED_FOR_EGRESS_LABEL}_$label"))
}
return when (predicates.size) {
0 -> null
1 -> predicates.single()
else -> Predicate.and(*predicates.toTypedArray())
}
}
/**
* Constructs the [Predicate] that is to be used for checks on egress particles in the given
* [Policy].
*
* For policies which don't require any redaction labels, the check is a simple one of the form
* `check x is allowedForEgress`.
*
* For policies with redaction labels (e.g. `label1`, `label2`, `label3`), the check looks so:
* ```
* check x is allowedForEgress
* or (is allowedForEgress_label1 and is label1)
* or (is allowedForEgress_label2 and is label2)
* or (is allowedForEgress_label3 and is label3)
* ```
*/
private fun createEgressCheckPredicate(policy: Policy): Predicate {
val allowedForEgress = labelPredicate(ALLOWED_FOR_EGRESS_LABEL)
if (policy.allRedactionLabels.isEmpty()) {
return allowedForEgress
}
// List of predicates of the form: allowedForEgress_X AND X.
val labelPredicates = policy.allRedactionLabels.sorted().map { label ->
labelPredicate("${ALLOWED_FOR_EGRESS_LABEL}_$label") and labelPredicate(label)
}
// OR the predicates for each redaction label together.
return Predicate.or(allowedForEgress, *labelPredicates.toTypedArray())
}
private fun labelPredicate(label: String) = Predicate.Label(SemanticTag(label))
const val ALLOWED_FOR_EGRESS_LABEL = "allowedForEgress"
/** Indicates that a policy was violated by a recipe. */
sealed class PolicyViolation(val policy: Policy, message: String) : Exception(
"Policy ${policy.name} violated: $message"
) {
/** Thrown when egress particles were found in the recipe that are not allowed by policy. */
class InvalidEgressTypeForParticles(
policy: Policy,
val invalidEgressParticles: List<ParticleSpec>
) : PolicyViolation(
policy,
"Invalid egress types found for particles: " +
invalidEgressParticles.namesAndEgressTypes() +
". Egress type allowed by policy: ${policy.egressType}."
)
/** Thrown when policy checks are violated by a recipe. */
class ChecksViolated(
policy: Policy,
checks: List<Check>
) : PolicyViolation(policy, "Recipe violates egress checks: $checks")
/** Thrown when a recipe is missing the `@policy` annotation. */
class MissingPolicyAnnotation(recipe: Recipe, policy: Policy) : PolicyViolation(
policy,
"Recipe '${recipe.name}' does not have an @policy annotation."
)
/** Thrown when a recipe was checked against a mismatched policy. */
class MismatchedPolicyName(electedPolicyName: String, policy: Policy) : PolicyViolation(
policy,
"Recipe elected a policy named '$electedPolicyName'."
)
}
/** Converts a list of particles into their names and egress types, as a string. */
private fun List<ParticleSpec>.namesAndEgressTypes(): String {
return sortedBy { it.name }.joinToString(prefix = "{", postfix = "}") {
"${it.name} (${it.egressType})"
}
}
| bsd-3-clause | ad3c0962f7ff235c3e323bf536bc7bb5 | 36.271605 | 99 | 0.731037 | 4.028019 | false | false | false | false |
JakeWharton/byteunits | src/jvmMain/kotlin/com/jakewharton/byteunits/BitUnit.kt | 1 | 9064 | package com.jakewharton.byteunits
import java.text.DecimalFormat
import java.text.NumberFormat
/**
* A [BitUnit] represents bit size at a given unit of granularity and provides utility
* methods to convert across units. A [BitUnit] does not maintain bit size information,
* but only helps organize and use bit size representations that may be maintained separately
* across various contexts.
*/
enum class BitUnit : ByteUnit {
/** Bit unit representing one bit. */
BITS {
override fun convert(sourceCount: Long, sourceUnit: BitUnit): Long =
sourceUnit.toBits(sourceCount)
override fun toBytes(count: Long): Long =
count / BYTE
override fun toBits(count: Long): Long =
count
override fun toKilobits(count: Long): Long =
count / (KB / B)
override fun toMegabits(count: Long): Long =
count / (MB / B)
override fun toGigabits(count: Long): Long =
count / (GB / B)
override fun toTerabits(count: Long): Long =
count / (TB / B)
override fun toPetabits(count: Long): Long =
count / (PB / B)
},
/** A bit unit representing 1000 bits. */
KILOBITS {
override fun convert(sourceCount: Long, sourceUnit: BitUnit): Long =
sourceUnit.toKilobits(sourceCount)
override fun toBytes(count: Long): Long =
count * KBYTE
override fun toBits(count: Long): Long =
checkedMultiply(count, KB / B, MAX / (KB / B))
override fun toKilobits(count: Long): Long =
count
override fun toMegabits(count: Long): Long =
count / (MB / KB)
override fun toGigabits(count: Long): Long =
count / (GB / KB)
override fun toTerabits(count: Long): Long =
count / (TB / KB)
override fun toPetabits(count: Long): Long =
count / (PB / KB)
},
/** A bit unit representing 1000 kilobits. */
MEGABITS {
override fun convert(sourceCount: Long, sourceUnit: BitUnit): Long =
sourceUnit.toMegabits(sourceCount)
override fun toBytes(count: Long): Long =
count * MBYTE
override fun toBits(count: Long): Long =
checkedMultiply(count, MB / B, MAX / (MB / B))
override fun toKilobits(count: Long): Long =
checkedMultiply(count, MB / KB, MAX / (MB / KB))
override fun toMegabits(count: Long): Long =
count
override fun toGigabits(count: Long): Long =
count / (GB / MB)
override fun toTerabits(count: Long): Long =
count / (TB / MB)
override fun toPetabits(count: Long): Long =
count / (PB / MB)
},
/** A bit unit representing 1000 megabits. */
GIGABITS {
override fun convert(sourceCount: Long, sourceUnit: BitUnit): Long =
sourceUnit.toGigabits(sourceCount)
override fun toBytes(count: Long): Long =
count * GBYTE
override fun toBits(count: Long): Long =
checkedMultiply(count, GB / B, MAX / (GB / B))
override fun toKilobits(count: Long): Long =
checkedMultiply(count, GB / KB, MAX / (GB / KB))
override fun toMegabits(count: Long): Long =
checkedMultiply(count, GB / MB, MAX / (GB / MB))
override fun toGigabits(count: Long): Long =
count
override fun toTerabits(count: Long): Long =
count / (TB / GB)
override fun toPetabits(count: Long): Long =
count / (PB / GB)
},
/** A bit unit representing 1000 gigabits. */
TERABITS {
override fun convert(sourceCount: Long, sourceUnit: BitUnit): Long =
sourceUnit.toTerabits(sourceCount)
override fun toBytes(count: Long): Long =
count * TBYTE
override fun toBits(count: Long): Long =
checkedMultiply(count, TB / B, MAX / (TB / B))
override fun toKilobits(count: Long): Long =
checkedMultiply(count, TB / KB, MAX / (TB / KB))
override fun toMegabits(count: Long): Long =
checkedMultiply(count, TB / MB, MAX / (TB / MB))
override fun toGigabits(count: Long): Long =
checkedMultiply(count, TB / GB, MAX / (TB / GB))
override fun toTerabits(count: Long): Long =
count
override fun toPetabits(count: Long): Long =
count / (PB / TB)
},
/** A bit unit representing 1000 terabits. */
PETABITS {
override fun convert(sourceCount: Long, sourceUnit: BitUnit): Long =
sourceUnit.toPetabits(sourceCount)
override fun toBytes(count: Long): Long =
count * PBYTE
override fun toBits(count: Long): Long =
checkedMultiply(count, PB / B, MAX / (PB / B))
override fun toKilobits(count: Long): Long =
checkedMultiply(count, PB / KB, MAX / (PB / KB))
override fun toMegabits(count: Long): Long =
checkedMultiply(count, PB / MB, MAX / (PB / MB))
override fun toGigabits(count: Long): Long =
checkedMultiply(count, PB / GB, MAX / (PB / GB))
override fun toTerabits(count: Long): Long =
checkedMultiply(count, PB / TB, MAX / (PB / TB))
override fun toPetabits(count: Long): Long =
count
};
/**
* Converts the given size in the given unit to this unit. Conversions from finer to coarser
* granularities truncate, so lose precision. For example, converting from `999` bit to
* kilobits results in `0`. Conversions from coarser to finer granularities with arguments
* that would numerically overflow saturate to [Long.MIN_VALUE] if negative or
* [Long.MAX_VALUE] if positive.
*
*
* For example, to convert 10 kilobytes to bytes, use:
* `ByteUnit.KILOBITS.convert(10, ByteUnit.BITS)`
*
* [sourceCount] the size in the given [sourceUnit].
* [sourceUnit] the unit of the [sourceCount] argument.
* @return the converted size in this unit, or [Long.MIN_VALUE] if conversion would
* negatively overflow, or [Long.MAX_VALUE] if it would positively overflow.
*/
abstract fun convert(sourceCount: Long, sourceUnit: BitUnit): Long
/**
* Equivalent to [BITS.convert(count, this)][convert].
* [count] the bit count
* @return the converted count, or [Long.MIN_VALUE] if conversion would negatively
* overflow, or [Long.MAX_VALUE] if it would positively overflow.
*/
abstract fun toBits(count: Long): Long
/**
* Equivalent to [KILOBITS.convert(count, this)][convert].
* [count] the bit count
* @return the converted count, or [Long.MIN_VALUE] if conversion would negatively
* overflow, or [Long.MAX_VALUE] if it would positively overflow.
*/
abstract fun toKilobits(count: Long): Long
/**
* Equivalent to [MEGABITS.convert(count, this)][convert].
* [count] the bit count
* @return the converted count, or [Long.MIN_VALUE] if conversion would negatively
* overflow, or [Long.MAX_VALUE] if it would positively overflow.
*/
abstract fun toMegabits(count: Long): Long
/**
* Equivalent to [GIGABITS.convert(count, this)][convert].
* [count] the bit count
* @return the converted count, or [Long.MIN_VALUE] if conversion would negatively
* overflow, or [Long.MAX_VALUE] if it would positively overflow.
*/
abstract fun toGigabits(count: Long): Long
/**
* Equivalent to [TERABITS.convert(count, this)][convert].
* [count] the bit count
* @return the converted count, or [Long.MIN_VALUE] if conversion would negatively
* overflow, or [Long.MAX_VALUE] if it would positively overflow.
*/
abstract fun toTerabits(count: Long): Long
/**
* Equivalent to [PETABITS.convert(count, this)][convert].
* [count] the bit count
* @return the converted count, or [Long.MIN_VALUE] if conversion would negatively
* overflow, or [Long.MAX_VALUE] if it would positively overflow.
*/
abstract fun toPetabits(count: Long): Long
companion object {
private const val B = 1L
private const val KB = B * 1000L
private const val MB = KB * 1000L
private const val GB = MB * 1000L
private const val TB = GB * 1000L
private const val PB = TB * 1000L
private const val BYTE = B * 8
private const val KBYTE = 1000L / BYTE
private const val MBYTE = KBYTE * 1000L
private const val GBYTE = MBYTE * 1000L
private const val TBYTE = GBYTE * 1000L
private const val PBYTE = TBYTE * 1000L
private const val MAX = Long.MAX_VALUE
private val UNITS = arrayOf("b", "Kb", "Mb", "Gb", "Tb", "Pb")
/**
* Return `bits` as human-readable size string (e.g., "1.2 Gb". This will use a
* [DecimalFormat] instance with [pattern] for formatting the number.
*/
fun format(bits: Long, pattern: String): String {
return format(bits, DecimalFormat(pattern))
}
/**
* Return `bits` as human-readable size string (e.g., "1.2 Gb". This will use a default
* [DecimalFormat] instance for formatting the number.
*/
@JvmOverloads fun format(
bits: Long,
format: NumberFormat = DecimalFormat(DEFAULT_FORMAT_PATTERN),
): String {
require(bits >= 0) { "bits < 0: $bits" }
var unitIndex = 0
var count = bits.toDouble()
while (count >= 1000.0 && unitIndex < UNITS.size - 1) {
count /= 1000.0
unitIndex += 1
}
return format.format(count) + ' ' + UNITS[unitIndex]
}
}
}
| apache-2.0 | fcdf0ef49152200f6326e65b583fce1b | 31.028269 | 94 | 0.649603 | 3.621254 | false | false | false | false |
Kaljurand/K6nele | app/src/main/java/ee/ioc/phon/android/speak/demo/ExtrasDemo.kt | 1 | 2139 | /*
* Copyright 2014, Institute of Cybernetics at Tallinn University of Technology
*
* 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 ee.ioc.phon.android.speak.demo
import android.content.Intent
import android.os.Bundle
import android.speech.RecognizerIntent
import ee.ioc.phon.android.speak.R
import ee.ioc.phon.android.speak.activity.DetailsActivity
import ee.ioc.phon.android.speechutils.Extras
import ee.ioc.phon.android.speechutils.utils.BundleUtils
class ExtrasDemo : AbstractRecognizerDemoActivity() {
public override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val intent = createRecognizerIntent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH)
if (getRecognizers(intent).size == 0) {
toast(getString(R.string.errorRecognizerNotPresent))
finish()
} else {
intent.putExtra(Extras.EXTRA_RETURN_ERRORS, true)
intent.putExtra(Extras.EXTRA_GET_AUDIO, true)
intent.putExtra(Extras.EXTRA_GET_AUDIO_FORMAT, null as String?)
//intent.putExtra(Extras.EXTRA_GET_AUDIO_FORMAT, Constants.SUPPORTED_AUDIO_FORMATS.iterator().next());
launchRecognizerIntent(intent)
}
}
/**
* Show the resulting extras
*/
override fun onSuccess(intent: Intent?) {
val list = BundleUtils.ppBundle(intent?.extras)
val details = Intent(this, DetailsActivity::class.java)
details.data = intent?.data
details.putExtra(DetailsActivity.EXTRA_STRING_ARRAY, list.toTypedArray())
startActivity(details)
finish()
}
} | apache-2.0 | 0ce8445590909b02a374f49262c2b204 | 35.896552 | 114 | 0.71108 | 4.194118 | false | false | false | false |
mdaniel/intellij-community | python/src/com/jetbrains/python/codeInsight/mlcompletion/PyImportCompletionFeatures.kt | 13 | 1873 | // Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.jetbrains.python.codeInsight.mlcompletion
import com.intellij.codeInsight.completion.CompletionLocation
import com.intellij.codeInsight.lookup.LookupElement
import com.intellij.psi.PsiElement
import com.jetbrains.python.codeInsight.completion.hasImportsFrom
import com.jetbrains.python.psi.PyImportElement
import com.jetbrains.python.psi.PyImportStatement
import com.jetbrains.python.psi.PyReferenceExpression
import com.jetbrains.python.psi.resolve.QualifiedNameFinder
object PyImportCompletionFeatures {
data class ElementImportPathFeatures (val isImported: Boolean,
val numPrivateComponents: Int,
val numComponents: Int)
fun getElementImportPathFeatures(element: LookupElement, location: CompletionLocation): ElementImportPathFeatures? {
val psiElement = element.psiElement ?: return null
val importPath = QualifiedNameFinder.findShortestImportableQName(psiElement.containingFile) ?: return null
val caretLocationFile = location.completionParameters.originalFile
val isImported = hasImportsFrom(caretLocationFile, importPath)
val numComponents = importPath.componentCount
val numPrivateComponents = importPath.components.count{ it.startsWith("_") }
return ElementImportPathFeatures(isImported, numPrivateComponents, numComponents)
}
fun getImportPopularityFeature(locationPsi: PsiElement, lookupString: String): Int? {
if (locationPsi.parent !is PyReferenceExpression) return null
if (locationPsi.parent.parent !is PyImportElement) return null
if (locationPsi.parent.parent.parent !is PyImportStatement) return null
return PyMlCompletionHelpers.importPopularity[lookupString]
}
} | apache-2.0 | 9bbbedac5a1193148bbff9f8b46c13a9 | 54.117647 | 140 | 0.789642 | 5.075881 | false | false | false | false |
square/picasso | picasso-sample/src/main/java/com/example/picasso/SampleContactsAdapter.kt | 1 | 2279 | /*
* Copyright (C) 2013 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.example.picasso
import android.content.Context
import android.database.Cursor
import android.provider.ContactsContract.Contacts
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.QuickContactBadge
import android.widget.TextView
import androidx.cursoradapter.widget.CursorAdapter
import com.example.picasso.SampleContactsActivity.ContactsQuery
internal class SampleContactsAdapter(context: Context) : CursorAdapter(context, null, 0) {
private val inflater = LayoutInflater.from(context)
override fun newView(
context: Context,
cursor: Cursor,
viewGroup: ViewGroup
): View {
val itemLayout = inflater.inflate(R.layout.sample_contacts_activity_item, viewGroup, false)
itemLayout.tag = ViewHolder(
text1 = itemLayout.findViewById(android.R.id.text1),
icon = itemLayout.findViewById(android.R.id.icon)
)
return itemLayout
}
override fun bindView(
view: View,
context: Context,
cursor: Cursor
) {
val contactUri = Contacts.getLookupUri(
cursor.getLong(ContactsQuery.ID),
cursor.getString(ContactsQuery.LOOKUP_KEY)
)
val holder = (view.tag as ViewHolder).apply {
text1.text = cursor.getString(ContactsQuery.DISPLAY_NAME)
icon.assignContactUri(contactUri)
}
PicassoInitializer.get()
.load(contactUri)
.placeholder(R.drawable.contact_picture_placeholder)
.tag(context)
.into(holder.icon)
}
override fun getCount(): Int {
return if (cursor == null) 0 else super.getCount()
}
private class ViewHolder(
val text1: TextView,
val icon: QuickContactBadge
)
}
| apache-2.0 | 680652cd49547cc00ff8c6ba79dae93d | 29.797297 | 95 | 0.733216 | 4.143636 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/RemoveFunctionBodyFix.kt | 4 | 2011 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.quickfix
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import org.jetbrains.kotlin.diagnostics.Diagnostic
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.codeinsight.api.classic.quickfixes.KotlinQuickFixAction
import org.jetbrains.kotlin.idea.util.CommentSaver
import org.jetbrains.kotlin.psi.KtFile
import org.jetbrains.kotlin.psi.KtFunction
import org.jetbrains.kotlin.psi.psiUtil.PsiChildRange
import org.jetbrains.kotlin.psi.psiUtil.getNonStrictParentOfType
class RemoveFunctionBodyFix(element: KtFunction) : KotlinQuickFixAction<KtFunction>(element) {
override fun getFamilyName() = KotlinBundle.message("remove.function.body")
override fun getText() = familyName
override fun isAvailable(project: Project, editor: Editor?, file: KtFile): Boolean {
val element = element ?: return false
return element.hasBody()
}
override fun invoke(project: Project, editor: Editor?, file: KtFile) {
val element = element ?: return
val bodyExpression = element.bodyExpression!!
val equalsToken = element.equalsToken
if (equalsToken != null) {
val commentSaver = CommentSaver(PsiChildRange(equalsToken.nextSibling, bodyExpression.prevSibling), true)
element.deleteChildRange(equalsToken, bodyExpression)
commentSaver.restore(element)
} else {
bodyExpression.delete()
}
}
companion object : KotlinSingleIntentionActionFactory() {
override fun createAction(diagnostic: Diagnostic): KotlinQuickFixAction<KtFunction>? {
val function = diagnostic.psiElement.getNonStrictParentOfType<KtFunction>() ?: return null
return RemoveFunctionBodyFix(function)
}
}
}
| apache-2.0 | f1db9aa2847af3db7537554493ffd48b | 43.688889 | 158 | 0.743909 | 4.990074 | false | false | false | false |
roylanceMichael/yaclib | core/src/main/java/org/roylance/yaclib/core/services/java/server/JavaLaunchBuilder.kt | 1 | 2322 | package org.roylance.yaclib.core.services.java.server
import org.roylance.common.service.IBuilder
import org.roylance.yaclib.YaclibModel
import org.roylance.yaclib.core.enums.CommonTokens
class JavaLaunchBuilder : IBuilder<YaclibModel.File> {
override fun build(): YaclibModel.File {
val returnFile = YaclibModel.File.newBuilder()
.setFileToWrite(ActualJavaFile)
.setFileName("Main")
.setFileExtension(YaclibModel.FileExtension.JAVA_EXT)
.setFileUpdateType(YaclibModel.FileUpdateType.WRITE_IF_NOT_EXISTS)
.setFullDirectoryLocation("src/main/java/launch")
return returnFile.build()
}
companion object {
private const val ActualJavaFile = """${CommonTokens.AutoGeneratedAlteringOkay}
package launch;
import org.apache.catalina.WebResourceRoot;
import org.apache.catalina.core.StandardContext;
import org.apache.catalina.startup.Tomcat;
import org.apache.catalina.webresources.DirResourceSet;
import org.apache.catalina.webresources.StandardRoot;
import java.io.File;
public class Main {
public static void main(String[] args) throws Exception {
final String webappDirLocation = "src/main/webapp/";
final Tomcat tomcat = new Tomcat();
//The port that we should run on can be set into an environment variable
//Look for that variable and default to 8080 if it isn't there.
String webPort = System.getenv("PORT");
if(webPort == null || webPort.isEmpty()) {
webPort = "8080";
}
tomcat.setPort(Integer.parseInt(webPort));
final StandardContext ctx = (StandardContext) tomcat.addWebapp("/", new File(webappDirLocation).getAbsolutePath());
System.out.println("configuring app with basedir: " + new File("./" + webappDirLocation).getAbsolutePath());
// Declare an alternative location for your "WEB-INF/classes" dir
// Servlet 3.0 annotation will work
final File additionWebInfClasses = new File("target/classes");
final WebResourceRoot resources = new StandardRoot(ctx);
resources.addPreResources(new DirResourceSet(resources, "/WEB-INF/classes",
additionWebInfClasses.getAbsolutePath(), "/"));
ctx.setResources(resources);
tomcat.start();
tomcat.getServer().await();
}
}
"""
}
} | mit | 45b0fcda41ac8965011d4c38921dd994 | 36.467742 | 123 | 0.70758 | 4.214156 | false | false | false | false |
ktorio/ktor | ktor-server/ktor-server-core/jvmAndNix/src/io/ktor/server/routing/Route.kt | 1 | 4864 | /*
* Copyright 2014-2019 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license.
*/
package io.ktor.server.routing
import io.ktor.server.application.*
import io.ktor.util.*
import io.ktor.util.collections.*
import io.ktor.util.pipeline.*
import io.ktor.utils.io.concurrent.*
/**
* Describes a node in a routing tree.
* @see [Application.routing]
*
* @param parent is a parent node in the tree, or null for root node.
* @param selector is an instance of [RouteSelector] for this node.
* @param developmentMode is flag to switch report level for stack traces.
*/
@Suppress("DEPRECATION")
@KtorDsl
public open class Route(
public val parent: Route?,
public val selector: RouteSelector,
developmentMode: Boolean = false,
environment: ApplicationEnvironment? = null
) : ApplicationCallPipeline(developmentMode, environment) {
/**
* Describes a node in a routing tree.
*
* @param parent is a parent node in the tree, or null for root node.
* @param selector is an instance of [RouteSelector] for this node.
*/
@Deprecated(message = "Please use constructor with developmentMode parameter", level = DeprecationLevel.HIDDEN)
public constructor(
parent: Route?,
selector: RouteSelector,
environment: ApplicationEnvironment? = null
) : this(parent, selector, developmentMode = false, environment = environment)
/**
* List of child routes for this node.
*/
public val children: List<Route> get() = childList
@OptIn(InternalAPI::class)
private val childList: MutableList<Route> = mutableListOf()
private var cachedPipeline: ApplicationCallPipeline? = null
@OptIn(InternalAPI::class)
internal val handlers = mutableListOf<PipelineInterceptor<Unit, ApplicationCall>>()
/**
* Creates a child node in this node with a given [selector] or returns an existing one with the same selector.
*/
public fun createChild(selector: RouteSelector): Route {
val existingEntry = childList.firstOrNull { it.selector == selector }
if (existingEntry == null) {
val entry = Route(this, selector, developmentMode, environment)
childList.add(entry)
return entry
}
return existingEntry
}
/**
* Allows using a route instance for building additional routes.
*/
public operator fun invoke(body: Route.() -> Unit): Unit = body()
/**
* Installs a handler into this route which is called when the route is selected for a call.
*/
public fun handle(handler: PipelineInterceptor<Unit, ApplicationCall>) {
handlers.add(handler)
// Adding a handler invalidates only pipeline for this entry
cachedPipeline = null
}
override fun afterIntercepted() {
// Adding an interceptor invalidates pipelines for all children
// We don't need synchronisation here, because order of intercepting and acquiring pipeline is indeterminate
// If some child already cached its pipeline, it's ok to execute with outdated pipeline
invalidateCachesRecursively()
}
private fun invalidateCachesRecursively() {
cachedPipeline = null
childList.forEach { it.invalidateCachesRecursively() }
}
internal fun buildPipeline(): ApplicationCallPipeline = cachedPipeline ?: run {
var current: Route? = this
val pipeline = ApplicationCallPipeline(developmentMode, application.environment)
val routePipelines = mutableListOf<ApplicationCallPipeline>()
while (current != null) {
routePipelines.add(current)
current = current.parent
}
for (index in routePipelines.lastIndex downTo 0) {
val routePipeline = routePipelines[index]
pipeline.merge(routePipeline)
pipeline.receivePipeline.merge(routePipeline.receivePipeline)
pipeline.sendPipeline.merge(routePipeline.sendPipeline)
}
val handlers = handlers
for (index in 0..handlers.lastIndex) {
pipeline.intercept(Call) {
if (call.isHandled) return@intercept
handlers[index].invoke(this, Unit)
}
}
cachedPipeline = pipeline
pipeline
}
override fun toString(): String {
return when (val parentRoute = parent?.toString()) {
null -> when (selector) {
is TrailingSlashRouteSelector -> "/"
else -> "/$selector"
}
else -> when (selector) {
is TrailingSlashRouteSelector -> if (parentRoute.endsWith('/')) parentRoute else "$parentRoute/"
else -> if (parentRoute.endsWith('/')) "$parentRoute$selector" else "$parentRoute/$selector"
}
}
}
}
| apache-2.0 | 539aeca4f5d7f9da42ce53439fcfe4f9 | 35.02963 | 119 | 0.656661 | 4.898288 | false | false | false | false |
emoji-gen/Emoji-Android | app/src/main/java/moe/pine/emoji/activity/SettingActivity.kt | 1 | 1731 | package moe.pine.emoji.activity
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.view.MenuItem
import kotlinx.android.synthetic.main.activity_setting.*
import moe.pine.emoji.R
import moe.pine.emoji.adapter.setting.SettingFragmentPagerAdapter
import moe.pine.emoji.components.common.ActionBarBackButtonComponent
import moe.pine.emoji.components.common.SupportActionBarComponent
/**
* Activity for Setting
* Created by pine on Apr 21, 2017.
*/
class SettingActivity : AppCompatActivity() {
companion object {
private val IS_FOCUS_KEY = "isFocus"
fun createIntent(context: Context, focus: Boolean = false): Intent {
return Intent(context, SettingActivity::class.java).also { intent ->
intent.putExtra(IS_FOCUS_KEY, focus)
}
}
}
private val actionBar by lazy { SupportActionBarComponent(this) }
private val backButton by lazy { ActionBarBackButtonComponent(this) }
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
this.setContentView(R.layout.activity_setting)
this.actionBar.onCreate()
val isFocus = this.intent.extras.getBoolean(IS_FOCUS_KEY, false)
val adapter = SettingFragmentPagerAdapter(this.supportFragmentManager, this, isFocus)
this.view_pager.adapter = adapter
this.view_pager.offscreenPageLimit = 2
this.tab_layout.setupWithViewPager(this.view_pager)
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
return this.backButton.onOptionsItemSelected(item) or super.onOptionsItemSelected(item)
}
} | mit | 84fb4fecbcde6315431091c0bd62f32d | 35.851064 | 95 | 0.735413 | 4.507813 | false | false | false | false |
dahlstrom-g/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/crossLanguage/KotlinElementActionsFactory.kt | 2 | 25383 | // 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.quickfix.crossLanguage
import com.intellij.codeInsight.daemon.QuickFixBundle
import com.intellij.codeInsight.intention.IntentionAction
import com.intellij.codeInsight.intention.QuickFixFactory
import com.intellij.lang.java.beans.PropertyKind
import com.intellij.lang.jvm.*
import com.intellij.lang.jvm.actions.*
import com.intellij.lang.jvm.types.JvmType
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.text.StringUtilRt
import com.intellij.psi.*
import com.intellij.psi.impl.source.tree.java.PsiReferenceExpressionImpl
import com.intellij.psi.util.PropertyUtil
import com.intellij.psi.util.PropertyUtilBase
import org.jetbrains.kotlin.asJava.classes.KtLightClassForFacade
import org.jetbrains.kotlin.asJava.classes.KtLightClassForSourceDeclaration
import org.jetbrains.kotlin.asJava.elements.KtLightElement
import org.jetbrains.kotlin.asJava.toLightMethods
import org.jetbrains.kotlin.asJava.unwrapped
import org.jetbrains.kotlin.descriptors.CallableDescriptor
import org.jetbrains.kotlin.descriptors.annotations.AnnotationUseSiteTarget
import org.jetbrains.kotlin.descriptors.annotations.KotlinTarget
import org.jetbrains.kotlin.descriptors.resolveClassByFqName
import org.jetbrains.kotlin.idea.KotlinBundle
import org.jetbrains.kotlin.idea.KotlinLanguage
import org.jetbrains.kotlin.idea.base.projectStructure.RootKindFilter
import org.jetbrains.kotlin.idea.base.projectStructure.matches
import org.jetbrains.kotlin.idea.caches.resolve.resolveToDescriptorIfAny
import org.jetbrains.kotlin.idea.core.ShortenReferences
import org.jetbrains.kotlin.idea.core.appendModifier
import org.jetbrains.kotlin.idea.quickfix.AddModifierFixFE10
import org.jetbrains.kotlin.idea.quickfix.MakeFieldPublicFix
import org.jetbrains.kotlin.idea.quickfix.MakeMemberStaticFix
import org.jetbrains.kotlin.idea.quickfix.RemoveModifierFixBase
import org.jetbrains.kotlin.idea.quickfix.createFromUsage.callableBuilder.TypeInfo
import org.jetbrains.kotlin.idea.resolve.ResolutionFacade
import org.jetbrains.kotlin.idea.util.CommentSaver
import org.jetbrains.kotlin.idea.util.IdeDescriptorRenderers
import org.jetbrains.kotlin.idea.util.resolveToKotlinType
import org.jetbrains.kotlin.incremental.components.NoLookupLocation
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.createSmartPointer
import org.jetbrains.kotlin.psi.psiUtil.visibilityModifierType
import org.jetbrains.kotlin.resolve.AnnotationChecker
import org.jetbrains.kotlin.resolve.annotations.JVM_STATIC_ANNOTATION_FQ_NAME
import org.jetbrains.kotlin.resolve.descriptorUtil.module
import org.jetbrains.kotlin.types.Variance
import org.jetbrains.kotlin.types.typeUtil.supertypes
import org.jetbrains.kotlin.utils.addToStdlib.safeAs
class KotlinElementActionsFactory : JvmElementActionsFactory() {
companion object {
val javaPsiModifiersMapping = mapOf(
JvmModifier.PRIVATE to KtTokens.PRIVATE_KEYWORD,
JvmModifier.PUBLIC to KtTokens.PUBLIC_KEYWORD,
JvmModifier.PROTECTED to KtTokens.PUBLIC_KEYWORD,
JvmModifier.ABSTRACT to KtTokens.ABSTRACT_KEYWORD
)
internal fun ExpectedTypes.toKotlinTypeInfo(resolutionFacade: ResolutionFacade): TypeInfo {
val candidateTypes = flatMapTo(LinkedHashSet()) {
val ktType = (it.theType as? PsiType)?.resolveToKotlinType(resolutionFacade) ?: return@flatMapTo emptyList()
when (it.theKind) {
ExpectedType.Kind.EXACT, ExpectedType.Kind.SUBTYPE -> listOf(ktType)
ExpectedType.Kind.SUPERTYPE -> listOf(ktType) + ktType.supertypes()
}
}
if (candidateTypes.isEmpty()) {
val nullableAnyType = resolutionFacade.moduleDescriptor.builtIns.nullableAnyType
return TypeInfo(nullableAnyType, Variance.INVARIANT)
}
return TypeInfo.ByExplicitCandidateTypes(candidateTypes.toList())
}
}
private class FakeExpressionFromParameter(private val psiParam: PsiParameter) : PsiReferenceExpressionImpl() {
override fun getText(): String = psiParam.name
override fun getProject(): Project = psiParam.project
override fun getParent(): PsiElement = psiParam.parent
override fun getType(): PsiType = psiParam.type
override fun isValid(): Boolean = true
override fun getContainingFile(): PsiFile = psiParam.containingFile
override fun getReferenceName(): String = psiParam.name
override fun resolve(): PsiElement = psiParam
}
internal class ModifierBuilder(
private val targetContainer: KtElement,
private val allowJvmStatic: Boolean = true
) {
private val psiFactory = KtPsiFactory(targetContainer.project)
val modifierList = psiFactory.createEmptyModifierList()
private fun JvmModifier.transformAndAppend(): Boolean {
javaPsiModifiersMapping[this]?.let {
modifierList.appendModifier(it)
return true
}
when (this) {
JvmModifier.STATIC -> {
if (allowJvmStatic && targetContainer is KtClassOrObject) {
addAnnotation(JVM_STATIC_ANNOTATION_FQ_NAME)
}
}
JvmModifier.ABSTRACT -> modifierList.appendModifier(KtTokens.ABSTRACT_KEYWORD)
JvmModifier.FINAL -> modifierList.appendModifier(KtTokens.FINAL_KEYWORD)
else -> return false
}
return true
}
var isValid = true
private set
fun addJvmModifier(modifier: JvmModifier) {
isValid = isValid && modifier.transformAndAppend()
}
fun addJvmModifiers(modifiers: Iterable<JvmModifier>) {
modifiers.forEach { addJvmModifier(it) }
}
fun addAnnotation(fqName: FqName) {
if (!isValid) return
modifierList.add(psiFactory.createAnnotationEntry("@${fqName.asString()}"))
}
}
private fun JvmClass.toKtClassOrFile(): KtElement? = when (val psi = sourceElement) {
is KtClassOrObject -> psi
is KtLightClassForSourceDeclaration -> psi.kotlinOrigin
is KtLightClassForFacade -> psi.files.firstOrNull()
else -> null
}
private inline fun <reified T : KtElement> JvmElement.toKtElement() = sourceElement?.unwrapped as? T
private fun fakeParametersExpressions(parameters: List<ExpectedParameter>, project: Project): Array<PsiExpression>? = when {
parameters.isEmpty() -> emptyArray()
else -> JavaPsiFacade
.getElementFactory(project)
.createParameterList(
parameters.map { it.semanticNames.firstOrNull() }.toTypedArray(),
parameters.map { param ->
param.expectedTypes.firstOrNull()?.theType?.let { type ->
JvmPsiConversionHelper.getInstance(project).convertType(type)
} ?: return null
}.toTypedArray()
)
.parameters
.map(::FakeExpressionFromParameter)
.toTypedArray()
}
override fun createChangeModifierActions(target: JvmModifiersOwner, request: ChangeModifierRequest): List<IntentionAction> {
val kModifierOwner =
target.toKtElement<KtModifierListOwner>()?.takeIf { RootKindFilter.projectSources.matches(it) } ?: return emptyList()
val modifier = request.modifier
val shouldPresent = request.shouldBePresent()
if (modifier == JvmModifier.PUBLIC && shouldPresent && kModifierOwner is KtProperty) {
return listOf(MakeFieldPublicFix(kModifierOwner))
}
if (modifier == JvmModifier.STATIC && shouldPresent && kModifierOwner is KtNamedDeclaration) {
return listOf(MakeMemberStaticFix(kModifierOwner))
}
//TODO: make similar to `createAddMethodActions`
val (kToken, shouldPresentMapped) = when {
modifier == JvmModifier.FINAL -> KtTokens.OPEN_KEYWORD to !shouldPresent
modifier == JvmModifier.PUBLIC && shouldPresent ->
kModifierOwner.visibilityModifierType()
?.takeIf { it != KtTokens.DEFAULT_VISIBILITY_KEYWORD }
?.let { it to false } ?: return emptyList()
else -> javaPsiModifiersMapping[modifier] to shouldPresent
}
if (kToken == null) return emptyList()
val action = if (shouldPresentMapped) {
AddModifierFixFE10.createIfApplicable(kModifierOwner, kToken)
} else {
RemoveModifierFixBase(kModifierOwner, kToken, false)
}
return listOfNotNull(action)
}
override fun createAddConstructorActions(targetClass: JvmClass, request: CreateConstructorRequest): List<IntentionAction> {
val targetKtClass =
targetClass.toKtClassOrFile().safeAs<KtClass>()?.takeIf { RootKindFilter.projectSources.matches(it) } ?: return emptyList()
val modifierBuilder = ModifierBuilder(targetKtClass).apply { addJvmModifiers(request.modifiers) }
if (!modifierBuilder.isValid) return emptyList()
val parameters = request.expectedParameters
val needPrimary = !targetKtClass.hasExplicitPrimaryConstructor()
val targetClassName = targetClass.name
val addConstructorAction = AddConstructorCreateCallableFromUsageFix(
request = request,
modifierList = modifierBuilder.modifierList,
familyName = KotlinBundle.message("add.method"),
providedText = KotlinBundle.message(
"add.0.constructor.to.1",
if (needPrimary) KotlinBundle.message("text.primary") else KotlinBundle.message("text.secondary"),
targetClassName.toString()
),
targetKtClass = targetKtClass
)
val changePrimaryConstructorAction = run {
val primaryConstructor = targetKtClass.primaryConstructor ?: return@run null
val lightMethod = primaryConstructor.toLightMethods().firstOrNull() ?: return@run null
val project = targetKtClass.project
val fakeParametersExpressions = fakeParametersExpressions(parameters, project) ?: return@run null
QuickFixFactory.getInstance().createChangeMethodSignatureFromUsageFix(
lightMethod,
fakeParametersExpressions,
PsiSubstitutor.EMPTY,
targetKtClass,
false,
2
).takeIf { it.isAvailable(project, null, targetKtClass.containingFile) }
}
return listOfNotNull(changePrimaryConstructorAction, addConstructorAction)
}
private fun createAddPropertyActions(
targetContainer: KtElement,
modifiers: Iterable<JvmModifier>,
propertyType: JvmType,
propertyName: String,
setterRequired: Boolean,
classOrFileName: String?
): List<IntentionAction> {
val modifierBuilder = ModifierBuilder(targetContainer).apply { addJvmModifiers(modifiers) }
if (!modifierBuilder.isValid) return emptyList()
val action = AddPropertyActionCreateCallableFromUsageFix(
targetContainer = targetContainer,
modifierList = modifierBuilder.modifierList,
propertyType = propertyType,
propertyName = propertyName,
setterRequired = setterRequired,
isLateinitPreferred = false,
classOrFileName = classOrFileName
)
val actions = if (setterRequired) {
listOf(
action, AddPropertyActionCreateCallableFromUsageFix(
targetContainer = targetContainer,
modifierList = modifierBuilder.modifierList,
propertyType = propertyType,
propertyName = propertyName,
setterRequired = true,
classOrFileName = classOrFileName
)
)
} else {
listOf(action)
}
return actions
}
override fun createAddFieldActions(targetClass: JvmClass, request: CreateFieldRequest): List<IntentionAction> {
val targetContainer = targetClass.toKtClassOrFile()?.takeIf { RootKindFilter.projectSources.matches(it) } ?: return emptyList()
val writable = JvmModifier.FINAL !in request.modifiers && !request.isConstant
val action = AddFieldActionCreateCallableFromUsageFix(
targetContainer = targetContainer, classOrFileName = targetClass.name, request = request, lateinit = false
)
val actions = if (writable) {
listOf(
action,
AddFieldActionCreateCallableFromUsageFix(
targetContainer = targetContainer, classOrFileName = targetClass.name, request = request, lateinit = true
)
)
} else {
listOf(action)
}
return actions
}
override fun createAddMethodActions(targetClass: JvmClass, request: CreateMethodRequest): List<IntentionAction> {
val targetContainer = targetClass.toKtClassOrFile()?.takeIf { RootKindFilter.projectSources.matches(it) } ?: return emptyList()
val modifierBuilder = ModifierBuilder(targetContainer).apply { addJvmModifiers(request.modifiers) }
if (!modifierBuilder.isValid) return emptyList()
val methodName = request.methodName
val targetClassName = targetClass.name
val nameAndKind = PropertyUtilBase.getPropertyNameAndKind(methodName)
if (nameAndKind != null) {
val setterRequired = nameAndKind.second == PropertyKind.SETTER
val expectedParameters = request.expectedParameters
val returnTypes = request.returnType
fun getCreatedPropertyType(): ExpectedType? {
if (setterRequired) {
val jvmPsiConversionHelper = JvmPsiConversionHelper.getInstance(targetContainer.project)
if (returnTypes.any { jvmPsiConversionHelper.convertType(it.theType) != PsiType.VOID }) return null
val expectedParameter = expectedParameters.singleOrNull() ?: return null
return expectedParameter.expectedTypes.firstOrNull()
} else if (expectedParameters.isEmpty()) {
return returnTypes.firstOrNull()
} else {
return null
}
}
val propertyType = getCreatedPropertyType()
if (propertyType != null) {
return createAddPropertyActions(
targetContainer,
request.modifiers,
propertyType.theType,
nameAndKind.first,
setterRequired,
targetClass.name
)
}
}
val addMethodAction = AddMethodCreateCallableFromUsageFix(
request = request,
modifierList = modifierBuilder.modifierList,
familyName = KotlinBundle.message("add.method"),
providedText = KotlinBundle.message("add.method.0.to.1", methodName, targetClassName.toString()),
targetContainer = targetContainer
)
return listOf(addMethodAction)
}
override fun createAddAnnotationActions(target: JvmModifiersOwner, request: AnnotationRequest): List<IntentionAction> {
val declaration = target.safeAs<KtLightElement<*, *>>()?.kotlinOrigin.safeAs<KtModifierListOwner>()?.takeIf {
it.language == KotlinLanguage.INSTANCE && RootKindFilter.projectSources.matches(it)
} ?: return emptyList()
val annotationUseSiteTarget = when (target) {
is JvmField -> AnnotationUseSiteTarget.FIELD
is JvmMethod -> when {
PropertyUtil.isSimplePropertySetter(target as? PsiMethod) -> AnnotationUseSiteTarget.PROPERTY_SETTER
PropertyUtil.isSimplePropertyGetter(target as? PsiMethod) -> AnnotationUseSiteTarget.PROPERTY_GETTER
else -> null
}
else -> null
}
return listOf(CreateAnnotationAction(declaration, annotationUseSiteTarget, request))
}
private class CreateAnnotationAction(
target: KtModifierListOwner,
val annotationTarget: AnnotationUseSiteTarget?,
val request: AnnotationRequest
) : IntentionAction {
private val pointer = target.createSmartPointer()
override fun startInWriteAction(): Boolean = true
override fun getText(): String =
QuickFixBundle.message("create.annotation.text", StringUtilRt.getShortName(request.qualifiedName))
override fun getFamilyName(): String = QuickFixBundle.message("create.annotation.family")
override fun isAvailable(project: Project, editor: Editor?, file: PsiFile?): Boolean = pointer.element != null
override fun invoke(project: Project, editor: Editor?, file: PsiFile?) {
val target = pointer.element ?: return
val entry = addAnnotationEntry(target, request, annotationTarget)
ShortenReferences.DEFAULT.process(entry)
}
}
override fun createChangeParametersActions(target: JvmMethod, request: ChangeParametersRequest): List<IntentionAction> {
val ktNamedFunction = (target as? KtLightElement<*, *>)?.kotlinOrigin as? KtNamedFunction ?: return emptyList()
return listOfNotNull(ChangeMethodParameters.create(ktNamedFunction, request))
}
override fun createChangeTypeActions(target: JvmMethod, request: ChangeTypeRequest): List<IntentionAction> {
val ktCallableDeclaration = (target as? KtLightElement<*, *>)?.kotlinOrigin as? KtCallableDeclaration ?: return emptyList()
return listOfNotNull(ChangeType(ktCallableDeclaration, request))
}
override fun createChangeTypeActions(target: JvmParameter, request: ChangeTypeRequest): List<IntentionAction> {
val ktCallableDeclaration = (target as? KtLightElement<*, *>)?.kotlinOrigin as? KtCallableDeclaration ?: return emptyList()
return listOfNotNull(ChangeType(ktCallableDeclaration, request))
}
private class ChangeType(
target: KtCallableDeclaration,
private val request: ChangeTypeRequest
) : IntentionAction {
private val pointer = target.createSmartPointer()
override fun startInWriteAction(): Boolean = true
override fun isAvailable(project: Project, editor: Editor?, file: PsiFile?): Boolean = pointer.element != null && request.isValid
override fun getText(): String {
if (pointer.element == null || !request.isValid) return KotlinBundle.message("fix.change.signature.unavailable")
val typeName = request.qualifiedName
if (typeName == null) return familyName
return QuickFixBundle.message("change.type.text", request.qualifiedName)
}
override fun getFamilyName(): String = QuickFixBundle.message("change.type.family")
override fun invoke(project: Project, editor: Editor?, file: PsiFile) {
if (!request.isValid) return
val target = pointer.element ?: return
val oldType = target.typeReference
val typeName = primitiveTypeMapping.getOrDefault(request.qualifiedName, request.qualifiedName ?: target.typeName() ?: return)
val psiFactory = KtPsiFactory(target)
val annotations = request.annotations.joinToString(" ") { "@${renderAnnotation(target, it, psiFactory)}" }
val newType = psiFactory.createType("$annotations $typeName".trim())
target.typeReference = newType
if (oldType != null) {
val commentSaver = CommentSaver(oldType)
commentSaver.restore(target.typeReference!!)
}
ShortenReferences.DEFAULT.process(target)
}
private fun KtCallableDeclaration.typeName(): String? {
val typeReference = this.typeReference
if (typeReference != null) return typeReference.typeElement?.text
if (this !is KtNamedFunction) return null
val descriptor = this.resolveToDescriptorIfAny() as? CallableDescriptor ?: return null
val returnType = descriptor.returnType ?: return null
return IdeDescriptorRenderers.SOURCE_CODE.renderType(returnType)
}
companion object {
private val primitiveTypeMapping = mapOf(
PsiType.VOID.name to "kotlin.Unit",
PsiType.BOOLEAN.name to "kotlin.Boolean",
PsiType.BYTE.name to "kotlin.Byte",
PsiType.CHAR.name to "kotlin.Char",
PsiType.SHORT.name to "kotlin.Short",
PsiType.INT.name to "kotlin.Int",
PsiType.FLOAT.name to "kotlin.Float",
PsiType.LONG.name to "kotlin.Long",
PsiType.DOUBLE.name to "kotlin.Double",
"${PsiType.BOOLEAN.name}[]" to "kotlin.BooleanArray",
"${PsiType.BYTE.name}[]" to "kotlin.ByteArray",
"${PsiType.CHAR.name}[]" to "kotlin.CharArray",
"${PsiType.SHORT.name}[]" to "kotlin.ShortArray",
"${PsiType.INT.name}[]" to "kotlin.IntArray",
"${PsiType.FLOAT.name}[]" to "kotlin.FloatArray",
"${PsiType.LONG.name}[]" to "kotlin.LongArray",
"${PsiType.DOUBLE.name}[]" to "kotlin.DoubleArray"
)
}
}
}
internal fun addAnnotationEntry(
target: KtModifierListOwner,
request: AnnotationRequest,
annotationTarget: AnnotationUseSiteTarget?
): KtAnnotationEntry {
val annotationUseSiteTargetPrefix = run prefixEvaluation@{
if (annotationTarget == null) return@prefixEvaluation ""
val moduleDescriptor = (target as? KtDeclaration)?.resolveToDescriptorIfAny()?.module ?: return@prefixEvaluation ""
val annotationClassDescriptor = moduleDescriptor.resolveClassByFqName(
FqName(request.qualifiedName), NoLookupLocation.FROM_IDE
) ?: return@prefixEvaluation ""
val applicableTargetSet = AnnotationChecker.applicableTargetSet(annotationClassDescriptor)
if (KotlinTarget.PROPERTY !in applicableTargetSet) return@prefixEvaluation ""
"${annotationTarget.renderName}:"
}
val psiFactory = KtPsiFactory(target)
// could be generated via descriptor when KT-30478 is fixed
val annotationText = '@' + annotationUseSiteTargetPrefix + renderAnnotation(target, request, psiFactory)
return target.addAnnotationEntry(psiFactory.createAnnotationEntry(annotationText))
}
private fun renderAnnotation(target: PsiElement, request: AnnotationRequest, psiFactory: KtPsiFactory): String {
val javaPsiFacade = JavaPsiFacade.getInstance(target.project)
fun isKotlinAnnotation(annotation: AnnotationRequest): Boolean =
javaPsiFacade.findClass(annotation.qualifiedName, target.resolveScope)?.language == KotlinLanguage.INSTANCE
return renderAnnotation(request, psiFactory, ::isKotlinAnnotation)
}
private fun renderAnnotation(
request: AnnotationRequest,
psiFactory: KtPsiFactory,
isKotlinAnnotation: (AnnotationRequest) -> Boolean
): String {
return "${request.qualifiedName}${
request.attributes.takeIf { it.isNotEmpty() }?.mapIndexed { i, p ->
if (!isKotlinAnnotation(request) && i == 0 && p.name == "value")
renderAttributeValue(p.value, psiFactory, isKotlinAnnotation, isVararg = true)
else
"${p.name} = ${renderAttributeValue(p.value, psiFactory, isKotlinAnnotation)}"
}?.joinToString(", ", "(", ")") ?: ""
}"
}
private fun renderAttributeValue(
annotationAttributeRequest: AnnotationAttributeValueRequest,
psiFactory: KtPsiFactory,
isKotlinAnnotation: (AnnotationRequest) -> Boolean,
isVararg: Boolean = false,
): String =
when (annotationAttributeRequest) {
is AnnotationAttributeValueRequest.PrimitiveValue -> annotationAttributeRequest.value.toString()
is AnnotationAttributeValueRequest.StringValue -> "\"" + annotationAttributeRequest.value + "\""
is AnnotationAttributeValueRequest.ClassValue -> annotationAttributeRequest.classFqn + "::class"
is AnnotationAttributeValueRequest.ConstantValue -> annotationAttributeRequest.text
is AnnotationAttributeValueRequest.NestedAnnotation ->
renderAnnotation(annotationAttributeRequest.annotationRequest, psiFactory, isKotlinAnnotation)
is AnnotationAttributeValueRequest.ArrayValue -> {
val (prefix, suffix) = if (isVararg) "" to "" else "[" to "]"
annotationAttributeRequest.members.joinToString(", ", prefix, suffix) { memberRequest ->
renderAttributeValue(memberRequest, psiFactory, isKotlinAnnotation)
}
}
}
| apache-2.0 | 482ea12e2bdd48f48ddc319f71192dad | 45.832103 | 137 | 0.675531 | 5.592201 | false | false | false | false |
dkandalov/katas | kotlin/src/katas/kotlin/permutation/AllPermutationTypes.kt | 1 | 6684 | package katas.kotlin.permutation
import nonstdlib.*
import datsok.*
import org.junit.*
import java.util.*
class AllPermutationTypes {
@Test fun `permutations by removal`() {
listOf(1, 2, 3).permutations_remove() shouldEqual listOf(
listOf(3, 2, 1),
listOf(2, 3, 1),
listOf(3, 1, 2),
listOf(1, 3, 2),
listOf(2, 1, 3),
listOf(1, 2, 3)
)
listOf(1, 2, 3, 4).permutations_remove().printed()
checkPermutationsFunction { it.permutations_remove().toList() }
checkPermutationsFunction { it.permutations_remove_sequence().toList() }
}
@Test fun `permutations by addition`() {
mutableListOf(1, 2, 3).permutations_add() shouldEqual listOf(
listOf(1, 2, 3),
listOf(2, 1, 3),
listOf(2, 3, 1),
listOf(1, 3, 2),
listOf(3, 1, 2),
listOf(3, 2, 1)
)
mutableListOf(1, 2, 3, 4).permutations_add().toList().printed()
checkPermutationsFunction { it.toMutableList().permutations_add().toList() }
}
@Test fun `permutations by addition minimum swaps`() {
mutableListOf(1, 2, 3).permutations_add_min_change() shouldEqual listOf(
listOf(1, 2, 3),
listOf(2, 1, 3),
listOf(2, 3, 1),
listOf(3, 2, 1),
listOf(3, 1, 2),
listOf(1, 3, 2)
)
mutableListOf(1, 2, 3, 4).permutations_add_min_change().printed()
mutableListOf(0, 1, 2, 3).permutations_add_min_change().printed()
.map { it.toLehmerCode().toLong().printed() }
checkPermutationsFunction { it.toMutableList().permutations_add_min_change().toList() }
}
@Test fun `lexicographic permutations`() {
listOf(1, 2, 3).permutations_lexicographic() shouldEqual listOf(
listOf(1, 2, 3),
listOf(1, 3, 2),
listOf(2, 1, 3),
listOf(2, 3, 1),
listOf(3, 1, 2),
listOf(3, 2, 1)
)
listOf(1, 2, 3, 4).permutations_lexicographic().join("\n").printed()
listOf(0, 1, 2, 3).permutations_lexicographic()
.map { it.toLehmerCode().toLong() } shouldEqual LongRange(0, 23).toList()
checkPermutationsFunction { it.toMutableList().permutations_lexicographic().toList() }
}
@Test fun `lexicographic permutations using Lehmer code`() {
listOf(1, 2, 3).permutations_lehmer() shouldEqual listOf(
listOf(1, 2, 3),
listOf(1, 3, 2),
listOf(2, 1, 3),
listOf(2, 3, 1),
listOf(3, 1, 2),
listOf(3, 2, 1)
)
listOf(1, 2, 3, 4).permutations_lehmer().join("\n").printed()
checkPermutationsFunction { it.permutations_lehmer().toList() }
}
@Test fun `Heap's permutations`() {
mutableListOf(1, 2, 3).permutations_heaps() shouldEqual listOf(
listOf(1, 2, 3),
listOf(2, 1, 3),
listOf(3, 1, 2),
listOf(1, 3, 2),
listOf(2, 3, 1),
listOf(3, 2, 1)
)
mutableListOf(1, 2, 3, 4).permutations_heaps().join("\n").printed()
checkPermutationsFunction { it.toMutableList().permutations_heaps().toList() }
}
companion object {
private fun List<Int>.permutations_remove(): List<List<Int>> =
if (size <= 1) listOf(this)
else flatMap { item ->
(this - item)
.permutations_remove()
.map { permutation -> permutation + item }
}
private fun List<Int>.permutations_remove_sequence(): Sequence<List<Int>> {
if (size <= 1) return sequenceOf(this)
val list = this
return sequence {
list.forEach { item ->
val permutations = (list - item)
.permutations_remove_sequence()
.map { permutation -> permutation + item }
yieldAll(permutations)
}
}
}
private fun MutableList<Int>.permutations_add(): List<List<Int>> {
if (size <= 1) return listOf(this)
val firstItem = first()
val subPermutations = drop(1).toMutableList().permutations_add()
return subPermutations.flatMap { subPermutation ->
(0..subPermutation.size)
.map { i -> ArrayList(subPermutation).apply { add(i, firstItem) } }
}
}
private fun MutableList<Int>.permutations_add_min_change(): List<List<Int>> {
if (size <= 1) return listOf(this)
val item = first()
val subPermutations = drop(1).toMutableList().permutations_add_min_change()
return subPermutations.mapIndexed { index, subPermutation ->
val permutation = (0..subPermutation.size)
.map { i -> ArrayList(subPermutation).apply { add(i, item) } }
if (index % 2 != 0) permutation.reversed() else permutation
}.flatten()
}
/**
* https://en.wikipedia.org/wiki/Permutation#Generation_in_lexicographic_order
* https://www.nayuki.io/page/next-lexicographical-permutation-algorithm
*/
private fun List<Int>.permutations_lexicographic(): List<List<Int>> {
val values = this
val list = indices.toMutableList()
val result = ArrayList<List<Int>>()
result.add(list.map { values[it] })
while (true) {
val i = list.indices.windowed(2).findLast { (i1, i2) -> list[i1] < list[i2] }?.first() ?: return result
val j = IntRange(i + 1, list.size - 1).findLast { list[i] < list[it] }!!
list.swap(i, j)
list.subList(i + 1, list.size).reverse()
result.add(list.map { values[it] })
}
}
private fun List<Int>.permutations_lehmer(): List<List<Int>> {
if (isEmpty()) return listOf(emptyList())
return LongRange(0, size.longFactorial() - 1)
.map { it.toLehmerCode(size = size).toPermutation(this) }
}
private fun MutableList<Int>.permutations_heaps(n: Int = size): List<List<Int>> {
if (n <= 1) return listOf(ArrayList(this))
return sequence {
(1..n).forEach { i ->
yieldAll(permutations_heaps(n - 1))
if (n % 2 == 0) swap(i - 1, n - 1)
else swap(0, n - 1)
}
}.toList()
}
}
}
| unlicense | c06b928b9604a1030841d036a7f4cad7 | 36.133333 | 119 | 0.521993 | 4.110701 | false | false | false | false |
DreierF/MyTargets | shared/src/main/java/de/dreier/mytargets/shared/targets/models/DBSCBlowpipe.kt | 1 | 1572 | /*
* Copyright (C) 2018 Florian Dreier
*
* This file is part of MyTargets.
*
* MyTargets is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2
* as published by the Free Software Foundation.
*
* MyTargets 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.
*/
package de.dreier.mytargets.shared.targets.models
import de.dreier.mytargets.shared.R
import de.dreier.mytargets.shared.models.Dimension
import de.dreier.mytargets.shared.models.Dimension.Unit.CENTIMETER
import de.dreier.mytargets.shared.targets.scoringstyle.ScoringStyle
import de.dreier.mytargets.shared.targets.zone.CircularZone
import de.dreier.mytargets.shared.utils.Color.DARK_GRAY
import de.dreier.mytargets.shared.utils.Color.DBSC_BLUE
import de.dreier.mytargets.shared.utils.Color.DBSC_RED
import de.dreier.mytargets.shared.utils.Color.DBSC_YELLOW
class DBSCBlowpipe : TargetModelBase(
id = ID,
nameRes = R.string.dbsc_blowpipe,
diameters = listOf(Dimension(18f, CENTIMETER)),
zones = listOf(
CircularZone(0.3333f, DBSC_YELLOW, DARK_GRAY, 8),
CircularZone(0.6666f, DBSC_RED, DARK_GRAY, 8),
CircularZone(1f, DBSC_BLUE, DARK_GRAY, 8)
),
scoringStyles = listOf(ScoringStyle(false, 7, 5, 3))
) {
companion object {
const val ID = 28L
}
}
| gpl-2.0 | 6319c81fcac901915d9c1a1a6cca4194 | 37.341463 | 68 | 0.724555 | 3.716312 | false | false | false | false |
zbeboy/ISY | src/main/java/top/zbeboy/isy/service/internship/InternshipCollegeServiceImpl.kt | 1 | 24640 | package top.zbeboy.isy.service.internship
import org.jooq.*
import org.jooq.impl.DSL
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Service
import org.springframework.transaction.annotation.Propagation
import org.springframework.transaction.annotation.Transactional
import org.springframework.util.ObjectUtils
import org.springframework.util.StringUtils
import top.zbeboy.isy.domain.Tables.*
import top.zbeboy.isy.domain.tables.daos.InternshipCollegeDao
import top.zbeboy.isy.domain.tables.pojos.InternshipCollege
import top.zbeboy.isy.domain.tables.records.InternshipApplyRecord
import top.zbeboy.isy.domain.tables.records.InternshipChangeHistoryRecord
import top.zbeboy.isy.domain.tables.records.InternshipCollegeRecord
import top.zbeboy.isy.service.plugin.DataTablesPlugin
import top.zbeboy.isy.service.util.DateTimeUtils
import top.zbeboy.isy.service.util.SQLQueryUtils
import top.zbeboy.isy.service.util.UUIDUtils
import top.zbeboy.isy.web.util.DataTablesUtils
import top.zbeboy.isy.web.vo.internship.apply.InternshipCollegeVo
import java.sql.Timestamp
import java.time.Clock
import java.util.*
import javax.annotation.Resource
/**
* Created by zbeboy 2017-12-27 .
**/
@Service("internshipCollegeService")
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
open class InternshipCollegeServiceImpl @Autowired constructor(dslContext: DSLContext) : DataTablesPlugin<InternshipCollege>(), InternshipCollegeService {
private val create: DSLContext = dslContext
@Resource
open lateinit var internshipCollegeDao: InternshipCollegeDao
override fun findById(id: String): InternshipCollege {
return internshipCollegeDao.findById(id)
}
override fun findByInternshipReleaseIdAndStudentId(internshipReleaseId: String, studentId: Int): Optional<Record> {
return create.select()
.from(INTERNSHIP_COLLEGE)
.where(INTERNSHIP_COLLEGE.INTERNSHIP_RELEASE_ID.eq(internshipReleaseId).and(INTERNSHIP_COLLEGE.STUDENT_ID.eq(studentId)))
.fetchOptional()
}
@Transactional(propagation = Propagation.REQUIRED, readOnly = false)
override fun save(internshipCollege: InternshipCollege) {
internshipCollegeDao.insert(internshipCollege)
}
override fun saveWithTransaction(internshipCollegeVo: InternshipCollegeVo) {
create.transaction { configuration ->
val now = Timestamp(Clock.systemDefaultZone().millis())
val state = 0
DSL.using(configuration)
.insertInto<InternshipApplyRecord>(INTERNSHIP_APPLY)
.set(INTERNSHIP_APPLY.INTERNSHIP_APPLY_ID, UUIDUtils.getUUID())
.set(INTERNSHIP_APPLY.INTERNSHIP_RELEASE_ID, internshipCollegeVo.internshipReleaseId)
.set(INTERNSHIP_APPLY.STUDENT_ID, internshipCollegeVo.studentId)
.set(INTERNSHIP_APPLY.APPLY_TIME, now)
.set(INTERNSHIP_APPLY.INTERNSHIP_APPLY_STATE, state)
.execute()
val headmasterArr = internshipCollegeVo.headmaster!!.split(" ".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()
if (headmasterArr.size >= 2) {
internshipCollegeVo.headmaster = headmasterArr[0]
internshipCollegeVo.headmasterContact = headmasterArr[1]
}
val schoolGuidanceTeacherArr = internshipCollegeVo.schoolGuidanceTeacher!!.split(" ".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()
if (schoolGuidanceTeacherArr.size >= 2) {
internshipCollegeVo.schoolGuidanceTeacher = schoolGuidanceTeacherArr[0]
internshipCollegeVo.schoolGuidanceTeacherTel = schoolGuidanceTeacherArr[1]
}
DSL.using(configuration)
.insertInto<InternshipCollegeRecord>(INTERNSHIP_COLLEGE)
.set(INTERNSHIP_COLLEGE.INTERNSHIP_COLLEGE_ID, UUIDUtils.getUUID())
.set(INTERNSHIP_COLLEGE.STUDENT_ID, internshipCollegeVo.studentId)
.set(INTERNSHIP_COLLEGE.STUDENT_USERNAME, internshipCollegeVo.studentUsername)
.set(INTERNSHIP_COLLEGE.INTERNSHIP_RELEASE_ID, internshipCollegeVo.internshipReleaseId)
.set(INTERNSHIP_COLLEGE.STUDENT_NAME, internshipCollegeVo.studentName)
.set(INTERNSHIP_COLLEGE.COLLEGE_CLASS, internshipCollegeVo.collegeClass)
.set(INTERNSHIP_COLLEGE.STUDENT_SEX, internshipCollegeVo.studentSex)
.set(INTERNSHIP_COLLEGE.STUDENT_NUMBER, internshipCollegeVo.studentNumber)
.set(INTERNSHIP_COLLEGE.PHONE_NUMBER, internshipCollegeVo.phoneNumber)
.set(INTERNSHIP_COLLEGE.QQ_MAILBOX, internshipCollegeVo.qqMailbox)
.set(INTERNSHIP_COLLEGE.PARENTAL_CONTACT, internshipCollegeVo.parentalContact)
.set(INTERNSHIP_COLLEGE.HEADMASTER, internshipCollegeVo.headmaster)
.set(INTERNSHIP_COLLEGE.HEADMASTER_CONTACT, internshipCollegeVo.headmasterContact)
.set(INTERNSHIP_COLLEGE.INTERNSHIP_COLLEGE_NAME, internshipCollegeVo.internshipCollegeName)
.set(INTERNSHIP_COLLEGE.INTERNSHIP_COLLEGE_ADDRESS, internshipCollegeVo.internshipCollegeAddress)
.set(INTERNSHIP_COLLEGE.INTERNSHIP_COLLEGE_CONTACTS, internshipCollegeVo.internshipCollegeContacts)
.set(INTERNSHIP_COLLEGE.INTERNSHIP_COLLEGE_TEL, internshipCollegeVo.internshipCollegeTel)
.set(INTERNSHIP_COLLEGE.SCHOOL_GUIDANCE_TEACHER, internshipCollegeVo.schoolGuidanceTeacher)
.set(INTERNSHIP_COLLEGE.SCHOOL_GUIDANCE_TEACHER_TEL, internshipCollegeVo.schoolGuidanceTeacherTel)
.set(INTERNSHIP_COLLEGE.START_TIME, DateTimeUtils.formatDate(internshipCollegeVo.startTime!!))
.set(INTERNSHIP_COLLEGE.END_TIME, DateTimeUtils.formatDate(internshipCollegeVo.endTime!!))
.execute()
DSL.using(configuration)
.insertInto<InternshipChangeHistoryRecord>(INTERNSHIP_CHANGE_HISTORY)
.set(INTERNSHIP_CHANGE_HISTORY.INTERNSHIP_CHANGE_HISTORY_ID, UUIDUtils.getUUID())
.set(INTERNSHIP_CHANGE_HISTORY.INTERNSHIP_RELEASE_ID, internshipCollegeVo.internshipReleaseId)
.set(INTERNSHIP_CHANGE_HISTORY.STUDENT_ID, internshipCollegeVo.studentId)
.set(INTERNSHIP_CHANGE_HISTORY.STATE, state)
.set(INTERNSHIP_CHANGE_HISTORY.APPLY_TIME, now)
.execute()
}
}
override fun update(internshipCollege: InternshipCollege) {
internshipCollegeDao.update(internshipCollege)
}
override fun deleteByInternshipReleaseIdAndStudentId(internshipReleaseId: String, studentId: Int) {
create.deleteFrom<InternshipCollegeRecord>(INTERNSHIP_COLLEGE)
.where(INTERNSHIP_COLLEGE.INTERNSHIP_RELEASE_ID.eq(internshipReleaseId).and(INTERNSHIP_COLLEGE.STUDENT_ID.eq(studentId)))
.execute()
}
override fun findAllByPage(dataTablesUtils: DataTablesUtils<InternshipCollege>, internshipCollege: InternshipCollege): Result<Record> {
return dataPagingQueryAllWithCondition(dataTablesUtils, create, INTERNSHIP_COLLEGE, INTERNSHIP_COLLEGE.INTERNSHIP_RELEASE_ID.eq(internshipCollege.internshipReleaseId))
}
override fun countAll(internshipCollege: InternshipCollege): Int {
return statisticsAllWithCondition(create, INTERNSHIP_COLLEGE, INTERNSHIP_COLLEGE.INTERNSHIP_RELEASE_ID.eq(internshipCollege.internshipReleaseId))
}
override fun countByCondition(dataTablesUtils: DataTablesUtils<InternshipCollege>, internshipCollege: InternshipCollege): Int {
return statisticsWithCondition(dataTablesUtils, create, INTERNSHIP_COLLEGE, INTERNSHIP_COLLEGE.INTERNSHIP_RELEASE_ID.eq(internshipCollege.internshipReleaseId))
}
override fun exportData(dataTablesUtils: DataTablesUtils<InternshipCollege>, internshipCollege: InternshipCollege): Result<Record> {
return dataPagingQueryAllWithConditionNoPage(dataTablesUtils, create, INTERNSHIP_COLLEGE, INTERNSHIP_COLLEGE.INTERNSHIP_RELEASE_ID.eq(internshipCollege.internshipReleaseId))
}
/**
* 全局搜索条件
*
* @param dataTablesUtils datatables工具类
* @return 搜索条件
*/
override fun searchCondition(dataTablesUtils: DataTablesUtils<InternshipCollege>): Condition? {
var a: Condition? = null
val search = dataTablesUtils.search
if (!ObjectUtils.isEmpty(search)) {
val studentName = StringUtils.trimWhitespace(search!!.getString("studentName"))
val studentNumber = StringUtils.trimWhitespace(search.getString("studentNumber"))
val collegeClass = StringUtils.trimWhitespace(search.getString("collegeClass"))
val phoneNumber = StringUtils.trimWhitespace(search.getString("phoneNumber"))
val headmaster = StringUtils.trimWhitespace(search.getString("headmaster"))
val schoolGuidanceTeacher = StringUtils.trimWhitespace(search.getString("schoolGuidanceTeacher"))
if (StringUtils.hasLength(studentName)) {
a = INTERNSHIP_COLLEGE.STUDENT_NAME.like(SQLQueryUtils.likeAllParam(studentName))
}
if (StringUtils.hasLength(studentNumber)) {
a = if (ObjectUtils.isEmpty(a)) {
INTERNSHIP_COLLEGE.STUDENT_NUMBER.like(SQLQueryUtils.likeAllParam(studentNumber))
} else {
a!!.and(INTERNSHIP_COLLEGE.STUDENT_NUMBER.like(SQLQueryUtils.likeAllParam(studentNumber)))
}
}
if (StringUtils.hasLength(collegeClass)) {
a = if (ObjectUtils.isEmpty(a)) {
INTERNSHIP_COLLEGE.COLLEGE_CLASS.like(SQLQueryUtils.likeAllParam(collegeClass))
} else {
a!!.and(INTERNSHIP_COLLEGE.COLLEGE_CLASS.like(SQLQueryUtils.likeAllParam(collegeClass)))
}
}
if (StringUtils.hasLength(phoneNumber)) {
a = if (ObjectUtils.isEmpty(a)) {
INTERNSHIP_COLLEGE.PHONE_NUMBER.like(SQLQueryUtils.likeAllParam(phoneNumber))
} else {
a!!.and(INTERNSHIP_COLLEGE.PHONE_NUMBER.like(SQLQueryUtils.likeAllParam(phoneNumber)))
}
}
if (StringUtils.hasLength(headmaster)) {
a = if (ObjectUtils.isEmpty(a)) {
INTERNSHIP_COLLEGE.HEADMASTER.like(SQLQueryUtils.likeAllParam(headmaster))
} else {
a!!.and(INTERNSHIP_COLLEGE.HEADMASTER.like(SQLQueryUtils.likeAllParam(headmaster)))
}
}
if (StringUtils.hasLength(schoolGuidanceTeacher)) {
a = if (ObjectUtils.isEmpty(a)) {
INTERNSHIP_COLLEGE.SCHOOL_GUIDANCE_TEACHER.like(SQLQueryUtils.likeAllParam(schoolGuidanceTeacher))
} else {
a!!.and(INTERNSHIP_COLLEGE.SCHOOL_GUIDANCE_TEACHER.like(SQLQueryUtils.likeAllParam(schoolGuidanceTeacher)))
}
}
}
return a
}
/**
* 数据排序
*
* @param dataTablesUtils datatables工具类
* @param selectConditionStep 条件
*/
override fun sortCondition(dataTablesUtils: DataTablesUtils<InternshipCollege>, selectConditionStep: SelectConditionStep<Record>?, selectJoinStep: SelectJoinStep<Record>?, type: Int) {
val orderColumnName = dataTablesUtils.orderColumnName
val orderDir = dataTablesUtils.orderDir
val isAsc = "asc".equals(orderDir, ignoreCase = true)
var sortField: Array<SortField<*>?>? = null
if (StringUtils.hasLength(orderColumnName)) {
if ("student_name".equals(orderColumnName!!, ignoreCase = true)) {
sortField = arrayOfNulls(2)
if (isAsc) {
sortField[0] = INTERNSHIP_COLLEGE.STUDENT_NAME.asc()
sortField[1] = INTERNSHIP_COLLEGE.INTERNSHIP_COLLEGE_ID.asc()
} else {
sortField[0] = INTERNSHIP_COLLEGE.STUDENT_NAME.desc()
sortField[1] = INTERNSHIP_COLLEGE.INTERNSHIP_COLLEGE_ID.desc()
}
}
if ("student_number".equals(orderColumnName, ignoreCase = true)) {
sortField = arrayOfNulls(1)
if (isAsc) {
sortField[0] = INTERNSHIP_COLLEGE.STUDENT_NUMBER.asc()
} else {
sortField[0] = INTERNSHIP_COLLEGE.STUDENT_NUMBER.desc()
}
}
if ("college_class".equals(orderColumnName, ignoreCase = true)) {
sortField = arrayOfNulls(2)
if (isAsc) {
sortField[0] = INTERNSHIP_COLLEGE.COLLEGE_CLASS.asc()
sortField[1] = INTERNSHIP_COLLEGE.INTERNSHIP_COLLEGE_ID.asc()
} else {
sortField[0] = INTERNSHIP_COLLEGE.COLLEGE_CLASS.desc()
sortField[1] = INTERNSHIP_COLLEGE.INTERNSHIP_COLLEGE_ID.desc()
}
}
if ("student_sex".equals(orderColumnName, ignoreCase = true)) {
sortField = arrayOfNulls(2)
if (isAsc) {
sortField[0] = INTERNSHIP_COLLEGE.STUDENT_SEX.asc()
sortField[1] = INTERNSHIP_COLLEGE.INTERNSHIP_COLLEGE_ID.asc()
} else {
sortField[0] = INTERNSHIP_COLLEGE.STUDENT_SEX.desc()
sortField[1] = INTERNSHIP_COLLEGE.INTERNSHIP_COLLEGE_ID.desc()
}
}
if ("phone_number".equals(orderColumnName, ignoreCase = true)) {
sortField = arrayOfNulls(1)
if (isAsc) {
sortField[0] = INTERNSHIP_COLLEGE.PHONE_NUMBER.asc()
} else {
sortField[0] = INTERNSHIP_COLLEGE.PHONE_NUMBER.desc()
}
}
if ("qq_mailbox".equals(orderColumnName, ignoreCase = true)) {
sortField = arrayOfNulls(2)
if (isAsc) {
sortField[0] = INTERNSHIP_COLLEGE.QQ_MAILBOX.asc()
sortField[1] = INTERNSHIP_COLLEGE.INTERNSHIP_COLLEGE_ID.asc()
} else {
sortField[0] = INTERNSHIP_COLLEGE.QQ_MAILBOX.desc()
sortField[1] = INTERNSHIP_COLLEGE.INTERNSHIP_COLLEGE_ID.desc()
}
}
if ("parental_contact".equals(orderColumnName, ignoreCase = true)) {
sortField = arrayOfNulls(2)
if (isAsc) {
sortField[0] = INTERNSHIP_COLLEGE.PARENTAL_CONTACT.asc()
sortField[1] = INTERNSHIP_COLLEGE.INTERNSHIP_COLLEGE_ID.asc()
} else {
sortField[0] = INTERNSHIP_COLLEGE.PARENTAL_CONTACT.desc()
sortField[1] = INTERNSHIP_COLLEGE.INTERNSHIP_COLLEGE_ID.desc()
}
}
if ("headmaster".equals(orderColumnName, ignoreCase = true)) {
sortField = arrayOfNulls(2)
if (isAsc) {
sortField[0] = INTERNSHIP_COLLEGE.HEADMASTER.asc()
sortField[1] = INTERNSHIP_COLLEGE.INTERNSHIP_COLLEGE_ID.asc()
} else {
sortField[0] = INTERNSHIP_COLLEGE.HEADMASTER.desc()
sortField[1] = INTERNSHIP_COLLEGE.INTERNSHIP_COLLEGE_ID.desc()
}
}
if ("headmaster_contact".equals(orderColumnName, ignoreCase = true)) {
sortField = arrayOfNulls(2)
if (isAsc) {
sortField[0] = INTERNSHIP_COLLEGE.HEADMASTER_CONTACT.asc()
sortField[1] = INTERNSHIP_COLLEGE.INTERNSHIP_COLLEGE_ID.asc()
} else {
sortField[0] = INTERNSHIP_COLLEGE.HEADMASTER_CONTACT.desc()
sortField[1] = INTERNSHIP_COLLEGE.INTERNSHIP_COLLEGE_ID.desc()
}
}
if ("internship_college_name".equals(orderColumnName, ignoreCase = true)) {
sortField = arrayOfNulls(2)
if (isAsc) {
sortField[0] = INTERNSHIP_COLLEGE.INTERNSHIP_COLLEGE_NAME.asc()
sortField[1] = INTERNSHIP_COLLEGE.INTERNSHIP_COLLEGE_ID.asc()
} else {
sortField[0] = INTERNSHIP_COLLEGE.INTERNSHIP_COLLEGE_NAME.desc()
sortField[1] = INTERNSHIP_COLLEGE.INTERNSHIP_COLLEGE_ID.desc()
}
}
if ("internship_college_address".equals(orderColumnName, ignoreCase = true)) {
sortField = arrayOfNulls(2)
if (isAsc) {
sortField[0] = INTERNSHIP_COLLEGE.INTERNSHIP_COLLEGE_ADDRESS.asc()
sortField[1] = INTERNSHIP_COLLEGE.INTERNSHIP_COLLEGE_ID.asc()
} else {
sortField[0] = INTERNSHIP_COLLEGE.INTERNSHIP_COLLEGE_ADDRESS.desc()
sortField[1] = INTERNSHIP_COLLEGE.INTERNSHIP_COLLEGE_ID.desc()
}
}
if ("internship_college_contacts".equals(orderColumnName, ignoreCase = true)) {
sortField = arrayOfNulls(2)
if (isAsc) {
sortField[0] = INTERNSHIP_COLLEGE.INTERNSHIP_COLLEGE_CONTACTS.asc()
sortField[1] = INTERNSHIP_COLLEGE.INTERNSHIP_COLLEGE_ID.asc()
} else {
sortField[0] = INTERNSHIP_COLLEGE.INTERNSHIP_COLLEGE_CONTACTS.desc()
sortField[1] = INTERNSHIP_COLLEGE.INTERNSHIP_COLLEGE_ID.desc()
}
}
if ("internship_college_tel".equals(orderColumnName, ignoreCase = true)) {
sortField = arrayOfNulls(2)
if (isAsc) {
sortField[0] = INTERNSHIP_COLLEGE.INTERNSHIP_COLLEGE_TEL.asc()
sortField[1] = INTERNSHIP_COLLEGE.INTERNSHIP_COLLEGE_ID.asc()
} else {
sortField[0] = INTERNSHIP_COLLEGE.INTERNSHIP_COLLEGE_TEL.desc()
sortField[1] = INTERNSHIP_COLLEGE.INTERNSHIP_COLLEGE_ID.desc()
}
}
if ("school_guidance_teacher".equals(orderColumnName, ignoreCase = true)) {
sortField = arrayOfNulls(2)
if (isAsc) {
sortField[0] = INTERNSHIP_COLLEGE.SCHOOL_GUIDANCE_TEACHER.asc()
sortField[1] = INTERNSHIP_COLLEGE.INTERNSHIP_COLLEGE_ID.asc()
} else {
sortField[0] = INTERNSHIP_COLLEGE.SCHOOL_GUIDANCE_TEACHER.desc()
sortField[1] = INTERNSHIP_COLLEGE.INTERNSHIP_COLLEGE_ID.desc()
}
}
if ("school_guidance_teacher_tel".equals(orderColumnName, ignoreCase = true)) {
sortField = arrayOfNulls(2)
if (isAsc) {
sortField[0] = INTERNSHIP_COLLEGE.SCHOOL_GUIDANCE_TEACHER_TEL.asc()
sortField[1] = INTERNSHIP_COLLEGE.INTERNSHIP_COLLEGE_ID.asc()
} else {
sortField[0] = INTERNSHIP_COLLEGE.SCHOOL_GUIDANCE_TEACHER_TEL.desc()
sortField[1] = INTERNSHIP_COLLEGE.INTERNSHIP_COLLEGE_ID.desc()
}
}
if ("start_time".equals(orderColumnName, ignoreCase = true)) {
sortField = arrayOfNulls(2)
if (isAsc) {
sortField[0] = INTERNSHIP_COLLEGE.START_TIME.asc()
sortField[1] = INTERNSHIP_COLLEGE.INTERNSHIP_COLLEGE_ID.asc()
} else {
sortField[0] = INTERNSHIP_COLLEGE.START_TIME.desc()
sortField[1] = INTERNSHIP_COLLEGE.INTERNSHIP_COLLEGE_ID.desc()
}
}
if ("end_time".equals(orderColumnName, ignoreCase = true)) {
sortField = arrayOfNulls(2)
if (isAsc) {
sortField[0] = INTERNSHIP_COLLEGE.END_TIME.asc()
sortField[1] = INTERNSHIP_COLLEGE.INTERNSHIP_COLLEGE_ID.asc()
} else {
sortField[0] = INTERNSHIP_COLLEGE.END_TIME.desc()
sortField[1] = INTERNSHIP_COLLEGE.INTERNSHIP_COLLEGE_ID.desc()
}
}
if ("commitment_book".equals(orderColumnName, ignoreCase = true)) {
sortField = arrayOfNulls(2)
if (isAsc) {
sortField[0] = INTERNSHIP_COLLEGE.COMMITMENT_BOOK.asc()
sortField[1] = INTERNSHIP_COLLEGE.INTERNSHIP_COLLEGE_ID.asc()
} else {
sortField[0] = INTERNSHIP_COLLEGE.COMMITMENT_BOOK.desc()
sortField[1] = INTERNSHIP_COLLEGE.INTERNSHIP_COLLEGE_ID.desc()
}
}
if ("safety_responsibility_book".equals(orderColumnName, ignoreCase = true)) {
sortField = arrayOfNulls(2)
if (isAsc) {
sortField[0] = INTERNSHIP_COLLEGE.SAFETY_RESPONSIBILITY_BOOK.asc()
sortField[1] = INTERNSHIP_COLLEGE.INTERNSHIP_COLLEGE_ID.asc()
} else {
sortField[0] = INTERNSHIP_COLLEGE.SAFETY_RESPONSIBILITY_BOOK.desc()
sortField[1] = INTERNSHIP_COLLEGE.INTERNSHIP_COLLEGE_ID.desc()
}
}
if ("practice_agreement".equals(orderColumnName, ignoreCase = true)) {
sortField = arrayOfNulls(2)
if (isAsc) {
sortField[0] = INTERNSHIP_COLLEGE.PRACTICE_AGREEMENT.asc()
sortField[1] = INTERNSHIP_COLLEGE.INTERNSHIP_COLLEGE_ID.asc()
} else {
sortField[0] = INTERNSHIP_COLLEGE.PRACTICE_AGREEMENT.desc()
sortField[1] = INTERNSHIP_COLLEGE.INTERNSHIP_COLLEGE_ID.desc()
}
}
if ("internship_application".equals(orderColumnName, ignoreCase = true)) {
sortField = arrayOfNulls(2)
if (isAsc) {
sortField[0] = INTERNSHIP_COLLEGE.INTERNSHIP_APPLICATION.asc()
sortField[1] = INTERNSHIP_COLLEGE.INTERNSHIP_COLLEGE_ID.asc()
} else {
sortField[0] = INTERNSHIP_COLLEGE.INTERNSHIP_APPLICATION.desc()
sortField[1] = INTERNSHIP_COLLEGE.INTERNSHIP_COLLEGE_ID.desc()
}
}
if ("practice_receiving".equals(orderColumnName, ignoreCase = true)) {
sortField = arrayOfNulls(2)
if (isAsc) {
sortField[0] = INTERNSHIP_COLLEGE.PRACTICE_RECEIVING.asc()
sortField[1] = INTERNSHIP_COLLEGE.INTERNSHIP_COLLEGE_ID.asc()
} else {
sortField[0] = INTERNSHIP_COLLEGE.PRACTICE_RECEIVING.desc()
sortField[1] = INTERNSHIP_COLLEGE.INTERNSHIP_COLLEGE_ID.desc()
}
}
if ("security_education_agreement".equals(orderColumnName, ignoreCase = true)) {
sortField = arrayOfNulls(2)
if (isAsc) {
sortField[0] = INTERNSHIP_COLLEGE.SECURITY_EDUCATION_AGREEMENT.asc()
sortField[1] = INTERNSHIP_COLLEGE.INTERNSHIP_COLLEGE_ID.asc()
} else {
sortField[0] = INTERNSHIP_COLLEGE.SECURITY_EDUCATION_AGREEMENT.desc()
sortField[1] = INTERNSHIP_COLLEGE.INTERNSHIP_COLLEGE_ID.desc()
}
}
if ("parental_consent".equals(orderColumnName, ignoreCase = true)) {
sortField = arrayOfNulls(2)
if (isAsc) {
sortField[0] = INTERNSHIP_COLLEGE.PARENTAL_CONSENT.asc()
sortField[1] = INTERNSHIP_COLLEGE.INTERNSHIP_COLLEGE_ID.asc()
} else {
sortField[0] = INTERNSHIP_COLLEGE.PARENTAL_CONSENT.desc()
sortField[1] = INTERNSHIP_COLLEGE.INTERNSHIP_COLLEGE_ID.desc()
}
}
}
sortToFinish(selectConditionStep, selectJoinStep, type, *sortField!!)
}
} | mit | 9c048bc2147ea0e8891b62405ae4f8e7 | 49.925466 | 188 | 0.602334 | 5.06925 | false | false | false | false |
outbrain/ob1k | ob1k-crud/src/main/java/com/outbrain/ob1k/crud/dao/CrudOperations.kt | 1 | 1686 | package com.outbrain.ob1k.crud.dao
import java.beans.Introspector
import java.beans.PropertyDescriptor
import java.util.*
fun <T> List<T>.range(range: IntRange) = if (isEmpty()) this else subList(rangeCheck(range.start), rangeCheck(range.last) + 1)
fun <T> List<T>.like(like: T?): List<T> {
if (like == null) {
return this
}
val filterProperties = like.properties().filter { like.value(it) != null }
return filter { item ->
filterProperties.all {
val itemValue = item.value(it)
val likeValue = like.value(it)
when (likeValue) {
is String -> itemValue.toString().contains(likeValue)
else -> likeValue == itemValue
}
}
}
}
fun <T> Collection<T>.sort(type: Class<*>, sort: Pair<String, String>): List<T> {
val sortProperty = type.properties().find { it.name == sort.first }!!
return sortedWith(compareBy<T> { it.asComparable(sortProperty) }.reverseIfNeeded(sort.second))
}
private fun Any?.value(pd: PropertyDescriptor) = this?.let { pd.readMethod.invoke(it) }
private fun Any.properties() = javaClass.properties()
private fun Class<*>.properties() = Introspector.getBeanInfo(this).propertyDescriptors
private fun <T> Comparator<T>.reverseIfNeeded(order: String) = if (order.toLowerCase() == "desc") reversed() else this
private fun List<*>.rangeCheck(idx: Int) = Math.min(Math.max(idx, 0), size - 1)
private fun <T> T.asComparable(sortProperty: PropertyDescriptor): Comparable<*>? {
val value = value(sortProperty)
return when (value) {
is Number -> value.toDouble()
is Date -> value
else -> value.toString()
}
} | apache-2.0 | c6967779b49b3bb29ef29a3a63d8a3ce | 36.488889 | 126 | 0.650652 | 3.730088 | false | false | false | false |
google/intellij-community | platform/workspaceModel/storage/testEntities/gen/com/intellij/workspaceModel/storage/entities/test/api/DefaultValueEntityImpl.kt | 1 | 7505 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.workspaceModel.storage.entities.test.api
import com.intellij.workspaceModel.deft.api.annotations.Default
import com.intellij.workspaceModel.storage.EntityInformation
import com.intellij.workspaceModel.storage.EntitySource
import com.intellij.workspaceModel.storage.EntityStorage
import com.intellij.workspaceModel.storage.GeneratedCodeApiVersion
import com.intellij.workspaceModel.storage.GeneratedCodeImplVersion
import com.intellij.workspaceModel.storage.ModifiableWorkspaceEntity
import com.intellij.workspaceModel.storage.MutableEntityStorage
import com.intellij.workspaceModel.storage.WorkspaceEntity
import com.intellij.workspaceModel.storage.impl.ConnectionId
import com.intellij.workspaceModel.storage.impl.ModifiableWorkspaceEntityBase
import com.intellij.workspaceModel.storage.impl.UsedClassesCollector
import com.intellij.workspaceModel.storage.impl.WorkspaceEntityBase
import com.intellij.workspaceModel.storage.impl.WorkspaceEntityData
import org.jetbrains.deft.ObjBuilder
import org.jetbrains.deft.Type
@GeneratedCodeApiVersion(1)
@GeneratedCodeImplVersion(1)
open class DefaultValueEntityImpl(val dataSource: DefaultValueEntityData) : DefaultValueEntity, WorkspaceEntityBase() {
companion object {
val connections = listOf<ConnectionId>(
)
}
override val name: String
get() = dataSource.name
override var isGenerated: Boolean = dataSource.isGenerated
override var anotherName: String = dataSource.anotherName
override fun connectionIdList(): List<ConnectionId> {
return connections
}
class Builder(val result: DefaultValueEntityData?) : ModifiableWorkspaceEntityBase<DefaultValueEntity>(), DefaultValueEntity.Builder {
constructor() : this(DefaultValueEntityData())
override fun applyToBuilder(builder: MutableEntityStorage) {
if (this.diff != null) {
if (existsInBuilder(builder)) {
this.diff = builder
return
}
else {
error("Entity DefaultValueEntity is already created in a different builder")
}
}
this.diff = builder
this.snapshot = builder
addToBuilder()
this.id = getEntityData().createEntityId()
// Process linked entities that are connected without a builder
processLinkedEntities(builder)
checkInitialization() // TODO uncomment and check failed tests
}
fun checkInitialization() {
val _diff = diff
if (!getEntityData().isEntitySourceInitialized()) {
error("Field WorkspaceEntity#entitySource should be initialized")
}
if (!getEntityData().isNameInitialized()) {
error("Field DefaultValueEntity#name should be initialized")
}
}
override fun connectionIdList(): List<ConnectionId> {
return connections
}
// Relabeling code, move information from dataSource to this builder
override fun relabel(dataSource: WorkspaceEntity, parents: Set<WorkspaceEntity>?) {
dataSource as DefaultValueEntity
this.entitySource = dataSource.entitySource
this.name = dataSource.name
this.isGenerated = dataSource.isGenerated
this.anotherName = dataSource.anotherName
if (parents != null) {
}
}
override var entitySource: EntitySource
get() = getEntityData().entitySource
set(value) {
checkModificationAllowed()
getEntityData().entitySource = value
changedProperty.add("entitySource")
}
override var name: String
get() = getEntityData().name
set(value) {
checkModificationAllowed()
getEntityData().name = value
changedProperty.add("name")
}
override var isGenerated: Boolean
get() = getEntityData().isGenerated
set(value) {
checkModificationAllowed()
getEntityData().isGenerated = value
changedProperty.add("isGenerated")
}
override var anotherName: String
get() = getEntityData().anotherName
set(value) {
checkModificationAllowed()
getEntityData().anotherName = value
changedProperty.add("anotherName")
}
override fun getEntityData(): DefaultValueEntityData = result ?: super.getEntityData() as DefaultValueEntityData
override fun getEntityClass(): Class<DefaultValueEntity> = DefaultValueEntity::class.java
}
}
class DefaultValueEntityData : WorkspaceEntityData<DefaultValueEntity>() {
lateinit var name: String
var isGenerated: Boolean = true
var anotherName: String = "Another Text"
fun isNameInitialized(): Boolean = ::name.isInitialized
override fun wrapAsModifiable(diff: MutableEntityStorage): ModifiableWorkspaceEntity<DefaultValueEntity> {
val modifiable = DefaultValueEntityImpl.Builder(null)
modifiable.allowModifications {
modifiable.diff = diff
modifiable.snapshot = diff
modifiable.id = createEntityId()
modifiable.entitySource = this.entitySource
}
modifiable.changedProperty.clear()
return modifiable
}
override fun createEntity(snapshot: EntityStorage): DefaultValueEntity {
return getCached(snapshot) {
val entity = DefaultValueEntityImpl(this)
entity.entitySource = entitySource
entity.snapshot = snapshot
entity.id = createEntityId()
entity
}
}
override fun getEntityInterface(): Class<out WorkspaceEntity> {
return DefaultValueEntity::class.java
}
override fun serialize(ser: EntityInformation.Serializer) {
}
override fun deserialize(de: EntityInformation.Deserializer) {
}
override fun createDetachedEntity(parents: List<WorkspaceEntity>): WorkspaceEntity {
return DefaultValueEntity(name, entitySource) {
this.isGenerated = [email protected]
this.anotherName = [email protected]
}
}
override fun getRequiredParents(): List<Class<out WorkspaceEntity>> {
val res = mutableListOf<Class<out WorkspaceEntity>>()
return res
}
override fun equals(other: Any?): Boolean {
if (other == null) return false
if (this::class != other::class) return false
other as DefaultValueEntityData
if (this.entitySource != other.entitySource) return false
if (this.name != other.name) return false
if (this.isGenerated != other.isGenerated) return false
if (this.anotherName != other.anotherName) return false
return true
}
override fun equalsIgnoringEntitySource(other: Any?): Boolean {
if (other == null) return false
if (this::class != other::class) return false
other as DefaultValueEntityData
if (this.name != other.name) return false
if (this.isGenerated != other.isGenerated) return false
if (this.anotherName != other.anotherName) return false
return true
}
override fun hashCode(): Int {
var result = entitySource.hashCode()
result = 31 * result + name.hashCode()
result = 31 * result + isGenerated.hashCode()
result = 31 * result + anotherName.hashCode()
return result
}
override fun hashCodeIgnoringEntitySource(): Int {
var result = javaClass.hashCode()
result = 31 * result + name.hashCode()
result = 31 * result + isGenerated.hashCode()
result = 31 * result + anotherName.hashCode()
return result
}
override fun collectClassUsagesData(collector: UsedClassesCollector) {
collector.sameForAllEntities = true
}
}
| apache-2.0 | 73fb05ac064cbc876accc742a1292bce | 32.061674 | 136 | 0.726049 | 5.255602 | false | false | false | false |
google/intellij-community | plugins/kotlin/base/project-structure/src/org/jetbrains/kotlin/idea/base/projectStructure/LibraryInfoCache.kt | 1 | 5305 | // 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.base.projectStructure
import com.intellij.openapi.components.service
import com.intellij.openapi.project.Project
import com.intellij.openapi.roots.OrderRootType
import com.intellij.openapi.roots.impl.libraries.LibraryEx
import com.intellij.openapi.roots.libraries.Library
import com.intellij.serviceContainer.AlreadyDisposedException
import com.intellij.util.PathUtil
import com.intellij.util.messages.Topic
import com.intellij.workspaceModel.ide.WorkspaceModelTopics
import org.jetbrains.kotlin.idea.base.util.caching.SynchronizedFineGrainedEntityCache
import org.jetbrains.kotlin.idea.base.platforms.LibraryEffectiveKindProvider
import org.jetbrains.kotlin.idea.base.platforms.isKlibLibraryRootForPlatform
import org.jetbrains.kotlin.idea.base.platforms.platform
import org.jetbrains.kotlin.idea.base.projectStructure.moduleInfo.*
import org.jetbrains.kotlin.idea.base.util.caching.LibraryEntityChangeListener
import org.jetbrains.kotlin.platform.IdePlatformKind
import org.jetbrains.kotlin.platform.TargetPlatform
import org.jetbrains.kotlin.platform.idePlatformKind
import org.jetbrains.kotlin.platform.impl.CommonIdePlatformKind
import org.jetbrains.kotlin.platform.impl.JsIdePlatformKind
import org.jetbrains.kotlin.platform.impl.JvmIdePlatformKind
import org.jetbrains.kotlin.platform.impl.NativeIdePlatformKind
import org.jetbrains.kotlin.platform.jvm.JvmPlatforms
import org.jetbrains.kotlin.utils.addToStdlib.flattenTo
class LibraryInfoCache(project: Project): SynchronizedFineGrainedEntityCache<Library, List<LibraryInfo>>(project, cleanOnLowMemory = true) {
override fun subscribe() {
val busConnection = project.messageBus.connect(this)
WorkspaceModelTopics.getInstance(project).subscribeImmediately(busConnection, ModelChangeListener(project))
}
override fun checkKeyValidity(key: Library) {
if (key is LibraryEx && key.isDisposed) {
throw AlreadyDisposedException("Library ${key.name} is already disposed")
}
}
override fun calculate(key: Library): List<LibraryInfo> {
val libraryInfos = when (val platformKind = getPlatform(key).idePlatformKind) {
is JvmIdePlatformKind -> listOf(JvmLibraryInfo(project, key))
is CommonIdePlatformKind -> createLibraryInfos(key, platformKind, ::CommonKlibLibraryInfo, ::CommonMetadataLibraryInfo)
is JsIdePlatformKind -> createLibraryInfos(key, platformKind, ::JsKlibLibraryInfo, ::JsMetadataLibraryInfo)
is NativeIdePlatformKind -> createLibraryInfos(key, platformKind, ::NativeKlibLibraryInfo, null)
else -> error("Unexpected platform kind: $platformKind")
}
return libraryInfos
}
override fun postProcessNewValue(key: Library, value: List<LibraryInfo>) {
project.messageBus.syncPublisher(LibraryInfoListener.TOPIC).libraryInfosAdded(value)
}
private fun createLibraryInfos(
library: Library,
platformKind: IdePlatformKind,
klibLibraryInfoFactory: (Project, Library, String) -> LibraryInfo,
metadataLibraryInfoFactory: ((Project, Library) -> LibraryInfo)?
): List<LibraryInfo> {
val defaultPlatform = platformKind.defaultPlatform
val klibFiles = library.getFiles(OrderRootType.CLASSES).filter { it.isKlibLibraryRootForPlatform(defaultPlatform) }
return if (klibFiles.isNotEmpty()) {
ArrayList<LibraryInfo>(klibFiles.size).apply {
for (file in klibFiles) {
val path = PathUtil.getLocalPath(file) ?: continue
add(klibLibraryInfoFactory(project, library, path))
}
}
} else if (metadataLibraryInfoFactory != null) {
listOfNotNull(metadataLibraryInfoFactory(project, library))
} else {
emptyList()
}
}
private fun getPlatform(library: Library): TargetPlatform {
if (library is LibraryEx && !library.isDisposed) {
return LibraryEffectiveKindProvider.getInstance(project).getEffectiveKind(library).platform
}
return JvmPlatforms.defaultJvmPlatform
}
internal class ModelChangeListener(project: Project) : LibraryEntityChangeListener(project, afterChangeApplied = false) {
override fun entitiesChanged(outdated: List<Library>) {
val libraryInfoCache = getInstance(project)
val droppedLibraryInfos = libraryInfoCache.invalidateKeysAndGetOutdatedValues(outdated).flattenTo(hashSetOf())
if (droppedLibraryInfos.isNotEmpty()) {
project.messageBus.syncPublisher(LibraryInfoListener.TOPIC).libraryInfosRemoved(droppedLibraryInfos)
}
}
}
companion object {
fun getInstance(project: Project): LibraryInfoCache = project.service()
}
}
interface LibraryInfoListener {
fun libraryInfosRemoved(libraryInfos: Collection<LibraryInfo>)
fun libraryInfosAdded(libraryInfos: Collection<LibraryInfo>) {}
companion object {
@JvmStatic
@Topic.ProjectLevel
val TOPIC = Topic.create("library info listener", LibraryInfoListener::class.java)
}
}
| apache-2.0 | ad87d61f625a57df85fd38265682f6b8 | 45.130435 | 140 | 0.742696 | 5.100962 | false | false | false | false |
google/intellij-community | tools/ideTestingFramework/intellij.tools.ide.starter/src/com/intellij/ide/starter/utils/retry.kt | 3 | 908 | package com.intellij.ide.starter.utils
import kotlinx.coroutines.delay
import kotlinx.coroutines.runBlocking
import kotlin.time.Duration.Companion.seconds
/** @return T - if successful; null - otherwise */
suspend fun <T> withRetryAsync(retries: Long = 3, messageOnFailure: String = "", retryAction: suspend () -> T): T? {
(1..retries).forEach { failureCount ->
try {
return retryAction()
}
catch (t: Throwable) {
if (messageOnFailure.isNotBlank())
logError(messageOnFailure)
t.printStackTrace()
if (failureCount < retries) {
logError("Retrying in 10 sec ...")
delay(10.seconds)
}
}
}
return null
}
/** @return T - if successful; null - otherwise */
fun <T> withRetry(retries: Long = 3, messageOnFailure: String = "", retryAction: () -> T): T? = runBlocking {
withRetryAsync(retries, messageOnFailure) { retryAction() }
}
| apache-2.0 | 0ac767595e0ed9d807d318c762842c15 | 25.705882 | 116 | 0.655286 | 4 | false | false | false | false |
JetBrains/intellij-community | platform/platform-api/src/com/intellij/ui/dsl/UiDslException.kt | 1 | 1972 | // 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.ui.dsl
import com.intellij.openapi.application.PathManager
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.project.Project
import com.intellij.ui.dsl.gridLayout.Constraints
import org.jetbrains.annotations.ApiStatus
import java.awt.Component
import java.nio.file.Files
import java.nio.file.Paths
import javax.swing.JComponent
@ApiStatus.Internal
class UiDslException(message: String = "Internal error", cause: Throwable? = null) : RuntimeException(message, cause) {
companion object {
fun error(message: String) {
if (runningFromSource) {
throw UiDslException(message)
}
else {
logger<UiDslException>().error(message)
}
}
}
}
@ApiStatus.Internal
fun checkTrue(value: Boolean) {
if (!value) {
throw UiDslException()
}
}
@ApiStatus.Internal
fun checkNonNegative(name: String, value: Int) {
if (value < 0) {
throw UiDslException("Value cannot be negative: $name = $value")
}
}
@ApiStatus.Internal
fun checkPositive(name: String, value: Int) {
if (value <= 0) {
throw UiDslException("Value must be positive: $name = $value")
}
}
@ApiStatus.Internal
fun checkComponent(component: Component?): JComponent {
if (component !is JComponent) {
throw UiDslException("Only JComponents are supported: $component")
}
return component
}
@ApiStatus.Internal
fun checkConstraints(constraints: Any?): Constraints {
if (constraints !is Constraints) {
throw UiDslException("Invalid constraints: $constraints")
}
return constraints
}
/**
* See [com.intellij.ide.plugins.PluginManagerCore.isRunningFromSources], which is not available here
*/
private val runningFromSource: Boolean by lazy(LazyThreadSafetyMode.PUBLICATION) {
Files.isDirectory(Paths.get(PathManager.getHomePath(), Project.DIRECTORY_STORE_FOLDER))
}
| apache-2.0 | 43496f2efe13c65eb5977c672fc211e4 | 26.013699 | 120 | 0.738844 | 4.065979 | false | false | false | false |
chrislo27/RhythmHeavenRemixEditor2 | core/src/main/kotlin/io/github/chrislo27/rhre3/screen/EditorVersionScreen.kt | 2 | 9929 | package io.github.chrislo27.rhre3.screen
import com.badlogic.gdx.Gdx
import com.badlogic.gdx.Input
import com.badlogic.gdx.graphics.Color
import com.badlogic.gdx.graphics.Texture
import com.badlogic.gdx.graphics.g2d.SpriteBatch
import com.badlogic.gdx.graphics.g2d.TextureRegion
import com.badlogic.gdx.graphics.glutils.ShapeRenderer
import com.badlogic.gdx.math.MathUtils
import io.github.chrislo27.rhre3.PreferenceKeys
import io.github.chrislo27.rhre3.RHRE3
import io.github.chrislo27.rhre3.RHRE3Application
import io.github.chrislo27.rhre3.analytics.AnalyticsHandler
import io.github.chrislo27.rhre3.stage.GenericStage
import io.github.chrislo27.toolboks.ToolboksScreen
import io.github.chrislo27.toolboks.i18n.Localization
import io.github.chrislo27.toolboks.registry.AssetRegistry
import io.github.chrislo27.toolboks.registry.ScreenRegistry
import io.github.chrislo27.toolboks.ui.Button
import io.github.chrislo27.toolboks.ui.TextLabel
import io.github.chrislo27.toolboks.version.Version
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import kotlin.properties.Delegates
class EditorVersionScreen(main: RHRE3Application)
: ToolboksScreen<RHRE3Application, EditorVersionScreen>(main) {
companion object {
private val DEFAULT_BEGINNING: Pair<Boolean, ToolboksScreen<*, *>?> = false to null
}
private enum class State {
CHECKING, GOOD, AVAILABLE;
}
override val stage: GenericStage<EditorVersionScreen> = GenericStage(main.uiPalette, null, main.defaultCamera)
private var state: State by Delegates.observable(State.CHECKING) { _, _, newState ->
checkButton.enabled = newState != State.CHECKING
longChangelogButton.visible = newState != State.AVAILABLE
shortChangelogButton.visible = newState == State.AVAILABLE
gotoUpdaterButton.visible = newState == State.AVAILABLE
}
private val label: TextLabel<EditorVersionScreen>
private val checkButton: Button<EditorVersionScreen>
private val longChangelogButton: Button<EditorVersionScreen>
private val shortChangelogButton: Button<EditorVersionScreen>
private val gotoUpdaterButton: Button<EditorVersionScreen>
var isBeginning: Pair<Boolean, ToolboksScreen<*, *>?> = DEFAULT_BEGINNING
private var timeOnScreen = 0f
private var timeToStayOnScreen = 0f
init {
val palette = stage.palette
stage.titleIcon.apply {
this.image = TextureRegion(AssetRegistry.get<Texture>("ui_icon_update"))
}
stage.backButton.visible = true
stage.backButton.tooltipTextIsLocalizationKey = true
stage.onBackButtonClick = {
main.screen = if (isBeginning.first) isBeginning.second else ScreenRegistry.getNonNull("info")
isBeginning = DEFAULT_BEGINNING
}
longChangelogButton = Button(palette, stage.bottomStage, stage.bottomStage).apply {
this.leftClickAction = { _, _ ->
Gdx.net.openURI(RHRE3.GITHUB_RELEASES)
val stage: GenericStage<EditorVersionScreen> = [email protected]
stage.backButton.enabled = true
}
this.addLabel(TextLabel(palette, this, this.stage).apply {
this.isLocalizationKey = true
this.textWrapping = false
this.text = "screen.version.viewChangelog"
})
this.location.set(screenX = 0.175f, screenWidth = 0.65f)
this.visible = true
}
stage.bottomStage.elements += longChangelogButton
checkButton = Button(palette, stage.bottomStage, stage.bottomStage).apply {
this.addLabel(TextLabel(palette, this, this.stage).apply {
this.isLocalizationKey = true
this.text = "screen.version.checkForUpdates"
this.fontScaleMultiplier = 0.9f
this.textWrapping = false
})
this.location.set(screenX = 0.85f, screenWidth = 0.15f)
this.leftClickAction = { _, _ ->
if ([email protected] != State.CHECKING) {
[email protected] = State.CHECKING
enabled = false
GlobalScope.launch {
main.fetchGithubVersion()
}
}
}
this.enabled = false
}
stage.bottomStage.elements += checkButton
shortChangelogButton = Button(palette, stage.bottomStage, stage.bottomStage).apply {
this.leftClickAction = { _, _ ->
Gdx.net.openURI(RHRE3.GITHUB_RELEASES + "/latest")
AnalyticsHandler.track("View Changelog", mapOf())
}
this.addLabel(TextLabel(palette, this, this.stage).apply {
this.isLocalizationKey = true
this.textWrapping = false
this.fontScaleMultiplier = 0.9f
this.text = "screen.version.viewChangelog.short"
})
this.location.set(screenX = 0.125f, screenWidth = 0.2f)
this.visible = false
}
stage.bottomStage.elements += shortChangelogButton
gotoUpdaterButton = Button(palette, stage.bottomStage, stage.bottomStage).apply {
this.leftClickAction = { _, _ ->
AnalyticsHandler.track("Run Auto-Updater", mapOf())
main.screen = AutoUpdaterScreen(main)
}
this.addLabel(TextLabel(palette, this, this.stage).apply {
this.isLocalizationKey = true
this.textWrapping = false
this.text = "screen.version.gotoUpdater"
this.textColor = Color.CYAN.cpy()
})
this.location.set(screenX = 0.35f, screenWidth = 0.475f)
this.visible = false
}
stage.bottomStage.elements += gotoUpdaterButton
label = object : TextLabel<EditorVersionScreen>(palette, stage.centreStage, stage.centreStage) {
private var lastGhVer: Version = main.githubVersion
override fun render(screen: EditorVersionScreen, batch: SpriteBatch, shapeRenderer: ShapeRenderer) {
if (lastGhVer != main.githubVersion || text.isEmpty()) {
lastGhVer = main.githubVersion
val ghVer = main.githubVersion
val currentVer: String = (if (ghVer.isUnknown)
"[LIGHT_GRAY]"
else if (ghVer <= RHRE3.VERSION)
"[CYAN]"
else
"[ORANGE]") + "${RHRE3.VERSION}[]"
val onlineVer: String = (if (ghVer.isUnknown)
"[LIGHT_GRAY]...[]"
else
"[CYAN]$ghVer[]")
val newState: State =
if (ghVer.isUnknown)
State.CHECKING
else if (ghVer <= RHRE3.VERSION && !RHRE3.triggerUpdateScreen)
State.GOOD
else
State.AVAILABLE
val humanFriendly: String = when (newState) {
State.CHECKING -> Localization["screen.version.checking"]
State.GOOD -> Localization["screen.version.upToDate"]
State.AVAILABLE -> Localization["screen.version.outOfDate",
main.preferences.getInteger(PreferenceKeys.TIMES_SKIPPED_UPDATE, 1)
.coerceAtLeast(1)]
}
[email protected] = newState
if (ghVer.major != 3)
gotoUpdaterButton.visible = false
text = Localization["screen.version.label", currentVer, onlineVer, humanFriendly]
}
super.render(screen, batch, shapeRenderer)
}
}.apply {
this.isLocalizationKey = false
this.textWrapping = true
}
stage.centreStage.elements += label
stage.updatePositions()
}
override fun renderUpdate() {
super.renderUpdate()
timeOnScreen += Gdx.graphics.deltaTime
if (timeOnScreen >= timeToStayOnScreen) {
stage.backButton.enabled = true
stage.backButton.tooltipText = null
if (Gdx.input.isKeyJustPressed(Input.Keys.ESCAPE)) {
stage.onBackButtonClick()
}
}
}
override fun show() {
super.show()
stage.titleLabel.text = "screen.version.title${MathUtils.random(0, 5)}"
timeOnScreen = 0f
if (isBeginning.first) {
stage.backButton.enabled = false
val timesSkipped = main.preferences.getInteger(PreferenceKeys.TIMES_SKIPPED_UPDATE, 1).coerceAtLeast(1)
val limitSkips = 5
val minWaitTime = 2f
val waitTimeAtLimit = 4f
val waitTimeAfterLimit = 6.5f
timeToStayOnScreen = if (timesSkipped <= limitSkips) ((waitTimeAtLimit / limitSkips) * timesSkipped).coerceAtLeast(minWaitTime) else waitTimeAfterLimit
// Analytics
AnalyticsHandler.track("Update Notification",
mapOf(
"timeToStayOnScreen" to timeToStayOnScreen,
"timesSkipped" to timesSkipped
))
}
checkButton.visible = !isBeginning.first
label.text = ""
}
override fun dispose() {
}
override fun tickUpdate() {
}
} | gpl-3.0 | 57c366649eed873211498613a203282f | 41.987013 | 163 | 0.586464 | 4.971958 | false | false | false | false |
allotria/intellij-community | plugins/markdown/src/org/intellij/plugins/markdown/injection/MarkdownCodeFenceUtils.kt | 3 | 4639 | // 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.injection
import com.intellij.lang.ASTNode
import com.intellij.lang.injection.InjectedLanguageManager
import com.intellij.openapi.util.TextRange
import com.intellij.psi.PsiDocumentManager
import com.intellij.psi.PsiElement
import com.intellij.psi.templateLanguages.OuterLanguageElement
import com.intellij.psi.util.PsiTreeUtil
import com.intellij.psi.util.elementType
import org.intellij.plugins.markdown.lang.MarkdownTokenTypeSets
import org.intellij.plugins.markdown.lang.MarkdownTokenTypes
import org.intellij.plugins.markdown.lang.psi.impl.MarkdownCodeFenceImpl
import org.intellij.plugins.markdown.util.MarkdownPsiUtil
import org.intellij.plugins.markdown.util.hasType
import org.intellij.plugins.markdown.util.parents
/**
* Utility functions used to work with Markdown Code Fences
*/
object MarkdownCodeFenceUtils {
/** Check if [node] is of CODE_FENCE type */
fun isCodeFence(node: ASTNode) = node.hasType(MarkdownTokenTypeSets.CODE_FENCE)
/** Check if [node] inside CODE_FENCE */
fun inCodeFence(node: ASTNode) = node.parents().any { it.hasType(MarkdownTokenTypeSets.CODE_FENCE) }
/**
* Get content of code fence as list of [PsiElement]
*
* @param withWhitespaces defines if whitespaces (including blockquote chars `>`) should be
* included in returned list. Otherwise, only new-line would be added.
*
* @return non-empty list of elements or null
*/
@JvmStatic
fun getContent(host: MarkdownCodeFenceImpl, withWhitespaces: Boolean): List<PsiElement>? {
var elements: List<PsiElement> = host.children.filter {
(it !is OuterLanguageElement
&& (it.node.elementType == MarkdownTokenTypes.CODE_FENCE_CONTENT
|| (MarkdownPsiUtil.WhiteSpaces.isNewLine(it))
//WHITE_SPACES may also include `>`
|| (withWhitespaces && MarkdownTokenTypeSets.WHITE_SPACES.contains(it.elementType))
)
)
}
//drop new line right after code fence lang definition
if (elements.isNotEmpty() && MarkdownPsiUtil.WhiteSpaces.isNewLine(elements.first())) {
elements = elements.drop(1)
}
//drop new right before code fence end
if (elements.isNotEmpty() && MarkdownPsiUtil.WhiteSpaces.isNewLine(elements.last())) {
elements = elements.dropLast(1)
}
return elements.takeIf { it.isNotEmpty() }
}
/**
* Check that code fence is reasonably formatted to accept injections
*
* Basically, it means that it has start and end code fence and at least
* one line (even empty) of text.
*/
@JvmStatic
fun isAbleToAcceptInjections(host: MarkdownCodeFenceImpl): Boolean {
if (host.children.all { !it.hasType(MarkdownTokenTypes.CODE_FENCE_END) }
|| host.children.all { !it.hasType(MarkdownTokenTypes.CODE_FENCE_START) }) {
return false
}
val newlines = host.children.count { MarkdownPsiUtil.WhiteSpaces.isNewLine(it) }
return newlines >= 2
}
/**
* Get valid empty range (in terms of Injection) for this code fence.
*
* Note, that this function should be used only if [getContent]
* returns null
*/
@JvmStatic
fun getEmptyRange(host: MarkdownCodeFenceImpl): TextRange {
val start = host.children.find { it.hasType(MarkdownTokenTypes.FENCE_LANG) }
?: host.children.find { it.hasType(MarkdownTokenTypes.CODE_FENCE_START) }
return TextRange.from(start!!.startOffsetInParent + start.textLength + 1, 0)
}
/**
* Get code fence if [element] is part of it.
*
* Would also work for injected elements.
*/
fun getCodeFence(element: PsiElement): MarkdownCodeFenceImpl? {
return InjectedLanguageManager.getInstance(element.project).getInjectionHost(element) as? MarkdownCodeFenceImpl?
?: PsiTreeUtil.getParentOfType(element, MarkdownCodeFenceImpl::class.java)
}
/**
* Get indent for this code fence.
*
* If code-fence is blockquoted indent may include `>` char.
* Note that indent should be used only for non top-level fences,
* top-level fences should use indentation from formatter.
*/
@JvmStatic
fun getIndent(element: MarkdownCodeFenceImpl): String? {
val document = PsiDocumentManager.getInstance(element.project).getDocument(element.containingFile) ?: return null
val offset = element.textOffset
val lineStartOffset = document.getLineStartOffset(document.getLineNumber(offset))
return document.getText(TextRange.create(lineStartOffset, offset)).replace("[^> ]".toRegex(), " ")
}
} | apache-2.0 | 7f39ff734736ce3e181f64a5b08313c4 | 38.65812 | 140 | 0.729036 | 4.359962 | false | false | false | false |
android/wear-os-samples | WearSpeakerSample/wear/src/main/java/com/example/android/wearable/speaker/SpeakerScreen.kt | 1 | 7189 | /*
* Copyright 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.android.wearable.speaker
import android.content.res.Configuration
import androidx.compose.animation.AnimatedVisibility
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.tooling.preview.Devices
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.tooling.preview.PreviewParameter
import androidx.compose.ui.tooling.preview.datasource.CollectionPreviewParameterProvider
import androidx.compose.ui.unit.dp
import androidx.constraintlayout.compose.ConstraintLayout
import androidx.constraintlayout.compose.Dimension
import androidx.wear.compose.material.ExperimentalWearMaterialApi
import androidx.wear.compose.material.Scaffold
import androidx.wear.compose.material.TimeText
/**
* The composable responsible for displaying the main UI.
*
* This composable is stateless, and simply displays the state given to it.
*/
@OptIn(ExperimentalWearMaterialApi::class)
@Composable
fun SpeakerScreen(
playbackState: PlaybackState,
isPermissionDenied: Boolean,
recordingProgress: Float,
onMicClicked: () -> Unit,
onPlayClicked: () -> Unit,
onMusicClicked: () -> Unit
) {
Scaffold(
timeText = {
TimeText()
}
) {
// Determine the control dashboard state.
// This converts the main app state into a control dashboard state for rendering
val controlDashboardUiState = computeControlDashboardUiState(
playbackState = playbackState,
isPermissionDenied = isPermissionDenied
)
// The progress bar should only be visible when actively recording
val isProgressVisible =
when (playbackState) {
PlaybackState.PlayingMusic,
PlaybackState.PlayingVoice,
is PlaybackState.Ready -> false
PlaybackState.Recording -> true
}
// We are using ConstraintLayout here to center the ControlDashboard, and align the progress
// indicator to it.
// In general, ConstraintLayout is less necessary for Compose than it was for Views
ConstraintLayout(
modifier = Modifier.fillMaxSize()
) {
val (controlDashboard, progressBar) = createRefs()
ControlDashboard(
controlDashboardUiState = controlDashboardUiState,
onMicClicked = onMicClicked,
onPlayClicked = onPlayClicked,
onMusicClicked = onMusicClicked,
modifier = Modifier
.constrainAs(controlDashboard) {
centerTo(parent)
}
)
AnimatedVisibility(
visible = isProgressVisible,
modifier = Modifier
.constrainAs(progressBar) {
width = Dimension.fillToConstraints
top.linkTo(controlDashboard.bottom, 5.dp)
start.linkTo(controlDashboard.start)
end.linkTo(controlDashboard.end)
}
) {
LinearProgressIndicator(
progress = recordingProgress
)
}
}
}
}
private fun computeControlDashboardUiState(
playbackState: PlaybackState,
isPermissionDenied: Boolean
): ControlDashboardUiState =
when (playbackState) {
PlaybackState.PlayingMusic -> ControlDashboardUiState(
micState = ControlDashboardButtonUiState(
expanded = false,
enabled = false,
visible = false
),
playState = ControlDashboardButtonUiState(
expanded = false,
enabled = false,
visible = false
),
musicState = ControlDashboardButtonUiState(
expanded = true,
enabled = true,
visible = true
)
)
PlaybackState.PlayingVoice -> ControlDashboardUiState(
micState = ControlDashboardButtonUiState(
expanded = false,
enabled = false,
visible = false
),
playState = ControlDashboardButtonUiState(
expanded = true,
enabled = true,
visible = true
),
musicState = ControlDashboardButtonUiState(
expanded = false,
enabled = false,
visible = false
)
)
PlaybackState.Ready -> ControlDashboardUiState(
micState = ControlDashboardButtonUiState(
expanded = false,
enabled = !isPermissionDenied,
visible = true
),
playState = ControlDashboardButtonUiState(
expanded = false,
enabled = true,
visible = true
),
musicState = ControlDashboardButtonUiState(
expanded = false,
enabled = true,
visible = true
)
)
PlaybackState.Recording -> ControlDashboardUiState(
micState = ControlDashboardButtonUiState(
expanded = true,
enabled = true,
visible = true
),
playState = ControlDashboardButtonUiState(
expanded = false,
enabled = false,
visible = false
),
musicState = ControlDashboardButtonUiState(
expanded = false,
enabled = false,
visible = false
)
)
}
private class PlaybackStatePreviewProvider : CollectionPreviewParameterProvider<PlaybackState>(
listOf(
PlaybackState.Ready,
PlaybackState.Recording,
PlaybackState.PlayingVoice,
PlaybackState.PlayingMusic
)
)
@Preview(
device = Devices.WEAR_OS_SMALL_ROUND,
showSystemUi = true,
widthDp = 200,
heightDp = 200,
uiMode = Configuration.UI_MODE_TYPE_WATCH
)
@Composable
fun SpeakerScreenPreview(
@PreviewParameter(PlaybackStatePreviewProvider::class) playbackState: PlaybackState
) {
SpeakerScreen(
playbackState = playbackState,
isPermissionDenied = true,
recordingProgress = 0.25f,
onMicClicked = {},
onPlayClicked = {},
onMusicClicked = {}
)
}
| apache-2.0 | e6fe3fbe542a27023b3837356ef3e941 | 33.233333 | 100 | 0.602726 | 5.665091 | false | false | false | false |
allotria/intellij-community | plugins/github/src/org/jetbrains/plugins/github/api/data/pullrequest/GHPullRequestRequestedReviewer.kt | 3 | 743 | // Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.plugins.github.api.data.pullrequest
import com.fasterxml.jackson.annotation.JsonSubTypes
import com.fasterxml.jackson.annotation.JsonTypeInfo
import org.jetbrains.plugins.github.api.data.GHUser
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "__typename", visible = false)
@JsonSubTypes(
JsonSubTypes.Type(name = "User", value = GHUser::class),
JsonSubTypes.Type(name = "Team", value = GHTeam::class)
)
interface GHPullRequestRequestedReviewer {
val shortName: String
val url: String
val avatarUrl: String
val name: String?
} | apache-2.0 | a5c98f1857cab1b6652ad3832bfc51ad | 40.333333 | 140 | 0.777927 | 4.016216 | false | false | false | false |
qkuronekop/MovingView | gesturetransformableview/src/main/java/jp/gr/java_conf/qkuronekop/gesturetransformableview/view/GestureTransformableImageView.kt | 1 | 4749 | package jp.gr.java_conf.qkuronekop.gesturetransformableview.view
import android.content.Context
import android.graphics.PointF
import android.util.AttributeSet
import android.view.MotionEvent
import android.view.View
import android.view.View.OnTouchListener
import android.widget.ImageView
import jp.gr.java_conf.qkuronekop.gesturetransformableview.detector.DragGestureDetector
import jp.gr.java_conf.qkuronekop.gesturetransformableview.detector.PinchGestureDetector
import jp.gr.java_conf.qkuronekop.gesturetransformableview.detector.RotateGestureDetector
import jp.gr.java_conf.qkuronekop.gesturetransformableview.listener.DragGestureListener
import jp.gr.java_conf.qkuronekop.gesturetransformableview.listener.PinchGestureListener
import jp.gr.java_conf.qkuronekop.gesturetransformableview.listener.RotateGestureListener
class GestureTransformableImageView : ImageView, OnTouchListener, DragGestureListener, PinchGestureListener, RotateGestureListener {
private var limitScaleMax = DEFAULT_LIMIT_SCALE_MAX
private var limitScaleMin = DEFAULT_LIMIT_SCALE_MIN
private var scaleFactor = 1.0f
private var rotateGestureDetector: RotateGestureDetector? = null
private var dragGestureDetector: DragGestureDetector? = null
private var pinchGestureDetector: PinchGestureDetector? = null
private var angle: Float = 0.toFloat()
constructor(context: Context, attrs: AttributeSet, defStyle: Int) : super(context, attrs,
defStyle) {
init(context, GESTURE_DRAGGABLE or GESTURE_ROTATABLE or GESTURE_SCALABLE)
}
constructor(context: Context, attrs: AttributeSet) : super(context, attrs) {
init(context, GESTURE_DRAGGABLE or GESTURE_ROTATABLE or GESTURE_SCALABLE)
}
constructor(context: Context) : super(context) {
init(context, GESTURE_DRAGGABLE or GESTURE_ROTATABLE or GESTURE_SCALABLE)
}
constructor(context: Context, gestureFlag: Int) : super(context) {
init(context, gestureFlag)
}
fun setLimitScaleMax(limit: Float) {
this.limitScaleMax = limit
}
fun setLimitScaleMin(limit: Float) {
this.limitScaleMin = limit
}
override fun onAttachedToWindow() {
super.onAttachedToWindow()
rotateGestureDetector?.rotationGestureListener = this
dragGestureDetector?.dragGestureListener = this
pinchGestureDetector?.pinchGestureListener = this
}
override fun onTouch(v: View, event: MotionEvent): Boolean {
rotateGestureDetector?.onTouchEvent(event)
dragGestureDetector?.onTouchEvent(event)
pinchGestureDetector?.onTouchEvent(event)
return true
}
private fun init(context: Context, gestureFlag: Int) {
setOnTouchListener(this)
if (gestureFlag and GESTURE_DRAGGABLE == GESTURE_DRAGGABLE) {
dragGestureDetector = DragGestureDetector()
}
if (gestureFlag and GESTURE_ROTATABLE == GESTURE_ROTATABLE) {
rotateGestureDetector = RotateGestureDetector()
}
if (gestureFlag and GESTURE_SCALABLE == GESTURE_SCALABLE) {
pinchGestureDetector = PinchGestureDetector()
}
}
private fun rotateXY(centerX: Float, centerY: Float, angle: Float, x: Float, y: Float): PointF {
val rad = Math.toRadians(angle.toDouble())
val resultX = ((x - centerX) * Math.cos(rad) - (y - centerY) * Math.sin(
rad) + centerX).toFloat()
val resultY = ((x - centerX) * Math.sin(rad) + (y - centerY) * Math.cos(
rad) + centerY.toDouble()).toFloat()
return PointF(resultX, resultY)
}
override fun onDragGestureListener(dragGestureDetector: DragGestureDetector) {
var dx = dragGestureDetector.deltaX
var dy = dragGestureDetector.deltaY
val pf = rotateXY(0f, 0f, angle, dx, dy)
dx = pf.x
dy = pf.y
x += dx * scaleFactor
y += dy * scaleFactor
}
override fun onPinchGestureListener(dragGestureDetector: PinchGestureDetector) {
val scale = dragGestureDetector.distance / dragGestureDetector.preDistance
val tmpScale = scaleFactor * scale
if (limitScaleMin <= tmpScale && tmpScale <= limitScaleMax) {
scaleFactor = tmpScale
scaleX = scaleFactor
scaleY = scaleFactor
return
}
}
override fun onRotation(detector: RotateGestureDetector) {
angle += detector.deltaAngle
rotation += detector.deltaAngle
}
override fun onRotationBegin(detector: RotateGestureDetector) {
}
override fun onRotationEnd(detector: RotateGestureDetector) {
}
companion object {
val GESTURE_DRAGGABLE = 0x0001
val GESTURE_ROTATABLE = 0x0002
val GESTURE_SCALABLE = 0x0004
val DEFAULT_LIMIT_SCALE_MAX = 6.0f
val DEFAULT_LIMIT_SCALE_MIN = 0.2f
}
}
| mit | 240cf8ff739f73a74ec106df0aa4f9f1 | 29.243421 | 132 | 0.722257 | 4.062447 | false | false | false | false |
agoda-com/Kakao | kakao/src/main/kotlin/com/agoda/kakao/intent/ActivityResultBuilder.kt | 1 | 754 | @file:Suppress("unused")
package com.agoda.kakao.intent
import android.app.Activity
import android.app.Instrumentation
import android.content.Intent
import com.agoda.kakao.common.KakaoDslMarker
/**
* Class for building ActivityResult
*/
@KakaoDslMarker
class ActivityResultBuilder {
private var code = Activity.RESULT_OK
private var data: Intent? = null
/**
* Sets given result code
*
* @param code Result code to be saved
*/
fun withCode(code: Int) {
this.code = code
}
/**
* Sets given result data
*
* @param data Result data to be saved
*/
fun withData(data: Intent) {
this.data = data
}
fun getResult() = Instrumentation.ActivityResult(code, data)
}
| apache-2.0 | 923a611b9525c7c957b039856c1ac98e | 19.378378 | 64 | 0.655172 | 4.032086 | false | false | false | false |
leafclick/intellij-community | platform/lang-impl/src/com/intellij/facet/impl/FacetTypeRegistryImpl.kt | 1 | 7014 | // 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.facet.impl
import com.intellij.facet.*
import com.intellij.facet.impl.invalid.InvalidFacetManager
import com.intellij.facet.impl.invalid.InvalidFacetType
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.application.runWriteAction
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.extensions.ExtensionPointListener
import com.intellij.openapi.extensions.PluginDescriptor
import com.intellij.openapi.project.Project
import com.intellij.openapi.project.ProjectManager
import org.jetbrains.jps.model.serialization.facet.FacetState
import java.util.*
class FacetTypeRegistryImpl : FacetTypeRegistry() {
private val myTypeIds: MutableMap<String, FacetTypeId<*>> = HashMap()
private val myFacetTypes: MutableMap<FacetTypeId<*>, FacetType<*, *>> = HashMap()
private var myExtensionsLoaded = false
@Synchronized
override fun registerFacetType(facetType: FacetType<*, *>) {
val typeId = facetType.id
val id = facetType.stringId
LOG.assertTrue(!id.contains("/"), "Facet type id '$id' contains illegal character '/'")
LOG.assertTrue(!myFacetTypes.containsKey(typeId), "Facet type '$id' is already registered")
myFacetTypes[typeId] = facetType
LOG.assertTrue(!myTypeIds.containsKey(id), "Facet type id '$id' is already registered")
myTypeIds[id] = typeId
}
private fun loadInvalidFacetsOfType(project: Project, facetType: FacetType<*, *>) {
val modulesWithFacets = InvalidFacetManager.getInstance(project).invalidFacets
.filter { it.configuration.facetState.facetType == facetType.stringId }
.mapTo(HashSet()) { it.module }
for (module in modulesWithFacets) {
val model = FacetManager.getInstance(module).createModifiableModel()
val invalidFacets = model.getFacetsByType(InvalidFacetType.TYPE_ID).filter { it.configuration.facetState.facetType == facetType.stringId }
for (invalidFacet in invalidFacets) {
val newFacet = FacetManagerImpl.createFacetFromStateRaw(module, facetType, invalidFacet.configuration.facetState,
invalidFacet.underlyingFacet)
model.replaceFacet(invalidFacet, newFacet)
for (subFacet in invalidFacet.configuration.facetState.subFacets) {
model.addFacet(FacetManagerBase.createInvalidFacet(module, subFacet, newFacet, invalidFacet.configuration.errorMessage, false, false))
}
}
model.commit()
}
}
@Synchronized
override fun unregisterFacetType(facetType: FacetType<*, *>) {
try {
ProjectManager.getInstance().openProjects.forEach {
convertFacetsToInvalid(it, facetType)
}
}
finally {
val id = facetType.id
val stringId = facetType.stringId
LOG.assertTrue(myFacetTypes.remove(id) != null, "Facet type '$stringId' is not registered")
myFacetTypes.remove(id)
myTypeIds.remove(stringId)
}
}
private fun convertFacetsToInvalid(project: Project, facetType: FacetType<*, *>) {
val modulesWithFacets = ProjectFacetManager.getInstance(project).getFacets(facetType.id).mapTo(HashSet()) { it.module }
for (module in modulesWithFacets) {
val model = FacetManager.getInstance(module).createModifiableModel()
val subFacets = model.allFacets.groupBy { it.underlyingFacet }
val facets = model.getFacetsByType(facetType.id)
for (facet in facets) {
val facetState = saveFacetWithSubFacets(facet, subFacets) ?: continue
val pluginName = facetType.pluginDescriptor?.name?.let { " '$it'" } ?: ""
val errorMessage = "Plugin$pluginName which provides support for '${facetType.presentableName}' facets is unloaded"
val reportError = !ApplicationManager.getApplication().isUnitTestMode
val invalidFacet = FacetManagerBase.createInvalidFacet(module, facetState, facet.underlyingFacet, errorMessage, true, reportError)
removeAllSubFacets(model, facet, subFacets)
model.replaceFacet(facet, invalidFacet)
}
model.commit()
}
}
private fun removeAllSubFacets(model: ModifiableFacetModel, facet: Facet<*>, subFacets: Map<Facet<*>, List<Facet<*>>>) {
val toRemove = subFacets[facet] ?: return
for (subFacet in toRemove) {
removeAllSubFacets(model, subFacet, subFacets)
model.removeFacet(subFacet)
}
}
private fun saveFacetWithSubFacets(facet: Facet<*>?, subFacets: Map<Facet<FacetConfiguration>, List<Facet<*>>>): FacetState? {
val state = FacetManagerImpl.saveFacetConfiguration(facet) ?: return null
(subFacets[facet] ?: emptyList()).mapNotNullTo(state.subFacets) { saveFacetWithSubFacets(it, subFacets) }
return state
}
@Synchronized
override fun getFacetTypeIds(): Array<FacetTypeId<*>> {
loadExtensions()
return myFacetTypes.keys.toTypedArray()
}
@Synchronized
override fun getFacetTypes(): Array<FacetType<*, *>> {
loadExtensions()
val facetTypes = myFacetTypes.values.toTypedArray()
Arrays.sort(facetTypes, FACET_TYPE_COMPARATOR)
return facetTypes
}
override fun getSortedFacetTypes(): Array<FacetType<*, *>> {
val types = facetTypes
Arrays.sort(types, FACET_TYPE_COMPARATOR)
return types
}
@Synchronized
override fun findFacetType(id: String): FacetType<*, *>? {
loadExtensions()
val typeId = myTypeIds[id] ?: return null
return myFacetTypes[typeId]
}
@Synchronized
override fun <F : Facet<C>?, C : FacetConfiguration?> findFacetType(typeId: FacetTypeId<F>): FacetType<F, C> {
loadExtensions()
@Suppress("UNCHECKED_CAST")
val type = myFacetTypes[typeId] as FacetType<F, C>?
LOG.assertTrue(type != null, "Cannot find facet by id '$typeId'")
return type!!
}
private fun loadExtensions() {
if (myExtensionsLoaded) {
return
}
FacetType.EP_NAME.forEachExtensionSafe {
registerFacetType(it)
}
myExtensionsLoaded = true
FacetType.EP_NAME.addExtensionPointListener(
object : ExtensionPointListener<FacetType<*, *>?> {
override fun extensionAdded(extension: FacetType<*, *>, pluginDescriptor: PluginDescriptor) {
registerFacetType(extension)
runWriteAction {
ProjectManager.getInstance().openProjects.forEach {
loadInvalidFacetsOfType(it, extension)
}
}
}
override fun extensionRemoved(extension: FacetType<*, *>,
pluginDescriptor: PluginDescriptor) {
unregisterFacetType(extension)
}
}, null)
}
companion object {
private val LOG = Logger.getInstance(FacetTypeRegistryImpl::class.java)
private val FACET_TYPE_COMPARATOR = Comparator { o1: FacetType<*, *>, o2: FacetType<*, *> ->
o1.presentableName.compareTo(o2.presentableName, ignoreCase = true)
}
}
} | apache-2.0 | aab788762e1cf6b11c1b9f3c5d6513f9 | 40.508876 | 144 | 0.706017 | 4.635823 | false | false | false | false |
vicboma1/Kotlin-Koans | src/main/java/v_builders/_39_HtmlBuilders.kt | 1 | 1274 | package v_builders
import util.TODO
import util.doc39
import v_builders.data.getProducts
import v_builders.htmlLibrary.*
fun getTitleColor() = "#b9c9fe"
fun getCellColor(index: Int, row: Int) = if ((index + row) %2 == 0) "#dce4ff" else "#eff2ff"
fun todoTask39(): Nothing = TODO(
"""
Task 39.
1) Fill the table with the proper values from products.
2) Color the table like a chess board (using getTitleColor() and getCellColor() functions above).
Pass a color as an argument to functions 'tr', 'td'.
You can run the 'Html Demo' configuration in IntelliJ to see the rendered table.
""",
documentation = doc39()
)
fun renderProductTable(): String {
return html {
table {
tr (color = getTitleColor(), init = {
td { this.text("Product") }
td { this.text("Price") }
td { this.text("Popularity") }
})
val products = getProducts()
products.forEachIndexed { i, product ->
tr{
td{ this.text(product.description) }
td{ this.text(product.price) }
td{ this.text(product.popularity) }
}
}
}
}.toString()
}
| mit | 6904d5f58debac40708afe6d77cd1ff0 | 30.85 | 105 | 0.55416 | 4.163399 | false | false | false | false |
JuliusKunze/kotlin-native | backend.native/tests/external/codegen/box/evaluate/maxValue.kt | 2 | 1385 | // TODO: muted automatically, investigate should it be ran for JS or not
// IGNORE_BACKEND: JS, NATIVE
// WITH_RUNTIME
@Retention(AnnotationRetention.RUNTIME)
annotation class Ann(
val p1: Int,
val p2: Int,
val p3: Int,
val p4: Int,
val p5: Long,
val p6: Long
)
@Ann(
p1 = java.lang.Byte.MAX_VALUE + 1,
p2 = java.lang.Short.MAX_VALUE + 1,
p3 = java.lang.Integer.MAX_VALUE + 1,
p4 = java.lang.Integer.MAX_VALUE + 1,
p5 = java.lang.Integer.MAX_VALUE + 1.toLong(),
p6 = java.lang.Long.MAX_VALUE + 1
) class MyClass
fun box(): String {
val annotation = MyClass::class.java.getAnnotation(Ann::class.java)!!
if (annotation.p1 != 128) return "fail 1, expected = ${128}, actual = ${annotation.p1}"
if (annotation.p2 != 32768) return "fail 2, expected = ${32768}, actual = ${annotation.p2}"
if (annotation.p3 != -2147483648) return "fail 3, expected = ${-2147483648}, actual = ${annotation.p3}"
if (annotation.p4 != -2147483648) return "fail 4, expected = ${-2147483648}, actual = ${annotation.p4}"
if (annotation.p5 != 2147483648.toLong()) return "fail 5, expected = ${2147483648}, actual = ${annotation.p5}"
if (annotation.p6 != java.lang.Long.MAX_VALUE + 1) return "fail 5, expected = ${java.lang.Long.MAX_VALUE + 1}, actual = ${annotation.p6}"
return "OK"
}
| apache-2.0 | e7dfe5c774bcdfa342a9eb3707c7e071 | 39.735294 | 141 | 0.623827 | 3.281991 | false | false | false | false |
Nunnery/MythicDrops | src/main/kotlin/com/tealcube/minecraft/bukkit/mythicdrops/socketing/combiners/MythicSocketGemCombinerGui.kt | 1 | 16770 | /*
* This file is part of MythicDrops, licensed under the MIT License.
*
* Copyright (C) 2019 Richard Harrah
*
* 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.tealcube.minecraft.bukkit.mythicdrops.socketing.combiners
import com.tealcube.minecraft.bukkit.mythicdrops.api.settings.SettingsManager
import com.tealcube.minecraft.bukkit.mythicdrops.api.socketing.SocketGem
import com.tealcube.minecraft.bukkit.mythicdrops.api.socketing.combiners.SocketGemCombinerGui
import com.tealcube.minecraft.bukkit.mythicdrops.chatColorize
import com.tealcube.minecraft.bukkit.mythicdrops.isSlotEmpty
import com.tealcube.minecraft.bukkit.mythicdrops.setDisplayNameChatColorized
import com.tealcube.minecraft.bukkit.mythicdrops.setLoreChatColorized
import com.tealcube.minecraft.bukkit.mythicdrops.socketing.SocketItem
import com.tealcube.minecraft.bukkit.mythicdrops.utils.GemUtil
import io.pixeloutlaw.minecraft.spigot.bandsaw.JulLoggerFactory
import org.bukkit.Bukkit
import org.bukkit.Material
import org.bukkit.entity.HumanEntity
import org.bukkit.entity.Player
import org.bukkit.event.Event
import org.bukkit.event.EventHandler
import org.bukkit.event.HandlerList
import org.bukkit.event.inventory.InventoryClickEvent
import org.bukkit.event.inventory.InventoryCloseEvent
import org.bukkit.inventory.Inventory
import org.bukkit.inventory.ItemStack
import org.bukkit.inventory.PlayerInventory
import java.util.UUID
class MythicSocketGemCombinerGui(
private val settingsManager: SettingsManager
) : SocketGemCombinerGui {
companion object {
const val size = 45
const val slot1 = 10
const val slot2 = 12
const val slot3 = 14
const val slot4 = 16
const val resultSlot = 31
val slots = listOf(slot1, slot2, slot3, slot4)
private val logger = JulLoggerFactory.getLogger(MythicSocketGemCombinerGui::class)
}
private val socketingSettings by lazy { settingsManager.socketingSettings }
private val socketGemCombinerOptions by lazy { socketingSettings.items.socketGemCombiner }
private val uuid = UUID.randomUUID()
private val inv: Inventory = Bukkit.createInventory(
this, size, socketGemCombinerOptions.name.chatColorize()
)
private val clickToCombineButton = ItemStack(socketGemCombinerOptions.clickToCombine.material).apply {
setDisplayNameChatColorized(socketGemCombinerOptions.clickToCombine.name)
}
private val ineligibleToCombineButton =
ItemStack(socketGemCombinerOptions.ineligibleToCombineOptions.material).apply {
setDisplayNameChatColorized(socketGemCombinerOptions.ineligibleToCombineOptions.name)
}
private val sameFamilyButton = ineligibleToCombineButton.clone().apply {
setLoreChatColorized(socketGemCombinerOptions.ineligibleToCombineOptions.sameFamilyLore)
}
private val sameLevelButton = ineligibleToCombineButton.clone().apply {
setLoreChatColorized(socketGemCombinerOptions.ineligibleToCombineOptions.sameLevelLore)
}
private val sameFamilyAndLevelButton = ineligibleToCombineButton.clone().apply {
setLoreChatColorized(socketGemCombinerOptions.ineligibleToCombineOptions.sameFamilyAndLevelLore)
}
private val noGemFoundButton = ineligibleToCombineButton.clone().apply {
setLoreChatColorized(socketGemCombinerOptions.ineligibleToCombineOptions.noGemFoundLore)
}
private var combinedGem: SocketGem? = null
init {
val buffer = ItemStack(socketGemCombinerOptions.buffer.material)
buffer.setDisplayNameChatColorized(socketGemCombinerOptions.buffer.name.chatColorize())
for (slot in 0 until size) {
if (slots.plus(resultSlot).contains(slot)) {
continue
}
inv.setItem(slot, buffer)
}
inv.maxStackSize = 1
}
override fun getInventory(): Inventory = inv
@EventHandler
override fun onGuiClick(event: InventoryClickEvent) {
if (event.isCancelled) {
logger.fine("event.isCancelled uuid=$uuid")
return
}
if (event.inventory.holder != this) {
logger.fine("event.inventory.holder != this uuid=$uuid")
return
}
event.result = Event.Result.DENY
val currentItem = event.currentItem
if (currentItem == null || currentItem.type == Material.AIR) {
logger.fine("currentItem == null || currentItem.type == Material.AIR uuid=$uuid")
return
}
val eventInventory = inventory
val player = event.whoClicked as? Player ?: return
val clickedInventory = event.clickedInventory
if (clickedInventory == null) {
logger.fine("clickedInventory == null uuid=$uuid")
return
}
when (clickedInventory.holder) {
is HumanEntity -> {
logger.fine("clickedInventory.holder is HumanEntity uuid=$uuid")
handleAddGemToCombiner(currentItem, player, eventInventory, event.slot)
}
is SocketGemCombinerGui -> {
logger.fine("clickedInventory.holder is SocketGemCombinerGui uuid=$uuid")
handleRemoveGemFromCombiner(currentItem, player, eventInventory, event.slot)
}
}
}
@EventHandler
override fun onGuiClose(event: InventoryCloseEvent) {
if (event.inventory.holder != this) {
return
}
listOfNotNull(
event.inventory.getItem(slot1),
event.inventory.getItem(slot2),
event.inventory.getItem(slot3),
event.inventory.getItem(slot4),
event.inventory.getItem(resultSlot)
).filter(this::isSocketGem)
.forEach {
if (event.player.inventory.firstEmpty() != -1) {
event.player.inventory.addItem(it)
} else {
event.player.world.dropItem(event.player.location, it)
}
}
HandlerList.unregisterAll(this)
}
override fun showToPlayer(player: Player) {
player.openInventory(inv)
}
private fun handleAddGemToCombiner(currentItem: ItemStack, player: Player, eventInventory: Inventory, slot: Int) {
val playerInventory = player.inventory
val clickedItem = currentItem.clone()
val resultSlotItem = (eventInventory.getItem(31) ?: ItemStack(Material.BARRIER)).clone()
// if clicked item is not a socket gem, we don't allow that in the combiner
if (!isSocketGem(clickedItem)) {
logger.fine("!isSocketGem(clickedItem) uuid=$uuid")
player.sendMessage(settingsManager.languageSettings.socketing.combinerMustBeGem.chatColorize())
return
}
// if the result item is already a socket gem, they need to claim it first
if (isSocketGem(resultSlotItem)) {
logger.fine("isSocketGem(resultSlotItem) uuid=$uuid")
player.sendMessage(settingsManager.languageSettings.socketing.combinerClaimOutput.chatColorize())
return
}
val firstEmptyCombinerSlot = getEmptySocketCombinerSlot(eventInventory)
if (firstEmptyCombinerSlot == -1) {
logger.fine("firstEmptyCombinerSlot == -1 uuid=$uuid")
return
}
val newGem = clickedItem.clone()
val oldGem = clickedItem.clone()
newGem.amount = 1
oldGem.amount = oldGem.amount - 1
eventInventory.setItem(firstEmptyCombinerSlot, newGem)
playerInventory.setItem(slot, oldGem)
if (getEmptySocketCombinerSlot(eventInventory) != -1) {
logger.fine("getEmptySocketCombinerSlot(eventInventory) != -1 uuid=$uuid")
return
}
val requireSameFamily = socketingSettings.combining.isRequireSameFamily
val requireSameLevel = socketingSettings.combining.isRequireSameLevel
val socketGemsInCombiner = getSocketGemsFromSlots(eventInventory)
val allHaveSameFamily = GemUtil.doAllGemsHaveSameFamily(socketGemsInCombiner)
val allHaveSameLevel = GemUtil.doAllGemsHaveSameLevel(socketGemsInCombiner)
val allHaveSameFamilyAndLevel = allHaveSameFamily && allHaveSameLevel
if (requireSameFamily && requireSameLevel) {
handleSameFamilyAndSameLevel(allHaveSameFamilyAndLevel, socketGemsInCombiner, eventInventory)
return
}
if (requireSameFamily) {
handleSameFamily(allHaveSameFamily, socketGemsInCombiner, eventInventory)
return
}
if (requireSameLevel) {
handleSameLevel(allHaveSameLevel, socketGemsInCombiner, eventInventory)
return
}
handleNoRequirements(socketGemsInCombiner, eventInventory)
}
private fun handleNoRequirements(
socketGemsInCombiner: List<SocketGem>,
eventInventory: Inventory
) {
logger.fine("no requirements uuid=$uuid")
val averageLevel = socketGemsInCombiner.map { it.level }.average().toInt()
val foundGem = GemUtil.getRandomSocketGemByWeightWithLevel(averageLevel + 1)
handleGemIfFound(foundGem, eventInventory)
}
private fun handleSameLevel(
allHaveSameLevel: Boolean,
socketGemsInCombiner: List<SocketGem>,
eventInventory: Inventory
) {
logger.fine("requireSameLevel uuid=$uuid")
if (allHaveSameLevel) {
logger.fine("allHaveSameLevel uuid=$uuid")
val firstGem = socketGemsInCombiner.first()
val foundGem = GemUtil.getRandomSocketGemByWeightWithLevel(firstGem.level + 1)
handleGemIfFound(foundGem, eventInventory)
} else {
logger.fine("!allHaveSameLevel uuid=$uuid")
combinedGem = null
eventInventory.setItem(resultSlot, sameLevelButton)
}
}
private fun handleSameFamily(
allHaveSameFamily: Boolean,
socketGemsInCombiner: List<SocketGem>,
eventInventory: Inventory
) {
logger.fine("requireSameFamily uuid=$uuid")
if (allHaveSameFamily) {
logger.fine("allHaveSameFamily uuid=$uuid")
val firstGem = socketGemsInCombiner.first()
val averageLevel = socketGemsInCombiner.map { it.level }.average().toInt()
val foundGem = GemUtil.getRandomSocketGemByWeightFromFamilyWithLevel(firstGem.family, averageLevel + 1)
handleGemIfFound(foundGem, eventInventory)
} else {
logger.fine("!allHaveSameFamily uuid=$uuid")
combinedGem = null
eventInventory.setItem(resultSlot, sameFamilyButton)
}
}
private fun handleSameFamilyAndSameLevel(
allHaveSameFamilyAndLevel: Boolean,
socketGemsInCombiner: List<SocketGem>,
eventInventory: Inventory
) {
logger.fine("requireSameFamily && requireSameLevel uuid=$uuid")
if (allHaveSameFamilyAndLevel) {
logger.fine("allHaveSameFamilyAndLevel uuid=$uuid")
val firstGem = socketGemsInCombiner.first()
val foundGem = GemUtil.getRandomSocketGemByWeightFromFamilyWithLevel(firstGem.family, firstGem.level + 1)
handleGemIfFound(foundGem, eventInventory)
} else {
logger.fine("!allHaveSameFamilyAndLevel uuid=$uuid")
combinedGem = null
eventInventory.setItem(resultSlot, sameFamilyAndLevelButton)
}
return
}
private fun handleGemIfFound(
foundGem: SocketGem?,
eventInventory: Inventory
) {
if (foundGem != null) {
logger.fine("foundGem != null uuid=$uuid")
combinedGem = foundGem
eventInventory.setItem(resultSlot, clickToCombineButton)
} else {
logger.fine("foundGem == null uuid=$uuid")
eventInventory.setItem(resultSlot, noGemFoundButton)
}
}
private fun handleRemoveGemFromCombiner(
currentItem: ItemStack,
player: Player,
eventInventory: Inventory,
slot: Int
) {
val playerInventory = player.inventory
val clickedItem = currentItem.clone()
// if the clicked item is not a socket gem
if (!isSocketGem(clickedItem) && !isCombineButton(clickedItem)) {
logger.fine("!isSocketGem(clickedItem) && !isCombineButton(clickedItem) uuid=$uuid")
return
}
when (slot) {
resultSlot -> {
val combinedGemAtTimeOfClick = combinedGem // combined gem is mutable so we need to hold onto the value
if (
isCombineButton(clickedItem) && combinedGemAtTimeOfClick != null &&
getEmptySocketCombinerSlot(eventInventory) == -1
) {
handleCombineClick(combinedGemAtTimeOfClick, eventInventory)
return
}
if (isSocketGem(currentItem)) {
handleClaimSocketGemClick(eventInventory, slot, playerInventory, player, currentItem)
return
}
}
slot1, slot2, slot3, slot4 -> {
handleRemoveGemClick(playerInventory, clickedItem, player, eventInventory, slot)
}
}
}
private fun handleRemoveGemClick(
playerInventory: PlayerInventory,
clickedItem: ItemStack,
player: Player,
eventInventory: Inventory,
slot: Int
) {
logger.fine("removing gem slot=$slot uuid=$uuid")
if (playerInventory.firstEmpty() != -1) {
playerInventory.addItem(clickedItem)
} else {
player.world.dropItem(player.location, clickedItem)
}
eventInventory.setItem(slot, null)
if (eventInventory.getItem(resultSlot) != null) {
eventInventory.setItem(resultSlot, null)
}
}
private fun handleClaimSocketGemClick(
eventInventory: Inventory,
slot: Int,
playerInventory: PlayerInventory,
player: Player,
currentItem: ItemStack
) {
logger.fine("clicked combined socket gem!")
eventInventory.setItem(slot, null)
if (playerInventory.firstEmpty() == -1) {
player.world.dropItem(player.location, currentItem)
} else {
playerInventory.addItem(currentItem)
}
}
private fun handleCombineClick(
combinedGemAtTimeOfClick: SocketGem,
eventInventory: Inventory
) {
logger.fine("clicked combine button! uuid=$uuid")
GemUtil.getRandomSocketGemMaterial()?.let {
val socketItem =
SocketItem(
it,
combinedGemAtTimeOfClick,
socketingSettings.items.socketGem
)
eventInventory.setItem(slot1, null)
eventInventory.setItem(slot2, null)
eventInventory.setItem(slot3, null)
eventInventory.setItem(slot4, null)
eventInventory.setItem(resultSlot, socketItem)
}
}
private fun getEmptySocketCombinerSlot(invy: Inventory): Int =
slots.firstOrNull(invy::isSlotEmpty) ?: -1
private fun isSocketGem(itemStack: ItemStack) = GemUtil.getSocketGemFromPotentialSocketItem(itemStack) != null
private fun isCombineButton(itemStack: ItemStack) = itemStack.isSimilar(clickToCombineButton)
private fun getSocketGemsFromSlots(invy: Inventory) = getSocketGems(slots.mapNotNull { invy.getItem(it) })
private fun getSocketGems(itemStacks: List<ItemStack>) =
itemStacks.mapNotNull(GemUtil::getSocketGemFromPotentialSocketItem)
}
| mit | eef7fcc9285f1ba1e94f39c5562d5e70 | 39.507246 | 119 | 0.670722 | 4.575716 | false | false | false | false |
LouisCAD/Splitties | samples/android-app/src/main/kotlin/com/example/splitties/preview/vibrator/VibrationEffect.kt | 1 | 4927 | /*
* Copyright 2019 Louis Cognault Ayeva Derman. Use of this source code is governed by the Apache 2.0 license.
*/
package com.example.splitties.preview.vibrator
import android.Manifest
import android.annotation.SuppressLint
import android.media.AudioAttributes
import android.os.Build.VERSION.SDK_INT
import android.os.Vibrator
import androidx.annotation.RequiresApi
import androidx.annotation.RequiresPermission
import android.os.VibrationEffect as VibrationEffectApi26
sealed class VibrationEffect {
companion object {
/** The default vibration strength of the device. */
@SuppressLint("InlinedApi")
const val DEFAULT_AMPLITUDE = VibrationEffectApi26.DEFAULT_AMPLITUDE
/**
* Creates a waveform vibration that is **pre-Oreo compatible**.
*
* Waveform vibrations are a potentially repeating series of timing and amplitude pairs. For
* each pair, the value in the amplitude array determines the strength of the vibration and
* the value in the timing array determines how long it vibrates for.
*
* *Even indexes are off durations, and odd indexes are on durations. Therefore,* **the
* first value is the time to wait before turning the vibrator on.**
* An amplitude of 0
* implies no vibration (i.e. off), and any pairs with a timing value of 0 will be ignored.
*
* To cause the pattern to repeat, pass the index into the timings array at which to start
* the repetition, or -1 to disable repeating.
*
* @param timings The timing values of the timing / amplitude pairs in milliseconds.
* Even indexes are off durations, and odd indexes are on durations. Therefore, **the first
* value is the time to wait before turning the vibrator on.** It will usually be 0. Timing
* values of 0 will cause the pair to be ignored.
* @param amplitudes The amplitude values of the timing / amplitude pairs, **ignored on
* pre-Oreo devices**. Amplitude values must be between 0 and 255, or equal to
* [VibrationEffect.DEFAULT_AMPLITUDE]. An amplitude value of 0 implies the motor is
* off.
* @param repeat The index into the timings array at which to repeat, or -1 if you you don't
* want to repeat.
*/
fun createWaveform(
timings: LongArray,
amplitudes: IntArray? = null,
repeat: Int = -1
): VibrationEffect = WaveForm(timings, amplitudes, repeat)
/**
* Creates a one shot vibration that is **pre-Oreo compatible**.
*
* One shot vibrations will vibrate constantly for the specified period of time at the
* specified amplitude, and then stop.
*
* @param milliseconds The number of milliseconds to vibrate. Must be a positive number.
* @param amplitude The strength of the vibration, **ignored on pre-Oreo devices**. Must
* be a value between 1 and 255, or [VibrationEffect.DEFAULT_AMPLITUDE].
*/
fun createOneShot(
milliseconds: Long,
amplitude: Int = DEFAULT_AMPLITUDE
): VibrationEffect = OneShot(milliseconds, amplitude)
}
}
@RequiresApi(21)
@RequiresPermission(Manifest.permission.VIBRATE)
fun Vibrator.vibrate(vibe: VibrationEffect, audioAttributes: AudioAttributes) {
@Suppress("DEPRECATION")
if (SDK_INT >= 26) vibrate(vibe.toPlatformVibe(), audioAttributes)
else when (vibe) {
is WaveForm -> vibrate(vibe.timings, vibe.repeat, audioAttributes)
is OneShot -> vibrate(vibe.milliseconds, audioAttributes)
}
}
@RequiresPermission(Manifest.permission.VIBRATE)
fun Vibrator.vibrate(vibe: VibrationEffect) {
@Suppress("DEPRECATION")
if (SDK_INT >= 26) vibrate(vibe.toPlatformVibe())
else when (vibe) {
is WaveForm -> vibrate(vibe.timings, vibe.repeat)
is OneShot -> vibrate(vibe.milliseconds)
}
}
private class WaveForm(
val timings: LongArray,
val amplitudes: IntArray?,
val repeat: Int
) : VibrationEffect()
private class OneShot(val milliseconds: Long, val amplitude: Int) : VibrationEffect()
@RequiresApi(26)
private fun VibrationEffect.toPlatformVibe(): VibrationEffectApi26 = when (this) {
is WaveForm -> when (amplitudes) {
null -> VibrationEffectApi26.createWaveform(timings, repeat)
else -> VibrationEffectApi26.createWaveform(timings, amplitudes, repeat)
}
is OneShot -> VibrationEffectApi26.createOneShot(milliseconds, amplitude)
}
/**
* Returns the duration of the vibration effect.
* The repeat property of wave form patterns is ignored because those effects
* are repeated until cancelled, with iterations count consequently unknown.
*/
fun VibrationEffect.durationMillis(): Long = when (this) {
is WaveForm -> timings.sum()
is OneShot -> milliseconds
}
| apache-2.0 | 574ca9966763dbf39f9964ee701c48a2 | 41.111111 | 109 | 0.686422 | 4.426774 | false | false | false | false |
google/intellij-community | platform/workspaceModel/storage/testEntities/gen/com/intellij/workspaceModel/storage/entities/test/api/KeyParentImpl.kt | 1 | 10144 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.workspaceModel.storage.entities.test.api
import com.intellij.workspaceModel.storage.*
import com.intellij.workspaceModel.storage.EntityInformation
import com.intellij.workspaceModel.storage.EntitySource
import com.intellij.workspaceModel.storage.EntityStorage
import com.intellij.workspaceModel.storage.GeneratedCodeApiVersion
import com.intellij.workspaceModel.storage.GeneratedCodeImplVersion
import com.intellij.workspaceModel.storage.ModifiableWorkspaceEntity
import com.intellij.workspaceModel.storage.MutableEntityStorage
import com.intellij.workspaceModel.storage.WorkspaceEntity
import com.intellij.workspaceModel.storage.impl.ConnectionId
import com.intellij.workspaceModel.storage.impl.EntityLink
import com.intellij.workspaceModel.storage.impl.ModifiableWorkspaceEntityBase
import com.intellij.workspaceModel.storage.impl.UsedClassesCollector
import com.intellij.workspaceModel.storage.impl.WorkspaceEntityBase
import com.intellij.workspaceModel.storage.impl.WorkspaceEntityData
import com.intellij.workspaceModel.storage.impl.extractOneToManyChildren
import com.intellij.workspaceModel.storage.impl.updateOneToManyChildrenOfParent
import org.jetbrains.deft.ObjBuilder
import org.jetbrains.deft.Type
import org.jetbrains.deft.annotations.Child
@GeneratedCodeApiVersion(1)
@GeneratedCodeImplVersion(1)
open class KeyParentImpl(val dataSource: KeyParentData) : KeyParent, WorkspaceEntityBase() {
companion object {
internal val CHILDREN_CONNECTION_ID: ConnectionId = ConnectionId.create(KeyParent::class.java, KeyChild::class.java,
ConnectionId.ConnectionType.ONE_TO_MANY, false)
val connections = listOf<ConnectionId>(
CHILDREN_CONNECTION_ID,
)
}
override val keyField: String
get() = dataSource.keyField
override val notKeyField: String
get() = dataSource.notKeyField
override val children: List<KeyChild>
get() = snapshot.extractOneToManyChildren<KeyChild>(CHILDREN_CONNECTION_ID, this)!!.toList()
override fun connectionIdList(): List<ConnectionId> {
return connections
}
class Builder(val result: KeyParentData?) : ModifiableWorkspaceEntityBase<KeyParent>(), KeyParent.Builder {
constructor() : this(KeyParentData())
override fun applyToBuilder(builder: MutableEntityStorage) {
if (this.diff != null) {
if (existsInBuilder(builder)) {
this.diff = builder
return
}
else {
error("Entity KeyParent is already created in a different builder")
}
}
this.diff = builder
this.snapshot = builder
addToBuilder()
this.id = getEntityData().createEntityId()
// Process linked entities that are connected without a builder
processLinkedEntities(builder)
checkInitialization() // TODO uncomment and check failed tests
}
fun checkInitialization() {
val _diff = diff
if (!getEntityData().isEntitySourceInitialized()) {
error("Field WorkspaceEntity#entitySource should be initialized")
}
if (!getEntityData().isKeyFieldInitialized()) {
error("Field KeyParent#keyField should be initialized")
}
if (!getEntityData().isNotKeyFieldInitialized()) {
error("Field KeyParent#notKeyField should be initialized")
}
// Check initialization for list with ref type
if (_diff != null) {
if (_diff.extractOneToManyChildren<WorkspaceEntityBase>(CHILDREN_CONNECTION_ID, this) == null) {
error("Field KeyParent#children should be initialized")
}
}
else {
if (this.entityLinks[EntityLink(true, CHILDREN_CONNECTION_ID)] == null) {
error("Field KeyParent#children should be initialized")
}
}
}
override fun connectionIdList(): List<ConnectionId> {
return connections
}
// Relabeling code, move information from dataSource to this builder
override fun relabel(dataSource: WorkspaceEntity, parents: Set<WorkspaceEntity>?) {
dataSource as KeyParent
this.entitySource = dataSource.entitySource
this.keyField = dataSource.keyField
this.notKeyField = dataSource.notKeyField
if (parents != null) {
}
}
override var entitySource: EntitySource
get() = getEntityData().entitySource
set(value) {
checkModificationAllowed()
getEntityData().entitySource = value
changedProperty.add("entitySource")
}
override var keyField: String
get() = getEntityData().keyField
set(value) {
checkModificationAllowed()
getEntityData().keyField = value
changedProperty.add("keyField")
}
override var notKeyField: String
get() = getEntityData().notKeyField
set(value) {
checkModificationAllowed()
getEntityData().notKeyField = value
changedProperty.add("notKeyField")
}
// List of non-abstract referenced types
var _children: List<KeyChild>? = emptyList()
override var children: List<KeyChild>
get() {
// Getter of the list of non-abstract referenced types
val _diff = diff
return if (_diff != null) {
_diff.extractOneToManyChildren<KeyChild>(CHILDREN_CONNECTION_ID, this)!!.toList() + (this.entityLinks[EntityLink(true,
CHILDREN_CONNECTION_ID)] as? List<KeyChild>
?: emptyList())
}
else {
this.entityLinks[EntityLink(true, CHILDREN_CONNECTION_ID)] as? List<KeyChild> ?: emptyList()
}
}
set(value) {
// Setter of the list of non-abstract referenced types
checkModificationAllowed()
val _diff = diff
if (_diff != null) {
for (item_value in value) {
if (item_value is ModifiableWorkspaceEntityBase<*> && (item_value as? ModifiableWorkspaceEntityBase<*>)?.diff == null) {
_diff.addEntity(item_value)
}
}
_diff.updateOneToManyChildrenOfParent(CHILDREN_CONNECTION_ID, this, value)
}
else {
for (item_value in value) {
if (item_value is ModifiableWorkspaceEntityBase<*>) {
item_value.entityLinks[EntityLink(false, CHILDREN_CONNECTION_ID)] = this
}
// else you're attaching a new entity to an existing entity that is not modifiable
}
this.entityLinks[EntityLink(true, CHILDREN_CONNECTION_ID)] = value
}
changedProperty.add("children")
}
override fun getEntityData(): KeyParentData = result ?: super.getEntityData() as KeyParentData
override fun getEntityClass(): Class<KeyParent> = KeyParent::class.java
}
}
class KeyParentData : WorkspaceEntityData<KeyParent>() {
lateinit var keyField: String
lateinit var notKeyField: String
fun isKeyFieldInitialized(): Boolean = ::keyField.isInitialized
fun isNotKeyFieldInitialized(): Boolean = ::notKeyField.isInitialized
override fun wrapAsModifiable(diff: MutableEntityStorage): ModifiableWorkspaceEntity<KeyParent> {
val modifiable = KeyParentImpl.Builder(null)
modifiable.allowModifications {
modifiable.diff = diff
modifiable.snapshot = diff
modifiable.id = createEntityId()
modifiable.entitySource = this.entitySource
}
modifiable.changedProperty.clear()
return modifiable
}
override fun createEntity(snapshot: EntityStorage): KeyParent {
return getCached(snapshot) {
val entity = KeyParentImpl(this)
entity.entitySource = entitySource
entity.snapshot = snapshot
entity.id = createEntityId()
entity
}
}
override fun getEntityInterface(): Class<out WorkspaceEntity> {
return KeyParent::class.java
}
override fun serialize(ser: EntityInformation.Serializer) {
}
override fun deserialize(de: EntityInformation.Deserializer) {
}
override fun createDetachedEntity(parents: List<WorkspaceEntity>): WorkspaceEntity {
return KeyParent(keyField, notKeyField, entitySource) {
}
}
override fun getRequiredParents(): List<Class<out WorkspaceEntity>> {
val res = mutableListOf<Class<out WorkspaceEntity>>()
return res
}
override fun equals(other: Any?): Boolean {
if (other == null) return false
if (this::class != other::class) return false
other as KeyParentData
if (this.entitySource != other.entitySource) return false
if (this.keyField != other.keyField) return false
if (this.notKeyField != other.notKeyField) return false
return true
}
override fun equalsIgnoringEntitySource(other: Any?): Boolean {
if (other == null) return false
if (this::class != other::class) return false
other as KeyParentData
if (this.keyField != other.keyField) return false
if (this.notKeyField != other.notKeyField) return false
return true
}
override fun hashCode(): Int {
var result = entitySource.hashCode()
result = 31 * result + keyField.hashCode()
result = 31 * result + notKeyField.hashCode()
return result
}
override fun hashCodeIgnoringEntitySource(): Int {
var result = javaClass.hashCode()
result = 31 * result + keyField.hashCode()
result = 31 * result + notKeyField.hashCode()
return result
}
override fun equalsByKey(other: Any?): Boolean {
if (other == null) return false
if (this::class != other::class) return false
other as KeyParentData
if (this.keyField != other.keyField) return false
return true
}
override fun hashCodeByKey(): Int {
var result = javaClass.hashCode()
result = 31 * result + keyField.hashCode()
return result
}
override fun collectClassUsagesData(collector: UsedClassesCollector) {
collector.sameForAllEntities = true
}
}
| apache-2.0 | 81fad01c90d9f5dd9d59bcfa3ea2d331 | 33.97931 | 166 | 0.679909 | 5.26961 | false | false | false | false |
jotomo/AndroidAPS | app/src/main/java/info/nightscout/androidaps/plugins/general/automation/elements/InputString.kt | 1 | 1174 | package info.nightscout.androidaps.plugins.general.automation.elements
import android.text.Editable
import android.text.TextWatcher
import android.view.ViewGroup
import android.widget.EditText
import android.widget.LinearLayout
import dagger.android.HasAndroidInjector
class InputString(injector: HasAndroidInjector) : Element(injector) {
var textWatcher: TextWatcher = object : TextWatcher {
override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {}
override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {}
override fun afterTextChanged(s: Editable) {
value = s.toString()
}
}
var value = ""
constructor(injector: HasAndroidInjector, value: String) : this(injector) {
this.value = value
}
override fun addToLayout(root: LinearLayout) {
val editText = EditText(root.context)
editText.setText(value)
editText.layoutParams = LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)
editText.addTextChangedListener(textWatcher)
root.addView(editText)
}
} | agpl-3.0 | bd703f9e3bf2b6d40c4e967e8b32dba7 | 36.903226 | 131 | 0.724872 | 4.733871 | false | false | false | false |
firebase/firebase-android-sdk | firebase-appdistribution-api/ktx/src/main/kotlin/com/google/firebase/appdistribution/ktx/FirebaseAppDistribution.kt | 1 | 3123 | // Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.firebase.appdistribution.ktx
import androidx.annotation.Keep
import com.google.firebase.BuildConfig
import com.google.firebase.FirebaseApp
import com.google.firebase.appdistribution.AppDistributionRelease
import com.google.firebase.appdistribution.FirebaseAppDistribution
import com.google.firebase.appdistribution.UpdateProgress
import com.google.firebase.components.Component
import com.google.firebase.components.ComponentRegistrar
import com.google.firebase.ktx.Firebase
import com.google.firebase.platforminfo.LibraryVersionComponent
/** Returns the [FirebaseAppDistribution] instance of the default [FirebaseApp]. */
val Firebase.appDistribution: FirebaseAppDistribution
get() = FirebaseAppDistribution.getInstance()
/**
* Destructuring declaration for [AppDistributionRelease] to provide binaryType.
*
* @return the binaryType of the [AppDistributionRelease]
*/
operator fun AppDistributionRelease.component1() = binaryType
/**
* Destructuring declaration for [AppDistributionRelease] to provide displayVersion.
*
* @return the displayVersion of the [AppDistributionRelease]
*/
operator fun AppDistributionRelease.component2() = displayVersion
/**
* Destructuring declaration for [AppDistributionRelease] to provide versionCode.
*
* @return the versionCode of the [AppDistributionRelease]
*/
operator fun AppDistributionRelease.component3() = versionCode
/**
* Destructuring declaration for [AppDistributionRelease] to provide releaseNotes.
*
* @return the releaseNotes of the [AppDistributionRelease]
*/
operator fun AppDistributionRelease.component4() = releaseNotes
/**
* Destructuring declaration for [UpdateProgress] to provide apkBytesDownloaded.
*
* @return the apkBytesDownloaded of the [UpdateProgress]
*/
operator fun UpdateProgress.component1() = apkBytesDownloaded
/**
* Destructuring declaration for [UpdateProgress] to provide apkFileTotalBytes.
*
* @return the apkFileTotalBytes of the [UpdateProgress]
*/
operator fun UpdateProgress.component2() = apkFileTotalBytes
/**
* Destructuring declaration for [UpdateProgress] to provide updateStatus.
*
* @return the updateStatus of the [UpdateProgress]
*/
operator fun UpdateProgress.component3() = updateStatus
internal const val LIBRARY_NAME: String = "fire-appdistribution-ktx"
/** @suppress */
@Keep
class FirebaseAppDistributionKtxRegistrar : ComponentRegistrar {
override fun getComponents(): List<Component<*>> =
listOf(LibraryVersionComponent.create(LIBRARY_NAME, BuildConfig.VERSION_NAME))
}
| apache-2.0 | 5a57f2530cb4415d7f36d51ef73d2b6b | 34.488636 | 84 | 0.795069 | 4.619822 | false | false | false | false |
lpy19930103/MinimalismJotter | app/src/main/java/com/lipy/jotter/app/App.kt | 1 | 808 | package com.lipy.jotter.app
import android.app.Application
import com.lipy.jotter.dao.DaoService
import com.youdao.note.sdk.openapi.IYNoteAPI
import com.youdao.note.sdk.openapi.YNoteAPIFactory
/**
* Application
* Created by lipy on 2017/2/28 0028.
*/
class App : Application() {
var AppId = ""
var api :IYNoteAPI? = null
override fun onCreate() {
super.onCreate()
if (instances == null) {
instances = this
}
DaoService.getInstance().initDb(this)
// [1]利用申请到的 AppId 生成 api 接口类
api = YNoteAPIFactory.getYNoteAPI(this, AppId)
// [2]注册 App 到有道云笔记
if(!api!!.isRegistered()){ api!!.registerApp();
}
}
companion object {
var instances: App? = null
}
}
| apache-2.0 | cb2caf80cffdbafb09605ef9ade4360f | 21.647059 | 55 | 0.614286 | 3.452915 | false | false | false | false |
siosio/intellij-community | plugins/kotlin/jvm/src/org/jetbrains/kotlin/idea/compiler/configuration/KotlinBuildProcessParametersProvider.kt | 1 | 1978 | // 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.compiler.configuration
import com.intellij.compiler.server.BuildProcessParametersProvider
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.registry.Registry
import org.jetbrains.kotlin.config.IncrementalCompilation
import org.jetbrains.kotlin.idea.PluginStartupApplicationService
import org.jetbrains.kotlin.idea.artifacts.KotlinArtifacts
class KotlinBuildProcessParametersProvider(private val project: Project) : BuildProcessParametersProvider() {
override fun getVMArguments(): MutableList<String> {
val compilerWorkspaceSettings = KotlinCompilerWorkspaceSettings.getInstance(project)
val res = arrayListOf<String>()
if (compilerWorkspaceSettings.preciseIncrementalEnabled) {
res.add("-D" + IncrementalCompilation.INCREMENTAL_COMPILATION_JVM_PROPERTY + "=true")
}
if (compilerWorkspaceSettings.incrementalCompilationForJsEnabled) {
res.add("-D" + IncrementalCompilation.INCREMENTAL_COMPILATION_JS_PROPERTY + "=true")
}
if (compilerWorkspaceSettings.enableDaemon) {
res.add("-Dkotlin.daemon.enabled")
}
if (Registry.`is`("kotlin.jps.instrument.bytecode", false)) {
res.add("-Dkotlin.jps.instrument.bytecode=true")
}
PluginStartupApplicationService.getInstance().aliveFlagPath.let {
if (!it.isBlank()) {
// TODO: consider taking the property name from compiler/daemon/common (check whether dependency will be not too heavy)
res.add("-Dkotlin.daemon.client.alive.path=\"$it\"")
}
}
return res
}
override fun getAdditionalPluginPaths(): Iterable<String> {
return listOf(KotlinArtifacts.instance.kotlincDirectory.path)
}
}
| apache-2.0 | 210608ab31a61970dbe0b8591c3485ab | 47.243902 | 158 | 0.718402 | 4.754808 | false | false | false | false |
siosio/intellij-community | plugins/kotlin/idea/tests/testData/findUsages/kotlin/conventions/plus.0.kt | 3 | 410 | // PSI_ELEMENT: org.jetbrains.kotlin.psi.KtNamedFunction
// OPTIONS: usages
class A(val n: Int) {
operator fun <caret>plus(m: Int): A = A(n + m)
operator fun plus(a: A): A = this + a.n
}
fun test(array: Array<A>) {
A(0) + A(1) + 2
A(0) plus A(1) plus 2
A(0).plus(A(1).plus(2))
var a = A(0)
a += 1
a += A(1)
+A(0)
val (a1, a2) = array
a1 + 1
}
// DISABLE-ERRORS | apache-2.0 | 07b8e5510cd1b7ed766cd4f45f29a43e | 16.125 | 56 | 0.521951 | 2.440476 | false | false | false | false |
siosio/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/intentions/loopToCallChain/LoopToCallChainInspection.kt | 1 | 5563 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.intentions.loopToCallChain
import com.intellij.codeInspection.*
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.TextRange
import org.jetbrains.kotlin.idea.KotlinBundle
import org.jetbrains.kotlin.idea.core.moveCaret
import org.jetbrains.kotlin.idea.inspections.AbstractKotlinInspection
import org.jetbrains.kotlin.idea.inspections.findExistingEditor
import org.jetbrains.kotlin.idea.intentions.SelfTargetingRangeIntention
import org.jetbrains.kotlin.idea.intentions.loopToCallChain.sequence.AsSequenceTransformation
import org.jetbrains.kotlin.psi.KtForExpression
import org.jetbrains.kotlin.psi.KtProperty
import org.jetbrains.kotlin.psi.KtVisitorVoid
import org.jetbrains.kotlin.psi.psiUtil.getParentOfType
import org.jetbrains.kotlin.psi.psiUtil.startOffset
class LoopToCallChainInspection : AbstractKotlinInspection() {
override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean, session: LocalInspectionToolSession) =
object : KtVisitorVoid() {
val nonLazyIntention = LoopToCallChainIntention()
val lazyIntention = LoopToLazyCallChainIntention()
override fun visitForExpression(expression: KtForExpression) {
super.visitForExpression(expression)
val nonLazyApplicable = nonLazyIntention.applicabilityRange(expression) != null
val lazyApplicable = lazyIntention.applicabilityRange(expression) != null
if (!nonLazyApplicable && !lazyApplicable) return
val fixes = mutableListOf<Fix>()
if (nonLazyApplicable) {
fixes += Fix(lazy = false, text = nonLazyIntention.text)
}
if (lazyApplicable) {
fixes += Fix(lazy = true, text = lazyIntention.text)
}
holder.registerProblem(
expression.forKeyword,
KotlinBundle.message("loop.can.be.replaced.with.stdlib.operations"),
ProblemHighlightType.GENERIC_ERROR_OR_WARNING,
*fixes.toTypedArray()
)
}
}
class Fix(val lazy: Boolean, val text: String = "") : LocalQuickFix {
override fun getFamilyName(): String {
return if (lazy) {
KotlinBundle.message("loop.to.call.fix.family.name2")
} else {
KotlinBundle.message("loop.to.call.fix.family.name")
}
}
override fun getName() = text
override fun applyFix(project: Project, descriptor: ProblemDescriptor) {
val expression = descriptor.psiElement.getParentOfType<KtForExpression>(strict = true) ?: return
applyFix(expression)
}
fun applyFix(expression: KtForExpression, editor: Editor? = expression.findExistingEditor()) {
val match = match(expression, lazy, true) ?: return
val offset = when (val result = convertLoop(expression, match)) {
// if result is variable declaration, put the caret onto its name to allow quick inline
is KtProperty -> result.nameIdentifier?.startOffset ?: result.startOffset
else -> result.startOffset
}
editor?.moveCaret(offset)
}
}
}
class LoopToCallChainIntention : AbstractLoopToCallChainIntention(
lazy = false,
textGetter = KotlinBundle.lazyMessage("replace.with.stdlib.operations")
)
class LoopToLazyCallChainIntention : AbstractLoopToCallChainIntention(
lazy = true,
textGetter = KotlinBundle.lazyMessage("replace.with.stdlib.operations.with.use.of.assequence")
)
abstract class AbstractLoopToCallChainIntention(
private val lazy: Boolean,
textGetter: () -> String
) : SelfTargetingRangeIntention<KtForExpression>(
KtForExpression::class.java,
textGetter
) {
override fun applicabilityRange(element: KtForExpression): TextRange? {
val match = match(element, lazy, false)
setTextGetter(
if (match != null)
KotlinBundle.lazyMessage("replace.with.0", match.transformationMatch.buildPresentation())
else
defaultTextGetter
)
return if (match != null) element.forKeyword.textRange else null
}
private fun TransformationMatch.Result.buildPresentation(): String =
buildPresentation(sequenceTransformations + resultTransformation, null)
private fun buildPresentation(transformations: List<Transformation>, prevPresentation: String?): String {
if (transformations.size > MAX) {
if (transformations[0] is AsSequenceTransformation) {
return buildPresentation(transformations.drop(1), transformations[0].presentation)
}
return buildPresentation(transformations.drop(transformations.size - MAX), prevPresentation?.let { it + ".." } ?: "..")
}
var result: String? = prevPresentation
for (transformation in transformations) {
result = transformation.buildPresentation(result)
}
return result!!
}
override fun applyTo(element: KtForExpression, editor: Editor?) = LoopToCallChainInspection.Fix(lazy).applyFix(element, editor)
companion object {
const val MAX = 3
}
}
| apache-2.0 | e4477a42fdfcd6880e62e2dd3a341704 | 40.207407 | 158 | 0.676074 | 5.179702 | false | false | false | false |
dpisarenko/econsim-tr01 | src/main/java/cc/altruix/econsimtr01/ch03/PropertiesFileSimParametersProvider.kt | 1 | 3876 | /*
* Copyright 2012-2016 Dmitri Pisarenko
*
* WWW: http://altruix.cc
* E-Mail: [email protected]
* Skype: dp118m (voice calls must be scheduled in advance)
*
* Physical address:
*
* 4-i Rostovskii pereulok 2/1/20
* 119121 Moscow
* Russian Federation
*
* This file is part of econsim-tr01.
*
* econsim-tr01 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.
*
* econsim-tr01 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 econsim-tr01. If not, see <http://www.gnu.org/licenses/>.
*
*/
package cc.altruix.econsimtr01.ch03
import cc.altruix.econsimtr01.IAgent
import cc.altruix.econsimtr01.ISimParametersProvider
import cc.altruix.econsimtr01.PlFlow
import cc.altruix.econsimtr01.PlTransformation
import cc.altruix.econsimtr01.ch0201.InfiniteResourceSupply
import cc.altruix.econsimtr01.ch0201.InitialResourceLevel
import java.io.File
import java.util.*
/**
* Created by pisarenko on 14.05.2016.
*/
abstract open class PropertiesFileSimParametersProvider(val file: File) :
ISimParametersProvider {
override val agents:MutableList<IAgent> = LinkedList()
get
override val flows:MutableList<PlFlow> = LinkedList()
get
override val initialResourceLevels:MutableList<InitialResourceLevel> =
LinkedList()
get
override val infiniteResourceSupplies:MutableList<InfiniteResourceSupply> =
LinkedList()
get
override val transformations:MutableList<PlTransformation> = LinkedList()
get
lateinit var validity:ValidationResult
get
lateinit var data:Properties
open fun initAndValidate() {
val validators = createValidators()
data = loadData()
val valResults = createValResults()
validators.entries.forEach { entry ->
applyValidators(data, valResults, entry.key, entry.value)
}
val valid = calculateValidity(valResults)
var message = createMessage(valResults, valid)
validity = ValidationResult(valid, message)
}
open internal fun createMessage(valResults: List<ValidationResult>,
valid: Boolean): String {
var message = ""
if (!valid) {
message = valResults.filter { it.valid == false }
.map { it.message }.joinToString(separator = ", ")
}
return message
}
open internal fun calculateValidity(valResults: List<ValidationResult>) =
valResults.filter { it.valid == false }.count() < 1
open internal fun applyValidators(data: Properties,
valResults: MutableList<ValidationResult>,
parameter: String,
parameterValidators:
List<IPropertiesFileValueValidator>) {
for (validator in parameterValidators) {
val vres = validator.validate(data, parameter)
if (!vres.valid) {
valResults.add(vres)
break;
}
}
}
open internal fun createValResults():MutableList<ValidationResult> =
LinkedList<ValidationResult>()
open internal fun loadData(): Properties {
val data = Properties()
data.load(file.reader())
return data
}
abstract fun createValidators():
Map<String,List<IPropertiesFileValueValidator>>
} | gpl-3.0 | 45e6c63f70e996ab732412479a04d0b6 | 33.008772 | 80 | 0.653251 | 4.726829 | false | false | false | false |
nrizzio/Signal-Android | app/src/main/java/org/thoughtcrime/securesms/mediapreview/MediaIntentFactory.kt | 1 | 2287 | package org.thoughtcrime.securesms.mediapreview
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.os.Parcelable
import kotlinx.parcelize.Parcelize
import org.thoughtcrime.securesms.attachments.DatabaseAttachment
import org.thoughtcrime.securesms.database.MediaDatabase
import org.thoughtcrime.securesms.database.MediaDatabase.MediaRecord
object MediaIntentFactory {
private const val ARGS_KEY = "args"
const val NOT_IN_A_THREAD = -2
const val UNKNOWN_TIMESTAMP = -2
const val THREAD_ID_EXTRA = "thread_id"
const val DATE_EXTRA = "date"
const val SIZE_EXTRA = "size"
const val CAPTION_EXTRA = "caption"
const val LEFT_IS_RECENT_EXTRA = "left_is_recent"
const val HIDE_ALL_MEDIA_EXTRA = "came_from_all_media"
const val SHOW_THREAD_EXTRA = "show_thread"
const val SORTING_EXTRA = "sorting"
const val IS_VIDEO_GIF = "is_video_gif"
@Parcelize
data class MediaPreviewArgs(
val threadId: Long,
val date: Long,
val initialMediaUri: Uri,
val initialMediaType: String,
val initialMediaSize: Long,
val initialCaption: String? = null,
val leftIsRecent: Boolean = false,
val hideAllMedia: Boolean = false,
val showThread: Boolean = false,
val allMediaInRail: Boolean = false,
val sorting: MediaDatabase.Sorting,
val isVideoGif: Boolean
) : Parcelable
@JvmStatic
fun requireArguments(bundle: Bundle): MediaPreviewArgs = bundle.getParcelable(ARGS_KEY)!!
@JvmStatic
fun create(context: Context, args: MediaPreviewArgs): Intent {
return Intent(context, MediaPreviewV2Activity::class.java).putExtra(ARGS_KEY, args)
}
fun intentFromMediaRecord(
context: Context,
mediaRecord: MediaRecord,
leftIsRecent: Boolean,
allMediaInRail: Boolean
): Intent {
val attachment: DatabaseAttachment = mediaRecord.attachment!!
return create(
context,
MediaPreviewArgs(
mediaRecord.threadId,
mediaRecord.date,
attachment.uri!!,
attachment.contentType,
attachment.size,
attachment.caption,
leftIsRecent,
allMediaInRail = allMediaInRail,
sorting = MediaDatabase.Sorting.Newest,
isVideoGif = attachment.isVideoGif
)
)
}
}
| gpl-3.0 | 2464937c4eec610b1160888d586f6dcb | 29.493333 | 91 | 0.722344 | 4.03351 | false | false | false | false |
androidx/androidx | room/room-compiler/src/main/kotlin/androidx/room/vo/Constructor.kt | 3 | 2966 | /*
* Copyright (C) 2017 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.vo
import androidx.room.compiler.codegen.XCodeBlock
import androidx.room.compiler.processing.XExecutableElement
import androidx.room.compiler.processing.isConstructor
import androidx.room.compiler.processing.isMethod
/**
* Each Entity / Pojo we process has a constructor. It might be the empty constructor or a
* constructor with fields. It can also be a static factory method, such as in the case of an
* AutoValue Pojo.
*/
data class Constructor(val element: XExecutableElement, val params: List<Param>) {
fun hasField(field: Field): Boolean {
return params.any {
when (it) {
is Param.FieldParam -> it.field === field
is Param.EmbeddedParam -> it.embedded.field === field
is Param.RelationParam -> it.relation.field === field
}
}
}
fun writeConstructor(outVar: String, args: String, builder: XCodeBlock.Builder) {
when {
element.isConstructor() -> {
builder.addStatement(
"%L = %L",
outVar,
XCodeBlock.ofNewInstance(
builder.language,
element.enclosingElement.asClassName(),
args
)
)
}
element.isMethod() -> {
// TODO when we generate Kotlin code, we need to handle not having enclosing
// elements.
builder.addStatement(
"%L = %T.%L(%L)",
outVar,
element.enclosingElement.asClassName(),
element.jvmName,
args
)
}
else -> throw IllegalStateException("Invalid constructor kind ${element.kindName()}")
}
}
sealed class Param {
abstract fun log(): String
class FieldParam(val field: Field) : Param() {
override fun log(): String = field.getPath()
}
class EmbeddedParam(val embedded: EmbeddedField) : Param() {
override fun log(): String = embedded.field.getPath()
}
class RelationParam(val relation: Relation) : Param() {
override fun log(): String = relation.field.getPath()
}
}
}
| apache-2.0 | 612d4d2864e65e7fa632fe610c24255b | 33.894118 | 97 | 0.585974 | 4.910596 | false | false | false | false |
androidx/androidx | room/room-compiler-processing/src/main/java/androidx/room/compiler/processing/ksp/KspAnnotationBox.kt | 3 | 7767 | /*
* Copyright 2020 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.room.compiler.processing.ksp
import androidx.room.compiler.processing.XAnnotationBox
import androidx.room.compiler.processing.XType
import com.google.devtools.ksp.symbol.KSAnnotation
import com.google.devtools.ksp.symbol.KSClassDeclaration
import com.google.devtools.ksp.symbol.KSType
import java.lang.reflect.Proxy
@Suppress("UNCHECKED_CAST")
internal class KspAnnotationBox<T : Annotation>(
private val env: KspProcessingEnv,
private val annotationClass: Class<T>,
private val annotation: KSAnnotation
) : XAnnotationBox<T> {
override fun getAsType(methodName: String): XType? {
val value = getFieldValue(methodName, KSType::class.java)
return value?.let {
env.wrap(
ksType = it,
allowPrimitives = true
)
}
}
override fun getAsTypeList(methodName: String): List<XType> {
val values = getFieldValue(methodName, Array::class.java) ?: return emptyList()
return values.filterIsInstance<KSType>().map {
env.wrap(
ksType = it,
allowPrimitives = true
)
}
}
override fun <R : Annotation> getAsAnnotationBox(methodName: String): XAnnotationBox<R> {
val value = getFieldValue(methodName, KSAnnotation::class.java)
@Suppress("FoldInitializerAndIfToElvis")
if (value == null) {
// see https://github.com/google/ksp/issues/53
return KspReflectiveAnnotationBox.createFromDefaultValue(
env = env,
annotationClass = annotationClass,
methodName = methodName
)
}
val annotationType = annotationClass.methods.first {
it.name == methodName
}.returnType as Class<R>
return KspAnnotationBox(
env = env,
annotationClass = annotationType,
annotation = value
)
}
@Suppress("SyntheticAccessor")
private fun <R : Any> getFieldValue(
methodName: String,
returnType: Class<R>
): R? {
val methodValue = annotation.arguments.firstOrNull {
it.name?.asString() == methodName
}?.value
return methodValue?.readAs(returnType)
}
override fun <R : Annotation> getAsAnnotationBoxArray(
methodName: String
): Array<XAnnotationBox<R>> {
val values = getFieldValue(methodName, Array::class.java) ?: return emptyArray()
val annotationType = annotationClass.methods.first {
it.name == methodName
}.returnType.componentType as Class<R>
if (values.isEmpty()) {
// KSP is unable to read defaults and returns empty array in that case.
// Subsequently, we don't know if developer set it to empty array intentionally or
// left it to default.
// we error on the side of default
return KspReflectiveAnnotationBox.createFromDefaultValues(
env = env,
annotationClass = annotationClass,
methodName = methodName
)
}
return values.map {
KspAnnotationBox(
env = env,
annotationClass = annotationType,
annotation = it as KSAnnotation
)
}.toTypedArray()
}
private val valueProxy: T = Proxy.newProxyInstance(
annotationClass.classLoader,
arrayOf(annotationClass)
) { _, method, _ ->
getFieldValue(method.name, method.returnType) ?: method.defaultValue
} as T
override val value: T
get() = valueProxy
}
@Suppress("UNCHECKED_CAST")
private fun <R> Any.readAs(returnType: Class<R>): R? {
return when {
returnType.isArray -> {
val values: List<Any?> = when (this) {
is List<*> -> {
// KSP might return list for arrays. convert it back.
this.mapNotNull {
it?.readAs(returnType.componentType)
}
}
is Array<*> -> mapNotNull { it?.readAs(returnType.componentType) }
else -> {
// If array syntax is not used in java code, KSP might return it as a single
// item instead of list or array
// see: https://github.com/google/ksp/issues/214
listOf(this.readAs(returnType.componentType))
}
}
if (returnType.componentType.isPrimitive) {
when (returnType) {
IntArray::class.java -> {
(values as Collection<Int>).toIntArray()
}
DoubleArray::class.java -> {
(values as Collection<Double>).toDoubleArray()
}
FloatArray::class.java -> {
(values as Collection<Float>).toFloatArray()
}
CharArray::class.java -> {
(values as Collection<Char>).toCharArray()
}
ByteArray::class.java -> {
(values as Collection<Byte>).toByteArray()
}
ShortArray::class.java -> {
(values as Collection<Short>).toShortArray()
}
LongArray::class.java -> {
(values as Collection<Long>).toLongArray()
}
BooleanArray::class.java -> {
(values as Collection<Boolean>).toBooleanArray()
}
else -> {
error("Unsupported primitive array type: $returnType")
}
}
} else {
val resultArray = java.lang.reflect.Array.newInstance(
returnType.componentType,
values.size
) as Array<Any?>
values.forEachIndexed { index, value ->
resultArray[index] = value
}
resultArray
}
}
returnType.isEnum -> {
this.readAsEnum(returnType)
}
else -> this
} as R?
}
private fun <R> Any.readAsEnum(enumClass: Class<R>): R? {
// TODO: https://github.com/google/ksp/issues/429
// If the enum value is from compiled code KSP gives us the actual value an not the KSType,
// so return it instead of using valueOf() to get an instance of the entry.
if (enumClass.isAssignableFrom(this::class.java)) {
return enumClass.cast(this)
}
val ksType = this as? KSType ?: return null
val classDeclaration = ksType.declaration as? KSClassDeclaration ?: return null
val enumValue = classDeclaration.simpleName.asString()
// get the instance from the valueOf function.
@Suppress("UNCHECKED_CAST", "BanUncheckedReflection")
return enumClass.getDeclaredMethod("valueOf", String::class.java)
.invoke(null, enumValue) as R?
} | apache-2.0 | 7ac77f78804655d56367f7c3a14c8842 | 37.078431 | 96 | 0.565469 | 5.130119 | false | false | false | false |
androidx/androidx | camera/integration-tests/camerapipetestapp/src/test/java/androidx/camera/integration/camera2/pipe/DataTransformations1DTests.kt | 3 | 4558 | /*
* Copyright 2020 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.camera.integration.camera2.pipe
import androidx.camera.integration.camera2.pipe.CameraMetadataKey.CONTROL_AE_MODE
import androidx.camera.integration.camera2.pipe.CameraMetadataKey.LENS_FOCAL_LENGTH
import androidx.camera.integration.camera2.pipe.CameraMetadataKey.LENS_FOCUS_DISTANCE
import androidx.camera.integration.camera2.pipe.CameraMetadataKey.STATISTICS_FACES
import androidx.camera.integration.camera2.pipe.transformations.DataTransformations1D
import com.google.common.truth.Truth.assertThat
import org.junit.Test
class DataTransformations1DTests {
/**
* LENS_FOCUS_DISTANCE tests
*/
@Test
fun lensFocusDistance_nullTest() {
assertThat(DataTransformations1D.convert(LENS_FOCUS_DISTANCE, null)).isNull()
}
@Test
fun lensFocusDistance_floatTest() {
val nums: MutableList<Float> = mutableListOf(1f, 32f, 64f, 1024f)
val transformedNums: MutableList<Float> = mutableListOf(1 / 1f, 1 / 32f, 1 / 64f, 1 / 1024f)
(0 until nums.size).forEach {
val transformedData = DataTransformations1D.convert(LENS_FOCUS_DISTANCE, nums[it])
assertThat(transformedData is Float).isTrue()
assertThat(transformedData as Float)
.isWithin(0.0001f)
.of(transformedNums[it])
}
}
@Test(expected = IllegalArgumentException::class)
fun lensFocusDistance_intTest() {
DataTransformations1D.convert(LENS_FOCUS_DISTANCE, 1)
}
@Test(expected = IllegalArgumentException::class)
fun lensFocusDistance_booleanTest() {
DataTransformations1D.convert(LENS_FOCUS_DISTANCE, true)
}
@Test(expected = IllegalArgumentException::class)
fun lensFocusDistance_arrayTest() {
DataTransformations1D.convert(LENS_FOCUS_DISTANCE, arrayListOf(1, 2))
}
/**
* CONTROL_AE_MODE tests
*/
@Test
fun controlAEMode_nullTest() {
assertThat(DataTransformations1D.convert(CONTROL_AE_MODE, null)).isNull()
}
@Test
fun controlAEMode_arrayOfIntTest() {
val keyData = 4
val transformedData = DataTransformations1D.convert(CONTROL_AE_MODE, keyData)
assertThat(transformedData).isEqualTo(keyData)
}
@Test(expected = IllegalArgumentException::class)
fun controlAEMode_floatTest() {
DataTransformations1D.convert(CONTROL_AE_MODE, 18F)
}
/**
* STATISTICS_FACES tests
*/
@Test
fun statisticsFaces_nullTest() {
assertThat(DataTransformations1D.convert(STATISTICS_FACES, null)).isNull()
}
@Test(expected = IllegalArgumentException::class)
fun statisticsFaces_arrayOfIntTest() {
val faces: Array<Int> = arrayOf()
DataTransformations1D.convert(STATISTICS_FACES, faces)
}
@Test(expected = IllegalArgumentException::class)
fun statisticsFaces_nonArrayTest() {
DataTransformations1D.convert(STATISTICS_FACES, 18L)
}
/**
* Tests for keys with no specific transformation e.g. LENS_FOCAL_LENGTH
*/
@Test
fun lensFocalLength_nullTest() {
assertThat(DataTransformations1D.convert(LENS_FOCAL_LENGTH, null)).isNull()
}
@Test
fun lensFocalLength_numberTest() {
val keyDataFloat = 29.9f
val transformedDataFloat = DataTransformations1D.convert(LENS_FOCAL_LENGTH, keyDataFloat)
assertThat(transformedDataFloat is Float).isTrue()
assertThat(keyDataFloat)
.isWithin(0.0001f)
.of(transformedDataFloat as Float)
val keyDataInt = 29
val transformedDataInt = DataTransformations1D.convert(LENS_FOCAL_LENGTH, keyDataInt)
assertThat(transformedDataInt is Int).isTrue()
assertThat(keyDataInt).isEqualTo(transformedDataInt)
}
@Test(expected = IllegalArgumentException::class)
fun lensFocalLength_booleanTest() {
DataTransformations1D.convert(LENS_FOCAL_LENGTH, true)
}
} | apache-2.0 | 6f452b671e2e42a7fc1464e32e75158d | 33.537879 | 100 | 0.703379 | 4.158759 | false | true | false | false |
GunoH/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/highlighter/KotlinColorSettingsPage.kt | 2 | 16501 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.highlighter
import com.intellij.openapi.editor.colors.TextAttributesKey
import com.intellij.openapi.fileTypes.SyntaxHighlighter
import com.intellij.openapi.options.OptionsBundle
import com.intellij.openapi.options.colors.AttributesDescriptor
import com.intellij.openapi.options.colors.ColorDescriptor
import com.intellij.openapi.options.colors.ColorSettingsPage
import com.intellij.openapi.options.colors.RainbowColorSettingsPage
import com.intellij.openapi.util.NlsSafe
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.KotlinIcons
import org.jetbrains.kotlin.idea.KotlinLanguage
import org.jetbrains.kotlin.idea.highlighter.dsl.DslKotlinHighlightingVisitorExtension
import java.lang.reflect.Modifier
class KotlinColorSettingsPage : ColorSettingsPage, RainbowColorSettingsPage {
override fun getLanguage() = KotlinLanguage.INSTANCE
override fun getIcon() = KotlinIcons.SMALL_LOGO
override fun getHighlighter(): SyntaxHighlighter = KotlinHighlighter()
override fun getDemoText(): String {
return """/* Block comment */
<KEYWORD>package</KEYWORD> hello
<KEYWORD>import</KEYWORD> kotlin.collections.* // line comment
/**
* Doc comment here for `SomeClass`
* @see <KDOC_LINK>Iterator#next()</KDOC_LINK>
*/
<ANNOTATION>@Deprecated</ANNOTATION>(<ANNOTATION_ATTRIBUTE_NAME_ATTRIBUTES>message</ANNOTATION_ATTRIBUTE_NAME_ATTRIBUTES> = "Deprecated class")
<BUILTIN_ANNOTATION>private</BUILTIN_ANNOTATION> class <CLASS>MyClass</CLASS><<BUILTIN_ANNOTATION>out</BUILTIN_ANNOTATION> <TYPE_PARAMETER>T</TYPE_PARAMETER> : <TRAIT>Iterable</TRAIT><<TYPE_PARAMETER>T</TYPE_PARAMETER>>>(var <PARAMETER><MUTABLE_VARIABLE><INSTANCE_PROPERTY>prop1</INSTANCE_PROPERTY></MUTABLE_VARIABLE></PARAMETER> : Int) {
fun <FUNCTION_DECLARATION>foo</FUNCTION_DECLARATION>(<PARAMETER>nullable</PARAMETER> : String<QUEST>?</QUEST>, <PARAMETER>r</PARAMETER> : <TRAIT>Runnable</TRAIT>, <PARAMETER>f</PARAMETER> : () -> Int, <PARAMETER>fl</PARAMETER> : <TRAIT>FunctionLike</TRAIT>, dyn: <KEYWORD>dynamic</KEYWORD>) {
<PACKAGE_FUNCTION_CALL>println</PACKAGE_FUNCTION_CALL>("length\nis ${"$"}{<PARAMETER>nullable</PARAMETER><SAFE_ACCESS>?.</SAFE_ACCESS><INSTANCE_PROPERTY>length</INSTANCE_PROPERTY>} <STRING_ESCAPE><INVALID_STRING_ESCAPE>\e</INVALID_STRING_ESCAPE></STRING_ESCAPE>")
<PACKAGE_FUNCTION_CALL>println</PACKAGE_FUNCTION_CALL>(<PARAMETER>nullable</PARAMETER><EXCLEXCL>!!</EXCLEXCL>.<INSTANCE_PROPERTY>length</INSTANCE_PROPERTY>)
val <LOCAL_VARIABLE>ints</LOCAL_VARIABLE> = java.util.<CONSTRUCTOR_CALL>ArrayList</CONSTRUCTOR_CALL><Int?>(2)
<LOCAL_VARIABLE>ints</LOCAL_VARIABLE>[0] = 102 + <PARAMETER><VARIABLE_AS_FUNCTION_CALL>f</VARIABLE_AS_FUNCTION_CALL></PARAMETER>() + <PARAMETER><VARIABLE_AS_FUNCTION_LIKE_CALL>fl</VARIABLE_AS_FUNCTION_LIKE_CALL></PARAMETER>()
val <LOCAL_VARIABLE>myFun</LOCAL_VARIABLE> = <FUNCTION_LITERAL_BRACES_AND_ARROW>{</FUNCTION_LITERAL_BRACES_AND_ARROW> <FUNCTION_LITERAL_BRACES_AND_ARROW>-></FUNCTION_LITERAL_BRACES_AND_ARROW> "" <FUNCTION_LITERAL_BRACES_AND_ARROW>}</FUNCTION_LITERAL_BRACES_AND_ARROW>;
var <LOCAL_VARIABLE><MUTABLE_VARIABLE>ref</MUTABLE_VARIABLE></LOCAL_VARIABLE> = <LOCAL_VARIABLE>ints</LOCAL_VARIABLE>.<INSTANCE_PROPERTY>size</INSTANCE_PROPERTY>
ints.<EXTENSION_PROPERTY>lastIndex</EXTENSION_PROPERTY> + <PACKAGE_PROPERTY>globalCounter</PACKAGE_PROPERTY>
<LOCAL_VARIABLE>ints</LOCAL_VARIABLE>.<EXTENSION_FUNCTION_CALL>forEach</EXTENSION_FUNCTION_CALL> <LABEL>lit@</LABEL> <FUNCTION_LITERAL_BRACES_AND_ARROW>{</FUNCTION_LITERAL_BRACES_AND_ARROW>
<KEYWORD>if</KEYWORD> (<FUNCTION_LITERAL_DEFAULT_PARAMETER>it</FUNCTION_LITERAL_DEFAULT_PARAMETER> == null) return<LABEL>@lit</LABEL>
<PACKAGE_FUNCTION_CALL>println</PACKAGE_FUNCTION_CALL>(<FUNCTION_LITERAL_DEFAULT_PARAMETER><SMART_CAST_VALUE>it</SMART_CAST_VALUE></FUNCTION_LITERAL_DEFAULT_PARAMETER> + <LOCAL_VARIABLE><MUTABLE_VARIABLE><WRAPPED_INTO_REF>ref</WRAPPED_INTO_REF></MUTABLE_VARIABLE></LOCAL_VARIABLE>)
<FUNCTION_LITERAL_BRACES_AND_ARROW>}</FUNCTION_LITERAL_BRACES_AND_ARROW>
dyn.<DYNAMIC_FUNCTION_CALL>dynamicCall</DYNAMIC_FUNCTION_CALL>()
dyn.<DYNAMIC_PROPERTY_CALL>dynamicProp</DYNAMIC_PROPERTY_CALL> = 5
val <LOCAL_VARIABLE>klass</LOCAL_VARIABLE> = <CLASS>MyClass</CLASS>::<KEYWORD>class</KEYWORD>
val year = java.time.LocalDate.now().<SYNTHETIC_EXTENSION_PROPERTY>year</SYNTHETIC_EXTENSION_PROPERTY>
}
<BUILTIN_ANNOTATION>override</BUILTIN_ANNOTATION> fun hashCode(): Int {
return <KEYWORD>super</KEYWORD>.<FUNCTION_CALL>hashCode</FUNCTION_CALL>() * 31
}
}
fun Int?.bar() {
<KEYWORD>if</KEYWORD> (this != null) {
println(<NAMED_ARGUMENT>message =</NAMED_ARGUMENT> <SMART_CAST_RECEIVER>toString</SMART_CAST_RECEIVER>())
}
else {
println(<SMART_CONSTANT>this</SMART_CONSTANT>.toString())
}
}
var <PACKAGE_PROPERTY_CUSTOM_PROPERTY_DECLARATION><MUTABLE_VARIABLE>globalCounter</MUTABLE_VARIABLE></PACKAGE_PROPERTY_CUSTOM_PROPERTY_DECLARATION> : Int = <NUMBER>5</NUMBER>
<KEYWORD>get</KEYWORD>() = <LOCAL_VARIABLE><MUTABLE_VARIABLE><BACKING_FIELD_VARIABLE>field</BACKING_FIELD_VARIABLE></MUTABLE_VARIABLE></LOCAL_VARIABLE>
<KEYWORD>abstract</KEYWORD> class <ABSTRACT_CLASS>Abstract</ABSTRACT_CLASS> {
val <INSTANCE_PROPERTY_CUSTOM_PROPERTY_DECLARATION>bar</INSTANCE_PROPERTY_CUSTOM_PROPERTY_DECLARATION> <KEYWORD>get</KEYWORD>() = 1
fun <FUNCTION_DECLARATION>test</FUNCTION_DECLARATION>() {
<INSTANCE_PROPERTY_CUSTOM_PROPERTY_DECLARATION>bar</INSTANCE_PROPERTY_CUSTOM_PROPERTY_DECLARATION>
}
}
<KEYWORD>object</KEYWORD> <OBJECT>Obj</OBJECT>
<KEYWORD>enum</KEYWORD> <KEYWORD>class</KEYWORD> <ENUM>E</ENUM> { <ENUM_ENTRY>A</ENUM_ENTRY>, <ENUM_ENTRY>B</ENUM_ENTRY> }
<KEYWORD>interface</KEYWORD> <TRAIT>FunctionLike</TRAIT> {
<BUILTIN_ANNOTATION>operator</BUILTIN_ANNOTATION> <KEYWORD>fun</KEYWORD> <FUNCTION_DECLARATION>invoke</FUNCTION_DECLARATION>() = <NUMBER>1</NUMBER>
}
<KEYWORD>typealias</KEYWORD> <TYPE_ALIAS>Predicate</TYPE_ALIAS><<TYPE_PARAMETER>T</TYPE_PARAMETER>> = (<TYPE_PARAMETER>T</TYPE_PARAMETER>) -> <CLASS>Boolean</CLASS>
<KEYWORD>fun</KEYWORD> <FUNCTION_DECLARATION>baz</FUNCTION_DECLARATION>(<PARAMETER>p</PARAMETER>: <TYPE_ALIAS>Predicate</TYPE_ALIAS><<CLASS>Int</CLASS>>) = <PARAMETER><VARIABLE_AS_FUNCTION_CALL>p</VARIABLE_AS_FUNCTION_CALL></PARAMETER>(<NUMBER>42</NUMBER>)
<KEYWORD>suspend</KEYWORD> <KEYWORD>fun</KEYWORD> <FUNCTION_DECLARATION>suspendCall</FUNCTION_DECLARATION>() =
<SUSPEND_FUNCTION_CALL>suspendFn</SUSPEND_FUNCTION_CALL>()
<KEYWORD>suspend</KEYWORD> <KEYWORD>fun</KEYWORD> <FUNCTION_DECLARATION>suspendFn</FUNCTION_DECLARATION>() {}"""
}
override fun getAdditionalHighlightingTagToDescriptorMap(): Map<String, TextAttributesKey> {
val map = HashMap<String, TextAttributesKey>()
for (field in KotlinHighlightingColors::class.java.fields) {
if (Modifier.isStatic(field.modifiers)) {
try {
map.put(field.name, field.get(null) as TextAttributesKey)
} catch (e: IllegalAccessException) {
assert(false)
}
}
}
map.putAll(DslKotlinHighlightingVisitorExtension.descriptionsToStyles)
return map
}
override fun getAttributeDescriptors(): Array<AttributesDescriptor> {
infix fun String.to(key: TextAttributesKey) = AttributesDescriptor(this, key)
return arrayOf(
KotlinBundle.message("highlighter.descriptor.text.builtin.keyword") to KotlinHighlightingColors.KEYWORD,
KotlinBundle.message("highlighter.descriptor.text.builtin.keyword.val") to KotlinHighlightingColors.VAL_KEYWORD,
KotlinBundle.message("highlighter.descriptor.text.builtin.keyword.var") to KotlinHighlightingColors.VAR_KEYWORD,
KotlinBundle.message("highlighter.descriptor.text.builtin.annotation") to KotlinHighlightingColors.BUILTIN_ANNOTATION,
OptionsBundle.message("options.java.attribute.descriptor.number") to KotlinHighlightingColors.NUMBER,
OptionsBundle.message("options.java.attribute.descriptor.string") to KotlinHighlightingColors.STRING,
KotlinBundle.message("highlighter.descriptor.text.string.escape") to KotlinHighlightingColors.STRING_ESCAPE,
OptionsBundle.message("options.java.attribute.descriptor.invalid.escape.in.string") to KotlinHighlightingColors.INVALID_STRING_ESCAPE,
OptionsBundle.message("options.java.attribute.descriptor.operator.sign") to KotlinHighlightingColors.OPERATOR_SIGN,
OptionsBundle.message("options.java.attribute.descriptor.parentheses") to KotlinHighlightingColors.PARENTHESIS,
OptionsBundle.message("options.java.attribute.descriptor.braces") to KotlinHighlightingColors.BRACES,
KotlinBundle.message("highlighter.descriptor.text.closure.braces") to KotlinHighlightingColors.FUNCTION_LITERAL_BRACES_AND_ARROW,
KotlinBundle.message("highlighter.descriptor.text.arrow") to KotlinHighlightingColors.ARROW,
OptionsBundle.message("options.java.attribute.descriptor.brackets") to KotlinHighlightingColors.BRACKETS,
OptionsBundle.message("options.java.attribute.descriptor.comma") to KotlinHighlightingColors.COMMA,
OptionsBundle.message("options.java.attribute.descriptor.semicolon") to KotlinHighlightingColors.SEMICOLON,
KotlinBundle.message("highlighter.descriptor.text.colon") to KotlinHighlightingColors.COLON,
KotlinBundle.message("highlighter.descriptor.text.double.colon") to KotlinHighlightingColors.DOUBLE_COLON,
OptionsBundle.message("options.java.attribute.descriptor.dot") to KotlinHighlightingColors.DOT,
KotlinBundle.message("highlighter.descriptor.text.safe.access") to KotlinHighlightingColors.SAFE_ACCESS,
KotlinBundle.message("highlighter.descriptor.text.quest") to KotlinHighlightingColors.QUEST,
KotlinBundle.message("highlighter.descriptor.text.exclexcl") to KotlinHighlightingColors.EXCLEXCL,
OptionsBundle.message("options.java.attribute.descriptor.line.comment") to KotlinHighlightingColors.LINE_COMMENT,
OptionsBundle.message("options.java.attribute.descriptor.block.comment") to KotlinHighlightingColors.BLOCK_COMMENT,
KotlinBundle.message("highlighter.descriptor.text.kdoc.comment") to KotlinHighlightingColors.DOC_COMMENT,
KotlinBundle.message("highlighter.descriptor.text.kdoc.tag") to KotlinHighlightingColors.KDOC_TAG,
KotlinBundle.message("highlighter.descriptor.text.kdoc.value") to KotlinHighlightingColors.KDOC_LINK,
OptionsBundle.message("options.java.attribute.descriptor.class") to KotlinHighlightingColors.CLASS,
OptionsBundle.message("options.java.attribute.descriptor.type.parameter") to KotlinHighlightingColors.TYPE_PARAMETER,
OptionsBundle.message("options.java.attribute.descriptor.abstract.class") to KotlinHighlightingColors.ABSTRACT_CLASS,
OptionsBundle.message("options.java.attribute.descriptor.interface") to KotlinHighlightingColors.TRAIT,
KotlinBundle.message("highlighter.descriptor.text.annotation") to KotlinHighlightingColors.ANNOTATION,
KotlinBundle.message("highlighter.descriptor.text.annotation.attribute.name") to KotlinHighlightingColors.ANNOTATION_ATTRIBUTE_NAME_ATTRIBUTES,
KotlinBundle.message("highlighter.descriptor.text.object") to KotlinHighlightingColors.OBJECT,
KotlinBundle.message("highlighter.descriptor.text.enum") to KotlinHighlightingColors.ENUM,
KotlinBundle.message("highlighter.descriptor.text.enumEntry") to KotlinHighlightingColors.ENUM_ENTRY,
KotlinBundle.message("highlighter.descriptor.text.typeAlias") to KotlinHighlightingColors.TYPE_ALIAS,
KotlinBundle.message("highlighter.descriptor.text.var") to KotlinHighlightingColors.MUTABLE_VARIABLE,
KotlinBundle.message("highlighter.descriptor.text.local.variable") to KotlinHighlightingColors.LOCAL_VARIABLE,
OptionsBundle.message("options.java.attribute.descriptor.parameter") to KotlinHighlightingColors.PARAMETER,
KotlinBundle.message("highlighter.descriptor.text.captured.variable") to KotlinHighlightingColors.WRAPPED_INTO_REF,
KotlinBundle.message("highlighter.descriptor.text.instance.property") to KotlinHighlightingColors.INSTANCE_PROPERTY,
KotlinBundle.message("highlighter.descriptor.text.instance.property.custom.property.declaration") to KotlinHighlightingColors.INSTANCE_PROPERTY_CUSTOM_PROPERTY_DECLARATION,
KotlinBundle.message("highlighter.descriptor.text.package.property.custom.property.declaration") to KotlinHighlightingColors.PACKAGE_PROPERTY_CUSTOM_PROPERTY_DECLARATION,
KotlinBundle.message("highlighter.descriptor.text.package.property") to KotlinHighlightingColors.PACKAGE_PROPERTY,
KotlinBundle.message("highlighter.descriptor.text.field") to KotlinHighlightingColors.BACKING_FIELD_VARIABLE,
KotlinBundle.message("highlighter.descriptor.text.extension.property") to KotlinHighlightingColors.EXTENSION_PROPERTY,
KotlinBundle.message("highlighter.descriptor.text.synthetic.extension.property") to KotlinHighlightingColors.SYNTHETIC_EXTENSION_PROPERTY,
KotlinBundle.message("highlighter.descriptor.text.dynamic.property") to KotlinHighlightingColors.DYNAMIC_PROPERTY_CALL,
KotlinBundle.message("highlighter.descriptor.text.android.extensions.property") to KotlinHighlightingColors.ANDROID_EXTENSIONS_PROPERTY_CALL,
KotlinBundle.message("highlighter.descriptor.text.it") to KotlinHighlightingColors.FUNCTION_LITERAL_DEFAULT_PARAMETER,
KotlinBundle.message("highlighter.descriptor.text.fun") to KotlinHighlightingColors.FUNCTION_DECLARATION,
KotlinBundle.message("highlighter.descriptor.text.fun.call") to KotlinHighlightingColors.FUNCTION_CALL,
KotlinBundle.message("highlighter.descriptor.text.dynamic.fun.call") to KotlinHighlightingColors.DYNAMIC_FUNCTION_CALL,
KotlinBundle.message("highlighter.descriptor.text.suspend.fun.call") to KotlinHighlightingColors.SUSPEND_FUNCTION_CALL,
KotlinBundle.message("highlighter.descriptor.text.package.fun.call") to KotlinHighlightingColors.PACKAGE_FUNCTION_CALL,
KotlinBundle.message("highlighter.descriptor.text.extension.fun.call") to KotlinHighlightingColors.EXTENSION_FUNCTION_CALL,
KotlinBundle.message("highlighter.descriptor.text.constructor.call") to KotlinHighlightingColors.CONSTRUCTOR_CALL,
KotlinBundle.message("highlighter.descriptor.text.variable.as.function.call") to KotlinHighlightingColors.VARIABLE_AS_FUNCTION_CALL,
KotlinBundle.message("highlighter.descriptor.text.variable.as.function.like.call") to KotlinHighlightingColors.VARIABLE_AS_FUNCTION_LIKE_CALL,
KotlinBundle.message("highlighter.descriptor.text.smart.cast") to KotlinHighlightingColors.SMART_CAST_VALUE,
KotlinBundle.message("highlighter.descriptor.text.smart.constant") to KotlinHighlightingColors.SMART_CONSTANT,
KotlinBundle.message("highlighter.descriptor.text.smart.cast.receiver") to KotlinHighlightingColors.SMART_CAST_RECEIVER,
KotlinBundle.message("highlighter.descriptor.text.label") to KotlinHighlightingColors.LABEL,
KotlinBundle.message("highlighter.descriptor.text.named.argument") to KotlinHighlightingColors.NAMED_ARGUMENT
) + DslKotlinHighlightingVisitorExtension.descriptionsToStyles.map { (description, key) -> description to key }.toTypedArray()
}
override fun getColorDescriptors(): Array<ColorDescriptor> = ColorDescriptor.EMPTY_ARRAY
override fun getDisplayName(): String {
@Suppress("UnnecessaryVariable")
@NlsSafe
val name = KotlinLanguage.NAME
return name
}
override fun isRainbowType(type: TextAttributesKey): Boolean {
return type == KotlinHighlightingColors.LOCAL_VARIABLE ||
type == KotlinHighlightingColors.PARAMETER
}
}
| apache-2.0 | 8f8e27fcc92526c0364ad2276bf5fabb | 83.188776 | 338 | 0.758075 | 4.710534 | false | false | false | false |
GunoH/intellij-community | platform/workspaceModel/storage/testEntities/gen/com/intellij/workspaceModel/storage/entities/test/api/OptionalStringEntityImpl.kt | 2 | 6201 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.workspaceModel.storage.entities.test.api
import com.intellij.workspaceModel.storage.EntityInformation
import com.intellij.workspaceModel.storage.EntitySource
import com.intellij.workspaceModel.storage.EntityStorage
import com.intellij.workspaceModel.storage.GeneratedCodeApiVersion
import com.intellij.workspaceModel.storage.GeneratedCodeImplVersion
import com.intellij.workspaceModel.storage.MutableEntityStorage
import com.intellij.workspaceModel.storage.WorkspaceEntity
import com.intellij.workspaceModel.storage.impl.ConnectionId
import com.intellij.workspaceModel.storage.impl.ModifiableWorkspaceEntityBase
import com.intellij.workspaceModel.storage.impl.UsedClassesCollector
import com.intellij.workspaceModel.storage.impl.WorkspaceEntityBase
import com.intellij.workspaceModel.storage.impl.WorkspaceEntityData
import com.intellij.workspaceModel.storage.impl.containers.toMutableWorkspaceList
import org.jetbrains.deft.ObjBuilder
import org.jetbrains.deft.Type
@GeneratedCodeApiVersion(1)
@GeneratedCodeImplVersion(1)
open class OptionalStringEntityImpl(val dataSource: OptionalStringEntityData) : OptionalStringEntity, WorkspaceEntityBase() {
companion object {
val connections = listOf<ConnectionId>(
)
}
override val data: String?
get() = dataSource.data
override val entitySource: EntitySource
get() = dataSource.entitySource
override fun connectionIdList(): List<ConnectionId> {
return connections
}
class Builder(result: OptionalStringEntityData?) : ModifiableWorkspaceEntityBase<OptionalStringEntity, OptionalStringEntityData>(
result), OptionalStringEntity.Builder {
constructor() : this(OptionalStringEntityData())
override fun applyToBuilder(builder: MutableEntityStorage) {
if (this.diff != null) {
if (existsInBuilder(builder)) {
this.diff = builder
return
}
else {
error("Entity OptionalStringEntity is already created in a different builder")
}
}
this.diff = builder
this.snapshot = builder
addToBuilder()
this.id = getEntityData().createEntityId()
// After adding entity data to the builder, we need to unbind it and move the control over entity data to builder
// Builder may switch to snapshot at any moment and lock entity data to modification
this.currentEntityData = null
// Process linked entities that are connected without a builder
processLinkedEntities(builder)
checkInitialization() // TODO uncomment and check failed tests
}
fun checkInitialization() {
val _diff = diff
if (!getEntityData().isEntitySourceInitialized()) {
error("Field WorkspaceEntity#entitySource should be initialized")
}
}
override fun connectionIdList(): List<ConnectionId> {
return connections
}
// Relabeling code, move information from dataSource to this builder
override fun relabel(dataSource: WorkspaceEntity, parents: Set<WorkspaceEntity>?) {
dataSource as OptionalStringEntity
if (this.entitySource != dataSource.entitySource) this.entitySource = dataSource.entitySource
if (this.data != dataSource?.data) this.data = dataSource.data
if (parents != null) {
}
}
override var entitySource: EntitySource
get() = getEntityData().entitySource
set(value) {
checkModificationAllowed()
getEntityData(true).entitySource = value
changedProperty.add("entitySource")
}
override var data: String?
get() = getEntityData().data
set(value) {
checkModificationAllowed()
getEntityData(true).data = value
changedProperty.add("data")
}
override fun getEntityClass(): Class<OptionalStringEntity> = OptionalStringEntity::class.java
}
}
class OptionalStringEntityData : WorkspaceEntityData<OptionalStringEntity>() {
var data: String? = null
override fun wrapAsModifiable(diff: MutableEntityStorage): WorkspaceEntity.Builder<OptionalStringEntity> {
val modifiable = OptionalStringEntityImpl.Builder(null)
modifiable.diff = diff
modifiable.snapshot = diff
modifiable.id = createEntityId()
return modifiable
}
override fun createEntity(snapshot: EntityStorage): OptionalStringEntity {
return getCached(snapshot) {
val entity = OptionalStringEntityImpl(this)
entity.snapshot = snapshot
entity.id = createEntityId()
entity
}
}
override fun getEntityInterface(): Class<out WorkspaceEntity> {
return OptionalStringEntity::class.java
}
override fun serialize(ser: EntityInformation.Serializer) {
}
override fun deserialize(de: EntityInformation.Deserializer) {
}
override fun createDetachedEntity(parents: List<WorkspaceEntity>): WorkspaceEntity {
return OptionalStringEntity(entitySource) {
this.data = [email protected]
}
}
override fun getRequiredParents(): List<Class<out WorkspaceEntity>> {
val res = mutableListOf<Class<out WorkspaceEntity>>()
return res
}
override fun equals(other: Any?): Boolean {
if (other == null) return false
if (this.javaClass != other.javaClass) return false
other as OptionalStringEntityData
if (this.entitySource != other.entitySource) return false
if (this.data != other.data) return false
return true
}
override fun equalsIgnoringEntitySource(other: Any?): Boolean {
if (other == null) return false
if (this.javaClass != other.javaClass) return false
other as OptionalStringEntityData
if (this.data != other.data) return false
return true
}
override fun hashCode(): Int {
var result = entitySource.hashCode()
result = 31 * result + data.hashCode()
return result
}
override fun hashCodeIgnoringEntitySource(): Int {
var result = javaClass.hashCode()
result = 31 * result + data.hashCode()
return result
}
override fun collectClassUsagesData(collector: UsedClassesCollector) {
collector.sameForAllEntities = true
}
}
| apache-2.0 | ec4f8e83f0bf0a5aaf6861d86bab95df | 31.636842 | 131 | 0.734559 | 5.336489 | false | false | false | false |
siosio/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/intentions/RemoveBracesIntention.kt | 2 | 5481 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.intentions
import com.intellij.openapi.editor.Editor
import com.intellij.psi.PsiComment
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiWhiteSpace
import org.jetbrains.kotlin.KtNodeTypes
import org.jetbrains.kotlin.idea.KotlinBundle
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.endOffset
import org.jetbrains.kotlin.psi.psiUtil.startOffset
class RemoveBracesIntention : SelfTargetingIntention<KtElement>(KtElement::class.java, KotlinBundle.lazyMessage("remove.braces")) {
private fun KtElement.findChildBlock() = when (this) {
is KtBlockExpression -> this
is KtLoopExpression -> body as? KtBlockExpression
is KtWhenEntry -> expression as? KtBlockExpression
else -> null
}
override fun isApplicableTo(element: KtElement, caretOffset: Int): Boolean {
val block = element.findChildBlock() ?: return false
if (!isApplicableTo(block)) return false
when (val container = block.parent) {
is KtContainerNode -> {
val description = container.description() ?: return false
setTextGetter(KotlinBundle.lazyMessage("remove.braces.from.0.statement", description))
}
is KtWhenEntry -> {
setTextGetter(KotlinBundle.lazyMessage("remove.braces.from.when.entry"))
}
}
return true
}
override fun applyTo(element: KtElement, editor: Editor?) {
val block = element.findChildBlock() ?: return
removeBraces(element, block, editor)
}
override fun allowCaretInsideElement(element: PsiElement) = element !is KtBlockExpression || element.parent is KtWhenEntry
companion object {
fun isApplicableTo(block: KtBlockExpression): Boolean {
val singleStatement = block.statements.singleOrNull() ?: return false
if (singleStatement is KtLambdaExpression && singleStatement.functionLiteral.arrow == null) return false
when (val container = block.parent) {
is KtContainerNode -> {
if (singleStatement is KtProperty || singleStatement is KtClass) return false
if (singleStatement is KtIfExpression) {
val elseExpression = (container.parent as? KtIfExpression)?.`else`
if (elseExpression != null && elseExpression != block) return false
}
return true
}
is KtWhenEntry -> {
return singleStatement !is KtNamedDeclaration
}
else -> return false
}
}
fun removeBraces(element: KtElement, block: KtBlockExpression, editor: Editor? = null) {
val factory = KtPsiFactory(element)
val statement = block.statements.single()
val caretOnAfterStatement = if (editor != null) editor.caretModel.offset >= statement.endOffset else false
val container = block.parent
val construct = container.parent as KtExpression
handleComments(construct, block)
val newElement = block.replace(statement.copy())
editor?.caretModel?.moveToOffset(if (caretOnAfterStatement) newElement.endOffset else newElement.startOffset)
if (construct is KtDoWhileExpression) {
newElement.parent!!.addAfter(factory.createNewLine(), newElement)
} else if (editor != null) {
val document = editor.document
val line = document.getLineNumber(newElement.startOffset)
val rightMargin = editor.settings.getRightMargin(editor.project)
if (document.getLineEndOffset(line) - document.getLineStartOffset(line) >= rightMargin) {
newElement.parent.addBefore(factory.createNewLine(), newElement)
}
}
if (construct is KtIfExpression &&
container.node.elementType == KtNodeTypes.ELSE &&
construct.parent is KtExpression &&
construct.parent !is KtStatementExpression
) {
val replaced = construct.replace(factory.createExpressionByPattern("($0)", construct))
(replaced.children[0] as? KtIfExpression)?.`else`?.let {
editor?.caretModel?.moveToOffset(if (caretOnAfterStatement) it.endOffset else it.startOffset)
}
}
}
private fun handleComments(construct: KtExpression, block: KtBlockExpression) {
var sibling = block.firstChild?.nextSibling
while (sibling != null) {
if (sibling is PsiComment) {
//cleans up extra whitespace
val psiFactory = KtPsiFactory(construct)
if (construct.prevSibling is PsiWhiteSpace) {
construct.prevSibling!!.replace(psiFactory.createNewLine())
}
val commentElement = construct.parent.addBefore(sibling, construct.prevSibling)
construct.parent.addBefore(psiFactory.createNewLine(), commentElement)
}
sibling = sibling.nextSibling
}
}
}
}
| apache-2.0 | 1c323cbbc66a464c19fda1ec9d62ecfc | 45.846154 | 158 | 0.624521 | 5.644696 | false | false | false | false |
JetBrains/kotlin-native | backend.native/compiler/ir/backend.native/src/org/jetbrains/kotlin/backend/konan/lower/InitializersLowering.kt | 1 | 11144 | /*
* Copyright 2010-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license
* that can be found in the LICENSE file.
*/
package org.jetbrains.kotlin.backend.konan.lower
import org.jetbrains.kotlin.backend.common.ClassLoweringPass
import org.jetbrains.kotlin.backend.common.CommonBackendContext
import org.jetbrains.kotlin.backend.common.ir.createDispatchReceiverParameter
import org.jetbrains.kotlin.backend.common.lower.createIrBuilder
import org.jetbrains.kotlin.backend.common.lower.irBlockBody
import org.jetbrains.kotlin.backend.konan.descriptors.synthesizedName
import org.jetbrains.kotlin.backend.konan.isNonGeneratedAnnotation
import org.jetbrains.kotlin.descriptors.*
import org.jetbrains.kotlin.ir.IrStatement
import org.jetbrains.kotlin.ir.builders.irDelegatingConstructorCall
import org.jetbrains.kotlin.ir.declarations.*
import org.jetbrains.kotlin.ir.declarations.impl.IrFunctionImpl
import org.jetbrains.kotlin.ir.expressions.*
import org.jetbrains.kotlin.ir.expressions.impl.*
import org.jetbrains.kotlin.ir.symbols.IrSimpleFunctionSymbol
import org.jetbrains.kotlin.ir.symbols.impl.IrSimpleFunctionSymbolImpl
import org.jetbrains.kotlin.ir.types.isPrimitiveType
import org.jetbrains.kotlin.ir.types.isString
import org.jetbrains.kotlin.ir.util.*
import org.jetbrains.kotlin.ir.visitors.IrElementTransformerVoid
import org.jetbrains.kotlin.ir.visitors.transformChildrenVoid
internal class InitializersLowering(val context: CommonBackendContext) : ClassLoweringPass {
object STATEMENT_ORIGIN_ANONYMOUS_INITIALIZER : IrStatementOriginImpl("ANONYMOUS_INITIALIZER")
object DECLARATION_ORIGIN_ANONYMOUS_INITIALIZER : IrDeclarationOriginImpl("ANONYMOUS_INITIALIZER")
override fun lower(irClass: IrClass) {
if (irClass.isInterface) return
InitializersTransformer(irClass).lowerInitializers()
}
private inner class InitializersTransformer(val irClass: IrClass) {
val initializers = mutableListOf<IrStatement>()
fun lowerInitializers() {
collectAndRemoveInitializers()
val initializeMethodSymbol = createInitializerMethod()
lowerConstructors(initializeMethodSymbol)
}
private fun collectAndRemoveInitializers() {
// Do with one traversal in order to preserve initializers order.
irClass.transformChildrenVoid(object : IrElementTransformerVoid() {
override fun visitClass(declaration: IrClass): IrStatement {
// Skip nested.
return declaration
}
override fun visitAnonymousInitializer(declaration: IrAnonymousInitializer): IrStatement {
initializers.add(IrBlockImpl(declaration.startOffset, declaration.endOffset,
context.irBuiltIns.unitType, STATEMENT_ORIGIN_ANONYMOUS_INITIALIZER, declaration.body.statements))
return declaration
}
override fun visitField(declaration: IrField): IrStatement {
val initializer = declaration.initializer ?: return declaration
val startOffset = initializer.startOffset
val endOffset = initializer.endOffset
val initExpression = initializer.expression
initializers.add(IrBlockImpl(startOffset, endOffset,
context.irBuiltIns.unitType,
IrStatementOrigin.INITIALIZE_FIELD,
listOf(
IrSetFieldImpl(startOffset, endOffset, declaration.symbol,
IrGetValueImpl(
startOffset, endOffset,
irClass.thisReceiver!!.type, irClass.thisReceiver!!.symbol
),
initExpression,
context.irBuiltIns.unitType,
IrStatementOrigin.INITIALIZE_FIELD)))
)
// We shall keep initializer for constants for compile-time instantiation.
// We suppose that if the property is const, then its initializer is IrConst.
// If this requirement isn't satisfied, then PropertyAccessorInlineLowering can fail.
declaration.initializer =
if (initExpression is IrConst<*> &&
declaration.correspondingPropertySymbol?.owner?.isConst == true) {
IrExpressionBodyImpl(initExpression.copy())
} else {
null
}
return declaration
}
})
irClass.declarations.transformFlat {
if (it !is IrAnonymousInitializer)
null
else listOf()
}
}
private fun createInitializerMethod(): IrSimpleFunctionSymbol? {
if (irClass.declarations.any { it is IrConstructor && it.isPrimary })
return null // Place initializers in the primary constructor.
val startOffset = irClass.startOffset
val endOffset = irClass.endOffset
val initializeFun =
IrFunctionImpl(
startOffset, endOffset,
DECLARATION_ORIGIN_ANONYMOUS_INITIALIZER,
IrSimpleFunctionSymbolImpl(),
"INITIALIZER".synthesizedName,
DescriptorVisibilities.PRIVATE,
Modality.FINAL,
context.irBuiltIns.unitType,
isInline = false,
isSuspend = false,
isExternal = false,
isTailrec = false,
isExpect = false,
isFakeOverride = false,
isOperator = false,
isInfix = false
).apply {
parent = irClass
irClass.declarations.add(this)
createDispatchReceiverParameter()
body = IrBlockBodyImpl(startOffset, endOffset, initializers)
}
for (initializer in initializers) {
initializer.transformChildrenVoid(object : IrElementTransformerVoid() {
override fun visitGetValue(expression: IrGetValue): IrExpression {
if (expression.symbol == irClass.thisReceiver!!.symbol) {
return IrGetValueImpl(
expression.startOffset,
expression.endOffset,
initializeFun.dispatchReceiverParameter!!.type,
initializeFun.dispatchReceiverParameter!!.symbol
)
}
return expression
}
})
initializer.setDeclarationsParent(initializeFun)
}
return initializeFun.symbol
}
private fun lowerConstructors(initializeMethodSymbol: IrSimpleFunctionSymbol?) {
if (irClass.kind == ClassKind.ANNOTATION_CLASS) {
if (irClass.isNonGeneratedAnnotation()) return
val irConstructor = irClass.declarations.filterIsInstance<IrConstructor>().single()
assert(irConstructor.body == null)
irConstructor.body = context.createIrBuilder(irConstructor.symbol).irBlockBody(irConstructor) {
+irDelegatingConstructorCall(context.irBuiltIns.anyClass.owner.constructors.single())
+IrInstanceInitializerCallImpl(startOffset, endOffset, irClass.symbol, context.irBuiltIns.unitType)
}
}
irClass.transformChildrenVoid(object : IrElementTransformerVoid() {
override fun visitClass(declaration: IrClass): IrStatement {
// Skip nested.
return declaration
}
override fun visitConstructor(declaration: IrConstructor): IrStatement {
val body = declaration.body ?: return declaration
val blockBody = body as? IrBlockBody
?: throw AssertionError("Unexpected constructor body: ${declaration.body}")
blockBody.statements.transformFlat {
when {
it is IrInstanceInitializerCall -> {
if (initializeMethodSymbol == null) {
assert(declaration.isPrimary)
for (initializer in initializers)
initializer.setDeclarationsParent(declaration)
initializers
} else {
val startOffset = it.startOffset
val endOffset = it.endOffset
listOf(IrCallImpl(startOffset, endOffset,
context.irBuiltIns.unitType, initializeMethodSymbol,
initializeMethodSymbol.owner.typeParameters.size,
initializeMethodSymbol.owner.valueParameters.size
).apply {
dispatchReceiver = IrGetValueImpl(
startOffset, endOffset,
irClass.thisReceiver!!.type, irClass.thisReceiver!!.symbol
)
})
}
}
/**
* IR for kotlin.Any is:
* BLOCK_BODY
* DELEGATING_CONSTRUCTOR_CALL 'constructor Any()'
* INSTANCE_INITIALIZER_CALL classDescriptor='Any'
*
* to avoid possible recursion we manually reject body generation for Any.
*/
it is IrDelegatingConstructorCall
&& irClass.symbol == context.irBuiltIns.anyClass
&& it.symbol == declaration.symbol -> {
listOf()
}
else -> null
}
}
return declaration
}
})
}
}
}
| apache-2.0 | 9859ec990abdf0f5ef173ba3c26aa535 | 48.309735 | 126 | 0.533291 | 6.947631 | false | false | false | false |
jwren/intellij-community | plugins/package-search/src/com/jetbrains/packagesearch/intellij/plugin/ui/toolwindow/panels/management/packages/PackagesListPanel.kt | 1 | 30335 | package com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.panels.management.packages
import com.intellij.openapi.actionSystem.ActionManager
import com.intellij.openapi.actionSystem.DefaultActionGroup
import com.intellij.openapi.application.EDT
import com.intellij.openapi.project.Project
import com.intellij.openapi.wm.IdeFocusManager
import com.intellij.ui.DocumentAdapter
import com.intellij.ui.SearchTextField
import com.intellij.ui.components.JBPanelWithEmptyText
import com.intellij.ui.components.JBScrollPane
import com.intellij.util.ui.JBUI
import com.jetbrains.packagesearch.api.v2.ApiPackagesResponse
import com.jetbrains.packagesearch.api.v2.ApiStandardPackage
import com.jetbrains.packagesearch.intellij.plugin.PackageSearchBundle
import com.jetbrains.packagesearch.intellij.plugin.data.PackageUpgradeCandidates
import com.jetbrains.packagesearch.intellij.plugin.fus.FUSGroupIds
import com.jetbrains.packagesearch.intellij.plugin.fus.PackageSearchEventsLogger
import com.jetbrains.packagesearch.intellij.plugin.ui.ComponentActionWrapper
import com.jetbrains.packagesearch.intellij.plugin.ui.PackageSearchUI
import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.FilterOptions
import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.InstalledDependency
import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.KnownRepositories
import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.OperationExecutor
import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.PackageIdentifier
import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.PackageModel
import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.PackageScope
import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.PackagesToUpgrade
import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.ProjectDataProvider
import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.SearchResultUiState
import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.TargetModules
import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.UiPackageModel
import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.matchesCoordinates
import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.operations.PackageSearchOperation
import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.operations.PackageSearchOperationFactory
import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.toUiPackageModel
import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.versions.NormalizedPackageVersion
import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.panels.PackageSearchPanelBase
import com.jetbrains.packagesearch.intellij.plugin.ui.updateAndRepaint
import com.jetbrains.packagesearch.intellij.plugin.ui.util.emptyBorder
import com.jetbrains.packagesearch.intellij.plugin.ui.util.onOpacityChanged
import com.jetbrains.packagesearch.intellij.plugin.ui.util.onVisibilityChanged
import com.jetbrains.packagesearch.intellij.plugin.ui.util.scaled
import com.jetbrains.packagesearch.intellij.plugin.util.CoroutineLRUCache
import com.jetbrains.packagesearch.intellij.plugin.util.lifecycleScope
import com.jetbrains.packagesearch.intellij.plugin.util.logDebug
import com.jetbrains.packagesearch.intellij.plugin.util.logTrace
import com.jetbrains.packagesearch.intellij.plugin.util.logWarn
import com.jetbrains.packagesearch.intellij.plugin.util.lookAndFeelFlow
import com.jetbrains.packagesearch.intellij.plugin.util.packageSearchProjectCachesService
import com.jetbrains.packagesearch.intellij.plugin.util.packageSearchProjectService
import com.jetbrains.packagesearch.intellij.plugin.util.packageVersionNormalizer
import com.jetbrains.packagesearch.intellij.plugin.util.parallelFilterNot
import com.jetbrains.packagesearch.intellij.plugin.util.parallelFlatMap
import com.jetbrains.packagesearch.intellij.plugin.util.parallelMap
import com.jetbrains.packagesearch.intellij.plugin.util.parallelMapNotNull
import com.jetbrains.packagesearch.intellij.plugin.util.timer
import com.jetbrains.packagesearch.intellij.plugin.util.uiStateSource
import com.jetbrains.packagesearch.intellij.plugin.util.whileLoading
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.async
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.combine
import kotlinx.coroutines.flow.combineTransform
import kotlinx.coroutines.flow.consumeAsFlow
import kotlinx.coroutines.flow.debounce
import kotlinx.coroutines.flow.distinctUntilChanged
import kotlinx.coroutines.flow.filterNot
import kotlinx.coroutines.flow.flowOn
import kotlinx.coroutines.flow.launchIn
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.mapLatest
import kotlinx.coroutines.flow.onEach
import kotlinx.coroutines.flow.shareIn
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import net.miginfocom.swing.MigLayout
import java.awt.BorderLayout
import java.awt.Dimension
import java.awt.event.ItemEvent
import javax.swing.BorderFactory
import javax.swing.Box
import javax.swing.BoxLayout
import javax.swing.JCheckBox
import javax.swing.JPanel
import javax.swing.JScrollPane
import javax.swing.JViewport
import javax.swing.event.DocumentEvent
import kotlin.time.Duration
import kotlin.time.measureTime
import kotlin.time.measureTimedValue
internal class PackagesListPanel(
private val project: Project,
private val headerOperationsCache: CoroutineLRUCache<PackagesToUpgrade.PackageUpgradeInfo, List<PackageSearchOperation<*>>> =
project.packageSearchProjectCachesService.headerOperationsCache,
private val searchCache: CoroutineLRUCache<SearchCommandModel, ApiPackagesResponse<ApiStandardPackage, ApiStandardPackage.ApiStandardVersion>> =
project.packageSearchProjectCachesService.searchCache,
private val searchPackageModelCache: CoroutineLRUCache<UiPackageModelCacheKey, UiPackageModel.SearchResult> =
project.packageSearchProjectCachesService.searchPackageModelCache,
operationFactory: PackageSearchOperationFactory,
operationExecutor: OperationExecutor,
viewModelFlow: Flow<ViewModel>,
private val dataProvider: ProjectDataProvider
) : PackageSearchPanelBase(PackageSearchBundle.message("packagesearch.ui.toolwindow.tab.packages.title")) {
private val searchFieldFocus = Channel<Unit>()
private val packagesTable = PackagesTable(project, operationExecutor, ::onSearchResultStateChanged)
private val onlyStableMutableStateFlow = MutableStateFlow(true)
val onlyStableStateFlow: StateFlow<Boolean> = onlyStableMutableStateFlow
val selectedPackageStateFlow: StateFlow<UiPackageModel<*>?> = packagesTable.selectedPackageStateFlow
private val onlyMultiplatformStateFlow = MutableStateFlow(false)
private val searchQueryStateFlow = MutableStateFlow("")
private val isSearchingStateFlow = MutableStateFlow(false)
private val isLoadingStateFlow = MutableStateFlow(false)
private val searchResultsUiStateOverridesState: MutableStateFlow<Map<PackageIdentifier, SearchResultUiState>> =
MutableStateFlow(emptyMap())
private val searchTextField = PackagesSmartSearchField(searchFieldFocus.consumeAsFlow(), project)
.apply {
goToTable = {
if (packagesTable.hasInstalledItems) {
packagesTable.selectedIndex = packagesTable.firstPackageIndex
IdeFocusManager.getInstance(project).requestFocus(packagesTable, false)
true
} else {
false
}
}
fieldClearedListener = {
PackageSearchEventsLogger.logSearchQueryClear()
}
}
private val packagesPanel = PackageSearchUI.borderPanel {
layout = BoxLayout(this, BoxLayout.Y_AXIS)
}
private val onlyStableCheckBox = PackageSearchUI.checkBox(PackageSearchBundle.message("packagesearch.ui.toolwindow.packages.filter.onlyStable"))
.apply {
isOpaque = false
border = emptyBorder(left = 6)
isSelected = true
}
private val onlyMultiplatformCheckBox =
PackageSearchUI.checkBox(PackageSearchBundle.message("packagesearch.ui.toolwindow.packages.filter.onlyMpp")) {
isOpaque = false
border = emptyBorder(left = 6)
isSelected = false
}
private val mainToolbar = ActionManager.getInstance()
.createActionToolbar("Packages.Manage", createActionGroup(), true)
.apply {
targetComponent = toolbar
component.background = PackageSearchUI.HeaderBackgroundColor
val paneBackground = JBUI.CurrentTheme.CustomFrameDecorations.paneBackground()
component.border = BorderFactory.createMatteBorder(0, 1.scaled(), 0, 0, paneBackground)
}
private fun createActionGroup() = DefaultActionGroup().apply {
add(ComponentActionWrapper { onlyStableCheckBox })
add(ComponentActionWrapper { onlyMultiplatformCheckBox })
}
private val searchPanel = PackageSearchUI.headerPanel {
PackageSearchUI.setHeightPreScaled(this, PackageSearchUI.MediumHeaderHeight.get())
border = BorderFactory.createEmptyBorder()
addToCenter(object : JPanel() {
init {
layout = MigLayout("ins 0, fill", "[left, fill, grow][right]", "center")
add(searchTextField)
add(mainToolbar.component)
}
override fun getBackground() = PackageSearchUI.UsualBackgroundColor
})
}
private val headerPanel = HeaderPanel {
logDebug("PackagesListPanel.headerPanel#onUpdateAllLinkClicked()") {
"The user has clicked the update all link. This will cause many operation(s) to be executed."
}
operationExecutor.executeOperations(it)
}
private val tableScrollPane = JBScrollPane(
packagesPanel.apply {
add(packagesTable)
add(Box.createVerticalGlue())
},
JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
JScrollPane.HORIZONTAL_SCROLLBAR_NEVER
).apply {
border = emptyBorder()
viewportBorder = emptyBorder()
viewport.scrollMode = JViewport.SIMPLE_SCROLL_MODE
verticalScrollBar.apply {
headerPanel.adjustForScrollbar(isVisible, isOpaque)
// Here we should make sure we set IGNORE_SCROLLBAR_IN_INSETS, but alas it doesn't work with JTables
// as of IJ 2020.3 (see JBViewport#updateBorder()). If it did, we could just set:
// UIUtil.putClientProperty(this, JBScrollPane.IGNORE_SCROLLBAR_IN_INSETS, false)
// Instead, we have to work around the issue, inferring if the scrollbar is "floating" by looking at
// its isOpaque property — since Swing maps the opacity of scrollbars to whether they're "floating"
// (e.g., on macOS, System Preferences > General > Show scroll bars: "When scrolling")
onOpacityChanged { newIsOpaque ->
headerPanel.adjustForScrollbar(isVisible, newIsOpaque)
}
onVisibilityChanged { newIsVisible ->
headerPanel.adjustForScrollbar(newIsVisible, isOpaque)
}
}
}
private val listPanel = JBPanelWithEmptyText().apply {
emptyText.text = PackageSearchBundle.message("packagesearch.ui.toolwindow.packages.empty.base")
layout = BorderLayout()
add(tableScrollPane, BorderLayout.CENTER)
background = PackageSearchUI.UsualBackgroundColor
border = BorderFactory.createMatteBorder(1.scaled(), 0, 0, 0, JBUI.CurrentTheme.CustomFrameDecorations.separatorForeground())
}
internal data class SearchCommandModel(
val onlyStable: Boolean,
val onlyMultiplatform: Boolean,
val searchQuery: String,
)
internal data class SearchResultsModel(
val onlyStable: Boolean,
val onlyMultiplatform: Boolean,
val searchQuery: String,
val apiSearchResults: ApiPackagesResponse<ApiStandardPackage, ApiStandardPackage.ApiStandardVersion>?
)
private data class ViewModels(
val targetModules: TargetModules,
val headerData: PackagesHeaderData,
val viewModel: PackagesTable.ViewModel
)
init {
registerForUiEvents()
val searchResultsFlow =
combine(onlyStableStateFlow, onlyMultiplatformStateFlow, searchQueryStateFlow) { onlyStable, onlyMultiplatform, searchQuery ->
SearchCommandModel(onlyStable, onlyMultiplatform, searchQuery)
}
.debounce(150)
.mapLatest { searchCommand ->
val (result, time) = isSearchingStateFlow.whileLoading {
val results = searchCache.getOrTryPutDefault(searchCommand) {
dataProvider.doSearch(
searchCommand.searchQuery,
FilterOptions(searchCommand.onlyStable, searchCommand.onlyMultiplatform)
)
}
SearchResultsModel(
searchCommand.onlyStable,
searchCommand.onlyMultiplatform,
searchCommand.searchQuery,
results
)
}
logTrace("PackagesListPanel main flow") { "Search took $time" }
result
}
.shareIn(project.lifecycleScope, SharingStarted.Eagerly, 1)
combine(
viewModelFlow,
searchResultsFlow,
searchResultsUiStateOverridesState
) { viewModel, searchResults, overrides ->
Triple(viewModel, searchResults, overrides)
}.mapLatest { (viewModel, searchResults, searchResultsUiStateOverrides) ->
val (targetModules, installedPackages, packagesUpdateCandidates,
knownRepositoriesInTargetModules) = viewModel
val (onlyStable, onlyMultiplatform, searchQuery, apiSearchResults) = searchResults
isLoadingStateFlow.emit(true)
val (result, time) = measureTimedValue {
val (result, time) = measureTimedValue {
val packagesToUpgrade = packagesUpdateCandidates.getPackagesToUpgrade(onlyStable)
val filteredPackageUpgrades = when (targetModules) {
is TargetModules.All -> packagesToUpgrade.allUpdates
is TargetModules.One -> packagesToUpgrade.getUpdatesForModule(targetModules.module)
TargetModules.None -> emptyList()
}
val filteredInstalledPackages = installedPackages.filterByTargetModules(targetModules)
filteredPackageUpgrades to filteredInstalledPackages
}
logTrace("PackagesListPanel main flow") { "Initial computation took $time" }
val (filteredPackageUpgrades, filteredInstalledPackages) = result
fun onComplete(computationName: String): (Duration) -> Unit =
{ time -> logTrace("PackagesListPanel main flow") { "Took $time for \"$computationName\"" } }
val filteredInstalledPackagesUiModels = computeFilteredInstalledPackagesUiModels(
packages = filteredInstalledPackages,
onlyMultiplatform = onlyMultiplatform,
targetModules = targetModules,
knownRepositoriesInTargetModules = knownRepositoriesInTargetModules,
onlyStable = onlyStable,
searchQuery = searchQuery,
project = project,
onComplete = onComplete("filteredInstalledPackagesUiModelsTime"),
)
val searchResultModels = computeSearchResultModels(
searchResults = apiSearchResults,
installedPackages = filteredInstalledPackagesUiModels,
onlyStable = onlyStable,
targetModules = targetModules,
searchResultsUiStateOverrides = searchResultsUiStateOverrides,
knownRepositoriesInTargetModules = knownRepositoriesInTargetModules,
project = project,
cache = searchPackageModelCache,
onComplete = onComplete("searchResultModels")
)
val tableItems = computePackagesTableItems(
packages = filteredInstalledPackagesUiModels + searchResultModels,
targetModules = targetModules,
onComplete = onComplete("tableItemsTime")
)
val headerData = project.lifecycleScope.computeHeaderData(
project = project,
totalItemsCount = tableItems.size,
packageUpdateInfos = filteredPackageUpgrades,
hasSearchResults = apiSearchResults?.packages?.isNotEmpty() ?: false,
targetModules = targetModules,
knownRepositoriesInTargetModules = knownRepositoriesInTargetModules,
operationFactory = operationFactory,
cache = headerOperationsCache,
onComplete = onComplete("headerDataTime")
)
ViewModels(
targetModules = targetModules,
headerData = headerData,
viewModel = PackagesTable.ViewModel(
items = tableItems,
onlyStable = onlyStable,
targetModules = targetModules,
knownRepositoriesInTargetModules = knownRepositoriesInTargetModules
)
)
}
logTrace("PackagesListPanel main flow") { "Total elaboration took $time" }
result
}
.flowOn(Dispatchers.Default)
.onEach { (targetModules, headerData, packagesTableViewModel) ->
val renderingTime = measureTime {
updateListEmptyState(targetModules)
headerPanel.display(headerData)
packagesTable.display(packagesTableViewModel)
tableScrollPane.isVisible = packagesTableViewModel.items.isNotEmpty()
listPanel.updateAndRepaint()
packagesTable.updateAndRepaint()
packagesPanel.updateAndRepaint()
}
logTrace("PackagesListPanel main flow") {
"Rendering took $renderingTime for ${packagesTableViewModel.items.size} items"
}
isLoadingStateFlow.emit(false)
}
.flowOn(Dispatchers.EDT)
.catch { logWarn("Error in PackagesListPanel main flow", it) }
.launchIn(project.lifecycleScope)
combineTransform(
isLoadingStateFlow,
isSearchingStateFlow,
project.packageSearchProjectService.isLoadingFlow
) { booleans -> emit(booleans.any { it }) }
.debounce(150)
.onEach { headerPanel.showBusyIndicator(it) }
.flowOn(Dispatchers.EDT)
.launchIn(project.lifecycleScope)
project.lookAndFeelFlow.onEach { updateUiOnLafChange() }
.launchIn(project.lifecycleScope)
// results may have changed server side. Better clear caches...
timer(Duration.minutes(10))
.onEach {
searchPackageModelCache.clear()
searchCache.clear()
headerOperationsCache.clear()
}
.launchIn(project.lifecycleScope)
searchResultsFlow.map { it.searchQuery }
.debounce(500)
.distinctUntilChanged()
.filterNot { it.isBlank() }
.onEach { PackageSearchEventsLogger.logSearchRequest(it) }
.launchIn(project.lifecycleScope)
}
private fun updateListEmptyState(targetModules: TargetModules) {
when {
isSearching() -> {
listPanel.emptyText.text = PackageSearchBundle.message("packagesearch.ui.toolwindow.packages.empty.searching")
}
targetModules is TargetModules.None -> {
listPanel.emptyText.text = PackageSearchBundle.message("packagesearch.ui.toolwindow.packages.empty.noModule")
}
else -> {
val targetModuleNames = when (targetModules) {
is TargetModules.All -> PackageSearchBundle.message("packagesearch.ui.toolwindow.packages.empty.allModules")
is TargetModules.One -> targetModules.module.projectModule.name
is TargetModules.None -> error("No module selected empty state should be handled separately")
}
listPanel.emptyText.text =
PackageSearchBundle.message("packagesearch.ui.toolwindow.packages.empty.packagesOnly", targetModuleNames)
}
}
}
private fun isSearching() = !searchTextField.text.isNullOrBlank()
internal data class ViewModel(
val targetModules: TargetModules,
val installedPackages: List<PackageModel.Installed>,
val packagesUpdateCandidates: PackageUpgradeCandidates,
val knownRepositoriesInTargetModules: KnownRepositories.InTargetModules
)
private fun registerForUiEvents() {
packagesTable.transferFocusUp = {
IdeFocusManager.getInstance(project).requestFocus(searchTextField, false)
}
searchTextField.addOnTextChangedListener { text ->
searchQueryStateFlow.tryEmit(text)
}
onlyStableCheckBox.addSelectionChangedListener { selected ->
onlyStableMutableStateFlow.tryEmit(selected)
PackageSearchEventsLogger.logToggle(FUSGroupIds.ToggleTypes.OnlyStable, selected)
}
onlyMultiplatformCheckBox.addSelectionChangedListener { selected ->
onlyMultiplatformStateFlow.tryEmit(selected)
PackageSearchEventsLogger.logToggle(FUSGroupIds.ToggleTypes.OnlyKotlinMp, selected)
}
project.uiStateSource.searchQueryFlow.onEach { searchTextField.text = it }
.flowOn(Dispatchers.EDT)
.launchIn(project.lifecycleScope)
}
private suspend fun updateUiOnLafChange() = withContext(Dispatchers.EDT) {
@Suppress("MagicNumber") // Dimension constants
with(searchTextField) {
textEditor.putClientProperty("JTextField.Search.Gap", 6.scaled())
textEditor.putClientProperty("JTextField.Search.GapEmptyText", (-1).scaled())
textEditor.border = emptyBorder(left = 6)
textEditor.isOpaque = true
textEditor.background = PackageSearchUI.HeaderBackgroundColor
}
}
override fun build() = PackageSearchUI.boxPanel {
add(searchPanel)
add(headerPanel)
add(listPanel)
@Suppress("MagicNumber") // Dimension constants
minimumSize = Dimension(200.scaled(), minimumSize.height)
}
private fun onSearchResultStateChanged(
searchResult: PackageModel.SearchResult,
overrideVersion: NormalizedPackageVersion<*>?,
overrideScope: PackageScope?
) {
project.lifecycleScope.launch {
val uiStates = searchResultsUiStateOverridesState.value.toMutableMap()
uiStates[searchResult.identifier] = SearchResultUiState(overrideVersion, overrideScope)
searchResultsUiStateOverridesState.emit(uiStates)
}
}
}
@Suppress("FunctionName")
private fun SearchTextFieldTextChangedListener(action: (DocumentEvent) -> Unit) =
object : DocumentAdapter() {
override fun textChanged(e: DocumentEvent) = action(e)
}
private fun SearchTextField.addOnTextChangedListener(action: (String) -> Unit) =
SearchTextFieldTextChangedListener { action(text) }.also { addDocumentListener(it) }
internal fun JCheckBox.addSelectionChangedListener(action: (Boolean) -> Unit) =
addItemListener { e -> action(e.stateChange == ItemEvent.SELECTED) }
private fun CoroutineScope.computeHeaderData(
project: Project,
totalItemsCount: Int,
packageUpdateInfos: List<PackagesToUpgrade.PackageUpgradeInfo>,
hasSearchResults: Boolean,
targetModules: TargetModules,
knownRepositoriesInTargetModules: KnownRepositories.InTargetModules,
operationFactory: PackageSearchOperationFactory,
cache: CoroutineLRUCache<PackagesToUpgrade.PackageUpgradeInfo, List<PackageSearchOperation<*>>>,
onComplete: (Duration) -> Unit = {}
): PackagesHeaderData {
val (result, time) = measureTimedValue {
val moduleNames = if (targetModules is TargetModules.One) {
targetModules.module.projectModule.name
} else {
PackageSearchBundle.message("packagesearch.ui.toolwindow.allModules").lowercase()
}
val title = if (hasSearchResults) {
PackageSearchBundle.message("packagesearch.ui.toolwindow.tab.packages.searchResults")
} else {
PackageSearchBundle.message("packagesearch.ui.toolwindow.tab.packages.installedPackages.addedIn", moduleNames)
}
val operations = async {
packageUpdateInfos.parallelFlatMap { packageUpdateInfo ->
cache.getOrPut(packageUpdateInfo) {
val repoToInstall = knownRepositoriesInTargetModules.repositoryToAddWhenInstallingOrUpgrading(
project = project,
packageModel = packageUpdateInfo.packageModel,
selectedVersion = packageUpdateInfo.targetVersion.originalVersion
)
operationFactory.createChangePackageVersionOperations(
packageModel = packageUpdateInfo.packageModel,
newVersion = packageUpdateInfo.targetVersion.originalVersion,
targetModules = targetModules,
repoToInstall = repoToInstall
)
}
}
}
PackagesHeaderData(
labelText = title,
count = totalItemsCount.coerceAtLeast(0),
availableUpdatesCount = packageUpdateInfos.distinctBy { it.packageModel.identifier }.size,
updateOperations = operations
)
}
onComplete(time)
return result
}
private fun List<PackageModel.Installed>.filterByTargetModules(
targetModules: TargetModules
) = when (targetModules) {
is TargetModules.All -> this
is TargetModules.One -> mapNotNull { installedPackage ->
val filteredUsages = installedPackage.usageInfo.filter {
it.projectModule == targetModules.module.projectModule
}
if (filteredUsages.isEmpty()) return@mapNotNull null
installedPackage.copyWithUsages(filteredUsages)
}
TargetModules.None -> emptyList()
}
private suspend fun computeSearchResultModels(
searchResults: ApiPackagesResponse<ApiStandardPackage, ApiStandardPackage.ApiStandardVersion>?,
installedPackages: List<UiPackageModel.Installed>,
onlyStable: Boolean,
targetModules: TargetModules,
searchResultsUiStateOverrides: Map<PackageIdentifier, SearchResultUiState>,
knownRepositoriesInTargetModules: KnownRepositories.InTargetModules,
project: Project,
onComplete: (Duration) -> Unit = {},
cache: CoroutineLRUCache<UiPackageModelCacheKey, UiPackageModel.SearchResult>
): List<UiPackageModel.SearchResult> {
val (result, time) = measureTimedValue {
if (searchResults == null || searchResults.packages.isEmpty()) return@measureTimedValue emptyList()
val installedDependencies = installedPackages
.map { InstalledDependency(it.packageModel.groupId, it.packageModel.artifactId) }
val index = searchResults.packages.parallelMap { "${it.groupId}:${it.artifactId}" }
searchResults.packages
.parallelFilterNot { installedDependencies.any { installed -> installed.matchesCoordinates(it) } }
.parallelMapNotNull { PackageModel.fromSearchResult(it, packageVersionNormalizer) }
.parallelMap {
val uiState = searchResultsUiStateOverrides[it.identifier]
cache.getOrPut(UiPackageModelCacheKey(targetModules, uiState, onlyStable, it)) {
it.toUiPackageModel(targetModules, project, uiState, knownRepositoriesInTargetModules, onlyStable)
}
}
.sortedBy { index.indexOf(it.identifier.rawValue) }
}
onComplete(time)
return result
}
private suspend fun computeFilteredInstalledPackagesUiModels(
packages: List<PackageModel.Installed>,
onlyMultiplatform: Boolean,
targetModules: TargetModules,
knownRepositoriesInTargetModules: KnownRepositories.InTargetModules,
onlyStable: Boolean,
searchQuery: String,
project: Project,
onComplete: (Duration) -> Unit = {}
): List<UiPackageModel.Installed> {
val (result, time) = measureTimedValue {
packages.let { list -> if (onlyMultiplatform) list.filter { it.isKotlinMultiplatform } else list }
.parallelMap { it.toUiPackageModel(targetModules, project, knownRepositoriesInTargetModules, onlyStable) }
.filter { it.sortedVersions.isNotEmpty() && it.packageModel.searchableInfo.contains(searchQuery) }
}
onComplete(time)
return result
}
internal data class UiPackageModelCacheKey(
val targetModules: TargetModules,
val uiState: SearchResultUiState?,
val onlyStable: Boolean,
val searchResult: PackageModel.SearchResult
)
| apache-2.0 | b0e001f820cf7b32c3f93ae99977dc67 | 45.882535 | 148 | 0.693238 | 5.875073 | false | false | false | false |
jwren/intellij-community | platform/workspaceModel/storage/tests/testSrc/com/intellij/workspaceModel/storage/ReferencesInStorageTest.kt | 1 | 27698 | // Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.workspaceModel.storage
import com.intellij.testFramework.UsefulTestCase
import com.intellij.testFramework.UsefulTestCase.assertEmpty
import com.intellij.testFramework.UsefulTestCase.assertInstanceOf
import com.intellij.workspaceModel.storage.impl.ChangeEntry
import com.intellij.workspaceModel.storage.impl.EntityStorageSerializerImpl
import com.intellij.workspaceModel.storage.impl.WorkspaceEntityStorageBuilderImpl
import com.intellij.workspaceModel.storage.impl.assertConsistency
import com.intellij.workspaceModel.storage.impl.url.VirtualFileUrlManagerImpl
import com.intellij.workspaceModel.storage.url.VirtualFileUrlManager
import org.junit.Assert.*
import org.junit.Before
import org.junit.Ignore
import org.junit.Test
import java.io.ByteArrayInputStream
import java.io.ByteArrayOutputStream
private fun WorkspaceEntityStorage.singleParent() = entities(ParentEntity::class.java).single()
private fun WorkspaceEntityStorage.singleChild() = entities(ChildEntity::class.java).single()
class ReferencesInStorageTest {
private lateinit var virtualFileManager: VirtualFileUrlManager
@Before
fun setUp() {
virtualFileManager = VirtualFileUrlManagerImpl()
}
@Test
fun `add entity`() {
val builder = createEmptyBuilder()
val child = builder.addChildEntity(builder.addParentEntity("foo"))
builder.assertConsistency()
assertEquals("foo", child.parent.parentProperty)
assertEquals(child, builder.singleChild())
assertEquals(child.parent, builder.singleParent())
assertEquals(child, child.parent.children.single())
}
@Test
fun `add entity via diff`() {
val builder = createEmptyBuilder()
val parentEntity = builder.addParentEntity("foo")
val diff = createBuilderFrom(builder.toStorage())
diff.addChildEntity(parentEntity = parentEntity)
builder.addDiff(diff)
builder.assertConsistency()
val child = builder.singleChild()
assertEquals("foo", child.parent.parentProperty)
assertEquals(child, builder.singleChild())
assertEquals(child.parent, builder.singleParent())
assertEquals(child, child.parent.children.single())
}
@Test
fun `add remove reference inside data class`() {
val builder = createEmptyBuilder()
val parent1 = builder.addParentEntity("parent1")
val parent2 = builder.addParentEntity("parent2")
builder.assertConsistency()
val child = builder.addChildEntity(parent1, "child", DataClass("data", builder.createReference(parent2)))
builder.assertConsistency()
assertEquals(child, parent1.children.single())
assertEquals(emptyList<ChildEntity>(), parent2.children.toList())
assertEquals("parent1", child.parent.parentProperty)
assertEquals("parent2", child.dataClass!!.parent.resolve(builder)?.parentProperty)
assertEquals(setOf(parent1, parent2), builder.entities(ParentEntity::class.java).toSet())
builder.modifyEntity(ModifiableChildEntity::class.java, child) {
dataClass = null
}
builder.assertConsistency()
assertEquals(setOf(parent1, parent2), builder.entities(ParentEntity::class.java).toSet())
}
@Test
fun `remove child entity`() {
val builder = createEmptyBuilder()
val parent = builder.addParentEntity()
builder.assertConsistency()
val child = builder.addChildEntity(parent)
builder.assertConsistency()
builder.removeEntity(child)
builder.assertConsistency()
assertEquals(emptyList<ChildEntity>(), builder.entities(ChildEntity::class.java).toList())
assertEquals(emptyList<ChildEntity>(), parent.children.toList())
assertEquals(parent, builder.singleParent())
}
@Test
fun `remove parent entity`() {
val builder = createEmptyBuilder()
val child = builder.addChildEntity(builder.addParentEntity())
builder.removeEntity(child.parent)
builder.assertConsistency()
assertEquals(emptyList<ChildEntity>(), builder.entities(ChildEntity::class.java).toList())
assertEquals(emptyList<ParentEntity>(), builder.entities(ParentEntity::class.java).toList())
}
@Test
fun `remove parent entity via diff`() {
val builder = createEmptyBuilder()
val oldParent = builder.addParentEntity("oldParent")
val oldChild = builder.addChildEntity(oldParent, "oldChild")
val diff = createEmptyBuilder()
val parent = diff.addParentEntity("newParent")
diff.addChildEntity(parent, "newChild")
diff.removeEntity(parent)
diff.assertConsistency()
builder.addDiff(diff)
builder.assertConsistency()
assertEquals(listOf(oldChild), builder.entities(ChildEntity::class.java).toList())
assertEquals(listOf(oldParent), builder.entities(ParentEntity::class.java).toList())
}
@Test
fun `remove parent entity with two children`() {
val builder = createEmptyBuilder()
val child1 = builder.addChildEntity(builder.addParentEntity())
builder.addChildEntity(parentEntity = child1.parent)
builder.removeEntity(child1.parent)
builder.assertConsistency()
assertEquals(emptyList<ChildEntity>(), builder.entities(ChildEntity::class.java).toList())
assertEquals(emptyList<ParentEntity>(), builder.entities(ParentEntity::class.java).toList())
}
@Test
fun `remove parent entity in DAG`() {
val builder = createEmptyBuilder()
val parent = builder.addParentEntity()
val child = builder.addChildEntity(parentEntity = parent)
builder.addChildChildEntity(parent, child)
builder.removeEntity(parent)
builder.assertConsistency()
assertEquals(emptyList<ChildEntity>(), builder.entities(ChildEntity::class.java).toList())
assertEquals(emptyList<ParentEntity>(), builder.entities(ParentEntity::class.java).toList())
}
// UNSUPPORTED
/*
@Test
fun `remove parent entity referenced via data class`() {
val builder = PEntityStorageBuilder.create()
val parent1 = builder.addPParentEntity("parent1")
val parent2 = builder.addPParentEntity("parent2")
builder.addPChildEntity(parent1, "child", PDataClass("data", builder.createReference(parent2)))
builder.removeEntity(parent2)
builder.assertConsistency()
assertEquals(emptyList<PChildEntity>(), builder.entities(PChildEntity::class.java).toList())
assertEquals(listOf(parent1), builder.entities(PParentEntity::class.java).toList())
assertEquals(emptyList<PChildEntity>(), parent1.children.toList())
}
*/
@Test
fun `remove parent entity referenced via two paths`() {
val builder = createEmptyBuilder()
val parent = builder.addParentEntity()
builder.addChildEntity(parent, "child", DataClass("data", builder.createReference(parent)))
builder.assertConsistency()
builder.removeEntity(parent)
builder.assertConsistency()
assertEquals(emptyList<ChildEntity>(), builder.entities(ChildEntity::class.java).toList())
assertEquals(emptyList<ParentEntity>(), builder.entities(ParentEntity::class.java).toList())
}
@Test
fun `remove parent entity referenced via two paths via entity ref`() {
val builder = createEmptyBuilder()
val parent = builder.addParentEntity()
builder.addChildEntity(parent, "child", DataClass("data", parent.createReference()))
builder.assertConsistency()
builder.removeEntity(parent)
builder.assertConsistency()
assertEquals(emptyList<ChildEntity>(), builder.entities(ChildEntity::class.java).toList())
assertEquals(emptyList<ParentEntity>(), builder.entities(ParentEntity::class.java).toList())
}
@Test
fun `modify parent property`() {
val builder = createEmptyBuilder()
val child = builder.addChildEntity(builder.addParentEntity())
val oldParent = child.parent
val newParent = builder.modifyEntity(ModifiableParentEntity::class.java, child.parent) {
parentProperty = "changed"
}
builder.assertConsistency()
assertEquals("changed", newParent.parentProperty)
assertEquals(newParent, builder.singleParent())
assertEquals(newParent, child.parent)
assertEquals(child, newParent.children.single())
assertEquals("parent", oldParent.parentProperty)
}
@Test
fun `modify parent property via diff`() {
val builder = createEmptyBuilder()
val child = builder.addChildEntity(builder.addParentEntity())
val oldParent = child.parent
val diff = createBuilderFrom(builder)
diff.modifyEntity(ModifiableParentEntity::class.java, child.parent) {
parentProperty = "changed"
}
builder.addDiff(diff)
builder.assertConsistency()
val newParent = builder.singleParent()
assertEquals("changed", newParent.parentProperty)
assertEquals(newParent, builder.singleParent())
assertEquals(newParent, child.parent)
assertEquals(child, newParent.children.single())
assertEquals("parent", oldParent.parentProperty)
}
@Test
fun `modify child property`() {
val builder = createEmptyBuilder()
val child = builder.addChildEntity(builder.addParentEntity())
val oldParent = child.parent
val newChild = builder.modifyEntity(ModifiableChildEntity::class.java, child) {
childProperty = "changed"
}
builder.assertConsistency()
assertEquals("changed", newChild.childProperty)
assertEquals(oldParent, builder.singleParent())
assertEquals(newChild, builder.singleChild())
assertEquals(oldParent, newChild.parent)
assertEquals(oldParent, child.parent)
assertEquals(newChild, oldParent.children.single())
assertEquals("child", child.childProperty)
}
@Test
fun `modify reference to parent`() {
val builder = createEmptyBuilder()
val child = builder.addChildEntity(builder.addParentEntity())
val oldParent = child.parent
val newParent = builder.addParentEntity("new")
val newChild = builder.modifyEntity(ModifiableChildEntity::class.java, child) {
parent = newParent
}
builder.assertConsistency()
assertEquals("child", newChild.childProperty)
assertEquals(setOf(oldParent, newParent), builder.entities(ParentEntity::class.java).toSet())
assertEquals(newChild, builder.singleChild())
assertEquals(newParent, newChild.parent)
assertEquals(newChild, newParent.children.single())
assertEquals(newParent, child.parent)
//assertEquals(oldParent, child.parent) // ProxyBasedStore behaviour
assertEquals(emptyList<ChildEntity>(), oldParent.children.toList())
}
@Test
fun `modify reference to parent via data class`() {
val builder = createEmptyBuilder()
val parent1 = builder.addParentEntity("parent1")
val oldParent = builder.addParentEntity("parent2")
val child = builder.addChildEntity(parent1, "child", DataClass("data", builder.createReference(oldParent)))
val newParent = builder.addParentEntity("new")
builder.assertConsistency()
val newChild = builder.modifyEntity(ModifiableChildEntity::class.java, child) {
dataClass = DataClass("data2", builder.createReference(newParent))
}
builder.assertConsistency()
assertEquals("child", newChild.childProperty)
assertEquals("data2", newChild.dataClass!!.stringProperty)
assertEquals(setOf(oldParent, newParent, parent1), builder.entities(ParentEntity::class.java).toSet())
assertEquals(newChild, builder.singleChild())
assertEquals(newParent, newChild.dataClass.parent.resolve(builder))
assertEquals(oldParent, child.dataClass!!.parent.resolve(builder))
}
@Test
fun `modify reference to parent via data class via entity ref`() {
val builder = createEmptyBuilder()
val parent1 = builder.addParentEntity("parent1")
val oldParent = builder.addParentEntity("parent2")
val child = builder.addChildEntity(parent1, "child", DataClass("data", oldParent.createReference()))
val newParent = builder.addParentEntity("new")
builder.assertConsistency()
val newChild = builder.modifyEntity(ModifiableChildEntity::class.java, child) {
dataClass = DataClass("data2", newParent.createReference())
}
builder.assertConsistency()
assertEquals("child", newChild.childProperty)
assertEquals("data2", newChild.dataClass!!.stringProperty)
assertEquals(setOf(oldParent, newParent, parent1), builder.entities(ParentEntity::class.java).toSet())
assertEquals(newChild, builder.singleChild())
assertEquals(newParent, newChild.dataClass.parent.resolve(builder))
assertEquals(oldParent, child.dataClass!!.parent.resolve(builder))
}
@Test
fun `builder from storage`() {
val storage = createEmptyBuilder().apply {
addChildEntity(addParentEntity())
}.toStorage()
storage.assertConsistency()
assertEquals("parent", storage.singleParent().parentProperty)
val builder = createBuilderFrom(storage)
builder.assertConsistency()
val oldParent = builder.singleParent()
assertEquals("parent", oldParent.parentProperty)
val newParent = builder.modifyEntity(ModifiableParentEntity::class.java, oldParent) {
parentProperty = "changed"
}
builder.assertConsistency()
assertEquals("changed", builder.singleParent().parentProperty)
assertEquals("parent", storage.singleParent().parentProperty)
assertEquals(newParent, builder.singleChild().parent)
assertEquals("changed", builder.singleChild().parent.parentProperty)
assertEquals("parent", storage.singleChild().parent.parentProperty)
val parent2 = builder.addParentEntity("parent2")
builder.modifyEntity(ModifiableChildEntity::class.java, builder.singleChild()) {
dataClass = DataClass("data", builder.createReference(parent2))
}
builder.assertConsistency()
assertEquals("parent", storage.singleParent().parentProperty)
assertEquals(null, storage.singleChild().dataClass)
assertEquals("data", builder.singleChild().dataClass!!.stringProperty)
assertEquals(parent2, builder.singleChild().dataClass!!.parent.resolve(builder))
assertEquals(setOf(parent2, newParent), builder.entities(ParentEntity::class.java).toSet())
}
@Test
fun `storage from builder`() {
val builder = createEmptyBuilder()
val child = builder.addChildEntity(builder.addParentEntity())
val snapshot = builder.toStorage()
builder.assertConsistency()
builder.modifyEntity(ModifiableParentEntity::class.java, child.parent) {
parentProperty = "changed"
}
builder.assertConsistency()
assertEquals("changed", builder.singleParent().parentProperty)
assertEquals("changed", builder.singleChild().parent.parentProperty)
assertEquals("parent", snapshot.singleParent().parentProperty)
assertEquals("parent", snapshot.singleChild().parent.parentProperty)
val parent2 = builder.addParentEntity("new")
builder.modifyEntity(ModifiableChildEntity::class.java, child) {
dataClass = DataClass("data", builder.createReference(parent2))
}
builder.assertConsistency()
assertEquals("parent", snapshot.singleParent().parentProperty)
assertEquals(null, snapshot.singleChild().dataClass)
assertEquals(parent2, builder.singleChild().dataClass!!.parent.resolve(builder))
}
@Test
fun `modify optional parent property`() {
val builder = createEmptyBuilder()
val child = builder.addChildWithOptionalParentEntity(null)
assertNull(child.optionalParent)
val newParent = builder.addParentEntity()
assertEquals(emptyList<ChildWithOptionalParentEntity>(), newParent.optionalChildren.toList())
val newChild = builder.modifyEntity(ModifiableChildWithOptionalParentEntity::class.java, child) {
optionalParent = newParent
}
builder.assertConsistency()
assertEquals(newParent, newChild.optionalParent)
assertEquals(newChild, newParent.optionalChildren.single())
val veryNewChild = builder.modifyEntity(ModifiableChildWithOptionalParentEntity::class.java, newChild) {
optionalParent = null
}
assertNull(veryNewChild.optionalParent)
assertEquals(emptyList<ChildWithOptionalParentEntity>(), newParent.optionalChildren.toList())
}
@Test
fun `removing one to one parent`() {
val builder = createEmptyBuilder()
val parentEntity = builder.addOoParentEntity()
builder.addOoChildEntity(parentEntity)
builder.removeEntity(parentEntity)
val parents = builder.entities(OoParentEntity::class.java).toList()
val children = builder.entities(OoChildEntity::class.java).toList()
assertEmpty(parents)
assertEmpty(children)
}
@Test
fun `add one to one entities`() {
val builder = createEmptyBuilder()
val parentEntity = builder.addOoParentEntity()
builder.addOoParentEntity()
builder.addOoChildEntity(parentEntity)
builder.assertConsistency()
}
@Test
fun `test replace by source one to one nullable ref with parent persistent Id and child without it`() {
val builder = createEmptyBuilder()
var parentEntity = builder.addOoParentWithPidEntity("parent")
builder.addOoChildForParentWithPidEntity(parentEntity, "child")
builder.checkConsistency()
val newBuilder = createEmptyBuilder()
parentEntity = newBuilder.addOoParentWithPidEntity("parent", AnotherSource)
newBuilder.addOoChildForParentWithPidEntity(parentEntity, "child", source = AnotherSource)
newBuilder.checkConsistency()
builder.replaceBySource({ it is AnotherSource }, newBuilder)
builder.checkConsistency()
val parent = builder.entities(OoParentWithPidEntity::class.java).single()
val child = builder.entities(OoChildForParentWithPidEntity::class.java).single()
assertEquals(AnotherSource, parent.entitySource)
assertEquals(AnotherSource, child.entitySource)
assertEquals(child, parent.childOne)
}
@Test
@Ignore("Skip because of unstable rbs")
fun `test replace by source one to one ref with parent persistent Id and child with persistent Id`() {
val builder = createEmptyBuilder()
var parentEntity = builder.addOoParentWithPidEntity("parent")
builder.addOoChildForParentWithPidEntity(parentEntity, "childOne")
builder.addOoChildAlsoWithPidEntity(parentEntity, "childTwo")
builder.checkConsistency()
val newBuilder = createEmptyBuilder()
parentEntity = newBuilder.addOoParentWithPidEntity("parent", AnotherSource)
newBuilder.addOoChildForParentWithPidEntity(parentEntity, "childOneOne", source = AnotherSource)
newBuilder.addOoChildAlsoWithPidEntity(parentEntity, "childTwo", source = AnotherSource)
newBuilder.checkConsistency()
builder.replaceBySource({ it is AnotherSource }, newBuilder)
builder.checkConsistency()
val parent = builder.entities(OoParentWithPidEntity::class.java).single()
val firstChild = builder.entities(OoChildForParentWithPidEntity::class.java).single()
val secondChild = builder.entities(OoChildAlsoWithPidEntity::class.java).single()
assertEquals(AnotherSource, parent.entitySource)
assertEquals(AnotherSource, firstChild.entitySource)
assertEquals(AnotherSource, secondChild.entitySource)
assertEquals("childOneOne", firstChild.childProperty)
assertEquals(parent, firstChild.parent)
assertEquals("childTwo", secondChild.childProperty)
assertEquals(parent, secondChild.parent)
}
@Test
fun `test replace by source with parent persistent Id and without children`() {
val builder = createEmptyBuilder()
val parentEntity = builder.addOoParentWithPidEntity("parent")
builder.addOoChildForParentWithPidEntity(parentEntity, "child")
builder.checkConsistency()
val newBuilder = createEmptyBuilder()
newBuilder.addOoParentWithPidEntity("parent", AnotherSource)
newBuilder.checkConsistency()
builder.replaceBySource({ it is AnotherSource }, newBuilder)
builder.checkConsistency()
val parent = builder.entities(OoParentWithPidEntity::class.java).single()
val child = builder.entities(OoChildForParentWithPidEntity::class.java).single()
assertEquals(AnotherSource, parent.entitySource)
assertEquals(MySource, child.entitySource)
assertEquals(child, parent.childOne)
}
@Test
fun `test replace by source one to one ref with parent persistent Id and child without it and parent entity source intersection`() {
val builder = createEmptyBuilder()
var parentEntity = builder.addOoParentWithPidEntity("parent", AnotherSource)
builder.addOoChildForParentWithPidEntity(parentEntity, "child")
builder.checkConsistency()
val newBuilder = createEmptyBuilder()
parentEntity = newBuilder.addOoParentWithPidEntity("parent", AnotherSource)
newBuilder.addOoChildForParentWithPidEntity(parentEntity, "child", source = AnotherSource)
newBuilder.checkConsistency()
builder.replaceBySource({ it is AnotherSource }, newBuilder)
builder.checkConsistency()
val parent = builder.entities(OoParentWithPidEntity::class.java).single()
val child = builder.entities(OoChildForParentWithPidEntity::class.java).single()
assertEquals(AnotherSource, parent.entitySource)
assertEquals(AnotherSource, child.entitySource)
assertEquals(child, parent.childOne)
}
@Test
fun `test replace by source one to one ref with parent persistent Id and child without it and child entity source intersection`() {
val builder = createEmptyBuilder()
var parentEntity = builder.addOoParentWithPidEntity("parent")
builder.addOoChildForParentWithPidEntity(parentEntity, "child", AnotherSource)
builder.checkConsistency()
val newBuilder = createEmptyBuilder()
parentEntity = newBuilder.addOoParentWithPidEntity("parent", AnotherSource)
newBuilder.addOoChildForParentWithPidEntity(parentEntity, "child", source = AnotherSource)
newBuilder.checkConsistency()
builder.replaceBySource({ it is AnotherSource }, newBuilder)
builder.checkConsistency()
val parent = builder.entities(OoParentWithPidEntity::class.java).single()
val child = builder.entities(OoChildForParentWithPidEntity::class.java).single()
assertEquals(AnotherSource, parent.entitySource)
assertEquals(AnotherSource, child.entitySource)
assertEquals(child, parent.childOne)
}
@Test
fun `test replace by source one to one nullable ref with child persistent Id and parent without it`() {
val builder = createEmptyBuilder()
var parentEntity = builder.addOoParentWithoutPidEntity("parent")
builder.addOoChildWithPidEntity(parentEntity, "child")
builder.checkConsistency()
val newBuilder = createEmptyBuilder()
parentEntity = newBuilder.addOoParentWithoutPidEntity("parent", AnotherSource)
newBuilder.addOoChildWithPidEntity(parentEntity, "child", source = AnotherSource)
newBuilder.checkConsistency()
builder.replaceBySource({ it is AnotherSource }, newBuilder)
builder.checkConsistency()
val listOfParent = builder.entities(OoParentWithoutPidEntity::class.java).toList()
val child = builder.entities(OoChildWithPidEntity::class.java).single()
assertEquals(2, listOfParent.size)
assertEquals(MySource, listOfParent[0].entitySource)
assertEquals(AnotherSource, listOfParent[1].entitySource)
assertEquals(AnotherSource, child.entitySource)
assertEquals("child", child.childProperty)
assertEquals(listOfParent[1], child.parent)
}
@Test
fun `add child to a single parent`() {
val builder = createEmptyBuilder()
val parentEntity = builder.addOoParentEntity()
builder.addOoChildEntity(parentEntity)
builder.addOoChildEntity(parentEntity)
builder.assertConsistency()
// Child has a not-null parent, so we remove it one field replace
val children = builder.entities(OoChildEntity::class.java).toList()
assertEquals(1, children.size)
}
@Test
fun `double child adding`() {
val builder = createEmptyBuilder()
val parentEntity = builder.addOoParentEntity()
builder.addOoChildWithNullableParentEntity(parentEntity)
builder.addOoChildWithNullableParentEntity(parentEntity)
builder.assertConsistency()
// Child has a nullable parent. So we just unlink a parent from one of the entities
val children = builder.entities(OoChildWithNullableParentEntity::class.java).toList()
assertEquals(2, children.size)
if (children[0].parent == null) {
assertNotNull(children[1].parent)
}
else {
assertNull(children[1].parent)
}
}
@Test
fun `remove children`() {
val builder = createEmptyBuilder()
val parentEntity = builder.addParentEntity()
val childEntity = builder.addChildEntity(parentEntity)
builder.changeLog.clear()
builder.modifyEntity(ModifiableParentEntity::class.java, parentEntity) {
this.children = emptyList<ChildEntity>().asSequence()
}
builder.assertConsistency()
assertTrue(builder.entities(ChildEntity::class.java).toList().isEmpty())
assertInstanceOf(builder.changeLog.changeLog[childEntity.id], ChangeEntry.RemoveEntity::class.java)
}
@Test
fun `remove multiple children`() {
val builder = createEmptyBuilder()
val parentEntity = builder.addParentEntity()
val childEntity1 = builder.addChildEntity(parentEntity)
val childEntity2 = builder.addChildEntity(parentEntity)
builder.changeLog.clear()
builder.modifyEntity(ModifiableParentEntity::class.java, parentEntity) {
this.children = sequenceOf(childEntity2)
}
builder.assertConsistency()
assertEquals(1, builder.entities(ChildEntity::class.java).toList().size)
assertInstanceOf(builder.changeLog.changeLog[childEntity1.id], ChangeEntry.RemoveEntity::class.java)
}
@Test
fun `check store consistency after deserialization`() {
val builder = createEmptyBuilder()
val parentEntity = builder.addParentEntity()
builder.addChildEntity(parentEntity)
builder.addChildEntity(parentEntity)
builder.assertConsistency()
builder.removeEntity(parentEntity.id)
builder.assertConsistency()
val stream = ByteArrayOutputStream()
val serializer = EntityStorageSerializerImpl(TestEntityTypesResolver(), VirtualFileUrlManagerImpl())
serializer.serializeCache(stream, builder.toStorage())
val byteArray = stream.toByteArray()
// Deserialization won't create collection which consists only from null elements
val deserializer = EntityStorageSerializerImpl(TestEntityTypesResolver(), VirtualFileUrlManagerImpl())
val deserialized = (deserializer.deserializeCache(ByteArrayInputStream(byteArray)) as? WorkspaceEntityStorageBuilderImpl)?.toStorage()
deserialized!!.assertConsistency()
}
@Test
fun `replace one to one connection with adding already existing child`() {
val builder = createEmptyBuilder()
val parentEntity = builder.addOoParentWithPidEntity()
builder.addOoChildForParentWithPidEntity(parentEntity)
val anotherBuilder = createBuilderFrom(builder)
anotherBuilder.addOoChildForParentWithPidEntity(parentEntity, childProperty = "MyProperty")
// Modify initial builder
builder.addOoChildForParentWithPidEntity(parentEntity)
builder.addDiff(anotherBuilder)
builder.assertConsistency()
assertEquals("MyProperty", builder.entities(OoParentWithPidEntity::class.java).single().childOne!!.childProperty)
}
@Test
fun `pull one to one connection into another builder`() {
val builder = createEmptyBuilder()
val anotherBuilder = createBuilderFrom(builder)
val parentEntity = anotherBuilder.addOoParentEntity()
anotherBuilder.addOoChildWithNullableParentEntity(parentEntity)
builder.addDiff(anotherBuilder)
builder.assertConsistency()
UsefulTestCase.assertNotEmpty(builder.entities(OoParentEntity::class.java).toList())
UsefulTestCase.assertNotEmpty(builder.entities(OoChildWithNullableParentEntity::class.java).toList())
}
}
| apache-2.0 | b2970458225f8accbfb3d3dfa01f0b70 | 39.912851 | 140 | 0.755325 | 5.233938 | false | true | false | false |
GunoH/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/intentions/ReplaceAddWithPlusAssignIntention.kt | 3 | 2691 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.intentions
import com.intellij.codeInsight.intention.FileModifier.SafeFieldForPreview
import com.intellij.openapi.editor.Editor
import org.jetbrains.kotlin.builtins.DefaultBuiltIns
import org.jetbrains.kotlin.descriptors.ClassDescriptor
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.caches.resolve.analyze
import org.jetbrains.kotlin.idea.codeinsight.api.classic.intentions.SelfTargetingOffsetIndependentIntention
import org.jetbrains.kotlin.psi.KtDotQualifiedExpression
import org.jetbrains.kotlin.psi.KtPsiFactory
import org.jetbrains.kotlin.psi.createExpressionByPattern
import org.jetbrains.kotlin.resolve.BindingContextUtils
import org.jetbrains.kotlin.resolve.calls.util.getResolvedCall
import org.jetbrains.kotlin.resolve.calls.util.getExplicitReceiverValue
import org.jetbrains.kotlin.resolve.descriptorUtil.isSubclassOf
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
class ReplaceAddWithPlusAssignIntention : SelfTargetingOffsetIndependentIntention<KtDotQualifiedExpression>(
KtDotQualifiedExpression::class.java,
KotlinBundle.lazyMessage("replace.with1")
) {
@SafeFieldForPreview
private val compatibleNames = setOf("add", "addAll")
override fun isApplicableTo(element: KtDotQualifiedExpression): Boolean {
if (element.callExpression?.valueArguments?.size != 1) return false
if (element.calleeName !in compatibleNames) return false
setTextGetter(KotlinBundle.lazyMessage("replace.0.with", element.calleeName.toString()))
val context = element.analyze(BodyResolveMode.PARTIAL)
BindingContextUtils.extractVariableDescriptorFromReference(context, element.receiverExpression)?.let {
if (it.isVar) return false
} ?: return false
val resolvedCall = element.getResolvedCall(context) ?: return false
val receiverType = resolvedCall.getExplicitReceiverValue()?.type ?: return false
val receiverClass = receiverType.constructor.declarationDescriptor as? ClassDescriptor ?: return false
return receiverClass.isSubclassOf(DefaultBuiltIns.Instance.mutableCollection)
}
override fun applyTo(element: KtDotQualifiedExpression, editor: Editor?) {
element.replace(
KtPsiFactory(element).createExpressionByPattern(
"$0 += $1", element.receiverExpression,
element.callExpression?.valueArguments?.get(0)?.getArgumentExpression() ?: return
)
)
}
} | apache-2.0 | 20510f636ee5fe06ac9a516b83e5ac39 | 49.792453 | 158 | 0.781865 | 5.235409 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/intentions/ConvertLazyPropertyToOrdinaryIntention.kt | 3 | 2064 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.intentions
import com.intellij.openapi.editor.Editor
import com.intellij.psi.PsiComment
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.codeinsight.api.classic.intentions.SelfTargetingIntention
import org.jetbrains.kotlin.idea.inspections.collections.isCalling
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.allChildren
class ConvertLazyPropertyToOrdinaryIntention : SelfTargetingIntention<KtProperty>(
KtProperty::class.java, KotlinBundle.lazyMessage("convert.to.ordinary.property")
) {
override fun isApplicableTo(element: KtProperty, caretOffset: Int): Boolean {
val delegateExpression = element.delegate?.expression as? KtCallExpression ?: return false
val lambdaBody = delegateExpression.functionLiteral()?.bodyExpression ?: return false
if (lambdaBody.statements.isEmpty()) return false
return delegateExpression.isCalling(FqName("kotlin.lazy"))
}
override fun applyTo(element: KtProperty, editor: Editor?) {
val delegate = element.delegate ?: return
val delegateExpression = delegate.expression as? KtCallExpression ?: return
val functionLiteral = delegateExpression.functionLiteral() ?: return
element.initializer = functionLiteral.singleStatement() ?: KtPsiFactory(element).createExpression("run ${functionLiteral.text}")
delegate.delete()
}
private fun KtCallExpression.functionLiteral(): KtFunctionLiteral? {
return lambdaArguments.singleOrNull()?.getLambdaExpression()?.functionLiteral
}
private fun KtFunctionLiteral.singleStatement(): KtExpression? {
val body = this.bodyExpression ?: return null
if (body.allChildren.any { it is PsiComment }) return null
return body.statements.singleOrNull()
}
}
| apache-2.0 | d6310192754b184b70e53438b0d67e1a | 49.341463 | 158 | 0.763081 | 5.108911 | false | false | false | false |
smmribeiro/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/findUsages/KotlinFindUsagesProvider.kt | 5 | 1798 | // 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.findUsages
import com.intellij.psi.PsiElement
import org.jetbrains.kotlin.descriptors.FunctionDescriptor
import org.jetbrains.kotlin.idea.caches.resolve.unsafeResolveToDescriptor
import org.jetbrains.kotlin.idea.completion.KotlinIdeaCompletionBundle
import org.jetbrains.kotlin.idea.util.IdeDescriptorRenderers
import org.jetbrains.kotlin.psi.KtFunction
import org.jetbrains.kotlin.types.typeUtil.isUnit
class KotlinFindUsagesProvider : KotlinFindUsagesProviderBase() {
override fun getDescriptiveName(element: PsiElement): String {
if (element !is KtFunction) return super.getDescriptiveName(element)
val name = element.name ?: ""
val descriptor = element.unsafeResolveToDescriptor() as FunctionDescriptor
val renderer = IdeDescriptorRenderers.SOURCE_CODE_SHORT_NAMES_NO_ANNOTATIONS
val paramsDescription =
descriptor.valueParameters.joinToString(prefix = "(", postfix = ")") { renderer.renderType(it.type) }
val returnType = descriptor.returnType
val returnTypeDescription = if (returnType != null && !returnType.isUnit()) renderer.renderType(returnType) else null
val funDescription = "$name$paramsDescription" + (returnTypeDescription?.let { ": $it" } ?: "")
return element.containerDescription?.let { KotlinIdeaCompletionBundle.message("find.usage.provider.0.of.1", funDescription, it) }
?: KotlinIdeaCompletionBundle.message("find.usage.provider.0", funDescription)
}
override fun getNodeText(element: PsiElement, useFullName: Boolean): String =
getDescriptiveName(element)
}
| apache-2.0 | da194a11971e874ed2978a6d8b7e6bb9 | 53.484848 | 158 | 0.759733 | 4.833333 | false | false | false | false |
smmribeiro/intellij-community | platform/platform-impl/src/com/intellij/ui/dsl/builder/impl/PlaceholderBaseImpl.kt | 1 | 3320 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.ui.dsl.builder.impl
import com.intellij.openapi.ui.DialogPanel
import com.intellij.ui.dsl.builder.CellBase
import com.intellij.ui.dsl.builder.SpacingConfiguration
import com.intellij.ui.dsl.gridLayout.Constraints
import org.jetbrains.annotations.ApiStatus
import javax.swing.JComponent
@ApiStatus.Internal
internal abstract class PlaceholderBaseImpl<T : CellBase<T>>(private val parent: RowImpl) : CellBaseImpl<T>() {
protected var placeholderCellData: PlaceholderCellData? = null
private set
private var visible = true
private var enabled = true
var component: JComponent? = null
set(value) {
reinstallComponent(field, value)
field = value
}
override fun enabledFromParent(parentEnabled: Boolean) {
doEnabled(parentEnabled && enabled)
}
override fun enabled(isEnabled: Boolean): CellBase<T> {
enabled = isEnabled
if (parent.isEnabled()) {
doEnabled(enabled)
}
return this
}
override fun visibleFromParent(parentVisible: Boolean) {
doVisible(parentVisible && visible)
}
override fun visible(isVisible: Boolean): CellBase<T> {
visible = isVisible
if (parent.isVisible()) {
doVisible(visible)
}
component?.isVisible = isVisible
return this
}
open fun init(panel: DialogPanel, constraints: Constraints, spacing: SpacingConfiguration) {
placeholderCellData = PlaceholderCellData(panel, constraints, spacing)
if (component != null) {
reinstallComponent(null, component)
}
}
private fun reinstallComponent(oldComponent: JComponent?, newComponent: JComponent?) {
var invalidate = false
if (oldComponent != null) {
placeholderCellData?.let {
if (oldComponent is DialogPanel) {
it.panel.unregisterSubPanel(oldComponent)
}
it.panel.remove(oldComponent)
invalidate = true
}
}
if (newComponent != null) {
newComponent.isVisible = visible && parent.isVisible()
newComponent.isEnabled = enabled && parent.isEnabled()
placeholderCellData?.let {
val gaps = customGaps ?: getComponentGaps(it.constraints.gaps.left, it.constraints.gaps.right, newComponent, it.spacing)
it.constraints = it.constraints.copy(
gaps = gaps,
visualPaddings = getVisualPaddings(newComponent.origin)
)
it.panel.add(newComponent, it.constraints)
if (newComponent is DialogPanel) {
it.panel.registerSubPanel(newComponent)
}
invalidate = true
}
}
if (invalidate) {
invalidate()
}
}
private fun doVisible(isVisible: Boolean) {
component?.let {
if (it.isVisible != isVisible) {
it.isVisible = isVisible
invalidate()
}
}
}
private fun doEnabled(isEnabled: Boolean) {
component?.let {
it.isEnabled = isEnabled
}
}
private fun invalidate() {
placeholderCellData?.let {
// Force parent to re-layout
it.panel.revalidate()
it.panel.repaint()
}
}
}
@ApiStatus.Internal
internal data class PlaceholderCellData(val panel: DialogPanel, var constraints: Constraints, val spacing: SpacingConfiguration)
| apache-2.0 | 24d44650720920dc1ef71bfad0bb3bb8 | 27.135593 | 128 | 0.683434 | 4.643357 | false | false | false | false |
smmribeiro/intellij-community | python/src/com/jetbrains/reflection/ReflectionUtils.kt | 7 | 5580 | // Copyright 2000-2017 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.reflection
import java.beans.Introspector
import java.beans.PropertyDescriptor
import kotlin.reflect.KClass
import kotlin.reflect.KMutableProperty
import kotlin.reflect.KProperty
import kotlin.reflect.full.memberProperties
import kotlin.reflect.jvm.javaType
/**
* Tools to fetch properties both from Java and Kotlin code and to copy them from one object to another.
* To be a property container class should have kotlin properties, java bean properties or implement [SimplePropertiesProvider].
*
* Properties should be writable except [DelegationProperty]
* @author Ilya.Kazakevich
*/
interface Property {
fun getName(): String
fun getType(): java.lang.reflect.Type
fun get(): Any?
fun set(value: Any?)
}
private class KotlinProperty(val property: KMutableProperty<*>, val instance: Any?) : Property {
override fun getName() = property.name
override fun getType() = property.returnType.javaType
override fun get() = property.getter.call(instance)
override fun set(value: Any?) = property.setter.call(instance, value)
}
private class JavaProperty(val property: PropertyDescriptor, val instance: Any?) : Property {
override fun getName() = property.name!!
override fun getType() = property.propertyType!!
override fun get() = property.readMethod.invoke(instance)!!
override fun set(value: Any?) {
property.writeMethod.invoke(instance, value)
}
}
private class SimpleProperty(private val propertyName: String,
private val provider: SimplePropertiesProvider) : Property {
override fun getName() = propertyName
override fun getType() = String::class.java
override fun get() = provider.getPropertyValue(propertyName)
override fun set(value: Any?) = provider.setPropertyValue(propertyName, value)
}
/**
* Implement to handle properties manually
*/
interface SimplePropertiesProvider {
val propertyNames: List<String>
fun setPropertyValue(propertyName: String, propertyValue: Any?)
fun getPropertyValue(propertyName: String): Any?
}
class Properties(val properties: List<Property>, val instance: Any) {
val propertiesMap: MutableMap<String, Property> = HashMap(properties.map { Pair(it.getName(), it) }.toMap())
init {
if (instance is SimplePropertiesProvider) {
instance.propertyNames.forEach { propertiesMap.put(it, SimpleProperty(it, instance)) }
}
}
fun copyTo(dst: Properties) {
propertiesMap.values.forEach {
val dstProperty = dst.propertiesMap[it.getName()]
if (dstProperty != null) {
val value = it.get()
dstProperty.set(value)
}
}
}
}
private fun KProperty<*>.isAnnotated(annotation: KClass<*>): Boolean {
return this.annotations.find { annotation.java.isAssignableFrom(it.javaClass) } != null
}
private val membersCache = object : ClassValue<Collection<KProperty<*>>>() {
override fun computeValue(type: Class<*>): Collection<KProperty<*>> = type.kotlin.memberProperties
}
private fun KClass<*>.memberPropertiesCached(): Collection<KProperty<*>> = membersCache.get(this.java)
/**
* @param instance object with properties (see module doc)
* @param annotationToFilterByClass optional annotation class to fetch only kotlin properties annotated with it. Only supported in Kotlin
* @param usePojoProperties search for java-style properties (kotlin otherwise)
* @return properties of some object
*/
fun getProperties(instance: Any, annotationToFilterByClass: Class<*>? = null, usePojoProperties: Boolean = false): Properties {
val annotationToFilterBy = annotationToFilterByClass?.kotlin
if (usePojoProperties) {
// Java props
val javaProperties = Introspector.getBeanInfo(instance.javaClass).propertyDescriptors
assert(annotationToFilterBy == null, { "Filtering java properties is not supported" })
return Properties(javaProperties.map { JavaProperty(it, instance) }, instance)
}
else {
// Kotlin props
val klass = instance.javaClass.kotlin
val allKotlinProperties = LinkedHashSet(klass.memberPropertiesCached())
val delegatedProperties = ArrayList<Property>() // See DelegationProperty doc
allKotlinProperties.filter { it.isAnnotated(DelegationProperty::class) }.forEach {
val delegatedInstance = it.getter.call(instance)
if (delegatedInstance != null) {
delegatedProperties.addAll(getProperties(delegatedInstance, annotationToFilterBy?.java, false).properties)
allKotlinProperties.remove(it)
}
}
val firstLevelProperties = allKotlinProperties.filterIsInstance(KMutableProperty::class.java)
if (annotationToFilterBy == null) {
return Properties(firstLevelProperties.map { KotlinProperty(it, instance) } + delegatedProperties, instance)
}
return Properties(
firstLevelProperties.filter { it.isAnnotated(annotationToFilterBy) }.map { KotlinProperty(it, instance) } + delegatedProperties, instance)
}
}
@Retention(AnnotationRetention.RUNTIME)
@Target(AnnotationTarget.PROPERTY)
/**
* Property marked with it is not considered to be [Property] by itself, but class with properties instead.
* Following structure is example:
* class User:
* +familyName: String
* +lastName: String
* +credentials: Credentials
*
* class Credentials:
* +login: String
* +password: String
*
* Property credentials here is [DelegationProperty]. It can be val, but all other properties should be var
*/
annotation class DelegationProperty
| apache-2.0 | 9edb0fef37351518d50889877ef99b98 | 36.959184 | 144 | 0.745699 | 4.555102 | false | false | false | false |
smmribeiro/intellij-community | platform/lang-impl/src/com/intellij/util/indexing/diagnostic/dto/JsonScanningStatistics.kt | 9 | 1734 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.util.indexing.diagnostic.dto
import com.fasterxml.jackson.annotation.JsonIgnoreProperties
import com.fasterxml.jackson.annotation.JsonInclude
import com.fasterxml.jackson.annotation.JsonProperty
import com.intellij.util.indexing.diagnostic.dump.paths.PortableFilePath
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonIgnoreProperties(ignoreUnknown = true)
data class JsonScanningStatistics(
val providerName: String = "",
val numberOfScannedFiles: Int = 0,
val numberOfSkippedFiles: Int = 0,
val numberOfFilesForIndexing: Int = 0,
val numberOfFilesFullyIndexedByInfrastructureExtensions: Int = 0,
val filesFullyIndexedByInfrastructureExtensions: List<String> = emptyList(),
val statusTime: JsonDuration = JsonDuration(0),
val scanningTime: JsonDuration = JsonDuration(0),
val timeProcessingUpToDateFiles: JsonDuration = JsonDuration(0),
val timeUpdatingContentLessIndexes: JsonDuration = JsonDuration(0),
val timeIndexingWithoutContent: JsonDuration = JsonDuration(0),
/**
* Available only if [com.intellij.util.indexing.diagnostic.IndexDiagnosticDumper.shouldDumpProviderRootPaths] is enabled.
*/
val roots: List<String> = emptyList(),
/**
* Available only if [com.intellij.util.indexing.diagnostic.IndexDiagnosticDumper.shouldDumpPathsOfIndexedFiles] is enabled.
*/
val scannedFiles: List<JsonScannedFile>? = null
) {
@JsonIgnoreProperties(ignoreUnknown = true)
data class JsonScannedFile(
val path: PortableFilePath,
val isUpToDate: Boolean,
@JsonProperty("wfibe")
val wasFullyIndexedByInfrastructureExtension: Boolean
)
} | apache-2.0 | 82174bd291804439b7b10f59b267faab | 41.317073 | 126 | 0.792388 | 4.587302 | false | false | false | false |
smmribeiro/intellij-community | platform/platform-impl/src/com/intellij/ui/colorpicker/GraphicalColorPipette.kt | 2 | 10493 | /*
* Copyright (C) 2018 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.ui.colorpicker
import com.intellij.icons.AllIcons
import com.intellij.ide.IdeEventQueue
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.util.Disposer
import com.intellij.openapi.util.SystemInfo
import com.intellij.openapi.util.registry.Registry
import com.intellij.openapi.wm.WindowManager
import com.intellij.util.ui.ImageUtil
import com.intellij.util.ui.JBUI
import java.awt.*
import java.awt.event.KeyAdapter
import java.awt.event.KeyEvent
import java.awt.event.MouseAdapter
import java.awt.event.MouseEvent
import java.awt.image.BufferedImage
import java.awt.image.ImageObserver
import javax.swing.*
/**
* The size of captured screen area. It is same as the number of pixels are caught.<br>
* The selected pixel is the central one, so this value must be odd.
*/
private const val SCREEN_CAPTURE_SIZE = 11
/**
* The size of zoomed rectangle which shows the captured screen.
*/
private val ZOOM_RECTANGLE_SIZE = Toolkit.getDefaultToolkit().getBestCursorSize(64, 64).width
private val PIPETTE_BORDER_COLOR = Color.BLACK
private val INDICATOR_BOUND_COLOR = Color.RED
/**
* The left/top bound of selected pixel in zoomed rectangle.
*/
private val INDICATOR_BOUND_START = ZOOM_RECTANGLE_SIZE * (SCREEN_CAPTURE_SIZE / 2) / SCREEN_CAPTURE_SIZE
/**
* The width/height of selected pixel in zoomed rectangle.
*/
private val INDICATOR_BOUND_SIZE = ZOOM_RECTANGLE_SIZE * (SCREEN_CAPTURE_SIZE / 2 + 1) / SCREEN_CAPTURE_SIZE - INDICATOR_BOUND_START
private val TRANSPARENT_COLOR = Color(0, true)
private const val CURSOR_NAME = "GraphicalColorPicker"
/**
* Duration of updating the color of current hovered pixel. The unit is millisecond.
*/
private const val DURATION_COLOR_UPDATING = 33
/**
* The [ColorPipette] which picks up the color from monitor.
*/
open class GraphicalColorPipette(private val parent: JComponent) : ColorPipette {
override val icon: Icon = AllIcons.Ide.Pipette
override val rolloverIcon: Icon = AllIcons.Ide.Pipette_rollover
override val pressedIcon: Icon = AllIcons.Ide.Pipette_rollover
override fun pick(callback: ColorPipette.Callback) = PickerDialog(parent, callback).pick()
}
class GraphicalColorPipetteProvider : ColorPipetteProvider {
override fun createPipette(owner: JComponent): ColorPipette = GraphicalColorPipette(owner)
}
private class PickerDialog(val parent: JComponent, val callback: ColorPipette.Callback) : ImageObserver {
private val timer = Timer(DURATION_COLOR_UPDATING) { updatePipette() }
private val center = Point(ZOOM_RECTANGLE_SIZE / 2, ZOOM_RECTANGLE_SIZE / 2)
private val zoomRect = Rectangle(0, 0, ZOOM_RECTANGLE_SIZE, ZOOM_RECTANGLE_SIZE)
private val captureRect = Rectangle()
private var disposable = newDisposable()
private fun newDisposable() = Disposer.newDisposable("Color Pipette")
private val maskImage = ImageUtil.createImage(ZOOM_RECTANGLE_SIZE, ZOOM_RECTANGLE_SIZE, BufferedImage.TYPE_INT_ARGB)
private val magnifierImage = ImageUtil.createImage(ZOOM_RECTANGLE_SIZE, ZOOM_RECTANGLE_SIZE, BufferedImage.TYPE_INT_ARGB)
private val image: BufferedImage = let {
val image = parent.graphicsConfiguration.createCompatibleImage(ZOOM_RECTANGLE_SIZE, ZOOM_RECTANGLE_SIZE, Transparency.TRANSLUCENT)
val graphics2d = image.graphics as Graphics2D
graphics2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_NEAREST_NEIGHBOR)
graphics2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF)
image
}
private val robot = Robot()
private var previousColor: Color? = null
private var previousLoc: Point? = null
private val picker: Dialog = let {
val owner = SwingUtilities.getWindowAncestor(parent)
val pickerFrame = when (owner) {
is Dialog -> JDialog(owner)
is Frame -> JDialog(owner)
else -> JDialog(JFrame())
}
pickerFrame.isUndecorated = true
pickerFrame.isAlwaysOnTop = true
pickerFrame.size = Dimension(ZOOM_RECTANGLE_SIZE, ZOOM_RECTANGLE_SIZE)
pickerFrame.defaultCloseOperation = WindowConstants.DISPOSE_ON_CLOSE
val rootPane = pickerFrame.rootPane
rootPane.putClientProperty("Window.shadow", false)
rootPane.border = JBUI.Borders.empty()
val mouseAdapter = object : MouseAdapter() {
override fun mouseReleased(e: MouseEvent) {
e.consume()
when {
SwingUtilities.isLeftMouseButton(e) -> pickDone()
SwingUtilities.isRightMouseButton(e) -> cancelPipette()
else -> Unit
}
}
override fun mouseMoved(e: MouseEvent) = updatePipette()
}
pickerFrame.addMouseListener(mouseAdapter)
pickerFrame.addMouseMotionListener(mouseAdapter)
pickerFrame.addKeyListener(object : KeyAdapter() {
override fun keyPressed(e: KeyEvent) {
when (e.keyCode) {
KeyEvent.VK_ESCAPE -> cancelPipette()
KeyEvent.VK_ENTER -> pickDone()
}
}
})
pickerFrame
}
init {
val maskG = maskImage.createGraphics()
maskG.color = Color.BLUE
maskG.fillRect(0, 0, ZOOM_RECTANGLE_SIZE, ZOOM_RECTANGLE_SIZE)
maskG.color = Color.RED
maskG.composite = AlphaComposite.SrcOut
maskG.fillRect(0, 0, ZOOM_RECTANGLE_SIZE, ZOOM_RECTANGLE_SIZE)
maskG.dispose()
}
fun pick() {
if (Registry.`is`("ide.color.picker.new.pipette")) {
timer.start()
disposable = newDisposable()
ApplicationManager.getApplication().invokeLater {
IdeEventQueue.getInstance().addDispatcher(IdeEventQueue.EventDispatcher {
if (it is MouseEvent) {
if (it.clickCount > 0) {
it.consume()
when {
SwingUtilities.isLeftMouseButton(it) -> pickDone()
SwingUtilities.isRightMouseButton(it) -> cancelPipette()
else -> Unit
}
}
else if (it.id == MouseEvent.MOUSE_MOVED) {
updatePipette();
}
}
if (it is KeyEvent && it.id == KeyEvent.KEY_PRESSED) {
when (it.keyCode) {
KeyEvent.VK_ESCAPE -> it.consume().also { cancelPipette() }
KeyEvent.VK_ENTER -> it.consume().also { pickDone() }
KeyEvent.VK_UP -> moveMouse(it, 0, -1)
KeyEvent.VK_DOWN -> moveMouse(it, 0, +1)
KeyEvent.VK_LEFT -> moveMouse(it, -1, 0)
KeyEvent.VK_RIGHT -> moveMouse(it, +1, 0)
}
}
false
}, disposable)
}
}
else {
picker.isVisible = true
timer.start()
// it seems like it's the lowest value for opacity for mouse events to be processed correctly
WindowManager.getInstance().setAlphaModeRatio(picker, if (SystemInfo.isMac) 0.95f else 0.99f)
}
}
private fun moveMouse(e: KeyEvent, x: Int, y: Int) {
val p = MouseInfo.getPointerInfo().location
robot.mouseMove(p.x + x, p.y + y)
e.consume()
}
override fun imageUpdate(img: Image, flags: Int, x: Int, y: Int, width: Int, height: Int) = false
private fun cancelPipette() {
timer.stop()
picker.isVisible = false
picker.dispose()
Disposer.dispose(disposable)
callback.cancel()
}
private fun pickDone() {
timer.stop()
val pointerInfo = MouseInfo.getPointerInfo()
val location = pointerInfo.location
val pickedColor = robot.getPixelColor(location.x, location.y)
picker.isVisible = false
Disposer.dispose(disposable)
callback.picked(pickedColor)
}
private fun updatePipette() {
if (Registry.`is`("ide.color.picker.new.pipette")) {
val pointerInfo = MouseInfo.getPointerInfo()
val mouseLoc = pointerInfo.location
val pickedColor = robot.getPixelColor(mouseLoc.x, mouseLoc.y)
if (previousLoc != mouseLoc || previousColor != pickedColor) {
previousLoc = mouseLoc
previousColor = pickedColor
callback.update(pickedColor)
}
}
else {
if (picker.isShowing) {
val pointerInfo = MouseInfo.getPointerInfo()
val mouseLoc = pointerInfo.location
picker.setLocation(mouseLoc.x - picker.width / 2, mouseLoc.y - picker.height / 2)
val pickedColor = robot.getPixelColor(mouseLoc.x, mouseLoc.y)
if (previousLoc != mouseLoc || previousColor != pickedColor) {
previousLoc = mouseLoc
previousColor = pickedColor
val halfPixelNumber = SCREEN_CAPTURE_SIZE / 2
captureRect.setBounds(mouseLoc.x - halfPixelNumber, mouseLoc.y - halfPixelNumber, SCREEN_CAPTURE_SIZE, SCREEN_CAPTURE_SIZE)
val capture = robot.createScreenCapture(captureRect)
val graphics = image.graphics as Graphics2D
// Clear the cursor graphics
graphics.composite = AlphaComposite.Src
graphics.color = TRANSPARENT_COLOR
graphics.fillRect(0, 0, image.width, image.height)
graphics.drawImage(capture, zoomRect.x, zoomRect.y, zoomRect.width, zoomRect.height, this)
// cropping round image
graphics.composite = AlphaComposite.DstOut
graphics.drawImage(maskImage, zoomRect.x, zoomRect.y, zoomRect.width, zoomRect.height, this)
// paint magnifier
graphics.composite = AlphaComposite.SrcOver
graphics.drawImage(magnifierImage, 0, 0, this)
graphics.composite = AlphaComposite.SrcOver
graphics.color = PIPETTE_BORDER_COLOR
graphics.drawRect(0, 0, ZOOM_RECTANGLE_SIZE - 1, ZOOM_RECTANGLE_SIZE - 1)
graphics.color = INDICATOR_BOUND_COLOR
graphics.drawRect(INDICATOR_BOUND_START, INDICATOR_BOUND_START, INDICATOR_BOUND_SIZE, INDICATOR_BOUND_SIZE)
picker.cursor = parent.toolkit.createCustomCursor(image, center, CURSOR_NAME)
callback.update(pickedColor)
}
}
}
}
}
| apache-2.0 | 132b0ba0d48fa43fa669ef43cdb4213f | 35.058419 | 134 | 0.691127 | 4.190495 | false | false | false | false |
smmribeiro/intellij-community | plugins/kotlin/analysis/src/org/jetbrains/kotlin/idea/references/referenceUtil.kt | 1 | 14742 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.references
import com.intellij.openapi.project.Project
import com.intellij.psi.*
import com.intellij.psi.search.GlobalSearchScope
import org.jetbrains.kotlin.asJava.unwrapped
import org.jetbrains.kotlin.builtins.isExtensionFunctionType
import org.jetbrains.kotlin.descriptors.*
import org.jetbrains.kotlin.idea.caches.resolve.resolveImportReference
import org.jetbrains.kotlin.idea.core.canMoveLambdaOutsideParentheses
import org.jetbrains.kotlin.idea.core.moveFunctionLiteralOutsideParentheses
import org.jetbrains.kotlin.idea.imports.canBeReferencedViaImport
import org.jetbrains.kotlin.idea.imports.importableFqName
import org.jetbrains.kotlin.idea.intentions.OperatorToFunctionIntention
import org.jetbrains.kotlin.idea.stubindex.KotlinFullClassNameIndex
import org.jetbrains.kotlin.idea.stubindex.KotlinFunctionShortNameIndex
import org.jetbrains.kotlin.idea.stubindex.KotlinPropertyShortNameIndex
import org.jetbrains.kotlin.idea.stubindex.KotlinTypeAliasShortNameIndex
import org.jetbrains.kotlin.idea.util.CallTypeAndReceiver
import org.jetbrains.kotlin.idea.util.ProjectRootsUtil
import org.jetbrains.kotlin.idea.util.safeAnalyzeNonSourceRootCode
import org.jetbrains.kotlin.kdoc.psi.impl.KDocName
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.*
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.FunctionImportedFromObject
import org.jetbrains.kotlin.resolve.PropertyImportedFromObject
import org.jetbrains.kotlin.resolve.calls.callUtil.getResolvedCall
import org.jetbrains.kotlin.resolve.calls.model.VariableAsFunctionResolvedCall
import org.jetbrains.kotlin.resolve.descriptorUtil.isExtension
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
import org.jetbrains.kotlin.resolve.source.getPsi
import org.jetbrains.kotlin.serialization.deserialization.descriptors.DeserializedClassDescriptor
import org.jetbrains.kotlin.serialization.deserialization.descriptors.DeserializedPropertyDescriptor
import org.jetbrains.kotlin.serialization.deserialization.descriptors.DeserializedSimpleFunctionDescriptor
import org.jetbrains.kotlin.serialization.deserialization.descriptors.DeserializedTypeAliasDescriptor
import org.jetbrains.kotlin.util.OperatorNameConventions
@Deprecated("For binary compatibility with AS, see KT-42061", replaceWith = ReplaceWith("mainReference"))
@get:JvmName("getMainReference")
val KtSimpleNameExpression.mainReferenceCompat: KtSimpleNameReference
get() = mainReference
@Deprecated("For binary compatibility with AS, see KT-42061", replaceWith = ReplaceWith("mainReference"))
@get:JvmName("getMainReference")
val KtReferenceExpression.mainReferenceCompat: KtReference
get() = mainReference
@Deprecated("For binary compatibility with AS, see KT-42061", replaceWith = ReplaceWith("mainReference"))
@get:JvmName("getMainReference")
val KDocName.mainReferenceCompat: KDocReference
get() = mainReference
@Deprecated("For binary compatibility with AS, see KT-42061", replaceWith = ReplaceWith("mainReference"))
@get:JvmName("getMainReference")
val KtElement.mainReferenceCompat: KtReference?
get() = mainReference
// Navigation element of the resolved reference
// For property accessor return enclosing property
val PsiReference.unwrappedTargets: Set<PsiElement>
get() {
fun PsiElement.adjust(): PsiElement? = when (val target = unwrapped?.originalElement) {
is KtPropertyAccessor -> target.getNonStrictParentOfType<KtProperty>()
else -> target
}
return when (this) {
is PsiPolyVariantReference -> multiResolve(false).mapNotNullTo(HashSet()) { it.element?.adjust() }
else -> listOfNotNull(resolve()?.adjust()).toSet()
}
}
//
fun PsiReference.canBeReferenceTo(candidateTarget: PsiElement): Boolean {
// optimization
return element.containingFile == candidateTarget.containingFile
|| ProjectRootsUtil.isInProjectOrLibSource(element, includeScriptsOutsideSourceRoots = true)
}
fun DeclarationDescriptor.findPsiDeclarations(project: Project, resolveScope: GlobalSearchScope): Collection<PsiElement> {
val fqName = importableFqName ?: return emptyList()
fun Collection<KtNamedDeclaration>.fqNameFilter() = filter { it.fqName == fqName }
return when (this) {
is DeserializedClassDescriptor -> KotlinFullClassNameIndex.getInstance()[fqName.asString(), project, resolveScope]
is DeserializedTypeAliasDescriptor -> KotlinTypeAliasShortNameIndex.getInstance()[fqName.shortName()
.asString(), project, resolveScope].fqNameFilter()
is DeserializedSimpleFunctionDescriptor, is FunctionImportedFromObject -> KotlinFunctionShortNameIndex.getInstance()[fqName.shortName()
.asString(), project, resolveScope].fqNameFilter()
is DeserializedPropertyDescriptor, is PropertyImportedFromObject -> KotlinPropertyShortNameIndex.getInstance()[fqName.shortName()
.asString(), project, resolveScope].fqNameFilter()
is DeclarationDescriptorWithSource -> listOfNotNull(source.getPsi())
else -> emptyList()
}
}
fun PsiReference.matchesTarget(candidateTarget: PsiElement): Boolean {
if (!canBeReferenceTo(candidateTarget)) return false
val unwrappedCandidate = candidateTarget.unwrapped?.originalElement ?: return false
// Optimizations
when (this) {
is KtInvokeFunctionReference -> {
if (candidateTarget !is KtNamedFunction && candidateTarget !is PsiMethod) return false
if ((candidateTarget as PsiNamedElement).name != OperatorNameConventions.INVOKE.asString()) {
return false
}
}
is KtDestructuringDeclarationReference -> {
if (candidateTarget !is KtNamedFunction && candidateTarget !is KtParameter && candidateTarget !is PsiMethod) return false
}
is KtSimpleNameReference -> {
if (unwrappedCandidate is PsiMethod && !canBePsiMethodReference()) return false
}
}
val element = element
if (candidateTarget is KtImportAlias &&
(element is KtSimpleNameExpression && element.getReferencedName() == candidateTarget.name ||
this is KDocReference && this.canonicalText == candidateTarget.name)
) {
val importDirective = candidateTarget.importDirective ?: return false
val importedFqName = importDirective.importedFqName ?: return false
val importedDescriptors = importDirective.containingKtFile.resolveImportReference(importedFqName)
val importableTargets = unwrappedTargets.mapNotNull {
when {
it is KtConstructor<*> -> it.containingClassOrObject
it is PsiMethod && it.isConstructor -> it.containingClass
else -> it
}
}
val project = element.project
val resolveScope = element.resolveScope
return importedDescriptors.any {
it.findPsiDeclarations(project, resolveScope).any { declaration ->
declaration in importableTargets
}
}
}
if (element is KtLabelReferenceExpression) {
when ((element.parent as? KtContainerNode)?.parent) {
is KtReturnExpression -> unwrappedTargets.forEach {
if (it !is KtFunctionLiteral && !(it is KtNamedFunction && it.name.isNullOrEmpty())) return@forEach
it as KtFunction
val labeledExpression = it.getLabeledParent(element.getReferencedName())
if (labeledExpression != null) {
if (candidateTarget == labeledExpression) return true else return@forEach
}
val calleeReference = it.getCalleeByLambdaArgument()?.mainReference ?: return@forEach
if (calleeReference.matchesTarget(candidateTarget)) return true
}
is KtBreakExpression, is KtContinueExpression -> unwrappedTargets.forEach {
val labeledExpression = (it as? KtExpression)?.getLabeledParent(element.getReferencedName()) ?: return@forEach
if (candidateTarget == labeledExpression) return true
}
}
}
val targets = unwrappedTargets
val manager = candidateTarget.manager
if (targets.any { manager.areElementsEquivalent(unwrappedCandidate, it) }) {
return true
}
if (this is KtReference) {
return targets.any {
it.isConstructorOf(unwrappedCandidate)
|| it is KtObjectDeclaration && it.isCompanion() && it.getNonStrictParentOfType<KtClass>() == unwrappedCandidate
}
}
// TODO: Workaround for Kotlin constructor search in Java code. To be removed after refactoring of the search API
else if (this is PsiJavaCodeReferenceElement && unwrappedCandidate is KtConstructor<*>) {
var parent = getElement().parent
if (parent is PsiAnonymousClass) {
parent = parent.getParent()
}
if ((parent as? PsiNewExpression)?.resolveConstructor()?.unwrapped == unwrappedCandidate) return true
}
if (this is PsiJavaCodeReferenceElement && candidateTarget is KtObjectDeclaration && unwrappedTargets.size == 1) {
val referredClass = unwrappedTargets.first()
if (referredClass is KtClass && candidateTarget in referredClass.companionObjects) {
if (parent is PsiImportStaticStatement) return true
return parent.reference?.unwrappedTargets?.any {
(it is KtProperty || it is KtNamedFunction) && it.parent?.parent == candidateTarget
} ?: false
}
}
return false
}
fun KtSimpleNameReference.canBePsiMethodReference(): Boolean {
// NOTE: Accessor references are handled separately, see SyntheticPropertyAccessorReference
if (element == (element.parent as? KtCallExpression)?.calleeExpression) return true
val callableReference = element.getParentOfTypeAndBranch<KtCallableReferenceExpression> { callableReference }
if (callableReference != null) return true
val binaryOperator = element.getParentOfTypeAndBranch<KtBinaryExpression> { operationReference }
if (binaryOperator != null) return true
val unaryOperator = element.getParentOfTypeAndBranch<KtUnaryExpression> { operationReference }
if (unaryOperator != null) return true
if (element.getNonStrictParentOfType<KtImportDirective>() != null) return true
return false
}
private fun PsiElement.isConstructorOf(unwrappedCandidate: PsiElement) =
when {
// call to Java constructor
this is PsiMethod && isConstructor && containingClass == unwrappedCandidate -> true
// call to Kotlin constructor
this is KtConstructor<*> && getContainingClassOrObject().isEquivalentTo(unwrappedCandidate) -> true
else -> false
}
fun AbstractKtReference<out KtExpression>.renameImplicitConventionalCall(newName: String?): KtExpression {
if (newName == null) return expression
val (newExpression, newNameElement) = OperatorToFunctionIntention.convert(expression)
if (OperatorNameConventions.INVOKE.asString() == newName && newExpression is KtDotQualifiedExpression) {
val canMoveLambda = newExpression.getPossiblyQualifiedCallExpression()?.canMoveLambdaOutsideParentheses() == true
OperatorToFunctionIntention.replaceExplicitInvokeCallWithImplicit(newExpression)?.let { newQualifiedExpression ->
newQualifiedExpression.getPossiblyQualifiedCallExpression()
?.takeIf { canMoveLambda }
?.let(KtCallExpression::moveFunctionLiteralOutsideParentheses)
return newQualifiedExpression
}
}
newNameElement.mainReference.handleElementRename(newName)
return newExpression
}
fun KtElement.resolveMainReferenceToDescriptors(): Collection<DeclarationDescriptor> {
val bindingContext = safeAnalyzeNonSourceRootCode(BodyResolveMode.PARTIAL)
return mainReference?.resolveToDescriptors(bindingContext) ?: emptyList()
}
fun PsiReference.getImportAlias(): KtImportAlias? {
return (this as? KtSimpleNameReference)?.getImportAlias()
}
// ----------- Read/write access -----------------------------------------------------------------------------------------------------------------------
fun KtReference.canBeResolvedViaImport(target: DeclarationDescriptor, bindingContext: BindingContext): Boolean {
if (this is KDocReference) {
val qualifier = element.getQualifier() ?: return true
return if (target.isExtension) {
val elementHasFunctionDescriptor = element.resolveMainReferenceToDescriptors().any { it is FunctionDescriptor }
val qualifierHasClassDescriptor = qualifier.resolveMainReferenceToDescriptors().any { it is ClassDescriptor }
elementHasFunctionDescriptor && qualifierHasClassDescriptor
} else {
false
}
}
return element.canBeResolvedViaImport(target, bindingContext)
}
fun KtElement.canBeResolvedViaImport(target: DeclarationDescriptor, bindingContext: BindingContext): Boolean {
if (!target.canBeReferencedViaImport()) return false
if (target.isExtension) return true // assume that any type of reference can use imports when resolved to extension
if (this !is KtNameReferenceExpression) return false
val callTypeAndReceiver = CallTypeAndReceiver.detect(this)
if (callTypeAndReceiver.receiver != null) {
if (target !is PropertyDescriptor || !target.type.isExtensionFunctionType) return false
if (callTypeAndReceiver !is CallTypeAndReceiver.DOT && callTypeAndReceiver !is CallTypeAndReceiver.SAFE) return false
val resolvedCall = bindingContext[BindingContext.CALL, this].getResolvedCall(bindingContext)
as? VariableAsFunctionResolvedCall ?: return false
if (resolvedCall.variableCall.explicitReceiverKind.isDispatchReceiver) return false
}
if (parent is KtThisExpression || parent is KtSuperExpression) return false // TODO: it's a bad design of PSI tree, we should change it
return true
}
fun KtFunction.getCalleeByLambdaArgument(): KtSimpleNameExpression? {
val argument = getParentOfTypeAndBranch<KtValueArgument> { getArgumentExpression() } ?: return null
val callExpression = when (argument) {
is KtLambdaArgument -> argument.parent as? KtCallExpression
else -> (argument.parent as? KtValueArgumentList)?.parent as? KtCallExpression
} ?: return null
return callExpression.calleeExpression as? KtSimpleNameExpression
}
| apache-2.0 | e93f4b0920d2170aac533d7e7ba70756 | 48.636364 | 158 | 0.7345 | 5.8593 | false | false | false | false |
libhide/solitaire | app/src/main/java/com/ratik/solitare/logic/GameModel.kt | 1 | 3177 | package com.ratik.solitare
object GameModel {
val deck = Deck()
val wastePile: MutableList<Card> = mutableListOf()
val foundationPiles = arrayOf(FoundationPile(clubs), FoundationPile(diamonds),
FoundationPile(hearts), FoundationPile(spades))
val tableauPiles = Array(7, { TableauPile() })
fun resetGame() {
wastePile.clear()
foundationPiles.forEach { it.reset() }
deck.reset()
tableauPiles.forEachIndexed { i, tableauPile ->
val cardsInPile: MutableList<Card> = Array(i + 1, { deck.drawCard() }).toMutableList()
tableauPiles[i] = TableauPile(cardsInPile)
}
}
fun onDeckTap() {
if (deck.cardsInDeck.size > 0) {
val card = deck.drawCard()
card.faceUp = true
wastePile.add(card)
} else {
deck.cardsInDeck = wastePile.toMutableList()
wastePile.clear()
}
}
fun onWasteTap() {
if (wastePile.size > 0) {
val card = wastePile.last()
if (playCard(card)) {
wastePile.remove(card)
}
}
}
fun onFoundationTap(foundationIndex: Int) {
val foundationPile = foundationPiles[foundationIndex]
if (foundationPile.cards.size > 0) {
val card = foundationPile.cards.last()
if (playCard(card)) {
foundationPile.removeCard(card)
}
}
}
fun onTableauTap(tableauIndex: Int, cardIndex: Int) {
val tableauPile = tableauPiles[tableauIndex]
if (tableauPile.cards.size > 0) {
if (tableauPile.cards[cardIndex].faceUp) {
val cards = tableauPile.cards.subList(cardIndex, tableauPile.cards.lastIndex + 1)
if (playCards(cards)) {
tableauPile.removeCards(cardIndex)
}
}
}
}
private fun playCards(cards: MutableList<Card>): Boolean {
if (cards.size == 1) {
return playCard(cards.first())
} else {
tableauPiles.forEach {
if (it.addCards(cards)) {
return true
}
}
}
return false
}
private fun playCard(card: Card): Boolean {
foundationPiles.forEach {
if (it.addCard(card)) {
return true
}
}
tableauPiles.forEach {
if (it.addCards(mutableListOf(card))) {
return true
}
}
return false
}
fun debugPrint() {
var firstLine = if (wastePile.size > 0) "${wastePile.last()}" else "___"
firstLine = firstLine.padEnd(18)
foundationPiles.forEach {
firstLine += if (it.cards.size > 0) "${it.cards.last()}" else "___"
firstLine += " "
}
println(firstLine)
println()
for (i in 0..12) {
var row = ""
tableauPiles.forEach {
row += if (it.cards.size > i) "${it.cards[i]}" else " "
row += " "
}
println(row)
}
}
} | mit | d0ba40cd2bc48a430ef290100bfecc6a | 28.155963 | 98 | 0.5096 | 4.125974 | false | false | false | false |
NlRVANA/Unity | app/src/main/java/com/zwq65/unity/ui/contract/LoginContract.kt | 1 | 1249 | /*
* Copyright [2017] [NIRVANA PRIVATE LIMITED]
*
* 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.zwq65.unity.ui.contract
import com.zwq65.unity.ui._base.BaseContract
/**
* ================================================
* <p>
* Created by NIRVANA on 2017/09/26
* Contact with <[email protected]>
* ================================================
*/
interface LoginContract {
interface View : BaseContract.View {
fun openMainActivity()
fun openRegisterActivity()
}
interface Presenter<V : BaseContract.View> : BaseContract.Presenter<V> {
fun login(account: String, password: String)
fun register()
fun forgotPsd()
}
}
| apache-2.0 | b026e67b76842d7f22a37c03899c348d | 28.738095 | 78 | 0.626902 | 4.277397 | false | false | false | false |
getsentry/raven-java | sentry/src/test/java/io/sentry/DsnTest.kt | 1 | 2852 | package io.sentry
import java.lang.IllegalArgumentException
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFailsWith
import kotlin.test.assertNull
class DsnTest {
@Test
fun `dsn parsed with path, sets all properties`() {
val dsn = Dsn("https://publicKey:secretKey@host/path/id")
assertEquals("https://host/path/api/id", dsn.sentryUri.toURL().toString())
assertEquals("publicKey", dsn.publicKey)
assertEquals("secretKey", dsn.secretKey)
assertEquals("/path/", dsn.path)
assertEquals("id", dsn.projectId)
}
@Test
fun `dsn parsed with path, sets all properties and ignores query strings`() {
// query strings were once a feature, but no more
val dsn = Dsn("https://publicKey:secretKey@host/path/id?sample.rate=0.1")
assertEquals("https://host/path/api/id", dsn.sentryUri.toURL().toString())
assertEquals("publicKey", dsn.publicKey)
assertEquals("secretKey", dsn.secretKey)
assertEquals("/path/", dsn.path)
assertEquals("id", dsn.projectId)
}
@Test
fun `dsn parsed without path`() {
val dsn = Dsn("https://key@host/id")
assertEquals("https://host/api/id", dsn.sentryUri.toURL().toString())
}
@Test
fun `dsn parsed with port number`() {
val dsn = Dsn("http://key@host:69/id")
assertEquals("http://host:69/api/id", dsn.sentryUri.toURL().toString())
}
@Test
fun `dsn parsed with trailing slash`() {
val dsn = Dsn("http://key@host/id/")
assertEquals("http://host/api/id", dsn.sentryUri.toURL().toString())
}
@Test
fun `dsn parsed with no delimiter for key`() {
val dsn = Dsn("https://publicKey@host/id")
assertEquals("publicKey", dsn.publicKey)
assertNull(dsn.secretKey)
}
@Test
fun `when no project id exists, throws exception`() {
val ex = assertFailsWith<IllegalArgumentException> { Dsn("http://key@host/") }
assertEquals("java.lang.IllegalArgumentException: Invalid DSN: A Project Id is required.", ex.message)
}
@Test
fun `when no key exists, throws exception`() {
val ex = assertFailsWith<IllegalArgumentException> { Dsn("http://host/id") }
assertEquals("java.lang.IllegalArgumentException: Invalid DSN: No public key provided.", ex.message)
}
@Test
fun `when only passing secret key, throws exception`() {
val ex = assertFailsWith<IllegalArgumentException> { Dsn("https://:secret@host/path/id") }
assertEquals("java.lang.IllegalArgumentException: Invalid DSN: No public key provided.", ex.message)
}
@Test
fun `dsn is normalized`() {
val dsn = Dsn("http://key@host//id")
assertEquals("http://host/api/id", dsn.sentryUri.toURL().toString())
}
}
| bsd-3-clause | eaa284f222cc1b7dc75521bfe0b96965 | 33.361446 | 110 | 0.641655 | 4.103597 | false | true | false | false |
timakden/advent-of-code | src/main/kotlin/ru/timakden/aoc/year2015/day05/Puzzle.kt | 1 | 882 | package ru.timakden.aoc.year2015.day05
import ru.timakden.aoc.util.measure
import kotlin.time.ExperimentalTime
@ExperimentalTime
fun main() {
measure {
println("Part One: ${solvePartOne(input)}")
println("Part Two: ${solvePartTwo(input)}")
}
}
fun solvePartOne(input: List<String>) = input.count(::isStringNicePartOne)
fun solvePartTwo(input: List<String>) = input.count(::isStringNicePartTwo)
fun isStringNicePartOne(s: String): Boolean {
val regex1 = "(.*[aeiou]){3}".toRegex()
val regex2 = "(.)\\1".toRegex()
val regex3 = "ab|cd|pq|xy".toRegex()
return regex1.containsMatchIn(s) && regex2.containsMatchIn(s) && !regex3.containsMatchIn(s)
}
fun isStringNicePartTwo(s: String): Boolean {
val regex1 = "(.{2}).*\\1".toRegex()
val regex2 = "(.).\\1".toRegex()
return regex1.containsMatchIn(s) && regex2.containsMatchIn(s)
}
| apache-2.0 | ff1d772676e1ea56e47314ba81ea866e | 28.4 | 95 | 0.676871 | 3.353612 | false | false | false | false |
wuan/bo-android | app/src/main/java/org/blitzortung/android/map/overlay/color/ColorHandler.kt | 1 | 3548 | /*
Copyright 2015 Andreas Würl
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.blitzortung.android.map.overlay.color
import android.content.SharedPreferences
import android.graphics.Color
import org.blitzortung.android.app.view.PreferenceKey
import org.blitzortung.android.app.view.get
import kotlin.math.max
import kotlin.math.min
abstract class ColorHandler(private val preferences: SharedPreferences) {
var colorScheme: ColorScheme = ColorScheme.BLITZORTUNG
private set
private lateinit var target: ColorTarget
init {
updateTarget()
}
fun updateTarget() {
target = getColorTarget()
colorScheme = ColorScheme.valueOf(preferences.get(PreferenceKey.COLOR_SCHEME, ColorScheme.BLITZORTUNG.toString()))
}
private fun getColorTarget(): ColorTarget {
return try {
ColorTarget.valueOf(preferences.get(PreferenceKey.MAP_TYPE, "SATELLITE"))
} catch (e: IllegalArgumentException) {
ColorTarget.SATELLITE
}
}
val colors: IntArray
get() = getColors(target)
protected abstract fun getColors(target: ColorTarget): IntArray
fun getColorSection(referenceTime: Long, eventTime: Long, intervalDuration: Int): Int {
val minutesPerColor = intervalDuration / colors.size
val section = if (minutesPerColor > 0) ((referenceTime - eventTime) / 1000 / 60 / minutesPerColor).toInt() else 0
return limitToValidRange(section)
}
fun getColor(referenceTime: Long, eventTime: Long, intervalDuration: Int): Int {
return getColor(getColorSection(referenceTime, eventTime, intervalDuration))
}
fun getColor(index: Int): Int {
return colors[limitToValidRange(index)]
}
private fun limitToValidRange(index: Int): Int {
return max(min(index, colors.size - 1), 0)
}
val textColor: Int
get() = getTextColor(target)
open fun getTextColor(target: ColorTarget): Int {
return when (target) {
ColorTarget.SATELLITE -> 0xffffffff.toInt()
ColorTarget.STREETMAP -> 0xff000000.toInt()
}
}
val lineColor: Int
get() = getLineColor(target)
open fun getLineColor(target: ColorTarget): Int {
return when (target) {
ColorTarget.SATELLITE -> 0xffffffff.toInt()
ColorTarget.STREETMAP -> 0xff000000.toInt()
}
}
val backgroundColor: Int
get() = getBackgroundColor(target)
open fun getBackgroundColor(target: ColorTarget): Int {
return when (target) {
ColorTarget.SATELLITE -> 0x00000000
ColorTarget.STREETMAP -> 0x00ffffff
}
}
val numberOfColors: Int
get() = colors.size
fun modifyBrightness(colors: IntArray, factor: Float): IntArray {
val hsvValues = FloatArray(3)
return colors.map {
Color.colorToHSV(it, hsvValues)
hsvValues[2] *= factor
Color.HSVToColor(hsvValues)
}.toIntArray()
}
} | apache-2.0 | f11571fabc0a5a561f14ef3ac03f1038 | 29.067797 | 122 | 0.671835 | 4.564994 | false | false | false | false |
Szewek/Minecraft-Flux | src/main/java/szewek/mcflux/blocks/BlockFluxGen.kt | 1 | 2495 | package szewek.mcflux.blocks
import net.minecraft.block.Block
import net.minecraft.block.state.IBlockState
import net.minecraft.entity.EntityLivingBase
import net.minecraft.entity.player.EntityPlayer
import net.minecraft.inventory.InventoryHelper
import net.minecraft.item.ItemStack
import net.minecraft.tileentity.TileEntity
import net.minecraft.util.EnumFacing
import net.minecraft.util.EnumHand
import net.minecraft.util.math.BlockPos
import net.minecraft.world.World
import net.minecraftforge.fluids.FluidUtil
import net.minecraftforge.items.wrapper.InvWrapper
import szewek.fl.block.BlockContainerModeled
import szewek.mcflux.MCFlux
import szewek.mcflux.R
import szewek.mcflux.tileentities.TileEntityFluxGen
class BlockFluxGen : BlockContainerModeled() {
init {
setHardness(1f)
}
override fun createNewTileEntity(worldIn: World, meta: Int): TileEntity? {
return TileEntityFluxGen()
}
override fun onBlockActivated(w: World?, pos: BlockPos?, state: IBlockState?, p: EntityPlayer?, h: EnumHand?, f: EnumFacing?, x: Float, y: Float, z: Float): Boolean {
val `is` = p!!.getHeldItem(h)
if (!w!!.isRemote) {
val te = w.getTileEntity(pos!!)
if (te is TileEntityFluxGen) {
val far = FluidUtil.tryEmptyContainerAndStow(`is`, te as TileEntityFluxGen?, InvWrapper(p.inventory), TileEntityFluxGen.fluidCap, p)
if (far.success)
p.setHeldItem(h, far.result)
else
p.openGui(MCFlux.MF!!, R.MF_GUI_FLUXGEN, w, pos.x, pos.y, pos.z)
}
}
return true
}
override fun onBlockPlacedBy(w: World?, bp: BlockPos?, ibs: IBlockState?, placer: EntityLivingBase?, stack: ItemStack?) {
if (!w!!.isRemote)
updateRedstoneState(w, bp)
}
override fun neighborChanged(ibs: IBlockState?, w: World?, bp: BlockPos?, b: Block?, fromPos: BlockPos?) {
if (!w!!.isRemote)
updateRedstoneState(w, bp)
}
override fun breakBlock(w: World, pos: BlockPos, state: IBlockState) {
val te = w.getTileEntity(pos)
if (te is TileEntityFluxGen) {
InventoryHelper.dropInventoryItems(w, pos, (te as TileEntityFluxGen?)!!)
w.updateComparatorOutputLevel(pos, this)
}
super.breakBlock(w, pos, state)
}
private fun updateRedstoneState(w: World, bp: BlockPos?) {
val tefg = w.getTileEntity(bp!!) as TileEntityFluxGen?
if (tefg != null) {
val b = tefg.receivedRedstone
var nb = false
for (f in EnumFacing.VALUES)
if (w.getRedstonePower(bp.offset(f, 1), f) > 0) {
nb = true
break
}
if (b != nb)
tefg.receivedRedstone = nb
}
}
}
| mit | bdcb829bff09a505aae25e59cc6ee83d | 30.987179 | 167 | 0.730261 | 3.344504 | false | false | false | false |
OpenConference/OpenConference-android | app/src/main/java/com/openconference/sessiondetails/DetailsSpeakerAdapterDelegate.kt | 1 | 2916 | package com.openconference.sessiondetails
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import butterknife.bindView
import com.hannesdorfmann.adapterdelegates2.AbsListItemAdapterDelegate
import com.openconference.R
import com.openconference.model.Speaker
import com.openconference.sessiondetails.presentationmodel.SessionDetailItem
import com.openconference.sessiondetails.presentationmodel.SessionSpeakerItem
import com.openconference.util.picasso.CircleImageTransformation
import com.openconference.util.picasso.PicassoScrollListener
import com.squareup.picasso.Picasso
/**
* Displays the description of a session
*
* @author Hannes Dorfmann
*/
open class DetailsSpeakerAdapterDelegate(protected val inflater: LayoutInflater, protected val picasso: Picasso, protected val clickListener: (Speaker) -> Unit) : AbsListItemAdapterDelegate<SessionSpeakerItem, SessionDetailItem, DetailsSpeakerAdapterDelegate.SpeakerViewHolder>() {
override fun isForViewType(item: SessionDetailItem, items: MutableList<SessionDetailItem>?,
position: Int): Boolean = item is SessionSpeakerItem
override fun onCreateViewHolder(parent: ViewGroup): SpeakerViewHolder =
SpeakerViewHolder(
inflater.inflate(R.layout.item_session_details_speaker, parent, false), picasso,
clickListener)
override fun onBindViewHolder(item: SessionSpeakerItem, viewHolder: SpeakerViewHolder) {
viewHolder.bind(item.speaker)
}
class SpeakerViewHolder(v: View, val picasso: Picasso, val clickListener: (Speaker) -> Unit) : RecyclerView.ViewHolder(
v) {
init {
v.setOnClickListener { clickListener(speaker) }
}
val name: TextView by bindView(R.id.name)
val company: TextView by bindView(R.id.company)
val profilePic: ImageView by bindView(R.id.profilePic)
lateinit var speaker: Speaker
inline fun bind(s: Speaker) {
speaker = s
name.text = s.name()
val companyName = s.company()
val jobTitle = s.jobTitle()
picasso.load(s.profilePic())
.placeholder(R.drawable.rounded_profile_pic_placeholder)
.tag(PicassoScrollListener.TAG)
.transform(CircleImageTransformation())
.fit()
.centerCrop()
.into(profilePic)
val companyJobTitle = StringBuilder()
if (companyName != null) {
companyJobTitle.append(companyName)
}
if (companyName != null && jobTitle != null) {
companyJobTitle.append(", ")
}
if (jobTitle != null) {
companyJobTitle.append(jobTitle)
}
if (companyJobTitle.length > 0) {
company.text = companyJobTitle.toString()
company.visibility = View.VISIBLE
} else {
company.visibility = View.GONE
}
}
}
} | apache-2.0 | 3bef80c498873cdb70a5e5caf519b198 | 32.918605 | 281 | 0.729081 | 4.584906 | false | false | false | false |
NephyProject/Penicillin | src/main/kotlin/jp/nephy/penicillin/extensions/models/StatusAction.kt | 1 | 2286 | /*
* The MIT License (MIT)
*
* Copyright (c) 2017-2019 Nephy Project Team
*
* 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.
*/
@file:Suppress("UNUSED", "PublicApiImplicitType")
package jp.nephy.penicillin.extensions.models
import jp.nephy.penicillin.endpoints.favorites
import jp.nephy.penicillin.endpoints.favorites.create
import jp.nephy.penicillin.endpoints.favorites.destroy
import jp.nephy.penicillin.endpoints.statuses
import jp.nephy.penicillin.endpoints.statuses.create
import jp.nephy.penicillin.endpoints.statuses.delete
import jp.nephy.penicillin.endpoints.statuses.show
import jp.nephy.penicillin.models.Status
/**
* Creates an action to retrieve this status.
*/
fun Status.refresh() = client.statuses.show(id = id)
/**
* Creates an action to favorite this status.
*/
fun Status.favorite() = client.favorites.create(id = id)
/**
* Creates an action to unfavorite this status.
*/
fun Status.unfavorite() = client.favorites.destroy(id = id)
/**
* Creates an action to delete this status.
*/
fun Status.delete() = client.statuses.delete(id = id)
/**
* Creates an action to send a mention to this status.
*
* @param text Status body.
*/
fun Status.mention(text: String) = client.statuses.create(text, inReplyToStatusId = id)
| mit | ce9d2c47e97630196fb45137758caf53 | 35.285714 | 87 | 0.758968 | 4.074866 | false | false | false | false |
fobo66/BookcrossingMobile | app/src/main/java/com/bookcrossing/mobile/ui/search/SearchHitBooksAdapter.kt | 1 | 2945 | /*
* Copyright 2019 Andrey Mukamolov
* 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.bookcrossing.mobile.ui.search
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.paging.PagedListAdapter
import androidx.recyclerview.widget.DiffUtil
import butterknife.BindView
import com.bookcrossing.mobile.R
import com.bookcrossing.mobile.models.SearchHitBook
import com.bookcrossing.mobile.modules.GlideApp
import com.bookcrossing.mobile.ui.search.SearchHitBooksAdapter.ViewHolder
import com.bookcrossing.mobile.util.adapters.BaseViewHolder
import com.bumptech.glide.load.resource.drawable.DrawableTransitionOptions.withCrossFade
import com.google.firebase.storage.FirebaseStorage
class SearchHitBooksAdapter : PagedListAdapter<SearchHitBook, ViewHolder>(SearchHitBooksAdapter) {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val view = LayoutInflater.from(parent.context)
.inflate(R.layout.hits_item, parent, false)
return ViewHolder(view)
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
val item = getItem(position)
if (item != null) {
holder.bind(item)
}
}
inner class ViewHolder(itemView: View) : BaseViewHolder(itemView) {
@BindView(R.id.search_hit_cover)
lateinit var cover: ImageView
@BindView(R.id.search_hit_book_name)
lateinit var bookName: TextView
@BindView(R.id.search_hit_author)
lateinit var author: TextView
@BindView(R.id.search_hit_current_position)
lateinit var currentPosition: TextView
fun bind(book: SearchHitBook) {
GlideApp.with(itemView.context)
.load(FirebaseStorage.getInstance().getReference(book.objectID + ".jpg"))
.placeholder(R.drawable.ic_book_cover_placeholder).transition(withCrossFade())
.into(cover)
bookName.text = book.name
author.text = book.author
currentPosition.text = book.positionName
}
}
companion object : DiffUtil.ItemCallback<SearchHitBook>() {
override fun areItemsTheSame(oldItem: SearchHitBook, newItem: SearchHitBook): Boolean {
return oldItem.objectID == newItem.objectID
}
override fun areContentsTheSame(oldItem: SearchHitBook, newItem: SearchHitBook): Boolean {
return oldItem == newItem
}
}
} | apache-2.0 | 581b1c36cbe9b269f56ef012f64df71d | 34.071429 | 98 | 0.748727 | 4.261939 | false | false | false | false |
siper/AdapterX | sample/src/main/java/pro/siper/adapterx/model/api/Urls.kt | 1 | 500 | package pro.siper.adapterx.model.api
import com.google.gson.annotations.Expose
import com.google.gson.annotations.SerializedName
class Urls {
@SerializedName("raw")
@Expose
var raw: String? = null
@SerializedName("full")
@Expose
var full: String? = null
@SerializedName("regular")
@Expose
var regular: String? = null
@SerializedName("small")
@Expose
var small: String? = null
@SerializedName("thumb")
@Expose
var thumb: String? = null
} | mit | 06ce4b7bf544ef86c02496bd0093c04e | 19.875 | 49 | 0.666 | 3.90625 | false | false | false | false |
nickthecoder/tickle | tickle-core/src/main/kotlin/uk/co/nickthecoder/tickle/sandbox/FontSandbox.kt | 1 | 3954 | /*
Tickle
Copyright (C) 2017 Nick Robinson
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package uk.co.nickthecoder.tickle.sandbox
import uk.co.nickthecoder.tickle.Pose
import uk.co.nickthecoder.tickle.graphics.Color
import uk.co.nickthecoder.tickle.graphics.TextHAlignment
import uk.co.nickthecoder.tickle.graphics.TextStyle
import uk.co.nickthecoder.tickle.graphics.TextVAlignment
import uk.co.nickthecoder.tickle.resources.FontResource
import java.awt.Font
/**
* Creates a FontTexture, and draws it in a window.
* The whole texture is drawn semi-transparent, and some specific lines of text are draw full opaque over the top.
*/
class FontSandbox : Sandbox(height = 700) {
val xPadding = 4
val yPadding = 4
val fontResource = FontResource(Font.SANS_SERIF, FontResource.FontStyle.PLAIN, 22.0, xPadding, yPadding)
val font = fontResource.fontTexture
val pose = Pose(font.glyphs.values.first().pose.texture)
var x = 10.0
var y = 10.0
init {
renderer.clearColor(Color.blue())
}
override fun tick() {
renderer.beginView()
renderer.clear()
val semiBlack = Color.black().semi()
val white = Color.white()
pose.draw(renderer, 250.0, 400.0, Color.white().semi())
val text = ".oO° Hello Worldy °Oo."
font.draw(renderer, "$text - Plain", 20.0, 100.0)
font.drawOutlined(renderer, "$text - Semi-Transparent Outline", 20.0, 130.0, outline = semiBlack)
font.drawOutlined(renderer, "$text - Outlined", 20.0, 160.0, outline = semiBlack)
font.drawOutlined(renderer, "$text - Blurred outline, thickness 3, alpha 0.3", 20.0, 190.0, outline = Color(0.0f, 0.0f, 0.0f, 0.3f), thickness = 3)
font.drawOutlined(renderer, "$text - Blurred outline, thickness 6, alpha 0.05", 20.0, 220.0, outline = Color(0.0f, 0.0f, 0.0f, 0.05f), thickness = 6)
font.drawOutlined(renderer, "$text - Blurred outline, thickness 6, alpha 0.025", 20.0, 250.0, outline = Color(0.0f, 0.0f, 0.0f, 0.025f), thickness = 6)
val topLeft = TextStyle(fontResource, TextHAlignment.LEFT, TextVAlignment.TOP, white)
val topRight = TextStyle(fontResource, TextHAlignment.RIGHT, TextVAlignment.TOP, white)
val bottomLeft = TextStyle(fontResource, TextHAlignment.LEFT, TextVAlignment.BOTTOM, white)
val bottomRight = TextStyle(fontResource, TextHAlignment.RIGHT, TextVAlignment.BOTTOM, white)
val baselineCenter = TextStyle(fontResource, TextHAlignment.CENTER, TextVAlignment.BASELINE, white)
val center = TextStyle(fontResource, TextHAlignment.CENTER, TextVAlignment.CENTER, white)
topLeft.draw(renderer, "Top\nLeft", 0.0, window.height.toDouble())
topRight.draw(renderer, "Top\nRight\n", window.width.toDouble(), window.height.toDouble())
bottomLeft.draw(renderer, "Bottom\nLeft", 0.0, 0.0)
bottomRight.draw(renderer, "Bottom\nRight", window.width.toDouble(), 0.0)
baselineCenter.draw(renderer, "Baseline\nCenter\njqy", window.width.toDouble() / 2, 0.0)
center.draw(renderer, "Center\nCenter\njqy", window.width.toDouble() / 2, window.height.toDouble() / 2)
val exampleGlyph = font.glyphs.values.first()
println("Glyph pose ${exampleGlyph.pose}")
renderer.endView()
window.swap()
}
}
fun main(args: Array<String>) {
FontSandbox().loop()
}
| gpl-3.0 | 643d3285a1f7c560bd0a57bdf09c1136 | 41.494624 | 159 | 0.705466 | 3.629017 | false | false | false | false |
shyiko/ktlint | ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/NoTrailingSpacesRule.kt | 1 | 1801 | package com.pinterest.ktlint.ruleset.standard
import com.pinterest.ktlint.core.Rule
import com.pinterest.ktlint.core.ast.nextLeaf
import org.jetbrains.kotlin.com.intellij.lang.ASTNode
import org.jetbrains.kotlin.com.intellij.psi.PsiWhiteSpace
import org.jetbrains.kotlin.com.intellij.psi.impl.source.tree.LeafPsiElement
class NoTrailingSpacesRule : Rule("no-trailing-spaces") {
override fun visit(
node: ASTNode,
autoCorrect: Boolean,
emit: (offset: Int, errorMessage: String, canBeAutoCorrected: Boolean) -> Unit
) {
if (node is PsiWhiteSpace) {
val lines = node.getText().split("\n")
if (lines.size > 1) {
val violated = checkForTrailingSpaces(lines.head(), node.startOffset, emit)
if (violated && autoCorrect) {
(node as LeafPsiElement).rawReplaceWithText("\n".repeat(lines.size - 1) + lines.last())
}
} else if (node.nextLeaf() == null /* eof */) {
val violated = checkForTrailingSpaces(lines, node.startOffset, emit)
if (violated && autoCorrect) {
(node as LeafPsiElement).rawReplaceWithText("\n".repeat(lines.size - 1))
}
}
}
}
private fun checkForTrailingSpaces(
lines: List<String>,
offset: Int,
emit: (offset: Int, errorMessage: String, canBeAutoCorrected: Boolean) -> Unit
): Boolean {
var violated = false
var violationOffset = offset
lines.forEach { line ->
if (!line.isEmpty()) {
emit(violationOffset, "Trailing space(s)", true)
violated = true
}
violationOffset += line.length + 1
}
return violated
}
}
| mit | 8bd7199dac79b8519ec7beb44fd1a0ec | 36.520833 | 107 | 0.592449 | 4.525126 | false | false | false | false |
STUDIO-apps/GeoShare_Android | mobile/src/main/java/uk/co/appsbystudio/geoshare/authentication/forgotpassword/ForgotPasswordFragment.kt | 1 | 2403 | package uk.co.appsbystudio.geoshare.authentication.forgotpassword
import android.content.Context
import android.os.Bundle
import android.support.v4.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import kotlinx.android.synthetic.main.fragment_forgot_password.*
import uk.co.appsbystudio.geoshare.R
import uk.co.appsbystudio.geoshare.authentication.AuthActivity
import uk.co.appsbystudio.geoshare.authentication.AuthView
class ForgotPasswordFragment : Fragment(), ForgotPasswordView {
private var fragmentCallback: AuthView? = null
private var presenter: ForgotPasswordPresenter? = null
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?): View? {
// Inflate the layout for this fragment
val view = inflater.inflate(R.layout.fragment_forgot_password, container, false)
presenter = ForgotPasswordPresenterImpl(this, ForgotPasswordInteractorImpl())
return view
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
progress_button_forgot_password.setOnClickListener {
presenter?.validate(edit_email_forgot_password.text.toString())
}
button_back_forgot_password.setOnClickListener {
fragmentCallback?.onBack()
}
}
override fun onAttach(context: Context?) {
super.onAttach(context)
try {
fragmentCallback = context as AuthActivity
} catch (e: ClassCastException) {
throw ClassCastException(activity.toString() + "must implement AuthView")
}
}
override fun setEmailError() {
edit_email_forgot_password.error = resources.getString(R.string.error_field_required)
}
override fun showProgress() {
progress_button_forgot_password.startAnimation()
}
override fun hideProgress() {
progress_button_forgot_password.revertAnimation()
}
override fun updateUI() {
//TODO: Replace string
Toast.makeText(this.context, "Email sent!", Toast.LENGTH_SHORT).show()
fragmentCallback?.onBack()
}
override fun showError(error: String) {
Toast.makeText(this.context, error, Toast.LENGTH_SHORT).show()
}
}
| apache-2.0 | 266d4efccd4e01955e9cd6edb0ec2f0b | 31.472973 | 93 | 0.703288 | 4.702544 | false | false | false | false |
ngageoint/mage-android | mage/src/main/java/mil/nga/giat/mage/data/layer/LayerRepository.kt | 1 | 1895 | package mil.nga.giat.mage.data.layer
import android.app.Application
import android.util.Log
import androidx.preference.PreferenceManager
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import mil.nga.giat.mage.R
import mil.nga.giat.mage.sdk.datastore.layer.LayerHelper
import mil.nga.giat.mage.sdk.datastore.staticfeature.StaticFeature
import mil.nga.giat.mage.sdk.datastore.staticfeature.StaticFeatureHelper
import mil.nga.giat.mage.sdk.datastore.user.EventHelper
import javax.inject.Inject
class LayerRepository @Inject constructor(
private val application: Application,
) {
private val layerHelper = LayerHelper.getInstance(application)
private val eventHelper = EventHelper.getInstance(application)
private val staticFeatureHelper = StaticFeatureHelper.getInstance(application)
suspend fun getStaticFeatureLayers(eventId: Long) = withContext(Dispatchers.IO) {
val preferences = PreferenceManager.getDefaultSharedPreferences(application)
val enabledLayers = preferences.getStringSet(application.getString(R.string.tileOverlaysKey), null) ?: emptySet()
try {
layerHelper.readByEvent(eventHelper.read(eventId), "Feature")
.asSequence()
.filter { it.isLoaded }
.filter { enabledLayers.contains(it.name) }
.toList()
} catch (e: Exception) {
Log.w(LOG_NAME, "Failed to load feature layers", e)
emptyList()
}
}
suspend fun getStaticFeature(layerId: Long, featureId: Long): StaticFeature = withContext(Dispatchers.IO) {
staticFeatureHelper.readFeature(layerId, featureId)
}
suspend fun getStaticFeatures(layerId: Long): Collection<StaticFeature> = withContext(Dispatchers.IO) {
layerHelper.read(layerId).staticFeatures
}
companion object {
private val LOG_NAME = LayerRepository::class.java.simpleName
}
} | apache-2.0 | 004cd555257670773de8c26192048d27 | 37.693878 | 119 | 0.750923 | 4.28733 | false | false | false | false |
emce/smog | app/src/main/java/mobi/cwiklinski/smog/database/CursorHelper.kt | 1 | 2626 | package mobi.cwiklinski.smog.database
import android.database.Cursor
object CursorHelper {
fun getLong(cursor: Cursor, columnName: String): Long {
return cursor.getLong(cursor.getColumnIndexOrThrow(columnName))
}
fun getFloat(cursor: Cursor, columnName: String): Float {
return cursor.getFloat(cursor.getColumnIndexOrThrow(columnName))
}
fun getInt(cursor: Cursor, columnName: String): Int {
return cursor.getInt(cursor.getColumnIndexOrThrow(columnName))
}
fun getString(cursor: Cursor, columnName: String): String? {
val columnIndex = cursor.getColumnIndexOrThrow(columnName)
if (cursor.isNull(columnIndex)) {
return null
} else {
return cursor.getString(cursor.getColumnIndexOrThrow(columnName))
}
}
fun getString(cursor: Cursor, columnName: String, alternate: String): String {
val columnIndex = cursor.getColumnIndexOrThrow(columnName)
if (cursor.isNull(columnIndex)) {
return alternate
} else {
return cursor.getString(cursor.getColumnIndexOrThrow(columnName))
}
}
fun getBoolean(cursor: Cursor, columnName: String): Boolean {
return cursor.getInt(cursor.getColumnIndexOrThrow(columnName)) == 1
}
fun getDouble(cursor: Cursor, columnName: String): Double? {
val columnIndex = cursor.getColumnIndexOrThrow(columnName)
if (cursor.isNull(columnIndex)) {
return null
} else {
return cursor.getDouble(columnIndex)
}
}
fun isNull(cursor: Cursor, columnName: String): Boolean {
return cursor.isNull(cursor.getColumnIndexOrThrow(columnName))
}
fun isEmpty(cursor: Cursor?): Boolean {
return cursor == null || cursor.count == 0
}
fun sumIntColumn(cursor: Cursor?, columnName: String): Int {
var value = 0
if (cursor != null && cursor.moveToFirst()) {
cursor.moveToPrevious()
val columnIndex = cursor.getColumnIndexOrThrow(columnName)
while (cursor.moveToNext()) {
value += cursor.getInt(columnIndex)
}
}
return value
}
fun sumDoubleColumn(cursor: Cursor?, columnName: String): Double {
var value = 0.0
if (cursor != null && cursor.moveToFirst()) {
cursor.moveToPrevious()
val columnIndex = cursor.getColumnIndexOrThrow(columnName)
while (cursor.moveToNext()) {
value += cursor.getDouble(columnIndex)
}
}
return value
}
} | apache-2.0 | b5c87f0e6f558b0d0561c512fe5abd8e | 31.036585 | 82 | 0.62757 | 5.079304 | false | false | false | false |
jiangkang/KTools | tools/src/main/java/com/jiangkang/tools/utils/SecurityUtils.kt | 1 | 1173 | package com.jiangkang.tools.utils
import android.graphics.Bitmap
import android.graphics.Bitmap.CompressFormat
import android.util.Base64
import java.io.ByteArrayOutputStream
import java.io.IOException
import java.io.UnsupportedEncodingException
/**
* Created by jiangkang on 2017/9/11.
*/
object SecurityUtils {
fun encodeByBase64(string: String): String {
var result = ""
try {
result = Base64.encodeToString(string.toByteArray(charset("utf-8")), Base64.DEFAULT)
} catch (e: UnsupportedEncodingException) {
}
return result
}
fun bmp2base64(bitmap: Bitmap?, compressFormat: CompressFormat?, quality: Int): String {
return if (bitmap == null) {
""
} else {
val outputStream = ByteArrayOutputStream()
bitmap.compress(compressFormat, quality, outputStream)
try {
outputStream.flush()
outputStream.close()
val bytes = outputStream.toByteArray()
Base64.encodeToString(bytes, Base64.DEFAULT)
} catch (e: IOException) {
""
}
}
}
} | mit | dc4efd5d1fb802dcf8f0902911391e8e | 29.102564 | 96 | 0.612958 | 4.82716 | false | false | false | false |
robinverduijn/gradle | buildSrc/subprojects/plugins/src/main/kotlin/org/gradle/plugins/performance/BuildCommitDistribution.kt | 1 | 3824 | /*
* Copyright 2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gradle.plugins.performance
import org.gradle.api.DefaultTask
import org.gradle.api.internal.GradleInternal
import org.gradle.api.tasks.Input
import org.gradle.api.tasks.Optional
import org.gradle.api.tasks.OutputDirectory
import org.gradle.api.tasks.OutputFile
import org.gradle.api.tasks.TaskAction
import org.gradle.caching.http.HttpBuildCache
import org.gradle.kotlin.dsl.*
import org.gradle.testing.performance.generator.tasks.RemoteProject
import java.io.File
// 5.1-commit-1a2b3c4d5e
private
val commitVersionRegex = """(\d+(\.\d+)+)-commit-[a-f0-9]+""".toRegex()
open class BuildCommitDistribution : DefaultTask() {
@Input
@Optional
val commitBaseline = project.objects.property<String>()
@OutputDirectory
val commitDistributionHome = project.objects.directoryProperty()
@OutputFile
val commitDistributionToolingApiJar = project.objects.fileProperty()
init {
onlyIf { commitBaseline.getOrElse("").matches(commitVersionRegex) }
commitDistributionHome.set(project.rootProject.layout.buildDirectory.dir(commitBaseline.map { "distributions/gradle-$it" }))
commitDistributionToolingApiJar.set(project.rootProject.layout.buildDirectory.file(commitBaseline.map { "distributions/gradle-tooling-api-$it.jar" }))
}
@TaskAction
fun buildCommitDistribution() {
val rootProjectDir = project.rootProject.rootDir.absolutePath
val commit = commitBaseline.map { it.substring(it.lastIndexOf('-') + 1) }
tryBuildDistribution(RemoteProject.checkout(this, rootProjectDir, commit.orNull, null))
println("Building the commit distribution succeeded, now the baseline is ${commitBaseline.get()}")
}
private
fun tryBuildDistribution(checkoutDir: File) {
project.exec({
commandLine(*getBuildCommands(checkoutDir))
workingDir = checkoutDir
})
}
private
fun getBuildCommands(checkoutDir: File): Array<String> {
project.delete(commitDistributionHome.get().asFile)
val buildCommands = mutableListOf(
"./gradlew",
"--init-script",
File(checkoutDir, "gradle/init-scripts/build-scan.init.gradle.kts").absolutePath,
"clean",
":install",
"-Pgradle_installPath=" + commitDistributionHome.get().asFile.absolutePath,
":toolingApi:installToolingApiShadedJar",
"-PtoolingApiShadedJarInstallPath=" + commitDistributionToolingApiJar.get().asFile.absolutePath)
if (project.gradle.startParameter.isBuildCacheEnabled) {
buildCommands.add("--build-cache")
val buildCacheConf = (project.gradle as GradleInternal).settings.buildCache
val remoteCache = buildCacheConf.remote as HttpBuildCache?
if (remoteCache?.url != null) {
buildCommands.add("-Dgradle.cache.remote.url=${remoteCache.url}")
buildCommands.add("-Dgradle.cache.remote.username=${remoteCache.credentials.username}")
buildCommands.add("-Dgradle.cache.remote.password=${remoteCache.credentials.password}")
}
}
return buildCommands.toTypedArray()
}
}
| apache-2.0 | 600de4574e2ab3f7b76ece81a25ad6f1 | 38.42268 | 158 | 0.706067 | 4.380298 | false | false | false | false |
tmarsteel/compiler-fiddle | test/compiler/ast/type/utils.kt | 1 | 1097 | /*
* Copyright 2018 Tobias Marstaller
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License
* as published by the Free Software Foundation; either version 3
* of the License, or (at your option) any later version.
*
* 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 Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
package compiler.ast.type
import compiler.binding.type.BaseType
fun fakeType(name: String, vararg superTypes: BaseType): BaseType = object: BaseType {
override fun toString() = name
override val superTypes = superTypes.toSet()
override val simpleName = name
override val fullyQualifiedName = name
} | lgpl-3.0 | 62592560d7ba2755e85cd064f6126e6c | 38.214286 | 86 | 0.751139 | 4.423387 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.