repo_name
stringlengths 7
81
| path
stringlengths 6
242
| copies
stringclasses 55
values | size
stringlengths 2
6
| content
stringlengths 55
737k
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 5.44
99.8
| line_max
int64 15
979
| alpha_frac
float64 0.3
0.91
| ratio
float64 2
9.93
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
mdaniel/intellij-community | plugins/ide-features-trainer/src/training/ui/MessageFactory.kt | 1 | 4764 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package training.ui
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.util.JDOMUtil
import com.intellij.openapi.util.text.Strings
import org.intellij.lang.annotations.Language
import org.jdom.Element
import org.jdom.Text
import org.jdom.output.XMLOutputter
import training.dsl.LessonUtil
import training.util.KeymapUtil
import training.util.openLinkInBrowser
import java.util.regex.Pattern
import javax.swing.KeyStroke
internal object MessageFactory {
private val LOG = Logger.getInstance(MessageFactory::class.java)
fun setLinksHandlers(messageParts: List<MessagePart>) {
for (message in messageParts) {
if (message.type == MessagePart.MessageType.LINK && message.runnable == null) {
val link = message.link
if (link.isNullOrEmpty()) {
LOG.error("No link specified for ${message.text}")
}
else {
message.runnable = Runnable {
try {
openLinkInBrowser(link)
}
catch (e: Exception) {
LOG.warn(e)
}
}
}
}
}
}
fun convert(@Language("HTML") text: String): List<MessagePart> {
return text
.splitToSequence("\n")
.map { paragraph ->
val wrappedText = "<root><text>$paragraph</text></root>"
val textAsElement = JDOMUtil.load(wrappedText.byteInputStream()).getChild("text")
?: throw IllegalStateException("Can't parse as XML:\n$paragraph")
convert(textAsElement)
}
.reduce { acc, item -> acc + MessagePart("\n", MessagePart.MessageType.LINE_BREAK) + item }
}
private fun convert(element: Element?): List<MessagePart> {
if (element == null) {
return emptyList()
}
val list = mutableListOf<MessagePart>()
for (content in element.content) {
if (content is Text) {
var text = content.getValue()
if (Pattern.matches(" *\\p{IsPunctuation}.*", text)) {
val indexOfFirst = text.indexOfFirst { it != ' ' }
text = "\u00A0".repeat(indexOfFirst) + text.substring(indexOfFirst)
}
list.add(MessagePart(text, MessagePart.MessageType.TEXT_REGULAR))
}
else if (content is Element) {
val outputter = XMLOutputter()
var type = MessagePart.MessageType.TEXT_REGULAR
val text: String = Strings.unescapeXmlEntities(outputter.outputString(content.content))
var textAndSplitFn: (() -> Pair<String, List<IntRange>?>)? = null
var link: String? = null
var runnable: Runnable? = null
when (content.name) {
"icon" -> error("Need to return reflection-based icon processing")
"illustration" -> type = MessagePart.MessageType.ILLUSTRATION
"icon_idx" -> type = MessagePart.MessageType.ICON_IDX
"code" -> type = MessagePart.MessageType.CODE
"shortcut" -> type = MessagePart.MessageType.SHORTCUT
"strong" -> type = MessagePart.MessageType.TEXT_BOLD
"callback" -> {
type = MessagePart.MessageType.LINK
val id = content.getAttributeValue("id")
if (id != null) {
val callback = LearningUiManager.getAndClearCallback(id.toInt())
if (callback != null) {
runnable = Runnable { callback() }
}
else {
LOG.error("Unknown callback with id $id and text $text")
}
}
}
"a" -> {
type = MessagePart.MessageType.LINK
link = content.getAttributeValue("href")
}
"action" -> {
type = MessagePart.MessageType.SHORTCUT
link = text
textAndSplitFn = {
val shortcutByActionId = KeymapUtil.getShortcutByActionId(text)
if (shortcutByActionId != null) {
KeymapUtil.getKeyboardShortcutData(shortcutByActionId)
}
else {
KeymapUtil.getGotoActionData(text)
}
}
}
"raw_shortcut" -> {
type = MessagePart.MessageType.SHORTCUT
textAndSplitFn = {
KeymapUtil.getKeyStrokeData(KeyStroke.getKeyStroke(text))
}
}
"ide" -> {
type = MessagePart.MessageType.TEXT_REGULAR
textAndSplitFn = { LessonUtil.productName to null }
}
}
val message = MessagePart(type, textAndSplitFn ?: { text to null })
message.link = link
message.runnable = runnable
list.add(message)
}
}
return list
}
} | apache-2.0 | ed0855fd88d604633bdef8de6dee7abb | 35.098485 | 120 | 0.59152 | 4.675172 | false | false | false | false |
mdaniel/intellij-community | platform/remoteDev-util/src/com/intellij/remoteDev/downloader/JetBrainsClientDownloaderConfigurationProvider.kt | 2 | 7231 | package com.intellij.remoteDev.downloader
import com.intellij.execution.configurations.GeneralCommandLine
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.diagnostic.thisLogger
import com.intellij.openapi.util.SystemInfo
import com.intellij.remoteDev.RemoteDevSystemSettings
import com.intellij.remoteDev.util.getJetBrainsSystemCachesDir
import com.intellij.remoteDev.util.onTerminationOrNow
import com.intellij.util.io.exists
import com.intellij.util.io.inputStream
import com.intellij.util.io.isFile
import com.intellij.util.io.size
import com.jetbrains.rd.util.lifetime.Lifetime
import com.jetbrains.rd.util.reactive.Signal
import com.sun.net.httpserver.HttpHandler
import com.sun.net.httpserver.HttpServer
import org.jetbrains.annotations.ApiStatus
import java.net.Inet4Address
import java.net.InetSocketAddress
import java.net.URI
import java.nio.file.Files
import java.nio.file.Path
import kotlin.io.path.*
// If you want to provide a custom url:
// 1) set TestJetBrainsClientDownloaderConfigurationProvider as serviceImplementation in RemoteDevUtil.xml
// 2) call (service<JetBrainsClientDownloaderConfigurationProvider> as TestJetBrainsClientDownloaderConfigurationProvider)
// .startServerAndServeClient(lifetime, clientDistribution, clientJdkBuildTxt)
@ApiStatus.Experimental
interface JetBrainsClientDownloaderConfigurationProvider {
fun modifyClientCommandLine(clientCommandLine: GeneralCommandLine)
val clientDownloadUrl: URI
val jreDownloadUrl: URI
val clientCachesDir: Path
val verifySignature: Boolean
fun patchVmOptions(vmOptionsFile: Path)
val clientLaunched: Signal<Unit>
}
@ApiStatus.Experimental
class RealJetBrainsClientDownloaderConfigurationProvider : JetBrainsClientDownloaderConfigurationProvider {
override fun modifyClientCommandLine(clientCommandLine: GeneralCommandLine) { }
override val clientDownloadUrl: URI
get() = RemoteDevSystemSettings.getClientDownloadUrl().value
override val jreDownloadUrl: URI
get() = RemoteDevSystemSettings.getJreDownloadUrl().value
override val clientCachesDir: Path get () {
val downloadDestination = IntellijClientDownloaderSystemSettings.getDownloadDestination()
if (downloadDestination.value != null) {
return Path(downloadDestination.value)
}
return getJetBrainsSystemCachesDir() / "JetBrainsClientDist"
}
override val verifySignature: Boolean = true
override fun patchVmOptions(vmOptionsFile: Path) { }
override val clientLaunched: Signal<Unit> = Signal()
}
@ApiStatus.Experimental
class TestJetBrainsClientDownloaderConfigurationProvider : JetBrainsClientDownloaderConfigurationProvider {
var x11DisplayForClient: String? = null
var guestConfigFolder: Path? = null
var guestSystemFolder: Path? = null
var guestLogFolder: Path? = null
var isDebugEnabled = false
var debugSuspendOnStart = false
var debugPort = -1
override fun modifyClientCommandLine(clientCommandLine: GeneralCommandLine) {
x11DisplayForClient?.let {
require(SystemInfo.isLinux) { "X11 display property makes sense only on Linux" }
logger<TestJetBrainsClientDownloaderConfigurationProvider>().info("Setting env var DISPLAY for Guest process=$it")
clientCommandLine.environment["DISPLAY"] = it
}
}
override var clientDownloadUrl: URI = URI("https://download.jetbrains.com/idea/code-with-me/")
override var jreDownloadUrl: URI = URI("https://download.jetbrains.com/idea/jbr/")
override var clientCachesDir: Path = Files.createTempDirectory("")
override var verifySignature: Boolean = true
override val clientLaunched: Signal<Unit> = Signal()
override fun patchVmOptions(vmOptionsFile: Path) {
thisLogger().info("Patching $vmOptionsFile")
val traceCategories = listOf("#com.jetbrains.rdserver.joinLinks", "#com.jetbrains.rd.platform.codeWithMe.network")
val debugOptions = run {
if (isDebugEnabled) {
val suspendOnStart = if (debugSuspendOnStart) "y" else "n"
// changed in Java 9, now we have to use *: to listen on all interfaces
"-agentlib:jdwp=transport=dt_socket,server=y,suspend=$suspendOnStart,address=$debugPort"
}
else ""
}
val testVmOptions = listOf(
"-Djb.consents.confirmation.enabled=false", // hz
"-Djb.privacy.policy.text=\"<!--999.999-->\"", // EULA
"-Didea.initially.ask.config=never",
"-Dfus.internal.test.mode=true",
"-Didea.suppress.statistics.report=true",
"-Drsch.send.usage.stat=false",
"-Duse.linux.keychain=false",
"-Dide.show.tips.on.startup.default.value=false",
"-Didea.is.internal=true",
"-DcodeWithMe.memory.only.certificate=true", // system keychain
"-Dide.slow.operations.assertion=false",
"-Deap.login.enabled=false",
"-Didea.config.path=${guestConfigFolder!!.absolutePathString()}",
"-Didea.system.path=${guestSystemFolder!!.absolutePathString()}",
"-Didea.log.path=${guestLogFolder!!.absolutePathString()}",
"-Didea.log.trace.categories=${traceCategories.joinToString(",")}",
debugOptions).joinToString(separator = "\n", prefix = "\n")
require(vmOptionsFile.isFile() && vmOptionsFile.exists())
val originalContent = vmOptionsFile.readText(Charsets.UTF_8)
thisLogger().info("Original .vmoptions=\n$originalContent")
val patchedContent = originalContent + testVmOptions
thisLogger().info("Patched .vmoptions=$patchedContent")
vmOptionsFile.writeText(patchedContent)
thisLogger().info("Patched $vmOptionsFile successfully")
}
private var tarGzServer: HttpServer? = null
fun mockClientDownloadsServer(lifetime: Lifetime, ipv4Address: InetSocketAddress) : InetSocketAddress {
require(tarGzServer == null)
thisLogger().info("Initializing HTTP server to download distributions as if from outer world")
val server = HttpServer.create(ipv4Address, 0)
thisLogger().info("HTTP server is bound to ${server.address}")
server.createContext("/")
thisLogger().info("Starting http server at ${server.address}")
clientDownloadUrl = URI("http:/${server.address}/")
verifySignature = false
lifetime.onTerminationOrNow {
clientDownloadUrl = URI("INVALID")
verifySignature = true
tarGzServer = null
server.stop(10)
}
server.start()
tarGzServer = server
return server.address
}
fun serveFile(file: Path) {
require(file.exists())
require(file.isFile())
val server = tarGzServer
require(server != null)
server.createContext("/${file.name}", HttpHandler { httpExchange ->
httpExchange.sendResponseHeaders(200, file.size())
httpExchange.responseBody.use { responseBody ->
file.inputStream().use {
it.copyTo(responseBody, 1024 * 1024)
}
}
})
}
@Suppress("unused")
fun startServerAndServeClient(lifetime: Lifetime, clientDistribution: Path, clientJdkBuildTxt: Path) {
require(clientJdkBuildTxt.name.endsWith(".txt")) { "Do not mix-up client archive and client jdk build txt arguments" }
mockClientDownloadsServer(lifetime, InetSocketAddress(Inet4Address.getLoopbackAddress(), 0))
serveFile(clientDistribution)
serveFile(clientJdkBuildTxt)
}
} | apache-2.0 | aec84ac4a91a7e8be6446c18f1d9f4ec | 36.471503 | 122 | 0.749965 | 4.623402 | false | true | false | false |
iPoli/iPoli-android | app/src/main/java/io/ipoli/android/repeatingquest/usecase/CreateRepeatingQuestHistoryUseCase.kt | 1 | 2904 | package io.ipoli.android.repeatingquest.usecase
import io.ipoli.android.common.UseCase
import io.ipoli.android.common.datetime.datesBetween
import io.ipoli.android.common.datetime.isBeforeOrEqual
import io.ipoli.android.quest.data.persistence.QuestRepository
import io.ipoli.android.repeatingquest.persistence.RepeatingQuestRepository
import org.threeten.bp.LocalDate
/**
* Created by Polina Zhelyazkova <[email protected]>
* on 3/2/18.
*/
class CreateRepeatingQuestHistoryUseCase(
private val questRepository: QuestRepository,
private val repeatingQuestRepository: RepeatingQuestRepository
) : UseCase<CreateRepeatingQuestHistoryUseCase.Params, CreateRepeatingQuestHistoryUseCase.History> {
override fun execute(parameters: Params): History {
val start = parameters.start
val end = parameters.end
require(!start.isAfter(end))
val rq = repeatingQuestRepository.findById(parameters.repeatingQuestId)
requireNotNull(rq)
val quests = questRepository.findScheduledForRepeatingQuestInPeriod(rq!!.id, start, end)
val shouldBeCompleteDates = quests.map { it.scheduledDate!! }.toSet()
val completedDates = quests.map { it.completedAtDate }.toSet()
val data = start.datesBetween(end).map {
val shouldBeCompleted = shouldBeCompleteDates.contains(it)
val isCompleted = completedDates.contains(it)
val state = when {
shouldBeCompleted && isCompleted -> DateHistory.DONE_ON_SCHEDULE
!shouldBeCompleted && isCompleted -> DateHistory.DONE_NOT_ON_SCHEDULE
it.isBefore(rq.start) -> DateHistory.BEFORE_START
rq.end != null && it.isAfter(rq.end) -> DateHistory.AFTER_END
it.isEqual(parameters.currentDate) -> DateHistory.TODAY
shouldBeCompleted && !isCompleted && it.isBeforeOrEqual(parameters.currentDate) -> DateHistory.FAILED
it.isBefore(parameters.currentDate) -> DateHistory.SKIPPED
shouldBeCompleted && !isCompleted -> DateHistory.TODO
else -> DateHistory.EMPTY
}
it to state
}.toMap()
return History(
currentDate = parameters.currentDate,
start = start,
end = end,
data = data
)
}
data class Params(
val repeatingQuestId: String,
val start: LocalDate,
val end: LocalDate,
val currentDate: LocalDate = LocalDate.now()
)
enum class DateHistory {
DONE_ON_SCHEDULE,
DONE_NOT_ON_SCHEDULE,
SKIPPED,
FAILED,
TODAY,
BEFORE_START,
AFTER_END,
TODO,
EMPTY
}
data class History(
val currentDate: LocalDate,
val start: LocalDate,
val end: LocalDate,
val data: Map<LocalDate, DateHistory>
)
} | gpl-3.0 | 3280ac0e33a6216d867ef2d871ced56e | 34.426829 | 117 | 0.655303 | 4.872483 | false | false | false | false |
Mystery00/JanYoShare | app/src/main/java/com/janyo/janyoshare/activity/FileTransferConfigureActivity.kt | 1 | 7937 | package com.janyo.janyoshare.activity
import android.app.Dialog
import android.os.Build
import android.os.Bundle
import android.os.Message
import android.support.v4.content.ContextCompat
import android.support.v7.app.AppCompatActivity
import android.support.v7.app.AppCompatDelegate
import android.transition.TransitionInflater
import android.view.Window
import android.widget.Toast
import com.janyo.janyoshare.R
import com.janyo.janyoshare.handler.ReceiveHandler
import com.janyo.janyoshare.handler.SendHandler
import com.janyo.janyoshare.handler.TransferHelperHandler
import com.janyo.janyoshare.util.FileTransferHelper
import com.janyo.janyoshare.util.Settings
import com.janyo.janyoshare.util.SocketUtil
import com.janyo.janyoshare.util.WIFIUtil
import com.zyao89.view.zloading.ZLoadingDialog
import com.zyao89.view.zloading.Z_TYPE
import vip.mystery0.tools.logs.Logs
import kotlinx.android.synthetic.main.content_file_transfer_configure.*
import java.util.concurrent.Executors
class FileTransferConfigureActivity : AppCompatActivity() {
private lateinit var spotsDialog: ZLoadingDialog
private val TAG = "FileTransferConfigureActivity"
private val sendHandler = SendHandler()
private val receiveHandler = ReceiveHandler()
private val socketUtil = SocketUtil()
private val singleThreadPool = Executors.newSingleThreadExecutor()
companion object {
val CREATE_SERVER = 1
val CREATE_CONNECTION = 2
val CONNECTED = 3
val VERIFY_DEVICE = 4
val SCAN_COMPLETE = 5
val VERIFY_ERROR = 6
val VERIFY_DONE = "VERIFY_DONE"
val VERIFY_CANCEL = "VERIFY_CANCEL"
}
override fun onCreate(savedInstanceState: Bundle?) {
if (Settings.getInstance(this).dayNight)
delegate.setLocalNightMode(AppCompatDelegate.MODE_NIGHT_YES)
else
delegate.setLocalNightMode(AppCompatDelegate.MODE_NIGHT_NO)
super.onCreate(savedInstanceState)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
window.requestFeature(Window.FEATURE_CONTENT_TRANSITIONS)
window.exitTransition = TransitionInflater.from(this).inflateTransition(android.R.transition.slide_right)
window.enterTransition = TransitionInflater.from(this).inflateTransition(android.R.transition.slide_left)
window.reenterTransition = TransitionInflater.from(this).inflateTransition(android.R.transition.slide_left)
}
setContentView(R.layout.activity_file_transfer_configure)
spotsDialog = ZLoadingDialog(this)
.setLoadingBuilder(Z_TYPE.CIRCLE_CLOCK)
.setHintText(getString(R.string.hint_upload_log))
.setHintTextSize(16F)
.setCanceledOnTouchOutside(false)
.setLoadingColor(ContextCompat.getColor(this, R.color.colorAccent))
.setHintTextColor(ContextCompat.getColor(this, R.color.colorAccent))
sendHandler.spotsDialog = spotsDialog
sendHandler.context = this
receiveHandler.spotsDialog = spotsDialog
receiveHandler.context = this
FileTransferHelper.getInstance().transferHelperHandler = TransferHelperHandler()
if (intent.getIntExtra("action", 0) == 1) {
FileTransferHelper.getInstance().transferHelperHandler!!.list.clear()
FileTransferHelper.getInstance().transferHelperHandler!!.list.addAll(FileTransferHelper.getInstance().fileList)
openAP()
}
sendFile.setOnClickListener {
openAP()
}
receiveFile.setOnClickListener {
spotsDialog.setHintText(getString(R.string.hint_socket_wait_client))
spotsDialog.show()
val task = singleThreadPool.submit {
WIFIUtil(this, FileTransferHelper.getInstance().verifyPort).scanIP(object : WIFIUtil.ScanListener {
override fun onScan(ipv4: String, socketUtil: SocketUtil) {
val message = Message()
message.what = CREATE_CONNECTION
message.obj = ipv4
receiveHandler.sendMessage(message)
Thread.sleep(100)
val resultMessage = socketUtil.receiveMessage()
if (resultMessage == "null") {
Logs.i(TAG, "onScan: 超时")
val message_error = Message()
message_error.what = VERIFY_ERROR
receiveHandler.sendMessage(message_error)
return
}
val message_verify = Message()
message_verify.what = VERIFY_DEVICE
val map = HashMap<String, Any>()
map.put("message", resultMessage)
map.put("socket", socketUtil)
message_verify.obj = map
receiveHandler.sendMessage(message_verify)
Thread.sleep(100)
}
override fun onError(e: Exception) {
Thread.sleep(100)
}
override fun onFinish(isDeviceFind: Boolean) {
Logs.i(TAG, "onFinish: " + isDeviceFind)
val message = Message()
message.what = SCAN_COMPLETE
message.obj = isDeviceFind
receiveHandler.sendMessage(message)
Thread.sleep(100)
}
})
}
spotsDialog.create().setOnCancelListener {
Logs.i(TAG, "openAP: 监听到返回键")
task.cancel(true)
}
}
}
private fun openAP() {
spotsDialog.setHintText(getString(R.string.hint_socket_wait_server))
spotsDialog.show()
val task = singleThreadPool.submit {
Logs.i(TAG, "openAP: 创建服务端")
val message_create = Message()
message_create.what = CREATE_SERVER
if (!socketUtil.createServerConnection(FileTransferHelper.getInstance().verifyPort)) {
Thread.sleep(100)
Logs.i(TAG, "openAP: 创建服务端失败")
spotsDialog.dismiss()
Toast.makeText(this, R.string.hint_socket_timeout, Toast.LENGTH_SHORT)
.show()
return@submit
}
Thread.sleep(100)
sendHandler.sendMessage(message_create)
Logs.i(TAG, "openAP: 验证设备")
val message_send = Message()
message_send.what = VERIFY_DEVICE
socketUtil.sendMessage(Build.MODEL)
sendHandler.sendMessage(message_send)
Thread.sleep(100)
if (socketUtil.receiveMessage() == VERIFY_DONE) {
Logs.i(TAG, "openAP: 验证完成")
FileTransferHelper.getInstance().ip = socketUtil.socket.remoteSocketAddress.toString().substring(1)
val message = Message.obtain()
message.what = FileTransferConfigureActivity.CONNECTED
sendHandler.sendMessage(message)
Logs.i(TAG, "openAP: 断开验证连接")
socketUtil.clientDisconnect()
socketUtil.serverDisconnect()
} else {
Logs.e(TAG, "openServer: 连接错误")
socketUtil.serverDisconnect()
spotsDialog.dismiss()
}
Thread.sleep(100)
}
spotsDialog.create().setOnCancelListener {
Logs.i(TAG, "openAP: 监听到返回键")
task.cancel(true)
}
}
override fun onDestroy() {
super.onDestroy()
singleThreadPool.shutdown()
}
}
| gpl-3.0 | b44249e100ca8c0cf818352d6cc43d77 | 41.427027 | 123 | 0.602752 | 5.133421 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/formatter/src/org/jetbrains/kotlin/idea/formatter/trailingComma/TrailingCommaState.kt | 4 | 2697 | // 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.formatter.trailingComma
import com.intellij.psi.PsiElement
import org.jetbrains.kotlin.idea.util.containsLineBreakInChild
import org.jetbrains.kotlin.idea.util.isMultiline
import org.jetbrains.kotlin.psi.KtDestructuringDeclaration
import org.jetbrains.kotlin.psi.KtElement
import org.jetbrains.kotlin.psi.KtFunctionLiteral
import org.jetbrains.kotlin.psi.KtWhenEntry
import org.jetbrains.kotlin.psi.psiUtil.endOffset
import org.jetbrains.kotlin.psi.psiUtil.startOffset
enum class TrailingCommaState {
/**
* The trailing comma is needed and exists
*/
EXISTS,
/**
* The trailing comma is needed and doesn't exists
*/
MISSING,
/**
* The trailing comma isn't needed and doesn't exists
*/
NOT_EXISTS,
/**
* The trailing comma isn't needed, but exists
*/
REDUNDANT,
/**
* The trailing comma isn't applicable for this element
*/
NOT_APPLICABLE,
;
companion object {
fun stateForElement(element: PsiElement): TrailingCommaState = when {
element !is KtElement || !element.canAddTrailingComma() -> NOT_APPLICABLE
isMultiline(element) ->
if (TrailingCommaHelper.trailingCommaExists(element))
EXISTS
else
MISSING
else ->
if (TrailingCommaHelper.trailingCommaExists(element))
REDUNDANT
else
NOT_EXISTS
}
}
}
private fun isMultiline(ktElement: KtElement): Boolean = when {
ktElement.parent is KtFunctionLiteral -> isMultiline(ktElement.parent as KtElement)
ktElement is KtFunctionLiteral -> ktElement.isMultiline(
startOffsetGetter = { valueParameterList?.startOffset },
endOffsetGetter = { arrow?.endOffset },
)
ktElement is KtWhenEntry -> ktElement.isMultiline(
startOffsetGetter = { startOffset },
endOffsetGetter = { arrow?.endOffset },
)
ktElement is KtDestructuringDeclaration -> ktElement.isMultiline(
startOffsetGetter = { lPar?.startOffset },
endOffsetGetter = { rPar?.endOffset },
)
else -> ktElement.isMultiline()
}
private fun <T : PsiElement> T.isMultiline(
startOffsetGetter: T.() -> Int?,
endOffsetGetter: T.() -> Int?,
): Boolean {
val startOffset = startOffsetGetter() ?: startOffset
val endOffset = endOffsetGetter() ?: endOffset
return containsLineBreakInChild(startOffset, endOffset)
}
| apache-2.0 | b0627d86d73ec710a6aa6dd8fe386256 | 30 | 158 | 0.667779 | 5.137143 | false | false | false | false |
cleverchap/AutoAnylysis | src/com/cc/io/ZipManager.kt | 1 | 5407 | package com.cc.io
import com.cc.util.logd
import com.cc.util.loge
import com.cc.util.logi
import com.cc.util.logv
import org.apache.tools.tar.TarEntry
import org.apache.tools.tar.TarInputStream
import java.io.*
import java.util.zip.GZIPInputStream
/**
* Created by clevercong on 2017/10/21.
* 压缩/解压缩相关的操作在此。
*/
class ZipManager {
val fileExtensionGz = "gz"
val fileExtensionTarGz = "tar.gz"
/**
* 解压文件总入口,根据后缀的不同调用不同的私有方法,目前正在完善中
* @param sourceDir 文件的路径
* @param outputDir 解压的路径
* @param extension 文件的后缀
*/
fun unzip(sourceDir: String, outputDir: String, extension: String) {
logv("unzip, sourceDir:$sourceDir, outputDir:$outputDir, ext:$extension")
when (extension) {
// 这个地方可能比较奇怪,是因为.tar.gz格式的文件extension字段只能识别为.gz
// 所以.gz格式的按照.tar.gz进行解压缩
// 而我又觉得解压缩.gz的代码来之不易(虽然没有调试过)。不想删啊。万一以后用到了呢。
// 2018.09.02:果然用到了,这里根据sourceDir是否包含tar.gz,用来区分tar.gz和gz的区别
fileExtensionGz ->
if (sourceDir.indexOf(fileExtensionTarGz) != -1) {
// 找到了tar.gz,按照tag.gz的解析
unzipForTarGz(sourceDir, outputDir)
} else {
// 否则按照.gz的来解析
unzipForGz(sourceDir, outputDir)
}
}
}
/**
* 解压GZ文件
* 代码来源:http://www.cnblogs.com/scw2901/p/4379143.html
* 惊人的发现竟然支持剪贴板Java到Kotlin的自动转换。那就不客气了。
* @param sourceDir 压缩文件路径
* @param outputFile 解压的路径
*/
private fun unzipForGz(sourceDir: String, outputFile: String) {
//var outputFile: String
try {
//建立gzip压缩文件输入流
val fin = FileInputStream(sourceDir)
//建立gzip解压工作流
val gzin = GZIPInputStream(fin)
//建立解压文件输出流
//outputFile = sourceDir.substring(0, sourceDir.lastIndexOf('.'))
//outputFile = outputFile.substring(0, outputFile.lastIndexOf('.'))
val fout = FileOutputStream(outputFile)
val buf = ByteArray(1024)
var num: Int = gzin.read(buf, 0, buf.size)
while (num != -1) {
fout.write(buf, 0, num)
num = gzin.read(buf, 0, buf.size)
}
gzin.close()
fout.close()
fin.close()
} catch (ex: Exception) {
ex.printStackTrace()
}
}
/**
* 解压TAR_GZ文件
* @param sourceDir 压缩文件路径
* @param outputDir 输出路径
*/
private fun unzipForTarGz(sourceDir: String, outputDir: String) {
var tarIn: TarInputStream? = null
try {
tarIn = TarInputStream(GZIPInputStream(
BufferedInputStream(FileInputStream(sourceDir))),
1024 * 2)
createDirectory(outputDir, null) // 创建输出目录
var entry: TarEntry? = tarIn.nextEntry
while (entry != null) {
if (entry.isDirectory) { // 是目录
createDirectory(outputDir, entry.name) // 创建空目录
} else { // 是文件
val tmpFile = File(outputDir + "/" + entry.name)
createDirectory(tmpFile.parent + "/", null)//创建输出目录
var out: OutputStream? = null
try {
out = FileOutputStream(tmpFile)
val b = ByteArray(2048)
var length = tarIn.read(b)
while (length != -1) {
out.write(b, 0, length)
length = tarIn.read(b)
}
} catch (ex: IOException) {
ex.printStackTrace()
} finally {
if (out != null) {
out.close()
}
}
}
entry = tarIn.nextEntry
}
logv("解压缩" + sourceDir + "成功!")
} catch (ex: IOException) {
// ex.printStackTrace()
loge("解压缩" + sourceDir + "失败!, ex = " + ex)
} finally {
try {
if (tarIn != null) {
tarIn.close()
}
} catch (ex: IOException) {
// ex.printStackTrace()
loge("关闭TarInputStream失败!, ex = " + ex)
}
}
}
private fun createDirectory(outputDir: String, subDir: String?) {
var file = File(outputDir)
if (!(subDir == null || subDir.trim { it <= ' ' } == "")) { // 子目录不为空
file = File("$outputDir/$subDir")
}
if (!file.exists()) {
if (!file.parentFile.exists())
file.parentFile.mkdirs()
file.mkdirs()
}
}
} | apache-2.0 | 6ee18e38b9a5e495eeecb083eb2c173d | 30.774834 | 81 | 0.491974 | 4.121134 | false | false | false | false |
codebutler/farebot | farebot-app/src/main/java/com/codebutler/farebot/app/core/sample/SampleSubscription.kt | 1 | 1572 | /*
* SampleSubscription.kt
*
* This file is part of FareBot.
* Learn more at: https://codebutler.github.io/farebot/
*
* Copyright (C) 2017 Eric Butler <[email protected]>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.codebutler.farebot.app.core.sample
import android.content.res.Resources
import com.codebutler.farebot.app.core.kotlin.date
import com.codebutler.farebot.transit.Subscription
import java.util.Date
class SampleSubscription : Subscription() {
override fun getId(): Int = 1
override fun getValidFrom(): Date = date(2017, 6)
override fun getValidTo(): Date = date(2017, 7)
override fun getAgencyName(resources: Resources): String = "Municipal Robot Railway"
override fun getShortAgencyName(resources: Resources): String = "Muni"
override fun getMachineId(): Int = 1
override fun getSubscriptionName(resources: Resources): String = "Monthly Pass"
override fun getActivation(): String = ""
}
| gpl-3.0 | 537f7319b9aaee68d9d7c64f86d269cc | 32.446809 | 88 | 0.739186 | 4.104439 | false | false | false | false |
marius-m/wt4 | app/src/main/java/lt/markmerkk/widgets/settings/OAuthAuthorizator.kt | 1 | 8082 | package lt.markmerkk.widgets.settings
import lt.markmerkk.JiraClientProvider
import lt.markmerkk.Tags
import lt.markmerkk.UserSettings
import lt.markmerkk.interactors.JiraBasicApi
import net.rcarz.jiraclient.JiraApi
import org.slf4j.LoggerFactory
import rx.Completable
import rx.Scheduler
import rx.Single
import rx.Subscription
class OAuthAuthorizator(
private val view: View,
private val oAuthInteractor: OAuthInteractor,
private val jiraClientProvider: JiraClientProvider,
private val jiraApi: JiraBasicApi,
private val userSettings: UserSettings,
private val ioScheduler: Scheduler,
private val uiScheduler: Scheduler
) {
private var subsCheckConnection: Subscription? = null
private var subsAuth1: Subscription? = null
private var subsAuth2: Subscription? = null
fun onAttach() {
val jiraUser = userSettings.jiraUser()
if (jiraUser.isEmpty()
|| userSettings.jiraOAuthCreds().isEmpty()) {
view.renderView(AuthViewModel(
showContainerWebview = false,
showContainerStatus = true,
showStatusEmoticon = AuthViewModel.StatusEmoticon.SAD,
textStatus = "No user connected!",
showButtonSetupNew = true
))
} else {
view.renderView(AuthViewModel(
showContainerWebview = false,
showContainerStatus = true,
showStatusEmoticon = AuthViewModel.StatusEmoticon.NEUTRAL,
textStatus = "Welcome '${jiraUser.displayName}'!",
showButtonSetupNew = true
))
}
}
fun onDetach() {
subsCheckConnection?.unsubscribe()
subsAuth1?.unsubscribe()
subsAuth2?.unsubscribe()
view.resetWeb()
}
fun checkAuth() {
subsCheckConnection?.unsubscribe()
subsCheckConnection = jiraApi.jiraUser()
.doOnSuccess { userSettings.changeJiraUser(it.name, it.email, it.displayName, it.accountId) }
.doOnError { userSettings.resetUserData() }
.subscribeOn(ioScheduler)
.observeOn(uiScheduler)
.doOnSubscribe { view.showProgress() }
.doAfterTerminate { view.hideProgress() }
.subscribe({
view.renderView(AuthViewModel(
showContainerWebview = false,
showContainerStatus = true,
showStatusEmoticon = AuthViewModel.StatusEmoticon.HAPPY,
textStatus = "Welcome '${it.displayName}'!",
showButtonSetupNew = false
))
view.accountReady()
}, {
logger.warn("Error trying to establish connection!", it)
view.renderView(AuthViewModel(
showContainerWebview = false,
showContainerStatus = true,
showStatusEmoticon = AuthViewModel.StatusEmoticon.SAD,
textStatus = "Error connecting to JIRA. Press 'Show logs' for more details!",
showButtonSetupNew = true
))
})
}
fun setupAuthStep1() {
logger.debug("Authorization STEP 1")
subsAuth1?.unsubscribe()
userSettings.resetUserData()
subsAuth1 = oAuthInteractor.generateAuthUrl()
.subscribeOn(ioScheduler)
.observeOn(uiScheduler)
.doOnSubscribe { view.showProgress() }
.doOnSuccess { view.hideProgress() }
.doOnError { view.hideProgress() }
.subscribe({
logger.debug("Loading authorization URL")
view.renderView(AuthViewModel(
showContainerWebview = true,
showContainerStatus = false,
showStatusEmoticon = AuthViewModel.StatusEmoticon.NEUTRAL,
textStatus = "",
showButtonSetupNew = false
))
view.loadAuthWeb(it)
}, {
logger.debug("Error trying to generate token for authorization", it)
view.renderView(AuthViewModel(
showContainerWebview = false,
showContainerStatus = true,
showStatusEmoticon = AuthViewModel.StatusEmoticon.SAD,
textStatus = "Error generating JIRA token. Press 'Show logs' for more info!",
showButtonSetupNew = true
))
})
}
fun setupAuthStep2(accessTokenKey: String) {
subsAuth2?.unsubscribe()
view.renderView(AuthViewModel(
showContainerWebview = false,
showContainerStatus = true,
showStatusEmoticon = AuthViewModel.StatusEmoticon.NEUTRAL,
textStatus = "Finishing up authorization...",
showButtonSetupNew = false
))
if (accessTokenKey.isEmpty()) {
userSettings.resetUserData()
logger.debug("Error getting access token key")
view.renderView(AuthViewModel(
showContainerWebview = false,
showContainerStatus = true,
showStatusEmoticon = AuthViewModel.StatusEmoticon.SAD,
textStatus = "Error generating JIRA token. Press 'Show logs' for more info",
showButtonSetupNew = true
))
return
}
logger.debug("Success finding '$accessTokenKey'")
subsAuth2 = oAuthInteractor.generateToken(accessTokenKey)
.flatMap {
userSettings.changeOAuthCreds(
tokenSecret = it.tokenSecret,
accessKey = it.accessKey
)
Single.just(jiraClientProvider.newClient())
}.flatMap { jiraApi.jiraUser() }
.doOnSuccess { userSettings.changeJiraUser(it.name, it.email, it.displayName, it.accountId) }
.doOnError { userSettings.resetUserData() }
.subscribeOn(ioScheduler)
.observeOn(uiScheduler)
.doOnSubscribe { view.showProgress() }
.doAfterTerminate { view.hideProgress() }
.subscribe({
logger.debug("Success running authorization, found projects: $it")
view.renderView(AuthViewModel(
showContainerWebview = false,
showContainerStatus = true,
showStatusEmoticon = AuthViewModel.StatusEmoticon.HAPPY,
textStatus = "Welcome '${it.displayName}'!",
showButtonSetupNew = false
))
view.accountReady()
}, {
logger.warn("Error finalizing JIRA token export!", it)
view.renderView(AuthViewModel(
showContainerWebview = false,
showContainerStatus = true,
showStatusEmoticon = AuthViewModel.StatusEmoticon.SAD,
textStatus = "Error generating JIRA token. Press 'Show logs' for more info",
showButtonSetupNew = true
))
})
}
interface View {
fun accountReady()
fun renderView(authViewModel: AuthViewModel)
fun showProgress()
fun hideProgress()
fun loadAuthWeb(url: String)
fun resetWeb()
}
companion object {
private val logger = LoggerFactory.getLogger(Tags.JIRA)!!
}
}
| apache-2.0 | 317545531e06dd21e64b46febdb32e14 | 41.536842 | 109 | 0.535635 | 6.528271 | false | false | false | false |
ForgetAll/GankKotlin | app/src/main/java/com/xiasuhuei321/gankkotlin/base/BaseToolbarActivity.kt | 1 | 1411 | package com.xiasuhuei321.gankkotlin.base
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import com.xiasuhuei321.gankkotlin.R
import kotlinx.android.synthetic.main.activity_base_toolbar.*
open class BaseToolbarActivity : BaseActivity() {
override val initBySelf: Boolean
get() = true
override val hideActionBar: Boolean
get() = true
var total = 0
var current = 0
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
super.setContentView(R.layout.activity_base_toolbar)
setSupportActionBar(toolbar)
}
override fun setContentView(layoutResID: Int) {
val v = LayoutInflater.from(this).inflate(layoutResID, rootLl, false)
rootLl.addView(v)
initView()
}
protected fun setBackBtn() {
supportActionBar?.setDisplayHomeAsUpEnabled(true)
toolbar.setNavigationOnClickListener {
onBackPressed()
}
}
protected fun initToolbar(title: String) {
supportActionBar?.title = title
}
protected fun initCountTv(total: Int) {
countTv.visibility = View.VISIBLE
this.total = total
setCurrent(current, total)
}
protected fun setCurrent(current: Int, total: Int = this.total) {
this.current = current
countTv.text = "${current} / ${total}"
}
} | apache-2.0 | 5175addada06bc2251154d8d3871d6d1 | 26.153846 | 77 | 0.671155 | 4.536977 | false | false | false | false |
ktorio/ktor | ktor-utils/common/src/io/ktor/util/converters/ConversionService.kt | 1 | 3856 | /*
* Copyright 2014-2021 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license.
*/
package io.ktor.util.converters
import io.ktor.util.reflect.*
import kotlin.reflect.*
/**
* Data conversion service that does serialization and deserialization to/from list of strings
*/
public interface ConversionService {
/**
* Deserialize [values] to an instance of [type]
*/
public fun fromValues(values: List<String>, type: TypeInfo): Any?
/**
* Serialize a [value] to values list
*/
public fun toValues(value: Any?): List<String>
}
/**
* The default conversion service that supports only basic types and enums
*/
public object DefaultConversionService : ConversionService {
override fun toValues(value: Any?): List<String> {
if (value == null) {
return emptyList()
}
val converted = platformDefaultToValues(value)
if (converted != null) {
return converted
}
return when (value) {
is Iterable<*> -> value.flatMap { toValues(it) }
else -> {
when (val klass = value::class) {
Int::class,
Float::class,
Double::class,
Long::class,
Short::class,
Char::class,
Boolean::class,
String::class -> listOf(value.toString())
else -> throw DataConversionException(
"Class $klass is not supported in default data conversion service"
)
}
}
}
}
override fun fromValues(values: List<String>, type: TypeInfo): Any? {
if (values.isEmpty()) {
return null
}
if (type.type == List::class || type.type == MutableList::class) {
val argumentType = type.kotlinType?.arguments?.single()?.type?.classifier as? KClass<*>
if (argumentType != null) {
return values.map { fromValue(it, argumentType) }
}
}
when {
values.isEmpty() ->
throw DataConversionException("There are no values when trying to construct single value $type")
values.size > 1 ->
throw DataConversionException("There are multiple values when trying to construct single value $type")
else -> return fromValue(values.single(), type.type)
}
}
public fun fromValue(value: String, klass: KClass<*>): Any {
val converted = convertPrimitives(klass, value)
if (converted != null) {
return converted
}
val platformConverted = platformDefaultFromValues(value, klass)
if (platformConverted != null) {
return platformConverted
}
throwConversionException(klass.toString())
}
private fun convertPrimitives(klass: KClass<*>, value: String) = when (klass) {
Int::class -> value.toInt()
Float::class -> value.toFloat()
Double::class -> value.toDouble()
Long::class -> value.toLong()
Short::class -> value.toShort()
Char::class -> value.single()
Boolean::class -> value.toBoolean()
String::class -> value
else -> null
}
private fun throwConversionException(typeName: String): Nothing {
throw DataConversionException("Type $typeName is not supported in default data conversion service")
}
}
internal expect fun platformDefaultFromValues(value: String, klass: KClass<*>): Any?
internal expect fun platformDefaultToValues(value: Any): List<String>?
/**
* Thrown when failed to convert value
*/
public open class DataConversionException(message: String = "Invalid data format") : Exception(message)
| apache-2.0 | e677eafd70d28bfb6b2e9e5b684d079a | 32.241379 | 119 | 0.586618 | 4.930946 | false | false | false | false |
chiclaim/android-sample | language-kotlin/kotlin-sample/kotlin-in-action/src/generic/GenericVariance.kt | 1 | 3830 | package generic
import generic.java_generic.bean.Apple
import generic.java_generic.bean.Food
import generic.java_generic.bean.Fruit
import generic.java_generic.bean.Pear
/**
* Desc: Kotlin泛型协变(out)、逆变(in)
*
* <p>
*
* 关于Java泛型的协变、逆变可以查看JavaGenericWildcardTest里面有详细的介绍
*
* Kotlin同样也有泛型的协变、逆变,他们之间的概念是一致的,但是在声明上有些差异:
*
* Java是在声明变量的时候声明泛型协变、逆变的,不能再声明类的时候声明泛型协变、逆变(如Collections.copy函数源码)
*
* Kotlin是在声明类的时候声明泛型协变和逆变的,然后在类里使用的泛型的时候就不用声明泛型协变了;也可以在声明变量的时候声明泛型协变
*
* <p>
*
*
*
* Created by Chiclaim on 2018/10/10.
*/
fun takeFruit(fruits: List<Fruit>) {
}
fun testGenericNumber2(numbers: MutableList<Number>) {
}
fun main(args: Array<String>) {
val foods: List<Food> = listOf(Food(), Food())
val fruits: List<Fruit> = listOf(Fruit(), Fruit())
val apples: List<Apple> = listOf(Apple(), Apple())
val pears: List<Pear> = listOf(Pear(), Pear())
//public interface List<out E>
//out修饰的泛型是 泛型协变 covariant
//像这样的类或接口如List,称之为协变(covariant)类(接口)
//和Java一样,协变泛型不能传递父类类型,只能传递Fruit或者它的子类
//takeFruit(foods) 编译报错
takeFruit(fruits)
takeFruit(apples)
takeFruit(pears)
//-------------------------------------
// 根据上面的介绍发现List是协变类
// 我们在来看下MutableList是否是协变类
val ints2: MutableList<Int> = mutableListOf(1, 3, 4)
//并不能成功传递参数,所以MutableList并不是一个协变类(invariant)
//testGenericNumber2(ints2)
//-------------------------------------
//我们分别来看下协变类List和非协变类MutableList的源码声明
//在声明类的时候使用协变、逆变
//Kotlin List是一个泛型协变
//public interface List<out E>
//MutableList是一个invariant
//public interface MutableList<E> : List<E>
//-------------------------------------
val foodComparator = Comparator<Food> { e1, e2 ->
e1.hashCode() - e2.hashCode()
}
val fruitComparator = Comparator<Fruit> { e1, e2 ->
e1.hashCode() - e2.hashCode()
}
val appleComparator = Comparator<Apple> { e1, e2 ->
e1.hashCode() - e2.hashCode()
}
val list = listOf(Fruit(), Fruit(), Fruit(), Fruit())
//来看下sortedWith方法的声明sortedWith(comparator: Comparator<in T>)
//Comparator声明成了逆变(contravariant),这和Java的泛型通配符super一样的
//所以只能传递Fruit以及Fruit父类的Comparator
list.sortedWith(foodComparator)
list.sortedWith(fruitComparator)
//list.sortedWith(appleComparator) 编译报错
//掌握了Java泛型通配符,也会很快掌握Kotlin的泛型协变和逆变
//不同的是:Java只能在声明变量用到泛型的地方使用泛型变异,称之为use-site variance
//Kotlin不仅支持use-site variance还支持 declaration-site variance
//declaration-site variance 就是在声明类的时候声明泛型变异,如上面使用的Kotlin List就是在定义类的时候声明泛型变异
//在下面的copyData和sortedWith都是use-site variance,即在用到的时候定义泛型变异
}
//也可以在声明泛型变量的时候使用协变、逆变
fun <T> copyData(source: MutableList<out T>,
destination: MutableList<T>) {
for (item in source) {
destination.add(item)
}
}
public fun <T> sortedWith(comparator: Comparator<in T>) {
}
| apache-2.0 | 397f4ce4554198f2f6db78833164f91f | 25.314815 | 80 | 0.669951 | 3.072432 | false | false | false | false |
inorichi/mangafeed | app/src/main/java/eu/kanade/tachiyomi/ui/base/controller/BaseController.kt | 2 | 4599 | package eu.kanade.tachiyomi.ui.base.controller
import android.os.Bundle
import android.view.LayoutInflater
import android.view.MenuItem
import android.view.View
import android.view.ViewGroup
import androidx.appcompat.app.AppCompatActivity
import androidx.viewbinding.ViewBinding
import com.bluelinelabs.conductor.Controller
import com.bluelinelabs.conductor.ControllerChangeHandler
import com.bluelinelabs.conductor.ControllerChangeType
import eu.kanade.tachiyomi.util.system.logcat
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.MainScope
import kotlinx.coroutines.cancel
abstract class BaseController<VB : ViewBinding>(bundle: Bundle? = null) : Controller(bundle) {
protected lateinit var binding: VB
private set
lateinit var viewScope: CoroutineScope
init {
addLifecycleListener(
object : LifecycleListener() {
override fun postCreateView(controller: Controller, view: View) {
onViewCreated(view)
}
override fun preCreateView(controller: Controller) {
viewScope = MainScope()
logcat { "Create view for ${controller.instance()}" }
}
override fun preAttach(controller: Controller, view: View) {
logcat { "Attach view for ${controller.instance()}" }
}
override fun preDetach(controller: Controller, view: View) {
logcat { "Detach view for ${controller.instance()}" }
}
override fun preDestroyView(controller: Controller, view: View) {
viewScope.cancel()
logcat { "Destroy view for ${controller.instance()}" }
}
}
)
}
abstract fun createBinding(inflater: LayoutInflater): VB
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup, savedViewState: Bundle?): View {
binding = createBinding(inflater)
return binding.root
}
open fun onViewCreated(view: View) {}
override fun onChangeStarted(handler: ControllerChangeHandler, type: ControllerChangeType) {
if (type.isEnter) {
setTitle()
setHasOptionsMenu(true)
}
super.onChangeStarted(handler, type)
}
open fun getTitle(): String? {
return null
}
fun setTitle(title: String? = null) {
var parentController = parentController
while (parentController != null) {
if (parentController is BaseController<*> && parentController.getTitle() != null) {
return
}
parentController = parentController.parentController
}
(activity as? AppCompatActivity)?.supportActionBar?.title = title ?: getTitle()
}
private fun Controller.instance(): String {
return "${javaClass.simpleName}@${Integer.toHexString(hashCode())}"
}
/**
* Workaround for buggy menu item layout after expanding/collapsing an expandable item like a SearchView.
* This method should be removed when fixed upstream.
* Issue link: https://issuetracker.google.com/issues/37657375
*/
var expandActionViewFromInteraction = false
fun MenuItem.fixExpand(onExpand: ((MenuItem) -> Boolean)? = null, onCollapse: ((MenuItem) -> Boolean)? = null) {
setOnActionExpandListener(
object : MenuItem.OnActionExpandListener {
override fun onMenuItemActionExpand(item: MenuItem): Boolean {
return onExpand?.invoke(item) ?: true
}
override fun onMenuItemActionCollapse(item: MenuItem): Boolean {
activity?.invalidateOptionsMenu()
return onCollapse?.invoke(item) ?: true
}
}
)
if (expandActionViewFromInteraction) {
expandActionViewFromInteraction = false
expandActionView()
}
}
/**
* Workaround for menu items not disappearing when expanding an expandable item like a SearchView.
* [expandActionViewFromInteraction] should be set to true in [onOptionsItemSelected] when the expandable item is selected
* This method should be called as part of [MenuItem.OnActionExpandListener.onMenuItemActionExpand]
*/
open fun invalidateMenuOnExpand(): Boolean {
return if (expandActionViewFromInteraction) {
activity?.invalidateOptionsMenu()
false
} else {
true
}
}
}
| apache-2.0 | 5cc4737ffbc5181e6b410f4af6d4eac7 | 33.840909 | 126 | 0.634051 | 5.629131 | false | false | false | false |
dahlstrom-g/intellij-community | uast/uast-common/src/org/jetbrains/uast/values/UPhiValue.kt | 15 | 1304 | // Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.uast.values
class UPhiValue private constructor(val values: Set<UValue>) : UValueBase() {
override val dependencies: Set<UDependency> = values.flatMapTo(linkedSetOf()) { it.dependencies }
override fun equals(other: Any?): Boolean = other is UPhiValue && values == other.values
override fun hashCode(): Int = values.hashCode()
override fun toString(): String = values.joinToString(prefix = "Phi(", postfix = ")", separator = ", ")
override val reachable: Boolean
get() = values.any { it.reachable }
companion object {
private const val PHI_LIMIT = 4
fun create(values: Iterable<UValue>): UValue {
val flattenedValues = values.flatMapTo(linkedSetOf<UValue>()) { (it as? UPhiValue)?.values ?: listOf(it) }
if (flattenedValues.size <= 1) {
throw AssertionError("UPhiValue should contain two or more values: $flattenedValues")
}
if (flattenedValues.size > PHI_LIMIT || UUndeterminedValue in flattenedValues) {
return UUndeterminedValue
}
return UPhiValue(flattenedValues)
}
fun create(vararg values: UValue): UValue = create(values.asIterable())
}
}
| apache-2.0 | f403024aad41c9ed0625c5c1dbab8622 | 37.352941 | 140 | 0.697853 | 4.317881 | false | false | false | false |
PaulWoitaschek/MaterialAudiobookPlayer | app/src/test/java/de/ph1b/audiobook/features/bookOverview/list/header/BookOverviewCategoryTest.kt | 1 | 1135 | package de.ph1b.audiobook.features.bookOverview.list.header
import com.google.common.truth.Truth.assertThat
import de.ph1b.audiobook.BookFactory
import org.junit.Test
class BookOverviewCategoryTest {
@Test
fun finished() {
val book = BookFactory.create().updateContent {
updateSettings {
val lastChapter = chapters.last()
copy(currentFile = lastChapter.file, positionInChapter = lastChapter.duration)
}
}
assertThat(book.category).isEqualTo(BookOverviewCategory.FINISHED)
}
@Test
fun notStarted() {
val book = BookFactory.create().updateContent {
updateSettings {
val firstChapter = chapters.first()
copy(currentFile = firstChapter.file, positionInChapter = 0)
}
}
assertThat(book.category).isEqualTo(BookOverviewCategory.NOT_STARTED)
}
@Test
fun current() {
val book = BookFactory.create().updateContent {
updateSettings {
val lastChapter = chapters.last()
copy(currentFile = lastChapter.file, positionInChapter = 0)
}
}
assertThat(book.category).isEqualTo(BookOverviewCategory.CURRENT)
}
}
| lgpl-3.0 | f14d3863e46e998231f7fc28a861b6fc | 26.682927 | 86 | 0.697797 | 4.595142 | false | true | false | false |
google/intellij-community | plugins/kotlin/base/compiler-configuration/src/org/jetbrains/kotlin/idea/compiler/configuration/BaseKotlinCompilerSettings.kt | 6 | 4678 | // 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.compiler.configuration
import com.intellij.openapi.components.PersistentStateComponent
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.Comparing
import com.intellij.openapi.util.JDOMUtil
import com.intellij.util.ReflectionUtil
import com.intellij.util.messages.Topic
import com.intellij.util.xmlb.Accessor
import com.intellij.util.xmlb.SerializationFilterBase
import com.intellij.util.xmlb.XmlSerializer
import org.jdom.Element
import org.jetbrains.kotlin.cli.common.arguments.*
import kotlin.reflect.KClass
abstract class BaseKotlinCompilerSettings<T : Freezable> protected constructor(private val project: Project) :
PersistentStateComponent<Element>, Cloneable {
// Based on com.intellij.util.xmlb.SkipDefaultValuesSerializationFilters
private object DefaultValuesFilter : SerializationFilterBase() {
private val defaultBeans = HashMap<Class<*>, Any>()
private fun createDefaultBean(beanClass: Class<Any>): Any {
return ReflectionUtil.newInstance(beanClass).apply {
if (this is K2JSCompilerArguments) {
sourceMapPrefix = ""
}
}
}
private fun getDefaultValue(accessor: Accessor, bean: Any): Any? {
if (bean is K2JSCompilerArguments && accessor.name == K2JSCompilerArguments::sourceMapEmbedSources.name) {
return if (bean.sourceMap) K2JsArgumentConstants.SOURCE_MAP_SOURCE_CONTENT_INLINING else null
}
val beanClass = bean.javaClass
val defaultBean = defaultBeans.getOrPut(beanClass) { createDefaultBean(beanClass) }
return accessor.read(defaultBean)
}
override fun accepts(accessor: Accessor, bean: Any, beanValue: Any?): Boolean {
val defValue = getDefaultValue(accessor, bean)
return if (defValue is Element && beanValue is Element) {
!JDOMUtil.areElementsEqual(beanValue, defValue)
} else {
!Comparing.equal(beanValue, defValue)
}
}
}
@Suppress("LeakingThis")
private var _settings: T = createSettings().frozen()
private set(value) {
field = value.frozen()
}
var settings: T
get() = _settings
set(value) {
val oldSettings = _settings
validateNewSettings(value)
_settings = value
KotlinCompilerSettingsTracker.getInstance(project).incModificationCount()
project.messageBus.syncPublisher(KotlinCompilerSettingsListener.TOPIC).settingsChanged(
oldSettings = oldSettings,
newSettings = _settings,
)
}
fun update(changer: T.() -> Unit) {
settings = settings.unfrozen().apply { changer() }
}
protected fun validateInheritedFieldsUnchanged(settings: T) {
@Suppress("UNCHECKED_CAST")
val inheritedProperties = collectProperties(settings::class as KClass<T>, true)
val defaultInstance = createSettings()
val invalidFields = inheritedProperties.filter { it.get(settings) != it.get(defaultInstance) }
if (invalidFields.isNotEmpty()) {
throw IllegalArgumentException("Following fields are expected to be left unchanged in ${settings.javaClass}: ${invalidFields.joinToString { it.name }}")
}
}
protected open fun validateNewSettings(settings: T) {}
protected abstract fun createSettings(): T
override fun getState() = XmlSerializer.serialize(_settings, DefaultValuesFilter)
override fun loadState(state: Element) {
_settings = ReflectionUtil.newInstance(_settings.javaClass).apply {
if (this is CommonCompilerArguments) {
freeArgs = mutableListOf()
internalArguments = mutableListOf()
}
XmlSerializer.deserializeInto(this, state)
}
KotlinCompilerSettingsTracker.getInstance(project).incModificationCount()
project.messageBus.syncPublisher(KotlinCompilerSettingsListener.TOPIC).settingsChanged(
oldSettings = null,
newSettings = settings,
)
}
public override fun clone(): Any = super.clone()
}
interface KotlinCompilerSettingsListener {
fun <T> settingsChanged(oldSettings: T?, newSettings: T?)
companion object {
@Topic.ProjectLevel
val TOPIC = Topic.create("KotlinCompilerSettingsListener", KotlinCompilerSettingsListener::class.java)
}
}
| apache-2.0 | edfb74f30a67368ce7d674c255f2b0dc | 37.983333 | 164 | 0.674647 | 5.209354 | false | false | false | false |
apoi/quickbeer-next | app/src/main/java/quickbeer/android/feature/beerdetails/BeerDetailsViewModel.kt | 2 | 8354 | /**
* This file is part of QuickBeer.
* Copyright (C) 2017 Antti Poikela <[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 quickbeer.android.feature.beerdetails
import androidx.lifecycle.SavedStateHandle
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import dagger.hilt.android.lifecycle.HiltViewModel
import javax.inject.Inject
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.flow.combineTransform
import kotlinx.coroutines.flow.filterIsInstance
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.flow.firstOrNull
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.take
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import org.threeten.bp.ZonedDateTime
import quickbeer.android.R
import quickbeer.android.data.repository.Accept
import quickbeer.android.data.state.State
import quickbeer.android.domain.beer.Beer
import quickbeer.android.domain.beer.network.BeerTickFetcher
import quickbeer.android.domain.beer.repository.BeerRepository
import quickbeer.android.domain.brewer.Brewer
import quickbeer.android.domain.brewer.repository.BrewerRepository
import quickbeer.android.domain.country.Country
import quickbeer.android.domain.country.repository.CountryRepository
import quickbeer.android.domain.login.LoginManager
import quickbeer.android.domain.style.Style
import quickbeer.android.domain.style.repository.StyleRepository
import quickbeer.android.domain.stylelist.repository.StyleListRepository
import quickbeer.android.feature.beerdetails.model.Address
import quickbeer.android.network.result.ApiResult
import quickbeer.android.util.ResourceProvider
import quickbeer.android.util.ToastProvider
import quickbeer.android.util.ktx.navId
@HiltViewModel
class BeerDetailsViewModel @Inject constructor(
savedStateHandle: SavedStateHandle,
private val loginManager: LoginManager,
private val beerRepository: BeerRepository,
private val brewerRepository: BrewerRepository,
private val styleRepository: StyleRepository,
private val styleListRepository: StyleListRepository,
private val countryRepository: CountryRepository,
private val beerTickFetcher: BeerTickFetcher,
private val resourceProvider: ResourceProvider,
private val toastProvider: ToastProvider
) : ViewModel() {
private val beerId = savedStateHandle.navId()
private val _isLoggedIn = MutableStateFlow(false)
val isLoggedIn: StateFlow<Boolean> = _isLoggedIn
private val _beerState = MutableStateFlow<State<Beer>>(State.Initial)
val beerState: Flow<State<Beer>> = _beerState
private val _brewerState = MutableStateFlow<State<Brewer>>(State.Initial)
val brewerState: Flow<State<Brewer>> = _brewerState
private val _styleState = MutableStateFlow<State<Style>>(State.Initial)
val styleState: Flow<State<Style>> = _styleState
private val _addressState = MutableStateFlow<State<Address>>(State.Initial)
val addressState: Flow<State<Address>> = _addressState
init {
updateAccessedBeer(beerId)
viewModelScope.launch(Dispatchers.IO) {
beerRepository.getStream(beerId, Beer.DetailsDataValidator())
.collectLatest {
_beerState.emit(it)
if (it is State.Success) {
getBrewer(it.value)
getStyle(it.value)
getAddress(it.value)
}
}
}
viewModelScope.launch(Dispatchers.IO) {
loginManager.isLoggedIn.collectLatest { _isLoggedIn.emit(it) }
}
}
private fun updateAccessedBeer(beerId: Int) {
viewModelScope.launch(Dispatchers.IO) {
beerRepository.getStream(beerId, Accept())
.filterIsInstance<State.Success<Beer>>()
.map { it.value }
.take(1)
.collect { beer ->
val accessed = beer.copy(accessed = ZonedDateTime.now())
beerRepository.persist(beer.id, accessed)
}
}
}
private fun updateAccessedBrewer(brewerId: Int) {
viewModelScope.launch(Dispatchers.IO) {
brewerRepository.getStream(brewerId, Accept())
.filterIsInstance<State.Success<Brewer>>()
.map { it.value }
.take(1)
.collect { brewer ->
val accessed = brewer.copy(accessed = ZonedDateTime.now())
brewerRepository.persist(brewer.id, accessed)
}
}
}
private fun getBrewer(beer: Beer) {
if (beer.brewerId == null) return
updateAccessedBrewer(beer.brewerId)
viewModelScope.launch(Dispatchers.IO) {
brewerRepository.getStream(beer.brewerId, Brewer.BasicDataValidator())
.collectLatest(_brewerState::emit)
}
}
private fun getStyle(beer: Beer) {
when {
beer.styleId != null -> getStyle(beer.styleId)
beer.styleName != null -> getStyle(beer.styleName)
}
}
private fun getStyle(styleId: Int) {
viewModelScope.launch(Dispatchers.IO) {
styleRepository.getStream(styleId, Accept())
.collectLatest(_styleState::emit)
}
}
private fun getStyle(styleName: String) {
viewModelScope.launch(Dispatchers.IO) {
styleListRepository.getStream(Accept())
.firstOrNull { it is State.Success }
?.let { if (it is State.Success) it.value else null }
?.firstOrNull { style -> style.name == styleName }
?.let { getStyle(it.id) }
}
}
private fun getAddress(beer: Beer) {
if (beer.brewerId == null || beer.countryId == null) return
val brewer = brewerRepository.getStream(beer.brewerId, Brewer.DetailsDataValidator())
val country = countryRepository.getStream(beer.countryId, Accept())
viewModelScope.launch(Dispatchers.IO) {
brewer.combineTransform(country) { b, c ->
emit(mergeAddress(b, c))
}.collectLatest { _addressState.emit(it) }
}
}
private fun mergeAddress(brewer: State<Brewer>, country: State<Country>): State<Address> {
return if (brewer is State.Success && country is State.Success) {
State.Success(Address.from(brewer.value, country.value))
} else State.Loading()
}
fun tickBeer(tick: Int) {
viewModelScope.launch(Dispatchers.IO) {
val beer = beerRepository.store.get(beerId) ?: error("No beer found!")
val userId = loginManager.userId.first() ?: error("Not logged in!")
val fetchKey = BeerTickFetcher.TickKey(beerId, userId, tick)
val result = beerTickFetcher.fetch(fetchKey)
if (result is ApiResult.Success) {
val update = beer.copy(tickValue = tick, tickDate = ZonedDateTime.now())
beerRepository.persist(beerId, update)
}
val message = when {
result !is ApiResult.Success -> resourceProvider.getString(R.string.tick_failure)
tick > 0 -> resourceProvider.getString(R.string.tick_success).format(beer.name)
else -> resourceProvider.getString(R.string.tick_removed)
}
withContext(Dispatchers.Main) {
toastProvider.showToast(message)
}
}
}
}
| gpl-3.0 | 1cd56704bbfaae5b3dd88be23a919d0a | 37.855814 | 97 | 0.677161 | 4.733144 | false | false | false | false |
google/intellij-community | plugins/github/src/org/jetbrains/plugins/github/ui/component/GHRepositorySelectorComponentFactory.kt | 1 | 2735 | // Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.plugins.github.ui.component
import com.intellij.openapi.ui.ComboBox
import com.intellij.openapi.util.NlsSafe
import com.intellij.ui.*
import com.intellij.util.castSafelyTo
import org.jetbrains.plugins.github.ui.util.GHUIUtil
import org.jetbrains.plugins.github.ui.util.getName
import org.jetbrains.plugins.github.util.GHGitRepositoryMapping
import javax.swing.JList
class GHRepositorySelectorComponentFactory {
fun create(model: ComboBoxWithActionsModel<GHGitRepositoryMapping>): ComboBox<*> {
return ComboBox(model).apply {
renderer = object : ColoredListCellRenderer<ComboBoxWithActionsModel.Item<GHGitRepositoryMapping>>() {
override fun customizeCellRenderer(list: JList<out ComboBoxWithActionsModel.Item<GHGitRepositoryMapping>>,
value: ComboBoxWithActionsModel.Item<GHGitRepositoryMapping>?,
index: Int,
selected: Boolean,
hasFocus: Boolean) {
if (value is ComboBoxWithActionsModel.Item.Wrapper) {
val mapping = value.wrappee.castSafelyTo<GHGitRepositoryMapping>() ?: return
val repositoryName = repositoryName(model, mapping)
val remoteName = mapping.remote.remote.name
append(repositoryName).append(" ").append(remoteName, SimpleTextAttributes.GRAYED_ATTRIBUTES)
}
if (value is ComboBoxWithActionsModel.Item.Action) {
if (model.size == index) border = IdeBorderFactory.createBorder(SideBorder.TOP)
append(value.action.getName())
}
}
}
isUsePreferredSizeAsMinimum = false
isOpaque = false
isSwingPopup = true
}.also {
installSpeedSearch(model, it)
}
}
private fun repositoryName(model: ComboBoxWithActionsModel<GHGitRepositoryMapping>, mapping: GHGitRepositoryMapping): @NlsSafe String {
val allRepositories = model.items.map(GHGitRepositoryMapping::repository)
return GHUIUtil.getRepositoryDisplayName(allRepositories, mapping.repository, true)
}
private fun installSpeedSearch(model: ComboBoxWithActionsModel<GHGitRepositoryMapping>,
comboBox: ComboBox<ComboBoxWithActionsModel.Item<GHGitRepositoryMapping>>) {
ComboboxSpeedSearch.installSpeedSearch(comboBox) {
when (it) {
is ComboBoxWithActionsModel.Item.Wrapper -> repositoryName(model, it.wrappee)
is ComboBoxWithActionsModel.Item.Action -> it.action.getName()
}
}
}
} | apache-2.0 | 2379ea9d52f3636cc31df6912d5ca515 | 47.857143 | 140 | 0.69287 | 5.47 | false | false | false | false |
vhromada/Catalog | core/src/main/kotlin/com/github/vhromada/catalog/mapper/impl/SongMapperImpl.kt | 1 | 1279 | package com.github.vhromada.catalog.mapper.impl
import com.github.vhromada.catalog.common.provider.UuidProvider
import com.github.vhromada.catalog.domain.Song
import com.github.vhromada.catalog.entity.ChangeSongRequest
import com.github.vhromada.catalog.mapper.SongMapper
import org.springframework.stereotype.Component
/**
* A class represents implementation of mapper for songs.
*
* @author Vladimir Hromada
*/
@Component("songMapper")
class SongMapperImpl(
/**
* Provider for UUID
*/
private val uuidProvider: UuidProvider
) : SongMapper {
override fun mapSong(source: Song): com.github.vhromada.catalog.entity.Song {
return com.github.vhromada.catalog.entity.Song(
uuid = source.uuid,
name = source.name,
length = source.length,
note = source.note
)
}
override fun mapSongs(source: List<Song>): List<com.github.vhromada.catalog.entity.Song> {
return source.map { mapSong(source = it) }
}
override fun mapRequest(source: ChangeSongRequest): Song {
return Song(
id = null,
uuid = uuidProvider.getUuid(),
name = source.name!!,
length = source.length!!,
note = source.note
)
}
}
| mit | b3d04ff331dbd693cd0a534559a357e7 | 27.422222 | 94 | 0.655981 | 4.179739 | false | false | false | false |
tiarebalbi/okhttp | okhttp/src/main/kotlin/okhttp3/internal/cache/DiskLruCache.kt | 1 | 35442 | /*
* Copyright (C) 2011 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 okhttp3.internal.cache
import okhttp3.internal.assertThreadHoldsLock
import okhttp3.internal.cache.DiskLruCache.Editor
import okhttp3.internal.closeQuietly
import okhttp3.internal.concurrent.Task
import okhttp3.internal.concurrent.TaskRunner
import okhttp3.internal.deleteContents
import okhttp3.internal.deleteIfExists
import okhttp3.internal.isCivilized
import okhttp3.internal.okHttpName
import okhttp3.internal.platform.Platform
import okhttp3.internal.platform.Platform.Companion.WARN
import okio.BufferedSink
import okio.ExperimentalFileSystem
import okio.FileNotFoundException
import okio.FileSystem
import okio.ForwardingFileSystem
import okio.ForwardingSource
import okio.Path
import okio.Sink
import okio.Source
import okio.blackholeSink
import okio.buffer
import java.io.Closeable
import java.io.EOFException
import java.io.Flushable
import java.io.IOException
/**
* A cache that uses a bounded amount of space on a filesystem. Each cache entry has a string key
* and a fixed number of values. Each key must match the regex `[a-z0-9_-]{1,64}`. Values are byte
* sequences, accessible as streams or files. Each value must be between `0` and `Int.MAX_VALUE`
* bytes in length.
*
* The cache stores its data in a directory on the filesystem. This directory must be exclusive to
* the cache; the cache may delete or overwrite files from its directory. It is an error for
* multiple processes to use the same cache directory at the same time.
*
* This cache limits the number of bytes that it will store on the filesystem. When the number of
* stored bytes exceeds the limit, the cache will remove entries in the background until the limit
* is satisfied. The limit is not strict: the cache may temporarily exceed it while waiting for
* files to be deleted. The limit does not include filesystem overhead or the cache journal so
* space-sensitive applications should set a conservative limit.
*
* Clients call [edit] to create or update the values of an entry. An entry may have only one editor
* at one time; if a value is not available to be edited then [edit] will return null.
*
* * When an entry is being **created** it is necessary to supply a full set of values; the empty
* value should be used as a placeholder if necessary.
*
* * When an entry is being **edited**, it is not necessary to supply data for every value; values
* default to their previous value.
*
* Every [edit] call must be matched by a call to [Editor.commit] or [Editor.abort]. Committing is
* atomic: a read observes the full set of values as they were before or after the commit, but never
* a mix of values.
*
* Clients call [get] to read a snapshot of an entry. The read will observe the value at the time
* that [get] was called. Updates and removals after the call do not impact ongoing reads.
*
* This class is tolerant of some I/O errors. If files are missing from the filesystem, the
* corresponding entries will be dropped from the cache. If an error occurs while writing a cache
* value, the edit will fail silently. Callers should handle other problems by catching
* `IOException` and responding appropriately.
*
* @constructor Create a cache which will reside in [directory]. This cache is lazily initialized on
* first access and will be created if it does not exist.
* @param directory a writable directory.
* @param valueCount the number of values per cache entry. Must be positive.
* @param maxSize the maximum number of bytes this cache should use to store.
*/
@OptIn(ExperimentalFileSystem::class)
class DiskLruCache(
fileSystem: FileSystem,
/** Returns the directory where this cache stores its data. */
val directory: Path,
private val appVersion: Int,
internal val valueCount: Int,
/** Returns the maximum number of bytes that this cache should use to store its data. */
maxSize: Long,
/** Used for asynchronous journal rebuilds. */
taskRunner: TaskRunner
) : Closeable, Flushable {
internal val fileSystem: FileSystem = object : ForwardingFileSystem(fileSystem) {
override fun sink(file: Path): Sink {
file.parent?.let {
// TODO from okhttp3.internal.io.FileSystem
if (!exists(it)) {
createDirectories(it)
}
}
return super.sink(file)
}
}
/** The maximum number of bytes that this cache should use to store its data. */
@get:Synchronized @set:Synchronized var maxSize: Long = maxSize
set(value) {
field = value
if (initialized) {
cleanupQueue.schedule(cleanupTask) // Trim the existing store if necessary.
}
}
/*
* This cache uses a journal file named "journal". A typical journal file looks like this:
*
* libcore.io.DiskLruCache
* 1
* 100
* 2
*
* CLEAN 3400330d1dfc7f3f7f4b8d4d803dfcf6 832 21054
* DIRTY 335c4c6028171cfddfbaae1a9c313c52
* CLEAN 335c4c6028171cfddfbaae1a9c313c52 3934 2342
* REMOVE 335c4c6028171cfddfbaae1a9c313c52
* DIRTY 1ab96a171faeeee38496d8b330771a7a
* CLEAN 1ab96a171faeeee38496d8b330771a7a 1600 234
* READ 335c4c6028171cfddfbaae1a9c313c52
* READ 3400330d1dfc7f3f7f4b8d4d803dfcf6
*
* The first five lines of the journal form its header. They are the constant string
* "libcore.io.DiskLruCache", the disk cache's version, the application's version, the value
* count, and a blank line.
*
* Each of the subsequent lines in the file is a record of the state of a cache entry. Each line
* contains space-separated values: a state, a key, and optional state-specific values.
*
* o DIRTY lines track that an entry is actively being created or updated. Every successful
* DIRTY action should be followed by a CLEAN or REMOVE action. DIRTY lines without a matching
* CLEAN or REMOVE indicate that temporary files may need to be deleted.
*
* o CLEAN lines track a cache entry that has been successfully published and may be read. A
* publish line is followed by the lengths of each of its values.
*
* o READ lines track accesses for LRU.
*
* o REMOVE lines track entries that have been deleted.
*
* The journal file is appended to as cache operations occur. The journal may occasionally be
* compacted by dropping redundant lines. A temporary file named "journal.tmp" will be used during
* compaction; that file should be deleted if it exists when the cache is opened.
*/
private val journalFile: Path
private val journalFileTmp: Path
private val journalFileBackup: Path
private var size: Long = 0L
private var journalWriter: BufferedSink? = null
internal val lruEntries = LinkedHashMap<String, Entry>(0, 0.75f, true)
private var redundantOpCount: Int = 0
private var hasJournalErrors: Boolean = false
private var civilizedFileSystem: Boolean = false
// Must be read and written when synchronized on 'this'.
private var initialized: Boolean = false
internal var closed: Boolean = false
private var mostRecentTrimFailed: Boolean = false
private var mostRecentRebuildFailed: Boolean = false
/**
* To differentiate between old and current snapshots, each entry is given a sequence number each
* time an edit is committed. A snapshot is stale if its sequence number is not equal to its
* entry's sequence number.
*/
private var nextSequenceNumber: Long = 0
private val cleanupQueue = taskRunner.newQueue()
private val cleanupTask = object : Task("$okHttpName Cache") {
override fun runOnce(): Long {
synchronized(this@DiskLruCache) {
if (!initialized || closed) {
return -1L // Nothing to do.
}
try {
trimToSize()
} catch (_: IOException) {
mostRecentTrimFailed = true
}
try {
if (journalRebuildRequired()) {
rebuildJournal()
redundantOpCount = 0
}
} catch (_: IOException) {
mostRecentRebuildFailed = true
journalWriter = blackholeSink().buffer()
}
return -1L
}
}
}
init {
require(maxSize > 0L) { "maxSize <= 0" }
require(valueCount > 0) { "valueCount <= 0" }
this.journalFile = directory / JOURNAL_FILE
this.journalFileTmp = directory / JOURNAL_FILE_TEMP
this.journalFileBackup = directory / JOURNAL_FILE_BACKUP
}
@Synchronized @Throws(IOException::class)
fun initialize() {
this.assertThreadHoldsLock()
if (initialized) {
return // Already initialized.
}
// If a bkp file exists, use it instead.
if (fileSystem.exists(journalFileBackup)) {
// If journal file also exists just delete backup file.
if (fileSystem.exists(journalFile)) {
fileSystem.delete(journalFileBackup)
} else {
fileSystem.atomicMove(journalFileBackup, journalFile)
}
}
civilizedFileSystem = fileSystem.isCivilized(journalFileBackup)
// Prefer to pick up where we left off.
if (fileSystem.exists(journalFile)) {
try {
readJournal()
processJournal()
initialized = true
return
} catch (journalIsCorrupt: IOException) {
Platform.get().log(
"DiskLruCache $directory is corrupt: ${journalIsCorrupt.message}, removing",
WARN,
journalIsCorrupt)
}
// The cache is corrupted, attempt to delete the contents of the directory. This can throw and
// we'll let that propagate out as it likely means there is a severe filesystem problem.
try {
delete()
} finally {
closed = false
}
}
rebuildJournal()
initialized = true
}
@Throws(IOException::class)
private fun readJournal() {
fileSystem.read(journalFile) {
val magic = readUtf8LineStrict()
val version = readUtf8LineStrict()
val appVersionString = readUtf8LineStrict()
val valueCountString = readUtf8LineStrict()
val blank = readUtf8LineStrict()
if (MAGIC != magic ||
VERSION_1 != version ||
appVersion.toString() != appVersionString ||
valueCount.toString() != valueCountString ||
blank.isNotEmpty()) {
throw IOException(
"unexpected journal header: [$magic, $version, $valueCountString, $blank]")
}
var lineCount = 0
while (true) {
try {
readJournalLine(readUtf8LineStrict())
lineCount++
} catch (_: EOFException) {
break // End of journal.
}
}
redundantOpCount = lineCount - lruEntries.size
// If we ended on a truncated line, rebuild the journal before appending to it.
if (!exhausted()) {
rebuildJournal()
} else {
journalWriter = newJournalWriter()
}
}
}
@Throws(FileNotFoundException::class)
private fun newJournalWriter(): BufferedSink {
val fileSink = fileSystem.appendingSink(journalFile)
val faultHidingSink = FaultHidingSink(fileSink) {
[email protected]()
hasJournalErrors = true
}
return faultHidingSink.buffer()
}
@Throws(IOException::class)
private fun readJournalLine(line: String) {
val firstSpace = line.indexOf(' ')
if (firstSpace == -1) throw IOException("unexpected journal line: $line")
val keyBegin = firstSpace + 1
val secondSpace = line.indexOf(' ', keyBegin)
val key: String
if (secondSpace == -1) {
key = line.substring(keyBegin)
if (firstSpace == REMOVE.length && line.startsWith(REMOVE)) {
lruEntries.remove(key)
return
}
} else {
key = line.substring(keyBegin, secondSpace)
}
var entry: Entry? = lruEntries[key]
if (entry == null) {
entry = Entry(key)
lruEntries[key] = entry
}
when {
secondSpace != -1 && firstSpace == CLEAN.length && line.startsWith(CLEAN) -> {
val parts = line.substring(secondSpace + 1)
.split(' ')
entry.readable = true
entry.currentEditor = null
entry.setLengths(parts)
}
secondSpace == -1 && firstSpace == DIRTY.length && line.startsWith(DIRTY) -> {
entry.currentEditor = Editor(entry)
}
secondSpace == -1 && firstSpace == READ.length && line.startsWith(READ) -> {
// This work was already done by calling lruEntries.get().
}
else -> throw IOException("unexpected journal line: $line")
}
}
/**
* Computes the initial size and collects garbage as a part of opening the cache. Dirty entries
* are assumed to be inconsistent and will be deleted.
*/
@Throws(IOException::class)
private fun processJournal() {
fileSystem.deleteIfExists(journalFileTmp)
val i = lruEntries.values.iterator()
while (i.hasNext()) {
val entry = i.next()
if (entry.currentEditor == null) {
for (t in 0 until valueCount) {
size += entry.lengths[t]
}
} else {
entry.currentEditor = null
for (t in 0 until valueCount) {
fileSystem.deleteIfExists(entry.cleanFiles[t])
fileSystem.deleteIfExists(entry.dirtyFiles[t])
}
i.remove()
}
}
}
/**
* Creates a new journal that omits redundant information. This replaces the current journal if it
* exists.
*/
@Synchronized @Throws(IOException::class)
internal fun rebuildJournal() {
journalWriter?.close()
fileSystem.write(journalFileTmp) {
writeUtf8(MAGIC).writeByte('\n'.toInt())
writeUtf8(VERSION_1).writeByte('\n'.toInt())
writeDecimalLong(appVersion.toLong()).writeByte('\n'.toInt())
writeDecimalLong(valueCount.toLong()).writeByte('\n'.toInt())
writeByte('\n'.toInt())
for (entry in lruEntries.values) {
if (entry.currentEditor != null) {
writeUtf8(DIRTY).writeByte(' '.toInt())
writeUtf8(entry.key)
writeByte('\n'.toInt())
} else {
writeUtf8(CLEAN).writeByte(' '.toInt())
writeUtf8(entry.key)
entry.writeLengths(this)
writeByte('\n'.toInt())
}
}
}
if (fileSystem.exists(journalFile)) {
fileSystem.atomicMove(journalFile, journalFileBackup)
fileSystem.atomicMove(journalFileTmp, journalFile)
fileSystem.deleteIfExists(journalFileBackup)
} else {
fileSystem.atomicMove(journalFileTmp, journalFile)
}
journalWriter = newJournalWriter()
hasJournalErrors = false
mostRecentRebuildFailed = false
}
/**
* Returns a snapshot of the entry named [key], or null if it doesn't exist is not currently
* readable. If a value is returned, it is moved to the head of the LRU queue.
*/
@Synchronized @Throws(IOException::class)
operator fun get(key: String): Snapshot? {
initialize()
checkNotClosed()
validateKey(key)
val entry = lruEntries[key] ?: return null
val snapshot = entry.snapshot() ?: return null
redundantOpCount++
journalWriter!!.writeUtf8(READ)
.writeByte(' '.toInt())
.writeUtf8(key)
.writeByte('\n'.toInt())
if (journalRebuildRequired()) {
cleanupQueue.schedule(cleanupTask)
}
return snapshot
}
/** Returns an editor for the entry named [key], or null if another edit is in progress. */
@Synchronized @Throws(IOException::class)
@JvmOverloads
fun edit(key: String, expectedSequenceNumber: Long = ANY_SEQUENCE_NUMBER): Editor? {
initialize()
checkNotClosed()
validateKey(key)
var entry: Entry? = lruEntries[key]
if (expectedSequenceNumber != ANY_SEQUENCE_NUMBER &&
(entry == null || entry.sequenceNumber != expectedSequenceNumber)) {
return null // Snapshot is stale.
}
if (entry?.currentEditor != null) {
return null // Another edit is in progress.
}
if (entry != null && entry.lockingSourceCount != 0) {
return null // We can't write this file because a reader is still reading it.
}
if (mostRecentTrimFailed || mostRecentRebuildFailed) {
// The OS has become our enemy! If the trim job failed, it means we are storing more data than
// requested by the user. Do not allow edits so we do not go over that limit any further. If
// the journal rebuild failed, the journal writer will not be active, meaning we will not be
// able to record the edit, causing file leaks. In both cases, we want to retry the clean up
// so we can get out of this state!
cleanupQueue.schedule(cleanupTask)
return null
}
// Flush the journal before creating files to prevent file leaks.
val journalWriter = this.journalWriter!!
journalWriter.writeUtf8(DIRTY)
.writeByte(' '.toInt())
.writeUtf8(key)
.writeByte('\n'.toInt())
journalWriter.flush()
if (hasJournalErrors) {
return null // Don't edit; the journal can't be written.
}
if (entry == null) {
entry = Entry(key)
lruEntries[key] = entry
}
val editor = Editor(entry)
entry.currentEditor = editor
return editor
}
/**
* Returns the number of bytes currently being used to store the values in this cache. This may be
* greater than the max size if a background deletion is pending.
*/
@Synchronized @Throws(IOException::class)
fun size(): Long {
initialize()
return size
}
@Synchronized @Throws(IOException::class)
internal fun completeEdit(editor: Editor, success: Boolean) {
val entry = editor.entry
check(entry.currentEditor == editor)
// If this edit is creating the entry for the first time, every index must have a value.
if (success && !entry.readable) {
for (i in 0 until valueCount) {
if (!editor.written!![i]) {
editor.abort()
throw IllegalStateException("Newly created entry didn't create value for index $i")
}
if (!fileSystem.exists(entry.dirtyFiles[i])) {
editor.abort()
return
}
}
}
for (i in 0 until valueCount) {
val dirty = entry.dirtyFiles[i]
if (success && !entry.zombie) {
if (fileSystem.exists(dirty)) {
val clean = entry.cleanFiles[i]
fileSystem.atomicMove(dirty, clean)
val oldLength = entry.lengths[i]
// TODO check null behaviour
val newLength = fileSystem.metadata(clean).size ?: 0
entry.lengths[i] = newLength
size = size - oldLength + newLength
}
} else {
fileSystem.deleteIfExists(dirty)
}
}
entry.currentEditor = null
if (entry.zombie) {
removeEntry(entry)
return
}
redundantOpCount++
journalWriter!!.apply {
if (entry.readable || success) {
entry.readable = true
writeUtf8(CLEAN).writeByte(' '.toInt())
writeUtf8(entry.key)
entry.writeLengths(this)
writeByte('\n'.toInt())
if (success) {
entry.sequenceNumber = nextSequenceNumber++
}
} else {
lruEntries.remove(entry.key)
writeUtf8(REMOVE).writeByte(' '.toInt())
writeUtf8(entry.key)
writeByte('\n'.toInt())
}
flush()
}
if (size > maxSize || journalRebuildRequired()) {
cleanupQueue.schedule(cleanupTask)
}
}
/**
* We only rebuild the journal when it will halve the size of the journal and eliminate at least
* 2000 ops.
*/
private fun journalRebuildRequired(): Boolean {
val redundantOpCompactThreshold = 2000
return redundantOpCount >= redundantOpCompactThreshold &&
redundantOpCount >= lruEntries.size
}
/**
* Drops the entry for [key] if it exists and can be removed. If the entry for [key] is currently
* being edited, that edit will complete normally but its value will not be stored.
*
* @return true if an entry was removed.
*/
@Synchronized @Throws(IOException::class)
fun remove(key: String): Boolean {
initialize()
checkNotClosed()
validateKey(key)
val entry = lruEntries[key] ?: return false
val removed = removeEntry(entry)
if (removed && size <= maxSize) mostRecentTrimFailed = false
return removed
}
@Throws(IOException::class)
internal fun removeEntry(entry: Entry): Boolean {
// If we can't delete files that are still open, mark this entry as a zombie so its files will
// be deleted when those files are closed.
if (!civilizedFileSystem) {
if (entry.lockingSourceCount > 0) {
// Mark this entry as 'DIRTY' so that if the process crashes this entry won't be used.
journalWriter?.let {
it.writeUtf8(DIRTY)
it.writeByte(' '.toInt())
it.writeUtf8(entry.key)
it.writeByte('\n'.toInt())
it.flush()
}
}
if (entry.lockingSourceCount > 0 || entry.currentEditor != null) {
entry.zombie = true
return true
}
}
entry.currentEditor?.detach() // Prevent the edit from completing normally.
for (i in 0 until valueCount) {
fileSystem.deleteIfExists(entry.cleanFiles[i])
size -= entry.lengths[i]
entry.lengths[i] = 0
}
redundantOpCount++
journalWriter?.let {
it.writeUtf8(REMOVE)
it.writeByte(' '.toInt())
it.writeUtf8(entry.key)
it.writeByte('\n'.toInt())
}
lruEntries.remove(entry.key)
if (journalRebuildRequired()) {
cleanupQueue.schedule(cleanupTask)
}
return true
}
@Synchronized private fun checkNotClosed() {
check(!closed) { "cache is closed" }
}
/** Force buffered operations to the filesystem. */
@Synchronized @Throws(IOException::class)
override fun flush() {
if (!initialized) return
checkNotClosed()
trimToSize()
journalWriter!!.flush()
}
@Synchronized fun isClosed(): Boolean = closed
/** Closes this cache. Stored values will remain on the filesystem. */
@Synchronized @Throws(IOException::class)
override fun close() {
if (!initialized || closed) {
closed = true
return
}
// Copying for concurrent iteration.
for (entry in lruEntries.values.toTypedArray()) {
if (entry.currentEditor != null) {
entry.currentEditor?.detach() // Prevent the edit from completing normally.
}
}
trimToSize()
journalWriter!!.close()
journalWriter = null
closed = true
}
@Throws(IOException::class)
fun trimToSize() {
while (size > maxSize) {
if (!removeOldestEntry()) return
}
mostRecentTrimFailed = false
}
/** Returns true if an entry was removed. This will return false if all entries are zombies. */
private fun removeOldestEntry(): Boolean {
for (toEvict in lruEntries.values) {
if (!toEvict.zombie) {
removeEntry(toEvict)
return true
}
}
return false
}
/**
* Closes the cache and deletes all of its stored values. This will delete all files in the cache
* directory including files that weren't created by the cache.
*/
@Throws(IOException::class)
fun delete() {
close()
fileSystem.deleteContents(directory)
}
/**
* Deletes all stored values from the cache. In-flight edits will complete normally but their
* values will not be stored.
*/
@Synchronized @Throws(IOException::class)
fun evictAll() {
initialize()
// Copying for concurrent iteration.
for (entry in lruEntries.values.toTypedArray()) {
removeEntry(entry)
}
mostRecentTrimFailed = false
}
private fun validateKey(key: String) {
require(LEGAL_KEY_PATTERN.matches(key)) { "keys must match regex [a-z0-9_-]{1,120}: \"$key\"" }
}
/**
* Returns an iterator over the cache's current entries. This iterator doesn't throw
* `ConcurrentModificationException`, but if new entries are added while iterating, those new
* entries will not be returned by the iterator. If existing entries are removed during iteration,
* they will be absent (unless they were already returned).
*
* If there are I/O problems during iteration, this iterator fails silently. For example, if the
* hosting filesystem becomes unreachable, the iterator will omit elements rather than throwing
* exceptions.
*
* **The caller must [close][Snapshot.close]** each snapshot returned by [Iterator.next]. Failing
* to do so leaks open files!
*/
@Synchronized @Throws(IOException::class)
fun snapshots(): MutableIterator<Snapshot> {
initialize()
return object : MutableIterator<Snapshot> {
/** Iterate a copy of the entries to defend against concurrent modification errors. */
private val delegate = ArrayList(lruEntries.values).iterator()
/** The snapshot to return from [next]. Null if we haven't computed that yet. */
private var nextSnapshot: Snapshot? = null
/** The snapshot to remove with [remove]. Null if removal is illegal. */
private var removeSnapshot: Snapshot? = null
override fun hasNext(): Boolean {
if (nextSnapshot != null) return true
synchronized(this@DiskLruCache) {
// If the cache is closed, truncate the iterator.
if (closed) return false
while (delegate.hasNext()) {
nextSnapshot = delegate.next()?.snapshot() ?: continue
return true
}
}
return false
}
override fun next(): Snapshot {
if (!hasNext()) throw NoSuchElementException()
removeSnapshot = nextSnapshot
nextSnapshot = null
return removeSnapshot!!
}
override fun remove() {
val removeSnapshot = this.removeSnapshot
checkNotNull(removeSnapshot) { "remove() before next()" }
try {
[email protected](removeSnapshot.key())
} catch (_: IOException) {
// Nothing useful to do here. We failed to remove from the cache. Most likely that's
// because we couldn't update the journal, but the cached entry will still be gone.
} finally {
this.removeSnapshot = null
}
}
}
}
/** A snapshot of the values for an entry. */
inner class Snapshot internal constructor(
private val key: String,
private val sequenceNumber: Long,
private val sources: List<Source>,
private val lengths: LongArray
) : Closeable {
fun key(): String = key
/**
* Returns an editor for this snapshot's entry, or null if either the entry has changed since
* this snapshot was created or if another edit is in progress.
*/
@Throws(IOException::class)
fun edit(): Editor? = [email protected](key, sequenceNumber)
/** Returns the unbuffered stream with the value for [index]. */
fun getSource(index: Int): Source = sources[index]
/** Returns the byte length of the value for [index]. */
fun getLength(index: Int): Long = lengths[index]
override fun close() {
for (source in sources) {
source.closeQuietly()
}
}
}
/** Edits the values for an entry. */
inner class Editor internal constructor(internal val entry: Entry) {
internal val written: BooleanArray? = if (entry.readable) null else BooleanArray(valueCount)
private var done: Boolean = false
/**
* Prevents this editor from completing normally. This is necessary either when the edit causes
* an I/O error, or if the target entry is evicted while this editor is active. In either case
* we delete the editor's created files and prevent new files from being created. Note that once
* an editor has been detached it is possible for another editor to edit the entry.
*/
internal fun detach() {
if (entry.currentEditor == this) {
if (civilizedFileSystem) {
completeEdit(this, false) // Delete it now.
} else {
entry.zombie = true // We can't delete it until the current edit completes.
}
}
}
/**
* Returns an unbuffered input stream to read the last committed value, or null if no value has
* been committed.
*/
fun newSource(index: Int): Source? {
synchronized(this@DiskLruCache) {
check(!done)
if (!entry.readable || entry.currentEditor != this || entry.zombie) {
return null
}
return try {
fileSystem.source(entry.cleanFiles[index])
} catch (_: FileNotFoundException) {
null
}
}
}
/**
* Returns a new unbuffered output stream to write the value at [index]. If the underlying
* output stream encounters errors when writing to the filesystem, this edit will be aborted
* when [commit] is called. The returned output stream does not throw IOExceptions.
*/
fun newSink(index: Int): Sink {
synchronized(this@DiskLruCache) {
check(!done)
if (entry.currentEditor != this) {
return blackholeSink()
}
if (!entry.readable) {
written!![index] = true
}
val dirtyFile = entry.dirtyFiles[index]
val sink: Sink
try {
sink = fileSystem.sink(dirtyFile)
} catch (_: FileNotFoundException) {
return blackholeSink()
}
return FaultHidingSink(sink) {
synchronized(this@DiskLruCache) {
detach()
}
}
}
}
/**
* Commits this edit so it is visible to readers. This releases the edit lock so another edit
* may be started on the same key.
*/
@Throws(IOException::class)
fun commit() {
synchronized(this@DiskLruCache) {
check(!done)
if (entry.currentEditor == this) {
completeEdit(this, true)
}
done = true
}
}
/**
* Aborts this edit. This releases the edit lock so another edit may be started on the same
* key.
*/
@Throws(IOException::class)
fun abort() {
synchronized(this@DiskLruCache) {
check(!done)
if (entry.currentEditor == this) {
completeEdit(this, false)
}
done = true
}
}
}
internal inner class Entry internal constructor(
internal val key: String
) {
/** Lengths of this entry's files. */
internal val lengths: LongArray = LongArray(valueCount)
internal val cleanFiles = mutableListOf<Path>()
internal val dirtyFiles = mutableListOf<Path>()
/** True if this entry has ever been published. */
internal var readable: Boolean = false
/** True if this entry must be deleted when the current edit or read completes. */
internal var zombie: Boolean = false
/**
* The ongoing edit or null if this entry is not being edited. When setting this to null the
* entry must be removed if it is a zombie.
*/
internal var currentEditor: Editor? = null
/**
* Sources currently reading this entry before a write or delete can proceed. When decrementing
* this to zero, the entry must be removed if it is a zombie.
*/
internal var lockingSourceCount = 0
/** The sequence number of the most recently committed edit to this entry. */
internal var sequenceNumber: Long = 0
init {
// The names are repetitive so re-use the same builder to avoid allocations.
val fileBuilder = StringBuilder(key).append('.')
val truncateTo = fileBuilder.length
for (i in 0 until valueCount) {
fileBuilder.append(i)
cleanFiles += directory / fileBuilder.toString()
fileBuilder.append(".tmp")
dirtyFiles += directory / fileBuilder.toString()
fileBuilder.setLength(truncateTo)
}
}
/** Set lengths using decimal numbers like "10123". */
@Throws(IOException::class)
internal fun setLengths(strings: List<String>) {
if (strings.size != valueCount) {
throw invalidLengths(strings)
}
try {
for (i in strings.indices) {
lengths[i] = strings[i].toLong()
}
} catch (_: NumberFormatException) {
throw invalidLengths(strings)
}
}
/** Append space-prefixed lengths to [writer]. */
@Throws(IOException::class)
internal fun writeLengths(writer: BufferedSink) {
for (length in lengths) {
writer.writeByte(' '.toInt()).writeDecimalLong(length)
}
}
@Throws(IOException::class)
private fun invalidLengths(strings: List<String>): Nothing {
throw IOException("unexpected journal line: $strings")
}
/**
* Returns a snapshot of this entry. This opens all streams eagerly to guarantee that we see a
* single published snapshot. If we opened streams lazily then the streams could come from
* different edits.
*/
internal fun snapshot(): Snapshot? {
[email protected]()
if (!readable) return null
if (!civilizedFileSystem && (currentEditor != null || zombie)) return null
val sources = mutableListOf<Source>()
val lengths = this.lengths.clone() // Defensive copy since these can be zeroed out.
try {
for (i in 0 until valueCount) {
sources += newSource(i)
}
return Snapshot(key, sequenceNumber, sources, lengths)
} catch (_: FileNotFoundException) {
// A file must have been deleted manually!
for (source in sources) {
source.closeQuietly()
}
// Since the entry is no longer valid, remove it so the metadata is accurate (i.e. the cache
// size.)
try {
removeEntry(this)
} catch (_: IOException) {
}
return null
}
}
private fun newSource(index: Int): Source {
val fileSource = fileSystem.source(cleanFiles[index])
if (civilizedFileSystem) return fileSource
lockingSourceCount++
return object : ForwardingSource(fileSource) {
private var closed = false
override fun close() {
super.close()
if (!closed) {
closed = true
synchronized(this@DiskLruCache) {
lockingSourceCount--
if (lockingSourceCount == 0 && zombie) {
removeEntry(this@Entry)
}
}
}
}
}
}
}
companion object {
@JvmField val JOURNAL_FILE = "journal"
@JvmField val JOURNAL_FILE_TEMP = "journal.tmp"
@JvmField val JOURNAL_FILE_BACKUP = "journal.bkp"
@JvmField val MAGIC = "libcore.io.DiskLruCache"
@JvmField val VERSION_1 = "1"
@JvmField val ANY_SEQUENCE_NUMBER: Long = -1
@JvmField val LEGAL_KEY_PATTERN = "[a-z0-9_-]{1,120}".toRegex()
@JvmField val CLEAN = "CLEAN"
@JvmField val DIRTY = "DIRTY"
@JvmField val REMOVE = "REMOVE"
@JvmField val READ = "READ"
}
}
| apache-2.0 | 55c591e050431fc4ccdbcbf652c1bd97 | 31.786309 | 100 | 0.64954 | 4.616647 | false | false | false | false |
StepicOrg/stepik-android | app/src/main/java/org/stepik/android/view/download/ui/activity/DownloadActivity.kt | 2 | 7479 | package org.stepik.android.view.download.ui.activity
import android.content.Context
import android.content.Intent
import android.content.res.ColorStateList
import android.os.Bundle
import android.view.MenuItem
import androidx.activity.viewModels
import androidx.core.content.ContextCompat
import androidx.core.text.bold
import androidx.core.text.buildSpannedString
import androidx.core.widget.TextViewCompat
import androidx.fragment.app.DialogFragment
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.DividerItemDecoration
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.SimpleItemAnimator
import kotlinx.android.synthetic.main.activity_download.*
import kotlinx.android.synthetic.main.empty_certificates.goToCatalog
import kotlinx.android.synthetic.main.empty_downloading.*
import kotlinx.android.synthetic.main.progress_bar_on_empty_screen.*
import org.stepic.droid.R
import org.stepic.droid.analytic.AmplitudeAnalytic
import org.stepic.droid.base.App
import org.stepic.droid.base.FragmentActivityBase
import org.stepic.droid.persistence.model.DownloadItem
import org.stepic.droid.ui.dialogs.LoadingProgressDialogFragment
import org.stepic.droid.ui.util.initCenteredToolbar
import org.stepic.droid.ui.util.snackbar
import org.stepic.droid.util.ProgressHelper
import org.stepic.droid.util.TextUtil
import org.stepik.android.domain.course.analytic.CourseViewSource
import org.stepik.android.model.Course
import org.stepik.android.presentation.download.DownloadPresenter
import org.stepik.android.presentation.download.DownloadView
import org.stepik.android.view.course_content.ui.dialog.RemoveCachedContentDialog
import org.stepik.android.view.download.ui.adapter.DownloadedCoursesAdapterDelegate
import org.stepik.android.view.ui.delegate.ViewStateDelegate
import ru.nobird.android.ui.adapters.DefaultDelegateAdapter
import ru.nobird.android.view.base.ui.extension.showIfNotExists
import javax.inject.Inject
class DownloadActivity : FragmentActivityBase(), DownloadView, RemoveCachedContentDialog.Callback {
companion object {
private const val MB = 1024 * 1024L
fun createIntent(context: Context): Intent =
Intent(context, DownloadActivity::class.java)
}
@Inject
internal lateinit var viewModelFactory: ViewModelProvider.Factory
private val downloadPresenter: DownloadPresenter by viewModels { viewModelFactory }
private val downloadedCoursesAdapter: DefaultDelegateAdapter<DownloadItem> = DefaultDelegateAdapter()
private val viewStateDelegate =
ViewStateDelegate<DownloadView.State>()
private val progressDialogFragment: DialogFragment =
LoadingProgressDialogFragment.newInstance()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_download)
injectComponent()
initCenteredToolbar(R.string.downloads_title, showHomeButton = true)
downloadedCoursesAdapter += DownloadedCoursesAdapterDelegate(
onItemClick = { screenManager.showCourseModules(this, it.course, CourseViewSource.Downloads) },
onItemRemoveClick = ::showRemoveCourseDialog
)
with(downloadsRecyclerView) {
(itemAnimator as? SimpleItemAnimator)?.supportsChangeAnimations = false
adapter = downloadedCoursesAdapter
layoutManager = LinearLayoutManager(context, LinearLayoutManager.VERTICAL, false)
addItemDecoration(DividerItemDecoration(this@DownloadActivity, LinearLayoutManager.VERTICAL))
}
initViewStateDelegate()
goToCatalog.setOnClickListener { screenManager.showCatalog(this) }
downloadPresenter.fetchStorage()
downloadPresenter.fetchDownloadedCourses()
TextViewCompat.setCompoundDrawableTintList(downloadsOtherApps, ColorStateList.valueOf(ContextCompat.getColor(this, R.color.color_overlay_yellow)))
TextViewCompat.setCompoundDrawableTintList(downloadsStepik, ColorStateList.valueOf(ContextCompat.getColor(this, R.color.color_overlay_green)))
TextViewCompat.setCompoundDrawableTintList(downloadsFree, ColorStateList.valueOf(ContextCompat.getColor(this, R.color.color_elevation_overlay_2dp)))
}
private fun injectComponent() {
App.component()
.downloadComponentBuilder()
.build()
.inject(this)
}
override fun onStart() {
super.onStart()
downloadPresenter.attachView(this)
}
override fun onStop() {
downloadPresenter.detachView(this)
super.onStop()
}
override fun onOptionsItemSelected(item: MenuItem): Boolean =
when (item.itemId) {
android.R.id.home -> {
onBackPressed()
true
}
else ->
super.onOptionsItemSelected(item)
}
private fun initViewStateDelegate() {
viewStateDelegate.addState<DownloadView.State.Idle>()
viewStateDelegate.addState<DownloadView.State.Loading>(loadProgressbarOnEmptyScreen)
viewStateDelegate.addState<DownloadView.State.Empty>(emptyDownloading)
viewStateDelegate.addState<DownloadView.State.DownloadedCoursesLoaded>(downloadStorageContainer, downloadsRecyclerView, downloadsStorageDivider)
}
override fun setState(state: DownloadView.State) {
viewStateDelegate.switchState(state)
if (state is DownloadView.State.DownloadedCoursesLoaded) {
downloadedCoursesAdapter.items = state.courses
}
}
override fun setBlockingLoading(isLoading: Boolean) {
if (isLoading) {
ProgressHelper.activate(progressDialogFragment, supportFragmentManager, LoadingProgressDialogFragment.TAG)
} else {
ProgressHelper.dismiss(supportFragmentManager, LoadingProgressDialogFragment.TAG)
}
}
override fun setStorageInfo(contentSize: Long, avalableSize: Long, totalSize: Long) {
downloadStorageUsed.text = buildSpannedString {
bold { append(TextUtil.formatBytes(contentSize, MB)) }
append(resources.getString(R.string.downloads_is_used_by_stepik))
}
downloadsFree.text = resources.getString(R.string.downloads_free_space, TextUtil.formatBytes(avalableSize, MB))
downloadsStorageProgress.max = (totalSize / MB).toInt()
downloadsStorageProgress.progress = ((totalSize - avalableSize) / MB).toInt()
downloadsStorageProgress.secondaryProgress = (downloadsStorageProgress.progress + (contentSize / MB)).toInt()
}
private fun showRemoveCourseDialog(downloadItem: DownloadItem) {
RemoveCachedContentDialog
.newInstance(course = downloadItem.course)
.showIfNotExists(supportFragmentManager, RemoveCachedContentDialog.TAG)
}
override fun onRemoveCourseDownloadConfirmed(course: Course) {
analytic.reportAmplitudeEvent(
AmplitudeAnalytic.Downloads.DELETED,
mapOf(
AmplitudeAnalytic.Downloads.PARAM_CONTENT to AmplitudeAnalytic.Downloads.Values.COURSE,
AmplitudeAnalytic.Downloads.PARAM_SOURCE to AmplitudeAnalytic.Downloads.Values.DOWNLOADS
)
)
downloadPresenter.removeCourseDownload(course)
}
override fun showRemoveTaskError() {
root.snackbar(messageRes = R.string.downloads_remove_task_error)
}
} | apache-2.0 | ad685c5cab1d735a77e660ba432cd62a | 41.988506 | 156 | 0.750903 | 5.19375 | false | false | false | false |
allotria/intellij-community | plugins/github/src/org/jetbrains/plugins/github/pullrequest/GHRepoVirtualFile.kt | 3 | 2282 | // Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.plugins.github.pullrequest
import com.intellij.openapi.fileTypes.FileType
import com.intellij.openapi.fileTypes.FileTypes
import com.intellij.openapi.project.Project
import com.intellij.openapi.vfs.VirtualFilePathWrapper
import com.intellij.openapi.vfs.VirtualFileSystem
import com.intellij.openapi.vfs.VirtualFileWithoutContent
import com.intellij.testFramework.LightVirtualFileBase
import org.jetbrains.plugins.github.api.GHRepositoryCoordinates
/**
* [fileManagerId] is a [org.jetbrains.plugins.github.pullrequest.data.GHPRFilesManagerImpl.id] which is required to differentiate files
* between launches of a PR toolwindow.
* This is necessary to make the files appear in "Recent Files" correctly.
* See [com.intellij.vcs.editor.ComplexPathVirtualFileSystem.ComplexPath.sessionId] for details.
*/
abstract class GHRepoVirtualFile(protected val fileManagerId: String,
val project: Project,
val repository: GHRepositoryCoordinates)
: LightVirtualFileBase("", null, 0), VirtualFileWithoutContent, VirtualFilePathWrapper {
override fun enforcePresentableName() = true
override fun getFileSystem(): VirtualFileSystem = GHPRVirtualFileSystem.getInstance()
override fun getFileType(): FileType = FileTypes.UNKNOWN
override fun getLength() = 0L
override fun contentsToByteArray() = throw UnsupportedOperationException()
override fun getInputStream() = throw UnsupportedOperationException()
override fun getOutputStream(requestor: Any?, newModificationStamp: Long, newTimeStamp: Long) = throw UnsupportedOperationException()
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other !is GHRepoVirtualFile) return false
if (fileManagerId != other.fileManagerId) return false
if (project != other.project) return false
if (repository != other.repository) return false
return true
}
override fun hashCode(): Int {
var result = fileManagerId.hashCode()
result = 31 * result + project.hashCode()
result = 31 * result + repository.hashCode()
return result
}
} | apache-2.0 | 03fd4998d19fcda5909fa002f1b747ae | 43.764706 | 140 | 0.763804 | 4.918103 | false | false | false | false |
allotria/intellij-community | platform/platform-impl/src/com/intellij/ide/actions/InvalidateCachesDialog.kt | 3 | 3451 | // Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.ide.actions
import com.google.common.collect.Sets
import com.intellij.ide.IdeBundle
import com.intellij.ide.caches.CachesInvalidator
import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.DialogWrapper
import com.intellij.openapi.util.text.HtmlChunk
import com.intellij.ui.components.Link
import com.intellij.ui.components.panels.NonOpaquePanel
import com.intellij.ui.layout.*
import com.intellij.util.ui.JBUI
import java.awt.BorderLayout
import javax.swing.Action
import javax.swing.JCheckBox
import javax.swing.JPanel
private var Action.text
get() = getValue(Action.NAME)
set(value) = putValue(Action.NAME, value)
class InvalidateCachesDialog(
project: Project?,
private val canRestart: Boolean,
private val invalidators: List<CachesInvalidator>,
) : DialogWrapper(project) {
private val JUST_RESTART_CODE = NEXT_USER_EXIT_CODE + 3
private val enabledInvalidators: MutableSet<CachesInvalidator> = Sets.newIdentityHashSet()
fun getSelectedInvalidators() : List<CachesInvalidator> {
if (!isOK) return emptyList()
return invalidators.filter {
it.description == null || it in enabledInvalidators
}
}
override fun getHelpId() = "invalidate-cache-restart"
init {
title = IdeBundle.message("dialog.title.invalidate.caches")
setResizable(false)
init()
okAction.text = when {
canRestart -> IdeBundle.message("button.invalidate.and.restart")
else -> IdeBundle.message("button.invalidate.and.exit")
}
cancelAction.text = IdeBundle.message("button.cancel.without.mnemonic")
}
fun isRestartOnly() = canRestart && exitCode == JUST_RESTART_CODE
override fun createSouthAdditionalPanel(): JPanel? {
if (!canRestart) return null
val link = Link(IdeBundle.message("link.just.restart")) {
close(JUST_RESTART_CODE)
}
val panel = NonOpaquePanel(BorderLayout())
panel.border = JBUI.Borders.emptyLeft(10)
panel.add(link)
return panel
}
override fun createCenterPanel() = panel {
row {
label(
HtmlChunk
.html()
.addText(IdeBundle.message("dialog.message.caches.will.be.invalidated"))
.toString()
).growPolicy(GrowPolicy.MEDIUM_TEXT).constraints(CCFlags.growY)
}
//we keep the original order as it comes from the extensions order
val invalidatorsWithDescriptor = invalidators.mapNotNull { it.description?.to(it) }
if (invalidatorsWithDescriptor.isNotEmpty()) {
row {
label(IdeBundle.message("dialog.message.the.following.items"))
for ((text, descr) in invalidatorsWithDescriptor) {
row {
val defaultValue = descr.optionalCheckboxDefaultValue()
val updateSelected = { cb: JCheckBox ->
when {
cb.isSelected -> enabledInvalidators += descr
else -> enabledInvalidators -= descr
}
}
val isSelected = defaultValue ?: true
checkBox(text, isSelected,
comment = descr.comment,
actionListener = { _, cb -> updateSelected(cb) }
).component.apply {
isEnabled = defaultValue != null
updateSelected(this)
}
}
}
}
}
}
}
| apache-2.0 | 096e592ee379d1886a24b1b68ac8a1f5 | 29.8125 | 140 | 0.673718 | 4.470207 | false | false | false | false |
LivingDoc/livingdoc | livingdoc-engine/src/main/kotlin/org/livingdoc/engine/execution/examples/Util.kt | 2 | 1613 | package org.livingdoc.engine.execution.examples
/**
* This function executes a before hook, the main function and an after hook in this order.
* It ensures, that the after hook is executed even if there was an exception in before or main function
* @param before the function that is called before the main part
* @param body the main function
* @param after the function that is called after the main part
*/
@Suppress("TooGenericExceptionCaught")
fun <T> executeWithBeforeAndAfter(before: () -> Unit, body: () -> T, after: () -> Unit): T {
var exception: Throwable? = null
val value =
try {
before.invoke()
body.invoke()
} catch (e: Throwable) {
exception = e
null
} finally {
runAfter(after, exception)
}
return value ?: throw IllegalStateException()
}
/**
* This function handles the execution of the after hook. It manages occurring exceptions too.
* @param after the after hook that should be executed
* @param exception a possibly occurred exception in the before or main function
*/
@Suppress("TooGenericExceptionCaught")
private fun runAfter(after: () -> Unit, exception: Throwable?) {
var originalException = exception
try {
after.invoke()
} catch (afterException: Throwable) {
if (originalException != null) {
originalException.addSuppressed(afterException)
} else {
originalException = afterException
}
} finally {
if (originalException != null) {
throw originalException
}
}
}
| apache-2.0 | a95c8804203b39d08b536eb01c037bd6 | 33.319149 | 104 | 0.647861 | 4.772189 | false | false | false | false |
JuliusKunze/kotlin-native | backend.native/tests/external/codegen/box/reflection/enclosing/lambdaInPropertySetter.kt | 2 | 738 | // TODO: muted automatically, investigate should it be ran for JS or not
// IGNORE_BACKEND: JS, NATIVE
// WITH_REFLECT
var _l: Any = ""
var l: Any
get() = _l
set(v) {
_l = {}
}
fun box(): String {
l = "" // to invoke the setter
val enclosingMethod = l.javaClass.getEnclosingMethod()
if (enclosingMethod?.getName() != "setL") return "method: $enclosingMethod"
val enclosingClass = l.javaClass.getEnclosingClass()!!.getName()
if (enclosingClass != "LambdaInPropertySetterKt") return "enclosing class: $enclosingClass"
val declaringClass = l.javaClass.getDeclaringClass()
if (declaringClass != null) return "anonymous function has a declaring class: $declaringClass"
return "OK"
}
| apache-2.0 | d65d1e470ee739bddb52fe1f49827139 | 26.333333 | 98 | 0.669377 | 4.077348 | false | false | false | false |
JuliusKunze/kotlin-native | backend.native/tests/external/codegen/box/functions/invoke/kt3450getAndInvoke.kt | 5 | 336 | //KT-3450 get and invoke are not parsed in one expression
public class A(val s: String) {
operator fun get(i: Int) : A = A("$s + $i")
operator fun invoke(builder : A.() -> String): String = builder()
}
fun x(y : String) : A = A(y)
fun foo() = x("aaa")[42] { "$s!!" }
fun box() = if (foo() == "aaa + 42!!") "OK" else "fail"
| apache-2.0 | db0934c9217785a3f3309d8dc176be54 | 24.846154 | 69 | 0.553571 | 2.847458 | false | false | false | false |
AndroidX/androidx | navigation/navigation-common/src/main/java/androidx/navigation/NavDestination.kt | 3 | 29302 | /*
* 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.navigation
import android.content.Context
import android.content.res.Resources
import android.net.Uri
import android.os.Bundle
import android.util.AttributeSet
import androidx.annotation.CallSuper
import androidx.annotation.IdRes
import androidx.annotation.RestrictTo
import androidx.collection.SparseArrayCompat
import androidx.collection.valueIterator
import androidx.core.content.res.use
import androidx.navigation.common.R
import java.util.regex.Pattern
import kotlin.reflect.KClass
/**
* NavDestination represents one node within an overall navigation graph.
*
* Each destination is associated with a [Navigator] which knows how to navigate to this
* particular destination.
*
* Destinations declare a set of [actions][putAction] that they
* support. These actions form a navigation API for the destination; the same actions declared
* on different destinations that fill similar roles allow application code to navigate based
* on semantic intent.
*
* Each destination has a set of [arguments][arguments] that will
* be applied when [navigating][NavController.navigate] to that destination.
* Any default values for those arguments can be overridden at the time of navigation.
*
* NavDestinations should be created via [Navigator.createDestination].
*/
public open class NavDestination(
/**
* The name associated with this destination's [Navigator].
*/
public val navigatorName: String
) {
/**
* This optional annotation allows tooling to offer auto-complete for the
* `android:name` attribute. This should match the class type passed to
* [parseClassFromName] when parsing the
* `android:name` attribute.
*/
@kotlin.annotation.Retention(AnnotationRetention.BINARY)
@Target(AnnotationTarget.ANNOTATION_CLASS, AnnotationTarget.CLASS)
public annotation class ClassType(val value: KClass<*>)
/** @suppress */
@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
public class DeepLinkMatch(
public val destination: NavDestination,
@get:Suppress("NullableCollection") // Needed for nullable bundle
public val matchingArgs: Bundle?,
private val isExactDeepLink: Boolean,
private val matchingPathSegments: Int,
private val hasMatchingAction: Boolean,
private val mimeTypeMatchLevel: Int
) : Comparable<DeepLinkMatch> {
override fun compareTo(other: DeepLinkMatch): Int {
// Prefer exact deep links
if (isExactDeepLink && !other.isExactDeepLink) {
return 1
} else if (!isExactDeepLink && other.isExactDeepLink) {
return -1
}
// Then prefer most exact match path segments
val pathSegmentDifference = matchingPathSegments - other.matchingPathSegments
if (pathSegmentDifference > 0) {
return 1
} else if (pathSegmentDifference < 0) {
return -1
}
if (matchingArgs != null && other.matchingArgs == null) {
return 1
} else if (matchingArgs == null && other.matchingArgs != null) {
return -1
}
if (matchingArgs != null) {
val sizeDifference = matchingArgs.size() - other.matchingArgs!!.size()
if (sizeDifference > 0) {
return 1
} else if (sizeDifference < 0) {
return -1
}
}
if (hasMatchingAction && !other.hasMatchingAction) {
return 1
} else if (!hasMatchingAction && other.hasMatchingAction) {
return -1
}
return mimeTypeMatchLevel - other.mimeTypeMatchLevel
}
}
/**
* Gets the [NavGraph] that contains this destination. This will be set when a
* destination is added to a NavGraph via [NavGraph.addDestination].
*/
public var parent: NavGraph? = null
/** @suppress */
@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
public set
private var idName: String? = null
/**
* The descriptive label of this destination.
*/
public var label: CharSequence? = null
private val deepLinks = mutableListOf<NavDeepLink>()
private val actions: SparseArrayCompat<NavAction> = SparseArrayCompat()
private var _arguments: MutableMap<String, NavArgument> = mutableMapOf()
/**
* The arguments supported by this destination. Returns a read-only map of argument names
* to [NavArgument] objects that can be used to check the type, default value
* and nullability of the argument.
*
* To add and remove arguments for this NavDestination
* use [addArgument] and [removeArgument].
* @return Read-only map of argument names to arguments.
*/
public val arguments: Map<String, NavArgument>
get() = _arguments.toMap()
/**
* NavDestinations should be created via [Navigator.createDestination].
*
* This constructor requires that the given Navigator has a [Navigator.Name] annotation.
*/
public constructor(navigator: Navigator<out NavDestination>) : this(
NavigatorProvider.getNameForNavigator(
navigator.javaClass
)
)
/**
* Called when inflating a destination from a resource.
*
* @param context local context performing inflation
* @param attrs attrs to parse during inflation
*/
@CallSuper
public open fun onInflate(context: Context, attrs: AttributeSet) {
context.resources.obtainAttributes(attrs, R.styleable.Navigator).use { array ->
route = array.getString(R.styleable.Navigator_route)
if (array.hasValue(R.styleable.Navigator_android_id)) {
id = array.getResourceId(R.styleable.Navigator_android_id, 0)
idName = getDisplayName(context, id)
}
label = array.getText(R.styleable.Navigator_android_label)
}
}
/**
* The destination's unique ID. This should be an ID resource generated by
* the Android resource system.
*/
@get:IdRes
public var id: Int = 0
set(@IdRes id) {
field = id
idName = null
}
/**
* The destination's unique route. Setting this will also update the [id] of the destinations
* so custom destination ids should only be set after setting the route.
*
* @return this destination's route, or null if no route is set
*
* @throws IllegalArgumentException is the given route is empty
*/
public var route: String? = null
set(route) {
if (route == null) {
id = 0
} else {
require(route.isNotBlank()) { "Cannot have an empty route" }
val internalRoute = createRoute(route)
id = internalRoute.hashCode()
addDeepLink(internalRoute)
}
deepLinks.remove(deepLinks.firstOrNull { it.uriPattern == createRoute(field) })
field = route
}
/**
* @hide
*/
@get:RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
public open val displayName: String
get() = idName ?: id.toString()
/**
* Checks the given deep link [Uri], and determines whether it matches a Uri pattern added
* to the destination by a call to [addDeepLink] . It returns `true`
* if the deep link is a valid match, and `false` otherwise.
*
* This should be called prior to [NavController.navigate] to ensure the deep link
* can be navigated to.
*
* @param deepLink to the destination reachable from the current NavGraph
* @return True if the deepLink exists for the destination.
* @see NavDestination.addDeepLink
* @see NavController.navigate
* @see NavDestination.hasDeepLink
*/
public open fun hasDeepLink(deepLink: Uri): Boolean {
return hasDeepLink(NavDeepLinkRequest(deepLink, null, null))
}
/**
* Checks the given [NavDeepLinkRequest], and determines whether it matches a
* [NavDeepLink] added to the destination by a call to
* [addDeepLink]. It returns `true` if the request is a valid
* match, and `false` otherwise.
*
* This should be called prior to [NavController.navigate] to
* ensure the deep link can be navigated to.
*
* @param deepLinkRequest to the destination reachable from the current NavGraph
* @return True if the deepLink exists for the destination.
* @see NavDestination.addDeepLink
* @see NavController.navigate
*/
public open fun hasDeepLink(deepLinkRequest: NavDeepLinkRequest): Boolean {
return matchDeepLink(deepLinkRequest) != null
}
/**
* Add a deep link to this destination. Matching Uris sent to
* [NavController.handleDeepLink] or [NavController.navigate] will
* trigger navigating to this destination.
*
* In addition to a direct Uri match, the following features are supported:
*
* - Uris without a scheme are assumed as http and https. For example,
* `www.example.com` will match `http://www.example.com` and
* `https://www.example.com`.
* - Placeholders in the form of `{placeholder_name}` matches 1 or more
* characters. The parsed value of the placeholder will be available in the arguments
* [Bundle] with a key of the same name. For example,
* `http://www.example.com/users/{id}` will match
* `http://www.example.com/users/4`.
* - The `.*` wildcard can be used to match 0 or more characters.
*
* These Uris can be declared in your navigation XML files by adding one or more
* `<deepLink app:uri="uriPattern" />` elements as
* a child to your destination.
*
* Deep links added in navigation XML files will automatically replace instances of
* `${applicationId}` with the applicationId of your app.
* Programmatically added deep links should use [Context.getPackageName] directly
* when constructing the uriPattern.
* @param uriPattern The uri pattern to add as a deep link
* @see NavController.handleDeepLink
* @see NavController.navigate
* @see NavDestination.addDeepLink
*/
public fun addDeepLink(uriPattern: String) {
addDeepLink(NavDeepLink.Builder().setUriPattern(uriPattern).build())
}
/**
* Add a deep link to this destination. Uris that match the given [NavDeepLink] uri
* sent to [NavController.handleDeepLink] or
* [NavController.navigate] will trigger navigating to this
* destination.
*
* In addition to a direct Uri match, the following features are supported:
*
* Uris without a scheme are assumed as http and https. For example,
* `www.example.com` will match `http://www.example.com` and
* `https://www.example.com`.
* Placeholders in the form of `{placeholder_name}` matches 1 or more
* characters. The String value of the placeholder will be available in the arguments
* [Bundle] with a key of the same name. For example,
* `http://www.example.com/users/{id}` will match
* `http://www.example.com/users/4`.
* The `.*` wildcard can be used to match 0 or more characters.
*
* These Uris can be declared in your navigation XML files by adding one or more
* `<deepLink app:uri="uriPattern" />` elements as
* a child to your destination.
*
* Custom actions and mimetypes are also supported by [NavDeepLink] and can be declared
* in your navigation XML files by adding
* `<app:action="android.intent.action.SOME_ACTION" />` or
* `<app:mimetype="type/subtype" />` as part of your deepLink declaration.
*
* Deep link Uris, actions, and mimetypes added in navigation XML files will automatically
* replace instances of `${applicationId}` with the applicationId of your app.
* Programmatically added deep links should use [Context.getPackageName] directly
* when constructing the uriPattern.
*
* When matching deep links for calls to [NavController.handleDeepLink] or
* [NavController.navigate] the order of precedence is as follows:
* the deep link with the most matching arguments will be chosen, followed by the deep link
* with a matching action, followed by the best matching mimeType (e.i. when matching
* mimeType image/jpg: image/ * > *\/jpg > *\/ *).
* @param navDeepLink The NavDeepLink to add as a deep link
* @see NavController.handleDeepLink
* @see NavController.navigate
*/
public fun addDeepLink(navDeepLink: NavDeepLink) {
val missingRequiredArguments =
arguments.filterValues { !it.isNullable && !it.isDefaultValuePresent }
.keys
.filter { it !in navDeepLink.argumentsNames }
require(missingRequiredArguments.isEmpty()) {
"Deep link ${navDeepLink.uriPattern} can't be used to open destination $this.\n" +
"Following required arguments are missing: $missingRequiredArguments"
}
deepLinks.add(navDeepLink)
}
/**
* Determines if this NavDestination has a deep link matching the given Uri.
* @param navDeepLinkRequest The request to match against all deep links added in
* [addDeepLink]
* @return The matching [NavDestination] and the appropriate [Bundle] of arguments
* extracted from the Uri, or null if no match was found.
* @suppress
*/
@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
public open fun matchDeepLink(navDeepLinkRequest: NavDeepLinkRequest): DeepLinkMatch? {
if (deepLinks.isEmpty()) {
return null
}
var bestMatch: DeepLinkMatch? = null
for (deepLink in deepLinks) {
val uri = navDeepLinkRequest.uri
// includes matching args for path, query, and fragment
val matchingArguments =
if (uri != null) deepLink.getMatchingArguments(uri, arguments) else null
val matchingPathSegments = deepLink.calculateMatchingPathSegments(uri)
val requestAction = navDeepLinkRequest.action
val matchingAction = requestAction != null && requestAction ==
deepLink.action
val mimeType = navDeepLinkRequest.mimeType
val mimeTypeMatchLevel =
if (mimeType != null) deepLink.getMimeTypeMatchRating(mimeType) else -1
if (matchingArguments != null || matchingAction || mimeTypeMatchLevel > -1) {
val newMatch = DeepLinkMatch(
this, matchingArguments,
deepLink.isExactDeepLink, matchingPathSegments, matchingAction,
mimeTypeMatchLevel
)
if (bestMatch == null || newMatch > bestMatch) {
bestMatch = newMatch
}
}
}
return bestMatch
}
/**
* Build an array containing the hierarchy from the root down to this destination.
*
* @param previousDestination the previous destination we are starting at
* @return An array containing all of the ids from the previous destination (or the root of
* the graph if null) to this destination
* @suppress
*/
@JvmOverloads
@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
public fun buildDeepLinkIds(previousDestination: NavDestination? = null): IntArray {
val hierarchy = ArrayDeque<NavDestination>()
var current: NavDestination? = this
do {
val parent = current!!.parent
if (
// If the current destination is a sibling of the previous, just add it straightaway
previousDestination?.parent != null &&
previousDestination.parent!!.findNode(current.id) === current
) {
hierarchy.addFirst(current)
break
}
if (parent == null || parent.startDestinationId != current.id) {
hierarchy.addFirst(current)
}
if (parent == previousDestination) {
break
}
current = parent
} while (current != null)
return hierarchy.toList().map { it.id }.toIntArray()
}
/**
* @return Whether this NavDestination supports outgoing actions
* @see NavDestination.putAction
* @suppress
*/
@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
public open fun supportsActions(): Boolean {
return true
}
/**
* Returns the [NavAction] for the given action ID. This will recursively check the
* [parent][getParent] of this destination if the action destination is not found in
* this destination.
*
* @param id action ID to fetch
* @return the [NavAction] mapped to the given action id, or null if one has not been set
*/
public fun getAction(@IdRes id: Int): NavAction? {
val destination = if (actions.isEmpty) null else actions[id]
// Search the parent for the given action if it is not found in this destination
return destination ?: parent?.run { getAction(id) }
}
/**
* Creates a [NavAction] for the given [destId] and associates it with the [actionId].
*
* @param actionId action ID to bind
* @param destId destination ID for the given action
*/
public fun putAction(@IdRes actionId: Int, @IdRes destId: Int) {
putAction(actionId, NavAction(destId))
}
/**
* Sets the [NavAction] destination for an action ID.
*
* @param actionId action ID to bind
* @param action action to associate with this action ID
* @throws UnsupportedOperationException this destination is considered a terminal destination
* and does not support actions
*/
public fun putAction(@IdRes actionId: Int, action: NavAction) {
if (!supportsActions()) {
throw UnsupportedOperationException(
"Cannot add action $actionId to $this as it does not support actions, " +
"indicating that it is a terminal destination in your navigation graph and " +
"will never trigger actions."
)
}
require(actionId != 0) { "Cannot have an action with actionId 0" }
actions.put(actionId, action)
}
/**
* Unsets the [NavAction] for an action ID.
*
* @param actionId action ID to remove
*/
public fun removeAction(@IdRes actionId: Int) {
actions.remove(actionId)
}
/**
* Sets an argument type for an argument name
*
* @param argumentName argument object to associate with destination
* @param argument argument object to associate with destination
*/
public fun addArgument(argumentName: String, argument: NavArgument) {
_arguments[argumentName] = argument
}
/**
* Unsets the argument type for an argument name.
*
* @param argumentName argument to remove
*/
public fun removeArgument(argumentName: String) {
_arguments.remove(argumentName)
}
/**
* Combines the default arguments for this destination with the arguments provided
* to construct the final set of arguments that should be used to navigate
* to this destination.
* @suppress
*/
@Suppress("NullableCollection") // Needed for nullable bundle
@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
public fun addInDefaultArgs(args: Bundle?): Bundle? {
if (args == null && _arguments.isNullOrEmpty()) {
return null
}
val defaultArgs = Bundle()
for ((key, value) in _arguments) {
value.putDefaultValue(key, defaultArgs)
}
if (args != null) {
defaultArgs.putAll(args)
for ((key, value) in _arguments) {
require(value.verify(key, defaultArgs)) {
"Wrong argument type for '$key' in argument bundle. ${value.type.name} " +
"expected."
}
}
}
return defaultArgs
}
/**
* Parses a dynamic label containing arguments into a String.
*
* Supports String Resource arguments by parsing `R.string` values of `ReferenceType`
* arguments found in `android:label` into their String values.
*
* Returns `null` if label is null.
*
* Returns the original label if the label was a static string.
*
* @param context Context used to resolve a resource's name
* @param bundle Bundle containing the arguments used in the label
* @return The parsed string or null if the label is null
* @throws IllegalArgumentException if an argument provided in the label cannot be found in
* the bundle, or if the label contains a string template but the bundle is null
*/
public fun fillInLabel(context: Context, bundle: Bundle?): String? {
val label = label ?: return null
val fillInPattern = Pattern.compile("\\{(.+?)\\}")
val matcher = fillInPattern.matcher(label)
val builder = StringBuffer()
while (matcher.find()) {
val argName = matcher.group(1)
if (bundle != null && bundle.containsKey(argName)) {
matcher.appendReplacement(builder, "")
val argType = argName?.let { arguments[argName]?.type }
if (argType == NavType.ReferenceType) {
val value = context.getString(bundle.getInt(argName))
builder.append(value)
} else {
builder.append(bundle.getString(argName))
}
} else {
throw IllegalArgumentException(
"Could not find \"$argName\" in $bundle to fill label \"$label\""
)
}
}
matcher.appendTail(builder)
return builder.toString()
}
override fun toString(): String {
val sb = StringBuilder()
sb.append(javaClass.simpleName)
sb.append("(")
if (idName == null) {
sb.append("0x")
sb.append(Integer.toHexString(id))
} else {
sb.append(idName)
}
sb.append(")")
if (!route.isNullOrBlank()) {
sb.append(" route=")
sb.append(route)
}
if (label != null) {
sb.append(" label=")
sb.append(label)
}
return sb.toString()
}
override fun equals(other: Any?): Boolean {
if (other == null || other !is NavDestination) return false
val equalDeepLinks = deepLinks.intersect(other.deepLinks).size == deepLinks.size
val equalActions = actions.size() == other.actions.size() &&
actions.valueIterator().asSequence().all { other.actions.containsValue(it) } &&
other.actions.valueIterator().asSequence().all { actions.containsValue(it) }
val equalArguments = arguments.size == other.arguments.size &&
arguments.asSequence().all {
other.arguments.containsKey(it.key) &&
other.arguments[it.key] == it.value
} &&
other.arguments.asSequence().all {
arguments.containsKey(it.key) &&
arguments[it.key] == it.value
}
return id == other.id &&
route == other.route &&
equalDeepLinks &&
equalActions &&
equalArguments
}
@Suppress("DEPRECATION")
override fun hashCode(): Int {
var result = id
result = 31 * result + route.hashCode()
deepLinks.forEach {
result = 31 * result + it.uriPattern.hashCode()
result = 31 * result + it.action.hashCode()
result = 31 * result + it.mimeType.hashCode()
}
actions.valueIterator().forEach { value ->
result = 31 * result + value.destinationId
result = 31 * result + value.navOptions.hashCode()
value.defaultArguments?.keySet()?.forEach {
result = 31 * result + value.defaultArguments!!.get(it).hashCode()
}
}
arguments.keys.forEach {
result = 31 * result + it.hashCode()
result = 31 * result + arguments[it].hashCode()
}
return result
}
public companion object {
private val classes = mutableMapOf<String, Class<*>>()
/**
* Parse the class associated with this destination from a raw name, generally extracted
* from the `android:name` attribute added to the destination's XML. This should
* be the class providing the visual representation of the destination that the
* user sees after navigating to this destination.
*
* This method does name -> Class caching and should be strongly preferred over doing your
* own parsing if your [Navigator] supports the `android:name` attribute to
* give consistent behavior across all Navigators.
*
* @param context Context providing the package name for use with relative class names and the
* ClassLoader
* @param name Absolute or relative class name. Null names will be ignored.
* @param expectedClassType The expected class type
* @return The parsed class
* @throws IllegalArgumentException if the class is not found in the provided Context's
* ClassLoader or if the class is not of the expected type
*/
@Suppress("UNCHECKED_CAST")
@JvmStatic
protected fun <C> parseClassFromName(
context: Context,
name: String,
expectedClassType: Class<out C?>
): Class<out C?> {
var innerName = name
if (innerName[0] == '.') {
innerName = context.packageName + innerName
}
var clazz = classes[innerName]
if (clazz == null) {
try {
clazz = Class.forName(innerName, true, context.classLoader)
classes[name] = clazz
} catch (e: ClassNotFoundException) {
throw IllegalArgumentException(e)
}
}
require(expectedClassType.isAssignableFrom(clazz!!)) {
"$innerName must be a subclass of $expectedClassType"
}
return clazz as Class<out C?>
}
/**
* Used internally for NavDestinationTest
* @suppress
*/
@JvmStatic
@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
public fun <C> parseClassFromNameInternal(
context: Context,
name: String,
expectedClassType: Class<out C?>
): Class<out C?> {
return parseClassFromName(context, name, expectedClassType)
}
/**
* Retrieve a suitable display name for a given id.
* @param context Context used to resolve a resource's name
* @param id The id to get a display name for
* @return The resource's name if it is a valid id or just the id itself if it is not
* a valid resource
* @hide
*/
@JvmStatic
@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
public fun getDisplayName(context: Context, id: Int): String {
// aapt-generated IDs have the high byte nonzero,
// so anything below that cannot be a valid resource id
return if (id <= 0x00FFFFFF) {
id.toString()
} else try {
context.resources.getResourceName(id)
} catch (e: Resources.NotFoundException) {
id.toString()
}
}
/**
* @hide
*/
@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
public fun createRoute(route: String?): String =
if (route != null) "android-app://androidx.navigation/$route" else ""
/**
* Provides a sequence of the NavDestination's hierarchy. The hierarchy starts with this
* destination itself and is then followed by this destination's [NavDestination.parent], then that
* graph's parent, and up the hierarchy until you've reached the root navigation graph.
*/
@JvmStatic
public val NavDestination.hierarchy: Sequence<NavDestination>
get() = generateSequence(this) { it.parent }
}
}
| apache-2.0 | 1b4e4fd0bb42afb29817408c3bff1c37 | 38.8125 | 107 | 0.620504 | 4.933827 | false | false | false | false |
exponent/exponent | android/versioned-abis/expoview-abi42_0_0/src/main/java/abi42_0_0/host/exp/exponent/modules/api/components/reactnativestripesdk/PaymentSheetFragment.kt | 2 | 6353 | package abi42_0_0.host.exp.exponent.modules.api.components.reactnativestripesdk
import android.content.Context
import android.content.Intent
import android.graphics.Bitmap
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.drawable.Drawable
import android.os.Bundle
import android.util.Base64
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.FrameLayout
import androidx.appcompat.content.res.AppCompatResources
import androidx.core.graphics.drawable.DrawableCompat
import androidx.fragment.app.Fragment
import com.stripe.android.paymentsheet.*
import com.stripe.android.paymentsheet.model.PaymentOption
import java.io.ByteArrayOutputStream
class PaymentSheetFragment : Fragment() {
private var paymentSheet: PaymentSheet? = null
private var flowController: PaymentSheet.FlowController? = null
private var paymentIntentClientSecret: String? = null
private var setupIntentClientSecret: String? = null
private lateinit var paymentSheetConfiguration: PaymentSheet.Configuration
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View {
return FrameLayout(requireActivity()).also {
it.visibility = View.GONE
}
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
val merchantDisplayName = arguments?.getString("merchantDisplayName").orEmpty()
val customerId = arguments?.getString("customerId").orEmpty()
val customerEphemeralKeySecret = arguments?.getString("customerEphemeralKeySecret").orEmpty()
val countryCode = arguments?.getString("countryCode").orEmpty()
val testEnv = arguments?.getBoolean("testEnv")
paymentIntentClientSecret = arguments?.getString("paymentIntentClientSecret").orEmpty()
setupIntentClientSecret = arguments?.getString("setupIntentClientSecret").orEmpty()
val paymentOptionCallback = object : PaymentOptionCallback {
override fun onPaymentOption(paymentOption: PaymentOption?) {
val intent = Intent(ON_PAYMENT_OPTION_ACTION)
if (paymentOption != null) {
val bitmap = getBitmapFromVectorDrawable(context, paymentOption.drawableResourceId)
val imageString = getBase64FromBitmap(bitmap)
intent.putExtra("label", paymentOption.label)
intent.putExtra("image", imageString)
}
activity?.sendBroadcast(intent)
}
}
val paymentResultCallback = object : PaymentSheetResultCallback {
override fun onPaymentSheetResult(paymentResult: PaymentSheetResult) {
val intent = Intent(ON_PAYMENT_RESULT_ACTION)
intent.putExtra("paymentResult", paymentResult)
activity?.sendBroadcast(intent)
}
}
paymentSheetConfiguration = PaymentSheet.Configuration(
merchantDisplayName = merchantDisplayName,
customer = if (customerId.isNotEmpty() && customerEphemeralKeySecret.isNotEmpty()) PaymentSheet.CustomerConfiguration(
id = customerId,
ephemeralKeySecret = customerEphemeralKeySecret
) else null,
googlePay = PaymentSheet.GooglePayConfiguration(
environment = if (testEnv == true) PaymentSheet.GooglePayConfiguration.Environment.Test else PaymentSheet.GooglePayConfiguration.Environment.Production,
countryCode = countryCode
)
)
if (arguments?.getBoolean("customFlow") == true) {
flowController = PaymentSheet.FlowController.create(this, paymentOptionCallback, paymentResultCallback)
configureFlowController()
} else {
paymentSheet = PaymentSheet(this, paymentResultCallback)
}
val intent = Intent(ON_FRAGMENT_CREATED)
activity?.sendBroadcast(intent)
}
fun present() {
if (!paymentIntentClientSecret.isNullOrEmpty()) {
paymentSheet?.presentWithPaymentIntent(paymentIntentClientSecret!!, paymentSheetConfiguration)
} else if (!setupIntentClientSecret.isNullOrEmpty()) {
paymentSheet?.presentWithSetupIntent(setupIntentClientSecret!!, paymentSheetConfiguration)
}
}
fun presentPaymentOptions() {
flowController?.presentPaymentOptions()
}
fun confirmPayment() {
flowController?.confirm()
}
private fun configureFlowController() {
val onFlowControllerConfigure = object : PaymentSheet.FlowController.ConfigCallback {
override fun onConfigured(success: Boolean, error: Throwable?) {
val paymentOption = flowController?.getPaymentOption()
val intent = Intent(ON_CONFIGURE_FLOW_CONTROLLER)
if (paymentOption != null) {
val bitmap = getBitmapFromVectorDrawable(context, paymentOption.drawableResourceId)
val imageString = getBase64FromBitmap(bitmap)
intent.putExtra("label", paymentOption.label)
intent.putExtra("image", imageString)
}
activity?.sendBroadcast(intent)
}
}
if (!paymentIntentClientSecret.isNullOrEmpty()) {
flowController?.configureWithPaymentIntent(
paymentIntentClientSecret = paymentIntentClientSecret!!,
configuration = paymentSheetConfiguration,
callback = onFlowControllerConfigure
)
} else if (!setupIntentClientSecret.isNullOrEmpty()) {
flowController?.configureWithSetupIntent(
setupIntentClientSecret = setupIntentClientSecret!!,
configuration = paymentSheetConfiguration,
callback = onFlowControllerConfigure
)
}
}
}
fun getBitmapFromVectorDrawable(context: Context?, drawableId: Int): Bitmap? {
var drawable: Drawable? = AppCompatResources.getDrawable(context!!, drawableId)
if (drawable == null) {
return null
}
drawable = DrawableCompat.wrap(drawable).mutate()
val bitmap = Bitmap.createBitmap(drawable.intrinsicWidth, drawable.intrinsicHeight, Bitmap.Config.ARGB_8888)
bitmap.eraseColor(Color.WHITE)
val canvas = Canvas(bitmap)
drawable.setBounds(0, 0, canvas.width, canvas.height)
drawable.draw(canvas)
return bitmap
}
fun getBase64FromBitmap(bitmap: Bitmap?): String? {
if (bitmap == null) {
return null
}
val baos = ByteArrayOutputStream()
bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos)
val imageBytes: ByteArray = baos.toByteArray()
return Base64.encodeToString(imageBytes, Base64.DEFAULT)
}
| bsd-3-clause | f28cb2a62d0aa9c1130e868b332834a1 | 36.591716 | 160 | 0.745475 | 5.272199 | false | true | false | false |
kpi-ua/ecampus-client-android | app/src/main/java/com/goldenpiedevs/schedule/app/ui/widget/ScheduleWidgetProvider.kt | 1 | 4171 | package com.goldenpiedevs.schedule.app.ui.widget
import android.app.PendingIntent
import android.appwidget.AppWidgetManager
import android.appwidget.AppWidgetProvider
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.widget.RemoteViews
import com.goldenpiedevs.schedule.app.R
import com.goldenpiedevs.schedule.app.core.ext.currentWeek
import com.goldenpiedevs.schedule.app.core.ext.todayName
import com.goldenpiedevs.schedule.app.ui.lesson.LessonActivity
import com.goldenpiedevs.schedule.app.ui.lesson.LessonImplementation
class ScheduleWidgetProvider : AppWidgetProvider() {
override fun onUpdate(context: Context?, appWidgetManager: AppWidgetManager?, appWidgetIds: IntArray?) {
appWidgetIds?.let {
for (appWidgetId in it) {
updateAppWidget(context, appWidgetManager, appWidgetId)
}
}
super.onUpdate(context, appWidgetManager, appWidgetIds)
}
override fun onReceive(context: Context?, intent: Intent?) {
when {
intent?.action.equals(ACTION_SCHEDULED_UPDATE)
|| intent?.action.equals("android.appwidget.action.APPWIDGET_UPDATE") -> context?.let {
val manager = AppWidgetManager.getInstance(it)
val ids = manager.getAppWidgetIds(ComponentName(it, ScheduleWidgetProvider::class.java))
onUpdate(it, manager, ids)
}
intent?.action.equals(ACTION_OPEN_LESSON) -> context?.let {
it.startActivity(Intent(it, LessonActivity::class.java)
.apply {
flags = Intent.FLAG_ACTIVITY_NEW_TASK
putExtra(LessonImplementation.LESSON_ID,
intent!!.getStringExtra(LESSON_ID))
})
}
}
super.onReceive(context, intent)
}
companion object {
const val ACTION_SCHEDULED_UPDATE = "com.goldenpiedevs.schedule.app.ui.widget.SCHEDULED_UPDATE"
const val ACTION_OPEN_LESSON = "com.goldenpiedevs.schedule.app.ui.widget.ACTION_OPEN_LESSON"
const val LESSON_ID = "com.goldenpiedevs.schedule.app.ui.widget.LESSON_ID"
fun updateWidget(context: Context) {
val intent = Intent(context, ScheduleWidgetProvider::class.java)
intent.action = ACTION_SCHEDULED_UPDATE
context.sendBroadcast(intent)
}
internal fun updateAppWidget(context: Context?, appWidgetManager: AppWidgetManager?,
appWidgetId: Int) {
context?.let {
with(RemoteViews(it.packageName, R.layout.schedule_widget)) {
val intent = Intent(context, WidgetService::class.java)
intent.data = Uri.parse(intent.toUri(Intent.URI_INTENT_SCHEME))
intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId)
val toastIntent = Intent(context, ScheduleWidgetProvider::class.java)
toastIntent.action = ScheduleWidgetProvider.ACTION_OPEN_LESSON
intent.data = Uri.parse(intent.toUri(Intent.URI_INTENT_SCHEME))
val toastPendingIntent = PendingIntent.getBroadcast(context, 0, toastIntent,
PendingIntent.FLAG_UPDATE_CURRENT)
setPendingIntentTemplate(R.id.widget_list, toastPendingIntent)
setRemoteAdapter(R.id.widget_list, intent)
setEmptyView(R.id.widget_list, R.id.widget_list_empty_view)
setTextViewText(R.id.widget_day_name,
todayName.substring(0, 1).toUpperCase() + todayName.substring(1))
setTextViewText(R.id.widget_day_date,
"${currentWeek + 1} ${context.getString(R.string.week)}")
appWidgetManager?.notifyAppWidgetViewDataChanged(appWidgetId, R.id.widget_list)
appWidgetManager?.updateAppWidget(appWidgetId, this)
}
}
}
}
} | apache-2.0 | 7efd30fa5f03daf791000187475045d8 | 44.846154 | 108 | 0.628626 | 5.031363 | false | false | false | false |
smmribeiro/intellij-community | notebooks/visualization/src/org/jetbrains/plugins/notebooks/visualization/r/inlays/InlayEditorManager.kt | 1 | 16194 | /*
* 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.notebooks.visualization.r.inlays
import com.intellij.ide.ui.UISettings
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.application.ModalityState
import com.intellij.openapi.application.ReadAction
import com.intellij.openapi.application.invokeLater
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.editor.FoldRegion
import com.intellij.openapi.editor.Inlay
import com.intellij.openapi.editor.event.CaretEvent
import com.intellij.openapi.editor.event.CaretListener
import com.intellij.openapi.editor.event.DocumentEvent
import com.intellij.openapi.editor.event.DocumentListener
import com.intellij.openapi.editor.ex.EditorGutterComponentEx
import com.intellij.openapi.editor.ex.FoldingListener
import com.intellij.openapi.editor.ex.util.EditorScrollingPositionKeeper
import com.intellij.openapi.editor.impl.EditorImpl
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.Key
import com.intellij.openapi.util.TextRange
import com.intellij.psi.PsiDocumentManager
import com.intellij.psi.PsiElement
import com.intellij.psi.util.PsiTreeUtil
import com.intellij.util.concurrency.FutureResult
import com.intellij.util.concurrency.NonUrgentExecutor
import com.intellij.util.ui.update.MergingUpdateQueue
import com.intellij.util.ui.update.Update
import org.jetbrains.annotations.TestOnly
import org.jetbrains.concurrency.CancellablePromise
import org.jetbrains.plugins.notebooks.visualization.r.inlays.components.InlayProgressStatus
import java.awt.Point
import java.awt.event.ComponentAdapter
import java.awt.event.ComponentEvent
import java.util.concurrent.Future
import kotlin.math.max
import kotlin.math.min
/**
* Manages inlays.
*
* On project load subscribes
* on editor opening/closing.
* on adding/removing notebook cells
* on any document changes
* on folding actions
*
* On editor open checks the PSI structure and restores saved inlays.
*
* ToDo should be split into InlaysManager with all basics and NotebookInlaysManager with all specific.
*/
class EditorInlaysManager(val project: Project, private val editor: EditorImpl, val descriptor: InlayElementDescriptor) {
private val inlays: MutableMap<PsiElement, NotebookInlayComponentPsi> = LinkedHashMap()
private val inlayElements = LinkedHashSet<PsiElement>()
private val scrollKeeper: EditorScrollingPositionKeeper = EditorScrollingPositionKeeper(editor)
private val viewportQueue = MergingUpdateQueue(VIEWPORT_TASK_NAME, VIEWPORT_TIME_SPAN, true, null, project)
@Volatile private var toolbarUpdateScheduled: Boolean = false
init {
addResizeListener()
addCaretListener()
addFoldingListener()
addDocumentListener()
addViewportListener()
editor.settings.isRightMarginShown = false
UISettings.instance.showEditorToolTip = false
MouseWheelUtils.wrapEditorMouseWheelListeners(editor)
restoreToolbars().onSuccess { restoreOutputs() }
onCaretPositionChanged()
ApplicationManager.getApplication().invokeLater {
if (editor.isDisposed) return@invokeLater
updateInlayComponentsWidth()
}
}
fun dispose() {
inlays.values.forEach {
it.disposeInlay()
it.dispose()
}
inlays.clear()
inlayElements.clear()
}
fun updateCell(psi: PsiElement, inlayOutputs: List<InlayOutput>? = null, createTextOutput: Boolean = false): Future<Unit> {
val result = FutureResult<Unit>()
if (ApplicationManager.getApplication().isUnitTestMode && !isEnabledInTests) return result.apply { set(Unit) }
ApplicationManager.getApplication().invokeLater {
try {
if (editor.isDisposed) {
result.set(Unit)
return@invokeLater
}
if (!psi.isValid) {
getInlayComponent(psi)?.let { oldInlay -> removeInlay(oldInlay, cleanup = false) }
result.set(Unit)
return@invokeLater
}
if (isOutputPositionCollapsed(psi)) {
result.set(Unit)
return@invokeLater
}
val outputs = inlayOutputs ?: descriptor.getInlayOutputs(psi)
if (outputs == null) {
result.set(Unit)
return@invokeLater
}
scrollKeeper.savePosition()
getInlayComponent(psi)?.let { oldInlay -> removeInlay(oldInlay, cleanup = false) }
if (outputs.isEmpty() && !createTextOutput) {
result.set(Unit)
return@invokeLater
}
val component = addInlayComponent(psi)
if (outputs.isNotEmpty()) addInlayOutputs(component, outputs)
if (createTextOutput) component.createOutputComponent()
scrollKeeper.restorePosition(true)
} catch (e: Throwable) {
result.set(Unit)
throw e
}
ApplicationManager.getApplication().invokeLater {
try {
scrollKeeper.savePosition()
updateInlays()
scrollKeeper.restorePosition(true)
}
finally {
result.set(Unit)
}
}
}
return result
}
private fun isOutputPositionCollapsed(psiCell: PsiElement): Boolean =
editor.foldingModel.isOffsetCollapsed(descriptor.getInlayOffset(psiCell))
fun addTextToInlay(psi: PsiElement, message: String, outputType: Key<*>) {
invokeLater {
scrollKeeper.savePosition()
getInlayComponent(psi)?.addText(message, outputType)
scrollKeeper.restorePosition(true)
}
}
fun updateInlayProgressStatus(psi: PsiElement, progressStatus: InlayProgressStatus): Future<Unit> {
val result = FutureResult<Unit>()
ApplicationManager.getApplication().invokeLater {
getInlayComponent(psi)?.updateProgressStatus(progressStatus)
result.set(Unit)
}
return result
}
private fun updateInlaysForViewport() {
invokeLater {
if (editor.isDisposed) return@invokeLater
val viewportRange = calculateViewportRange(editor)
val expansionRange = calculateInlayExpansionRange(editor, viewportRange)
for (element in inlayElements) {
updateInlayForViewport(element, viewportRange, expansionRange)
}
}
}
private fun updateInlayForViewport(element: PsiElement, viewportRange: IntRange, expansionRange: IntRange) {
val inlay = inlays[element]
if (inlay != null) {
val bounds = inlay.bounds
val isInViewport = bounds.y <= viewportRange.last && bounds.y + bounds.height >= viewportRange.first
inlay.onViewportChange(isInViewport)
} else {
if (element.textRange.startOffset in expansionRange) {
updateCell(element)
}
}
}
private fun addInlayOutputs(inlayComponent: NotebookInlayComponentPsi,
inlayOutputs: List<InlayOutput>) {
inlayComponent.addInlayOutputs(inlayOutputs) { removeInlay(inlayComponent) }
}
private fun removeInlay(inlayComponent: NotebookInlayComponentPsi, cleanup: Boolean = true) {
val cell = inlayComponent.cell
if (cleanup && cell.isValid) descriptor.cleanup(cell)
inlayComponent.parent?.remove(inlayComponent)
inlayComponent.disposeInlay()
inlayComponent.dispose()
inlays.remove(cell)
}
private fun addFoldingListener() {
data class Region(val textRange: TextRange, val isExpanded: Boolean)
val listener = object : FoldingListener {
private val regions = ArrayList<Region>()
override fun onFoldRegionStateChange(region: FoldRegion) {
if(region.isValid) {
regions.add(Region(TextRange.create(region.startOffset, region.endOffset), region.isExpanded))
}
}
override fun onFoldProcessingEnd() {
inlays.filter { pair -> isOutputPositionCollapsed(pair.key) }.forEach {
removeInlay(it.value, cleanup = false)
}
inlayElements.filter { key -> regions.filter { it.isExpanded }.any { key.textRange.intersects(it.textRange) } }.forEach {
updateCell(it)
}
regions.clear()
updateInlays()
}
}
editor.foldingModel.addListener(listener, editor.disposable)
}
private fun addDocumentListener() {
editor.document.addDocumentListener(object : DocumentListener {
override fun documentChanged(event: DocumentEvent) {
if (project.isDisposed()) return
if (!toolbarUpdateScheduled) {
toolbarUpdateScheduled = true
PsiDocumentManager.getInstance(project).performForCommittedDocument(editor.document) {
try {
scheduleIntervalUpdate(event.offset, event.newFragment.length)
} finally {
toolbarUpdateScheduled = false
}
}
}
if (!descriptor.shouldUpdateInlays(event)) return
PsiDocumentManager.getInstance(project).performForCommittedDocument(editor.document) {
updateInlays()
}
}
}, editor.disposable)
}
private fun scheduleIntervalUpdate(offset: Int, length: Int) {
val psiFile = descriptor.psiFile
var node = psiFile.node.findLeafElementAt(offset)?.psi
while (node != null && node.parent != psiFile) {
node = node.parent
}
inlayElements.filter { !it.isValid }.forEach { getInlayComponent(it)?.let { inlay -> removeInlay(inlay) } }
inlayElements.removeIf { !it.isValid }
while (node != null && node.textRange.startOffset < offset + length) {
PsiTreeUtil.collectElements(node) { psi -> descriptor.isInlayElement(psi) }.forEach { psi ->
inlayElements.add(psi)
}
node = node.nextSibling
}
}
/** On editor resize all inlays got width of editor. */
private fun addResizeListener() {
editor.component.addComponentListener(object : ComponentAdapter() {
override fun componentResized(e: ComponentEvent) {
updateInlayComponentsWidth()
}
})
}
private fun addViewportListener() {
editor.scrollPane.viewport.addChangeListener {
viewportQueue.queue(object : Update(VIEWPORT_TASK_IDENTITY) {
override fun run() {
updateInlaysForViewport()
}
})
}
}
private fun restoreOutputs() {
updateInlaysForViewport()
}
private fun restoreToolbars(): CancellablePromise<*> {
val inlaysPsiElements = ArrayList<PsiElement>()
return ReadAction.nonBlocking {
PsiTreeUtil.processElements(descriptor.psiFile) { element ->
if (descriptor.isInlayElement(element)) inlaysPsiElements.add(element)
true
}
}.finishOnUiThread(ModalityState.NON_MODAL) {
inlayElements.clear()
inlayElements.addAll(inlaysPsiElements)
}.inSmartMode(project).submit(NonUrgentExecutor.getInstance())
}
private fun getInlayComponentByOffset(offset: Int): NotebookInlayComponentPsi? {
return if (offset == editor.document.textLength)
inlays.entries.firstOrNull { it.key.textRange.containsOffset(offset) }?.value
else
inlays.entries.firstOrNull { it.key.textRange.contains(offset) }?.value
}
/** Add caret listener for editor to draw highlighted background for psiCell under caret. */
private fun addCaretListener() {
editor.caretModel.addCaretListener(object : CaretListener {
override fun caretPositionChanged(e: CaretEvent) {
if (editor.caretModel.primaryCaret != e.caret) return
onCaretPositionChanged()
}
}, editor.disposable)
}
private fun onCaretPositionChanged() {
if (editor.isDisposed) {
return
}
val cellUnderCaret = getInlayComponentByOffset(editor.logicalPositionToOffset(editor.caretModel.logicalPosition))
if (cellUnderCaret == null) {
inlays.values.forEach { it.selected = false }
}
else {
if (!cellUnderCaret.selected) {
inlays.values.forEach { it.selected = false }
cellUnderCaret.selected = true
}
}
}
/** When we are adding or removing paragraphs, old cells can change their text ranges*/
private fun updateInlays() {
inlays.values.forEach { updateInlayPosition(it) }
}
private fun setupInlayComponent(inlayComponent: NotebookInlayComponentPsi) {
fun updateInlaysInEditor(editor: Editor) {
val end = editor.xyToLogicalPosition(Point(0, Int.MAX_VALUE))
val offsetEnd = editor.logicalPositionToOffset(end)
val inlays = editor.inlayModel.getBlockElementsInRange(0, offsetEnd)
inlays.forEach { inlay ->
if (inlay.renderer is InlayComponent) {
(inlay.renderer as InlayComponent).updateComponentBounds(inlay)
}
}
}
inlayComponent.beforeHeightChanged = {
scrollKeeper.savePosition()
}
inlayComponent.afterHeightChanged = {
updateInlaysInEditor(editor)
scrollKeeper.restorePosition(true)
}
}
/** Aligns all editor inlays to fill full width of editor. */
private fun updateInlayComponentsWidth() {
val inlayWidth = InlayDimensions.calculateInlayWidth(editor)
if (inlayWidth > 0) {
inlays.values.forEach {
it.setSize(inlayWidth, it.height)
it.inlay?.updateSize()
}
}
}
/** It could be that user started to type below inlay. In this case we will detect new position and perform inlay repositioning. */
private fun updateInlayPosition(inlayComponent: NotebookInlayComponentPsi) {
// editedCell here contains old text. This event will be processed by PSI later.
val offset = descriptor.getInlayOffset(inlayComponent.cell)
if (inlayComponent.inlay!!.offset != offset) {
inlayComponent.disposeInlay()
val inlay = addBlockElement(offset, inlayComponent)
inlayComponent.assignInlay(inlay)
}
inlayComponent.updateComponentBounds(inlayComponent.inlay!!)
}
private fun addBlockElement(offset: Int, inlayComponent: NotebookInlayComponentPsi): Inlay<NotebookInlayComponentPsi> {
return editor.inlayModel.addBlockElement(offset, true, false, INLAY_PRIORITY, inlayComponent)
}
private fun addInlayComponent(cell: PsiElement): NotebookInlayComponentPsi {
val existingInlay = inlays[cell]
if (existingInlay != null) {
throw Exception("Cell already added.")
}
InlayDimensions.init(editor)
val offset = descriptor.getInlayOffset(cell)
val inlayComponent = NotebookInlayComponentPsi(cell, editor)
// On editor creation it has 0 width
val gutterWidth = (editor.gutter as EditorGutterComponentEx).width
var editorWideWidth = editor.component.width - inlayComponent.width - gutterWidth - InlayDimensions.rightBorder
if (editorWideWidth <= 0) {
editorWideWidth = InlayDimensions.width
}
inlayComponent.setBounds(0, editor.offsetToXY(offset).y + editor.lineHeight, editorWideWidth, InlayDimensions.smallHeight)
editor.contentComponent.add(inlayComponent)
val inlay = addBlockElement(offset, inlayComponent)
inlayComponent.assignInlay(inlay)
inlays[cell] = inlayComponent
setupInlayComponent(inlayComponent)
return inlayComponent
}
private fun getInlayComponent(cell: PsiElement): NotebookInlayComponentPsi? {
return inlays[cell]
}
companion object {
private const val VIEWPORT_TASK_NAME = "On viewport change"
private const val VIEWPORT_TASK_IDENTITY = "On viewport change task"
private const val VIEWPORT_TIME_SPAN = 50
const val INLAY_PRIORITY = 0
@TestOnly
var isEnabledInTests: Boolean = false
}
}
const val VIEWPORT_INLAY_RANGE = 20
fun calculateViewportRange(editor: EditorImpl): IntRange {
val viewport = editor.scrollPane.viewport
val yMin = viewport.viewPosition.y
val yMax = yMin + viewport.height
return yMin until yMax
}
fun calculateInlayExpansionRange(editor: EditorImpl, viewportRange: IntRange): IntRange {
val startLine = editor.xyToLogicalPosition(Point(0, viewportRange.first)).line
val endLine = editor.xyToLogicalPosition(Point(0, viewportRange.last + 1)).line
val startOffset = editor.document.getLineStartOffset(max(startLine - VIEWPORT_INLAY_RANGE, 0))
val endOffset = editor.document.getLineStartOffset(max(min(endLine + VIEWPORT_INLAY_RANGE, editor.document.lineCount - 1), 0))
return startOffset..endOffset
} | apache-2.0 | f5b573c455579ccdfae25a113a96471b | 34.829646 | 140 | 0.715821 | 4.748974 | false | false | false | false |
ThatsNoMoon/KDA | src/main/kotlin/com/thatsnomoon/kda/extensions/RestActionExtensions.kt | 1 | 6125 | /*
* Copyright 2018 Benjamin Scherer
*
* 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.thatsnomoon.kda.extensions
import com.thatsnomoon.kda.globalCoroutineContext
import com.thatsnomoon.kda.toDuration
import kotlinx.coroutines.experimental.Deferred
import kotlinx.coroutines.experimental.async
import kotlinx.coroutines.experimental.channels.ReceiveChannel
import kotlinx.coroutines.experimental.channels.produce
import kotlinx.coroutines.experimental.future.asDeferred
import kotlinx.coroutines.experimental.future.await
import kotlinx.coroutines.experimental.time.delay
import net.dv8tion.jda.core.requests.RestAction
import net.dv8tion.jda.core.requests.restaction.pagination.PaginationAction
import java.time.Duration
import java.util.concurrent.TimeUnit
/**
* Queues and converts this RestAction into a [Deferred]3
*
* @return Deferred that resolves to the result of this action
*/
fun <T> RestAction<T>.asDeferred(): Deferred<T> = this.submit().asDeferred()
/**
* Suspends until this RestAction is complete3
*
* @return The result of this action
*/
suspend fun <T> RestAction<T>.await(): T = this.submit().await()
/**
* Queues this RestAction after [delay] and converts it into a [Deferred].
*
* @param delay [Duration] to wait before queueing this action
*
* @return Deferred that resolves to the result of this action
*/
infix fun <T> RestAction<T>.after(delay: Duration): Deferred<T> = async(globalCoroutineContext) {
delay(delay)
[email protected]()
}
/**
* Queues this RestAction after [delay] in [TimeUnit] and converts it into a [Deferred].
*
* @param delay Time to wait before queueing this action
* @param unit Unit of [delay]
*
* @return Deferred that resolves to the result of this action
*/
fun <T> RestAction<T>.after(delay: Long, unit: TimeUnit): Deferred<T> = this after toDuration(delay, unit)
/**
* Maps the result of this [RestAction] to a new value by calling [success].
*
* This is simply a convenience function over [Deferred.map], using [asDeferred].
*
* @param success Function to map the resulting value of this RestAction
* @return A Deferred that resolves to the return value of [success]
*/
inline infix fun <T, U> RestAction<T>.map(crossinline success: suspend (T) -> U): Deferred<U> = this.asDeferred() map success
/**
* Adds a suspending success callback to this RestAction.
*
* This is simply a convenience function over [Deferred.then], using [asDeferred].
*
* @param success Callback to add to this RestAction
*/
inline infix fun <T> RestAction<T>.then(crossinline success: suspend (T) -> Unit) = this.asDeferred() then success
/**
* Maps the result of this RestAction to a new value, "flattening" a nested [Deferred], by calling [success].
*
* This is simply a convenience function over [Deferred.flatMap], using [asDeferred].
*
* @param success Function to map the resulting value of this RestAction
* @return Deferred that resolves to the resolution value of the return value of [success]
*/
inline infix fun <T, U> RestAction<T>.flatMap(crossinline success: suspend (T) -> Deferred<U>): Deferred<U> = this.asDeferred() flatMap success
/**
* Adds a suspending failure callback to this RestAction.
*
* This is simply a convenience function over [Deferred.catch], using [asDeferred].
*
* @param failure Failure callback to add to this RestAction
*/
inline infix fun <T> RestAction<T>.catch(crossinline failure: suspend (Throwable) -> Unit) = this.asDeferred() catch failure
/**
* Adds suspending success and failure callbacks to this RestAction.
*
* This is simply a convenience function over [Deferred.accept], using [asDeferred]
*
* @param success Success callback to add to this RestAction
* @param failure Failure callback to add to this RestAction
*/
inline fun <T> RestAction<T>.accept(crossinline success: suspend (T) -> Unit, crossinline failure: suspend (Throwable) -> Unit) = this.asDeferred().accept(success, failure)
/**
* Maps a failed RestAction to a successfully completed [Deferred].
*
* This is simply a convenience function over [Deferred.handle], using [asDeferred]
*
* @param failure Function to map the error of this RestAction to a successful value
* @return A Deferred that resolves to the result of this action if successful, or the return value of [failure] otherwise
*/
inline infix fun <T> RestAction<T>.handle(crossinline failure: suspend (Throwable) -> T): Deferred<T> = this.asDeferred() handle failure
/**
* Maps a successful or failed RestAction to a successfully completed [Deferred].
*
* This is simply a convenience function over [Deferred.apply], using [asDeferred]
*
* @param success Function to map the successful result of this RestAction
* @param failure Function to map the error of this RestAction
* @return A Deferred that resolves to the return value of [success] or [failure]
*/
inline fun <T, U> RestAction<T>.apply(crossinline success: suspend (T) -> U, crossinline failure: suspend (Throwable) -> U): Deferred<U> = this.asDeferred().apply(success, failure)
/**
* Converts this PaginationAction into a [ReceiveChannel] that produces its values.
*
* @return ReceiveChannel that produces the values of this PaginationAction
*/
fun <T, M: PaginationAction<T, M>> PaginationAction<T, M>.toChannel(): ReceiveChannel<T> = produce(globalCoroutineContext) {
var items: List<T> = [email protected]()
var cursor = 0
while (cursor < items.size) {
send(items[cursor])
cursor += 1
if (cursor == items.size) {
items = [email protected]()
cursor = 0
}
}
} | apache-2.0 | 13c67e69603cdc7754e9e1bd61b74488 | 38.779221 | 180 | 0.737306 | 4.105228 | false | false | false | false |
kickstarter/android-oss | app/src/main/java/com/kickstarter/ui/activities/LoginActivity.kt | 1 | 7647 | package com.kickstarter.ui.activities
import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.util.Pair
import com.kickstarter.R
import com.kickstarter.databinding.LoginLayoutBinding
import com.kickstarter.libs.ActivityRequestCodes
import com.kickstarter.libs.BaseActivity
import com.kickstarter.libs.KSString
import com.kickstarter.libs.qualifiers.RequiresActivityViewModel
import com.kickstarter.libs.rx.transformers.Transformers.observeForUI
import com.kickstarter.libs.utils.ObjectUtils
import com.kickstarter.libs.utils.TransitionUtils.slideInFromLeft
import com.kickstarter.libs.utils.ViewUtils
import com.kickstarter.libs.utils.extensions.getResetPasswordIntent
import com.kickstarter.ui.IntentKey
import com.kickstarter.ui.extensions.hideKeyboard
import com.kickstarter.ui.extensions.onChange
import com.kickstarter.ui.extensions.showSnackbar
import com.kickstarter.ui.extensions.text
import com.kickstarter.ui.views.ConfirmDialog
import com.kickstarter.viewmodels.LoginViewModel
@RequiresActivityViewModel(LoginViewModel.ViewModel::class)
class LoginActivity : BaseActivity<LoginViewModel.ViewModel>() {
private var confirmResetPasswordSuccessDialog: ConfirmDialog? = null
private lateinit var ksString: KSString
private val forgotPasswordString = R.string.login_buttons_forgot_password_html
private val forgotPasswordSentEmailString = R.string.forgot_password_we_sent_an_email_to_email_address_with_instructions_to_reset_your_password
private val loginDoesNotMatchString = R.string.login_errors_does_not_match
private val unableToLoginString = R.string.login_errors_unable_to_log_in
private val loginString = R.string.login_buttons_log_in
private val errorTitleString = R.string.login_errors_title
private lateinit var binding: LoginLayoutBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = LoginLayoutBinding.inflate(layoutInflater)
setContentView(binding.root)
this.ksString = requireNotNull(environment().ksString())
binding.loginToolbar.loginToolbar.setTitle(getString(this.loginString))
binding.loginFormView.forgotYourPasswordTextView.text = ViewUtils.html(getString(this.forgotPasswordString))
binding.loginFormView.email.onChange { this.viewModel.inputs.email(it) }
binding.loginFormView.password.onChange { this.viewModel.inputs.password(it) }
errorMessages()
.compose(bindToLifecycle())
.compose(observeForUI())
.subscribe { e -> ViewUtils.showDialog(this, getString(this.errorTitleString), e) }
this.viewModel.outputs.tfaChallenge()
.compose(bindToLifecycle())
.compose(observeForUI())
.subscribe { startTwoFactorActivity() }
this.viewModel.outputs.loginSuccess()
.compose(bindToLifecycle())
.compose(observeForUI())
.subscribe { onSuccess() }
this.viewModel.outputs.prefillEmail()
.compose(bindToLifecycle())
.compose(observeForUI())
.subscribe {
binding.loginFormView.email.setText(it)
binding.loginFormView.email.setSelection(it.length)
}
this.viewModel.outputs.showChangedPasswordSnackbar()
.compose(bindToLifecycle())
.compose(observeForUI())
.subscribe { showSnackbar(binding.loginToolbar.loginToolbar, R.string.Got_it_your_changes_have_been_saved) }
this.viewModel.outputs.showCreatedPasswordSnackbar()
.compose(bindToLifecycle())
.compose(observeForUI())
.subscribe { showSnackbar(binding.loginToolbar.loginToolbar, R.string.Got_it_your_changes_have_been_saved) }
this.viewModel.outputs.showResetPasswordSuccessDialog()
.compose(bindToLifecycle())
.compose(observeForUI())
.subscribe { showAndEmail ->
val show = showAndEmail.first
val email = showAndEmail.second
if (show) {
resetPasswordSuccessDialog(email).show()
} else {
resetPasswordSuccessDialog(email).dismiss()
}
}
this.viewModel.outputs.loginButtonIsEnabled()
.compose(bindToLifecycle())
.compose(observeForUI())
.subscribe({ this.setLoginButtonEnabled(it) })
binding.loginFormView.forgotYourPasswordTextView.setOnClickListener {
startResetPasswordActivity()
}
binding.loginFormView.loginButton.setOnClickListener {
this.viewModel.inputs.loginClick()
[email protected]()
}
}
/**
* Lazily creates a reset password success confirmation dialog and stores it in an instance variable.
*/
private fun resetPasswordSuccessDialog(email: String): ConfirmDialog {
if (this.confirmResetPasswordSuccessDialog == null) {
val message = this.ksString.format(getString(this.forgotPasswordSentEmailString), "email", email)
this.confirmResetPasswordSuccessDialog = ConfirmDialog(this, null, message)
this.confirmResetPasswordSuccessDialog!!
.setOnDismissListener { this.viewModel.inputs.resetPasswordConfirmationDialogDismissed() }
this.confirmResetPasswordSuccessDialog!!
.setOnCancelListener { this.viewModel.inputs.resetPasswordConfirmationDialogDismissed() }
}
return this.confirmResetPasswordSuccessDialog!!
}
private fun errorMessages() =
this.viewModel.outputs.invalidLoginError()
.map(ObjectUtils.coalesceWith(getString(this.loginDoesNotMatchString)))
.mergeWith(
this.viewModel.outputs.genericLoginError()
.map(ObjectUtils.coalesceWith(getString(this.unableToLoginString)))
)
override fun onActivityResult(requestCode: Int, resultCode: Int, intent: Intent?) {
super.onActivityResult(requestCode, resultCode, intent)
if (requestCode != ActivityRequestCodes.LOGIN_FLOW && requestCode != ActivityRequestCodes.RESET_FLOW) {
return
}
if (requestCode != ActivityRequestCodes.RESET_FLOW) {
setResult(resultCode, intent)
finish()
}
}
private fun onSuccess() {
setResult(Activity.RESULT_OK)
finish()
}
private fun setLoginButtonEnabled(enabled: Boolean) {
binding.loginFormView.loginButton.isEnabled = enabled
}
private fun startTwoFactorActivity() {
val intent = Intent(this, TwoFactorActivity::class.java)
.putExtra(IntentKey.EMAIL, binding.loginFormView.email.text())
.putExtra(IntentKey.PASSWORD, binding.loginFormView.password.text())
startActivityForResult(intent, ActivityRequestCodes.LOGIN_FLOW)
overridePendingTransition(R.anim.slide_in_right, R.anim.fade_out_slide_out_left)
}
private fun startResetPasswordActivity() {
val intent = Intent().getResetPasswordIntent(this, email = binding.loginFormView.email.text.toString())
startActivityForResult(intent, ActivityRequestCodes.RESET_FLOW)
overridePendingTransition(R.anim.slide_in_right, R.anim.fade_out_slide_out_left)
}
override fun exitTransition(): Pair<Int, Int>? {
return slideInFromLeft()
}
override fun back() {
if (this.supportFragmentManager.backStackEntryCount == 0) {
super.back()
}
}
}
| apache-2.0 | ae0375461c053201f7685bf5f13ea7e0 | 40.786885 | 147 | 0.697921 | 5.087824 | false | false | false | false |
leafclick/intellij-community | platform/testFramework/src/com/intellij/util/io/FileTreePrinter.kt | 1 | 2065 | // 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.util.io
import com.intellij.util.containers.nullize
import java.nio.charset.MalformedInputException
import java.nio.file.Path
@JvmOverloads
fun Path.getDirectoryTree(excluded: Set<String> = emptySet(), printContent: Boolean = true): String {
val sb = StringBuilder()
getDirectoryTree(this, 0, sb, excluded, printContent = printContent)
return sb.toString()
}
private fun getDirectoryTree(dir: Path, indent: Int, sb: StringBuilder, excluded: Set<String>, printContent: Boolean) {
val fileList = sortedFileList(dir, excluded).nullize() ?: return
getIndentString(indent, sb)
if (printContent) {
sb.append("\u251c\u2500\u2500")
}
sb.append(dir.fileName.toString())
sb.append("/")
sb.append("\n")
for (file in fileList) {
if (file.isDirectory()) {
getDirectoryTree(file, indent + 1, sb, excluded, printContent)
}
else {
printFile(file, indent + 1, sb, printContent)
}
}
}
private fun sortedFileList(dir: Path, excluded: Set<String>): List<Path>? {
return dir.directoryStreamIfExists { stream ->
var sequence = stream.asSequence()
if (excluded.isNotEmpty()) {
sequence = sequence.filter { !excluded.contains(it.fileName.toString()) }
}
val list = sequence.toMutableList()
list.sort()
list
}
}
private fun printFile(file: Path, indent: Int, sb: StringBuilder, printContent: Boolean) {
getIndentString(indent, sb)
if (printContent) {
sb.append("\u251c\u2500\u2500")
}
val fileName = file.fileName.toString()
sb.append(fileName)
sb.append("\n")
if (printContent && !(fileName.endsWith(".zip") || fileName.endsWith(".jar") || fileName.endsWith(".class"))) {
try {
sb.append(file.readChars()).append("\n\n")
}
catch (ignore: MalformedInputException) {
}
}
}
private fun getIndentString(indent: Int, sb: StringBuilder) {
for (i in 0 until indent) {
sb.append(" ")
}
} | apache-2.0 | 913787068b1326ca978aa9e9ea8c2aa6 | 29.382353 | 140 | 0.685714 | 3.720721 | false | false | false | false |
siosio/intellij-community | platform/lang-impl/src/com/intellij/model/psi/impl/targets.kt | 1 | 6988 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.model.psi.impl
import com.intellij.codeInsight.TargetElementUtil
import com.intellij.diagnostic.PluginException
import com.intellij.model.Symbol
import com.intellij.model.psi.PsiSymbolDeclaration
import com.intellij.model.psi.PsiSymbolReference
import com.intellij.openapi.util.TextRange
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiFile
import com.intellij.psi.util.leavesAroundOffset
import com.intellij.util.SmartList
import org.jetbrains.annotations.ApiStatus.Experimental
/**
* Entry point for obtaining target symbols by [offset] in a [file].
*
* @return collection of referenced or declared symbols
*/
@Experimental
fun targetSymbols(file: PsiFile, offset: Int): Collection<Symbol> {
val (declaredData, referencedData) = declaredReferencedData(file, offset)
?: return emptyList()
val data = referencedData
?: declaredData
?: return emptyList()
return data.targets.map { it.symbol }
}
/**
* @return two collections: of declared and of referenced symbols
*/
@Experimental
fun targetDeclarationAndReferenceSymbols(file: PsiFile, offset: Int): Pair<Collection<Symbol>, Collection<Symbol>> {
val (declaredData, referencedData) = declaredReferencedData(file, offset) ?: return Pair(emptyList(), emptyList())
return (declaredData?.targets?.map { it.symbol } ?: emptyList()) to (referencedData?.targets?.map { it.symbol } ?: emptyList())
}
internal fun declaredReferencedData(file: PsiFile, offset: Int): DeclaredReferencedData? {
val allDeclarationsOrReferences: List<DeclarationOrReference> = declarationsOrReferences(file, offset)
if (allDeclarationsOrReferences.isEmpty()) {
return null
}
val withMinimalRanges: Collection<DeclarationOrReference> = try {
chooseByRange(allDeclarationsOrReferences, offset, DeclarationOrReference::rangeWithOffset)
}
catch (e: RangeOverlapException) {
val details = allDeclarationsOrReferences.joinToString(separator = "") { item ->
"\n${item.rangeWithOffset} : $item"
}
LOG.error("Range overlap", PluginException.createByClass(e, file.javaClass), details)
return null
}
var declaration: PsiSymbolDeclaration? = null
val references: MutableList<PsiSymbolReference> = ArrayList()
for (dr in withMinimalRanges) {
when (dr) {
is DeclarationOrReference.Declaration -> {
if (declaration != null) {
LOG.error(
"""
Multiple declarations with the same range are not supported.
Declaration: $declaration; class: ${declaration.javaClass.name}.
Another declaration: ${dr.declaration}; class: ${dr.declaration.javaClass.name}.
""".trimIndent()
)
}
else {
declaration = dr.declaration
}
}
is DeclarationOrReference.Reference -> {
references.add(dr.reference)
}
}
}
return DeclaredReferencedData(
declaredData = declaration?.let(TargetData::Declared),
referencedData = references.takeUnless { it.isEmpty() }?.let(TargetData::Referenced)
)
}
private sealed class DeclarationOrReference {
abstract val rangeWithOffset: TextRange
class Declaration(val declaration: PsiSymbolDeclaration) : DeclarationOrReference() {
override val rangeWithOffset: TextRange get() = declaration.absoluteRange
override fun toString(): String = declaration.toString()
}
class Reference(val reference: PsiSymbolReference, private val offset: Int) : DeclarationOrReference() {
override val rangeWithOffset: TextRange by lazy(LazyThreadSafetyMode.NONE) {
referenceRanges(reference).find {
it.containsOffset(offset)
} ?: error("One of the ranges must contain offset at this point")
}
override fun toString(): String = reference.toString()
}
}
internal fun referenceRanges(it: PsiSymbolReference): List<TextRange> {
return if (it is EvaluatorReference) {
it.origin.absoluteRanges
}
else {
// Symbol references don't support multi-ranges yet.
listOf(it.absoluteRange)
}
}
/**
* @return declarations/references which contain the given [offset] in the [file]
*/
private fun declarationsOrReferences(file: PsiFile, offset: Int): List<DeclarationOrReference> {
val result = SmartList<DeclarationOrReference>()
var foundNamedElement: PsiElement? = null
val allDeclarations = file.allDeclarationsAround(offset)
if (allDeclarations.isEmpty()) {
namedElement(file, offset)?.let { (namedElement, leaf) ->
foundNamedElement = namedElement
val declaration: PsiSymbolDeclaration = PsiElement2Declaration.createFromDeclaredPsiElement(namedElement, leaf)
result += DeclarationOrReference.Declaration(declaration)
}
}
else {
allDeclarations.mapTo(result, DeclarationOrReference::Declaration)
}
val allReferences = file.allReferencesAround(offset)
if (allReferences.isEmpty()) {
fromTargetEvaluator(file, offset)?.let { evaluatorReference ->
if (foundNamedElement != null && evaluatorReference.targetElements.singleOrNull() === foundNamedElement) {
return@let // treat self-reference as a declaration
}
result += DeclarationOrReference.Reference(evaluatorReference, offset)
}
}
else {
allReferences.mapTo(result) { DeclarationOrReference.Reference(it, offset) }
}
return result
}
private data class NamedElementAndLeaf(val namedElement: PsiElement, val leaf: PsiElement)
private fun namedElement(file: PsiFile, offset: Int): NamedElementAndLeaf? {
for ((leaf, _) in file.leavesAroundOffset(offset)) {
val namedElement: PsiElement? = TargetElementUtil.getNamedElement(leaf)
if (namedElement != null) {
return NamedElementAndLeaf(namedElement, leaf)
}
}
return null
}
private fun fromTargetEvaluator(file: PsiFile, offset: Int): EvaluatorReference? {
val editor = mockEditor(file) ?: return null
val flags = TargetElementUtil.getInstance().allAccepted and
TargetElementUtil.ELEMENT_NAME_ACCEPTED.inv() and
TargetElementUtil.LOOKUP_ITEM_ACCEPTED.inv()
val reference = TargetElementUtil.findReference(editor, offset)
val origin: PsiOrigin = if (reference != null) {
PsiOrigin.Reference(reference)
}
else {
val leaf = file.findElementAt(TargetElementUtil.adjustOffset(file, editor.document, offset)) ?: return null
PsiOrigin.Leaf(leaf)
}
val targetElement = TargetElementUtil.getInstance().findTargetElement(editor, flags, offset)
val targetElements: List<PsiElement> = when {
targetElement != null -> listOf(targetElement)
reference != null -> TargetElementUtil.getInstance().getTargetCandidates(reference).toList()
else -> emptyList()
}
if (targetElements.isEmpty()) {
return null
}
return EvaluatorReference(origin, targetElements)
}
| apache-2.0 | b53356bd5a26ae7ab495f31c88debb04 | 35.395833 | 158 | 0.727104 | 4.747283 | false | false | false | false |
siosio/intellij-community | platform/lang-api/src/com/intellij/execution/suggestUsingDashboard.kt | 1 | 2724 | // Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
@file: JvmName("SuggestUsingRunDashBoardUtil")
package com.intellij.execution
import com.intellij.CommonBundle
import com.intellij.execution.configurations.ConfigurationType
import com.intellij.execution.dashboard.RunDashboardManager
import com.intellij.icons.AllIcons
import com.intellij.lang.LangBundle
import com.intellij.notification.*
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.application.runWriteAction
import com.intellij.openapi.project.Project
/**
* If Run Dashboard is not configured for [configurationTypes], show [Notification] allowing to enable dashboard for those configurations.
**/
fun promptUserToUseRunDashboard(project: Project, configurationTypes: Collection<ConfigurationType>) {
ApplicationManager.getApplication().invokeLater {
val currentTypes = RunDashboardManager.getInstance(project).types
val typesToAdd = configurationTypes.filter {
it.id !in currentTypes
}
if (typesToAdd.isNotEmpty()) {
Notifications.Bus.notify(
SuggestDashboardNotification(project, typesToAdd.toSet(), RunDashboardManager.getInstance(project).toolWindowId), project)
}
}
}
private const val suggestRunDashboardId = "Suggest Run Dashboard"
private class SuggestDashboardNotification(
private val project: Project,
types: Set<ConfigurationType>,
toolWindowId: String
) : Notification(
suggestRunDashboardId,
LangBundle.message("notification.title.use.toolwindow", toolWindowId),
LangBundle.message("notification.suggest.dashboard", toolWindowId, toolWindowId,
types.joinToString(prefix = "<b>", postfix = "</b>", separator = "<br>") { it.configurationTypeDescription }),
NotificationType.INFORMATION
) {
init {
icon = AllIcons.RunConfigurations.TestState.Run
addAction(NotificationAction.create(CommonBundle.message("button.without.mnemonic.yes")) { _ ->
ApplicationManager.getApplication().invokeLater {
runWriteAction {
val runDashboardManager = RunDashboardManager.getInstance(project)
runDashboardManager.types = runDashboardManager.types + types.map { it.id }
}
}
expire()
})
addAction(NotificationAction.create(LangBundle.message("button.not.this.time.text")) { _ ->
expire()
})
addAction(NotificationAction.create(LangBundle.message("button.do.not.ask.again.text")) { _ ->
NotificationsConfiguration.getNotificationsConfiguration().changeSettings(
suggestRunDashboardId, NotificationDisplayType.NONE, true, false
)
expire()
})
}
}
| apache-2.0 | 9bf376f89fc41fe3fae6e566bcb33b87 | 40.907692 | 140 | 0.755874 | 4.812721 | false | true | false | false |
jwren/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/highlighter/KotlinRecursiveCallLineMarkerProvider.kt | 3 | 7654 | // 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.highlighter
import com.intellij.codeInsight.daemon.LineMarkerInfo
import com.intellij.codeInsight.daemon.LineMarkerProvider
import com.intellij.icons.AllIcons
import com.intellij.openapi.editor.markup.GutterIconRenderer
import com.intellij.openapi.progress.ProgressManager
import com.intellij.psi.PsiDocumentManager
import com.intellij.psi.PsiElement
import org.jetbrains.kotlin.descriptors.ClassDescriptor
import org.jetbrains.kotlin.descriptors.SimpleFunctionDescriptor
import org.jetbrains.kotlin.idea.KotlinBundle
import org.jetbrains.kotlin.idea.caches.resolve.analyze
import org.jetbrains.kotlin.idea.highlighter.markers.LineMarkerInfos
import org.jetbrains.kotlin.idea.inspections.RecursivePropertyAccessorInspection
import org.jetbrains.kotlin.idea.util.getReceiverTargetDescriptor
import org.jetbrains.kotlin.idea.caches.resolve.safeAnalyzeNonSourceRootCode
import org.jetbrains.kotlin.lexer.KtToken
import org.jetbrains.kotlin.name.Name
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.parents
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.inline.InlineUtil
import org.jetbrains.kotlin.resolve.scopes.receivers.Receiver
import org.jetbrains.kotlin.resolve.scopes.receivers.ReceiverValue
import org.jetbrains.kotlin.types.expressions.OperatorConventions
import org.jetbrains.kotlin.util.OperatorNameConventions
class KotlinRecursiveCallLineMarkerProvider : LineMarkerProvider {
override fun getLineMarkerInfo(element: PsiElement) = null
override fun collectSlowLineMarkers(elements: MutableList<out PsiElement>, result: LineMarkerInfos) {
val markedLineNumbers = HashSet<Int>()
for (element in elements) {
ProgressManager.checkCanceled()
if (element is KtElement) {
val lineNumber = element.getLineNumber()
if (lineNumber !in markedLineNumbers && isRecursiveCall(element)) {
markedLineNumbers.add(lineNumber)
result.add(RecursiveMethodCallMarkerInfo(getElementForLineMark(element)))
}
}
}
}
private fun getEnclosingFunction(element: KtElement, stopOnNonInlinedLambdas: Boolean): KtNamedFunction? {
for (parent in element.parents) {
when (parent) {
is KtFunctionLiteral -> if (stopOnNonInlinedLambdas && !InlineUtil.isInlinedArgument(
parent,
parent.analyze(),
false
)
) return null
is KtNamedFunction -> {
when (parent.parent) {
is KtBlockExpression, is KtClassBody, is KtFile, is KtScript -> return parent
else -> if (stopOnNonInlinedLambdas && !InlineUtil.isInlinedArgument(parent, parent.analyze(), false)) return null
}
}
is KtClassOrObject -> return null
}
}
return null
}
private fun isRecursiveCall(element: KtElement): Boolean {
if (RecursivePropertyAccessorInspection.isRecursivePropertyAccess(element)) return true
if (RecursivePropertyAccessorInspection.isRecursiveSyntheticPropertyAccess(element)) return true
// Fast check for names without resolve
val resolveName = getCallNameFromPsi(element) ?: return false
val enclosingFunction = getEnclosingFunction(element, false) ?: return false
val enclosingFunctionName = enclosingFunction.name
if (enclosingFunctionName != OperatorNameConventions.INVOKE.asString()
&& enclosingFunctionName != resolveName.asString()
) return false
// Check that there were no not-inlined lambdas on the way to enclosing function
if (enclosingFunction != getEnclosingFunction(element, true)) return false
val bindingContext = element.safeAnalyzeNonSourceRootCode()
val enclosingFunctionDescriptor = bindingContext[BindingContext.FUNCTION, enclosingFunction] ?: return false
val call = bindingContext[BindingContext.CALL, element] ?: return false
val resolvedCall = bindingContext[BindingContext.RESOLVED_CALL, call] ?: return false
if (resolvedCall.candidateDescriptor.original != enclosingFunctionDescriptor) return false
fun isDifferentReceiver(receiver: Receiver?): Boolean {
if (receiver !is ReceiverValue) return false
val receiverOwner = receiver.getReceiverTargetDescriptor(bindingContext) ?: return true
return when (receiverOwner) {
is SimpleFunctionDescriptor -> receiverOwner != enclosingFunctionDescriptor
is ClassDescriptor -> receiverOwner != enclosingFunctionDescriptor.containingDeclaration
else -> return true
}
}
if (isDifferentReceiver(resolvedCall.dispatchReceiver)) return false
return true
}
private class RecursiveMethodCallMarkerInfo(callElement: PsiElement) : LineMarkerInfo<PsiElement>(
callElement,
callElement.textRange,
AllIcons.Gutter.RecursiveMethod,
{ KotlinBundle.message("highlighter.tool.tip.text.recursive.call") },
null,
GutterIconRenderer.Alignment.RIGHT,
{ KotlinBundle.message("highlighter.tool.tip.text.recursive.call") }
) {
override fun createGutterRenderer(): GutterIconRenderer {
return object : LineMarkerInfo.LineMarkerGutterIconRenderer<PsiElement>(this) {
override fun getClickAction() = null // to place breakpoint on mouse click
}
}
}
}
internal fun getElementForLineMark(callElement: PsiElement): PsiElement = when (callElement) {
is KtSimpleNameExpression -> callElement.getReferencedNameElement()
else ->
// a fallback,
//but who knows what to reference in KtArrayAccessExpression ?
generateSequence(callElement) { it.firstChild }.last()
}
private fun PsiElement.getLineNumber(): Int {
return PsiDocumentManager.getInstance(project).getDocument(containingFile)!!.getLineNumber(textOffset)
}
private fun getCallNameFromPsi(element: KtElement): Name? {
when (element) {
is KtSimpleNameExpression -> when (val elementParent = element.getParent()) {
is KtCallExpression -> return Name.identifier(element.getText())
is KtOperationExpression -> {
val operationReference = elementParent.operationReference
if (element == operationReference) {
val node = operationReference.getReferencedNameElementType()
return if (node is KtToken) {
val conventionName = if (elementParent is KtPrefixExpression)
OperatorConventions.getNameForOperationSymbol(node, true, false)
else
OperatorConventions.getNameForOperationSymbol(node)
conventionName ?: Name.identifier(element.getText())
} else {
Name.identifier(element.getText())
}
}
}
}
is KtArrayAccessExpression -> return OperatorNameConventions.GET
is KtThisExpression -> if (element.getParent() is KtCallExpression) return OperatorNameConventions.INVOKE
}
return null
}
| apache-2.0 | fd7608b9a8bf716c34de0484f91931f2 | 44.832335 | 158 | 0.688921 | 5.716206 | false | false | false | false |
dahlstrom-g/intellij-community | plugins/kotlin/jvm-debugger/test/testData/evaluation/singleBreakpoint/compilingEvaluator/inaccessibleMembers/javaFields.kt | 10 | 1485 | // FILE: lib/JavaFields.java
package lib;
public class JavaFields {
private static String s = "s";
static int i = 1;
private static double d = 2.0;
private static boolean b = true;
String is = "is";
private int ii = 2;
private double id = 3.0;
private boolean ib = false;
public JavaFields() {}
}
// FILE: test.kt
package foo
import lib.JavaFields
fun main() {
val f = JavaFields()
//Breakpoint!
val a = 0
}
fun <T> block(block: () -> T): T {
return block()
}
// EXPRESSION: block { JavaFields.s = "ss" }
// RESULT: VOID_VALUE
// EXPRESSION: block { JavaFields.s }
// RESULT: "ss": Ljava/lang/String;
// EXPRESSION: block { JavaFields.i = 2 }
// RESULT: VOID_VALUE
// EXPRESSION: block { JavaFields.i }
// RESULT: 2: I
// EXPRESSION: block { JavaFields.d = -4.0 }
// RESULT: VOID_VALUE
// EXPRESSION: block { JavaFields.d }
// RESULT: -4.0: D
// EXPRESSION: block { JavaFields.b = false }
// RESULT: VOID_VALUE
// EXPRESSION: block { JavaFields.b }
// RESULT: 0: Z
// EXPRESSION: block { f.`is` = "isis" }
// RESULT: VOID_VALUE
// EXPRESSION: block { f.`is` }
// RESULT: "isis": Ljava/lang/String;
// EXPRESSION: block { f.ii = 4 }
// RESULT: VOID_VALUE
// EXPRESSION: block { f.ii }
// RESULT: 4: I
// EXPRESSION: block { f.id = 6.0 }
// RESULT: VOID_VALUE
// EXPRESSION: block { f.id }
// RESULT: 6.0: D
// EXPRESSION: block { f.ib = true }
// RESULT: VOID_VALUE
// EXPRESSION: block { f.ib }
// RESULT: 1: Z | apache-2.0 | 6b753ff527be7f3968ed4adb6f65b61a | 17.810127 | 45 | 0.606734 | 3.049281 | false | false | false | false |
JetBrains/intellij-community | plugins/kotlin/code-insight/structural-search-k1/src/org/jetbrains/kotlin/idea/structuralsearch/KotlinStructuralSearchProfile.kt | 2 | 18518 | // 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.structuralsearch
import com.intellij.lang.Language
import com.intellij.openapi.fileTypes.LanguageFileType
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.Key
import com.intellij.openapi.util.text.StringUtil
import com.intellij.psi.PsiComment
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiErrorElement
import com.intellij.psi.PsiWhiteSpace
import com.intellij.psi.util.elementType
import com.intellij.structuralsearch.*
import com.intellij.structuralsearch.impl.matcher.CompiledPattern
import com.intellij.structuralsearch.impl.matcher.GlobalMatchingVisitor
import com.intellij.structuralsearch.impl.matcher.PatternTreeContext
import com.intellij.structuralsearch.impl.matcher.compiler.GlobalCompilingVisitor
import com.intellij.structuralsearch.impl.matcher.predicates.MatchPredicate
import com.intellij.structuralsearch.impl.matcher.predicates.NotPredicate
import com.intellij.structuralsearch.plugin.replace.ReplaceOptions
import com.intellij.structuralsearch.plugin.ui.Configuration
import com.intellij.structuralsearch.plugin.ui.UIUtil
import com.intellij.util.SmartList
import org.jetbrains.kotlin.idea.KotlinFileType
import org.jetbrains.kotlin.idea.KotlinLanguage
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.liveTemplates.KotlinTemplateContextType
import org.jetbrains.kotlin.idea.structuralsearch.filters.*
import org.jetbrains.kotlin.idea.structuralsearch.predicates.KotlinAlsoMatchCompanionObjectPredicate
import org.jetbrains.kotlin.idea.structuralsearch.predicates.KotlinAlsoMatchValVarPredicate
import org.jetbrains.kotlin.idea.structuralsearch.predicates.KotlinExprTypePredicate
import org.jetbrains.kotlin.idea.structuralsearch.predicates.KotlinMatchCallSemantics
import org.jetbrains.kotlin.idea.structuralsearch.visitor.KotlinCompilingVisitor
import org.jetbrains.kotlin.idea.structuralsearch.visitor.KotlinMatchingVisitor
import org.jetbrains.kotlin.idea.structuralsearch.visitor.KotlinRecursiveElementWalkingVisitor
import org.jetbrains.kotlin.kdoc.psi.impl.KDocTag
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.psi.*
class KotlinStructuralSearchProfile : StructuralSearchProfile() {
override fun isMatchNode(element: PsiElement?): Boolean = element !is PsiWhiteSpace
override fun createMatchingVisitor(globalVisitor: GlobalMatchingVisitor): KotlinMatchingVisitor =
KotlinMatchingVisitor(globalVisitor)
override fun createCompiledPattern(): CompiledPattern = object : CompiledPattern() {
init {
strategy = KotlinMatchingStrategy
}
override fun getTypedVarPrefixes(): Array<String> = arrayOf(TYPED_VAR_PREFIX)
override fun isTypedVar(str: String): Boolean = when {
str.isEmpty() -> false
str[0] == '@' -> str.regionMatches(1, TYPED_VAR_PREFIX, 0, TYPED_VAR_PREFIX.length)
else -> str.startsWith(TYPED_VAR_PREFIX)
}
override fun getTypedVarString(element: PsiElement): String {
val typedVarString = super.getTypedVarString(element)
return if (typedVarString.firstOrNull() == '@') typedVarString.drop(1) else typedVarString
}
}
override fun isMyLanguage(language: Language): Boolean = language == KotlinLanguage.INSTANCE
override fun getTemplateContextTypeClass(): Class<KotlinTemplateContextType.Generic> = KotlinTemplateContextType.Generic::class.java
override fun getPredefinedTemplates(): Array<Configuration> = KotlinPredefinedConfigurations.createPredefinedTemplates()
override fun getDefaultFileType(fileType: LanguageFileType?): LanguageFileType = fileType ?: KotlinFileType.INSTANCE
override fun supportsShortenFQNames(): Boolean = true
override fun compile(elements: Array<out PsiElement>, globalVisitor: GlobalCompilingVisitor) {
KotlinCompilingVisitor(globalVisitor).compile(elements)
}
override fun getPresentableElement(element: PsiElement): PsiElement {
val elem = if (isIdentifier(element)) element.parent else return element
return if(elem is KtReferenceExpression) elem.parent else elem
}
override fun isIdentifier(element: PsiElement?): Boolean = element != null && element.node?.elementType == KtTokens.IDENTIFIER
override fun createPatternTree(
text: String,
context: PatternTreeContext,
fileType: LanguageFileType,
language: Language,
contextId: String?,
project: Project,
physical: Boolean
): Array<PsiElement> {
var elements: List<PsiElement>
val factory = KtPsiFactory(project, false)
if (PROPERTY_CONTEXT.id == contextId) {
try {
val fragment = factory.createProperty(text)
elements = listOf(getNonWhitespaceChildren(fragment).first().parent)
if (elements.first() !is KtProperty) return PsiElement.EMPTY_ARRAY
} catch (e: Exception) {
return arrayOf(factory.createComment("//").apply {
putUserData(PATTERN_ERROR, KotlinBundle.message("error.context.getter.or.setter"))
})
}
} else {
val fragment = factory.createBlockCodeFragment("Unit\n$text", null).let {
if (physical) it else it.copy() // workaround to create non-physical code fragment
}
elements = when (fragment.lastChild) {
is PsiComment -> getNonWhitespaceChildren(fragment).drop(1)
else -> getNonWhitespaceChildren(fragment.firstChild).drop(1)
}
}
if (elements.isEmpty()) return PsiElement.EMPTY_ARRAY
// Standalone KtAnnotationEntry support
if (elements.first() is KtAnnotatedExpression && elements.first().lastChild is PsiErrorElement)
elements = getNonWhitespaceChildren(elements.first()).dropLast(1)
// Standalone KtNullableType || KtUserType w/ type parameter support
if (elements.last() is PsiErrorElement && elements.last().firstChild.elementType == KtTokens.QUEST
|| elements.first() is KtCallExpression && (elements.first() as KtCallExpression).valueArgumentList == null) {
try {
val fragment = factory.createType(text)
elements = listOf(getNonWhitespaceChildren(fragment).first().parent)
} catch (e: Exception) {}
}
// for (element in elements) print(DebugUtil.psiToString(element, false))
return elements.toTypedArray()
}
inner class KotlinValidator : KotlinRecursiveElementWalkingVisitor() {
override fun visitErrorElement(element: PsiErrorElement) {
super.visitErrorElement(element)
if (shouldShowProblem(element)) {
throw MalformedPatternException(element.errorDescription)
}
}
override fun visitComment(comment: PsiComment) {
super.visitComment(comment)
comment.getUserData(PATTERN_ERROR)?.let { error ->
throw MalformedPatternException(error)
}
}
}
override fun checkSearchPattern(pattern: CompiledPattern) {
val visitor = KotlinValidator()
val nodes = pattern.nodes
while (nodes.hasNext()) {
nodes.current().accept(visitor)
nodes.advance()
}
nodes.reset()
}
override fun shouldShowProblem(error: PsiErrorElement): Boolean {
val description = error.errorDescription
val parent = error.parent
return when {
parent is KtTryExpression && KotlinBundle.message("error.expected.catch.or.finally") == description -> false //naked try
parent is KtAnnotatedExpression && KotlinBundle.message("error.expected.an.expression") == description -> false
else -> true
}
}
override fun checkReplacementPattern(project: Project, options: ReplaceOptions) {
val matchOptions = options.matchOptions
val fileType = matchOptions.fileType!!
val dialect = matchOptions.dialect!!
val searchIsDeclaration = isProbableExpression(matchOptions.searchPattern, fileType, dialect, project)
val replacementIsDeclaration = isProbableExpression(options.replacement, fileType, dialect, project)
if (searchIsDeclaration != replacementIsDeclaration) {
throw UnsupportedPatternException(
if (searchIsDeclaration) SSRBundle.message("replacement.template.is.not.expression.error.message")
else SSRBundle.message("search.template.is.not.expression.error.message")
)
}
}
private fun ancestors(node: PsiElement?): List<PsiElement?> {
val family = mutableListOf(node)
repeat(7) { family.add(family.last()?.parent) }
return family.drop(1)
}
override fun isApplicableConstraint(
constraintName: String,
variableNode: PsiElement?,
completePattern: Boolean,
target: Boolean
): Boolean {
if (variableNode != null)
return when (constraintName) {
UIUtil.TYPE, UIUtil.TYPE_REGEX -> isApplicableType(variableNode)
UIUtil.MINIMUM_ZERO -> isApplicableMinCount(variableNode) || isApplicableMinMaxCount(variableNode)
UIUtil.MAXIMUM_UNLIMITED -> isApplicableMaxCount(variableNode) || isApplicableMinMaxCount(variableNode)
UIUtil.TEXT_HIERARCHY -> isApplicableTextHierarchy(variableNode)
UIUtil.REFERENCE -> isApplicableReference(variableNode)
AlsoMatchVarModifier.CONSTRAINT_NAME -> variableNode.parent is KtProperty && !(variableNode.parent as KtProperty).isVar
AlsoMatchValModifier.CONSTRAINT_NAME -> variableNode.parent is KtProperty && (variableNode.parent as KtProperty).isVar
AlsoMatchCompanionObjectModifier.CONSTRAINT_NAME -> variableNode.parent is KtObjectDeclaration &&
!(variableNode.parent as KtObjectDeclaration).isCompanion()
MatchCallSemanticsModifier.CONSTRAINT_NAME -> variableNode.parent.parent is KtCallElement
else -> super.isApplicableConstraint(constraintName, variableNode, completePattern, target)
}
return super.isApplicableConstraint(constraintName, null as PsiElement?, completePattern, target)
}
private fun isApplicableReference(variableNode: PsiElement): Boolean = variableNode.parent is KtNameReferenceExpression
private fun isApplicableTextHierarchy(variableNode: PsiElement): Boolean {
val family = ancestors(variableNode)
return when {
family[0] is KtClass && (family[0] as KtClass).nameIdentifier == variableNode -> true
family[0] is KtObjectDeclaration && (family[0] as KtObjectDeclaration).nameIdentifier == variableNode -> true
family[0] is KtEnumEntry && (family[0] as KtEnumEntry).nameIdentifier == variableNode -> true
family[0] is KtNamedDeclaration && family[2] is KtClassOrObject -> true
family[3] is KtSuperTypeListEntry && family[5] is KtClassOrObject -> true
family[4] is KtSuperTypeListEntry && family[6] is KtClassOrObject -> true
else -> false
}
}
private fun isApplicableType(variableNode: PsiElement): Boolean {
val family = ancestors(variableNode)
return when {
family[0] is KtNameReferenceExpression -> when (family[1]) {
is KtValueArgument,
is KtProperty,
is KtBinaryExpression, is KtBinaryExpressionWithTypeRHS,
is KtIsExpression,
is KtBlockExpression,
is KtContainerNode,
is KtArrayAccessExpression,
is KtPostfixExpression,
is KtDotQualifiedExpression,
is KtSafeQualifiedExpression,
is KtCallableReferenceExpression,
is KtSimpleNameStringTemplateEntry, is KtBlockStringTemplateEntry,
is KtPropertyAccessor,
is KtWhenEntry -> true
else -> false
}
family[0] is KtProperty -> true
family[0] is KtParameter -> true
else -> false
}
}
/**
* Returns true if the largest count filter should be [0; 1].
*/
private fun isApplicableMinCount(variableNode: PsiElement): Boolean {
val family = ancestors(variableNode)
return when {
family[0] is KtObjectDeclaration -> true
family[0] !is KtNameReferenceExpression -> false
family[1] is KtProperty -> true
family[1] is KtDotQualifiedExpression -> true
family[1] is KtCallableReferenceExpression && family[0]?.nextSibling.elementType == KtTokens.COLONCOLON -> true
family[1] is KtWhenExpression -> true
family[2] is KtTypeReference && family[3] is KtNamedFunction -> true
family[3] is KtConstructorCalleeExpression -> true
else -> false
}
}
/**
* Returns true if the largest count filter should be [1; +inf].
*/
private fun isApplicableMaxCount(variableNode: PsiElement): Boolean {
val family = ancestors(variableNode)
return when {
family[0] is KtDestructuringDeclarationEntry -> true
family[0] is KtNameReferenceExpression && family[1] is KtWhenConditionWithExpression -> true
else -> false
}
}
/**
* Returns true if the largest count filter should be [0; +inf].
*/
private fun isApplicableMinMaxCount(variableNode: PsiElement): Boolean {
val family = ancestors(variableNode)
return when {
// Containers (lists, bodies, ...)
family[0] is KtObjectDeclaration -> false
family[1] is KtClassBody -> true
family[0] is KtParameter && family[1] is KtParameterList -> true
family[0] is KtTypeParameter && family[1] is KtTypeParameterList -> true
family[2] is KtTypeParameter && family[3] is KtTypeParameterList -> true
family[1] is KtUserType && family[4] is KtParameterList && family[5] !is KtNamedFunction -> true
family[1] is KtUserType && family[3] is KtSuperTypeEntry -> true
family[1] is KtValueArgument && family[2] is KtValueArgumentList -> true
family[1] is KtBlockExpression && family[3] is KtDoWhileExpression -> true
family[0] is KtNameReferenceExpression && family[1] is KtBlockExpression -> true
family[1] is KtUserType && family[3] is KtTypeProjection && family[5] !is KtNamedFunction -> true
// Annotations
family[1] is KtUserType && family[4] is KtAnnotationEntry -> true
family[1] is KtCollectionLiteralExpression -> true
// Strings
family[1] is KtSimpleNameStringTemplateEntry -> true
// KDoc
family[0] is KDocTag -> true
// Default: count filter not applicable
else -> false
}
}
override fun getCustomPredicates(
constraint: MatchVariableConstraint,
name: String,
options: MatchOptions
): MutableList<MatchPredicate> {
val result = SmartList<MatchPredicate>()
constraint.apply {
if (!StringUtil.isEmptyOrSpaces(nameOfExprType)) {
val predicate = KotlinExprTypePredicate(
search = if (isRegexExprType) nameOfExprType else expressionTypes,
withinHierarchy = isExprTypeWithinHierarchy,
ignoreCase = !options.isCaseSensitiveMatch,
target = isPartOfSearchResults,
baseName = name,
regex = isRegexExprType
)
result.add(if (isInvertExprType) NotPredicate(predicate) else predicate)
}
if (getAdditionalConstraint(AlsoMatchValModifier.CONSTRAINT_NAME) == OneStateFilter.ENABLED ||
getAdditionalConstraint(AlsoMatchVarModifier.CONSTRAINT_NAME) == OneStateFilter.ENABLED
) result.add(KotlinAlsoMatchValVarPredicate())
if (getAdditionalConstraint(AlsoMatchCompanionObjectModifier.CONSTRAINT_NAME) == OneStateFilter.ENABLED) {
result.add(KotlinAlsoMatchCompanionObjectPredicate())
}
if (getAdditionalConstraint(MatchCallSemanticsModifier.CONSTRAINT_NAME) == OneStateFilter.ENABLED) {
result.add(KotlinMatchCallSemantics())
}
}
return result
}
private fun isProbableExpression(pattern: String, fileType: LanguageFileType, dialect: Language, project: Project): Boolean {
if(pattern.isEmpty()) return false
val searchElements = try {
createPatternTree(pattern, PatternTreeContext.Block, fileType, dialect, null, project, false)
} catch (e: Exception) { return false }
if (searchElements.isEmpty()) return false
return searchElements[0] is KtDeclaration
}
override fun getReplaceHandler(project: Project, replaceOptions: ReplaceOptions): KotlinStructuralReplaceHandler =
KotlinStructuralReplaceHandler(project)
override fun getPatternContexts(): MutableList<PatternContext> = PATTERN_CONTEXTS
companion object {
const val TYPED_VAR_PREFIX: String = "_____"
val DEFAULT_CONTEXT: PatternContext = PatternContext("default", KotlinBundle.lazyMessage("context.default"))
val PROPERTY_CONTEXT: PatternContext = PatternContext("property", KotlinBundle.lazyMessage("context.property.getter.or.setter"))
private val PATTERN_CONTEXTS: MutableList<PatternContext> = mutableListOf(DEFAULT_CONTEXT, PROPERTY_CONTEXT)
private val PATTERN_ERROR: Key<String> = Key("patternError")
fun getNonWhitespaceChildren(fragment: PsiElement): List<PsiElement> {
var element = fragment.firstChild
val result: MutableList<PsiElement> = SmartList()
while (element != null) {
if (element !is PsiWhiteSpace) result.add(element)
element = element.nextSibling
}
return result
}
}
} | apache-2.0 | 80605f209228aa063bf3c71ef607dbeb | 47.479058 | 136 | 0.677341 | 5.394116 | false | false | false | false |
androidx/androidx | compose/material/material/src/commonMain/kotlin/androidx/compose/material/ListItem.kt | 3 | 15905 | /*
* Copyright 2019 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.compose.material
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.heightIn
import androidx.compose.foundation.layout.sizeIn
import androidx.compose.foundation.layout.widthIn
import androidx.compose.runtime.Composable
import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.layout.AlignmentLine
import androidx.compose.ui.layout.FirstBaseline
import androidx.compose.ui.layout.LastBaseline
import androidx.compose.ui.layout.Layout
import androidx.compose.ui.semantics.semantics
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.unit.Constraints
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.IntSize
import androidx.compose.ui.unit.dp
import androidx.compose.ui.util.fastForEachIndexed
import kotlin.math.max
/**
* <a href="https://material.io/components/lists" class="external" target="_blank">Material Design list</a> item.
*
* Lists are continuous, vertical indexes of text or images.
*
* 
*
* To make this [ListItem] clickable, use [Modifier.clickable].
* To add a background to the [ListItem], wrap it with a [Surface].
*
* This component can be used to achieve the list item templates existing in the spec. For example:
* - one-line items
* @sample androidx.compose.material.samples.OneLineListItems
* - two-line items
* @sample androidx.compose.material.samples.TwoLineListItems
* - three-line items
* @sample androidx.compose.material.samples.ThreeLineListItems
*
* You can combine this component with a checkbox or switch as in the following examples:
* @sample androidx.compose.material.samples.ClickableListItems
*
* @param modifier Modifier to be applied to the list item
* @param icon The leading supporting visual of the list item
* @param secondaryText The secondary text of the list item
* @param singleLineSecondaryText Whether the secondary text is single line
* @param overlineText The text displayed above the primary text
* @param trailing The trailing meta text, icon, switch or checkbox
* @param text The primary text of the list item
*/
@Composable
@ExperimentalMaterialApi
fun ListItem(
modifier: Modifier = Modifier,
icon: @Composable (() -> Unit)? = null,
secondaryText: @Composable (() -> Unit)? = null,
singleLineSecondaryText: Boolean = true,
overlineText: @Composable (() -> Unit)? = null,
trailing: @Composable (() -> Unit)? = null,
text: @Composable () -> Unit
) {
val typography = MaterialTheme.typography
val styledText = applyTextStyle(typography.subtitle1, ContentAlpha.high, text)!!
val styledSecondaryText = applyTextStyle(typography.body2, ContentAlpha.medium, secondaryText)
val styledOverlineText = applyTextStyle(typography.overline, ContentAlpha.high, overlineText)
val styledTrailing = applyTextStyle(typography.caption, ContentAlpha.high, trailing)
val semanticsModifier = modifier.semantics(mergeDescendants = true) {}
if (styledSecondaryText == null && styledOverlineText == null) {
OneLine.ListItem(semanticsModifier, icon, styledText, styledTrailing)
} else if (
(styledOverlineText == null && singleLineSecondaryText) || styledSecondaryText == null
) {
TwoLine.ListItem(
semanticsModifier,
icon,
styledText,
styledSecondaryText,
styledOverlineText,
styledTrailing
)
} else {
ThreeLine.ListItem(
semanticsModifier,
icon,
styledText,
styledSecondaryText,
styledOverlineText,
styledTrailing
)
}
}
private object OneLine {
// TODO(popam): support wide icons
// TODO(popam): convert these to sp
// List item related defaults.
private val MinHeight = 48.dp
private val MinHeightWithIcon = 56.dp
// Icon related defaults.
private val IconMinPaddedWidth = 40.dp
private val IconLeftPadding = 16.dp
private val IconVerticalPadding = 8.dp
// Content related defaults.
private val ContentLeftPadding = 16.dp
private val ContentRightPadding = 16.dp
// Trailing related defaults.
private val TrailingRightPadding = 16.dp
@Composable
fun ListItem(
modifier: Modifier = Modifier,
icon: @Composable (() -> Unit)?,
text: @Composable (() -> Unit),
trailing: @Composable (() -> Unit)?
) {
val minHeight = if (icon == null) MinHeight else MinHeightWithIcon
Row(modifier.heightIn(min = minHeight)) {
if (icon != null) {
Box(
Modifier.align(Alignment.CenterVertically)
.widthIn(min = IconLeftPadding + IconMinPaddedWidth)
.padding(
start = IconLeftPadding,
top = IconVerticalPadding,
bottom = IconVerticalPadding
),
contentAlignment = Alignment.CenterStart
) { icon() }
}
Box(
Modifier.weight(1f)
.align(Alignment.CenterVertically)
.padding(start = ContentLeftPadding, end = ContentRightPadding),
contentAlignment = Alignment.CenterStart
) { text() }
if (trailing != null) {
Box(
Modifier
.align(Alignment.CenterVertically)
.padding(end = TrailingRightPadding)
) { trailing() }
}
}
}
}
private object TwoLine {
// List item related defaults.
private val MinHeight = 64.dp
private val MinHeightWithIcon = 72.dp
// Icon related defaults.
private val IconMinPaddedWidth = 40.dp
private val IconLeftPadding = 16.dp
private val IconVerticalPadding = 16.dp
// Content related defaults.
private val ContentLeftPadding = 16.dp
private val ContentRightPadding = 16.dp
private val OverlineBaselineOffset = 24.dp
private val OverlineToPrimaryBaselineOffset = 20.dp
private val PrimaryBaselineOffsetNoIcon = 28.dp
private val PrimaryBaselineOffsetWithIcon = 32.dp
private val PrimaryToSecondaryBaselineOffsetNoIcon = 20.dp
private val PrimaryToSecondaryBaselineOffsetWithIcon = 20.dp
// Trailing related defaults.
private val TrailingRightPadding = 16.dp
@Composable
fun ListItem(
modifier: Modifier = Modifier,
icon: @Composable (() -> Unit)?,
text: @Composable (() -> Unit),
secondaryText: @Composable (() -> Unit)?,
overlineText: @Composable (() -> Unit)?,
trailing: @Composable (() -> Unit)?
) {
val minHeight = if (icon == null) MinHeight else MinHeightWithIcon
Row(modifier.heightIn(min = minHeight)) {
val columnModifier = Modifier.weight(1f)
.padding(start = ContentLeftPadding, end = ContentRightPadding)
if (icon != null) {
Box(
Modifier
.sizeIn(
minWidth = IconLeftPadding + IconMinPaddedWidth,
minHeight = minHeight
)
.padding(
start = IconLeftPadding,
top = IconVerticalPadding,
bottom = IconVerticalPadding
),
contentAlignment = Alignment.TopStart
) { icon() }
}
if (overlineText != null) {
BaselinesOffsetColumn(
listOf(OverlineBaselineOffset, OverlineToPrimaryBaselineOffset),
columnModifier
) {
overlineText()
text()
}
} else {
BaselinesOffsetColumn(
listOf(
if (icon != null) {
PrimaryBaselineOffsetWithIcon
} else {
PrimaryBaselineOffsetNoIcon
},
if (icon != null) {
PrimaryToSecondaryBaselineOffsetWithIcon
} else {
PrimaryToSecondaryBaselineOffsetNoIcon
}
),
columnModifier
) {
text()
secondaryText!!()
}
}
if (trailing != null) {
OffsetToBaselineOrCenter(
if (icon != null) {
PrimaryBaselineOffsetWithIcon
} else {
PrimaryBaselineOffsetNoIcon
}
) {
Box(
// TODO(popam): find way to center and wrap content without minHeight
Modifier.heightIn(min = minHeight)
.padding(end = TrailingRightPadding),
contentAlignment = Alignment.Center
) { trailing() }
}
}
}
}
}
private object ThreeLine {
// List item related defaults.
private val MinHeight = 88.dp
// Icon related defaults.
private val IconMinPaddedWidth = 40.dp
private val IconLeftPadding = 16.dp
private val IconThreeLineVerticalPadding = 16.dp
// Content related defaults.
private val ContentLeftPadding = 16.dp
private val ContentRightPadding = 16.dp
private val ThreeLineBaselineFirstOffset = 28.dp
private val ThreeLineBaselineSecondOffset = 20.dp
private val ThreeLineBaselineThirdOffset = 20.dp
private val ThreeLineTrailingTopPadding = 16.dp
// Trailing related defaults.
private val TrailingRightPadding = 16.dp
@Composable
fun ListItem(
modifier: Modifier = Modifier,
icon: @Composable (() -> Unit)?,
text: @Composable (() -> Unit),
secondaryText: @Composable (() -> Unit),
overlineText: @Composable (() -> Unit)?,
trailing: @Composable (() -> Unit)?
) {
Row(modifier.heightIn(min = MinHeight)) {
if (icon != null) {
val minSize = IconLeftPadding + IconMinPaddedWidth
Box(
Modifier
.sizeIn(minWidth = minSize, minHeight = minSize)
.padding(
start = IconLeftPadding,
top = IconThreeLineVerticalPadding,
bottom = IconThreeLineVerticalPadding
),
contentAlignment = Alignment.CenterStart
) { icon() }
}
BaselinesOffsetColumn(
listOf(
ThreeLineBaselineFirstOffset,
ThreeLineBaselineSecondOffset,
ThreeLineBaselineThirdOffset
),
Modifier.weight(1f)
.padding(start = ContentLeftPadding, end = ContentRightPadding)
) {
if (overlineText != null) overlineText()
text()
secondaryText()
}
if (trailing != null) {
OffsetToBaselineOrCenter(
ThreeLineBaselineFirstOffset - ThreeLineTrailingTopPadding,
Modifier.padding(top = ThreeLineTrailingTopPadding, end = TrailingRightPadding),
trailing
)
}
}
}
}
/**
* Layout that expects [Text] children, and positions them with specific offsets between the
* top of the layout and the first text, as well as the last baseline and first baseline
* for subsequent pairs of texts.
*/
// TODO(popam): consider making this a layout composable in `foundation-layout`.
@Composable
private fun BaselinesOffsetColumn(
offsets: List<Dp>,
modifier: Modifier = Modifier,
content: @Composable () -> Unit
) {
Layout(content, modifier) { measurables, constraints ->
val childConstraints = constraints.copy(minHeight = 0, maxHeight = Constraints.Infinity)
val placeables = measurables.map { it.measure(childConstraints) }
val containerWidth = placeables.fold(0) { maxWidth, placeable ->
max(maxWidth, placeable.width)
}
val y = Array(placeables.size) { 0 }
var containerHeight = 0
placeables.fastForEachIndexed { index, placeable ->
val toPreviousBaseline = if (index > 0) {
placeables[index - 1].height - placeables[index - 1][LastBaseline]
} else 0
val topPadding = max(
0,
offsets[index].roundToPx() - placeable[FirstBaseline] - toPreviousBaseline
)
y[index] = topPadding + containerHeight
containerHeight += topPadding + placeable.height
}
layout(containerWidth, containerHeight) {
placeables.fastForEachIndexed { index, placeable ->
placeable.placeRelative(0, y[index])
}
}
}
}
/**
* Layout that takes a child and adds the necessary padding such that the first baseline of the
* child is at a specific offset from the top of the container. If the child does not have
* a first baseline, the layout will match the minHeight constraint and will center the
* child.
*/
// TODO(popam): support fallback alignment in AlignmentLineOffset, and use that here.
@Composable
private fun OffsetToBaselineOrCenter(
offset: Dp,
modifier: Modifier = Modifier,
content: @Composable () -> Unit
) {
Layout(content, modifier) { measurables, constraints ->
val placeable = measurables[0].measure(constraints.copy(minHeight = 0))
val baseline = placeable[FirstBaseline]
val y: Int
val containerHeight: Int
if (baseline != AlignmentLine.Unspecified) {
y = offset.roundToPx() - baseline
containerHeight = max(constraints.minHeight, y + placeable.height)
} else {
containerHeight = max(constraints.minHeight, placeable.height)
y = Alignment.Center.align(
IntSize.Zero,
IntSize(0, containerHeight - placeable.height),
layoutDirection
).y
}
layout(placeable.width, containerHeight) {
placeable.placeRelative(0, y)
}
}
}
private fun applyTextStyle(
textStyle: TextStyle,
contentAlpha: Float,
icon: @Composable (() -> Unit)?
): @Composable (() -> Unit)? {
if (icon == null) return null
return {
CompositionLocalProvider(LocalContentAlpha provides contentAlpha) {
ProvideTextStyle(textStyle, icon)
}
}
}
| apache-2.0 | f8247c258193ee986787c7b43eec7b94 | 36.161215 | 113 | 0.6 | 5.395183 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/uast/uast-kotlin/src/org/jetbrains/uast/kotlin/internal/CliKotlinUastResolveProviderService.kt | 2 | 4099 | // 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.uast.kotlin.internal
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiElement
import org.jetbrains.kotlin.analyzer.AnalysisResult
import org.jetbrains.kotlin.codegen.ClassBuilderMode
import org.jetbrains.kotlin.codegen.state.KotlinTypeMapper
import org.jetbrains.kotlin.config.LanguageVersionSettings
import org.jetbrains.kotlin.config.LanguageVersionSettingsImpl
import org.jetbrains.kotlin.container.ComponentProvider
import org.jetbrains.kotlin.container.get
import org.jetbrains.kotlin.context.ProjectContext
import org.jetbrains.kotlin.descriptors.ModuleDescriptor
import org.jetbrains.kotlin.metadata.jvm.deserialization.JvmProtoBufUtil
import org.jetbrains.kotlin.psi.KtElement
import org.jetbrains.kotlin.psi.KtExpression
import org.jetbrains.kotlin.psi.KtFile
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.BindingTrace
import org.jetbrains.kotlin.resolve.jvm.extensions.AnalysisHandlerExtension
import org.jetbrains.uast.kotlin.KotlinUastResolveProviderService
class CliKotlinUastResolveProviderService : KotlinUastResolveProviderService {
private val Project.analysisCompletedHandler: UastAnalysisHandlerExtension?
get() = getExtensions(AnalysisHandlerExtension.extensionPointName)
.filterIsInstance<UastAnalysisHandlerExtension>()
.firstOrNull()
@Deprecated("For binary compatibility, please, use KotlinUastTypeMapper")
override fun getTypeMapper(element: KtElement): KotlinTypeMapper? {
@Suppress("DEPRECATION")
return element.project.analysisCompletedHandler?.getTypeMapper()
}
override fun getBindingContext(element: KtElement): BindingContext {
return element.project.analysisCompletedHandler?.getBindingContext() ?: BindingContext.EMPTY
}
override fun isJvmElement(psiElement: PsiElement) = true
override fun getLanguageVersionSettings(element: KtElement): LanguageVersionSettings {
return element.project.analysisCompletedHandler?.getLanguageVersionSettings() ?: LanguageVersionSettingsImpl.DEFAULT
}
override fun getReferenceVariants(ktExpression: KtExpression, nameHint: String): Sequence<PsiElement> =
emptySequence() // Not supported
}
class UastAnalysisHandlerExtension : AnalysisHandlerExtension {
private var context: BindingContext? = null
private var typeMapper: KotlinTypeMapper? = null
private var languageVersionSettings: LanguageVersionSettings? = null
fun getBindingContext() = context
fun getLanguageVersionSettings() = languageVersionSettings
@Deprecated("For binary compatibility, please, use KotlinUastTypeMapper")
fun getTypeMapper(): KotlinTypeMapper? {
if (typeMapper != null) return typeMapper
val bindingContext = context ?: return null
val typeMapper = KotlinTypeMapper(
bindingContext, ClassBuilderMode.LIGHT_CLASSES,
JvmProtoBufUtil.DEFAULT_MODULE_NAME,
KotlinTypeMapper.LANGUAGE_VERSION_SETTINGS_DEFAULT, // TODO use proper LanguageVersionSettings
useOldInlineClassesManglingScheme = false
)
this.typeMapper = typeMapper
return typeMapper
}
override fun doAnalysis(
project: Project,
module: ModuleDescriptor,
projectContext: ProjectContext,
files: Collection<KtFile>,
bindingTrace: BindingTrace,
componentProvider: ComponentProvider
): AnalysisResult? {
languageVersionSettings = componentProvider.get<LanguageVersionSettings>()
return super.doAnalysis(project, module, projectContext, files, bindingTrace, componentProvider)
}
override fun analysisCompleted(
project: Project,
module: ModuleDescriptor,
bindingTrace: BindingTrace,
files: Collection<KtFile>
): AnalysisResult? {
context = bindingTrace.bindingContext
return null
}
}
| apache-2.0 | f0183ccc971280ca196a88c957ec5481 | 41.697917 | 124 | 0.764333 | 5.661602 | false | false | false | false |
NordicSemiconductor/Android-DFU-Library | profile_dfu/src/main/java/no/nordicsemi/android/dfu/profile/settings/repository/SettingsDataSource.kt | 1 | 4802 | /*
* Copyright (c) 2022, Nordic Semiconductor
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are
* permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice, this list
* of conditions and the following disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* 3. Neither the name of the copyright holder nor the names of its contributors may be
* used to endorse or promote products derived from this software without specific prior
* written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
* PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
* OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
* EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package no.nordicsemi.android.dfu.profile.settings.repository
import android.content.Context
import androidx.datastore.core.DataStore
import androidx.datastore.preferences.core.Preferences
import androidx.datastore.preferences.core.booleanPreferencesKey
import androidx.datastore.preferences.core.edit
import androidx.datastore.preferences.core.intPreferencesKey
import androidx.datastore.preferences.preferencesDataStore
import dagger.hilt.android.qualifiers.ApplicationContext
import kotlinx.coroutines.flow.map
import no.nordicsemi.android.dfu.profile.settings.domain.DFUSettings
import no.nordicsemi.android.dfu.profile.settings.domain.NUMBER_OF_POCKETS_INITIAL
import javax.inject.Inject
import javax.inject.Singleton
private val PACKETS_RECEIPT_NOTIFICATION_KEY = booleanPreferencesKey("packets_receipt")
private val KEEP_BOND_KEY = booleanPreferencesKey("keep_bond")
private val EXTERNAL_MCU_KEY = booleanPreferencesKey("external_mcu")
private val SHOW_WELCOME_KEY = booleanPreferencesKey("show_welcome")
private val DISABLE_RESUME = booleanPreferencesKey("disable_resume")
private val FORCE_SCANNING_ADDRESS = booleanPreferencesKey("force_scanning_address")
private val NUMBER_OF_POCKETS_KEY = intPreferencesKey("number_of_pockets")
private val PREPARE_OBJECT_DELAY_KEY = intPreferencesKey("prepare_data_object_delay")
private val REBOOT_TIME_KEY = intPreferencesKey("reboot_time")
private val SCAN_TIMEOUT_KEY = intPreferencesKey("scan_timeout")
@Singleton
class SettingsDataSource @Inject constructor(
@ApplicationContext private val context: Context
) {
private val Context.dataStore: DataStore<Preferences> by preferencesDataStore(name = "settings")
val settings = context.dataStore.data.map { it.toSettings() }
suspend fun tickWelcomeScreenShown() {
context.dataStore.edit {
it[SHOW_WELCOME_KEY] = false
}
}
suspend fun storeSettings(settings: DFUSettings) {
context.dataStore.edit {
it[PACKETS_RECEIPT_NOTIFICATION_KEY] = settings.packetsReceiptNotification
it[PREPARE_OBJECT_DELAY_KEY] = settings.prepareDataObjectDelay
it[REBOOT_TIME_KEY] = settings.rebootTime
it[SCAN_TIMEOUT_KEY] = settings.scanTimeout
it[NUMBER_OF_POCKETS_KEY] = settings.numberOfPackets
it[KEEP_BOND_KEY] = settings.keepBondInformation
it[EXTERNAL_MCU_KEY] = settings.externalMcuDfu
it[DISABLE_RESUME] = settings.disableResume
it[FORCE_SCANNING_ADDRESS] = settings.forceScanningInLegacyDfu
it[SHOW_WELCOME_KEY] = settings.showWelcomeScreen
}
}
private fun Preferences.toSettings(): DFUSettings {
return DFUSettings(
this[PACKETS_RECEIPT_NOTIFICATION_KEY] ?: false,
this[NUMBER_OF_POCKETS_KEY] ?: NUMBER_OF_POCKETS_INITIAL,
this[KEEP_BOND_KEY] ?: false,
this[EXTERNAL_MCU_KEY] ?: false,
this[DISABLE_RESUME] ?: false,
this[PREPARE_OBJECT_DELAY_KEY] ?: 400,
this[REBOOT_TIME_KEY] ?: 0,
this[SCAN_TIMEOUT_KEY] ?: 2_000,
this[FORCE_SCANNING_ADDRESS] ?: false,
this[SHOW_WELCOME_KEY] ?: true,
)
}
}
| bsd-3-clause | 6a84f6dbb5602b9484edb7ae98133f3b | 46.078431 | 100 | 0.743024 | 4.454545 | false | false | false | false |
OnyxDevTools/onyx-database-parent | onyx-database-tests/src/test/kotlin/database/query/SelectQueryTest.kt | 1 | 5005 | package database.query
import com.onyx.exception.OnyxException
import com.onyx.persistence.IManagedEntity
import com.onyx.persistence.query.*
import database.base.PrePopulatedDatabaseTest
import entities.AllAttributeForFetch
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.runners.Parameterized
import java.util.*
import kotlin.reflect.KClass
import kotlin.test.assertEquals
import kotlin.test.assertNotNull
import kotlin.test.assertTrue
@RunWith(Parameterized::class)
class SelectQueryTest(override var factoryClass: KClass<*>) : PrePopulatedDatabaseTest(factoryClass) {
@Test
fun testExecuteSelectFields() {
val criteria = QueryCriteria("stringValue", QueryCriteriaOperator.STARTS_WITH, "Some")
val query = Query(AllAttributeForFetch::class.java, Arrays.asList("longValue", "intPrimitive"), criteria)
val results = manager.executeQuery<IManagedEntity>(query)
assertNotNull(results)
assertEquals(4, results.size, "Expected 5 matching criteria")
assertTrue(results[0] is Map<*, *>, "Result is not a map")
assertTrue(((results[0] as Map<*, *>)["longValue"] as Number).toInt() > 0, "longValue was not assigned")
}
@Test
@Throws(OnyxException::class, InstantiationException::class, IllegalAccessException::class)
fun testSelectOnlyOne() {
val criteria = QueryCriteria("stringValue", QueryCriteriaOperator.STARTS_WITH, "Some")
val query = Query(AllAttributeForFetch::class.java, arrayListOf("longValue", "intPrimitive"), criteria)
query.firstRow = 0
query.maxResults = 1
val results = manager.executeQuery<Any>(query)
assertNotNull(results, "Results were null")
assertEquals(1, results.size, "Expected 1 result")
assertTrue(results[0] is Map<*, *>, "Results are not in map format")
if (results[0] is Long) {
assertTrue((results[0] as Map<*, *>)["longValue"] as Long > 0, "longValue was not assigned")
} else if (results[0] is Int) {
assertTrue((results[0] as Map<*, *>)["longValue"] as Int > 0, "Long value was not assigned")
}
}
@Test
fun testSelectTwoOrderBy() {
val results = manager.select("intPrimitive", "stringValue", "longPrimitive")
.from(AllAttributeForFetch::class)
.where("stringValue" startsWith "Some")
.orderBy("intPrimitive", "stringValue")
.first(2)
.limit(2)
.list<Map<String, Any?>>()
assertNotNull(results, "Results should not be null")
assertEquals(3, results[0]["intPrimitive"] as Int, "intPrimitive has incorrect value")
assertEquals(4, results[1]["intPrimitive"] as Int, "intPrimitive has incorrect value")
}
@Test
fun testNoSelect() {
val results = manager.from(AllAttributeForFetch::class).where("stringValue" startsWith "Some")
.first(0)
.limit(2)
.orderBy("stringValue", "intPrimitive")
.list<AllAttributeForFetch>()
assertNotNull(results, "Results should not be null")
assertEquals(2, results.size, "Expected 2 results")
assertEquals("FIRST ONE", results[0].id, "Query order is incorrect")
assertEquals("FIRST ONE1", results[1].id, "Query order is incorrect")
}
@Test
fun testSelectRelationship() {
val criteria = QueryCriteria("stringValue", QueryCriteriaOperator.STARTS_WITH, "Some")
.and("child.someOtherField", QueryCriteriaOperator.STARTS_WITH, "HIYA")
val query = Query(AllAttributeForFetch::class.java, criteria)
query.firstRow = 0
query.maxResults = 2
query.queryOrders = Arrays.asList(QueryOrder("child.someOtherField"), QueryOrder("intPrimitive"))
query.selections = Arrays.asList("longValue", "intPrimitive", "child.someOtherField")
val results = manager.executeQuery<Any>(query)
assertNotNull(results)
assertTrue(results.size == 1)
assertTrue(results[0] is Map<*, *>)
}
@Test
fun testSelectRelationshipMultiResult() {
val results = manager.select("id", "longValue", "intPrimitive", "child.someOtherField")
.from(AllAttributeForFetch::class)
.where(("id" startsWith "FIRST ONE") and ("child.someOtherField" startsWith "HIYA"))
.first(0)
.limit(2)
.orderBy("id", "longValue", "intPrimitive", "child.someOtherField")
.list<Map<String, Any?>>()
assertNotNull(results)
assertEquals(2, results.size, "Results should have 2 records")
assertEquals("FIRST ONE", results[0]["id"], "Invalid query order")
assertEquals("FIRST ONE4", results[1]["id"], "Invalid query order")
}
} | agpl-3.0 | f465b3f84267ead4332fb3fa40352e77 | 43.300885 | 113 | 0.631568 | 4.849806 | false | true | false | false |
GunoH/intellij-community | python/tools/src/com/jetbrains/python/tools/PackPythonSdkLibsForStubs.kt | 8 | 1409 | // Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.jetbrains.python.tools
import com.jetbrains.python.PythonHelper
import com.jetbrains.python.sdk.PythonSdkUtil
import java.io.BufferedReader
import java.io.File
import java.io.InputStreamReader
fun main() {
val pythons = System.getenv("PACK_STDLIB_FROM")
val baseDir = System.getenv("PACK_STDLIB_TO")
if (!File(baseDir).exists()) {
File(baseDir).mkdirs()
}
for (python in File(pythons).listFiles()!!) {
if (python.name.startsWith(".")) {
continue
}
val sdkHome = python.absolutePath
val executable = PythonSdkUtil.getPythonExecutable(sdkHome)?.let { File(it) }
if (executable == null) {
println("No python on $sdkHome")
continue
}
else {
println("Packing stdlib of $sdkHome")
}
val arg = PythonHelper.GENERATOR3.asParamString()
val process = ProcessBuilder(executable.absolutePath, arg, "-u", baseDir).start()
BufferedReader(InputStreamReader(process.inputStream)).use {
it.lines().forEach(::println)
}
BufferedReader(InputStreamReader(process.errorStream)).use {
it.lines().forEach(::println)
}
val rc = process.waitFor()
if (rc != 0) {
error("Process '${executable.absolutePath} $arg' exited with error code $rc")
}
}
} | apache-2.0 | f8df1b6ed43d3726e48188ed1e587336 | 27.2 | 140 | 0.681334 | 4.119883 | false | false | false | false |
siosio/intellij-community | plugins/kotlin/fir/src/org/jetbrains/kotlin/idea/fir/inspections/AddFunctionReturnTypeIntention.kt | 1 | 1717 | /*
* Copyright 2010-2020 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlin.idea.fir.inspections
import com.intellij.openapi.editor.Editor
import org.jetbrains.kotlin.idea.frontend.api.KtAnalysisSession
import org.jetbrains.kotlin.idea.frontend.api.types.*
import org.jetbrains.kotlin.psi.KtNamedFunction
import org.jetbrains.kotlin.psi.KtPsiFactory
class AddFunctionReturnTypeIntention :
AbstractHighLevelApiBasedIntention<KtNamedFunction, TypeCandidate>(
KtNamedFunction::class.java,
{ "Specify type explicitly" }
) {
override fun isApplicableByPsi(element: KtNamedFunction): Boolean =
element.typeReference == null && !element.hasBlockBody()
override fun KtAnalysisSession.analyzeAndGetData(element: KtNamedFunction): TypeCandidate? {
val returnType = element.getReturnKtType()
val approximated = approximateTypeToUpperDenotable(returnType) ?: return null
return TypeCandidate(approximated.render())
}
private tailrec fun approximateTypeToUpperDenotable(type: KtType): KtDenotableType? = when (type) {
is KtNonDenotableType -> when (type) {
is KtFlexibleType -> approximateTypeToUpperDenotable(type.upperBound)
is KtIntersectionType -> null
}
is KtDenotableType -> type
else -> null
}
override fun applyTo(element: KtNamedFunction, data: TypeCandidate, editor: Editor?) {
element.typeReference = KtPsiFactory(element).createType(data.candidate)
}
}
data class TypeCandidate(val candidate: String) | apache-2.0 | f6bbaf6868fa4cfe0e85e92cabbc1e95 | 38.953488 | 115 | 0.740827 | 4.809524 | false | false | false | false |
jwren/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/replaceWith/DeprecatedSymbolUsageFixBase.kt | 2 | 16422 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.quickfix.replaceWith
import com.intellij.codeInsight.hint.HintManager
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiElement
import com.intellij.psi.search.GlobalSearchScope
import com.intellij.psi.search.searches.ReferencesSearch
import org.jetbrains.kotlin.base.fe10.analysis.getAnnotationValue
import org.jetbrains.kotlin.base.fe10.analysis.getArrayValue
import org.jetbrains.kotlin.base.fe10.analysis.getStringValue
import org.jetbrains.kotlin.builtins.KotlinBuiltIns
import org.jetbrains.kotlin.builtins.StandardNames
import org.jetbrains.kotlin.descriptors.*
import org.jetbrains.kotlin.descriptors.impl.TypeAliasConstructorDescriptor
import org.jetbrains.kotlin.diagnostics.Diagnostic
import org.jetbrains.kotlin.diagnostics.DiagnosticFactory
import org.jetbrains.kotlin.diagnostics.Errors
import org.jetbrains.kotlin.idea.KotlinBundle
import org.jetbrains.kotlin.idea.caches.KotlinShortNamesCache
import org.jetbrains.kotlin.idea.caches.resolve.analyze
import org.jetbrains.kotlin.idea.caches.resolve.getResolutionFacade
import org.jetbrains.kotlin.idea.codeInliner.CallableUsageReplacementStrategy
import org.jetbrains.kotlin.idea.codeInliner.ClassUsageReplacementStrategy
import org.jetbrains.kotlin.idea.codeInliner.UsageReplacementStrategy
import org.jetbrains.kotlin.idea.core.OptionalParametersHelper
import org.jetbrains.kotlin.idea.intentions.isInvokeOperator
import org.jetbrains.kotlin.idea.quickfix.KotlinQuickFixAction
import org.jetbrains.kotlin.idea.references.mainReference
import org.jetbrains.kotlin.idea.references.resolveMainReferenceToDescriptors
import org.jetbrains.kotlin.idea.references.resolveToDescriptors
import org.jetbrains.kotlin.idea.search.restrictToKotlinSources
import org.jetbrains.kotlin.idea.util.application.isDispatchThread
import org.jetbrains.kotlin.idea.util.replaceOrCreateTypeArgumentList
import org.jetbrains.kotlin.ir.expressions.typeParametersCount
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.getStrictParentOfType
import org.jetbrains.kotlin.psi.psiUtil.isCallee
import org.jetbrains.kotlin.psi.psiUtil.referenceExpression
import org.jetbrains.kotlin.renderer.DescriptorRenderer
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.calls.util.getResolvedCall
import org.jetbrains.kotlin.resolve.calls.components.hasDefaultValue
import org.jetbrains.kotlin.resolve.calls.model.isReallySuccess
import org.jetbrains.kotlin.resolve.constants.StringValue
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
import org.jetbrains.kotlin.util.*
//TODO: different replacements for property accessors
abstract class DeprecatedSymbolUsageFixBase(
element: KtReferenceExpression,
val replaceWith: ReplaceWithData
) : KotlinQuickFixAction<KtReferenceExpression>(element) {
internal val isAvailable: Boolean
init {
assert(!isDispatchThread()) {
"${javaClass.name} should not be created on EDT"
}
isAvailable = buildUsageReplacementStrategy(
element,
replaceWith,
recheckAnnotation = true,
reformat = false
)?.let { it.createReplacer(element) != null } == true
}
override fun isAvailable(project: Project, editor: Editor?, file: KtFile): Boolean = element != null && isAvailable
final override fun invoke(project: Project, editor: Editor?, file: KtFile) {
val expression = element ?: return
val strategy = buildUsageReplacementStrategy(
expression, replaceWith, recheckAnnotation = false, reformat = true, editor = editor
) ?: return
invoke(strategy, project, editor)
}
protected abstract operator fun invoke(replacementStrategy: UsageReplacementStrategy, project: Project, editor: Editor?)
companion object {
fun fetchReplaceWithPattern(
descriptor: DeclarationDescriptor,
project: Project,
contextElement: KtReferenceExpression?,
replaceInWholeProject: Boolean
): ReplaceWithData? {
val annotation = descriptor.annotations.findAnnotation(StandardNames.FqNames.deprecated) ?: return null
val replaceWithValue = annotation.getAnnotationValue(Deprecated::replaceWith) ?: return null
val pattern = replaceWithValue.getStringValue(ReplaceWith::expression)?.takeIf { it.isNotEmpty() } ?: return null
val imports = replaceWithValue.getArrayValue(ReplaceWith::imports)?.mapAll { (it as? StringValue)?.value } ?: return null
// should not be available for descriptors with optional parameters if we cannot fetch default values for them (currently for library with no sources)
if (descriptor is CallableDescriptor && descriptor.valueParameters.any {
it.hasDefaultValue() && OptionalParametersHelper.defaultParameterValue(it, project) == null
}
) return null
return if (replaceInWholeProject) {
ReplaceWithData(pattern, imports, true)
} else {
ReplaceWithData(pattern.applyContextElement(contextElement, descriptor), imports, false)
}
}
private fun String.applyContextElement(
element: KtReferenceExpression?,
descriptor: DeclarationDescriptor
): String {
if (element == null) return this
val psiFactory = KtPsiFactory(element)
val expressionFromPattern = psiFactory.createExpressionIfPossible(this) ?: return this
val classLiteral = when (expressionFromPattern) {
is KtClassLiteralExpression -> expressionFromPattern
is KtDotQualifiedExpression -> expressionFromPattern.receiverExpression as? KtClassLiteralExpression
else -> null
}
if (classLiteral != null) {
val receiver = classLiteral.receiverExpression ?: return this
val typeParameterText = (descriptor as? CallableDescriptor)?.typeParameters?.firstOrNull()?.name?.asString() ?: return this
if (receiver.text != typeParameterText) return this
val typeReference = (element.parent as? KtCallExpression)?.typeArguments?.firstOrNull()?.typeReference ?: return this
val type = element.analyze(BodyResolveMode.PARTIAL)[BindingContext.TYPE, typeReference]
if (type != null && KotlinBuiltIns.isArray(type)) {
receiver.replace(typeReference)
} else {
receiver.replace(psiFactory.createExpression(typeReference.text.takeWhile { it != '<' }))
}
return expressionFromPattern.text
}
if (expressionFromPattern !is KtCallExpression) return this
val methodFromPattern = expressionFromPattern.referenceExpression()?.let { name ->
KotlinShortNamesCache(element.project).getMethodsByName(
name.text,
element.resolveScope
).firstOrNull()
}
val patternTypeArgumentList = expressionFromPattern.typeArgumentList
val patternTypeArgumentCount = methodFromPattern?.typeParameterList?.typeParameters?.size
?: patternTypeArgumentList?.arguments?.size
?: return this
val typeArgumentList = (element.parent as? KtCallExpression)?.typeArgumentList
?: (element.parent as? KtUserType)?.typeArgumentList
val descriptorTypeParameterCount = (descriptor as? CallableDescriptor)?.typeParametersCount
?: (descriptor as? ClassDescriptor)?.declaredTypeParameters?.size
return if (patternTypeArgumentCount == descriptorTypeParameterCount ||
patternTypeArgumentCount == typeArgumentList?.arguments?.size
) {
if (typeArgumentList != null) expressionFromPattern.replaceOrCreateTypeArgumentList(typeArgumentList.copy() as KtTypeArgumentList)
else patternTypeArgumentList?.delete()
expressionFromPattern.text
} else this
}
data class Data(
val referenceExpression: KtReferenceExpression,
val replaceWith: ReplaceWithData,
val descriptor: DeclarationDescriptor
)
fun extractDataFromDiagnostic(deprecatedDiagnostic: Diagnostic, replaceInWholeProject: Boolean): Data? {
val referenceExpression = when (val psiElement = deprecatedDiagnostic.psiElement) {
is KtArrayAccessExpression -> psiElement
is KtSimpleNameExpression -> psiElement
is KtConstructorCalleeExpression -> psiElement.constructorReferenceExpression
else -> null
} ?: return null
val descriptor = when (deprecatedDiagnostic.factory) {
Errors.DEPRECATION -> DiagnosticFactory.cast(deprecatedDiagnostic, Errors.DEPRECATION).a
Errors.DEPRECATION_ERROR -> DiagnosticFactory.cast(deprecatedDiagnostic, Errors.DEPRECATION_ERROR).a
Errors.TYPEALIAS_EXPANSION_DEPRECATION ->
DiagnosticFactory.cast(deprecatedDiagnostic, Errors.TYPEALIAS_EXPANSION_DEPRECATION).b
Errors.TYPEALIAS_EXPANSION_DEPRECATION_ERROR ->
DiagnosticFactory.cast(deprecatedDiagnostic, Errors.TYPEALIAS_EXPANSION_DEPRECATION_ERROR).b
else -> throw IllegalStateException("Bad QuickFixRegistrar configuration")
}
val replacement =
fetchReplaceWithPattern(descriptor, referenceExpression.project, referenceExpression, replaceInWholeProject) ?: return null
return Data(referenceExpression, replacement, descriptor)
}
private fun buildUsageReplacementStrategy(
element: KtReferenceExpression,
replaceWith: ReplaceWithData,
recheckAnnotation: Boolean,
reformat: Boolean,
editor: Editor? = null
): UsageReplacementStrategy? {
val resolutionFacade = element.getResolutionFacade()
val bindingContext = resolutionFacade.analyze(element, BodyResolveMode.PARTIAL)
val resolvedCall = element.getResolvedCall(bindingContext)
var target = resolvedCall?.resultingDescriptor?.takeIf { it.isInvokeOperator }
?: element.mainReference.resolveToDescriptors(bindingContext).singleOrNull()
?: return null
var replacePatternFromSymbol =
fetchReplaceWithPattern(target, resolutionFacade.project, element, replaceWith.replaceInWholeProject)
if (replacePatternFromSymbol == null && target is ConstructorDescriptor) {
target = target.containingDeclaration
replacePatternFromSymbol =
fetchReplaceWithPattern(target, resolutionFacade.project, element, replaceWith.replaceInWholeProject)
}
// check that ReplaceWith hasn't changed
if (recheckAnnotation && replacePatternFromSymbol != replaceWith) return null
when (target) {
is CallableDescriptor -> {
if (resolvedCall == null) return null
if (!resolvedCall.isReallySuccess()) return null
val replacement = ReplaceWithAnnotationAnalyzer.analyzeCallableReplacement(
replaceWith, target, resolutionFacade, reformat
) ?: return null
return CallableUsageReplacementStrategy(replacement, inlineSetter = false)
}
is ClassifierDescriptorWithTypeParameters -> {
val replacementType = ReplaceWithAnnotationAnalyzer.analyzeClassifierReplacement(replaceWith, target, resolutionFacade)
return when {
replacementType != null -> {
if (editor != null) {
val typeAlias = element
.getStrictParentOfType<KtUserType>()
?.getStrictParentOfType<KtTypeReference>()
?.getStrictParentOfType<KtTypeAlias>()
if (typeAlias != null) {
val usedConstructorWithOwnReplaceWith = usedConstructorsWithOwnReplaceWith(
element.project, target, typeAlias, element, replaceWith.replaceInWholeProject
)
if (usedConstructorWithOwnReplaceWith != null) {
val constructorStr = DescriptorRenderer.ONLY_NAMES_WITH_SHORT_TYPES.render(
usedConstructorWithOwnReplaceWith
)
HintManager.getInstance().showErrorHint(
editor,
KotlinBundle.message(
"there.is.own.replacewith.on.0.that.is.used.through.this.alias.please.replace.usages.first",
constructorStr
)
)
return null
}
}
}
//TODO: check that it's really resolved and is not an object otherwise it can be expression as well
ClassUsageReplacementStrategy(replacementType, null, element.project)
}
target is ClassDescriptor -> {
val constructor = target.unsubstitutedPrimaryConstructor ?: return null
val replacementExpression = ReplaceWithAnnotationAnalyzer.analyzeCallableReplacement(
replaceWith,
constructor,
resolutionFacade,
reformat
) ?: return null
ClassUsageReplacementStrategy(null, replacementExpression, element.project)
}
else -> null
}
}
else -> return null
}
}
private fun usedConstructorsWithOwnReplaceWith(
project: Project,
classifier: ClassifierDescriptorWithTypeParameters,
typeAlias: PsiElement,
contextElement: KtReferenceExpression,
replaceInWholeProject: Boolean
): ConstructorDescriptor? {
val specialReplaceWithForConstructor = classifier.constructors.filter {
fetchReplaceWithPattern(it, project, contextElement, replaceInWholeProject) != null
}.toSet()
if (specialReplaceWithForConstructor.isEmpty()) {
return null
}
val searchAliasConstructorUsagesScope = GlobalSearchScope.allScope(project).restrictToKotlinSources()
ReferencesSearch.search(typeAlias, searchAliasConstructorUsagesScope).find { reference ->
val element = reference.element
if (element is KtSimpleNameExpression && element.isCallee()) {
val aliasConstructors = element.resolveMainReferenceToDescriptors().filterIsInstance<TypeAliasConstructorDescriptor>()
for (referenceConstructor in aliasConstructors) {
if (referenceConstructor.underlyingConstructorDescriptor in specialReplaceWithForConstructor) {
return referenceConstructor.underlyingConstructorDescriptor
}
}
}
false
}
return null
}
}
}
| apache-2.0 | e524942a7cee78e04254489a89149d61 | 51.803859 | 162 | 0.641944 | 6.5688 | false | false | false | false |
K0zka/kerub | src/test/kotlin/com/github/kerubistan/kerub/planner/steps/storage/share/iscsi/ctld/CtldIscsiShareTest.kt | 2 | 801 | package com.github.kerubistan.kerub.planner.steps.storage.share.iscsi.ctld
import com.github.kerubistan.kerub.model.dynamic.VirtualStorageLvmAllocation
import com.github.kerubistan.kerub.planner.steps.OperationalStepVerifications
import com.github.kerubistan.kerub.testDisk
import com.github.kerubistan.kerub.testHost
import com.github.kerubistan.kerub.testLvmCapability
import io.github.kerubistan.kroki.size.GB
internal class CtldIscsiShareTest : OperationalStepVerifications() {
override val step = CtldIscsiShare(
host = testHost,
allocation = VirtualStorageLvmAllocation(
vgName = testLvmCapability.volumeGroupName,
capabilityId = testLvmCapability.id,
hostId = testHost.id,
path = "/dev/blah/${testDisk.id}",
actualSize = 1.GB
),
vstorage = testDisk
)
} | apache-2.0 | f7f3666ed5144c079bbb7971b5ce4398 | 33.869565 | 77 | 0.790262 | 4.128866 | false | true | false | false |
jwren/intellij-community | plugins/kotlin/frontend-independent/src/org/jetbrains/kotlin/idea/findUsages/findUsageUtils.kt | 4 | 2900 | // 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.find.findUsages.FindUsagesManager
import com.intellij.find.findUsages.FindUsagesOptions
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiReference
import com.intellij.psi.impl.light.LightMemberReference
import com.intellij.psi.search.LocalSearchScope
import com.intellij.psi.search.SearchScope
import com.intellij.psi.search.searches.ReferencesSearch
import com.intellij.usageView.UsageInfo
import com.intellij.util.Query
import org.jetbrains.kotlin.asJava.toLightClass
import org.jetbrains.kotlin.asJava.toLightElements
import org.jetbrains.kotlin.idea.references.KtReference
import org.jetbrains.kotlin.psi.KtConstructor
import org.jetbrains.kotlin.psi.KtDeclaration
import org.jetbrains.kotlin.psi.KtPsiUtil
import org.jetbrains.kotlin.utils.SmartList
import org.jetbrains.kotlin.utils.addIfNotNull
fun KtDeclaration.processAllExactUsages(
options: FindUsagesOptions,
processor: (UsageInfo) -> Unit
) {
fun elementsToCheckReferenceAgainst(reference: PsiReference): List<PsiElement> {
if (reference is KtReference) return listOf(this)
return SmartList<PsiElement>().also { list ->
list += this
list += toLightElements()
if (this is KtConstructor<*>) {
list.addIfNotNull(getContainingClassOrObject().toLightClass())
}
}
}
FindUsagesManager(project).getFindUsagesHandler(this, true)?.processElementUsages(
this,
{ usageInfo ->
val reference = usageInfo.reference ?: return@processElementUsages true
if (reference is LightMemberReference || elementsToCheckReferenceAgainst(reference).any { reference.isReferenceTo(it) }) {
processor(usageInfo)
}
true
},
options
)
}
fun KtDeclaration.processAllUsages(
options: FindUsagesOptions,
processor: (UsageInfo) -> Unit
) {
val findUsagesHandler = KotlinFindUsagesHandlerFactory(project).createFindUsagesHandler(this, true)
findUsagesHandler.processElementUsages(
this,
{
processor(it)
true
},
options
)
}
object ReferencesSearchScopeHelper {
fun search(declaration: KtDeclaration, defaultScope: SearchScope? = null): Query<PsiReference> {
val enclosingElement = KtPsiUtil.getEnclosingElementForLocalDeclaration(declaration)
return when {
enclosingElement != null -> ReferencesSearch.search(declaration, LocalSearchScope(enclosingElement))
defaultScope != null -> ReferencesSearch.search(declaration, defaultScope)
else -> ReferencesSearch.search(declaration)
}
}
} | apache-2.0 | 32a20c802e7c09ffc76e15682e138f92 | 37.171053 | 158 | 0.724138 | 5.034722 | false | false | false | false |
smmribeiro/intellij-community | plugins/devkit/devkit-core/src/inspections/RegistryPropertiesAnnotator.kt | 5 | 6041 | // Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.idea.devkit.inspections
import com.intellij.codeInsight.intention.IntentionAction
import com.intellij.lang.annotation.AnnotationHolder
import com.intellij.lang.annotation.Annotator
import com.intellij.lang.annotation.HighlightSeverity
import com.intellij.lang.properties.psi.PropertiesFile
import com.intellij.lang.properties.psi.impl.PropertyImpl
import com.intellij.lang.properties.psi.impl.PropertyKeyImpl
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.Messages
import com.intellij.openapi.util.text.StringUtil
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiFile
import com.intellij.util.IncorrectOperationException
import com.intellij.util.PsiNavigateUtil
import org.jetbrains.annotations.Nls
import org.jetbrains.annotations.NonNls
import org.jetbrains.idea.devkit.DevKitBundle
import org.jetbrains.idea.devkit.util.PsiUtil
/**
* Highlights key in `registry.properties` without matching `key.description` entry + corresponding quickfix.
*/
class RegistryPropertiesAnnotator : Annotator {
override fun annotate(element: PsiElement, holder: AnnotationHolder) {
if (element !is PropertyKeyImpl) return
val file = holder.currentAnnotationSession.file
if (!isRegistryPropertiesFile(file)) {
return
}
val propertyName = element.text
if (isImplicitUsageKey(propertyName)) {
return
}
val groupName = propertyName.substringBefore('.').toLowerCase()
@Suppress("HardCodedStringLiteral")
if (PLUGIN_GROUP_NAMES.contains(groupName) ||
propertyName.startsWith("editor.config.")) {
holder.newAnnotation(HighlightSeverity.ERROR, DevKitBundle.message("registry.properties.annotator.plugin.keys.use.ep"))
.withFix(ShowEPDeclarationIntention(propertyName)).create()
}
val propertiesFile = file as PropertiesFile
val descriptionProperty = propertiesFile.findPropertyByKey(propertyName + DESCRIPTION_SUFFIX)
if (descriptionProperty == null) {
holder.newAnnotation(HighlightSeverity.WARNING,
DevKitBundle.message("registry.properties.annotator.key.no.description.key", propertyName))
.withFix(AddDescriptionKeyIntention(propertyName)).create()
}
}
private class ShowEPDeclarationIntention(private val propertyName: String) : IntentionAction {
override fun startInWriteAction(): Boolean = false
override fun getFamilyName(): String = DevKitBundle.message("registry.properties.annotator.show.ep.family.name")
override fun isAvailable(project: Project, editor: Editor?, file: PsiFile?): Boolean = true
override fun getText(): String = DevKitBundle.message("registry.properties.annotator.show.ep.name", propertyName)
override fun invoke(project: Project, editor: Editor?, file: PsiFile?) {
val propertiesFile = file as PropertiesFile
val defaultValue = propertiesFile.findPropertyByKey(propertyName)!!.value
val description = propertiesFile.findPropertyByKey(propertyName + DESCRIPTION_SUFFIX)?.value
@NonNls var restartRequiredText = ""
if (propertiesFile.findPropertyByKey(propertyName + RESTART_REQUIRED_SUFFIX) != null) {
restartRequiredText = "restartRequired=\"true\""
}
val epText = """
<registryKey key="${propertyName}" defaultValue="${defaultValue}" ${restartRequiredText}
description="${description}"/>
""".trimIndent()
Messages.showMultilineInputDialog(project,
DevKitBundle.message("registry.properties.annotator.show.ep.message"),
DevKitBundle.message("registry.properties.annotator.show.ep.title"),
epText, null, null)
}
}
private class AddDescriptionKeyIntention(private val myPropertyName: String) : IntentionAction {
@Nls
override fun getText(): String = DevKitBundle.message("registry.properties.annotator.add.description.text", myPropertyName)
@Nls
override fun getFamilyName(): String = DevKitBundle.message("registry.properties.annotator.add.description.family.name")
override fun isAvailable(project: Project, editor: Editor, file: PsiFile): Boolean = true
@Suppress("HardCodedStringLiteral")
@Throws(IncorrectOperationException::class)
override fun invoke(project: Project, editor: Editor, file: PsiFile) {
val propertiesFile = file as PropertiesFile
val originalProperty = propertiesFile.findPropertyByKey(myPropertyName) as PropertyImpl?
val descriptionProperty = propertiesFile.addPropertyAfter(myPropertyName + DESCRIPTION_SUFFIX, "Description", originalProperty)
val valueNode = (descriptionProperty.psiElement as PropertyImpl).valueNode!!
PsiNavigateUtil.navigate(valueNode.psi)
}
override fun startInWriteAction(): Boolean = true
}
companion object {
@NonNls
private val PLUGIN_GROUP_NAMES = setOf(
"appcode", "cidr", "clion",
"cvs", "git", "github", "svn", "hg4idea", "tfs",
"dart", "markdown",
"java", "javac", "uast", "junit4", "dsm",
"js", "javascript", "typescript", "nodejs", "eslint", "jest",
"ruby", "rubymine",
"groovy", "grails", "python", "php", "kotlin"
)
@NonNls
private const val REGISTRY_PROPERTIES_FILENAME = "registry.properties"
@NonNls
const val DESCRIPTION_SUFFIX = ".description"
@NonNls
const val RESTART_REQUIRED_SUFFIX = ".restartRequired"
@JvmStatic
fun isImplicitUsageKey(keyName: String): Boolean =
StringUtil.endsWith(keyName, DESCRIPTION_SUFFIX) || StringUtil.endsWith(keyName, RESTART_REQUIRED_SUFFIX)
@JvmStatic
fun isRegistryPropertiesFile(psiFile: PsiFile): Boolean =
PsiUtil.isIdeaProject(psiFile.project) && psiFile.name == REGISTRY_PROPERTIES_FILENAME
}
} | apache-2.0 | c7015d6b72d94127fcc36388782729e5 | 41.251748 | 140 | 0.728025 | 4.805887 | false | false | false | false |
80998062/Fank | presentation/src/main/java/com/sinyuk/fanfou/ui/BadgedImageView.kt | 1 | 5643 | /*
*
* * Apache License
* *
* * Copyright [2017] Sinyuk
* *
* * 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.sinyuk.fanfou.ui
import android.content.Context
import android.graphics.*
import android.graphics.Bitmap.Config.ARGB_8888
import android.graphics.Paint.ANTI_ALIAS_FLAG
import android.graphics.Paint.SUBPIXEL_TEXT_FLAG
import android.graphics.PorterDuff.Mode.CLEAR
import android.graphics.drawable.Drawable
import android.support.annotation.ColorInt
import android.text.TextPaint
import android.util.AttributeSet
import android.view.Gravity
import com.sinyuk.fanfou.R
import com.sinyuk.fanfou.util.px2dp
/**
* Created by sinyuk on 2018/1/25.
* <p>
* A view group that draws a badge drawable on top of it's contents.
* <p/>
*/
class BadgedImageView(context: Context, attrs: AttributeSet) : SquareImageView(context, attrs) {
var drawBadge = false
private val badge: Drawable
private var badgeBoundsSet = false
private val badgeGravity: Int
private val badgePadding: Int
init {
badge = GifBadge(context)
val a = context.obtainStyledAttributes(attrs, R.styleable.BadgedImageView, 0, 0)
badgeGravity = a.getInt(R.styleable.BadgedImageView_badgeGravity, Gravity.END or Gravity
.BOTTOM)
badgePadding = a.getDimensionPixelSize(R.styleable.BadgedImageView_badgePadding, px2dp(context, 8f))
a.recycle()
}
fun setBadgeColor(@ColorInt color: Int) {
badge.setColorFilter(color, PorterDuff.Mode.SRC_IN)
}
val badgeBounds: Rect
get() {
if (!badgeBoundsSet) {
layoutBadge()
}
return badge.bounds
}
override fun draw(canvas: Canvas) {
super.draw(canvas)
if (drawBadge) {
if (!badgeBoundsSet) {
layoutBadge()
}
badge.draw(canvas)
}
}
override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
super.onSizeChanged(w, h, oldw, oldh)
layoutBadge()
}
private fun layoutBadge() {
val badgeBounds = badge.bounds
Gravity.apply(badgeGravity,
badge.intrinsicWidth,
badge.intrinsicHeight,
Rect(0, 0, width, height),
badgePadding,
badgePadding,
badgeBounds)
badge.bounds = badgeBounds
badgeBoundsSet = true
}
/**
* A drawable for indicating that an image is animated
*/
private class GifBadge internal constructor(context: Context) : Drawable() {
private val paint = Paint()
init {
if (bitmap == null) {
val dm = context.resources.displayMetrics
val density = dm.density
val scaledDensity = dm.scaledDensity
val textPaint = TextPaint(ANTI_ALIAS_FLAG or SUBPIXEL_TEXT_FLAG)
textPaint.typeface = Typeface.create(TYPEFACE, TYPEFACE_STYLE)
textPaint.textSize = TEXT_SIZE * scaledDensity
val padding = PADDING * density
val textBounds = Rect()
textPaint.getTextBounds(GIF, 0, GIF.length, textBounds)
val height = padding + textBounds.height() + padding
val width = padding + textBounds.width() + padding
bitmap = Bitmap.createBitmap(width.toInt(), height.toInt(), ARGB_8888).apply {
setHasAlpha(true)
}
Canvas(bitmap).apply {
val backgroundPaint = Paint(ANTI_ALIAS_FLAG)
backgroundPaint.color = BACKGROUND_COLOR
val cornerRadius = CORNER_RADIUS * density
drawRoundRect(0f, 0f, width, height, cornerRadius, cornerRadius, backgroundPaint)
// punch out the word 'GIF', leaving transparency
textPaint.xfermode = PorterDuffXfermode(CLEAR)
drawText(GIF, padding, height - padding, textPaint)
}
}
}
override fun getIntrinsicWidth() = bitmap?.width ?: 0
override fun getIntrinsicHeight() = bitmap?.height ?: 0
override fun draw(canvas: Canvas) {
canvas.drawBitmap(bitmap, bounds.left.toFloat(), bounds.top.toFloat(), paint)
}
override fun setAlpha(alpha: Int) {
paint.alpha = alpha
}
override fun setColorFilter(cf: ColorFilter?) {
paint.colorFilter = cf
}
override fun getOpacity() = PixelFormat.TRANSLUCENT
companion object {
private const val GIF = "GIF"
private const val TEXT_SIZE = 11 // sp
private const val PADDING = 4 // dp
private const val CORNER_RADIUS = 4 // dp
private const val BACKGROUND_COLOR = Color.WHITE
private const val TYPEFACE = "sans-serif-black"
private const val TYPEFACE_STYLE = Typeface.NORMAL
private var bitmap: Bitmap? = null
}
}
} | mit | b946cb28833eb73bfca9ff7d1c7d46ea | 33.414634 | 108 | 0.607301 | 4.621622 | false | false | false | false |
80998062/Fank | domain/src/main/java/com/sinyuk/fanfou/domain/repo/SignInTask.kt | 1 | 2834 | /*
*
* * Apache License
* *
* * Copyright [2017] Sinyuk
* *
* * 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.sinyuk.fanfou.domain.repo
import android.annotation.SuppressLint
import android.arch.lifecycle.MutableLiveData
import android.content.SharedPreferences
import com.sinyuk.fanfou.domain.ACCESS_SECRET
import com.sinyuk.fanfou.domain.ACCESS_TOKEN
import com.sinyuk.fanfou.domain.DO.Authorization
import com.sinyuk.fanfou.domain.DO.Resource
import com.sinyuk.fanfou.domain.TYPE_GLOBAL
import com.sinyuk.fanfou.domain.util.XauthUtils
import okhttp3.HttpUrl
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.Response
import java.io.IOException
import javax.inject.Named
/**
* Created by sinyuk on 2017/12/6.
*
*/
class SignInTask constructor(private val account: String,
private val password: String,
private val client: OkHttpClient,
@Named(TYPE_GLOBAL) private val preferences: SharedPreferences) : Runnable {
val liveData: MutableLiveData<Resource<Authorization>> = MutableLiveData()
@SuppressLint("CommitPrefEdits")
override fun run() {
try {
val url: HttpUrl = XauthUtils.newInstance(account, password).url()
val request = Request.Builder().url(url).build()
val response: Response = client.newCall(request).execute()
if (response.isSuccessful && response.body() != null) {
val text = response.body()!!.string()
val querySpilt = text.split("&")
val tokenAttr = querySpilt[0].split("=".toRegex())
val secretAttr = querySpilt[1].split("=".toRegex())
val token = tokenAttr[1]
val secret = secretAttr[1]
preferences.edit().apply {
putString(ACCESS_SECRET, secret)
putString(ACCESS_TOKEN, token)
}.apply()
liveData.postValue(Resource.success(Authorization(token, secret)))
} else {
liveData.postValue(Resource.error(response.message(), null))
}
} catch (e: IOException) {
liveData.postValue(Resource.error(e.message, null))
}
}
} | mit | 407218ef6569784245866f41efda2ac3 | 35.818182 | 105 | 0.642908 | 4.366718 | false | false | false | false |
jbmlaird/DiscogsBrowser | app/src/main/java/bj/vinylbrowser/label/LabelController.kt | 1 | 4342 | package bj.vinylbrowser.label
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.Toolbar
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import bj.vinylbrowser.R
import bj.vinylbrowser.common.BaseController
import bj.vinylbrowser.customviews.MyRecyclerView
import bj.vinylbrowser.main.MainActivity
import bj.vinylbrowser.main.MainComponent
import bj.vinylbrowser.model.common.Label
import bj.vinylbrowser.model.labelrelease.LabelRelease
import bj.vinylbrowser.release.ReleaseController
import bj.vinylbrowser.utils.analytics.AnalyticsTracker
import com.bluelinelabs.conductor.RouterTransaction
import com.bluelinelabs.conductor.changehandler.FadeChangeHandler
import kotlinx.android.synthetic.main.controller_single_list.view.*
import javax.inject.Inject
/**
* Created by Josh Laird on 29/05/2017.
*/
class LabelController(val title: String, val id: String) : BaseController(), LabelContract.View {
@Inject lateinit var presenter: LabelPresenter
@Inject lateinit var tracker: AnalyticsTracker
@Inject lateinit var epxController: LabelEpxController
lateinit var recyclerView: MyRecyclerView
lateinit var toolbar: Toolbar
constructor(args: Bundle) : this(args.getString("title"), args.getString("id"))
override fun setupComponent(mainComponent: MainComponent) {
mainComponent
.labelComponentBuilder()
.labelActivityModule(LabelModule(this))
.build()
.inject(this)
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup): View {
val view = inflater.inflate(R.layout.controller_recyclerview, container, false)
setupComponent((activity as MainActivity).mainComponent)
recyclerView = view.recyclerView
setupToolbar(view.toolbar, "")
setupRecyclerView(recyclerView, epxController, title)
presenter.fetchReleaseDetails(id)
return view
}
override fun onAttach(view: View) {
super.onAttach(view)
if (view.recyclerView.adapter == null)
setupRecyclerView(view.recyclerView, epxController, title)
}
private fun setupRecyclerView(recyclerView: MyRecyclerView?, controller: LabelEpxController, title: String?) {
recyclerView?.layoutManager = LinearLayoutManager(applicationContext)
recyclerView?.adapter = controller.adapter
controller.setTitle(title)
controller.requestModelBuild()
}
override fun openLink(url: String?) {
tracker.send(applicationContext?.getString(R.string.label_activity), applicationContext?.getString(R.string.label_activity), applicationContext?.getString(R.string.clicked), url, "1")
val intent = Intent(Intent.ACTION_VIEW, Uri.parse(url))
activity?.startActivity(intent)
}
override fun retry() {
tracker.send(applicationContext?.getString(R.string.label_activity), applicationContext?.getString(R.string.label_activity), applicationContext?.getString(R.string.clicked), "retry", "1")
presenter.fetchReleaseDetails(args.getString("id"))
}
override fun displayRelease(id: String, title: String) {
tracker.send(applicationContext?.getString(R.string.label_activity), applicationContext?.getString(R.string.label_activity), applicationContext?.getString(R.string.clicked), "labelRelease", "1")
router.pushController(RouterTransaction.with(ReleaseController(title, id))
.popChangeHandler(FadeChangeHandler())
.pushChangeHandler(FadeChangeHandler())
.tag("ReleaseController"))
}
override fun onRestoreViewState(view: View, savedViewState: Bundle) {
super.onRestoreViewState(view, savedViewState)
epxController.setLabel(savedViewState.getParcelable<Label>("label"))
epxController.setLabelReleases(savedViewState.getParcelableArrayList("labelReleases"))
}
override fun onSaveViewState(view: View, outState: Bundle) {
outState.putParcelable("label", epxController.label)
outState.putParcelableArrayList("labelReleases", epxController.labelReleases as ArrayList<LabelRelease>)
super.onSaveViewState(view, outState)
}
} | mit | 0741e84608f0653b4e40f32394a6c739 | 43.316327 | 202 | 0.743667 | 5.025463 | false | false | false | false |
juzraai/ted-xml-model | src/main/kotlin/hu/juzraai/ted/xml/model/tedexport/links/Link.kt | 1 | 902 | package hu.juzraai.ted.xml.model.tedexport.links
import hu.juzraai.ted.xml.model.meta.Compatible
import hu.juzraai.ted.xml.model.meta.TedXmlSchemaVersion.R208
import hu.juzraai.ted.xml.model.meta.TedXmlSchemaVersion.R209
import org.simpleframework.xml.Attribute
import org.simpleframework.xml.Namespace
import org.simpleframework.xml.Root
@Root
data class Link(
@field:Attribute(name = "type")
@field:Namespace(prefix = "xlink", reference = "http://www.w3.org/1999/xlink")
@field:Compatible(R208, R209)
var type: String = "",
@field:Attribute(name = "href")
@field:Namespace(prefix = "xlink", reference = "http://www.w3.org/1999/xlink")
@field:Compatible(R208, R209)
var href: String = "",
@field:Attribute(name = "title", required = false)
@field:Namespace(prefix = "xlink", reference = "http://www.w3.org/1999/xlink")
@field:Compatible(R208, R209)
var title: String = ""
) | apache-2.0 | c1976bf3a9ce680e380bed1c42a5c9e7 | 33.730769 | 80 | 0.732816 | 3.037037 | false | false | false | false |
myunusov/maxur-mserv | maxur-mserv-core/src/main/kotlin/org/maxur/mserv/frame/runner/LocatorBuilder.kt | 1 | 1333 | package org.maxur.mserv.frame.runner
import org.maxur.mserv.frame.LocatorConfig
import org.maxur.mserv.frame.LocatorImpl
import org.maxur.mserv.frame.kotlin.Locator
import java.util.concurrent.atomic.AtomicInteger
/**
* The Service Locator Builder.
*
* @author Maxim Yunusov
* @version 1.0
* @since <pre>26.08.2017</pre>
*/
abstract class LocatorBuilder() {
companion object {
private var nameCount = AtomicInteger()
}
protected val name get() = "locator ${nameCount.andIncrement}"
/**
* List of project service packages for service locator lookup.
*/
var packages: Set<String> = setOf()
/**
* Build service locator.
*/
fun build(init: LocatorConfig.() -> Unit): Locator = try {
val locator = make()
locator.configure {
bind(org.maxur.mserv.frame.kotlin.Locator(locator))
bind(org.maxur.mserv.frame.java.Locator(locator))
}
locator.registerAsSingleton()
configure(locator) {
init()
}
org.maxur.mserv.frame.kotlin.Locator(locator)
} catch (e: Exception) {
Locator.current.onConfigurationError(e)
}
protected abstract fun make(): LocatorImpl
protected abstract fun configure(locator: LocatorImpl, function: LocatorConfig.() -> Unit): LocatorConfig
} | apache-2.0 | b0cdc9f02da1d531670cf221b0f8856e | 26.22449 | 109 | 0.655664 | 4.152648 | false | true | false | false |
sksamuel/ktest | kotest-property/src/jvmTest/kotlin/com/sksamuel/kotest/property/shrinking/ListShrinkerTest.kt | 1 | 3859 | package com.sksamuel.kotest.property.shrinking
import io.kotest.assertions.throwables.shouldThrowAny
import io.kotest.core.spec.style.FunSpec
import io.kotest.extensions.system.captureStandardOut
import io.kotest.inspectors.forAtLeastOne
import io.kotest.matchers.collections.shouldHaveAtMostSize
import io.kotest.matchers.collections.shouldHaveSize
import io.kotest.matchers.shouldBe
import io.kotest.matchers.string.shouldContain
import io.kotest.property.Arb
import io.kotest.property.PropTestConfig
import io.kotest.property.PropertyTesting
import io.kotest.property.ShrinkingMode
import io.kotest.property.arbitrary.ListShrinker
import io.kotest.property.arbitrary.constant
import io.kotest.property.arbitrary.int
import io.kotest.property.arbitrary.list
import io.kotest.property.checkAll
import io.kotest.property.internal.doShrinking
import io.kotest.property.rtree
class ListShrinkerTest : FunSpec() {
init {
val state = PropertyTesting.shouldPrintShrinkSteps
beforeSpec {
PropertyTesting.shouldPrintShrinkSteps = false
}
afterSpec {
PropertyTesting.shouldPrintShrinkSteps = state
}
test("ListShrinker should include bisected input") {
checkAll(Arb.list(Arb.int(0..1000))) { list ->
if (list.size > 1) {
val candidates = ListShrinker<Int>(0..100).shrink(list)
candidates.forAtLeastOne {
list.take(list.size / 2) shouldBe it
}
}
}
}
test("ListShrinker should include input minus head") {
checkAll(Arb.list(Arb.int(0..1000))) { list ->
if (list.size > 1) {
val candidates = ListShrinker<Int>(0..100).shrink(list)
candidates.forAtLeastOne {
list.drop(1) shouldBe it
}
}
}
}
test("ListShrinker should include input minus tail") {
checkAll(Arb.list(Arb.int(0..1000))) { list ->
if (list.size > 1) {
val candidates = ListShrinker<Int>(0..100).shrink(list)
candidates.forAtLeastOne {
list.dropLast(1) shouldBe it
}
}
}
}
test("ListShrinker should shrink to expected value") {
checkAll(Arb.list(Arb.int(0..1000))) { list ->
if (list.isNotEmpty()) {
val shrinks = ListShrinker<Int>(0..100).rtree(list)
val shrunk = doShrinking(shrinks, ShrinkingMode.Unbounded) {
it shouldHaveSize 0
}
shrunk.shrink shouldHaveSize 1
}
}
val input = listOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
val shrinks = ListShrinker<Int>(0..100).rtree(input)
val shrunk = doShrinking(shrinks, ShrinkingMode.Unbounded) {
it shouldHaveAtMostSize 2
}
shrunk.shrink shouldHaveSize 3
}
test("ListShrinker should observe range") {
checkAll(Arb.list(Arb.constant(0), range = 4..100)) { list ->
if (list.isNotEmpty()) {
val shrinks = ListShrinker<Int>(4..100).rtree(list)
val shrunk = doShrinking(shrinks, ShrinkingMode.Unbounded) {
it shouldHaveSize 0
}
shrunk.shrink shouldHaveSize 4
}
}
}
test("ListShrinker in action") {
val stdout = captureStandardOut {
PropertyTesting.shouldPrintShrinkSteps = true
shouldThrowAny {
checkAll(PropTestConfig(seed = 123132), Arb.list(Arb.int(0..100))) { list ->
list.shouldHaveAtMostSize(3)
}
}
}
println(stdout)
stdout.shouldContain("Shrink result (after 24 shrinks) => [1, 100, 96, 29")
}
}
}
| mit | 77d9cb6d2e21d84b79d879d7bafd387d | 32.850877 | 91 | 0.598601 | 4.632653 | false | true | false | false |
ZoranPandovski/al-go-rithms | sort/bogo_sort/kotlin/bogo_sort.kt | 1 | 1665 | /*
Bogo Sort
Bogo Sort is the most inefficient way of sorting an algorithm.
The way Bogo Sort works is like throwing a deck of cards in the air
and picking them back up and checking to see if it's organized.
Array of ints [ 3, 1, 2 ]
Step 1.
Starts at the start of the array and will grab a random index from the array to switch with.
randomIndex = RANDOM NUMBER
Step 2.
Once random index is obtained, it will then switch the current index value with the random index value
Example: randomIndex = 2, currentIndex = 0
[ 3, 1, 2 ] ---> [ 2, 1, 3 ]
Step 3.
Check if array is sorted.
[ 2, 1, 3 ] <---- Is not sorted so go onto the next index and repeat steps 1 & 2. Stop when sorted
- You could be done in the next step or the next million steps :')
*/
package com.exam.kotlin.codingproject
import kotlin.random.Random
class BogoSort {
companion object{
private val randomValues = List(10) { Random.nextInt(0, 100) }
private fun isSorted(arr: IntArray): Boolean {
for (i in 0 until arr.size - 1) {
if (arr[i] > arr[i + 1]) {
return false
}
}
return true
}
fun bogoSort(numbersToSort: IntArray) : IntArray {
while (!isSorted(numbersToSort)) {
for (i in numbersToSort.indices) {
val randomIndex = randomValues[numbersToSort.size]
val holder = numbersToSort[i]
numbersToSort[i] = numbersToSort[randomIndex]
numbersToSort[randomIndex] = holder
}
}
return numbersToSort
}
}
}
| cc0-1.0 | e889315fbf8515a727404e4eead49e58 | 27.706897 | 102 | 0.603003 | 4.141791 | false | false | false | false |
breadwallet/breadwallet-android | app/src/main/java/com/breadwallet/ui/settings/SettingsScreen.kt | 1 | 9095 | /**
* BreadWallet
*
* Created by Pablo Budelli <[email protected]> on 10/17/19.
* Copyright (c) 2019 breadwallet LLC
*
* 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.breadwallet.ui.settings
import android.net.Uri
import com.breadwallet.R
import com.breadwallet.tools.util.Link
import com.breadwallet.ui.ViewEffect
import com.breadwallet.ui.navigation.NavigationEffect
import com.breadwallet.ui.navigation.NavigationTarget
import com.breadwallet.util.CurrencyCode
import dev.zacsweers.redacted.annotations.Redacted
object SettingsScreen {
const val CONFIRM_EXPORT_TRANSACTIONS_DIALOG = "confirm_export"
data class M(
val section: SettingsSection,
@Redacted val items: List<SettingsItem> = listOf(),
val isLoading: Boolean = false
) {
companion object {
fun createDefault(section: SettingsSection) = M(section)
}
}
sealed class E {
data class OnLinkScanned(val link: Link) : E()
data class OnOptionClicked(val option: SettingsOption) : E()
data class OnOptionsLoaded(@Redacted val options: List<SettingsItem>) : E()
object OnBackClicked : E()
object OnCloseClicked : E()
object OnAuthenticated : E()
data class ShowPhrase(@Redacted val phrase: List<String>) : E()
data class SetApiServer(val host: String) : E()
data class SetPlatformDebugUrl(val url: String) : E()
data class SetPlatformBundle(val bundle: String) : E()
data class SetTokenBundle(val bundle: String) : E()
object OnWalletsUpdated : E()
object ShowHiddenOptions : E()
object OnCloseHiddenMenu : E()
data class OnATMMapClicked(val url: String, val mapJson: String) : E()
object OnExportTransactionsConfirmed : E()
data class OnTransactionsExportFileGenerated(val uri: Uri) : E()
}
sealed class F {
object SendAtmFinderRequest : F()
object SendLogs : F()
object ViewLogs : F(), NavigationEffect {
override val navigationTarget = NavigationTarget.LogcatViewer
}
object ViewMetadata : F(), NavigationEffect {
override val navigationTarget = NavigationTarget.MetadataViewer
}
object ShowApiServerDialog : F(), ViewEffect
object ShowPlatformDebugUrlDialog : F(), ViewEffect
object ShowPlatformBundleDialog : F(), ViewEffect
object ShowTokenBundleDialog : F(), ViewEffect
object ResetDefaultCurrencies : F()
object WipeNoPrompt : F()
object GetPaperKey : F()
object EnableAllWallets : F()
object ClearBlockchainData : F()
object ToggleRateAppPrompt : F()
object RefreshTokens : F()
object DetailedLogging : F()
object CopyPaperKey : F()
object ToggleTezos : F()
data class SetApiServer(val host: String) : F()
data class SetPlatformDebugUrl(val url: String) : F()
data class SetPlatformBundle(val bundle: String) : F()
data class SetTokenBundle(val bundle: String) : F()
data class LoadOptions(val section: SettingsSection) : F()
data class GoToSection(val section: SettingsSection) : F(), NavigationEffect {
override val navigationTarget = NavigationTarget.Menu(section)
}
object GoBack : F(), NavigationEffect {
override val navigationTarget = NavigationTarget.Back
}
object GoToSupport : F(), NavigationEffect {
override val navigationTarget = NavigationTarget.SupportPage("")
}
object GoToQrScan : F(), NavigationEffect {
override val navigationTarget = NavigationTarget.QRScanner
}
object GoToBrdRewards : F(), NavigationEffect {
override val navigationTarget = NavigationTarget.BrdRewards
}
object GoToGooglePlay : F(), NavigationEffect {
override val navigationTarget = NavigationTarget.ReviewBrd
}
object GoToAbout : F(), NavigationEffect {
override val navigationTarget = NavigationTarget.About
}
object GoToDisplayCurrency : F(), NavigationEffect {
override val navigationTarget = NavigationTarget.DisplayCurrency
}
object GoToNotificationsSettings : F(), NavigationEffect {
override val navigationTarget = NavigationTarget.NotificationsSettings
}
object GoToShareData : F(), NavigationEffect {
override val navigationTarget = NavigationTarget.ShareDataSettings
}
object GoToImportWallet : F(), NavigationEffect {
override val navigationTarget = NavigationTarget.ImportWallet()
}
data class GoToSyncBlockchain(
val currencyCode: CurrencyCode
) : F(), NavigationEffect {
override val navigationTarget = NavigationTarget.SyncBlockchain(currencyCode)
}
object GoToNodeSelector : F(), NavigationEffect {
override val navigationTarget = NavigationTarget.BitcoinNodeSelector
}
object GoToEnableSegWit : F(), NavigationEffect {
override val navigationTarget = NavigationTarget.EnableSegWit
}
object GoToLegacyAddress : F(), NavigationEffect {
override val navigationTarget = NavigationTarget.LegacyAddress
}
object GoToFingerprintAuth : F(), NavigationEffect {
override val navigationTarget = NavigationTarget.FingerprintSettings
}
object GoToUpdatePin : F(), NavigationEffect {
override val navigationTarget = NavigationTarget.SetPin()
}
object GoToWipeWallet : F(), NavigationEffect {
override val navigationTarget = NavigationTarget.WipeWallet
}
object GoToOnboarding : F(), NavigationEffect {
override val navigationTarget = NavigationTarget.OnBoarding
}
object GoToNativeApiExplorer : F(), NavigationEffect {
override val navigationTarget = NavigationTarget.NativeApiExplorer
}
object GoToHomeScreen : F(), NavigationEffect {
override val navigationTarget = NavigationTarget.Home
}
object GoToAuthentication : F(), NavigationEffect {
override val navigationTarget = NavigationTarget.Authentication()
}
data class GoToPaperKey(
@Redacted val phrase: List<String>
) : F(), NavigationEffect {
override val navigationTarget =
NavigationTarget.PaperKey(phrase, null)
}
data class GoToFastSync(
val currencyCode: CurrencyCode
) : F(), NavigationEffect {
override val navigationTarget = NavigationTarget.FastSync(currencyCode)
}
data class GoToLink(val link: Link) : F(), NavigationEffect {
override val navigationTarget = NavigationTarget.DeepLink(
link = link,
authenticated = true
)
}
data class GoToATMMap(val url: String, val mapJson: String) : F(), NavigationEffect {
override val navigationTarget = NavigationTarget.ATMMap(url, mapJson)
}
object RelaunchHomeScreen : F(), NavigationEffect {
override val navigationTarget = NavigationTarget.Home
}
object ShowConfirmExportTransactions : F(), NavigationEffect {
override val navigationTarget = NavigationTarget.AlertDialog(
titleResId = R.string.ExportConfirmation_title,
messageResId = R.string.ExportConfirmation_message,
positiveButtonResId = R.string.ExportConfirmation_continue,
negativeButtonResId = R.string.ExportConfirmation_cancel,
dialogId = CONFIRM_EXPORT_TRANSACTIONS_DIALOG
)
}
object GenerateTransactionsExportFile: F()
data class ExportTransactions(val uri: Uri) : F(), ViewEffect
}
}
| mit | f29f960b565eb4e56dbffefa92d51354 | 37.214286 | 93 | 0.662012 | 5.469032 | false | false | false | false |
Austin72/Charlatano | src/main/kotlin/com/charlatano/game/Entities.kt | 1 | 2980 | /*
* Charlatano: Free and open-source (FOSS) cheat for CS:GO/CS:CO
* Copyright (C) 2017 - Thomas G. P. Nappo, Jonathan Beaudoin
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.charlatano.game
import com.charlatano.settings.MAX_ENTITIES
import com.charlatano.game.entity.Entity
import com.charlatano.game.entity.EntityType
import com.charlatano.game.entity.Player
import com.charlatano.game.entity.bone
import com.charlatano.utils.Angle
import com.charlatano.utils.collections.CacheableList
import com.charlatano.utils.collections.ListContainer
import com.charlatano.utils.readCached
import it.unimi.dsi.fastutil.ints.Int2ObjectArrayMap
import it.unimi.dsi.fastutil.longs.Long2ObjectMap
import it.unimi.dsi.fastutil.longs.Long2ObjectOpenHashMap
import it.unimi.dsi.fastutil.objects.Object2ObjectArrayMap
import it.unimi.dsi.fastutil.objects.Object2ObjectMap
import java.util.*
var me: Player = 0
var clientState: ClientState = 0
typealias EntityContainer = ListContainer<EntityContext>
typealias EntityList = Object2ObjectArrayMap<EntityType, CacheableList<EntityContext>>
private val cachedResults = Int2ObjectArrayMap<EntityContainer>(EntityType.size)
val entitiesValues = arrayOfNulls<CacheableList<EntityContext>>(MAX_ENTITIES)
var entitiesValuesCounter = 0
val entities: Object2ObjectMap<EntityType, CacheableList<EntityContext>> = EntityList(EntityType.size).apply {
for (type in EntityType.cachedValues) {
val cacheableList = CacheableList<EntityContext>(MAX_ENTITIES)
put(type, cacheableList)
entitiesValues[entitiesValuesCounter++] = cacheableList
}
}
fun entityByType(type: EntityType): EntityContext? = entities[type]?.firstOrNull()
internal inline fun forEntities(types: Array<EntityType> = EntityType.cachedValues,
crossinline body: (EntityContext) -> Unit) {
val hash = Arrays.hashCode(types)
val container = cachedResults.get(hash) ?: EntityContainer(EntityType.size)
if (container.empty()) {
for (type in types) if (type != EntityType.NULL) {
val cacheableList = entities[type]!!
container.addList(cacheableList)
cachedResults.put(hash, container)
}
}
container.forEach(body)
}
val entityToBones: Long2ObjectMap<Angle> = Long2ObjectOpenHashMap()
fun Entity.bones(boneID: Int) = readCached(entityToBones) {
x = bone(0xC, boneID)
y = bone(0x1C, boneID)
z = bone(0x2C, boneID)
} | agpl-3.0 | 121dad5d94bf5ee8952603f688690258 | 36.2625 | 110 | 0.783893 | 3.825417 | false | false | false | false |
JakeWharton/dex-method-list | diffuse/src/main/kotlin/com/jakewharton/diffuse/ApiMapping.kt | 1 | 6267 | package com.jakewharton.diffuse
import com.jakewharton.diffuse.io.Input
class ApiMapping private constructor(private val typeMappings: Map<TypeDescriptor, TypeMapping>) {
override fun equals(other: Any?) = other is ApiMapping && typeMappings == other.typeMappings
override fun hashCode() = typeMappings.hashCode()
override fun toString() = typeMappings.toString()
fun isEmpty() = typeMappings.isEmpty()
val types get() = typeMappings.size
val methods get() = typeMappings.values.sumBy { it.methods.size }
val fields get() = typeMappings.values.sumBy { it.fields.size }
/**
* Given a [TypeDescriptor] which is typically obfuscated, return a new [TypeDescriptor] for the
* original name or return [type] if not included in the mapping.
*/
operator fun get(type: TypeDescriptor): TypeDescriptor {
return typeMappings[type.componentDescriptor]
?.typeDescriptor
?.asArray(type.arrayArity)
?: type
}
/**
* Given a [Member] which is typically obfuscated, return a new [Member] with the types and
* name mapped back to their original values or return [member] if the declaring type is not
* included in the mapping.
*/
operator fun get(member: Member) = when (member) {
is Field -> this[member]
is Method -> this[member]
}
/**
* Given a [Field] which is typically obfuscated, return a new [Field] with the types and
* name mapped back to their original values or return [field] if the declaring type is not
* included in the mapping.
*/
operator fun get(field: Field): Field {
val declaringType = field.declaringType.componentDescriptor
val declaringTypeMapping = typeMappings[declaringType] ?: return field
val newDeclaringType = declaringTypeMapping.typeDescriptor
.asArray(field.declaringType.arrayArity)
val newType = this[field.type]
val newName = declaringTypeMapping[field.name] ?: field.name
return Field(newDeclaringType, newName, newType)
}
/**
* Given a [Method] which is typically obfuscated, return a new [Method] with the types and
* name mapped back to their original values or return [method] if the declaring type is not
* included in the mapping.
*/
operator fun get(method: Method): Method {
val declaringType = method.declaringType.componentDescriptor
val declaringTypeMapping = typeMappings[declaringType] ?: return method
val newDeclaringType = declaringTypeMapping.typeDescriptor
.asArray(method.declaringType.arrayArity)
val newReturnType = this[method.returnType]
val newParameters = method.parameterTypes.map(::get)
val signature = MethodSignature(newReturnType, method.name, newParameters)
val newName = declaringTypeMapping[signature] ?: method.name
return Method(newDeclaringType, newName, newParameters, newReturnType)
}
companion object {
@JvmField
val EMPTY = ApiMapping(emptyMap())
@JvmStatic
@JvmName("parse")
fun Input.toApiMapping(): ApiMapping {
val typeMappings = mutableMapOf<TypeDescriptor, TypeMapping>()
var fromDescriptor: TypeDescriptor? = null
var toDescriptor: TypeDescriptor? = null
var fields: MutableMap<String, String>? = null
var methods: MutableMap<MethodSignature, String>? = null
toUtf8().split('\n').forEachIndexed { index, line ->
if (line.startsWith('#') || line.isBlank()) {
return@forEachIndexed
}
if (line.startsWith(' ')) {
val result = memberLine.matchEntire(line)
?: throw IllegalArgumentException(
"Unable to parse line ${index + 1} as member mapping: $line")
val (_, returnType, fromName, parameters, toName) = result.groupValues
if (parameters != "") {
val returnDescriptor = humanNameToDescriptor(returnType)
val parameterDescriptors = parameters
.substring(1, parameters.lastIndex) // Remove leading '(' and trailing ')'.
.takeUnless(String::isEmpty) // Do not process parameter-less methods.
?.split(',')
?.map(::humanNameToDescriptor)
?: emptyList()
val lookupSignature = MethodSignature(returnDescriptor, toName, parameterDescriptors)
methods!![lookupSignature] = fromName
} else {
fields!![toName] = fromName
}
} else {
if (fromDescriptor != null) {
typeMappings[toDescriptor!!] = TypeMapping(fromDescriptor!!, fields!!, methods!!)
}
val result = typeLine.matchEntire(line)
?: throw IllegalArgumentException(
"Unable to parse line ${index + 1} as type mapping: $line")
val (_, fromType, toType) = result.groupValues
fromDescriptor = humanNameToDescriptor(fromType)
toDescriptor = humanNameToDescriptor(toType)
fields = mutableMapOf()
methods = mutableMapOf()
}
}
if (fromDescriptor != null) {
typeMappings[toDescriptor!!] = TypeMapping(fromDescriptor!!, fields!!, methods!!)
}
return ApiMapping(typeMappings)
}
private val typeLine = Regex("(.+?) -> (.+?):")
private val memberLine = Regex("\\s+(?:\\d+:\\d+:)?(.+?) (.+?)(\\(.*?\\))?(?::\\d+:\\d+)? -> (.+)")
private fun humanNameToDescriptor(name: String): TypeDescriptor {
val type = name.trimEnd('[', ']')
val descriptor = when (type) {
"void" -> "V"
"boolean" -> "Z"
"byte" -> "B"
"char" -> "C"
"double" -> "D"
"float" -> "F"
"int" -> "I"
"long" -> "J"
"short" -> "S"
else -> "L${type.replace('.', '/')};"
}
val arrayArity = (name.length - type.length) / 2
return TypeDescriptor(descriptor).asArray(arrayArity)
}
}
}
private data class MethodSignature(
val returnType: TypeDescriptor,
val name: String,
val parameterTypes: List<TypeDescriptor>
)
private data class TypeMapping(
val typeDescriptor: TypeDescriptor,
val fields: Map<String, String>,
val methods: Map<MethodSignature, String>
) {
operator fun get(field: String) = fields[field]
operator fun get(method: MethodSignature) = methods[method]
}
| apache-2.0 | 1c950f81a67860b6b1cc25987f4a8842 | 36.753012 | 103 | 0.646721 | 4.722683 | false | false | false | false |
RocketChat/Rocket.Chat.Android | app/src/main/java/chat/rocket/android/chatroom/ui/Menu.kt | 2 | 2666 | package chat.rocket.android.chatroom.ui
import android.content.Context
import android.view.Menu
import android.view.MenuItem
import android.widget.EditText
import androidx.appcompat.widget.SearchView
import androidx.core.content.res.ResourcesCompat
import chat.rocket.android.R
import chat.rocket.android.util.extension.onQueryTextListener
internal fun ChatRoomFragment.setupMenu(menu: Menu) {
setupSearchMessageMenuItem(menu, requireContext())
}
private fun ChatRoomFragment.setupSearchMessageMenuItem(menu: Menu, context: Context) {
val searchItem = menu.add(
Menu.NONE,
Menu.NONE,
Menu.NONE,
R.string.title_search_message
).setActionView(SearchView(context))
.setIcon(R.drawable.ic_chatroom_toolbar_magnifier_20dp)
.setShowAsActionFlags(
MenuItem.SHOW_AS_ACTION_IF_ROOM or MenuItem.SHOW_AS_ACTION_COLLAPSE_ACTION_VIEW
)
.setOnActionExpandListener(object : MenuItem.OnActionExpandListener {
override fun onMenuItemActionExpand(item: MenuItem?): Boolean {
dismissEmojiKeyboard()
return true
}
override fun onMenuItemActionCollapse(item: MenuItem?): Boolean {
dismissEmojiKeyboard()
return true
}
})
(searchItem.actionView as? SearchView)?.let {
// TODO: Check why we need to stylize the search text programmatically instead of by defining it in the styles.xml (ChatRoom.SearchView)
it.maxWidth = Integer.MAX_VALUE
stylizeSearchView(it, context)
setupSearchViewTextListener(it)
if (it.isIconified) {
isSearchTermQueried = false
}
}
}
private fun stylizeSearchView(searchView: SearchView, context: Context) {
val searchText = searchView.findViewById<EditText>(androidx.appcompat.R.id.search_src_text)
searchText.setTextColor(ResourcesCompat.getColor(context.resources, R.color.color_white, null))
searchText.setHintTextColor(
ResourcesCompat.getColor(context.resources, R.color.color_white, null)
)
}
private fun ChatRoomFragment.setupSearchViewTextListener(searchView: SearchView) {
searchView.onQueryTextListener {
// TODO: We use isSearchTermQueried to avoid querying when the search view is expanded but the user doesn't start typing. Check for a native solution.
if (it.isEmpty() && isSearchTermQueried) {
presenter.loadMessages(chatRoomId, chatRoomType, clearDataSet = true)
} else if (it.isNotEmpty()) {
presenter.searchMessages(chatRoomId, it)
isSearchTermQueried = true
}
}
} | mit | 1cf29b2fbc720b95891a0db4825194b7 | 38.220588 | 158 | 0.700675 | 4.70194 | false | false | false | false |
google/private-compute-libraries | javatests/com/google/android/libraries/pcc/chronicle/codegen/backend/DataTypeDescriptorDaggerProviderTest.kt | 1 | 2734 | /*
* Copyright 2022 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.libraries.pcc.chronicle.codegen.backend
import com.google.common.truth.StringSubject
import com.google.common.truth.Truth.assertThat
import com.squareup.javapoet.JavaFile
import com.squareup.javapoet.TypeSpec
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.runners.JUnit4
@RunWith(JUnit4::class)
class DataTypeDescriptorDaggerProviderTest {
@Test
fun provideContentsInto_defaultDtdContainingClassName() {
val provider = DataTypeDescriptorDaggerProvider("MyDataClass")
assertThat(provider)
.generatesMethod(
"""
| @Provides
| @Singleton
| @IntoSet
| public static DataTypeDescriptor provideMyDataClassDataTypeDescriptor() {
| return MyDataClass_GeneratedKt.MY_DATA_CLASS_GENERATED_DTD;
| }
""".trimMargin()
)
}
@Test
fun provideContentsInto_customDtdContainingClassName() {
val provider =
DataTypeDescriptorDaggerProvider(
elementName = "MyDataClass",
dtdContainingClassName = "MyDtds"
)
assertThat(provider)
.generatesMethod(
"""
| @Provides
| @Singleton
| @IntoSet
| public static DataTypeDescriptor provideMyDataClassDataTypeDescriptor() {
| return MyDtds.MY_DATA_CLASS_GENERATED_DTD;
| }
""".trimMargin()
)
}
private fun assertThat(provider: DataTypeDescriptorDaggerProvider): StringSubject {
val typeSpec =
TypeSpec.classBuilder("MyClass").apply { provider.provideContentsInto(this) }.build()
val contents = JavaFile.builder("com.google", typeSpec).build().toString().trim()
return assertThat(contents)
}
private fun StringSubject.generatesMethod(method: String) {
isEqualTo(
"""
|package com.google;
|
|import com.google.android.libraries.pcc.chronicle.api.DataTypeDescriptor;
|import dagger.Provides;
|import dagger.multibindings.IntoSet;
|import javax.inject.Singleton;
|
|class MyClass {
|$method
|}
""".trimMargin()
)
}
}
| apache-2.0 | d998cc7f479ddd0ebaa83b516a6132ba | 29.377778 | 91 | 0.681053 | 4.489327 | false | false | false | false |
javiyt/nftweets | app/src/main/java/yt/javi/nftweets/infrastructure/repositories/inmemory/TeamInMemoryRepository.kt | 1 | 666 | package yt.javi.nftweets.infrastructure.repositories.inmemory
import yt.javi.nfltweets.domain.model.team.Team
import yt.javi.nftweets.domain.model.Conference
import yt.javi.nftweets.domain.model.Division
import yt.javi.nftweets.domain.model.team.TeamRepository
class TeamInMemoryRepository(private val teams: List<Team>): TeamRepository {
override fun findTeams(conference: Conference?, division: Division?): List<Team> =
teams.filter { conference == null || it.conference == conference }
.filter { division == null || it.division == division }
override fun findTeam(name: String): Team = teams.first { it.name == name }
} | apache-2.0 | 326ef6a5576dfd597427338d9c5d6346 | 43.466667 | 86 | 0.732733 | 4.111111 | false | false | false | false |
ajalt/clikt | clikt/src/commonMain/kotlin/com/github/ajalt/clikt/parameters/types/range.kt | 1 | 3865 | package com.github.ajalt.clikt.parameters.types
import com.github.ajalt.clikt.core.Context
import com.github.ajalt.clikt.parameters.arguments.ProcessedArgument
import com.github.ajalt.clikt.parameters.options.OptionWithValues
private inline fun <T : Comparable<T>> checkRange(
it: T,
min: T?,
max: T?,
clamp: Boolean,
context: Context,
fail: (String) -> Unit,
): T {
require(min == null || max == null || min < max) { "min must be less than max" }
if (clamp) {
if (min != null && it < min) return min
if (max != null && it > max) return max
} else if (min != null && it < min || max != null && it > max) {
fail(when {
min == null -> context.localization.rangeExceededMax(it.toString(), max.toString())
max == null -> context.localization.rangeExceededMin(it.toString(), min.toString())
else -> context.localization.rangeExceededBoth(it.toString(), min.toString(), max.toString())
})
}
return it
}
// Arguments
/**
* Restrict the argument values to fit into a range.
*
* By default, conversion fails if the value is outside the range, but if [clamp] is true, the value will be
* silently clamped to fit in the range.
*
* This must be called before transforms like `pair`, `default`, or `multiple`, since it checks each
* individual value.
*
* ### Example:
*
* ```
* argument().int().restrictTo(max=10, clamp=true).default(10)
* ```
*/
fun <T : Comparable<T>> ProcessedArgument<T, T>.restrictTo(min: T? = null, max: T? = null, clamp: Boolean = false)
: ProcessedArgument<T, T> {
return copy(
{ checkRange(transformValue(it), min, max, clamp, context) { m -> fail(m) } },
transformAll,
transformValidator
)
}
/**
* Restrict the argument values to fit into a range.
*
* By default, conversion fails if the value is outside the range, but if [clamp] is true, the value will be
* silently clamped to fit in the range.
*
* This must be called before transforms like `pair`, `default`, or `multiple`, since it checks each
* individual value.
*
* ### Example:
*
* ```
* argument().int().restrictTo(1..10, clamp=true).default(10)
* ```
*/
fun <T : Comparable<T>> ProcessedArgument<T, T>.restrictTo(
range: ClosedRange<T>,
clamp: Boolean = false,
): ProcessedArgument<T, T> {
return restrictTo(range.start, range.endInclusive, clamp)
}
// Options
/**
* Restrict the option values to fit into a range.
*
* By default, conversion fails if the value is outside the range, but if [clamp] is true, the value will be
* silently clamped to fit in the range.
*
* This must be called before transforms like `pair`, `default`, or `multiple`, since it checks each
* individual value.
*
* ### Example:
*
* ```
* option().int().restrictTo(max=10, clamp=true).default(10)
* ```
*/
fun <T : Comparable<T>> OptionWithValues<T?, T, T>.restrictTo(
min: T? = null,
max: T? = null,
clamp: Boolean = false,
): OptionWithValues<T?, T, T> {
return copy(
{ checkRange(transformValue(it), min, max, clamp, context) { m -> fail(m) } },
transformEach,
transformAll,
transformValidator
)
}
/**
* Restrict the option values to fit into a range.
*
* By default, conversion fails if the value is outside the range, but if [clamp] is true, the value will be
* silently clamped to fit in the range.
*
* This must be called before transforms like `pair`, `default`, or `multiple`, since it checks each
* individual value.
*
* ### Example:
*
* ```
* option().int().restrictTo(1..10, clamp=true).default(10)
* ```
*/
fun <T : Comparable<T>> OptionWithValues<T?, T, T>.restrictTo(
range: ClosedRange<T>,
clamp: Boolean = false,
): OptionWithValues<T?, T, T> {
return restrictTo(range.start, range.endInclusive, clamp)
}
| apache-2.0 | 0a1d4b0087d4fbe709908f53a481d3e9 | 29.195313 | 114 | 0.639845 | 3.615529 | false | false | false | false |
skydoves/WaterDrink | app/src/main/java/com/skydoves/waterdays/persistence/sqlite/SqliteManager.kt | 1 | 5157 | /*
* Copyright (C) 2016 skydoves
*
* 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.skydoves.waterdays.persistence.sqlite
import android.content.Context
import android.database.sqlite.SQLiteDatabase
import android.database.sqlite.SQLiteOpenHelper
import com.skydoves.waterdays.models.Capacity
import timber.log.Timber
import java.util.ArrayList
/**
* Created by skydoves on 2016-10-15.
* Updated by skydoves on 2017-08-17.
* Copyright (c) 2017 skydoves rights reserved.
*/
class SqliteManager(context: Context, name: String, factory: SQLiteDatabase.CursorFactory?, version: Int) : SQLiteOpenHelper(context, name, factory, version) {
override fun onCreate(db: SQLiteDatabase) {
val CREATE_TABLE_RECORD = "CREATE TABLE " + TABLE_RECORD + "(pk_recordid integer primary key autoincrement, recorddate " +
"DATETIME DEFAULT (datetime('now','localtime')), amount varchar(4));"
db.execSQL(CREATE_TABLE_RECORD)
val CREATE_TABLE_ALARM = "CREATE TABLE " + TABLE_ALARM + "(requestcode integer primary key, daylist varchar(20), " +
"starttime varchar(20), endtime varchar(20), interval integer);"
db.execSQL(CREATE_TABLE_ALARM)
val CREATE_TABLE_CAPACITY = "CREATE TABLE $TABLE_CAPACITY(capacity integer primary key)"
db.execSQL(CREATE_TABLE_CAPACITY)
}
override fun onUpgrade(db: SQLiteDatabase, oldVersion: Int, newVersion: Int) {
db.execSQL("DROP TABLE IF EXISTS $TABLE_RECORD")
db.execSQL("DROP TABLE IF EXISTS $TABLE_ALARM")
db.execSQL("DROP TABLE IF EXISTS $TABLE_CAPACITY")
onCreate(db)
}
fun addCapacity(capacity: Capacity) {
val query_addCapacity = "Insert Into " + TABLE_CAPACITY + " (capacity) Values(" + capacity.amount + ");"
writableDatabase.execSQL(query_addCapacity)
Timber.d("SUCCESS Capacity Inserted : %s", capacity.amount)
}
fun deleteCapacity(capacity: Capacity) {
val query_deleteCapacity = "Delete from " + TABLE_CAPACITY + " Where capacity = " + capacity.amount + ""
writableDatabase.execSQL(query_deleteCapacity)
Timber.d("SUCCESS Capacity Deleted : %s", capacity.amount)
}
val capacityList: List<Capacity>
get() {
val capacities = ArrayList<Capacity>()
val cursor = readableDatabase.rawQuery("select *from $TABLE_CAPACITY order by capacity asc", null)
if (cursor != null && cursor.count > 0 && cursor.moveToFirst()) {
do {
val capacity = Capacity(cursor.getInt(0))
capacities.add(capacity)
} while (cursor.moveToNext())
}
return capacities
}
fun addRecord(amount: String) {
val query_addRecord = "Insert Into $TABLE_RECORD (amount) Values('$amount');"
writableDatabase.execSQL(query_addRecord)
Timber.d("SUCCESS Record Inserted : %s", amount)
}
fun deleteRecord(index: Int) {
val query_addRecord = "Delete from $TABLE_RECORD Where pk_recordid = '$index'"
writableDatabase.execSQL(query_addRecord)
Timber.d("SUCCESS Record Deleted : %s", index)
}
fun updateRecordAmount(index: Int, amount: Int) {
val query_updateAmount = "Update $TABLE_RECORD set amount = '$amount' Where pk_recordid = '$index'"
writableDatabase.execSQL(query_updateAmount)
Timber.d("SUCCESS Record Updated : %s", amount)
}
fun getDayDrinkAmount(datetime: String): Int {
var TotalAmount = 0
val cursor = readableDatabase.rawQuery("select * from " + TABLE_RECORD + " where recorddate >= datetime(date('" + datetime + "','localtime')) " +
"and recorddate < datetime(date('" + datetime + "', 'localtime', '+1 day'))", null)
if (cursor != null && cursor.count > 0 && cursor.moveToFirst()) {
do {
TotalAmount += cursor.getInt(2)
} while (cursor.moveToNext())
}
return TotalAmount
}
fun addAlarm(requestcode: Int, daylist: String, starttime: String, endtime: String, interval: Int) {
val query_addRecord = "Insert Into $TABLE_ALARM Values($requestcode,'$daylist','$starttime','$endtime', $interval);"
writableDatabase.execSQL(query_addRecord)
Timber.d("SUCCESS Alarm Inserted : %s", requestcode)
}
fun deleteAlarm(requestcode: Int) {
val query_addRecord = "Delete from $TABLE_ALARM Where requestcode = '$requestcode'"
writableDatabase.execSQL(query_addRecord)
Timber.d("SUCCESS Alarm Deleted : %s", requestcode)
}
@Synchronized
override fun close() {
super.close()
}
companion object {
const val DATABASE_VERSION = 1
const val DATABASE_NAME = "waterdays.db"
private const val TABLE_RECORD = "RecordList"
private const val TABLE_ALARM = "AlarmList"
private const val TABLE_CAPACITY = "capacityList"
}
}
| apache-2.0 | f8a31b631d4663cb3b2e4c98f2104e23 | 37.485075 | 159 | 0.697692 | 4.06063 | false | false | false | false |
cypressious/learning-spaces | app/src/main/java/de/maxvogler/learningspaces/services/LocationService.kt | 2 | 6510 | package de.maxvogler.learningspaces.services
import com.google.android.gms.maps.model.LatLng
import com.squareup.okhttp.OkHttpClient
import com.squareup.okhttp.Request
import com.squareup.otto.Produce
import com.squareup.otto.Subscribe
import de.maxvogler.learningspaces.events.RequestLocationsEvent
import de.maxvogler.learningspaces.events.UpdateLocationsEvent
import de.maxvogler.learningspaces.exceptions.NetworkException
import de.maxvogler.learningspaces.helpers.*
import de.maxvogler.learningspaces.models.FreeSeatMeasurement
import de.maxvogler.learningspaces.models.Location
import de.maxvogler.learningspaces.models.OpeningHourPair
import de.maxvogler.learningspaces.services.filters.GroupKitBibSuedFilter
import org.jetbrains.anko.async
import org.jetbrains.anko.uiThread
import org.joda.time.LocalTime
import org.joda.time.format.DateTimeFormat
import org.json.simple.JSONArray
import org.json.simple.JSONObject
import org.json.simple.parser.JSONParser
import org.json.simple.parser.ParseException
import java.io.IOException
import java.util.*
/**
* A network service, querying the KIT library location data.
*/
public open class LocationService : BusBasedService() {
private val http = OkHttpClient()
private val filters = listOf(GroupKitBibSuedFilter())
// TODO: Initialize mLastResults with static data to show something while live data is loaded
protected var lastResults: Map<String, Location> = emptyMap()
private val URL = "http://services.bibliothek.kit.edu/leitsystem/getdata.php?callback=jQuery1102036302255163900554_1417122682722&location%5B0%5D=LSG%2CLST%2CLSW%2CLSN%2CLBS%2CFBC%2CLAF%2CFBW%2CFBP%2CFBI%2CFBM%2CFBA%2CBIB-N%2CFBH%2CFBD%2CTheaBib&values%5B0%5D=seatestimate%2Cmanualcount&after%5B0%5D=-10800seconds&before%5B0%5D=now&limit%5B0%5D=-17&location%5B1%5D=LSG%2CLST%2CLSW%2CLSN%2CLBS%2CFBC%2CLAF%2CFBW%2CFBP%2CFBI%2CFBM%2CFBA%2CBIB-N%2CFBH%2CFBD%2CTheaBib&values%5B1%5D=location&after%5B1%5D=&before%5B1%5D=now&limit%5B1%5D=1&refresh=&_=1417122682724"
private val DATE_TIME_FORMAT = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss")
@Subscribe
public open fun onRequestLocations(e: RequestLocationsEvent) {
requestLocationsAsync();
}
public open fun requestLocationsAsync() {
async {
val locations = getLocations()
uiThread {
bus.post(UpdateLocationsEvent(locations))
}
}
}
@Throws(NetworkException::class)
public open fun getLocations(): Map<String, Location> {
val request = Request.Builder().url(URL).build()
val jsonp = try {
http.newCall(request).execute().body().string()
} catch (e: IOException) {
throw NetworkException(e)
}
val json = jsonp.substringAfter('(').substringBeforeLast(')')
return getLocations(json)
}
@Throws(NetworkException::class)
public open fun getLocations(json: String): Map<String, Location> {
var locations: MutableMap<String, Location> = HashMap()
val parser = JSONParser()
try {
parseRecursively(locations, parser.parse(json))
} catch (e: ParseException) {
throw NetworkException(e)
}
filters.forEach { locations = it.apply(locations) }
lastResults = locations
return locations
}
@Produce
public fun getLastResults(): UpdateLocationsEvent {
return UpdateLocationsEvent(lastResults)
}
private fun parseRecursively(locations: MutableMap<String, Location>, root: Any) {
if (root is JSONObject) {
if (root.containsKeys("location_name", "free_seats")) {
parseFreeSeatMeasurement(locations, root)
} else if (root.containsKeys("name", "long_name")) {
parseLocation(locations, root)
} else {
root.values().forEach { parseRecursively(locations, it!!) }
}
} else if (root is JSONArray) {
root.forEach { parseRecursively(locations, it!!) }
}
}
private fun parseLocation(locations: MutableMap<String, Location>, node: JSONObject) {
val name = node.string("name")!!
val location = locations.getOrPut(name, { Location(name) })
val coordinates = node.string("geo_coordinates")
location.name = node.string("long_name")
location.building = node.string("building")
location.room = node.string("room")
location.level = node.string("level")
location.superLocationString = node.string("super_location")
location.totalSeats = node.int("available_seats") ?: 0
location.openingHours.addAll(parseOpeningHourPairs(node))
if (coordinates != null) location.coordinates = parseLatLng(coordinates)
}
private fun parseOpeningHourPairs(json: JSONObject): List<OpeningHourPair> {
val hoursArray = json.obj("opening_hours")?.array("weekly_opening_hours")!!
return hoursArray.flatMap {
val (open, close) = (it as JSONArray)
.map { it as JSONObject }
.map { DATE_TIME_FORMAT.parseLocalDateTime(it.string("date")) }
val openWeekday = open.toWeekday()
val closeWeekday = close.toWeekday()
(openWeekday..closeWeekday).map { weekday ->
if(openWeekday == weekday && closeWeekday == weekday) {
OpeningHourPair(weekday, open.toLocalTime(), close.toLocalTime())
} else {
val openTime = if (openWeekday < weekday) LocalTime.MIDNIGHT else open.toLocalTime()
val closeTime = if(closeWeekday > weekday) LocalTime(23, 59, 59) else close.toLocalTime()
OpeningHourPair(weekday, openTime, closeTime)
}
}
}
}
private fun parseFreeSeatMeasurement(locations: MutableMap<String, Location>, json: JSONObject) {
val name = json.string("location_name")!!
val freeSeats = json.int("free_seats")
val date = DATE_TIME_FORMAT.parseLocalDateTime(json.obj("timestamp")?.string("date"))
val location = locations.getOrPut(name, { Location(name) })
if (freeSeats != null) location.measurements.add(FreeSeatMeasurement(date, freeSeats))
}
private fun parseLatLng(geoCoordinates: String): LatLng {
val (lat, lng) = geoCoordinates.split(";").map { it.toDouble() }
return LatLng(lat, lng)
}
} | gpl-2.0 | 6a561c82d3a1b458fe115d6fd3c021bb | 38.944785 | 563 | 0.674808 | 4.091766 | false | false | false | false |
ngageoint/mage-android | mage/src/main/java/mil/nga/giat/mage/geopackage/media/GeoPackageMediaViewModel.kt | 1 | 3118 | package mil.nga.giat.mage.geopackage.media
import android.app.Application
import android.webkit.MimeTypeMap
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import mil.nga.geopackage.GeoPackageCache
import mil.nga.geopackage.GeoPackageFactory
import mil.nga.geopackage.extension.related.RelatedTablesExtension
import java.io.File
import javax.inject.Inject
enum class GeoPackageMediaType {
IMAGE,
VIDEO,
AUDIO,
OTHER;
companion object {
fun fromContentType(contentType: String): GeoPackageMediaType {
return when {
contentType.contains("image/") -> IMAGE
contentType.contains("video/") -> VIDEO
contentType.contains("audio/") -> AUDIO
else -> OTHER
}
}
}
}
data class GeoPackageMedia(val path: String, val type: GeoPackageMediaType)
@HiltViewModel
open class GeoPackageMediaViewModel @Inject constructor(
val application: Application
) : ViewModel() {
private var file: File? = null
private val geoPackageCache = GeoPackageCache(GeoPackageFactory.getManager(application))
private val _geoPackageMedia = MutableLiveData<GeoPackageMedia>()
val geoPackageMedia: LiveData<GeoPackageMedia> = _geoPackageMedia
override fun onCleared() {
super.onCleared()
file?.delete()
file = null
}
fun setMedia(geoPackageName: String, mediaTable: String, mediaId: Long) {
viewModelScope.launch(Dispatchers.IO) {
getMedia(geoPackageName, mediaTable, mediaId)?.let { media ->
_geoPackageMedia.postValue(media)
}
}
}
private fun getMedia(
geoPackageName: String,
mediaTable: String,
mediaId: Long
): GeoPackageMedia? {
val geoPackage = geoPackageCache.getOrOpen(geoPackageName)
val relatedTablesExtension = RelatedTablesExtension(geoPackage)
val mediaDao = relatedTablesExtension.getMediaDao(mediaTable)
val mediaRow = mediaDao.getRow(mediaDao.queryForIdRow(mediaId))
return mediaRow.columns.getColumnIndex("content_type", false)?.let { index ->
val contentType = mediaRow.getValue(index).toString()
val path = saveMedia(geoPackageName, mediaTable, mediaId, mediaRow.data, contentType)
GeoPackageMedia(path, GeoPackageMediaType.fromContentType(contentType))
}
}
private fun saveMedia(
geoPackageName: String,
mediaTable: String,
mediaId: Long,
data: ByteArray,
contentType: String
): String {
val directory = File(application.cacheDir, "geopackage").apply {
mkdirs()
}
val tempFile = File.createTempFile(
"${geoPackageName}_${mediaTable}_${mediaId}",
".${MimeTypeMap.getSingleton().getExtensionFromMimeType(contentType)}",
directory
)
tempFile.writeBytes(data)
file = tempFile
return tempFile.absolutePath
}
}
| apache-2.0 | 5782b3b238ed1ac995c2b3b5341a7d57 | 29.871287 | 94 | 0.706543 | 4.834109 | false | false | false | false |
ngageoint/mage-android | mage/src/main/java/mil/nga/giat/mage/network/gson/observation/AttachmentTypeAdapter.kt | 1 | 1717 | package mil.nga.giat.mage.network.gson.observation
import com.google.gson.TypeAdapter
import com.google.gson.stream.JsonReader
import com.google.gson.stream.JsonToken
import com.google.gson.stream.JsonWriter
import mil.nga.giat.mage.network.gson.nextLongOrNull
import mil.nga.giat.mage.network.gson.nextStringOrNull
import mil.nga.giat.mage.sdk.datastore.observation.Attachment
class AttachmentTypeAdapter: TypeAdapter<Attachment>() {
override fun write(out: JsonWriter, value: Attachment) {
throw UnsupportedOperationException()
}
override fun read(reader: JsonReader): Attachment {
val attachment = Attachment()
attachment.isDirty = false
if (reader.peek() != JsonToken.BEGIN_OBJECT) {
reader.skipValue()
return attachment
}
reader.beginObject()
while(reader.hasNext()) {
when(reader.nextName()) {
"id" -> attachment.remoteId = reader.nextString()
"action" -> attachment.action = reader.nextStringOrNull()
"observationFormId" -> attachment.observationFormId = reader.nextString()
"fieldName" -> attachment.fieldName = reader.nextString()
"contentType" -> attachment.contentType = reader.nextStringOrNull()
"size" -> attachment.size = reader.nextLongOrNull()
"name" -> attachment.name = reader.nextStringOrNull()
"url" -> attachment.url = reader.nextStringOrNull()
"localPath" -> attachment.localPath = reader.nextStringOrNull()
"relativePath" -> attachment.remotePath = reader.nextStringOrNull()
else -> reader.skipValue()
}
}
reader.endObject()
return attachment
}
} | apache-2.0 | ab3439b6ad9a2f4a131cb7b37c7cab33 | 35.553191 | 85 | 0.67385 | 4.730028 | false | false | false | false |
sampsonjoliver/Firestarter | app/src/main/java/com/sampsonjoliver/firestarter/views/gallery/GalleryActivity.kt | 1 | 2416 | package com.sampsonjoliver.firestarter.views.gallery
import android.app.Activity
import android.os.Bundle
import android.support.v7.widget.GridLayoutManager
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.sampsonjoliver.firestarter.FirebaseActivity
import com.sampsonjoliver.firestarter.R
import com.sampsonjoliver.firestarter.models.Message
import com.sampsonjoliver.firestarter.views.GridSpacingItemDecoration
import kotlinx.android.synthetic.main.activity_gallery.*
import kotlinx.android.synthetic.main.item_photo_thumbnail.view.*
import java.util.*
class GalleryActivity : FirebaseActivity() {
companion object {
val EXTRA_TITLE = "EXTRA_TITLE"
val EXTRA_MESSAGES = "EXTRA_MESSAGES"
}
val messages by lazy { intent.getParcelableArrayListExtra<Message>(EXTRA_MESSAGES) }
val title by lazy { intent.getStringExtra(EXTRA_TITLE) }
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_gallery)
setSupportActionBar(toolbar)
supportActionBar?.setDisplayHomeAsUpEnabled(true)
supportActionBar?.title = title
val spacingPx = 5
val manager = GridLayoutManager(this, 4)
recycler.addItemDecoration(GridSpacingItemDecoration(4, spacingPx, true))
recycler?.layoutManager = manager
recycler?.adapter = PhotoAdapter(messages)
}
inner class PhotoAdapter(val messages: List<Message>) : RecyclerView.Adapter<RecyclerView.ViewHolder>() {
override fun onBindViewHolder(holder: RecyclerView.ViewHolder?, position: Int) {
holder?.itemView?.drawee?.setImageURI(messages[position].contentThumbUri)
holder?.itemView?.setOnClickListener {
GalleryItemFragment.newInstance(ArrayList(messages), position).show(fragmentManager, "")
}
}
override fun getItemCount(): Int = messages.size
override fun onCreateViewHolder(parent: ViewGroup?, viewType: Int): RecyclerView.ViewHolder {
val view = LayoutInflater.from(parent?.context)?.inflate(R.layout.item_photo_thumbnail, parent, false)
return PhotoThumbnailHolder(view)
}
}
inner class PhotoThumbnailHolder(itemView: View?) : RecyclerView.ViewHolder(itemView) {
}
} | apache-2.0 | 06fbb0dc8a869a204ed9d6bc2b9427ef | 37.983871 | 114 | 0.737169 | 4.95082 | false | false | false | false |
MaTriXy/PermissionsDispatcher | processor/src/main/kotlin/permissions/dispatcher/processor/impl/kotlin/WriteSettingsHelper.kt | 1 | 1179 | package permissions.dispatcher.processor.impl.kotlin
import com.squareup.kotlinpoet.ClassName
import com.squareup.kotlinpoet.FunSpec
class WriteSettingsHelper : SensitivePermissionInterface {
private val PERMISSION_UTILS = ClassName("permissions.dispatcher", "PermissionUtils")
private val SETTINGS = ClassName("android.provider", "Settings")
private val INTENT = ClassName("android.content", "Intent")
private val URI = ClassName("android.net", "Uri")
override fun addHasSelfPermissionsCondition(builder: FunSpec.Builder, activity: String, permissionField: String) {
builder.beginControlFlow("if (%T.hasSelfPermissions(%N, *%N) || %T.System.canWrite(%N))", PERMISSION_UTILS, activity, permissionField, SETTINGS, activity)
}
override fun addRequestPermissionsStatement(builder: FunSpec.Builder, targetParam: String, activityVar: String, requestCodeField: String) {
builder.addStatement("val intent = %T(%T.ACTION_MANAGE_WRITE_SETTINGS, %T.parse(\"package:\" + %N!!.getPackageName()))", INTENT, SETTINGS, URI, activityVar)
builder.addStatement("%N.startActivityForResult(intent, %N)", targetParam, requestCodeField)
}
} | apache-2.0 | 64bbe4492de3f1b5e2b7c64b2e4df1b6 | 55.190476 | 164 | 0.752332 | 4.569767 | false | false | false | false |
facebook/litho | sample/src/main/java/com/facebook/samples/litho/kotlin/mountables/SimpleImageViewWithAccessibilityExampleComponent.kt | 1 | 1556 | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.facebook.samples.litho.kotlin.mountables
import com.facebook.litho.Column
import com.facebook.litho.Component
import com.facebook.litho.ComponentScope
import com.facebook.litho.KComponent
import com.facebook.litho.Style
import com.facebook.litho.core.height
import com.facebook.litho.core.margin
import com.facebook.litho.core.padding
import com.facebook.litho.core.width
import com.facebook.litho.dp
import com.facebook.litho.kotlin.widget.Text
class SimpleImageViewWithAccessibilityExampleComponent : KComponent() {
override fun ComponentScope.render(): Component {
return Column(style = Style.padding(all = 20.dp)) {
child(
SimpleImageViewWithAccessibility(
style = Style.width(100.dp).height(100.dp).margin(all = 50.dp)))
child(
Text(
"Litho logo with a11y features rendered using a Mountable Component",
textSize = 16f.dp))
}
}
}
| apache-2.0 | 16136a7d53309978bcac9c585f8c6bfe | 34.363636 | 83 | 0.735219 | 4.041558 | false | false | false | false |
square/leakcanary | shark-cli/src/main/java/shark/SharkCliCommand.kt | 2 | 6750 | package shark
import com.github.ajalt.clikt.core.CliktCommand
import com.github.ajalt.clikt.core.CliktError
import com.github.ajalt.clikt.core.Context
import com.github.ajalt.clikt.core.UsageError
import com.github.ajalt.clikt.output.TermUi
import com.github.ajalt.clikt.parameters.groups.OptionGroup
import com.github.ajalt.clikt.parameters.groups.cooccurring
import com.github.ajalt.clikt.parameters.options.flag
import com.github.ajalt.clikt.parameters.options.option
import com.github.ajalt.clikt.parameters.options.required
import com.github.ajalt.clikt.parameters.options.versionOption
import com.github.ajalt.clikt.parameters.types.file
import shark.DumpProcessCommand.Companion.dumpHeap
import shark.SharkCliCommand.HeapDumpSource.HprofFileSource
import shark.SharkCliCommand.HeapDumpSource.ProcessSource
import shark.SharkLog.Logger
import java.io.File
import java.io.PrintWriter
import java.io.StringWriter
import java.util.Properties
import java.util.concurrent.TimeUnit.SECONDS
class SharkCliCommand : CliktCommand(
name = "shark-cli",
// This ASCII art is a remix of a shark from -David "TAZ" Baltazar- and chick from jgs.
help = """
|Version: $versionName
|
|```
|$S ^`. .=""=.
|$S^_ \ \ / _ _ \
|$S\ \ { \ | d b |
|$S{ \ / `~~~--__ \ /\ /
|$S{ \___----~~' `~~-_/'-=\/=-'\,
|$S \ /// a `~. \ \
|$S / /~~~~-, ,__. , /// __,,,,) \ |
|$S \/ \/ `~~~; ,---~~-_`/ \ / \/
|$S / / '. .'
|$S '._.' _|`~~`|_
|$S /|\ /|\
|```
""".trimMargin()
) {
private class ProcessOptions : OptionGroup() {
val processName by option(
"--process", "-p",
help = "Full or partial name of a process, e.g. \"example\" would match \"com.example.app\""
).required()
val device by option(
"-d", "--device", metavar = "ID", help = "device/emulator id"
)
}
private val processOptions by ProcessOptions().cooccurring()
private val obfuscationMappingPath by option(
"-m", "--obfuscation-mapping", help = "path to obfuscation mapping file"
).file()
private val verbose by option(
help = "provide additional details as to what shark-cli is doing"
).flag("--no-verbose")
private val heapDumpFile by option("--hprof", "-h", help = "path to a .hprof file").file(
exists = true,
folderOkay = false,
readable = true
)
init {
versionOption(versionName)
}
class CommandParams(
val source: HeapDumpSource,
val obfuscationMappingPath: File?
)
sealed class HeapDumpSource {
class HprofFileSource(val file: File) : HeapDumpSource()
class ProcessSource(
val processName: String,
val deviceId: String?
) : HeapDumpSource()
}
override fun run() {
if (verbose) {
setupVerboseLogger()
}
if (processOptions != null && heapDumpFile != null) {
throw UsageError("Option --process cannot be used with --hprof")
} else if (processOptions != null) {
context.sharkCliParams = CommandParams(
source = ProcessSource(processOptions!!.processName, processOptions!!.device),
obfuscationMappingPath = obfuscationMappingPath
)
} else if (heapDumpFile != null) {
context.sharkCliParams = CommandParams(
source = HprofFileSource(heapDumpFile!!),
obfuscationMappingPath = obfuscationMappingPath
)
} else {
throw UsageError("Must provide one of --process, --hprof")
}
}
private fun setupVerboseLogger() {
class CLILogger : Logger {
override fun d(message: String) {
echo(message)
}
override fun d(
throwable: Throwable,
message: String
) {
d("$message\n${getStackTraceString(throwable)}")
}
private fun getStackTraceString(throwable: Throwable): String {
val stringWriter = StringWriter()
val printWriter = PrintWriter(stringWriter, false)
throwable.printStackTrace(printWriter)
printWriter.flush()
return stringWriter.toString()
}
}
SharkLog.logger = CLILogger()
}
companion object {
/** Zero width space */
private const val S = '\u200b'
var Context.sharkCliParams: CommandParams
get() {
var ctx: Context? = this
while (ctx != null) {
if (ctx.obj is CommandParams) return ctx.obj as CommandParams
ctx = ctx.parent
}
throw IllegalStateException("CommandParams not found in Context.obj")
}
set(value) {
obj = value
}
fun CliktCommand.retrieveHeapDumpFile(params: CommandParams): File {
return when (val source = params.source) {
is HprofFileSource -> source.file
is ProcessSource -> dumpHeap(source.processName, source.deviceId)
}
}
fun CliktCommand.echoNewline() {
echo("")
}
/**
* Copy of [CliktCommand.echo] to make it publicly visible and therefore accessible
* from [CliktCommand] extension functions
*/
fun CliktCommand.echo(
message: Any?,
trailingNewline: Boolean = true,
err: Boolean = false,
lineSeparator: String = context.console.lineSeparator
) {
TermUi.echo(message, trailingNewline, err, context.console, lineSeparator)
}
fun runCommand(
directory: File,
vararg arguments: String
): String {
val process = ProcessBuilder(*arguments)
.directory(directory)
.start()
.also { it.waitFor(10, SECONDS) }
// See https://github.com/square/leakcanary/issues/1711
// On Windows, the process doesn't always exit; calling to readText() makes it finish, so
// we're reading the output before checking for the exit value
val output = process.inputStream.bufferedReader().readText()
if (process.exitValue() != 0) {
val command = arguments.joinToString(" ")
val errorOutput = process.errorStream.bufferedReader()
.readText()
throw CliktError(
"Failed command: '$command', error output:\n---\n$errorOutput---"
)
}
return output
}
private val versionName = run {
val properties = Properties()
properties.load(
SharkCliCommand::class.java.getResourceAsStream("/version.properties")
?: throw IllegalStateException("version.properties missing")
)
properties.getProperty("version_name") ?: throw IllegalStateException(
"version_name property missing"
)
}
}
} | apache-2.0 | 0ec49ae7bf4a7ac4e8d60eadc23f7052 | 30.546729 | 98 | 0.612 | 4.326923 | false | false | false | false |
jdinkla/groovy-java-ray-tracer | src/main/kotlin/net/dinkla/raytracer/lights/AreaLight.kt | 1 | 2515 | package net.dinkla.raytracer.lights
import net.dinkla.raytracer.colors.Color
import net.dinkla.raytracer.hits.Shade
import net.dinkla.raytracer.materials.IMaterial
import net.dinkla.raytracer.math.Normal
import net.dinkla.raytracer.math.Point3D
import net.dinkla.raytracer.math.Ray
import net.dinkla.raytracer.math.Vector3D
import net.dinkla.raytracer.worlds.World
import java.util.*
class AreaLight : Light(), ILightSource {
var `object`: ILightSource? = null
// Emissive Material TODO: Warum nicht Emissive?
var material: IMaterial? = null
var numSamples: Int = 0
inner class Sample {
var samplePoint: Point3D? = null
var lightNormal: Normal? = null
var wi: Vector3D? = null
val nDotD: Double
get() = (-lightNormal!!) dot (wi!!)
}
init {
numSamples = 4
}
fun L(world: World, sr: Shade, sample: Sample): Color {
return if (sample.nDotD > 0) {
sr.material?.getLe(sr) ?: world.backgroundColor
} else {
Color.BLACK
}
}
fun inShadow(world: World, ray: Ray, sr: Shade, sample: Sample): Boolean {
val d = sample.samplePoint!!.minus(ray.origin).dot(ray.direction)
return world.inShadow(ray, sr, d)
}
fun G(sr: Shade, sample: Sample): Double {
val nDotD = sample.nDotD
val d2 = sample.samplePoint!!.sqrDistance(sr.hitPoint)
return nDotD / d2
}
override fun pdf(sr: Shade): Double {
return `object`!!.pdf(sr)
}
fun getSample(sr: Shade): Sample {
val sample = Sample()
sample.samplePoint = `object`!!.sample()
sample.lightNormal = `object`!!.getNormal(sample.samplePoint!!)
sample.wi = sample.samplePoint!!.minus(sr.hitPoint).normalize()
return sample
}
fun getSamples(sr: Shade): List<Sample> {
val result = ArrayList<Sample>()
for (i in 0 until numSamples) {
result.add(getSample(sr))
}
return result
}
override fun sample(): Point3D {
throw RuntimeException("NLU")
}
override fun getNormal(p: Point3D): Normal {
throw RuntimeException("NLU")
}
override fun L(world: World, sr: Shade): Color {
throw RuntimeException("NLU")
}
override fun getDirection(sr: Shade): Vector3D {
throw RuntimeException("NLU")
}
override fun inShadow(world: World, ray: Ray, sr: Shade): Boolean {
throw RuntimeException("NLU")
}
}
| apache-2.0 | 967f3335c9dc3aaf18335e21ac7ee1f1 | 25.473684 | 78 | 0.621074 | 3.948195 | false | false | false | false |
Jonatino/Xena | src/main/kotlin/org/xena/cs/Weapons.kt | 1 | 2193 | /*
* Copyright 2016 Jonathan Beaudoin
*
* 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.xena.cs
/**
* Created by Jonathan on 7/24/2016.
*/
enum class Weapons(val id: Int, val skin: Int = -1, val customSkin: Boolean = (skin != -1)) {
DESERT_EAGLE(1, CRIMSON_WEB),
FIVE_SEVEN(3, MONKEY_BUSINESS),
GLOCK(4, FADE),
CZ75A(63, CRIMSON_WEB),
DUAL_BERRETA(2, URBAN_SHOCK),
P2000(32, IMPERIAL_DRAGON),
P250(36, ASIIMOV_2),
R8_REVOLVER(6, REBOOT),
TEC9(30, AVALANCHE),
USP_SILENCER(61, KILL_CONFIRMED),
AK47(7, FRONTSIDE_MISTY),
AUG(8, AKIHABARA_ACCEPT),
AWP(9, DRAGON_LORE),
FAMAS(10, AFTERIMAGE),
M4A1_SILENCER(60, MECHA_INDUSTRIES),
M4A4(16, HOWL),
SSG08(40, DETOUR),
PP_BIZON(26, JUDGEMENT_OF_ANUBIS),
P90(19, DEATH_BY_KITTY),
UMP45(24, PRIMAL_SABER),
G3SG1(11),
GALIL(13),
M249(14),
MAC10(17),
XM1014(25),
MAG7(27),
NEGEV(28),
SAWED_OFF(29),
ZEUS_X27(31),
MP7(33),
MP9(34),
NOVA(35),
SCAR20(38),
SG556(39),
KNIFE(42),
FLASH_GRENADE(43),
EXPLOSIVE_GRENADE(44),
SMOKE_GRENADE(45),
MOLOTOV(46),
DECOY_GRENADE(47),
INCENDIARY_GRENADE(48),
C4(49),
KNIFE_T(59, MARBLE_FADE),
KNIFE_CT(41, MARBLE_FADE),
KNIFE_BAYONET(500),
KNIFE_FLIP(505),
KNIFE_GUT(506),
KNIFE_KARAMBIT(507, MARBLE_FADE),
KNIFE_M9_BAYONET(508, MARBLE_FADE),
KNIFE_TACTICAL(509),
KNIFE_TALCHION(512),
KNIFE_BOWIE(514),
KNIFE_BUTTERFLY(515),
KNIFE_PUSH(516),
FISTS(69),
MEDISHOT(57),
TABLET(72),
DIVERSION_DEVICE(82),
FIRE_BOMB(81),
CHARGE(70),
HAMMER(76);
companion object {
private val cachedValues = values()
@JvmStatic
fun byID(id: Int) = cachedValues.firstOrNull { it.id == id }
}
} | apache-2.0 | 7c5c91d8b3d705110c3a01cdd95f88c2 | 20.94 | 93 | 0.673507 | 2.439377 | false | false | false | false |
Caellian/Math | src/main/kotlin/hr/caellian/math/internal/Inverse.kt | 1 | 4565 | package hr.caellian.math.internal
/**
* You don't need to interact with this class in most cases as it's handled by Matrix
* classes automatically.
*
* This class is based on Apache Math LUDecomposition class but is optimised to work
* better with this library as it doesn't calculate data this library doesn't use.
*
* @since 2.0.0
* @author Caellian
*/
object Inverse {
/**
* Java implementation of Doolittle LUP matrix decomposition algorithm.
*
* @param lu input matrix which will turn into LU data matrix.
* @param singularityThreshold singularity threshold. This should be a very low number.
* @return Pivot decomposition data.
*/
@JvmStatic
fun doolittleLUP(lu: Array<Array<Double>>, singularityThreshold: Double): Array<Int> {
if (lu.size != lu[0].size) {
throw IllegalArgumentException("LU decomposition of non-square matrices not supported!")
}
val n = lu.size
// Pivot
val p = Array(n) { it }
// Iterate over columns
for (col in 0 until n) {
// Upper matrix construction
for (row in 0 until col) {
val luRow = lu[row]
var sum = luRow[col]
for (i in 0 until row) {
sum -= luRow[i] * lu[i][col]
}
luRow[col] = sum
}
// Lower matrix construction
var max = col // Permutation row
var largest = 0.0
for (row in col until n) {
val luRow = lu[row]
var sum = luRow[col]
for (i in 0 until col) {
sum -= luRow[i] * lu[i][col]
}
luRow[col] = sum
// Maintain best permutation choice
if (Math.abs(sum) > largest) {
largest = Math.abs(sum)
max = row
}
}
// Singularity check
if (Math.abs(lu[max][col]) < singularityThreshold) {
throw IllegalArgumentException("LUP Decomposition impossible for singular matrices!")
}
// Pivot if necessary
if (max != col) {
val luMax = lu[max]
val luCol = lu[col]
var tmp: Double
for (i in 0 until n) {
tmp = luMax[i]
luMax[i] = luCol[i]
luCol[i] = tmp
}
val temp = p[max]
p[max] = p[col]
p[col] = temp
}
// Divide the lower elements by the "winning" diagonal elt.
val luDiagonal = lu[col][col]
for (row in col + 1 until n) {
lu[row][col] /= luDiagonal
}
}
return p
}
/**
* Calculates inverse matrix of input matrix. Unwrapped matrix format is used to
* increase performance.
*
* @param lu input matrix which will turn into LU data matrix.
* @param singularityThreshold singularity threshold. This should be a very low number.
* @return inverse matrix of given matrix.
*/
@JvmStatic
fun inverseMatrix(lu: Array<Array<Double>>, singularityThreshold: Double): Array<Array<Double>> {
// Decomposition pivot
val p = doolittleLUP(lu, singularityThreshold)
// Size of decomposed matrix
val n = lu.size
val b = Array(n) { _ -> Array(n) { 0.0 } }
for (row in 0 until n) {
val bRow = b[row]
val pRow = p[row]
for (col in 0 until n) {
bRow[col] = (if (pRow == col) 1 else 0).toDouble()
}
}
// Solve LY = b
for (col in 0 until n) {
val bpCol = b[col]
for (i in col + 1 until n) {
val bpI = b[i]
val luICol = lu[i][col]
for (j in 0 until n) {
bpI[j] -= bpCol[j] * luICol
}
}
}
// Solve UX = Y
for (col in n - 1 downTo 0) {
val bpCol = b[col]
val luDiag = lu[col][col]
for (j in 0 until n) {
bpCol[j] /= luDiag
}
for (i in 0 until col) {
val bpI = b[i]
val luICol = lu[i][col]
for (j in 0 until n) {
bpI[j] -= bpCol[j] * luICol
}
}
}
return b
}
}
| mit | 0dfda398d750ce94a8bf8d29d0a1edae | 29.231788 | 101 | 0.47448 | 4.29445 | false | false | false | false |
angryziber/picasa-gallery | src/views/photo.kt | 1 | 1325 | package views
import integration.Profile
import photos.Album
import photos.Photo
//language=HTML
fun photo(photo: Photo, album: Album, profile: Profile, redirectUrl: String?) = """
<!DOCTYPE html>
<html lang="en">
<head>
<title>${+album.title} - ${+photo.description} by ${+profile.name}</title>
<meta name="viewport" content="width=device-width">
<meta name="medium" content="image">
<meta property="og:title" content="${+(photo.description ?: album.title)} by ${+profile.name}">
<meta property="og:image" content="${+photo.thumbUrlLarge}">
<link rel="image_src" href="${+photo.thumbUrlLarge}">
<style>
html, body { background: black; color: gray; font-family: sans-serif }
a { color: white }
img { padding: 1em 0; max-height: 90vh; max-width: 95vw; cursor: pointer }
</style>
</head>
<body>
<div itemscope itemtype="http://schema.org/Photograph">
<meta itemprop="datePublished" content="${photo.date}">
<a href="${album.url}">${+album.title} by <span itemprop="author">${+profile.name}</span></a>
<span itemprop="description">${+photo.description}</span>
<div>
<img itemprop="image" src="${photo.fullHdUrl}" alt="${+(photo.description ?: album.title)}">
</div>
</div>
${redirectUrl / """<script>location.href = '$redirectUrl'</script>""" }}
</body>
</html>
"""
| gpl-3.0 | b464edd4698fa9445167fbc03f8a15cb | 35.805556 | 98 | 0.655849 | 3.29602 | false | false | false | false |
artfable/telegram-api-java | src/test/kotlin/com/artfable/telegram/api/LongPollingTelegramBotTest.kt | 1 | 3381 | package com.artfable.telegram.api
import com.artfable.telegram.api.request.GetUpdatesRequest
import com.artfable.telegram.api.service.TelegramSender
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.assertThrows
import org.junit.jupiter.api.extension.ExtendWith
import org.mockito.ArgumentMatchers.any
import org.mockito.BDDMockito.given
import org.mockito.Mock
import org.mockito.Mockito.never
import org.mockito.Mockito.verify
import org.mockito.junit.jupiter.MockitoExtension
import java.lang.reflect.InvocationTargetException
import java.util.concurrent.Executor
import kotlin.reflect.full.declaredMemberFunctions
import kotlin.reflect.jvm.isAccessible
/**
* @author aveselov
* @since 08/08/2020
*/
@ExtendWith(MockitoExtension::class)
internal class LongPollingTelegramBotTest {
@Mock
private lateinit var taskExecutor: Executor
@Mock
private lateinit var telegramSender: TelegramSender
@Mock
private lateinit var behaviour: Behaviour
@Mock
private lateinit var behaviour2: Behaviour
@Test
fun subscribeToUpdates() {
val longPollingTelegramBot = createBot()
val updates = listOf(Update(1L))
given(telegramSender.executeMethod<List<Update>>(GetUpdatesRequest(timeout = 100))).willReturn(updates)
callSubscribeToUpdates(longPollingTelegramBot)
verify(behaviour).parse(updates)
verify(behaviour2).parse(updates)
verify(taskExecutor).execute(any())
}
@Test
fun subscribeToUpdates_skipFailed() {
val longPollingTelegramBot = createBot()
val updates = listOf(Update(1L))
given(telegramSender.executeMethod<List<Update>>(GetUpdatesRequest(timeout = 100))).willReturn(updates)
given(behaviour.parse(updates)).willThrow(IllegalArgumentException::class.java)
callSubscribeToUpdates(longPollingTelegramBot)
verify(behaviour2).parse(updates)
verify(taskExecutor).execute(any())
}
@Test
fun subscribeToUpdates_doNotSkipFailed() {
val longPollingTelegramBot = createBot(false)
val updates = listOf(Update(1L))
given(telegramSender.executeMethod<List<Update>>(GetUpdatesRequest(timeout = 100))).willReturn(updates)
given(behaviour.parse(updates)).willThrow(IllegalArgumentException::class.java)
assertThrows<IllegalArgumentException> {
callSubscribeToUpdates(longPollingTelegramBot)
}
verify(behaviour2).parse(updates)
verify(taskExecutor, never()).execute(any())
}
private fun createBot(skipFailed: Boolean? = null): LongPollingTelegramBot {
return if (skipFailed == null) {
object : LongPollingTelegramBot(taskExecutor, telegramSender, setOf(behaviour, behaviour2), setOf()) {}
} else {
object : LongPollingTelegramBot(taskExecutor, telegramSender, setOf(behaviour, behaviour2), setOf(), skipFailed) {}
}
}
private fun callSubscribeToUpdates(bot: LongPollingTelegramBot) {
try {
LongPollingTelegramBot::class.declaredMemberFunctions.asSequence()
.filter { it.name == "subscribeToUpdates" }
.onEach { it.isAccessible = true }
.first()
.call(bot, null)
} catch (e: InvocationTargetException) {
throw e.targetException
}
}
} | mit | cc9c819e3a8e522ea0d8163c4704175f | 32.485149 | 127 | 0.709553 | 4.83 | false | false | false | false |
beyama/winter | winter/src/test/kotlin/io/jentz/winter/assertions.kt | 1 | 1346 | package io.jentz.winter
import org.opentest4j.AssertionFailedError
inline fun <T> expectValueToChange(from: T, to: T, valueProvider: () -> T, block: () -> Unit) {
val a = valueProvider()
if (a != from) fail("Expected initial value to be ${formatValue(from)} but was ${formatValue(a)}")
block()
val b = valueProvider()
if (b != to) fail("Expected change from ${formatValue(from)} to ${formatValue(to)} but was ${formatValue(b)}")
}
internal inline fun <reified S : UnboundService<*>> Component.shouldContainServiceOfType(key: TypeKey<*>) {
val service = this[key]
?: fail("Component was expected to contain service with key <$key> but doesn't")
if (service !is S) fail("Service with key <$key> was expected to be <${S::class}> but was <${service.javaClass}>.")
}
internal fun Component.shouldContainService(key: TypeKey<*>) {
if (!containsKey(key)) fail("Component was expected to contain service with key <$key> but doesn't")
}
internal fun Component.shouldNotContainService(key: TypeKey<*>) {
if (containsKey(key)) fail("Component wasn't expected to contain service with key <$key> but does.")
}
fun fail(message: String): Nothing {
throw AssertionFailedError(message)
}
@PublishedApi
internal fun formatValue(any: Any?) = when (any) {
is String -> "\"$any\""
else -> "<$any>"
} | apache-2.0 | 29b1773957dd5696d65df9d1e1fe2fe2 | 37.485714 | 119 | 0.679049 | 3.958824 | false | false | false | false |
mkAndroDev/SimpleRemoteController | app/src/main/java/com/krawczyk/maciej/simpleremotecontroller/android/fragments/AdjustableOnOffFragment.kt | 1 | 2385 | package com.krawczyk.maciej.simpleremotecontroller.android.fragments
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.krawczyk.maciej.simpleremotecontroller.R
import com.krawczyk.maciej.simpleremotecontroller.data.model.Weather
import com.krawczyk.maciej.simpleremotecontroller.data.model.WeatherModel
import com.krawczyk.maciej.simpleremotecontroller.domain.mappers.WeatherMapper
import kotlinx.android.synthetic.main.fragment_adjustable_on_off.*
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
class AdjustableOnOffFragment : BaseFragment() {
private val weather = Weather()
override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?,
savedInstanceState: Bundle?): View? {
return inflater!!.inflate(R.layout.fragment_adjustable_on_off, container, false)
}
override fun onViewCreated(view: View?, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
setupViews()
}
private fun setupViews() {
val getSetWeather = weatherService.setWeather
getSetWeather.enqueue(getCallback())
btn_set.setOnClickListener({
weather.temperature = et_furnace_when.text.toString().toDouble()
weather.humidity = et_airing_when.text.toString().toDouble()
val setWeather = weatherService.setTemperatureAndAiring(WeatherMapper.getWeatherModel(weather))
setWeather.enqueue(getCallback())
})
}
private fun getCallback(): Callback<WeatherModel> {
return object : Callback<WeatherModel> {
override fun onResponse(call: Call<WeatherModel>, response: Response<WeatherModel>) {
if (response.isSuccessful && response.body() != null) {
et_furnace_when.setText(response.body()!!.temperature.toString())
et_airing_when.setText(response.body()!!.humidity.toString())
}
}
override fun onFailure(call: Call<WeatherModel>, t: Throwable) {
Log.d("Weather Response: ", t.message)
}
}
}
companion object {
fun newInstance(): AdjustableOnOffFragment {
return AdjustableOnOffFragment()
}
}
}
| apache-2.0 | 095bd89e8b9eecf33842064134760c83 | 34.597015 | 107 | 0.685115 | 4.857434 | false | false | false | false |
Jonatino/Vision | src/main/kotlin/org/anglur/vision/net/Decoder.kt | 1 | 2302 | /*
* Vision - free remote desktop software built with Kotlin
* Copyright (C) 2016 Jonathan Beaudoin
*
* 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 org.anglur.vision.net
import io.netty.channel.Channel
import io.netty.channel.ChannelHandlerContext
import io.netty.channel.socket.DatagramPacket
import io.netty.handler.codec.MessageToMessageDecoder
import org.anglur.vision.net.packet.incoming
import org.anglur.vision.util.extensions.readString
class Decoder : MessageToMessageDecoder<DatagramPacket>() {
override fun decode(ctx: ChannelHandlerContext, msg: DatagramPacket, out: MutableList<Any>) {
val buff = msg.content()
if (buff.readableBytes() > 0) {
val packetId = buff.readUnsignedByte().toInt()
println("Packet $packetId")
//If secret has not been set, read the id instead. This should only happen during handshake (packet 0)
val pos = buff.readerIndex()
val session = Sessions[buff.readLong()] ?: Sessions[buff.readerIndex(pos).readString()]
if (!ctx.channel().hasAttr(SESSION) && packetId != 0) {
//If the key hasn't been set, than they are trying to fake a packet
ctx.channel().close()
return
} else ctx.channel().attr(SESSION).set(session)
incoming[packetId]!!(PacketPayload(buff, ctx, session))
}
}
fun session(c: Channel): RemoteSession? = c.attr(SESSION).get()
override fun channelActive(ctx: ChannelHandlerContext) {
session(ctx.channel())?.connect()
}
override fun channelUnregistered(ctx: ChannelHandlerContext) {
session(ctx.channel())?.disconnect()
}
override fun exceptionCaught(ctx: ChannelHandlerContext, cause: Throwable) = TODO()
} | gpl-3.0 | f492f2244d35233d76e9978f435ea00d | 35.555556 | 105 | 0.721546 | 3.989601 | false | false | false | false |
alygin/intellij-rust | src/main/kotlin/org/rust/lang/core/completion/LookupElements.kt | 1 | 5478 | /*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.lang.core.completion
import com.intellij.codeInsight.AutoPopupController
import com.intellij.codeInsight.completion.InsertionContext
import com.intellij.codeInsight.completion.PrioritizedLookupElement
import com.intellij.codeInsight.lookup.LookupElement
import com.intellij.codeInsight.lookup.LookupElementBuilder
import com.intellij.openapi.editor.EditorModificationUtil
import org.rust.ide.icons.RsIcons
import org.rust.lang.core.psi.*
import org.rust.lang.core.psi.ext.*
import org.rust.lang.core.types.ty.TyUnknown
import org.rust.lang.core.types.type
const val KEYWORD_PRIORITY = 10.0
fun createLookupElement(element: RsCompositeElement, scopeName: String): LookupElement {
val base = LookupElementBuilder.create(element, scopeName)
.withIcon(if (element is RsFile) RsIcons.MODULE else element.getIcon(0))
return when (element) {
is RsMod -> if (scopeName == "self" || scopeName == "super") {
base.withTailText("::")
.withInsertHandler({ ctx, _ ->
val offset = ctx.editor.caretModel.offset
if (ctx.file.findElementAt(offset)?.parentOfType<RsUseGlobList>() == null) {
ctx.addSuffix("::")
}
})
} else {
base
}
is RsConstant -> base.withTypeText(element.typeReference?.text)
is RsFieldDecl -> base.withTypeText(element.typeReference?.text)
is RsFunction -> base
.withTypeText(element.retType?.typeReference?.text ?: "()")
.withTailText(element.valueParameterList?.text?.replace("\\s+".toRegex(), " ") ?: "()")
.appendTailText(element.extraTailText, true)
.withInsertHandler handler@ { context: InsertionContext, _: LookupElement ->
if (context.isInUseBlock) return@handler
if (!context.alreadyHasCallParens) {
context.document.insertString(context.selectionEndOffset, "()")
}
EditorModificationUtil.moveCaretRelatively(context.editor, if (element.valueParameters.isEmpty()) 2 else 1)
if (!element.valueParameters.isEmpty()) {
AutoPopupController.getInstance(element.project)?.autoPopupParameterInfo(context.editor, element)
}
}
is RsStructItem -> base
.withTailText(when {
element.blockFields != null -> " { ... }"
element.tupleFields != null -> element.tupleFields!!.text
else -> ""
})
is RsEnumVariant -> base
.withTypeText(element.parentOfType<RsEnumItem>()?.name ?: "")
.withTailText(when {
element.blockFields != null -> " { ... }"
element.tupleFields != null ->
element.tupleFields!!.tupleFieldDeclList
.map { it.typeReference.text }
.joinToString(prefix = "(", postfix = ")")
else -> ""
})
.withInsertHandler handler@ { context, _ ->
if (context.isInUseBlock) return@handler
val (text, shift) = when {
element.tupleFields != null -> Pair("()", 1)
element.blockFields != null -> Pair(" {}", 2)
else -> return@handler
}
if (!(context.alreadyHasPatternParens || context.alreadyHasCallParens)) {
context.document.insertString(context.selectionEndOffset, text)
}
EditorModificationUtil.moveCaretRelatively(context.editor, shift)
}
is RsPatBinding -> base
.withTypeText(element.type.let {
when (it) {
is TyUnknown -> ""
else -> it.toString()
}
})
is RsMacroBinding -> base.withTypeText(element.fragmentSpecifier)
is RsMacroDefinition -> {
val parens = when (element.name) {
"vec" -> "[]"
else -> "()"
}
base
.withTailText("!")
.withInsertHandler { context: InsertionContext, _: LookupElement ->
context.document.insertString(context.selectionEndOffset, "!$parens")
EditorModificationUtil.moveCaretRelatively(context.editor, 2)
}
}
else -> base
}
}
fun LookupElementBuilder.withPriority(priority: Double): LookupElement =
PrioritizedLookupElement.withPriority(this, priority)
private val InsertionContext.isInUseBlock: Boolean
get() = file.findElementAt(startOffset - 1)!!.parentOfType<RsUseItem>() != null
private val InsertionContext.alreadyHasCallParens: Boolean get() {
val parent = file.findElementAt(startOffset)!!.parentOfType<RsExpr>()
return (parent is RsDotExpr && parent.methodCall != null) || parent?.parent is RsCallExpr
}
private val InsertionContext.alreadyHasPatternParens: Boolean get() {
val pat = file.findElementAt(startOffset)!!.parentOfType<RsPatEnum>()
?: return false
return pat.path.textRange.contains(startOffset)
}
private val RsFunction.extraTailText: String
get() = parentOfType<RsImplItem>()?.traitRef?.text?.let { " of $it" } ?: ""
| mit | 529a54c71e1d067e0afacaabb3e081fa | 40.816794 | 123 | 0.596386 | 5.277457 | false | false | false | false |
Aptoide/aptoide-client-v8 | app/src/main/java/cm/aptoide/pt/download/view/outofspace/InstalledAppCardModel.kt | 1 | 1518 | package cm.aptoide.pt.download.view.outofspace
import android.widget.ImageView
import android.widget.TextView
import cm.aptoide.pt.R
import cm.aptoide.pt.networking.image.ImageLoader
import cm.aptoide.pt.utils.AptoideUtils
import com.airbnb.epoxy.EpoxyAttribute
import com.airbnb.epoxy.EpoxyModelClass
import com.airbnb.epoxy.EpoxyModelWithHolder
import com.fa.epoxysample.bundles.models.base.BaseViewHolder
import rx.subjects.PublishSubject
@EpoxyModelClass(layout = R.layout.out_of_space_installed_app_card)
abstract class InstalledAppCardModel : EpoxyModelWithHolder<InstalledAppCardModel.CardHolder>() {
@EpoxyAttribute
var application: InstalledApp? = null
@EpoxyAttribute(EpoxyAttribute.Option.DoNotHash)
var eventSubject: PublishSubject<String>? = null
override fun bind(holder: CardHolder) {
application?.let { app ->
holder.name.text = app.appName
ImageLoader.with(holder.itemView.context).load(app.icon, holder.appIcon)
holder.appSize.text = AptoideUtils.StringU.formatBytes(app.size, false)
handleUninstallClick(holder, app)
}
}
private fun handleUninstallClick(holder: CardHolder, app: InstalledApp) {
holder.uninstallButton.setOnClickListener { eventSubject?.onNext(app.packageName) }
}
class CardHolder : BaseViewHolder() {
val appIcon by bind<ImageView>(R.id.app_icon)
val name by bind<TextView>(R.id.app_name)
val appSize by bind<TextView>(R.id.app_size)
val uninstallButton by bind<TextView>(R.id.uninstall_button)
}
} | gpl-3.0 | 07d93899a95f9d790be41364114d45c6 | 32.021739 | 97 | 0.776021 | 3.942857 | false | false | false | false |
strooooke/quickfit | app/src/main/java/com/lambdasoup/quickfit/ui/FitFailureResolutionActivity.kt | 1 | 4187 | /*
* Copyright 2016 Juliane Lehmann <[email protected]>
*
* 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.lambdasoup.quickfit.ui
import android.content.ActivityNotFoundException
import android.content.Intent
import android.os.Bundle
import com.google.android.gms.auth.api.signin.GoogleSignIn
import com.google.android.gms.auth.api.signin.GoogleSignInAccount
import com.lambdasoup.quickfit.Constants.FITNESS_API_OPTIONS
import com.lambdasoup.quickfit.FitActivityService.Companion.enqueueSyncSession
import com.lambdasoup.quickfit.persist.FitApiFailureResolution
import com.lambdasoup.quickfit.persist.FitApiFailureResolution.registerAsCurrentForeground
import com.lambdasoup.quickfit.persist.FitApiFailureResolution.unregisterAsCurrentForeground
import com.lambdasoup.quickfit.persist.FitApiFailureResolver
import timber.log.Timber
/**
* Base class for activities that bind to [FitApiFailureResolution]; which allows to interrupt the
* user with Fit Api connection failure resolution while this activity is in the foreground. Can also be started with an
* intent with a failure connection result as extra to start the resolution process.
*/
abstract class FitFailureResolutionActivity : DialogActivity(), FitApiFailureResolver {
private var failureResolutionInProgress = false
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
if (savedInstanceState != null) {
failureResolutionInProgress = savedInstanceState.getBoolean(KEY_FAILURE_RESOLUTION_IN_PROGRESS)
}
}
override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
outState.putBoolean(KEY_FAILURE_RESOLUTION_IN_PROGRESS, failureResolutionInProgress)
}
override fun onStart() {
super.onStart()
registerAsCurrentForeground(this)
}
override fun onStop() {
super.onStop()
unregisterAsCurrentForeground(this)
}
override fun onResume() {
super.onResume()
// if started from notification (failure occurred while no activity was bound to FitApiFailureResolution)
val account: GoogleSignInAccount? = intent.getParcelableExtra(EXTRA_PLAY_API_SIGNIN_ACCOUNT)
if (account != null) {
requestFitPermissions(account)
}
}
override fun requestFitPermissions(account: GoogleSignInAccount) {
if (failureResolutionInProgress) {
// nothing to do
return
}
failureResolutionInProgress = true
try {
GoogleSignIn.requestPermissions(
this,
REQUEST_FAILURE_RESOLUTION,
account,
FITNESS_API_OPTIONS
)
} catch (e: ActivityNotFoundException) {
Timber.e(e, "Exception while starting resolution activity")
}
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
if (requestCode == REQUEST_FAILURE_RESOLUTION) {
failureResolutionInProgress = false
intent.removeExtra(EXTRA_PLAY_API_SIGNIN_ACCOUNT)
if (resultCode == RESULT_OK) {
enqueueSyncSession(applicationContext)
}
} else {
super.onActivityResult(requestCode, resultCode, data)
}
}
companion object {
const val EXTRA_PLAY_API_SIGNIN_ACCOUNT = "com.lambdasoup.quickfit.play_api_connect_result"
private const val REQUEST_FAILURE_RESOLUTION = 0
private const val KEY_FAILURE_RESOLUTION_IN_PROGRESS = "com.lambdasoup.quickfit.failure_resolution_in_progress"
}
}
| apache-2.0 | 3e39bdfc77bd0d9a5e39bac0e1eb0cc4 | 38.5 | 120 | 0.710533 | 5.014371 | false | false | false | false |
amardeshbd/android-daily-headlines | mobile/src/main/java/info/hossainkhan/dailynewsheadlines/HeadlinesBrowseActivity.kt | 1 | 8818 | /*
* MIT License
*
* Copyright (c) 2016 Hossain Khan
*
* 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 info.hossainkhan.dailynewsheadlines
import android.os.Bundle
import android.support.design.widget.NavigationView
import android.support.v4.view.GravityCompat
import android.support.v7.app.ActionBarDrawerToggle
import android.support.v7.app.AppCompatActivity
import android.view.Menu
import android.view.MenuItem
import android.view.View
import android.widget.Toast
import info.hossainkhan.android.core.headlines.HeadlinesContract
import info.hossainkhan.android.core.headlines.HeadlinesPresenter
import info.hossainkhan.android.core.model.NewsHeadlineItem
import info.hossainkhan.android.core.model.NewsCategoryHeadlines
import info.hossainkhan.android.core.model.NewsHeadlines
import info.hossainkhan.android.core.model.ScreenType
import info.hossainkhan.android.core.newsprovider.NewsProviderManager
import kotlinx.android.synthetic.main.activity_headlines_nav_and_content.*
import kotlinx.android.synthetic.main.headlines_item_viewpager_container.*
import kotlinx.android.synthetic.main.headlines_main_content_container.*
import kotlinx.android.synthetic.main.nav_header_main.*
import timber.log.Timber
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale
class HeadlinesBrowseActivity
: AppCompatActivity(),
NavigationView.OnNavigationItemSelectedListener,
HeadlinesContract.View {
/**
* The [android.support.v4.view.PagerAdapter] that will provide
* fragments for each of the sections. We use a
* {@link FragmentPagerAdapter} derivative, which will keep every
* loaded fragment in memory. If this becomes too memory intensive, it
* may be best to switch to a
* [android.support.v13.app.FragmentStatePagerAdapter].
*/
private var headlinesPagerAdapter: HeadlinesPagerAdapter? = null
private lateinit var headlinesPresenter: HeadlinesPresenter
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_headlines_nav_and_content)
setSupportActionBar(toolbar)
supportActionBar?.title = getString(R.string.choose_source_title)
setupNavigationDrawer()
// NOTE use DI to inject
val context = applicationContext
val newsProviderManager = NewsProviderManager(context)
headlinesPresenter = HeadlinesPresenter(context, this, newsProviderManager)
}
private fun setupNavigationDrawer() {
val toggle = ActionBarDrawerToggle(
this, drawer_layout, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close)
drawer_layout.addDrawerListener(toggle)
toggle.syncState()
nav_view.setNavigationItemSelectedListener(this)
sidebar_subtitle.text = SimpleDateFormat("EEE, d MMM yyy", Locale.getDefault()).format(Date())
}
override fun onStop() {
// NOTE - What happens when presenter is attached again.
headlinesPresenter.detachView()
super.onStop()
}
override fun onBackPressed() {
if (drawer_layout.isDrawerOpen(GravityCompat.START)) {
drawer_layout.closeDrawer(GravityCompat.START)
} else {
super.onBackPressed()
}
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
// Inflate the menu; this adds items to the action bar if it is present.
menuInflater.inflate(R.menu.menu_headlines_browse, menu)
return true
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
val isConsumed = headlinesPresenter.onMenuItemClicked(item)
return if (isConsumed) {
true
} else {
super.onOptionsItemSelected(item)
}
}
override fun onNavigationItemSelected(item: MenuItem): Boolean {
// Handle navigation view item clicks here.
when (item.itemId) {
R.id.action_add_news_source_feed -> {
// Handle the camera action
}
}
drawer_layout.closeDrawer(GravityCompat.START)
return true
}
/**
* Setups the navigation bar with all the news sources which can be selected.
*/
private fun setupNavigationDrawerAdapter(headlines: List<NewsHeadlines>) {
nav_drawer_recycler_view.adapter = NewsSourceAdapter(headlines,
this::onNewsSourceSelected)
}
/**
* Updates toolbar title with currently selected content
*/
private fun updateToolbarTitle(title: String) {
toolbar.title = title
}
fun onNewsSourceSelected(selectedRow: NewsCategoryHeadlines) {
Timber.d("onNewsSourceSelected() called with: row = [${selectedRow}]")
updateToolbarTitle(selectedRow.displayTitle ?: selectedRow.title!!)
// Create the adapter that will return a fragment for each of the three
// primary sections of the activity.
if (headlinesPagerAdapter == null) {
// Set up the ViewPager with the sections adapter.
headlinesPagerAdapter = HeadlinesPagerAdapter(fragmentManager, selectedRow.newsHeadlines!!)
news_headlines_pager_container.adapter = headlinesPagerAdapter
} else {
headlinesPagerAdapter!!.setData(selectedRow.newsHeadlines!!)
news_headlines_pager_container.setCurrentItem(0, true)
}
if (drawer_layout.isDrawerOpen(GravityCompat.START)) {
drawer_layout.closeDrawer(GravityCompat.START)
}
}
//
// HeadlinesContract.View
//
override fun showHeadlines(headlines: MutableList<NewsHeadlines>) {
Timber.d("showHeadlines() called with: categoriesHeadlines = [${headlines}]")
setupNavigationDrawerAdapter(headlines)
}
override fun showHeadlineDetailsUi(newsHeadlineItem: NewsHeadlineItem?) {
Timber.d("showHeadlineDetailsUi() called with: newsHeadlineItem = [${newsHeadlineItem}]")
// NOTE: Details view on mobile is not supported to keep it minimal.
}
override fun showAppSettingsScreen() {
Timber.d("showAppSettingsScreen() called")
Toast.makeText(this, "Feature not implemented yet.", Toast.LENGTH_SHORT).show()
}
override fun showHeadlineBackdropBackground(imageUrl: String?) {
Timber.d("showHeadlineBackdropBackground() called with: imageUrl = [${imageUrl}]")
}
override fun showDefaultBackground() {
Timber.d("showDefaultBackground() called")
}
override fun toggleLoadingIndicator(active: Boolean) {
Timber.d("toggleLoadingIndicator() called with: active = [${active}]")
if (active) {
news_headlines_loading_indicator.visibility = View.VISIBLE
} else {
news_headlines_loading_indicator.visibility = View.GONE
}
}
override fun showDataLoadingError() {
Timber.d("showDataLoadingError() called")
Toast.makeText(this, "Failed to load news.", Toast.LENGTH_LONG).show()
}
override fun showDataNotAvailable() {
Timber.d("showDataNotAvailable() called")
}
override fun showAddNewsSourceScreen() {
Timber.d("showAddNewsSourceScreen() called")
Toast.makeText(this, "Feature not implemented yet.", Toast.LENGTH_SHORT).show()
}
override fun showUiScreen(type: ScreenType) {
Timber.d("showUiScreen() called with: type = [${type}]")
Toast.makeText(this, "Feature not implemented yet.", Toast.LENGTH_SHORT).show()
}
}
| mit | 7e49839a8d20e000254ef9fe00eea4e4 | 37.008621 | 112 | 0.704808 | 4.829135 | false | false | false | false |
alashow/music-android | modules/base-android/src/main/java/tm/alashow/base/util/ThrowableExtensions.kt | 1 | 2222 | /*
* Copyright (C) 2018, Alashov Berkeli
* All rights reserved.
*/
package tm.alashow.base.util.extensions
import android.content.res.Resources
import androidx.annotation.StringRes
import com.andretietz.retroauth.AuthenticationCanceledException
import java.io.IOException
import retrofit2.HttpException
import tm.alashow.base.R
import tm.alashow.base.util.ValidationErrorException
import tm.alashow.domain.models.errors.ApiErrorException
import tm.alashow.domain.models.errors.EmptyResultException
@StringRes
fun Throwable?.localizedTitle(): Int = when (this) {
is EmptyResultException -> R.string.error_empty_title
else -> R.string.error_title
}
@StringRes
fun Throwable?.localizedMessage(): Int = when (this) {
is ApiErrorException -> localizeApiError()
is EmptyResultException -> R.string.error_empty
is HttpException -> {
when (code()) {
404 -> R.string.error_notFound
500 -> R.string.error_server
502 -> R.string.error_keyError
503 -> R.string.error_unavailable
403, 401 -> R.string.error_auth
else -> R.string.error_unknown
}
}
is AuthenticationCanceledException -> R.string.error_noAuth
is AppError -> messageRes
is RuntimeException, is IOException -> R.string.error_network
is ValidationErrorException -> error.errorRes
else -> R.string.error_unknown
}
fun ApiErrorException.localizeApiError(): Int = when (val errorRes = errorRes) {
is Int -> errorRes
else -> when (error.id) {
"unknown" -> R.string.error_unknown
else -> R.string.error_api
}
}
val localizedApiMessages = mapOf(
"test" to R.string.error_errorLogOut
)
fun String.hasLocalizeApiMessage(): Boolean = localizedApiMessages.containsKey(this)
fun String.tryToLocalizeApiMessage(resources: Resources, overrideOnFail: Boolean = true): String = when {
localizedApiMessages.containsKey(this) -> resources.getString(localizedApiMessages[this] ?: 0)
else -> if (overrideOnFail) resources.getString(R.string.error_unknown) else this
}
data class ThrowableString(val value: String) : Throwable()
data class AppError(val messageRes: Int = R.string.error_unknown) : Throwable()
| apache-2.0 | 90e15a31dd5c5d4d8198bedadaff4df4 | 32.666667 | 105 | 0.720522 | 4.062157 | false | false | false | false |
LanternPowered/LanternServer | src/main/kotlin/org/lanternpowered/server/entity/LanternItem.kt | 1 | 12355 | /*
* Lantern
*
* Copyright (c) LanternPowered <https://www.lanternpowered.org>
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* This work is licensed under the terms of the MIT License (MIT). For
* a copy, see 'LICENSE.txt' or <https://opensource.org/licenses/MIT>.
*/
package org.lanternpowered.server.entity
import org.lanternpowered.api.cause.CauseStack
import org.lanternpowered.api.cause.withFrame
import org.lanternpowered.api.data.Keys
import org.lanternpowered.api.event.EventManager
import org.lanternpowered.api.item.inventory.Carrier
import org.lanternpowered.api.item.inventory.ItemStack
import org.lanternpowered.api.item.inventory.emptyItemStackSnapshot
import org.lanternpowered.api.item.inventory.fix
import org.lanternpowered.api.item.inventory.stack.asSnapshot
import org.lanternpowered.api.item.inventory.stack.isNotEmpty
import org.lanternpowered.api.item.inventory.stack.isSimilarTo
import org.lanternpowered.api.util.duration.max
import org.lanternpowered.api.util.math.plus
import org.lanternpowered.api.util.math.times
import org.lanternpowered.api.util.optional.orNull
import org.lanternpowered.api.world.getIntersectingBlockCollisionBoxes
import org.lanternpowered.api.world.getIntersectingEntities
import org.lanternpowered.server.effect.entity.EntityEffectCollection
import org.lanternpowered.server.effect.entity.EntityEffectTypes
import org.lanternpowered.server.effect.entity.particle.item.ItemDeathParticleEffect
import org.lanternpowered.server.entity.event.CollectEntityEvent
import org.lanternpowered.server.event.LanternEventContextKeys
import org.lanternpowered.server.event.LanternEventFactory
import org.lanternpowered.server.network.entity.EntityProtocolTypes
import org.spongepowered.api.entity.Item
import org.spongepowered.api.entity.living.Living
import org.spongepowered.api.event.item.inventory.ChangeInventoryEvent.Pickup
import org.spongepowered.api.util.AABB
import org.spongepowered.api.util.Direction
import org.spongepowered.math.vector.Vector3d
import kotlin.time.Duration
import kotlin.time.seconds
class LanternItem(creationData: EntityCreationData) : LanternEntity(creationData), Item {
companion object {
val DEFAULT_EFFECT_COLLECTION = EntityEffectCollection.builder()
.add(EntityEffectTypes.DEATH, ItemDeathParticleEffect)
.build()
val BOUNDING_BOX_EXTENT = AABB(Vector3d(-0.125, 0.0, -0.125), Vector3d(0.125, 0.25, 0.125))
val DROPPED_PICKUP_DELAY = 2.seconds
}
private var timer = Duration.ZERO
init {
this.protocolType = EntityProtocolTypes.ITEM
this.boundingBoxExtent = BOUNDING_BOX_EXTENT
this.effectCollection = DEFAULT_EFFECT_COLLECTION.copy()
keyRegistry {
register(Keys.ITEM_STACK_SNAPSHOT, emptyItemStackSnapshot())
registerBounded(Keys.PICKUP_DELAY, 0.5.seconds).minimum(Duration.ZERO).coerceInBounds()
registerBounded(Keys.DESPAWN_DELAY, 300.seconds).minimum(Duration.ZERO).coerceInBounds()
register(Keys.GRAVITATIONAL_ACCELERATION, 0.04)
register(Keys.INFINITE_PICKUP_DELAY, false)
register(Keys.INFINITE_DESPAWN_DELAY, false)
}
}
override fun update(deltaTime: Duration) {
super.update(deltaTime)
var pickupDelay = this.require(Keys.PICKUP_DELAY)
var despawnDelay = this.require(Keys.DESPAWN_DELAY)
val infinitePickupDelay = this.require(Keys.INFINITE_PICKUP_DELAY)
val infiniteDespawnDelay = this.require(Keys.INFINITE_DESPAWN_DELAY)
val oldPickupDelay = pickupDelay
val oldDespawnDelay = despawnDelay
if (!infinitePickupDelay)
pickupDelay -= deltaTime
if (!infiniteDespawnDelay)
despawnDelay -= deltaTime
this.timer += deltaTime
val timer = this.timer
if (timer > 1.seconds) {
val data = combineItemStacks(pickupDelay, despawnDelay)
if (data != null) {
pickupDelay = data.pickupDelay
despawnDelay = data.despawnDelay
// Play the merge effect?
this.effectCollection.getCombinedOrEmpty(EntityEffectTypes.MERGE).play(this)
}
this.timer = Duration.ZERO
}
if (timer > 0.5.seconds && !infinitePickupDelay && pickupDelay <= Duration.ZERO)
this.tryToPickupItems()
if (pickupDelay != oldPickupDelay)
this.offer(Keys.PICKUP_DELAY, pickupDelay)
if (despawnDelay != oldDespawnDelay)
this.offer(Keys.DESPAWN_DELAY, despawnDelay)
if (despawnDelay <= Duration.ZERO) {
CauseStack.withFrame { frame ->
frame.pushCause(this)
// Throw the expire entity event
val event = LanternEventFactory.createExpireEntityEvent(
frame.currentCause, this)
EventManager.post(event)
// Remove the item, also within this context
this.remove()
}
// Play the death effect?
this.effectCollection.getCombinedOrEmpty(EntityEffectTypes.DEATH).play(this)
} else {
this.updatePhysics(deltaTime)
}
}
private fun updatePhysics(deltaTime: Duration) {
// Get the current velocity
var velocity = this.require(Keys.VELOCITY)
// Update the position based on the velocity
this.position = this.position + (velocity * deltaTime.inSeconds)
// We will check if there is a collision box under the entity
var ground = false
val thisBox = this.boundingBox.get().offset(0.0, -0.1, 0.0)
val boxes: Set<AABB> = this.world.getIntersectingBlockCollisionBoxes(thisBox)
for (box in boxes) {
val factor = box.center.sub(thisBox.center)
if (Direction.getClosest(factor).isUpright)
ground = true
}
if (!ground && this.get(Keys.IS_GRAVITY_AFFECTED).orElse(true)) {
val constant = this.get(Keys.GRAVITATIONAL_ACCELERATION).orNull()
if (constant != null) {
// Apply the gravity factor
velocity = velocity.add(0.0, -constant * deltaTime.inSeconds, 0.0)
}
}
velocity = velocity.mul(0.98, 0.98, 0.98)
if (ground)
velocity = velocity.mul(1.0, -0.5, 1.0)
// Offer the velocity back
this.offer(Keys.VELOCITY, velocity)
}
private fun tryToPickupItems() {
val entities = this.world.getIntersectingEntities(
this.boundingBox.get().expand(2.0, 0.5, 2.0)) { entity -> entity !== this && entity is Carrier }
if (entities.isEmpty())
return
val stack = this.require(Keys.ITEM_STACK_SNAPSHOT).createStack()
if (stack.isEmpty) {
this.remove()
return
}
// TODO: Call pre pickup event
for (entity in entities) {
// Ignore dead entities
if (entity is LanternLiving && entity.isDead)
continue
val inventory = (entity as Carrier).inventory.fix()
/*
if (inventory is PlayerInventory) {
// TODO: Get priority hotbar inventory
//inventory = inventory.primary.transform(InventoryTransforms.PRIORITY_HOTBAR)
}
*/
// Copy before consuming
val originalStack = stack.copy()
val peekResult = inventory.peekOffer(stack)
var event: Pickup
CauseStack.withFrame { frame ->
frame.addContext(LanternEventContextKeys.ORIGINAL_ITEM_STACK, originalStack)
if (stack.isNotEmpty)
frame.addContext(LanternEventContextKeys.REST_ITEM_STACK, stack)
event = LanternEventFactory.createChangeInventoryEventPickup(
frame.currentCause, inventory, peekResult.transactions)
event.isCancelled = peekResult.transactions.isEmpty()
EventManager.post(event)
}
// Don't continue if the entity was removed during the event
if (event.isCancelled && !this.isRemoved)
continue
event.transactions.stream()
.filter { transaction -> transaction.isValid }
.forEach { transaction -> transaction.slot.set(transaction.final.createStack()) }
val added = originalStack.quantity - stack.quantity
if (added != 0 && entity is Living)
this.triggerEvent(CollectEntityEvent(entity as Living, added))
if (this.isRemoved)
stack.quantity = 0
if (stack.isEmpty)
break
}
if (stack.isNotEmpty) {
this.offer(Keys.ITEM_STACK_SNAPSHOT, stack.asSnapshot())
} else {
this.remove()
}
}
private inner class CombineData(
val pickupDelay: Duration,
val despawnDelay: Duration
)
private fun combineItemStacks(pickupDelay: Duration, despawnDelay: Duration): CombineData? {
// Remove items with no item stack
val item = this.require(Keys.ITEM_STACK_SNAPSHOT)
if (item.isEmpty) {
this.remove()
return null
}
val max = item.type.maxStackQuantity
var quantity = item.quantity
// Check if the stack is already at it's maximum size
if (quantity >= max)
return null
val frame = CauseStack.pushCauseFrame()
frame.pushCause(this)
// Search for surrounding items
val entities = this.world.getIntersectingEntities(
this.boundingBox.get().expand(0.6, 0.0, 0.6)) { entity -> entity !== this && entity is LanternItem }
var newPickupDelay = pickupDelay
var newDespawnDelay = despawnDelay
var newItem: ItemStack? = null
for (other in entities) {
val otherInfinitePickupDelay = other.require(Keys.INFINITE_PICKUP_DELAY)
if (otherInfinitePickupDelay)
continue
val otherPickupDelay = other.require(Keys.PICKUP_DELAY)
val otherItem = other.require(Keys.ITEM_STACK_SNAPSHOT)
var otherQuantity = otherItem.quantity
// Don't bother stacks that are already filled and
// make sure that the stacks can be merged
if (otherQuantity >= max || !item.isSimilarTo(otherItem))
continue
// Call the merge event
val event = LanternEventFactory.createItemMergeWithItemEvent(
frame.currentCause, other as Item, this)
EventManager.post(event)
if (event.isCancelled)
continue
// Merge the items
quantity += otherQuantity
if (quantity > max) {
otherQuantity = quantity - max
quantity = max
// Create a new stack and offer it back the entity
val newOtherItem = otherItem.createStack()
newOtherItem.quantity = otherQuantity
// The snapshot can be wrapped
other.offer(Keys.ITEM_STACK_SNAPSHOT, newOtherItem.asSnapshot())
} else {
// The other entity is completely drained and will be removed
other.offer(Keys.ITEM_STACK_SNAPSHOT, emptyItemStackSnapshot())
other.remove()
}
// The item stack has changed
if (newItem == null)
newItem = item.createStack()
newItem!!.quantity = quantity
// When merging items, also merge the pickup and despawn delays
newPickupDelay = max(newPickupDelay, otherPickupDelay)
newDespawnDelay = max(newDespawnDelay, other.require(Keys.DESPAWN_DELAY))
// The stack is already full, stop here
if (quantity == max)
break
}
frame.close()
if (newItem != null) {
this.offer(Keys.ITEM_STACK_SNAPSHOT, newItem.asSnapshot())
return CombineData(newPickupDelay, newDespawnDelay)
}
return null
}
}
| mit | 8775c5c21a93bccec5528d5ae3b5348f | 39.775578 | 116 | 0.631809 | 4.751923 | false | false | false | false |
Kotlin/kotlinx.serialization | formats/cbor/commonTest/src/kotlinx/serialization/cbor/CborNumberEncodingTest.kt | 1 | 6040 | package kotlinx.serialization.cbor
import kotlinx.serialization.decodeFromByteArray
import kotlinx.serialization.encodeToByteArray
import kotlin.test.Test
import kotlin.test.assertEquals
class CborNumberEncodingTest {
// 0-23 packs into a single byte
@Test
fun testEncodingLengthOfTinyNumbers() {
val tinyNumbers = listOf(0, 1, 23)
for (number in tinyNumbers) {
assertEquals(
expected = 1,
actual = Cbor.encodeToByteArray(number).size,
"when encoding value '$number'"
)
}
}
// 24..(2^8-1) packs into 2 bytes
@Test
fun testEncodingLengthOf8BitNumbers() {
val tinyNumbers = listOf(24, 127, 128, 255)
for (number in tinyNumbers) {
assertEquals(
expected = 2,
actual = Cbor.encodeToByteArray(number).size,
"when encoding value '$number'"
)
}
}
// 2^8..(2^16-1) packs into 3 bytes
@Test
fun testEncodingLengthOf16BitNumbers() {
val tinyNumbers = listOf(256, 32767, 32768, 65535)
for (number in tinyNumbers) {
assertEquals(
expected = 3,
actual = Cbor.encodeToByteArray(number).size,
"when encoding value '$number'"
)
}
}
// 2^16..(2^32-1) packs into 5 bytes
@Test
fun testEncodingLengthOf32BitNumbers() {
val tinyNumbers = listOf(65536, 2147483647, 2147483648, 4294967295)
for (number in tinyNumbers) {
assertEquals(
expected = 5,
actual = Cbor.encodeToByteArray(number).size,
"when encoding value '$number'"
)
}
}
// 2^32+ packs into 9 bytes
@Test
fun testEncodingLengthOfLargeNumbers() {
val tinyNumbers = listOf(4294967296, 8589934592)
for (number in tinyNumbers) {
assertEquals(
expected = 9,
actual = Cbor.encodeToByteArray(number).size,
"when encoding value '$number'"
)
}
}
@Test
fun testEncodingLargestPositiveTinyNumber() {
assertEquals(
expected = byteArrayOf(23).toList(),
actual = Cbor.encodeToByteArray(23).toList(),
)
}
@Test
fun testDecodingLargestPositiveTinyNumber() {
assertEquals(
expected = 23,
actual = Cbor.decodeFromByteArray(byteArrayOf(23)),
)
}
@Test
fun testEncodingLargestNegativeTinyNumber() {
assertEquals(
expected = byteArrayOf(55).toList(),
actual = Cbor.encodeToByteArray(-24).toList(),
)
}
@Test
fun testDecodingLargestNegativeTinyNumber() {
assertEquals(
expected = -24,
actual = Cbor.decodeFromByteArray(byteArrayOf(55)),
)
}
@Test
fun testEncodingLargestPositive8BitNumber() {
val bytes = listOf(24, 255).map { it.toByte() }
assertEquals(
expected = bytes,
actual = Cbor.encodeToByteArray(255).toList(),
)
}
@Test
fun testDecodingLargestPositive8BitNumber() {
val bytes = listOf(24, 255).map { it.toByte() }.toByteArray()
assertEquals(
expected = 255,
actual = Cbor.decodeFromByteArray(bytes),
)
}
@Test
fun testEncodingLargestNegative8BitNumber() {
val bytes = listOf(56, 255).map { it.toByte() }
assertEquals(
expected = bytes,
actual = Cbor.encodeToByteArray(-256).toList(),
)
}
@Test
fun testDecodingLargestNegative8BitNumber() {
val bytes = listOf(56, 255).map { it.toByte() }.toByteArray()
assertEquals(
expected = -256,
actual = Cbor.decodeFromByteArray(bytes),
)
}
@Test
fun testEncodingLargestPositive16BitNumber() {
val bytes = listOf(25, 255, 255).map { it.toByte() }
assertEquals(
expected = bytes,
actual = Cbor.encodeToByteArray(65535).toList(),
)
}
@Test
fun testDecodingLargestPositive16BitNumber() {
val bytes = listOf(25, 255, 255).map { it.toByte() }.toByteArray()
assertEquals(
expected = 65535,
actual = Cbor.decodeFromByteArray(bytes),
)
}
@Test
fun testEncodingLargestNegative16BitNumber() {
val bytes = listOf(57, 255, 255).map { it.toByte() }
assertEquals(
expected = bytes,
actual = Cbor.encodeToByteArray(-65536).toList(),
)
}
@Test
fun testDecodingLargestNegative16BitNumber() {
val bytes = listOf(57, 255, 255).map { it.toByte() }.toByteArray()
assertEquals(
expected = -65536,
actual = Cbor.decodeFromByteArray(bytes),
)
}
@Test
fun testEncodingLargestPositive32BitNumber() {
val bytes = listOf(26, 255, 255, 255, 255).map { it.toByte() }
assertEquals(
expected = bytes,
actual = Cbor.encodeToByteArray(4294967295).toList(),
)
}
@Test
fun testDecodingLargestPositive32BitNumber() {
val bytes = listOf(26, 255, 255, 255, 255).map { it.toByte() }.toByteArray()
assertEquals(
expected = 4294967295,
actual = Cbor.decodeFromByteArray(bytes),
)
}
@Test
fun testEncodingLargestNegative32BitNumber() {
val bytes = listOf(58, 255, 255, 255, 255).map { it.toByte() }
assertEquals(
expected = bytes,
actual = Cbor.encodeToByteArray(-4294967296).toList(),
)
}
@Test
fun testDecodingLargestNegative32BitNumber() {
val bytes = listOf(58, 255, 255, 255, 255).map { it.toByte() }.toByteArray()
assertEquals(
expected = -4294967296,
actual = Cbor.decodeFromByteArray(bytes),
)
}
}
| apache-2.0 | a0f45678c61dbdab8692ad83ea555c66 | 27.093023 | 84 | 0.562914 | 4.890688 | false | true | false | false |
LISTEN-moe/android-app | app/src/main/kotlin/me/echeung/moemoekyun/service/auto/AutoMediaBrowserService.kt | 1 | 2333 | package me.echeung.moemoekyun.service.auto
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.ServiceConnection
import android.os.Bundle
import android.os.IBinder
import android.support.v4.media.MediaBrowserCompat
import android.support.v4.media.MediaDescriptionCompat
import androidx.media.MediaBrowserServiceCompat
import me.echeung.moemoekyun.App
import me.echeung.moemoekyun.R
import me.echeung.moemoekyun.service.RadioService
class AutoMediaBrowserService : MediaBrowserServiceCompat(), ServiceConnection {
override fun onCreate() {
super.onCreate()
if (App.service != null) {
setSessionToken()
} else {
val intent = Intent(applicationContext, RadioService::class.java)
applicationContext.bindService(intent, this, Context.BIND_AUTO_CREATE or Context.BIND_IMPORTANT)
}
}
override fun onGetRoot(clientPackageName: String, clientUid: Int, rootHints: Bundle?): BrowserRoot? {
return BrowserRoot(MEDIA_ID_ROOT, null)
}
override fun onLoadChildren(parentId: String, result: Result<List<MediaBrowserCompat.MediaItem>>) {
val mediaItems = listOf(
createPlayableMediaItem(RadioService.LIBRARY_JPOP, resources.getString(R.string.jpop)),
createPlayableMediaItem(RadioService.LIBRARY_KPOP, resources.getString(R.string.kpop)),
)
result.sendResult(mediaItems)
}
override fun onServiceConnected(className: ComponentName, service: IBinder) {
val binder = service as RadioService.ServiceBinder
val radioService = binder.service
App.service = radioService
setSessionToken()
}
override fun onServiceDisconnected(arg0: ComponentName) {
}
private fun setSessionToken() {
val mediaSession = App.service!!.mediaSession
sessionToken = mediaSession!!.sessionToken
}
private fun createPlayableMediaItem(mediaId: String, title: String): MediaBrowserCompat.MediaItem {
val builder = MediaDescriptionCompat.Builder()
.setMediaId(mediaId)
.setTitle(title)
return MediaBrowserCompat.MediaItem(builder.build(), MediaBrowserCompat.MediaItem.FLAG_PLAYABLE)
}
}
private const val MEDIA_ID_ROOT = "media_root"
| mit | 6ad6fd48dcbbe9de5d9ec2ccc3aa062d | 33.820896 | 108 | 0.726104 | 4.840249 | false | false | false | false |
googlecodelabs/watchnext-for-movie-tv-episodes | step_4_completed/src/main/java/com/android/tv/reference/watchnext/WatchNextWorker.kt | 8 | 3897 | /*
* Copyright 2020 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.tv.reference.watchnext
import android.annotation.SuppressLint
import android.app.Application
import android.content.Context
import androidx.work.Worker
import androidx.work.WorkerParameters
import com.android.tv.reference.repository.VideoRepositoryFactory
import com.android.tv.reference.shared.datamodel.VideoType
import timber.log.Timber
/**
* Worker triggered by WorkManager to add/update/remove video to Watch Next channel.
*
* <code>
* WorkManager.getInstance(context).enqueue(OneTimeWorkRequest.Builder(WatchNextWorker::class.java).build())
* </code>
*/
class WatchNextWorker(private val context: Context, params: WorkerParameters) :
Worker(context, params) {
/**
* Worker thread to add/update/remove content from Watch Next channel.
* Events triggered from player state change events &
* playback lifecycle events (onPause) are consumed here.
*/
@SuppressLint("RestrictedApi")
override fun doWork(): Result {
// Step 1 : get the video information from the "inputData".
val videoId = inputData.getString(WatchNextHelper.VIDEO_ID)
val watchPosition =
inputData.getLong(WatchNextHelper.CURRENT_POSITION, /* defaultValue= */ 0)
val state = inputData.getString(WatchNextHelper.PLAYER_STATE)
Timber.v("Work Manager called watch id $videoId , watchTime $watchPosition")
// Step 2 : Check for invalid inputData.
// If videoId is invalid, abort worker and return.
if (videoId.isNullOrEmpty()) {
Timber.e("Error.Invalid entry for Watch Next. videoid: $videoId")
return Result.failure()
}
// Check for invalid player state.
if ((state != WatchNextHelper.PLAY_STATE_PAUSED) and
(state != WatchNextHelper.PLAY_STATE_ENDED)
) {
Timber.e("Error.Invalid entry for Watch Next. Player state: $state")
return Result.failure()
}
// Step 3: Get video object from videoId to be added to Watch Next.
val video =
VideoRepositoryFactory.getVideoRepository(context.applicationContext as Application)
.getVideoById(videoId)
Timber.v("Retrieved video from repository with id %s, %s", videoId, video)
// Step 4 : Handle Watch Next for different types of content.
when (video?.videoType) {
VideoType.MOVIE -> {
Timber.v("Add Movie to Watch Next : id = ${video.id}")
WatchNextHelper.handleWatchNextForMovie(video, watchPosition.toInt(), state, context)
}
VideoType.EPISODE -> {
Timber.v("Add Episode to Watch Next : id = ${video.id}")
WatchNextHelper.handleWatchNextForEpisode(
video, watchPosition.toInt(), state,
VideoRepositoryFactory.getVideoRepository(
context.applicationContext as Application), context)
}
VideoType.CLIP -> Timber.w(
"NOT recommended to add Clips / Trailers /Short videos to Watch Next "
)
else -> Timber.e("Invalid category for Video Type: ${video?.videoType}")
}
Timber.v("WatchNextWorker finished")
return Result.success()
}
}
| apache-2.0 | 32873e80189973c6f863d95480db3a81 | 39.59375 | 108 | 0.662561 | 4.700844 | false | false | false | false |
bobrofon/easysshfs | app/src/main/java/ru/nsu/bobrofon/easysshfs/InternetStateChangeReceiver.kt | 1 | 1838 | package ru.nsu.bobrofon.easysshfs
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.net.NetworkInfo
import android.net.wifi.WifiManager
import android.os.Handler
import android.util.Log
import com.topjohnwu.superuser.Shell
import ru.nsu.bobrofon.easysshfs.mountpointlist.MountPointsList
private const val TAG = "InternetStateChange"
private const val AUTO_MOUNT_DELAY_MILLIS: Long = 5000
class InternetStateChangeReceiver(
private val handler: Handler
) : BroadcastReceiver() {
private val shell: Shell by lazy { EasySSHFSActivity.initNewShell() }
override fun onReceive(context: Context, intent: Intent) {
if (WifiManager.NETWORK_STATE_CHANGED_ACTION != intent.action) {
return
}
Log.d(TAG, "network state changed")
val info = intent.getParcelableExtra<NetworkInfo>(WifiManager.EXTRA_NETWORK_INFO) ?: return
val mountPointsList = MountPointsList.instance(context)
handler.removeCallbacksAndMessages(null) // ignore repeated intents
if (info.isConnected) {
Log.d(TAG, "network is connected")
handler.postDelayed({autoMount(mountPointsList, shell)}, AUTO_MOUNT_DELAY_MILLIS)
} else {
Log.d(TAG, "unmount everything")
handler.post { forceUmount(mountPointsList, shell) }
}
}
private fun autoMount(mountPointsList: MountPointsList, shell: Shell) {
Log.d(TAG, "check auto-mount")
if (mountPointsList.needAutomount()) {
Log.d(TAG, "auto-mount required")
mountPointsList.autoMount(shell)
}
}
private fun forceUmount(mountPointsList: MountPointsList, shell: Shell) {
Log.d(TAG, "force umount everything")
mountPointsList.umount(shell)
}
}
| mit | c90016f490ef3a6529cc374ef1bf70db | 32.418182 | 99 | 0.697497 | 4.215596 | false | false | false | false |
clappr/clappr-android | clappr/src/main/kotlin/io/clappr/player/plugin/control/TimeIndicatorPlugin.kt | 1 | 3098 | package io.clappr.player.plugin.control
import android.os.Bundle
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup.LayoutParams.WRAP_CONTENT
import android.widget.LinearLayout
import android.widget.TextView
import io.clappr.player.R
import io.clappr.player.base.Event
import io.clappr.player.base.InternalEvent
import io.clappr.player.base.NamedType
import io.clappr.player.components.Core
import io.clappr.player.components.Playback
import io.clappr.player.extensions.asTimeInterval
import io.clappr.player.extensions.unlessChromeless
import io.clappr.player.plugin.PluginEntry
open class TimeIndicatorPlugin(core: Core) : MediaControl.Plugin(core, name) {
companion object : NamedType {
override val name = "timeIndicator"
val entry = PluginEntry.Core(
name = name,
factory = ::TimeIndicatorPlugin.unlessChromeless()
)
}
override var panel: Panel = Panel.BOTTOM
override var position: Position = Position.LEFT
protected val textView by lazy {
LayoutInflater.from(applicationContext).inflate(R.layout.time_indicator, null) as TextView
}
override val view: View?
get() = textView
private val playbackListenerIds = mutableListOf<String>()
init {
listenTo(core, InternalEvent.DID_CHANGE_ACTIVE_PLAYBACK.value, { setupPlaybackListeners() })
updateLiveStatus()
}
private fun setupPlaybackListeners() {
updateLiveStatus()
stopPlaybackListeners()
core.activePlayback?.let {
updateValue(null)
playbackListenerIds.add(listenTo(it, Event.DID_LOAD_SOURCE.value) { setupPlaybackListeners() })
playbackListenerIds.add(listenTo(it, Event.DID_UPDATE_POSITION.value) { bundle -> updateValue(bundle) })
playbackListenerIds.add(listenTo(it, Event.DID_COMPLETE.value) { hide() })
}
}
private fun stopPlaybackListeners() {
playbackListenerIds.forEach(::stopListening)
playbackListenerIds.clear()
}
private fun updateLiveStatus() {
val isVOD = core.activePlayback?.mediaType == Playback.MediaType.VOD
view?.visibility = if (!isVOD || isPlaybackIdle) View.GONE else View.VISIBLE
}
private fun updateValue(bundle: Bundle?) {
(bundle ?: Bundle()).let {
val position = it.getDouble("time", 0.0)
val duration = core.activePlayback?.duration ?: 0.0
textView.text = "%s / %s".format(position.asTimeInterval(), duration.asTimeInterval())
}
updateLiveStatus()
}
override fun render() {
val height = applicationContext.resources?.getDimensionPixelSize(R.dimen.time_indicator_height) ?: 0
val layoutParams = LinearLayout.LayoutParams(WRAP_CONTENT, height)
layoutParams.gravity = Gravity.CENTER_VERTICAL
textView.layoutParams = layoutParams
textView.text = "00:00 / 00:00"
}
override fun destroy() {
stopPlaybackListeners()
super.destroy()
}
} | bsd-3-clause | 5a126eebe1242e4320071fa356b22032 | 33.433333 | 116 | 0.690445 | 4.509461 | false | false | false | false |
lukashaertel/megal-vm | src/main/kotlin/org/softlang/megal/plugins/Plugin.kt | 1 | 2615 | package org.softlang.megal.plugins
import org.softlang.megal.content.*
//import org.softlang.megal.content.by
//import org.softlang.megal.content.from
import java.io.InputStreamReader
import java.net.URI
/**
* Base interface for all configurable plugins.
*/
interface Plugin
/**
* Root navigation plugin, resolves root URI to content.
*/
interface BaseResolver : Plugin {
/**
* Initializes root navigation.
* @param uri The root URI
* @return Returns resolved content
*/
operator fun get(uri: URI): Content
/**
* Initializes root navigation.
* @param uri The root URI as a string
* @return Returns resolved content
*/
operator fun get(uri: String) = get(URI(uri))
}
/**
* Creates a simple root navigation plugin.
* @param method The implementation
* @return Returns a new root navigation plugin
*/
inline fun baseBy(crossinline method: (URI) -> Content) =
object : BaseResolver {
override fun get(uri: URI) = method(uri)
}
/**
* Nested navigation plugin, resolves navigating URI in a given context.
*/
interface NestedResolver : Plugin {
/**
* Navigates to the [uri] in a given [context].
* @param uri The nested URI
* @param context The context to resolve in
* @return Returns the next resolved content
*/
operator fun get(uri: URI, context: Content): Content
/**
* Navigates to the [uri] in a given [context].
* @param uri The nested URI as a string
* @param context The context to resolve in
* @return Returns the next resolved content
*/
operator fun get(uri: String, context: Content) = get(URI(uri), context)
}
/**
* Creates a simple nested navigation plugin.
* @param method The implementation
* @return Returns a new nested navigation plugin
*/
inline fun nestedBy(crossinline method: (URI, Content) -> Content) =
object : NestedResolver {
override fun get(uri: URI, context: Content) = method(uri, context)
}
/**
* Evaluation plugin, used for inference, verification et cetera.
*/
interface EvalPlugin : Plugin {
/**
* Evaluates the given input as arbitrary content.
* @param content The content to handle
* @return Returns result content
*/
fun eval(content: Content): Content
}
/**
* Creates a simple evaluation plugin.
* @param method The implementation
* @return Returns a new evaluation plugin
*/
inline fun evalBy(crossinline method: (Content) -> Content) =
object : EvalPlugin {
override fun eval(content: Content) = method(content)
} | mit | f5e3195d15086db14b78bac34b7976ce | 26.829787 | 79 | 0.665392 | 4.231392 | false | false | false | false |
alfiewm/Keddit | app/src/main/java/meng/keddit/features/news/adapter/NewsAdapter.kt | 1 | 2245 | package meng.keddit.features.news.adapter
import android.support.v4.util.SparseArrayCompat
import android.support.v7.widget.RecyclerView
import android.view.ViewGroup
import meng.keddit.commons.RedditNewsItem
import meng.keddit.commons.adapter.*
/**
* Created by meng on 2017/7/31.
*/
class NewsAdapter : RecyclerView.Adapter<RecyclerView.ViewHolder>() {
private var items: ArrayList<ViewType>
private var delegateAdapters = SparseArrayCompat<ViewTypeDelegateAdapter>()
private var loadingItem = object : ViewType {
override fun getViewType() = AdapterConstants.LOADING
}
init {
delegateAdapters.put(AdapterConstants.LOADING, LoadingDelegateAdapter())
delegateAdapters.put(AdapterConstants.NEWS, NewsDelegateAdapter())
items = ArrayList()
items.add(loadingItem)
}
override fun getItemCount(): Int {
return items.size
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
return delegateAdapters.get(viewType).onCreateViewHolder(parent)
}
override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
delegateAdapters.get(getItemViewType(position)).onBindViewHolder(holder, this.items[position])
}
override fun getItemViewType(position: Int): Int {
return this.items[position].getViewType()
}
fun addNews(news: List<RedditNewsItem>) {
// first remove loading and notify
val initPosition = items.size - 1
items.removeAt(initPosition)
// insert news and the loading at the end of the list
items.addAll(news)
items.add(loadingItem)
notifyItemRangeChanged(initPosition, items.size + 1)
}
fun clearAndAddNews(news: List<RedditNewsItem>) {
items.clear()
notifyItemRangeRemoved(0, getLastPosition())
items.addAll(news)
items.add(loadingItem)
notifyItemRangeInserted(0, items.size)
}
fun getNews(): List<RedditNewsItem> {
return items.filter { it.getViewType() == AdapterConstants.NEWS }
.map { it as RedditNewsItem }
}
private fun getLastPosition() = if (items.lastIndex == -1) 0 else items.lastIndex
} | mit | 611a1d66596a0e5be7b53e52477921c6 | 31.550725 | 102 | 0.69755 | 4.696653 | false | false | false | false |
jingcai-wei/android-news | app/src/main/java/com/sky/android/news/data/cache/CacheManager.kt | 1 | 5174 | /*
* Copyright (c) 2021 The sky 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 com.sky.android.news.data.cache
import android.content.Context
import com.google.gson.Gson
import com.jakewharton.disklrucache.DiskLruCache
import com.sky.android.common.util.Alog
import com.sky.android.common.util.FileUtil
import com.sky.android.common.util.MD5Util
import com.sky.android.news.BuildConfig
import java.io.File
import java.io.IOException
/**
* Created by sky on 17-9-21.
*/
class CacheManager private constructor(private val mContext: Context): ICacheManager {
private var mDiskLruCache: DiskLruCache? = null
private var mGson: Gson = Gson()
companion object {
private val TAG = CacheManager::class.java.simpleName
private const val MAX_SIZE = 1024 * 1024 * 20
@Volatile
private var instance: ICacheManager? = null
fun getInstance(context: Context): ICacheManager {
if (instance == null) {
synchronized(CacheManager::class) {
if (instance == null) {
instance = CacheManager(context)
}
}
}
return instance!!
}
}
init {
initCacheManager()
}
private fun initCacheManager() {
val version = BuildConfig.VERSION_CODE
val cacheDir = File(mContext.cacheDir, "net_cache")
if (!cacheDir.exists()) FileUtil.createDir(cacheDir)
mDiskLruCache = try {
DiskLruCache.open(cacheDir, version, 1, MAX_SIZE.toLong())
} catch (e: IOException) {
Alog.e(TAG, "打开缓存目录异常", e)
null
}
}
@Synchronized
override fun <T> get(key: String, tClass: Class<T>): T? {
try {
// 获取缓存信息
val snapshot = get(key)
if (snapshot != null) {
// 返回相应的信息
return mGson.fromJson(snapshot.getString(0), tClass)
}
} catch (e: Exception) {
Alog.e(TAG, "获取信息失败", e)
}
return null
}
@Synchronized
override fun <T> put(key: String, value: T): Boolean {
var editor: DiskLruCache.Editor? = null
try {
// 获取编辑器
editor = edit(key)
if (editor != null) {
// 保存数据
editor.set(0, mGson.toJson(value))
editor.commit()
return true
}
} catch (e: Exception) {
abortQuietly(editor)
Alog.e(TAG, "保存分类信息出错!", e)
} finally {
flushQuietly()
}
return false
}
@Synchronized
override fun remove(key: String): Boolean {
if (!verifyCache()) return false
try {
// 删除数据
mDiskLruCache!!.remove(key)
return true
} catch (e: IOException) {
Alog.e(TAG, "移除数据失败", e)
}
return false
}
override fun clear() {
if (!verifyCache()) return
try {
// 删除数据
mDiskLruCache!!.delete()
initCacheManager()
} catch (e: IOException) {
Alog.e(TAG, "删除数据失败", e)
}
}
@Synchronized
override fun close() {
if (!verifyCache()) return
try {
mDiskLruCache!!.close()
} catch (e: IOException) {
Alog.e(TAG, "关闭缓存失败", e)
}
}
override fun buildKey(value: String): String = MD5Util.md5sum(value)
private fun verifyCache(): Boolean = mDiskLruCache != null
@Throws(IOException::class)
private operator fun get(key: String): DiskLruCache.Snapshot? =
if (verifyCache()) mDiskLruCache!!.get(key) else null
@Throws(IOException::class)
private fun edit(key: String): DiskLruCache.Editor? =
if (verifyCache()) mDiskLruCache!!.edit(key) else null
@Throws(IOException::class)
private fun abort(editor: DiskLruCache.Editor?) {
editor?.abort()
}
private fun abortQuietly(editor: DiskLruCache.Editor?) {
try {
abort(editor)
} catch (e: IOException) {
Alog.e(TAG, "abortQuietly", e)
}
}
@Throws(IOException::class)
private fun flush() {
if (verifyCache()) mDiskLruCache!!.flush()
}
private fun flushQuietly() {
try {
flush()
} catch (e: IOException) {
Alog.e(TAG, "flushQuietly", e)
}
}
} | apache-2.0 | 61988f1c4efa17aa79f663756ee1df6e | 24.678571 | 86 | 0.56399 | 4.364267 | false | false | false | false |
uchuhimo/kotlinx-bimap | src/main/kotlin/com/uchuhimo/collections/BiMaps.kt | 1 | 3660 | /*
* Copyright 2017 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.
*/
@file:kotlin.jvm.JvmName("BiMapsKt")
@file:kotlin.jvm.JvmMultifileClass
package com.uchuhimo.collections
/**
* Returns an empty read-only bimap of specified type.
*
* @return an empty read-only bimap
*/
fun <K, V> emptyBiMap(): BiMap<K, V> = @Suppress("UNCHECKED_CAST") (emptyBiMap as BiMap<K, V>)
/**
* Returns a new read-only bimap containing all key-value pairs from the given map.
*
* The returned bimap preserves the entry iteration order of the original map.
*
* @receiver the original map
* @return a new read-only bimap
*/
fun <K, V> Map<K, V>.toBiMap(): BiMap<K, V> =
if (isNotEmpty()) {
val inversePairs = entries.map { (key, value) -> value to key }.toMap()
BiMapImpl(this, inversePairs)
} else {
emptyBiMap()
}
/**
* Returns a new read-only bimap with the specified contents, given as a list of pairs
* where the first value is the key and the second is the value.
*
* If multiple pairs have the same key or the same value, the resulting bimap will contain
* the last of those pairs.
*
* Entries of the bimap are iterated in the order they were specified.
*
* @param pairs the specified contents for the returned bimap
* @return a new read-only bimap
*/
fun <K, V> biMapOf(vararg pairs: Pair<K, V>): BiMap<K, V> = pairs.toMap().toBiMap()
/**
* Returns a new read-only bimap, mapping only the specified key to the
* specified value.
*
* @param pair a pair of key and value for the returned bimap
* @return a new read-only bimap
*/
fun <K, V> biMapOf(pair: Pair<K, V>): BiMap<K, V> =
BiMapImpl(mapOf(pair), mapOf(pair.second to pair.first))
private class BiMapImpl<K, V> private constructor(delegate: Map<K, V>) :
BiMap<K, V>, Map<K, V> by delegate {
constructor(forward: Map<K, V>, backward: Map<V, K>) : this(forward) {
_inverse = BiMapImpl(backward, this)
}
private constructor(backward: Map<K, V>, forward: BiMap<V, K>) : this(backward) {
_inverse = forward
}
private lateinit var _inverse: BiMap<V, K>
override val inverse: BiMap<V, K> get() = _inverse
override val values: Set<V> get() = inverse.keys
override fun equals(other: Any?): Boolean = equals(this, other)
override fun hashCode(): Int = hashCodeOf(this)
}
internal fun equals(bimap: BiMap<*, *>, other: Any?): Boolean {
if (bimap === other) return true
if (other !is BiMap<*, *>) return false
if (other.size != bimap.size) return false
val i = bimap.entries.iterator()
while (i.hasNext()) {
val e = i.next()
val key = e.key
val value = e.value
if (value == null) {
if (other[key] != null || !other.containsKey(key))
return false
} else {
if (value != other[key])
return false
}
}
return true
}
internal fun hashCodeOf(map: Map<*, *>): Int {
return map.entries.fold(0) { acc, entry ->
acc + entry.hashCode()
}
}
private val emptyBiMap = BiMapImpl<Any?, Any?>(emptyMap(), emptyMap())
| apache-2.0 | 1c4446013b33121bc5f0c3310e1bb188 | 30.551724 | 94 | 0.65082 | 3.693239 | false | false | false | false |
lfkdsk/JustDB | src/buffer/BufferManagerImpl.kt | 1 | 2236 | package buffer
import core.JustDB
import storage.Block
/**
* Buffer Abort
* Created by liufengkai on 2017/4/30.
*/
class BufferAbortException : RuntimeException()
/**
* Buffer-Manager Impl
* Created by liufengkai on 2017/4/30.
*/
class BufferManagerImpl(justDB: JustDB, bufferNumber: Int) : BufferManager {
/**
* max-wait-time
*/
private val MAX_TIME: Long = 10000 // 10 seconds
private val bufferPoolManager = BufferPoolManagerImpl(justDB, bufferNumber)
/**
* sync - lock - object
*/
private val lock = java.lang.Object()
/**
* Buffer pin block
* @param block => block
*/
@Throws(BufferAbortException::class)
override
fun pin(block: Block): Buffer = synchronized(lock) {
try {
val timestamp = System.currentTimeMillis()
var buff = bufferPoolManager.pin(block)
while (buff == null && !waitingTooLong(timestamp)) {
lock.wait(MAX_TIME)
buff = bufferPoolManager.pin(block)
}
if (buff == null)
throw BufferAbortException()
return buff
} catch (e: InterruptedException) {
throw BufferAbortException()
}
}
/**
* Pin new fileName Block
* @param fileName
* @param pageFormatter
*/
@Throws(BufferAbortException::class)
override
fun pinNew(fileName: String, pageFormatter: PageFormatter): Buffer = synchronized(lock) {
try {
val timestamp = System.currentTimeMillis()
var buff = bufferPoolManager.pinNew(fileName, pageFormatter)
while (buff == null && !waitingTooLong(timestamp)) {
lock.wait(MAX_TIME)
// get new block
buff = bufferPoolManager.pinNew(fileName, pageFormatter)
}
if (buff == null)
throw BufferAbortException()
return buff
} catch (e: InterruptedException) {
throw BufferAbortException()
}
}
/**
* unpin buffer from block
* @param buffer this buffer
*/
override
fun unpin(buffer: Buffer) = synchronized(lock) {
bufferPoolManager.unpin(buffer)
// unpin all -> lock
if (!buffer.isPinned())
lock.notifyAll()
}
override
fun flushAll(transaction: Int) {
bufferPoolManager.flushAll(transaction)
}
override
fun available(): Int {
return bufferPoolManager.available()
}
private fun waitingTooLong(startTime: Long) = System.currentTimeMillis() - startTime > MAX_TIME
}
| apache-2.0 | ad7234fbf0d4fe83a7e46f38e1547757 | 20.5 | 96 | 0.692755 | 3.726667 | false | false | false | false |
FHannes/intellij-community | plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/transformations/impl/synch/SynchronizedTransformationAnnotator.kt | 22 | 2884 | /*
* Copyright 2000-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.plugins.groovy.transformations.impl.synch
import com.intellij.lang.annotation.AnnotationHolder
import com.intellij.lang.annotation.Annotator
import com.intellij.psi.PsiElement
import org.jetbrains.plugins.groovy.lang.lexer.GroovyTokenTypes
import org.jetbrains.plugins.groovy.lang.psi.api.auxiliary.modifiers.GrModifierList
import org.jetbrains.plugins.groovy.lang.psi.api.auxiliary.modifiers.annotation.GrAnnotation
import org.jetbrains.plugins.groovy.lang.psi.api.statements.GrField
import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.literals.GrLiteral
import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.members.GrMethod
import org.jetbrains.plugins.groovy.lang.psi.util.GrTraitUtil
class SynchronizedTransformationAnnotator : Annotator {
override fun annotate(element: PsiElement, holder: AnnotationHolder) {
if (element is GrAnnotation && element.qualifiedName == ANNO_FQN) {
val method = (element.owner as? GrModifierList)?.parent as? GrMethod ?: return
if (GrTraitUtil.isMethodAbstract(method)) {
holder.createErrorAnnotation(element, "@Synchronized not allowed on abstract method")
}
}
else if (element.node.elementType == GroovyTokenTypes.mIDENT) {
val field = element.parent as? GrField ?: return
val staticField = field.isStatic()
if (!staticField) {
val hasStaticMethods = getMethodsReferencingLock(field).any { it.isStatic() }
if (hasStaticMethods) {
holder.createErrorAnnotation(element, "Lock field '${field.name}' must be static")
}
}
else if (field.name == LOCK_NAME) {
val hasInstanceMethods = getMethodsReferencingLock(field).any { !it.isStatic() }
if (hasInstanceMethods) {
holder.createErrorAnnotation(element, "Lock field '$LOCK_NAME' must not be static")
}
}
}
else if (PATTERN.accepts(element)) {
element as GrLiteral
val reference = element.reference ?: return
val field = reference.resolve() as? GrField
if (field == null) {
val range = reference.rangeInElement.shiftRight(element.textRange.startOffset)
holder.createErrorAnnotation(range, "Lock field '${element.value}' not found")
}
}
}
}
| apache-2.0 | 01cebe88b013576f7dec7a83997776a9 | 44.0625 | 93 | 0.731276 | 4.33033 | false | false | false | false |
KenVanHoeylandt/KIP-8 | src/main/kotlin/com/bytewelder/kip8/ui/Screen.kt | 1 | 1258 | package com.bytewelder.kip8.ui
/**
* Implementation of a Panel that can render a ScreenBuffer.
*/
class Screen internal constructor(val screenBuffer: ScreenBuffer, val pixelSize: Int) : javax.swing.JPanel(), java.awt.event.ActionListener {
val timer: javax.swing.Timer
private val DELAY = 50
init {
timer = javax.swing.Timer(DELAY, this)
timer.start()
setSize(pixelSize * screenBuffer.columns, pixelSize * screenBuffer.rows)
}
override fun paintComponent(graphics: java.awt.Graphics) {
super.paintComponent(graphics)
val graphics2d = graphics as java.awt.Graphics2D
drawBackground(graphics2d)
drawPixels(graphics2d)
}
override fun actionPerformed(e: java.awt.event.ActionEvent) {
repaint()
}
private fun drawPoint(graphics: java.awt.Graphics2D, x: Int, y: Int) {
val fromX = pixelSize * x
val fromY = pixelSize * y
graphics.fillRect(fromX, fromY, pixelSize, pixelSize)
}
private fun drawBackground(graphics: java.awt.Graphics2D) {
graphics.paint = java.awt.Color.black
graphics.fillRect(0, 0, width, height)
}
private fun drawPixels(graphics: java.awt.Graphics2D) {
graphics.paint = java.awt.Color.green
screenBuffer.forEachPixel { x, y, isOn ->
if (isOn) {
drawPoint(graphics, x, y)
}
}
}
} | apache-2.0 | 3288ea8dbdda81a2a7de8a3c751b76ac | 25.229167 | 141 | 0.728935 | 3.233933 | false | false | false | false |
didi/DoraemonKit | Android/dokit-gps-mock/src/main/java/com/didichuxing/doraemonkit/gps_mock/lbs/route/NaviSettings.kt | 1 | 401 | package com.didichuxing.doraemonkit.gps_mock.lbs.route
/**
* Created by kuloud on 4/11/16.
*/
object NaviSettings {
const val POLYLINE_Z_INDEX = 1
const val ROUTE_SHADOW_Z_INDEX = -1
const val ROUTE_NORMAL_Z_INDEX = 0
const val TEXT_Z_INDEX = 4
/**
* 位置信息获取的频率(长),单位为毫秒。
*/
const val LOCATION_UPDATE_TIME_LONG_IN_MILLIS = 3000
}
| apache-2.0 | fc68e6907ddb4a94ada2d12cfaa51ef6 | 21.9375 | 56 | 0.648501 | 2.889764 | false | false | false | false |
pgutkowski/KGraphQL | src/main/kotlin/com/github/pgutkowski/kgraphql/schema/execution/ArgumentTransformer.kt | 1 | 2846 | package com.github.pgutkowski.kgraphql.schema.execution
import com.github.pgutkowski.kgraphql.ExecutionException
import com.github.pgutkowski.kgraphql.RequestException
import com.github.pgutkowski.kgraphql.isLiteral
import com.github.pgutkowski.kgraphql.request.Variables
import com.github.pgutkowski.kgraphql.schema.DefaultSchema
import com.github.pgutkowski.kgraphql.schema.scalar.deserializeScalar
import com.github.pgutkowski.kgraphql.schema.structure2.InputValue
import com.github.pgutkowski.kgraphql.schema.structure2.Type
import kotlin.reflect.KType
import kotlin.reflect.jvm.jvmErasure
open class ArgumentTransformer(val schema : DefaultSchema) {
fun transformValue(type: Type, value: String, variables: Variables) : Any? {
val kType = type.toKType()
return when {
value.startsWith("$") -> {
variables.get (
kType.jvmErasure, kType, value, { subValue -> transformValue(type, subValue, variables) }
)
}
value == "null" && type.isNullable() -> null
value == "null" && type.isNotNullable() -> {
throw RequestException("argument '$value' is not valid value of type ${type.unwrapped().name}")
}
else -> {
return transformString(value, kType)
}
}
}
private fun transformString(value: String, kType: KType): Any {
val kClass = kType.jvmErasure
fun throwInvalidEnumValue(enumType : Type.Enum<*>){
throw RequestException(
"Invalid enum ${schema.model.enums[kClass]?.name} value. Expected one of ${enumType.values}"
)
}
schema.model.enums[kClass]?.let { enumType ->
if(value.isLiteral()) {
throw RequestException("String literal '$value' is invalid value for enum type ${enumType.name}")
}
return enumType.values.find { it.name == value }?.value ?: throwInvalidEnumValue(enumType)
} ?: schema.model.scalars[kClass]?.let { scalarType ->
return deserializeScalar(scalarType, value)
} ?: throw RequestException("Invalid argument value '$value' for type ${schema.model.inputTypes[kClass]?.name}")
}
fun transformCollectionElementValue(inputValue: InputValue<*>, value: String, variables: Variables): Any? {
assert(inputValue.type.isList())
val elementType = inputValue.type.unwrapList().ofType as Type?
?: throw ExecutionException("Unable to handle value of element of collection without type")
return transformValue(elementType, value, variables)
}
fun transformPropertyValue(parameter: InputValue<*>, value: String, variables: Variables): Any? {
return transformValue(parameter.type, value, variables)
}
} | mit | ff94e78bab6c461a89256e910ba1fd6f | 40.867647 | 120 | 0.658117 | 4.848382 | false | false | false | false |
hypercube1024/firefly | firefly-net/src/main/kotlin/com/fireflysource/net/http/common/v2/stream/AsyncHttp2Stream.kt | 1 | 14069 | package com.fireflysource.net.http.common.v2.stream
import com.fireflysource.common.`object`.Assert
import com.fireflysource.common.concurrent.exceptionallyAccept
import com.fireflysource.common.sys.Result
import com.fireflysource.common.sys.Result.discard
import com.fireflysource.common.sys.SystemLogger
import com.fireflysource.net.http.common.exception.Http2StreamFrameProcessException
import com.fireflysource.net.http.common.model.HttpHeader
import com.fireflysource.net.http.common.model.MetaData
import com.fireflysource.net.http.common.v2.frame.*
import com.fireflysource.net.http.common.v2.frame.CloseState.*
import com.fireflysource.net.http.common.v2.frame.CloseState.Event.*
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import java.io.Closeable
import java.io.IOException
import java.time.Duration
import java.util.*
import java.util.concurrent.ConcurrentHashMap
import java.util.concurrent.ConcurrentMap
import java.util.concurrent.TimeoutException
import java.util.concurrent.atomic.AtomicInteger
import java.util.concurrent.atomic.AtomicReference
import java.util.function.Consumer
class AsyncHttp2Stream(
private val asyncHttp2Connection: AsyncHttp2Connection,
private val id: Int,
private val local: Boolean,
var listener: Stream.Listener = defaultStreamListener
) : Stream, Closeable {
companion object {
private val log = SystemLogger.create(AsyncHttp2Stream::class.java)
val defaultStreamListener = Stream.Listener.Adapter()
}
private val attributes: ConcurrentMap<String, Any> by lazy { ConcurrentHashMap() }
private val sendWindow = AtomicInteger()
private val recvWindow = AtomicInteger()
private val level = AtomicInteger()
private val closeState = AtomicReference(NOT_CLOSED)
private var localReset = false
private var remoteReset = false
private val createTime = System.currentTimeMillis()
private var lastActiveTime = createTime
private var idleTimeout: Long = 0
private var idleCheckJob: Job? = null
private var dataLength = Long.MIN_VALUE
val stashedDataFrames = LinkedList<DataFrameEntry>()
override fun getId(): Int = id
override fun getHttp2Connection(): Http2Connection = asyncHttp2Connection
override fun getIdleTimeout(): Long = idleTimeout
override fun setIdleTimeout(idleTimeout: Long) {
if (idleTimeout > 0) {
this.idleTimeout = idleTimeout
val job = idleCheckJob
idleCheckJob = if (job == null) {
launchIdleCheckJob()
} else {
job.cancel(CancellationException("Set the new idle timeout. id: $id"))
launchIdleCheckJob()
}
}
}
private fun noIdle() {
lastActiveTime = System.currentTimeMillis()
}
private fun launchIdleCheckJob() = asyncHttp2Connection.coroutineScope.launch {
while (true) {
val timeout = Duration.ofSeconds(idleTimeout).toMillis()
val delayTime = (timeout - getIdleTime()).coerceAtLeast(0)
log.debug { "Stream idle check delay: $delayTime" }
if (delayTime > 0) {
delay(delayTime)
}
val idle = getIdleTime()
if (idle >= timeout) {
notifyIdleTimeout()
break
}
}
}
private fun getIdleTime() = System.currentTimeMillis() - lastActiveTime
private fun notifyIdleTimeout() {
try {
val reset = listener.onIdleTimeout(this, TimeoutException("Stream idle timeout"))
if (reset) {
val frame = ResetFrame(id, ErrorCode.CANCEL_STREAM_ERROR.code)
reset(frame, discard())
}
} catch (e: Exception) {
log.error(e) { "failure while notifying listener" }
}
}
override fun getAttribute(key: String): Any? = attributes[key]
override fun setAttribute(key: String, value: Any) {
attributes[key] = value
}
override fun removeAttribute(key: String): Any? = attributes.remove(key)
fun process(frame: Frame, result: Consumer<Result<Void>>) {
when (frame.type) {
FrameType.HEADERS -> onHeaders(frame as HeadersFrame, result)
FrameType.DATA -> onData(frame as DataFrame, result)
FrameType.RST_STREAM -> onReset(frame as ResetFrame, result)
FrameType.PUSH_PROMISE -> {
// They are closed when receiving an end-stream DATA frame.
// Pushed streams implicitly locally closed.
// They are closed when receiving an end-stream DATA frame.
updateClose(true, AFTER_SEND)
result.accept(Result.SUCCESS)
}
FrameType.WINDOW_UPDATE -> result.accept(Result.SUCCESS)
FrameType.FAILURE -> notifyFailure(this, frame as FailureFrame, result)
else -> throw Http2StreamFrameProcessException("Process frame type error. ${frame.type}")
}
}
// header frame
override fun headers(frame: HeadersFrame, result: Consumer<Result<Void>>) {
try {
noIdle()
Assert.isTrue(frame.streamId == id, "The headers frame id must equal the stream id")
sendControlFrame(frame, result)
} catch (e: Exception) {
result.accept(Result.createFailedResult(e))
}
}
private fun onHeaders(frame: HeadersFrame, result: Consumer<Result<Void>>) {
noIdle()
val metaData: MetaData = frame.metaData
if (metaData.isRequest || metaData.isResponse) {
val fields = metaData.fields
var length: Long = -1
if (fields != null) {
length = fields.getLongField(HttpHeader.CONTENT_LENGTH.value)
}
dataLength = if (length >= 0) length else Long.MIN_VALUE
}
if (updateClose(frame.isEndStream, RECEIVED)) {
asyncHttp2Connection.removeStream(this)
}
result.accept(Result.SUCCESS)
}
// push promise frame
override fun push(frame: PushPromiseFrame, promise: Consumer<Result<Stream?>>, listener: Stream.Listener) {
noIdle()
asyncHttp2Connection.push(frame, promise, listener)
}
// data frame
override fun data(frame: DataFrame, result: Consumer<Result<Void>>) {
noIdle()
asyncHttp2Connection.sendDataFrame(this, frame)
.thenAccept { result.accept(Result.SUCCESS) }
.exceptionallyAccept { result.accept(Result.createFailedResult(it)) }
}
private fun onData(frame: DataFrame, result: Consumer<Result<Void>>) {
noIdle()
if (getRecvWindow() < 0) {
// It's a bad client, it does not deserve to be treated gently by just resetting the stream.
asyncHttp2Connection.close(ErrorCode.FLOW_CONTROL_ERROR.code, "stream_window_exceeded", discard())
result.accept(Result.createFailedResult(IOException("stream_window_exceeded")))
return
}
// SPEC: remotely closed streams must be replied with a reset.
if (isRemotelyClosed()) {
reset(ResetFrame(id, ErrorCode.STREAM_CLOSED_ERROR.code), discard())
result.accept(Result.createFailedResult(IOException("stream_closed")))
return
}
if (isReset) { // Just drop the frame.
result.accept(Result.createFailedResult(IOException("stream_reset")))
return
}
if (dataLength != Long.MIN_VALUE) {
dataLength -= frame.remaining()
if (frame.isEndStream && dataLength != 0L) {
reset(ResetFrame(id, ErrorCode.PROTOCOL_ERROR.code), discard())
result.accept(Result.createFailedResult(IOException("invalid_data_length")))
return
}
}
if (updateClose(frame.isEndStream, RECEIVED)) {
asyncHttp2Connection.removeStream(this)
}
notifyData(this, frame, result)
}
fun isRemotelyClosed(): Boolean {
val state = closeState.get()
return state === REMOTELY_CLOSED || state === CLOSING
}
private fun notifyData(stream: Stream, frame: DataFrame, result: Consumer<Result<Void>>) {
try {
listener.onData(stream, frame, result)
} catch (e: Throwable) {
log.error(e) { "Failure while notifying listener $listener" }
result.accept(Result.createFailedResult(e))
}
}
// window update
fun updateSendWindow(delta: Int): Int = sendWindow.getAndAdd(delta)
fun getSendWindow(): Int = sendWindow.get()
fun updateRecvWindow(delta: Int): Int = recvWindow.getAndAdd(delta)
fun getRecvWindow(): Int = recvWindow.get()
fun addAndGetLevel(delta: Int): Int = level.addAndGet(delta)
fun setLevel(level: Int) {
this.level.set(level)
}
// reset frame
override fun reset(frame: ResetFrame, result: Consumer<Result<Void>>) {
if (isReset) {
result.accept(Result.createFailedResult(IllegalStateException("The stream: $id is reset")))
return
}
localReset = true
sendControlFrame(frame, result)
}
override fun isReset(): Boolean {
return localReset || remoteReset
}
private fun onReset(frame: ResetFrame, result: Consumer<Result<Void>>) {
remoteReset = true
close()
asyncHttp2Connection.removeStream(this)
notifyReset(this, frame, result)
}
private fun notifyReset(stream: Stream, frame: ResetFrame, result: Consumer<Result<Void>>) {
try {
listener.onReset(stream, frame, result)
} catch (e: Exception) {
log.error(e) { "failure while notifying listener" }
}
}
private fun notifyFailure(stream: Stream, frame: FailureFrame, result: Consumer<Result<Void>>) {
try {
listener.onFailure(stream, frame.error, frame.reason, result)
} catch (e: Exception) {
log.error(e) { "failure while notifying listener" }
result.accept(Result.createFailedResult(e))
}
}
private fun sendControlFrame(frame: Frame, result: Consumer<Result<Void>>) {
asyncHttp2Connection.sendControlFrame(this, frame)
.thenAccept { result.accept(Result.SUCCESS) }
.exceptionallyAccept { result.accept(Result.createFailedResult(it)) }
}
// close frame
override fun close() {
val oldState = closeState.getAndSet(CLOSED)
if (oldState != CLOSED) {
idleCheckJob?.cancel(CancellationException("The stream closed. id: $id"))
val deltaClosing = if (oldState == CLOSING) -1 else 0
asyncHttp2Connection.updateStreamCount(local, -1, deltaClosing)
notifyClosed(this)
}
}
fun updateClose(update: Boolean, event: Event): Boolean {
log.debug { "Update close for $this update=$update event=$event" }
if (!update) {
return false
}
return when (event) {
RECEIVED -> updateCloseAfterReceived()
BEFORE_SEND -> updateCloseBeforeSend()
AFTER_SEND -> updateCloseAfterSend()
}
}
override fun isClosed(): Boolean {
return closeState.get() == CLOSED
}
private fun updateCloseAfterReceived(): Boolean {
while (true) {
when (val current = closeState.get()) {
NOT_CLOSED -> if (closeState.compareAndSet(current, REMOTELY_CLOSED)) {
return false
}
LOCALLY_CLOSING -> {
if (closeState.compareAndSet(current, CLOSING)) {
asyncHttp2Connection.updateStreamCount(local, 0, 1)
return false
}
}
LOCALLY_CLOSED -> {
close()
return true
}
else -> return false
}
}
}
private fun updateCloseBeforeSend(): Boolean {
while (true) {
when (val current = closeState.get()) {
NOT_CLOSED -> if (closeState.compareAndSet(current, LOCALLY_CLOSING)) {
return false
}
REMOTELY_CLOSED -> if (closeState.compareAndSet(current, CLOSING)) {
asyncHttp2Connection.updateStreamCount(local, 0, 1)
return false
}
else -> return false
}
}
}
private fun updateCloseAfterSend(): Boolean {
while (true) {
when (val current = closeState.get()) {
NOT_CLOSED, LOCALLY_CLOSING -> if (closeState.compareAndSet(current, LOCALLY_CLOSED)) {
return false
}
REMOTELY_CLOSED, CLOSING -> {
close()
return true
}
else -> return false
}
}
}
private fun notifyClosed(stream: Stream) {
try {
listener.onClosed(stream)
} catch (x: Throwable) {
log.info("Failure while notifying listener $listener", x)
}
}
fun notifyTerminal(stream: Stream) {
try {
listener.onTerminal(stream)
} catch (x: Throwable) {
log.info("Failure while notifying listener $listener", x)
}
}
override fun toString(): String {
return String.format(
"%s@%x#%d{sendWindow=%s,recvWindow=%s,local=%b,reset=%b/%b,%s,age=%d}",
"AsyncHttp2Stream",
hashCode(),
getId(),
sendWindow,
recvWindow,
local,
localReset,
remoteReset,
closeState,
(System.currentTimeMillis() - createTime)
)
}
} | apache-2.0 | 87391c2185f98f355d0c3f48eedc8a97 | 33.233577 | 111 | 0.60516 | 4.761083 | false | false | false | false |
cbeust/kobalt | modules/kobalt-plugin-api/src/main/kotlin/com/beust/kobalt/misc/NewRunCommand.kt | 1 | 5105 | package com.beust.kobalt.misc
import java.io.BufferedReader
import java.io.File
import java.io.InputStream
import java.io.InputStreamReader
import java.util.concurrent.TimeUnit
class RunCommandInfo {
lateinit var command: String
var args : List<String> = arrayListOf()
var directory : File = File("")
var env : Map<String, String> = hashMapOf()
/**
* Some commands fail but return 0, so the only way to find out if they failed is to look
* at the error stream. However, some commands succeed but output text on the error stream.
* This field is used to specify how errors are caught.
*/
var useErrorStreamAsErrorIndicator : Boolean = true
var useInputStreamAsErrorIndicator : Boolean = false
var ignoreExitValue : Boolean = false
var errorCallback: Function1<List<String>, Unit> = NewRunCommand.DEFAULT_ERROR
var successCallback: Function1<List<String>, Unit> = NewRunCommand.DEFAULT_SUCCESS
var isSuccess: (Boolean, List<String>, List<String>) -> Boolean = {
isSuccess: Boolean,
input: List<String>,
error: List<String> ->
var hasErrors = ! isSuccess
if (useErrorStreamAsErrorIndicator && ! hasErrors) {
hasErrors = hasErrors || error.size > 0
}
if (useInputStreamAsErrorIndicator && ! hasErrors) {
hasErrors = hasErrors || input.size > 0
}
! hasErrors
}
var containsErrors: ((List<String>) -> Boolean)? = null
}
fun runCommand(init: RunCommandInfo.() -> Unit) = NewRunCommand(RunCommandInfo().apply { init() }).invoke()
open class NewRunCommand(val info: RunCommandInfo) {
companion object {
val DEFAULT_SUCCESS = { output: List<String> -> }
// val DEFAULT_SUCCESS_VERBOSE = { output: List<String> -> kobaltLog(2, "Success:\n " + output.joinToString
// ("\n"))}
// val defaultSuccess = DEFAULT_SUCCESS
val DEFAULT_ERROR = { output: List<String> ->
kobaltError(output.joinToString("\n "))
}
}
// fun useErrorStreamAsErrorIndicator(f: Boolean) : RunCommand {
// useErrorStreamAsErrorIndicator = f
// return this
// }
fun invoke() : Int {
val allArgs = arrayListOf<String>()
allArgs.add(info.command)
allArgs.addAll(info.args)
val pb = ProcessBuilder(allArgs)
pb.directory(info.directory)
kobaltLog(2, "Running command in directory ${info.directory.absolutePath}" +
"\n " + allArgs.joinToString(" ").replace("\\", "/"))
pb.environment().let { pbEnv ->
info.env.forEach {
pbEnv.put(it.key, it.value)
}
}
val process = pb.start()
// Run the command and collect the return code and streams
val processFinished = process.waitFor(240, TimeUnit.SECONDS)
if (!processFinished)
kobaltError("process timed out!")
val processExitedOk = process.exitValue() == 0
if (!processExitedOk)
kobaltError("process returned non-zero code!")
val input =
if (process.inputStream.available() > 0) fromStream(process.inputStream)
else listOf()
val error =
if (process.errorStream.available() > 0) fromStream(process.errorStream)
else listOf()
kobaltLog(3, "info contains errors: " + (info.containsErrors != null))
// Check to see if the command succeeded
val isSuccess =
if (info.containsErrors != null) ! info.containsErrors!!(error)
else isSuccess(processFinished && if (info.ignoreExitValue) true else processExitedOk, input, error)
if (isSuccess) {
if (!info.useErrorStreamAsErrorIndicator) {
info.successCallback(error + input)
} else {
info.successCallback(input)
}
} else {
info.errorCallback(error + input)
}
return if (isSuccess) 0 else 1
}
/**
* Subclasses can override this method to do their own error handling, since commands can
* have various ways to signal errors.
*/
open protected fun isSuccess(isSuccess: Boolean, input: List<String>, error: List<String>) : Boolean {
var hasErrors: Boolean = ! isSuccess
if (info.useErrorStreamAsErrorIndicator && ! hasErrors) {
hasErrors = hasErrors || error.isNotEmpty()
}
if (info.useInputStreamAsErrorIndicator && ! hasErrors) {
hasErrors = hasErrors || input.isNotEmpty()
}
return ! hasErrors
}
/**
* Turn the given InputStream into a list of strings.
*/
private fun fromStream(ins: InputStream) : List<String> {
val result = arrayListOf<String>()
val br = BufferedReader(InputStreamReader(ins))
var line = br.readLine()
while (line != null) {
result.add(line)
line = br.readLine()
}
return result
}
}
| apache-2.0 | ec139f463759149d3a7120db460b9250 | 33.727891 | 118 | 0.602742 | 4.679193 | false | false | false | false |
DemonWav/IntelliJBukkitSupport | src/main/kotlin/platform/mixin/inspection/injector/ParameterGroup.kt | 1 | 1472 | /*
* Minecraft Dev for IntelliJ
*
* https://minecraftdev.org
*
* Copyright (c) 2021 minecraft-dev
*
* MIT License
*/
package com.demonwav.mcdev.platform.mixin.inspection.injector
import com.demonwav.mcdev.util.Parameter
import com.demonwav.mcdev.util.isErasureEquivalentTo
import com.intellij.psi.PsiArrayType
import com.intellij.psi.PsiEllipsisType
import com.intellij.psi.PsiParameter
data class ParameterGroup(
val parameters: List<Parameter>?,
val required: Boolean = parameters != null,
val default: Boolean = required
) {
val size
get() = this.parameters?.size ?: 0
fun match(parameters: Array<PsiParameter>, currentPosition: Int): Boolean {
if (this.parameters == null) {
// Wildcard parameter groups always match
return true
}
// Check if remaining parameter count is enough
if (currentPosition + size > parameters.size) {
return false
}
var pos = currentPosition
// Check parameter types
for ((_, expectedType) in this.parameters) {
val type = parameters[pos++].type
if (!type.isErasureEquivalentTo(expectedType)) {
// Allow using array instead of varargs
if (expectedType !is PsiEllipsisType || type !is PsiArrayType || type != expectedType.toArrayType()) {
return false
}
}
}
return true
}
}
| mit | 9ad5a2da9119e9c7ef44969afce7064b | 26.259259 | 118 | 0.624321 | 4.810458 | false | false | false | false |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.